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 reconnect;
96#[cfg(test)]
97use reconnect::is_reconnect_transient;
98mod slots;
99use slots::*;
100mod reservation;
101pub use reservation::{CorrelationId, PendingReply, RequestBody, RequestReservation};
102mod catalog;
103mod config_ops;
104mod supervisor_ops;
105use catalog::decode_route_open_response;
106pub use catalog::CatalogSubscription;
107pub use config_ops::{
108    ConfigApplyResponse, ConfigEdit, ConfigEditAction, ConfigFileError, ConfigFileErrorLayer,
109    ConfigModule, ConfigModulesResponse, ConfigPlanRefusal, ConfigPlanView, ConfigSchemaResponse,
110    ConfigSettingsLayer, ConfigShowResponse, ConfigStatus, ConfigSubscription, ConfigThrough,
111    ConfigWatchEvent, Digest,
112};
113
114#[cfg(test)]
115mod reader_skew_tests;
116
117#[cfg(test)]
118mod connection_ops_tests;
119pub use cancellation::{CancelHandle, CancelOutcome};
120use cancellation::{CancelRegistration, UnaryCancel};
121pub use supervisor_ops::{
122    HealthProbeResponse, ServerDescription, StderrTailResponse, SupervisorAck,
123    SupervisorHealthResponse, SupervisorProvenanceResponse,
124};
125
126/// `supervisor.spawn_subscribe` refused a cursor from another daemon incarnation.
127pub const SPAWN_CURSOR_INCARNATION_MISMATCH: &str = "spawn_cursor_incarnation_mismatch";
128/// `supervisor.spawn_subscribe` refused a cursor older than the daemon's retained ring.
129pub const SPAWN_CURSOR_TOO_OLD: &str = "spawn_cursor_too_old";
130/// The daemon dropped a spawn subscriber that fell too far behind.
131pub const SPAWN_SUBSCRIBER_LAGGED: &str = "spawn_subscriber_lagged";
132
133type ReverseRequestFuture =
134    Pin<Box<dyn Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static>>;
135type ReverseRequestHandler =
136    Arc<dyn Fn(Vec<u8>, ReverseRequestContext) -> ReverseRequestFuture + Send + Sync + 'static>;
137
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct ReverseRequestContext {
140    pub corr: u64,
141    pub method: String,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct ReverseRequestError {
146    message: String,
147}
148
149impl ReverseRequestError {
150    pub fn new(message: impl Into<String>) -> Self {
151        Self {
152            message: message.into(),
153        }
154    }
155}
156
157impl fmt::Display for ReverseRequestError {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str(&self.message)
160    }
161}
162
163impl Error for ReverseRequestError {}
164
165#[derive(Default)]
166struct ReverseRequestRegistryState {
167    handlers: HashMap<String, ReverseRequestHandler>,
168    declared_families: Option<BTreeSet<String>>,
169    consumer_capabilities: BTreeSet<String>,
170}
171
172/// Handler registry prepared before route.open. It carries the reverse-request
173/// method families and any extra capability strings added through route options'
174/// `with_consumer_capability` builder.
175#[derive(Clone, Default)]
176pub struct ReverseRequestRegistry {
177    inner: Arc<Mutex<ReverseRequestRegistryState>>,
178}
179
180impl fmt::Debug for ReverseRequestRegistry {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.debug_struct("ReverseRequestRegistry")
183            .field("capabilities", &self.capabilities())
184            .field("consumer_capabilities", &self.consumer_capabilities())
185            .finish()
186    }
187}
188
189impl PartialEq for ReverseRequestRegistry {
190    fn eq(&self, other: &Self) -> bool {
191        self.capabilities() == other.capabilities()
192            && self.consumer_capabilities() == other.consumer_capabilities()
193    }
194}
195
196impl Eq for ReverseRequestRegistry {}
197
198impl ReverseRequestRegistry {
199    pub fn new() -> Self {
200        Self::default()
201    }
202
203    pub fn on_request<F, Fut>(
204        &self,
205        method_family: impl Into<String>,
206        handler: F,
207    ) -> Result<(), ReverseRequestRegistrationError>
208    where
209        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
210        Fut: Future<Output = Vec<u8>> + Send + 'static,
211    {
212        self.on_request_fallible(method_family, move |body, ctx| {
213            let future = handler(body, ctx);
214            async move { Ok(future.await) }
215        })
216    }
217
218    pub fn on_request_fallible<F, Fut>(
219        &self,
220        method_family: impl Into<String>,
221        handler: F,
222    ) -> Result<(), ReverseRequestRegistrationError>
223    where
224        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
225        Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
226    {
227        let method_family = method_family.into();
228        if !is_valid_method_family(&method_family) {
229            return Err(ReverseRequestRegistrationError::InvalidFamily(
230                method_family,
231            ));
232        }
233        let mut state = self
234            .inner
235            .lock()
236            .unwrap_or_else(|poisoned| poisoned.into_inner());
237        if state
238            .declared_families
239            .as_ref()
240            .is_some_and(|families| !families.contains(&method_family))
241        {
242            return Err(ReverseRequestRegistrationError::NotDeclared(method_family));
243        }
244        state.handlers.insert(
245            method_family,
246            Arc::new(move |body, ctx| Box::pin(handler(body, ctx))),
247        );
248        Ok(())
249    }
250
251    fn capabilities(&self) -> Vec<String> {
252        let state = self
253            .inner
254            .lock()
255            .unwrap_or_else(|poisoned| poisoned.into_inner());
256        let mut capabilities = state.handlers.keys().cloned().collect::<Vec<_>>();
257        capabilities.sort();
258        capabilities
259    }
260
261    fn declare_consumer_capability(
262        &self,
263        capability: String,
264    ) -> Result<(), ConsumerCapabilityError> {
265        if capability.is_empty()
266            || capability.len() > 64
267            || !capability.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
268        {
269            return Err(ConsumerCapabilityError { capability });
270        }
271
272        self.inner
273            .lock()
274            .unwrap_or_else(|poisoned| poisoned.into_inner())
275            .consumer_capabilities
276            .insert(capability);
277        Ok(())
278    }
279
280    fn consumer_capabilities(&self) -> Vec<String> {
281        self.inner
282            .lock()
283            .unwrap_or_else(|poisoned| poisoned.into_inner())
284            .consumer_capabilities
285            .iter()
286            .cloned()
287            .collect()
288    }
289
290    fn handler(&self, method_family: &str) -> Option<ReverseRequestHandler> {
291        self.inner
292            .lock()
293            .unwrap_or_else(|poisoned| poisoned.into_inner())
294            .handlers
295            .get(method_family)
296            .cloned()
297    }
298
299    pub(crate) fn seal(&self) {
300        let mut state = self
301            .inner
302            .lock()
303            .unwrap_or_else(|poisoned| poisoned.into_inner());
304        if state.declared_families.is_none() {
305            state.declared_families = Some(state.handlers.keys().cloned().collect());
306        }
307    }
308}
309
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub enum ReverseRequestRegistrationError {
312    InvalidFamily(String),
313    NotDeclared(String),
314    NotConsumerRoute,
315}
316
317impl fmt::Display for ReverseRequestRegistrationError {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        match self {
320            Self::InvalidFamily(family) => {
321                write!(f, "invalid reverse-request method family {family:?}")
322            }
323            Self::NotDeclared(family) => write!(
324                f,
325                "reverse-request capability {family:?} was not registered before route.open"
326            ),
327            Self::NotConsumerRoute => {
328                f.write_str("route handle does not belong to a consumer route")
329            }
330        }
331    }
332}
333
334impl Error for ReverseRequestRegistrationError {}
335
336fn is_valid_method_family(value: &str) -> bool {
337    let mut segments = value.split(['.', '_', '-']);
338    segments.next().is_some_and(|segment| {
339        segment
340            .as_bytes()
341            .first()
342            .is_some_and(u8::is_ascii_lowercase)
343            && segment
344                .bytes()
345                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
346    }) && segments.all(|segment| {
347        !segment.is_empty()
348            && segment
349                .bytes()
350                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
351    })
352}
353
354/// Reverse-request handlers live in a process-global map keyed by an id the
355/// `RouteHandle` carries, rather than inside the handle itself.
356///
357/// WHY, so nobody "simplifies" this into the handle later: `RouteHandle` is
358/// `Copy`, deliberately and publicly. Every route-scoped call in this SDK takes
359/// it by value, and the fleet's Rust consumers pass it around freely on that
360/// assumption. An `Arc<ReverseRequestRegistry>` field would make it non-`Copy`
361/// and break every one of those call sites across twelve repositories, for a
362/// lane most of them do not use.
363///
364/// The cost is real and bounded: entries are removed on every teardown path
365/// (`remove_route`, `remove_route_by_handle`, `drain_routes`,
366/// `uninstall_route_handle`, `install_ingress_handle`), so a consumer that opens
367/// and closes routes for its lifetime does not grow. A consumer DROPPED without
368/// closing leaks its remaining entries until process exit, which is the one gap
369/// and is acceptable because nothing else about a dropped consumer is reclaimed
370/// either.
371///
372/// If `RouteHandle` ever stops being `Copy` for another reason, move this into
373/// the handle and delete the map — the indirection exists only to preserve that
374/// property.
375static NEXT_REVERSE_REQUEST_REGISTRY_ID: AtomicU64 = AtomicU64::new(1);
376static REVERSE_REQUEST_REGISTRIES: OnceLock<Mutex<HashMap<u64, ReverseRequestRegistry>>> =
377    OnceLock::new();
378
379fn reverse_request_registries() -> &'static Mutex<HashMap<u64, ReverseRequestRegistry>> {
380    REVERSE_REQUEST_REGISTRIES.get_or_init(|| Mutex::new(HashMap::new()))
381}
382
383pub(crate) fn install_reverse_request_registry(registry: ReverseRequestRegistry) -> u64 {
384    let id = crate::checked_increment(&NEXT_REVERSE_REQUEST_REGISTRY_ID)
385        .expect("reverse-request route registry id exhausted");
386    reverse_request_registries()
387        .lock()
388        .unwrap_or_else(|poisoned| poisoned.into_inner())
389        .insert(id, registry);
390    id
391}
392
393pub(crate) fn route_reverse_request_registry(
394    id: u64,
395) -> Result<ReverseRequestRegistry, ReverseRequestRegistrationError> {
396    if id == 0 {
397        return Err(ReverseRequestRegistrationError::NotConsumerRoute);
398    }
399    reverse_request_registries()
400        .lock()
401        .unwrap_or_else(|poisoned| poisoned.into_inner())
402        .get(&id)
403        .cloned()
404        .ok_or(ReverseRequestRegistrationError::NotConsumerRoute)
405}
406
407fn release_reverse_request_registry(handle: RouteHandle) {
408    let id = handle.reverse_request_registry_id();
409    if id != 0 {
410        reverse_request_registries()
411            .lock()
412            .unwrap_or_else(|poisoned| poisoned.into_inner())
413            .remove(&id);
414    }
415}
416
417/// Capped exponential backoff used for reconnects and transient route-open retry.
418/// Each delay is jittered before it is slept: half of it is kept and the other
419/// half is random.
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421pub struct RetryBackoff {
422    pub base: Duration,
423    pub cap: Duration,
424    /// Maximum attempts, including the first immediate attempt.
425    pub max_attempts: usize,
426}
427
428impl Default for RetryBackoff {
429    fn default() -> Self {
430        Self {
431            base: Duration::from_millis(100),
432            cap: Duration::from_secs(2),
433            max_attempts: 6,
434        }
435    }
436}
437
438impl RetryBackoff {
439    fn delay_after_attempt(self, attempt: usize) -> Duration {
440        let mut delay = self.base;
441        for _ in 1..attempt {
442            delay = (delay * 2).min(self.cap);
443        }
444        delay
445    }
446}
447
448/// Transport used for the initial connection and every reconnect attempt.
449#[derive(Debug, Clone, Copy, PartialEq, Eq)]
450enum ConsumerTransport {
451    /// Use the connection file's TCP endpoint (the default).
452    Tcp,
453    /// Use only `local_endpoint`, re-read on every connection attempt.
454    Local,
455}
456
457/// Options for [`SubcConsumer::connect`].
458#[derive(Debug, Clone, PartialEq, Eq)]
459pub struct ConsumerOptions {
460    pub handshake_timeout: Duration,
461    /// Deadline for channel-0 calls that do not take per-call options.
462    pub call_timeout: Duration,
463    pub reconnect_backoff: RetryBackoff,
464    pub restored_debounce: Duration,
465    /// Window a post-deadline Ping waits for any inbound frame before the connection is
466    /// treated as half-open. Exposed so callers can use a shorter deterministic test window.
467    pub liveness_probe_window: Duration,
468}
469
470impl Default for ConsumerOptions {
471    fn default() -> Self {
472        Self {
473            handshake_timeout: DEFAULT_HANDSHAKE_TIMEOUT,
474            call_timeout: DEFAULT_CALL_TIMEOUT,
475            reconnect_backoff: RetryBackoff::default(),
476            restored_debounce: DEFAULT_RESTORED_DEBOUNCE,
477            liveness_probe_window: DEFAULT_LIVENESS_PROBE_WINDOW,
478        }
479    }
480}
481
482/// A consumer-capability declaration was empty, contained whitespace or
483/// non-printable/non-ASCII bytes, or exceeded 64 bytes.
484#[derive(Debug, Clone, PartialEq, Eq)]
485pub struct ConsumerCapabilityError {
486    capability: String,
487}
488
489impl ConsumerCapabilityError {
490    /// The invalid declaration value.
491    pub fn capability(&self) -> &str {
492        &self.capability
493    }
494}
495
496impl fmt::Display for ConsumerCapabilityError {
497    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498        write!(
499            f,
500            "invalid consumer capability {:?}: expected 1-64 printable ASCII bytes without whitespace",
501            self.capability
502        )
503    }
504}
505
506impl Error for ConsumerCapabilityError {}
507
508/// Options for [`SubcConsumer::close_route`].
509#[derive(Debug, Clone)]
510pub struct CloseRouteOptions {
511    /// Scope used to open the cached route. Defaults to `None`, which selects
512    /// only the unscoped entry; other scopes and epochs are never closed here.
513    /// [`SubcConsumer::close_handle`] rejects this option because the handle
514    /// already selects exactly one route.
515    pub scope: Option<ScopeSelector>,
516    /// Await in-flight unary requests on the route to settle naturally before tearing
517    /// it down. Defaults to false: close immediately, settling anything in flight as
518    /// at-most-once failures (outcome_unknown if already sent, not_sent otherwise).
519    pub drain: bool,
520    /// Upper bound on the drain wait (ignored when `drain` is false).
521    pub drain_timeout: Duration,
522    /// Override for the consumer identity used to locate the route being closed;
523    /// when absent, the supervised launch identity identifies the route, except
524    /// on connections created by [`SubcConsumer::connect_operator_app`].
525    /// On claim-bound connections, a legacy nonce identity conflicts with the
526    /// binding; `close_route` refuses it by doing nothing.
527    pub consumer_identity: Option<ConsumerIdentity>,
528    /// Reverse-request handlers plus extra capability strings added through
529    /// [`Self::with_consumer_capability`]. Together, they identify the route being closed.
530    pub reverse_requests: ReverseRequestRegistry,
531    /// The role versions the route being closed was opened with (see
532    /// [`CallOptions::role_versions`]); part of the route's identity.
533    pub role_versions: Option<BTreeMap<String, String>>,
534}
535
536impl Default for CloseRouteOptions {
537    fn default() -> Self {
538        Self {
539            scope: None,
540            drain: false,
541            drain_timeout: DEFAULT_CALL_TIMEOUT,
542            consumer_identity: None,
543            reverse_requests: ReverseRequestRegistry::new(),
544            role_versions: None,
545        }
546    }
547}
548
549impl CloseRouteOptions {
550    /// Add a provider-contract capability declaration to the route identity.
551    ///
552    /// Values are merged with the reverse-request families. For example,
553    /// `tool-result/v1` declares the tool-provider content result format; the
554    /// declaration is not verified and grants no privilege.
555    ///
556    /// Like reverse-request handlers, declarations are kept in the options'
557    /// shared reverse-request state, so options cloned before this call share
558    /// the declaration. Add declarations before cloning options for other
559    /// routes.
560    pub fn with_consumer_capability(
561        self,
562        capability: impl Into<String>,
563    ) -> Result<Self, ConsumerCapabilityError> {
564        self.reverse_requests
565            .declare_consumer_capability(capability.into())?;
566        Ok(self)
567    }
568
569    /// The extra capability strings added with `with_consumer_capability`, not
570    /// the reverse-request handler families. For example, `tool-result/v1` declares
571    /// tool-provider content-result support; declarations are unverified and
572    /// grant nothing.
573    pub fn consumer_capabilities(&self) -> Vec<String> {
574        self.reverse_requests.consumer_capabilities()
575    }
576}
577
578/// Per-call options for [`SubcConsumer::call`].
579#[derive(Debug, Clone, PartialEq, Eq)]
580pub struct CallOptions {
581    /// Scope for a managed call's cached route, including reconnect reopens.
582    /// Each owner/ref/epoch has a separate cache entry, apart from unscoped routes.
583    /// Admission, retries and terminal refusals follow [`SubcConsumer::open_route_scoped`].
584    /// A later call after a scope-related close tries a fresh route; the daemon
585    /// refuses it as `scope_ended` for an old epoch or `scope_not_live` if the
586    /// scope ref is gone. No tombstone is cached.
587    /// Defaults to `None`. Methods using an already-open handle reject this option;
588    /// select the scope when opening the route instead.
589    pub scope: Option<ScopeSelector>,
590    /// Deadline for the whole managed call, including route-open retry and the response wait.
591    pub timeout: Duration,
592    pub priority: Priority,
593    /// Admission behavior stamped into the request frame. Defaults to NORMAL.
594    pub admission_class: AdmissionClass,
595    pub route_retry: RetryBackoff,
596    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
597    /// Bounds the whole route open, including the first attempt: a zero budget
598    /// means no open is attempted. For a single attempt, allow that attempt's time.
599    pub route_retry_deadline: Duration,
600    /// Explicit consumer identity for route.open; when absent, the supervised
601    /// launch identity is used, except on [`SubcConsumer::connect_operator_app`]
602    /// connections, which omit implicit identity.
603    /// A claim-bound connection rejects legacy nonce identity overrides as not
604    /// sent, rather than changing the connection's authority.
605    pub consumer_identity: Option<ConsumerIdentity>,
606    /// Reverse-request handlers plus extra capability strings added with
607    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
608    /// tool-provider content-result support. These declarations are unverified
609    /// and grant nothing; both sets are merged and omitted when empty.
610    pub reverse_requests: ReverseRequestRegistry,
611    /// The versions of provider roles this consumer speaks on the route, role
612    /// name to version (`{"tool-provider": "v1"}`), sent on `route.open` and
613    /// forwarded by the daemon to the provider's bind. An unverified
614    /// declaration that grants nothing. Routes that differ only here are
615    /// separate routes, so a legacy route and a versioned one to the same
616    /// target are never shared; an empty map is the same as `None`.
617    ///
618    /// A daemon that does not advertise `route-role-versions/v1`
619    /// ([`subc_protocol::scope::CAP_ROUTE_ROLE_VERSIONS_V1`]) drops the field
620    /// without telling the provider, so check the capability before relying
621    /// on it. A malformed map (see
622    /// [`subc_protocol::session::validate_role_versions`]) is refused by the
623    /// daemon as `invalid_request` and the call fails as not sent.
624    pub role_versions: Option<BTreeMap<String, String>>,
625}
626
627impl Default for CallOptions {
628    fn default() -> Self {
629        Self {
630            scope: None,
631            timeout: DEFAULT_CALL_TIMEOUT,
632            priority: Priority::Interactive,
633            admission_class: AdmissionClass::Normal,
634            route_retry: RetryBackoff::default(),
635            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
636            consumer_identity: None,
637            reverse_requests: ReverseRequestRegistry::new(),
638            role_versions: None,
639        }
640    }
641}
642
643impl CallOptions {
644    fn reject_scope(&self) -> Result<(), CallError> {
645        if self.scope.is_some() {
646            return Err(CallError::not_sent(
647                "CallOptions.scope is not supported here; select the scope with open_route_scoped or a managed call",
648            ));
649        }
650        Ok(())
651    }
652
653    /// Add a provider-contract capability declaration to the route.
654    ///
655    /// The list is merged with reverse-request handler families, sorted and
656    /// de-duplicated. For example, `tool-result/v1` declares the tool-provider
657    /// content result format. This remains an unverified declaration and grants
658    /// no privilege. Invalid values are rejected here, before route.open can be
659    /// sent.
660    ///
661    /// Like reverse-request handlers, declarations are kept in the options'
662    /// shared reverse-request state, so options cloned before this call share
663    /// the declaration. Add declarations before cloning options for other
664    /// routes.
665    pub fn with_consumer_capability(
666        self,
667        capability: impl Into<String>,
668    ) -> Result<Self, ConsumerCapabilityError> {
669        self.reverse_requests
670            .declare_consumer_capability(capability.into())?;
671        Ok(self)
672    }
673
674    /// The extra capability strings added with `with_consumer_capability`, not
675    /// the reverse-request handler families. For example, `tool-result/v1` declares
676    /// tool-provider content-result support; declarations are unverified and
677    /// grant nothing.
678    pub fn consumer_capabilities(&self) -> Vec<String> {
679        self.reverse_requests.consumer_capabilities()
680    }
681}
682
683/// Options for [`SubcConsumer::subscribe`].
684#[derive(Debug, Clone, PartialEq, Eq)]
685pub struct SubscribeOptions {
686    /// Scope for the cached route and its reopen attempts. Defaults to `None`.
687    /// Cache separation and daemon refusals follow [`CallOptions::scope`].
688    /// [`SubcConsumer::subscribe_route`] rejects this option because its handle
689    /// already fixes the scope. A scope-related close ends the subscription;
690    /// it is not automatically reopened under this or any other selector.
691    pub scope: Option<ScopeSelector>,
692    pub priority: Priority,
693    /// Admission behavior stamped into the subscription request. Defaults to NORMAL.
694    pub admission_class: AdmissionClass,
695    /// Maximum number of events buffered for the caller before the subscription is dropped.
696    /// The reader task never awaits a slow event consumer; if this bounded channel fills,
697    /// `closed()` resolves with [`CallError::SubscriptionBackpressure`].
698    pub event_buffer: usize,
699    pub route_retry: RetryBackoff,
700    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
701    pub route_retry_deadline: Duration,
702    /// Deadline for opening the managed route and queuing the held-open request.
703    /// The subscription itself has no response timeout once the request is sent.
704    pub route_open_timeout: Duration,
705    /// Explicit consumer identity for route.open; when absent, the supervised
706    /// launch identity is used, except on [`SubcConsumer::connect_operator_app`]
707    /// connections, which omit implicit identity.
708    /// Claim-bound connections reject legacy nonce identity overrides as not sent.
709    pub consumer_identity: Option<ConsumerIdentity>,
710    /// Reverse-request handlers plus extra capability strings added with
711    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
712    /// tool-provider content-result support. These declarations are unverified
713    /// and grant nothing; both sets are merged and omitted when empty.
714    pub reverse_requests: ReverseRequestRegistry,
715    /// The role versions declared on the subscription's route; see
716    /// [`CallOptions::role_versions`].
717    pub role_versions: Option<BTreeMap<String, String>>,
718}
719
720impl Default for SubscribeOptions {
721    fn default() -> Self {
722        Self {
723            scope: None,
724            priority: Priority::Interactive,
725            admission_class: AdmissionClass::Normal,
726            event_buffer: DEFAULT_SUBSCRIPTION_EVENT_BUFFER,
727            route_retry: RetryBackoff::default(),
728            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
729            route_open_timeout: DEFAULT_CALL_TIMEOUT,
730            consumer_identity: None,
731            reverse_requests: ReverseRequestRegistry::new(),
732            role_versions: None,
733        }
734    }
735}
736
737impl SubscribeOptions {
738    /// Add a provider-contract capability declaration to the subscription route.
739    ///
740    /// This merges with reverse-request families. For example, `tool-result/v1`
741    /// declares the tool-provider content result format. The declaration is
742    /// unverified and grants no privilege; invalid values are refused before
743    /// route.open is sent.
744    pub fn with_consumer_capability(
745        self,
746        capability: impl Into<String>,
747    ) -> Result<Self, ConsumerCapabilityError> {
748        self.reverse_requests
749            .declare_consumer_capability(capability.into())?;
750        Ok(self)
751    }
752
753    /// The extra capability strings added with `with_consumer_capability`, not
754    /// the reverse-request handler families. For example, `tool-result/v1` declares
755    /// tool-provider content-result support; declarations are unverified and
756    /// grant nothing.
757    pub fn consumer_capabilities(&self) -> Vec<String> {
758        self.reverse_requests.consumer_capabilities()
759    }
760}
761
762/// Minimal connection lifecycle signal. It is useful for logging and route-cache invalidation,
763/// but callers must not use the consumer epoch as proof that a target provider is current.
764#[derive(Debug, Clone, PartialEq, Eq)]
765pub enum ConnectionState {
766    Dropped,
767    Restored { epoch: u64 },
768}
769
770/// Result of a route-scoped status or liveness poll.
771#[derive(Debug, Clone, PartialEq, Eq)]
772pub struct RoutePollResult {
773    pub handle: RouteHandle,
774    pub status: Option<String>,
775    pub live: Option<bool>,
776}
777
778/// Typed response from the daemon's channel-0 `catalog.list` operation.
779///
780/// Each module entry exposes the provider roles and tool definitions advertised by
781/// that module.
782#[derive(Debug, Clone, serde::Deserialize, PartialEq)]
783pub struct CatalogList {
784    pub generation: u64,
785    #[serde(default)]
786    pub modules: Vec<CatalogEntry>,
787    #[serde(default)]
788    pub subc_ops: Vec<String>,
789}
790
791/// Typed response from the daemon's channel-0 `supervisor.list` operation.
792///
793/// Unlike `catalog.list`, this includes configured modules that are stopped or
794/// disabled, along with their current supervisor state.
795#[derive(Debug, Clone, PartialEq)]
796pub struct SupervisorListResponse {
797    pub generation: u64,
798    pub modules: Vec<SupervisorEntry>,
799    pub daemon: Option<subc_control::DaemonResources>,
800    pub agent_commands: Option<Vec<subc_control::AgentCommandResources>>,
801}
802
803/// A provider-originated push delivered on one live route.
804#[derive(Debug, Clone, PartialEq, Eq)]
805pub struct PushEvent {
806    /// The connection-fenced route identity on which the push arrived.
807    pub handle: RouteHandle,
808    /// Opaque payload bytes sent by the provider.
809    pub body: Vec<u8>,
810}
811
812/// Disposition of one provider push at delivery time, so the two drop causes
813/// land on their own counters (issue #40): the remedies differ.
814enum DroppedPush {
815    Delivered,
816    NoReceiver,
817    ReceiverFull,
818}
819
820/// A parsed daemon-originated channel-0 control push.
821#[derive(Debug, Clone)]
822pub struct ControlPush {
823    /// The push discriminator, e.g. `route.closing` / `route.closed`.
824    pub op: String,
825    /// The full parsed body, `op` included, for op-specific fields.
826    pub body: serde_json::Value,
827}
828
829/// A route-close reason accepted from the daemon control-push wire.
830///
831/// The protocol may add reasons before this SDK is upgraded. Preserve that fact
832/// as [`Self::Unknown`] and classify it conservatively rather than refusing to
833/// deliver the enclosing control push.
834#[derive(Debug, Clone, PartialEq, Eq)]
835#[non_exhaustive]
836pub enum RouteCloseReason {
837    Reload,
838    Restart,
839    AuthorityChanged,
840    Disable,
841    Crash,
842    CapabilityDenied,
843    ScopeEnded,
844    ScopeCarrierRemoved,
845    ScopeDelegationChanged,
846    ScopeParentEnded,
847    Unknown(String),
848}
849
850/// Close reasons understood by this SDK, declared only after the daemon
851/// advertises `route-close-reasons/v1` so older daemons see unchanged requests.
852pub const ACCEPTED_CLOSE_REASONS: &[&str] = &[
853    "reload",
854    "restart",
855    "authority_changed",
856    "disable",
857    "crash",
858    "capability_denied",
859    "scope_ended",
860    "scope_carrier_removed",
861    "scope_delegation_changed",
862    "scope_parent_ended",
863];
864
865/// Why a route ended. Even a planned closure can leave a call's outcome unknown.
866#[derive(Debug, Clone, PartialEq, Eq)]
867#[non_exhaustive]
868pub enum RouteEndReason {
869    Daemon(RouteCloseReason),
870    ClosedByCaller,
871    ConnectionLost,
872    Unknown,
873}
874
875#[derive(Debug, Clone)]
876struct RouteEnd {
877    reason: RouteEndReason,
878    terminal: Option<bool>,
879}
880
881impl From<RouteEndReason> for RouteEnd {
882    fn from(reason: RouteEndReason) -> Self {
883        Self {
884            reason,
885            terminal: None,
886        }
887    }
888}
889
890/// Whether a closed route may be reopened automatically from its reason alone.
891#[derive(Debug, Clone, Copy, PartialEq, Eq)]
892pub enum RouteCloseDisposition {
893    MayReopen,
894    MustNotReopen,
895}
896
897impl RouteCloseReason {
898    /// Decode a wire reason without making a new daemon reason fatal to push delivery.
899    pub fn from_wire(reason: &str) -> Self {
900        match reason {
901            "reload" => Self::Reload,
902            "restart" => Self::Restart,
903            "authority_changed" => Self::AuthorityChanged,
904            "disable" => Self::Disable,
905            "crash" => Self::Crash,
906            "capability_denied" => Self::CapabilityDenied,
907            "scope_ended" => Self::ScopeEnded,
908            "scope_carrier_removed" => Self::ScopeCarrierRemoved,
909            "scope_delegation_changed" => Self::ScopeDelegationChanged,
910            "scope_parent_ended" => Self::ScopeParentEnded,
911            other => Self::Unknown(other.to_string()),
912        }
913    }
914
915    /// Unknown reasons take the strictest action: never reopen on their behalf.
916    pub fn disposition(&self) -> RouteCloseDisposition {
917        match self {
918            Self::Reload | Self::Restart | Self::AuthorityChanged => {
919                RouteCloseDisposition::MayReopen
920            }
921            Self::Disable
922            | Self::Crash
923            | Self::CapabilityDenied
924            | Self::ScopeEnded
925            | Self::ScopeCarrierRemoved
926            | Self::ScopeDelegationChanged
927            | Self::ScopeParentEnded
928            | Self::Unknown(_) => RouteCloseDisposition::MustNotReopen,
929        }
930    }
931}
932
933impl ControlPush {
934    /// Decode the close reason from a route lifecycle push, if this is one.
935    pub fn route_close_reason(&self) -> Option<RouteCloseReason> {
936        matches!(self.op.as_str(), "route.closing" | "route.closed")
937            .then(|| {
938                self.body
939                    .get("reason")?
940                    .as_str()
941                    .map(RouteCloseReason::from_wire)
942            })
943            .flatten()
944    }
945}
946
947/// Managed Rust consumer for subc route calls.
948pub struct SubcConsumer {
949    shared: Arc<Shared>,
950}
951
952/// The daemon's view of this connection at the time of the query.
953/// Recognition may change after revalidation or a reconnect.
954#[non_exhaustive]
955#[derive(Debug, Clone, PartialEq, Eq)]
956pub struct ConnectionFacts {
957    local: bool,
958    operator_app: Option<subc_protocol::peer::OperatorApp>,
959}
960
961impl ConnectionFacts {
962    /// Whether this connection arrived on the Unix socket or Windows named pipe.
963    pub fn local(&self) -> bool {
964        self.local
965    }
966
967    /// The operator app currently recognised for this connection. `route.bind`
968    /// sends it only to targets that advertise `operator-app/v1`.
969    pub fn operator_app(&self) -> Option<&subc_protocol::peer::OperatorApp> {
970        self.operator_app.as_ref()
971    }
972}
973
974/// Failure to ask the daemon to open an installed operator app.
975#[non_exhaustive]
976#[derive(Debug)]
977pub enum AppOpenError {
978    /// A daemon error frame. Codes are open strings so future refusals survive.
979    /// The current checks, in order, are `app_open_not_used`,
980    /// `app_open_disabled`, `app_unknown`, `app_not_installed`, and
981    /// `app_verification_failed` (see `subc_control::APP_OPEN_ERROR_CODES`).
982    /// An already-running app succeeds between the unknown and installed checks.
983    Refused { code: String, message: String },
984    /// A transport or protocol failure rather than a daemon refusal.
985    Call(CallError),
986}
987
988impl fmt::Display for AppOpenError {
989    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990        match self {
991            Self::Refused { code, message } => write!(f, "{code}: {message}"),
992            Self::Call(err) => err.fmt(f),
993        }
994    }
995}
996
997impl Error for AppOpenError {
998    fn source(&self) -> Option<&(dyn Error + 'static)> {
999        match self {
1000            Self::Call(err) => Some(err),
1001            Self::Refused { .. } => None,
1002        }
1003    }
1004}
1005
1006impl From<CallError> for AppOpenError {
1007    fn from(err: CallError) -> Self {
1008        Self::Call(err)
1009    }
1010}
1011
1012/// A managed unary reply with the module's raw-body declaration preserved.
1013#[non_exhaustive]
1014#[derive(Debug, Clone, PartialEq, Eq)]
1015pub struct CallReply {
1016    body: Vec<u8>,
1017    binary: bool,
1018}
1019
1020impl CallReply {
1021    /// The body bytes, unchanged from the terminal Response frame.
1022    /// A StreamEnd without a Response has an empty body.
1023    pub fn body(&self) -> &[u8] {
1024        &self.body
1025    }
1026
1027    /// Consume the reply and return its body bytes without copying them.
1028    pub fn into_body(self) -> Vec<u8> {
1029        self.body
1030    }
1031
1032    /// Whether the terminal Response carried `FLAG_BINARY` (raw bytes, not JSON).
1033    /// A StreamEnd without a Response returns `false`.
1034    pub fn is_binary(&self) -> bool {
1035        self.binary
1036    }
1037}
1038
1039/// The first terminal outcome of a subscription.
1040#[derive(Debug, Clone, PartialEq)]
1041#[non_exhaustive]
1042pub enum SubscriptionEnd {
1043    Response(Vec<u8>),
1044    StreamEnd,
1045    Error(ErrorBody),
1046    /// An Error frame reported that the established route is no longer usable.
1047    RouteDead(ErrorBody),
1048    RouteClosed {
1049        reason: RouteEndReason,
1050    },
1051    ConnectionLost,
1052    Cancelled,
1053    /// The bounded event channel filled before the caller drained it.
1054    Backpressure,
1055}
1056
1057impl SubscriptionEnd {
1058    /// Whether an Error frame reported that the established route is no longer usable.
1059    pub fn is_route_dead(&self) -> bool {
1060        matches!(self, Self::RouteDead(_))
1061    }
1062}
1063
1064/// A live subscription to a provider event stream.
1065///
1066/// The event receiver yields each `StreamData` payload for the held-open request's
1067/// correlation id. Await [`Subscription::closed`] to learn whether the provider ended
1068/// the stream cleanly (`Response` or `StreamEnd`) or the stream was rejected by an Error frame,
1069/// route GOODBYE, connection drop, or local backpressure. Dropping the subscription
1070/// sends a best-effort Cancel frame, the same as calling [`Subscription::unsubscribe`].
1071pub struct Subscription {
1072    events: mpsc::Receiver<Vec<u8>>,
1073    closed: SubscriptionClosed,
1074    ended: watch::Receiver<Option<SubscriptionEnd>>,
1075    cancel: SubscriptionCancel,
1076}
1077
1078impl Subscription {
1079    /// Receive event payloads emitted as `StreamData` frames for this subscription.
1080    pub fn events(&mut self) -> &mut mpsc::Receiver<Vec<u8>> {
1081        &mut self.events
1082    }
1083
1084    /// Future that resolves when the subscription reaches a terminal state.
1085    ///
1086    /// It resolves with `Ok(())` on `Response`, `StreamEnd` or local unsubscribe, and returns a
1087    /// [`CallError`] for module Error frames, route teardown, connection loss, or
1088    /// event-channel backpressure. Await it after the event receiver returns `None`
1089    /// to distinguish a clean end from an error.
1090    pub fn closed(&mut self) -> &mut SubscriptionClosed {
1091        &mut self.closed
1092    }
1093
1094    /// Wait for the terminal outcome, retaining a Response body or module Error.
1095    ///
1096    /// This is independent of the one-shot [`Self::closed`] future: either can be
1097    /// awaited first, and `ended` can be awaited again after completion. Neither
1098    /// method reads frames; both observe the same pending request's settlement.
1099    pub async fn ended(&mut self) -> SubscriptionEnd {
1100        loop {
1101            if let Some(end) = self.ended.borrow().clone() {
1102                return end;
1103            }
1104            if self.ended.changed().await.is_err() {
1105                return SubscriptionEnd::ConnectionLost;
1106            }
1107        }
1108    }
1109
1110    /// Cancel the held-open request.
1111    ///
1112    /// This sends a best-effort header-only Cancel frame for the subscription's
1113    /// `(channel, corr)` and settles [`Subscription::closed`] promptly with `Ok(())`.
1114    /// The provider may still send a terminal frame later; it is ignored because the
1115    /// local subscription is already closed.
1116    pub fn unsubscribe(&self) -> Result<(), CallError> {
1117        self.cancel.unsubscribe()
1118    }
1119}
1120
1121impl Drop for Subscription {
1122    fn drop(&mut self) {
1123        let _ = self.cancel.unsubscribe();
1124    }
1125}
1126
1127/// A held `supervisor.spawn_subscribe` request: the daemon's spawn events, in cursor
1128/// order, until the stream ends. Dropping it cancels the request.
1129pub struct SpawnSubscription {
1130    inner: Subscription,
1131    finished: bool,
1132}
1133
1134impl SpawnSubscription {
1135    /// The next event. `Ok(None)` is a clean end (the daemon ended the stream, or it was
1136    /// unsubscribed); every later call returns it too.
1137    ///
1138    /// Every event the daemon queued before a terminal error is yielded first, so the
1139    /// last event received is the cursor to resume from. A refused cursor or a dropped
1140    /// subscriber comes back as the matching [`SpawnStreamError`] variant; anything else
1141    /// that ends the stream (connection loss, local backpressure, an event that does not
1142    /// decode) is [`SpawnStreamError::Call`] or [`SpawnStreamError::Decode`].
1143    pub async fn next(&mut self) -> Result<Option<SpawnEvent>, SpawnStreamError> {
1144        if self.finished {
1145            return Ok(None);
1146        }
1147        if let Some(body) = self.inner.events().recv().await {
1148            return serde_json::from_slice::<SpawnEvent>(&body)
1149                .map(Some)
1150                .map_err(|err| {
1151                    self.finished = true;
1152                    let _ = self.inner.unsubscribe();
1153                    SpawnStreamError::Decode(err.to_string())
1154                });
1155        }
1156        // Marked finished only once the terminal has been read: a caller that drops this
1157        // future mid-await (a `select!` arm) still gets the terminal on its next call.
1158        let terminal = self.inner.closed().await;
1159        self.finished = true;
1160        match terminal {
1161            Ok(()) => Ok(None),
1162            Err(err) => Err(SpawnStreamError::from_call_error(err)),
1163        }
1164    }
1165
1166    /// Cancel the held request; the daemon releases the subscriber.
1167    pub fn unsubscribe(&self) -> Result<(), CallError> {
1168        self.inner.unsubscribe()
1169    }
1170}
1171
1172/// Why a spawn stream ended with an error, by the daemon's code where it sent one.
1173#[derive(Debug)]
1174pub enum SpawnStreamError {
1175    /// `spawn_cursor_incarnation_mismatch`: the cursor names another daemon incarnation,
1176    /// so every event since it is unknowable from this daemon.
1177    CursorIncarnationMismatch {
1178        current_daemon_incarnation: String,
1179        body: Box<ErrorBody>,
1180    },
1181    /// `spawn_cursor_too_old`: events after the cursor have left the daemon's ring.
1182    CursorTooOld {
1183        oldest_retained_cursor: SpawnCursor,
1184        body: Box<ErrorBody>,
1185    },
1186    /// `spawn_subscriber_lagged`: the daemon dropped this subscriber for falling behind,
1187    /// after delivering every event it had queued for it.
1188    SubscriberLagged {
1189        first_undelivered_cursor: SpawnCursor,
1190        body: Box<ErrorBody>,
1191    },
1192    /// Any other end: another daemon error (one of the codes above with a detail that
1193    /// does not parse included, so its code is still readable), connection loss, or
1194    /// local backpressure.
1195    Call(CallError),
1196    /// An event body that is not a `SpawnEvent`.
1197    Decode(String),
1198}
1199
1200impl SpawnStreamError {
1201    fn from_call_error(err: CallError) -> Self {
1202        let CallError::Module(body) = err else {
1203            return Self::Call(err);
1204        };
1205        let detail = |key: &str| body.detail.as_ref().and_then(|detail| detail.get(key));
1206        let cursor = |key: &str| {
1207            detail(key).and_then(|value| serde_json::from_value::<SpawnCursor>(value.clone()).ok())
1208        };
1209        match body.code.as_str() {
1210            SPAWN_CURSOR_INCARNATION_MISMATCH => {
1211                match detail("current_daemon_incarnation").and_then(|value| value.as_str()) {
1212                    Some(current) => Self::CursorIncarnationMismatch {
1213                        current_daemon_incarnation: current.to_string(),
1214                        body: Box::new(body),
1215                    },
1216                    None => Self::Call(CallError::Module(body)),
1217                }
1218            }
1219            SPAWN_CURSOR_TOO_OLD => match cursor("oldest_retained_cursor") {
1220                Some(oldest_retained_cursor) => Self::CursorTooOld {
1221                    oldest_retained_cursor,
1222                    body: Box::new(body),
1223                },
1224                None => Self::Call(CallError::Module(body)),
1225            },
1226            SPAWN_SUBSCRIBER_LAGGED => match cursor("first_undelivered_cursor") {
1227                Some(first_undelivered_cursor) => Self::SubscriberLagged {
1228                    first_undelivered_cursor,
1229                    body: Box::new(body),
1230                },
1231                None => Self::Call(CallError::Module(body)),
1232            },
1233            _ => Self::Call(CallError::Module(body)),
1234        }
1235    }
1236
1237    /// The daemon's error code, when the stream ended with one.
1238    pub fn code(&self) -> Option<&str> {
1239        match self {
1240            Self::CursorIncarnationMismatch { .. } => Some(SPAWN_CURSOR_INCARNATION_MISMATCH),
1241            Self::CursorTooOld { .. } => Some(SPAWN_CURSOR_TOO_OLD),
1242            Self::SubscriberLagged { .. } => Some(SPAWN_SUBSCRIBER_LAGGED),
1243            Self::Call(err) => err.code(),
1244            Self::Decode(_) => None,
1245        }
1246    }
1247}
1248
1249impl fmt::Display for SpawnStreamError {
1250    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251        match self {
1252            Self::CursorIncarnationMismatch {
1253                current_daemon_incarnation,
1254                ..
1255            } => write!(
1256                f,
1257                "{SPAWN_CURSOR_INCARNATION_MISMATCH}: the daemon is incarnation \
1258                 {current_daemon_incarnation}"
1259            ),
1260            Self::CursorTooOld {
1261                oldest_retained_cursor,
1262                ..
1263            } => write!(
1264                f,
1265                "{SPAWN_CURSOR_TOO_OLD}: the oldest retained event is seq {}",
1266                oldest_retained_cursor.seq
1267            ),
1268            Self::SubscriberLagged {
1269                first_undelivered_cursor,
1270                ..
1271            } => write!(
1272                f,
1273                "{SPAWN_SUBSCRIBER_LAGGED}: the first undelivered event is seq {}",
1274                first_undelivered_cursor.seq
1275            ),
1276            Self::Call(err) => write!(f, "spawn stream ended: {err}"),
1277            Self::Decode(message) => write!(f, "spawn event did not decode: {message}"),
1278        }
1279    }
1280}
1281
1282impl Error for SpawnStreamError {}
1283
1284/// Future returned by [`Subscription::closed`].
1285pub struct SubscriptionClosed {
1286    rx: oneshot::Receiver<Result<(), CallError>>,
1287}
1288
1289impl Unpin for SubscriptionClosed {}
1290
1291impl Future for SubscriptionClosed {
1292    type Output = Result<(), CallError>;
1293
1294    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1295        let this = self.get_mut();
1296        match Pin::new(&mut this.rx).poll(cx) {
1297            Poll::Ready(Ok(result)) => Poll::Ready(result),
1298            Poll::Ready(Err(_)) => Poll::Ready(Err(CallError::outcome_unknown(
1299                "subscription closed result channel dropped",
1300                OutcomeUnknownCause::CompletionFailed,
1301            ))),
1302            Poll::Pending => Poll::Pending,
1303        }
1304    }
1305}
1306
1307struct SubscriptionCancel {
1308    shared: Arc<Shared>,
1309    position: Arc<SubscriptionPosition>,
1310    priority: Priority,
1311    cancelled: AtomicBool,
1312}
1313
1314impl SubscriptionCancel {
1315    fn new(shared: Arc<Shared>, position: Arc<SubscriptionPosition>, priority: Priority) -> Self {
1316        Self {
1317            shared,
1318            position,
1319            priority,
1320            cancelled: AtomicBool::new(false),
1321        }
1322    }
1323
1324    fn unsubscribe(&self) -> Result<(), CallError> {
1325        let key = *self
1326            .position
1327            .key
1328            .lock()
1329            .unwrap_or_else(|err| err.into_inner());
1330        let handle = RouteHandle::new(key.channel, key.epoch, key.generation);
1331        self.shared.validate_current_handle(handle)?;
1332        if self.cancelled.swap(true, Ordering::AcqRel) {
1333            return Ok(());
1334        }
1335        self.shared
1336            .unsubscribe_subscription(&self.position, self.priority)
1337    }
1338}
1339
1340impl SubcConsumer {
1341    /// Connect through an explicit connection-file path. The initial connection
1342    /// generation uses epoch 1; each reconnect advances it.
1343    /// In a supervised process, the module's primary registration connection
1344    /// mints a fresh self claim for
1345    /// every connection, including reconnects. Mint/presentation failure is an
1346    /// error, never a direct connection: dropping the binding would change the
1347    /// caller's authority. Unsupervised processes retain the legacy behavior.
1348    pub async fn connect(
1349        connection_file: &Path,
1350        opts: ConsumerOptions,
1351    ) -> Result<Self, ConsumerError> {
1352        Self::connect_with_transport(connection_file, opts, ConsumerTransport::Tcp, true).await
1353    }
1354
1355    /// Connect only to the connection file's same-user Unix socket or Windows pipe.
1356    ///
1357    /// Each connection attempt, including reconnects, reads the current local
1358    /// endpoint and key from the same owner-checked file. A missing
1359    /// `local_endpoint` returns [`ConsumerError::NoEndpoint`]; a local connect
1360    /// failure retains its endpoint and I/O error. Neither case falls back to TCP.
1361    pub async fn connect_local(
1362        connection_file: &Path,
1363        opts: ConsumerOptions,
1364    ) -> Result<Self, ConsumerError> {
1365        Self::connect_with_transport(connection_file, opts, ConsumerTransport::Local, true).await
1366    }
1367
1368    async fn connect_with_transport(
1369        connection_file: &Path,
1370        opts: ConsumerOptions,
1371        transport: ConsumerTransport,
1372        identity_from_environment: bool,
1373    ) -> Result<Self, ConsumerError> {
1374        let opened =
1375            open_connection(connection_file, opts.handshake_timeout, transport, None).await?;
1376        let mut shared = Shared::with_transport(connection_file.to_path_buf(), opts, transport);
1377        shared.identity_from_environment = identity_from_environment;
1378        let shared = Arc::new(shared);
1379        shared.install_initial(opened)?;
1380        Ok(Self { shared })
1381    }
1382
1383    /// Discover the daemon's connection file, authenticate, and start the I/O loop.
1384    pub async fn connect_default(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1385        let discovered = connection_file::discover(None)
1386            .map_err(|source| ConsumerError::Discovery { source })?;
1387        let opened =
1388            open_connection_with_info(&discovered.path, &discovered.info, opts.handshake_timeout)
1389                .await?;
1390        let shared = Arc::new(Shared::new(discovered.path, opts));
1391        shared.install_initial(opened)?;
1392        Ok(Self { shared })
1393    }
1394
1395    /// Discover the daemon's connection file and connect only to its local endpoint.
1396    ///
1397    /// Uses [`Self::connect_local`], including its per-attempt file reads and
1398    /// refusal to fall back to TCP.
1399    pub async fn connect_default_local(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1400        let discovered = connection_file::discover(None)
1401            .map_err(|source| ConsumerError::Discovery { source })?;
1402        Self::connect_local(&discovered.path, opts).await
1403    }
1404
1405    /// Connect the desktop operator app to the installed daemon without reading
1406    /// environment variables for discovery or consumer identity.
1407    ///
1408    /// Tries [`crate::operator_app_candidates`] in order on every attempt,
1409    /// selecting the first existing owner-checked file. Uses the
1410    /// same per-attempt file reads and local-only transport as
1411    /// [`Self::connect_local`], never falling back to TCP. Requests omit implicit
1412    /// consumer identity, including after reconnect; explicit identities in
1413    /// [`CallOptions`] and [`CloseRouteOptions`] are still honoured.
1414    pub async fn connect_operator_app(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1415        Self::connect_operator_app_resolving(
1416            opts,
1417            ConsumerTransport::Local,
1418            crate::operator_app_candidates,
1419        )
1420        .await
1421    }
1422
1423    /// Open the desktop operator app's plain connection over TCP.
1424    ///
1425    /// Selects and owner-checks the installed daemon's connection file with the
1426    /// same [`crate::operator_app_candidates`] policy as
1427    /// [`Self::connect_operator_app`], then connects to the file's first TCP
1428    /// endpoint instead of its Unix socket or Windows named pipe.
1429    ///
1430    /// The daemon recognises a connection as the operator app only when it
1431    /// arrives over its Unix socket or named pipe, so this connection never
1432    /// carries the `operator_app` stamp and can't skip the daemon's
1433    /// confirmation. Its privileged requests follow the daemon's configured
1434    /// policy like any other client's. The caller decides which actions to send
1435    /// here, for example those made through assistive technology. This API
1436    /// doesn't classify input.
1437    ///
1438    /// When the daemon supports `connection.describe`,
1439    /// [`Self::describe_connection`] reports this connection with
1440    /// `local() == false`. There, `local` means the Unix socket or named pipe,
1441    /// not loopback.
1442    ///
1443    /// Like [`Self::connect_operator_app`], it reads no environment variable for
1444    /// discovery or consumer identity, including after reconnect, and never
1445    /// falls back to the local endpoint.
1446    pub async fn connect_operator_app_plain(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
1447        Self::connect_operator_app_resolving(
1448            opts,
1449            ConsumerTransport::Tcp,
1450            crate::operator_app_candidates,
1451        )
1452        .await
1453    }
1454
1455    async fn connect_operator_app_resolving(
1456        opts: ConsumerOptions,
1457        transport: ConsumerTransport,
1458        resolve: impl FnOnce() -> Result<Vec<PathBuf>, crate::OperatorAppPathError>,
1459    ) -> Result<Self, ConsumerError> {
1460        let candidates = resolve().map_err(|source| ConsumerError::ConnectionFile {
1461            path: PathBuf::new(),
1462            source: ConnectionFileError::Io {
1463                op: "resolve installed daemon connection-file path",
1464                path: PathBuf::new(),
1465                source: io::Error::other(source),
1466            },
1467        })?;
1468        let path = candidates[0].clone();
1469        let opened =
1470            open_connection(&path, opts.handshake_timeout, transport, Some(&candidates)).await?;
1471        let mut shared = Shared::with_transport(path, opts, transport);
1472        shared.operator_app_candidates = Some(candidates);
1473        shared.identity_from_environment = false;
1474        let shared = Arc::new(shared);
1475        shared.install_initial(opened)?;
1476        Ok(Self { shared })
1477    }
1478
1479    /// Open or reuse an unscoped managed route and return a handle tied to its
1480    /// current connection (stale after a reconnect).
1481    /// A scope in `opts` is an argument error; use [`Self::open_route_scoped`].
1482    pub async fn open_route(
1483        &self,
1484        target: RouteTarget,
1485        identity: BindIdentity,
1486        opts: CallOptions,
1487    ) -> Result<RouteHandle, CallError> {
1488        opts.reject_scope()?;
1489        let deadline = Instant::now() + opts.timeout;
1490        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
1491        let consumer_capabilities = route_open_consumer_capabilities(&opts);
1492        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
1493        let key = RouteKey::new(
1494            &target,
1495            &identity,
1496            consumer_identity.as_ref(),
1497            consumer_capabilities.as_deref(),
1498        )
1499        .with_role_versions(role_versions.as_ref());
1500        let params = RouteOpenParams {
1501            target: &target,
1502            identity: &identity,
1503            consumer_identity: &consumer_identity,
1504            consumer_capabilities: &consumer_capabilities,
1505            role_versions: &role_versions,
1506            reverse_requests: &opts.reverse_requests,
1507            scope: None,
1508        };
1509        self.shared
1510            .ensure_route(&key, &params, &opts, deadline)
1511            .await
1512            .map(|route| route.handle)
1513    }
1514
1515    /// Open or reuse a managed route admitted under `scope`, and return a handle
1516    /// tied to its current connection (stale after a reconnect).
1517    ///
1518    /// This is how a carrier opens its onward route for a session. The daemon
1519    /// admits the open only when the opener (the consumer identity in `opts`,
1520    /// or the supervised module's own identity from the environment) is the
1521    /// scope's owner or one of its listed carriers, and it stamps the
1522    /// provider's bind with the scope. `scope.scope_epoch` must be set: the
1523    /// daemon refuses an open without it (`scope_epoch_required`).
1524    ///
1525    /// The route is cached under the whole selector (owner, ref and epoch) as
1526    /// well as the target and identities, so a route opened under one scope or
1527    /// epoch is never returned to a caller asking for another, and a scoped
1528    /// route is never returned by [`Self::open_route`] (nor an unscoped one
1529    /// here). Once the route closes, the next call with the same selector opens
1530    /// a fresh route under that selector. Close it early with
1531    /// [`Self::close_handle`].
1532    ///
1533    /// Refusals: `scope_not_synced` (the owner has not synced since the daemon
1534    /// started) and `scope_changed` (the scope changed while the bind was in
1535    /// flight) are retried within the call's deadline, like a module reload.
1536    /// `scope_ended`, `scope_not_live`, `scope_epoch_required` and
1537    /// `scope_not_carrier` end the call at once as [`CallError::NotSent`], with
1538    /// the daemon's code in [`CallError::route_open_refusal`].
1539    ///
1540    /// When the daemon later closes the route because its scope ended or the
1541    /// opener's authority under it was revoked, [`Self::control_pushes`]
1542    /// delivers `route.closed` with a `scope_*` reason. Its
1543    /// [`RouteCloseReason::disposition`] is
1544    /// [`RouteCloseDisposition::MustNotReopen`]: the session the route served is
1545    /// over, so callers should stop work for that session. The SDK does not
1546    /// cache a tombstone: a later explicit open or managed call with the same
1547    /// selector attempts a fresh open. The daemon refuses it as `scope_ended`
1548    /// if the ref is live at another epoch, or `scope_not_live` if the ref is gone.
1549    /// A selector in `opts.scope` must equal `scope`, or the call fails locally
1550    /// as an argument error before opening a route.
1551    pub async fn open_route_scoped(
1552        &self,
1553        target: RouteTarget,
1554        identity: BindIdentity,
1555        scope: ScopeSelector,
1556        opts: CallOptions,
1557    ) -> Result<RouteHandle, CallError> {
1558        if opts
1559            .scope
1560            .as_ref()
1561            .is_some_and(|selected| selected != &scope)
1562        {
1563            return Err(CallError::not_sent(
1564                "CallOptions.scope differs from open_route_scoped's explicit scope",
1565            ));
1566        }
1567        let deadline = Instant::now() + opts.timeout;
1568        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
1569        let consumer_capabilities = route_open_consumer_capabilities(&opts);
1570        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
1571        let key = RouteKey::new(
1572            &target,
1573            &identity,
1574            consumer_identity.as_ref(),
1575            consumer_capabilities.as_deref(),
1576        )
1577        .with_role_versions(role_versions.as_ref())
1578        .with_scope(Some(&scope));
1579        let params = RouteOpenParams {
1580            target: &target,
1581            identity: &identity,
1582            consumer_identity: &consumer_identity,
1583            consumer_capabilities: &consumer_capabilities,
1584            role_versions: &role_versions,
1585            reverse_requests: &opts.reverse_requests,
1586            scope: Some(&scope),
1587        };
1588        self.shared
1589            .ensure_route(&key, &params, &opts, deadline)
1590            .await
1591            .map(|route| route.handle)
1592    }
1593
1594    /// Open one admitted route without entering the managed route cache.
1595    ///
1596    /// Admitted routes are never cached or reopened after a connection drop. If
1597    /// this call fails or the route later closes, the caller must perform admission
1598    /// again and call this method with fresh facts.
1599    ///
1600    /// The route declares no reverse-request capabilities, so the provider cannot
1601    /// send it requests. Use [`Self::open_route_with_admission_facts_and_options`]
1602    /// when the provider asks the consumer questions on the route (elicitation).
1603    pub async fn open_route_with_admission_facts(
1604        &self,
1605        target: RouteTarget,
1606        identity: BindIdentity,
1607        facts: serde_json::Value,
1608    ) -> Result<RouteHandle, CallError> {
1609        let deadline = Instant::now() + self.shared.opts.call_timeout;
1610        self.open_admitted_route(
1611            target,
1612            identity,
1613            facts,
1614            &CallOptions::default(),
1615            None,
1616            deadline,
1617        )
1618        .await
1619    }
1620
1621    /// Open one admitted route, with the reverse-request handlers, capability
1622    /// declarations and timeout in `opts`.
1623    ///
1624    /// The route declares the method families of handlers registered on
1625    /// `opts.reverse_requests`, together with any provider-contract declarations
1626    /// in the extra declarations reported by `opts.consumer_capabilities()`. For example, `tool-result/v1` declares the
1627    /// tool-provider content result format. These are unverified declarations,
1628    /// not privilege grants. Requests the provider sends back (elicitation,
1629    /// sampling) reach the registered handlers, exactly as on a managed route.
1630    /// Handlers must be registered before this call: the registry is sealed
1631    /// when the route opens, because the declared method families are what the
1632    /// provider was told.
1633    ///
1634    /// Like [`Self::open_route_with_admission_facts`], the route is never cached
1635    /// or reopened; after a failure or a close the caller performs admission again.
1636    /// A non-`None` `opts.scope` is rejected as an argument error.
1637    pub async fn open_route_with_admission_facts_and_options(
1638        &self,
1639        target: RouteTarget,
1640        identity: BindIdentity,
1641        facts: serde_json::Value,
1642        opts: CallOptions,
1643    ) -> Result<RouteHandle, CallError> {
1644        opts.reject_scope()?;
1645        let deadline = Instant::now() + opts.timeout;
1646        let reverse_requests = opts.reverse_requests.clone();
1647        self.open_admitted_route(
1648            target,
1649            identity,
1650            facts,
1651            &opts,
1652            Some(reverse_requests),
1653            deadline,
1654        )
1655        .await
1656    }
1657
1658    /// One admitted route.open. With `reverse_requests`, the route is opened the
1659    /// way the managed path opens one: the capabilities are declared, the socket
1660    /// reader installs the handle before the open resolves (so a request the
1661    /// provider sends right after binding is not lost), and the handle carries
1662    /// the registry. Without it, the route has no reverse-request handling.
1663    async fn open_admitted_route(
1664        &self,
1665        target: RouteTarget,
1666        identity: BindIdentity,
1667        facts: serde_json::Value,
1668        opts: &CallOptions,
1669        reverse_requests: Option<ReverseRequestRegistry>,
1670        deadline: Instant,
1671    ) -> Result<RouteHandle, CallError> {
1672        let consumer_capabilities = route_open_consumer_capabilities(opts);
1673        let target_label = route_target_label(&target);
1674        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
1675            busy_refusals: Some(true),
1676            target,
1677            identity,
1678            consumer_identity: self.shared.route_open_consumer_identity(opts)?,
1679            consumer_capabilities,
1680            role_versions: route_open_role_versions(opts.role_versions.as_ref()),
1681            admission_facts: Some(facts),
1682            scope: None,
1683        })
1684        .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;
1685
1686        let terminal = self
1687            .shared
1688            .paced_route_open(body, deadline, reverse_requests.clone())
1689            .await?;
1690        let (generation, body) = match terminal {
1691            TerminalFrame::Response {
1692                generation, body, ..
1693            } => (generation, body),
1694            // The daemon refused the open. Keep its code and detail, as the
1695            // plain route.open does, so a caller can tell "retry shortly"
1696            // (module_warming) from "this configuration will never work"
1697            // (admission_facts_not_permitted).
1698            TerminalFrame::Error { body, .. } => {
1699                return Err(CallError::route_open_refused(target_label, body));
1700            }
1701            _ => {
1702                return Err(CallError::not_sent_with_cause(
1703                    "route.open returned a non-response frame",
1704                    NotSentCause::RouteOpenAbandoned,
1705                ));
1706            }
1707        };
1708        let ClientControlResponse::RouteOpen {
1709            route_channel,
1710            route_epoch,
1711            request_window,
1712            watch_window,
1713            ..
1714        } = decode_route_open_response(&body)
1715            .map_err(|err| {
1716                CallError::not_sent_with_cause(
1717                    format!("failed to decode route.open response: {err}"),
1718                    NotSentCause::RouteOpenAbandoned,
1719                )
1720            })?
1721            .0
1722        else {
1723            return Err(CallError::not_sent_with_cause(
1724                "route.open returned an unexpected control response",
1725                NotSentCause::RouteOpenAbandoned,
1726            ));
1727        };
1728        // Adopt the handle the socket reader installed for this response, which
1729        // carries the registry passed to control_call; build one only if the
1730        // reader did not (the connection moved on before the response landed).
1731        let handle = self
1732            .shared
1733            .ingress_handle(generation, route_channel, route_epoch)
1734            .unwrap_or_else(|| match reverse_requests {
1735                Some(reverse_requests) => RouteHandle::new_consumer(
1736                    route_channel,
1737                    route_epoch,
1738                    generation,
1739                    reverse_requests,
1740                ),
1741                None => RouteHandle::new(route_channel, route_epoch, generation),
1742            });
1743        let route = RouteState::windows(handle, request_window, watch_window);
1744        self.shared.install_one_shot_route(route.clone())?;
1745        Ok(route.handle)
1746    }
1747
1748    /// Describe this connection without prompting or granting any privilege.
1749    /// An older daemon's `unknown_control_op` refusal returns `None`: that daemon
1750    /// doesn't support this query, which says nothing about recognition.
1751    pub async fn describe_connection(&self) -> Result<Option<ConnectionFacts>, CallError> {
1752        let body =
1753            serde_json::to_vec(&subc_control::ConnectionDescribeRequest::new()).map_err(|err| {
1754                CallError::not_sent(format!("failed to encode connection.describe: {err}"))
1755            })?;
1756        let deadline = Instant::now() + self.shared.opts.call_timeout;
1757        match self
1758            .shared
1759            .control_call(body, deadline, false, None)
1760            .await?
1761        {
1762            TerminalFrame::Response { body, .. } => {
1763                let reply: subc_control::ConnectionDescribeReply = serde_json::from_slice(&body)
1764                    .map_err(|err| {
1765                        CallError::invalid_response(format!(
1766                            "failed to decode connection.describe: {err}"
1767                        ))
1768                    })?;
1769                Ok(Some(ConnectionFacts {
1770                    local: reply.local,
1771                    operator_app: reply.operator_app,
1772                }))
1773            }
1774            // The client-control dispatcher uses this exact code for unknown ops.
1775            TerminalFrame::Error { body, .. } if body.code == "unknown_control_op" => Ok(None),
1776            TerminalFrame::Error { body, .. } => Err(CallError::Module(body)),
1777            TerminalFrame::StreamEnd => Err(CallError::invalid_response(
1778                "connection.describe returned StreamEnd",
1779            )),
1780        }
1781    }
1782
1783    /// Ask the daemon to open a known installed app. Starting it grants nothing.
1784    /// Future success statuses and refusal codes are preserved for the caller.
1785    pub async fn app_open(&self, app: &str) -> Result<subc_control::AppOpenReply, AppOpenError> {
1786        let body = serde_json::to_vec(&subc_control::AppOpenRequest::new(app))
1787            .map_err(|err| CallError::not_sent(format!("failed to encode app.open: {err}")))?;
1788        let deadline = Instant::now() + self.shared.opts.call_timeout;
1789        match self
1790            .shared
1791            .control_call(body, deadline, false, None)
1792            .await?
1793        {
1794            TerminalFrame::Response { body, .. } => serde_json::from_slice(&body).map_err(|err| {
1795                CallError::invalid_response(format!("failed to decode app.open: {err}")).into()
1796            }),
1797            TerminalFrame::Error { body, .. } => Err(AppOpenError::Refused {
1798                code: body.code,
1799                message: body.message,
1800            }),
1801            TerminalFrame::StreamEnd => {
1802                Err(CallError::invalid_response("app.open returned StreamEnd").into())
1803            }
1804        }
1805    }
1806
1807    /// Fetch the daemon's module catalog over channel 0.
1808    /// Transport retries use the consumer's reconnect backoff and call deadline.
1809    pub async fn catalog_list(&self) -> Result<CatalogList, CallError> {
1810        let deadline = Instant::now() + self.shared.opts.call_timeout;
1811        let body = serde_json::to_vec(&serde_json::json!({
1812            "op": subc_control::ops::CATALOG_LIST,
1813        }))
1814        .map_err(|err| CallError::not_sent(format!("failed to encode catalog.list: {err}")))?;
1815
1816        let mut attempt = 0usize;
1817        loop {
1818            attempt = attempt.saturating_add(1);
1819            match self
1820                .shared
1821                .control_call(body.clone(), deadline, false, None)
1822                .await
1823            {
1824                Ok(TerminalFrame::Response { body, .. }) => {
1825                    let response =
1826                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1827                            CallError::invalid_response(format!(
1828                                "failed to decode catalog.list response: {err}"
1829                            ))
1830                        })?;
1831                    let ClientControlResponse::CatalogList {
1832                        generation,
1833                        modules,
1834                        subc_ops,
1835                    } = response
1836                    else {
1837                        return Err(CallError::invalid_response(
1838                            "catalog.list returned an unexpected control response",
1839                        ));
1840                    };
1841                    return Ok(CatalogList {
1842                        generation,
1843                        modules,
1844                        subc_ops,
1845                    });
1846                }
1847                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1848                Ok(TerminalFrame::StreamEnd) => {
1849                    return Err(CallError::invalid_response(
1850                        "catalog.list returned StreamEnd",
1851                    ));
1852                }
1853                Err(err)
1854                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1855                {
1856                    // Connection-file and discovery failures can complete without
1857                    // yielding. Pace the outer retry as well as reconnect itself,
1858                    // so repeated immediate failures cannot monopolize the executor.
1859                    let delay = self.shared.jittered(
1860                        self.shared
1861                            .opts
1862                            .reconnect_backoff
1863                            .delay_after_attempt(attempt),
1864                    );
1865                    self.shared.sleep_until_retry(deadline, delay).await?;
1866                    continue;
1867                }
1868                Err(err) => return Err(err),
1869            }
1870        }
1871    }
1872
1873    /// Fetch the supervisor's configured module list over channel 0.
1874    /// Transport retries use the consumer's reconnect backoff and call deadline.
1875    pub async fn supervisor_list(&self) -> Result<SupervisorListResponse, CallError> {
1876        let deadline = Instant::now() + self.shared.opts.call_timeout;
1877        let body = serde_json::to_vec(&ClientControlRequest::SupervisorList {}).map_err(|err| {
1878            CallError::not_sent(format!("failed to encode supervisor.list: {err}"))
1879        })?;
1880
1881        let mut attempt = 0usize;
1882        loop {
1883            attempt = attempt.saturating_add(1);
1884            match self
1885                .shared
1886                .control_call(body.clone(), deadline, false, None)
1887                .await
1888            {
1889                Ok(TerminalFrame::Response { body, .. }) => {
1890                    let response =
1891                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1892                            CallError::invalid_response(format!(
1893                                "failed to decode supervisor.list response: {err}"
1894                            ))
1895                        })?;
1896                    let ClientControlResponse::SupervisorList {
1897                        generation,
1898                        modules,
1899                        daemon,
1900                        agent_commands,
1901                    } = response
1902                    else {
1903                        return Err(CallError::invalid_response(
1904                            "supervisor.list returned an unexpected control response",
1905                        ));
1906                    };
1907                    return Ok(SupervisorListResponse {
1908                        generation,
1909                        modules,
1910                        daemon,
1911                        agent_commands,
1912                    });
1913                }
1914                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1915                Ok(TerminalFrame::StreamEnd) => {
1916                    return Err(CallError::invalid_response(
1917                        "supervisor.list returned StreamEnd",
1918                    ));
1919                }
1920                Err(err)
1921                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1922                {
1923                    // Pace immediate discovery failures so retries cannot monopolize the executor.
1924                    let delay = self.shared.jittered(
1925                        self.shared
1926                            .opts
1927                            .reconnect_backoff
1928                            .delay_after_attempt(attempt),
1929                    );
1930                    self.shared.sleep_until_retry(deadline, delay).await?;
1931                    continue;
1932                }
1933                Err(err) => return Err(err),
1934            }
1935        }
1936    }
1937
1938    /// Fetch the supervisor's atomic spawn snapshot (`supervisor.spawn_snapshot`)
1939    /// over channel 0: the live processes with their spawn generations, and the
1940    /// cursor at which they were observed.
1941    ///
1942    /// A daemon refusal comes back as [`CallError::Module`], so its code is readable
1943    /// through [`CallError::code`]. Transport failures are retried until the
1944    /// consumer's call deadline with its reconnect backoff, as for
1945    /// [`SubcConsumer::catalog_list`].
1946    pub async fn spawn_snapshot(&self) -> Result<SpawnSnapshot, CallError> {
1947        let deadline = Instant::now() + self.shared.opts.call_timeout;
1948        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSnapshot {}).map_err(
1949            |err| CallError::not_sent(format!("failed to encode supervisor.spawn_snapshot: {err}")),
1950        )?;
1951
1952        let mut attempt = 0usize;
1953        loop {
1954            attempt = attempt.saturating_add(1);
1955            match self
1956                .shared
1957                .control_call(body.clone(), deadline, false, None)
1958                .await
1959            {
1960                Ok(TerminalFrame::Response { body, .. }) => {
1961                    let response =
1962                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
1963                            CallError::invalid_response(format!(
1964                                "failed to decode supervisor.spawn_snapshot response: {err}"
1965                            ))
1966                        })?;
1967                    let ClientControlResponse::SupervisorSpawnSnapshot { snapshot } = response
1968                    else {
1969                        return Err(CallError::invalid_response(
1970                            "supervisor.spawn_snapshot returned an unexpected control response",
1971                        ));
1972                    };
1973                    return Ok(snapshot);
1974                }
1975                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
1976                Ok(TerminalFrame::StreamEnd) => {
1977                    return Err(CallError::invalid_response(
1978                        "supervisor.spawn_snapshot returned StreamEnd",
1979                    ));
1980                }
1981                Err(err)
1982                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
1983                {
1984                    let delay = self.shared.jittered(
1985                        self.shared
1986                            .opts
1987                            .reconnect_backoff
1988                            .delay_after_attempt(attempt),
1989                    );
1990                    self.shared.sleep_until_retry(deadline, delay).await?;
1991                    continue;
1992                }
1993                Err(err) => return Err(err),
1994            }
1995        }
1996    }
1997
1998    /// Query the newest-first activity ledger. The reply preserves entries, the
1999    /// continuation cursor and the head to subscribe from without a query/follow gap.
2000    /// Except for operator-app connections, identity is filled from the supervised
2001    /// launch environment, as for route.open; without one the daemon treats the
2002    /// caller as Direct. Refusals retain their code
2003    /// through [`CallError::code`]. Transport retries are paced to the call deadline.
2004    pub async fn query_activity(
2005        &self,
2006        request: ActivityQueryRequest,
2007    ) -> Result<ActivityQueryResponse, CallError> {
2008        let deadline = Instant::now() + self.shared.opts.call_timeout;
2009        let body = self.shared.activity_read_body(request)?;
2010        let mut attempt = 0usize;
2011        loop {
2012            attempt = attempt.saturating_add(1);
2013            match self
2014                .shared
2015                .control_call(body.clone(), deadline, false, None)
2016                .await
2017            {
2018                Ok(TerminalFrame::Response { body, .. }) => {
2019                    return serde_json::from_slice(&body).map_err(|err| {
2020                        CallError::invalid_response(format!(
2021                            "invalid activity.query response: {err}"
2022                        ))
2023                    });
2024                }
2025                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
2026                Ok(TerminalFrame::StreamEnd) => {
2027                    return Err(CallError::invalid_response(
2028                        "activity.query returned StreamEnd",
2029                    ));
2030                }
2031                Err(err)
2032                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
2033                {
2034                    let delay = self.shared.jittered(
2035                        self.shared
2036                            .opts
2037                            .reconnect_backoff
2038                            .delay_after_attempt(attempt),
2039                    );
2040                    self.shared.sleep_until_retry(deadline, delay).await?;
2041                }
2042                Err(err) => return Err(err),
2043            }
2044        }
2045    }
2046
2047    /// Follow durable activity entries after `since`, or from now if absent.
2048    /// The launch identity is filled as for [`Self::query_activity`]. Refused cursors
2049    /// and subscriber lag are terminal stream errors whose daemon code is readable
2050    /// through [`crate::ActivityStreamError::code`]. On reconnect the stream ends;
2051    /// recover with a query and subscribe from its head.
2052    pub async fn subscribe_activity(
2053        &self,
2054        since: Option<ActivityCursor>,
2055    ) -> Result<ActivitySubscription, CallError> {
2056        let deadline = Instant::now() + self.shared.opts.call_timeout;
2057        let body = self
2058            .shared
2059            .activity_read_body(ActivitySubscribeRequest { since })?;
2060        loop {
2061            self.shared.ensure_connected_for_call(deadline).await?;
2062            let permit = Arc::new(Semaphore::new(1))
2063                .acquire_owned()
2064                .await
2065                .map_err(|_| CallError::not_sent("activity subscription permit closed"))?;
2066            match self
2067                .shared
2068                .send_subscription(SubscriptionSend {
2069                    expected_handle: None,
2070                    channel: 0,
2071                    epoch: 0,
2072                    body: body.clone(),
2073                    priority: Priority::Interactive,
2074                    admission_class: AdmissionClass::Normal,
2075                    event_buffer: ACTIVITY_EVENT_BUFFER,
2076                    deadline,
2077                    permit: RoutePermit::legacy(permit),
2078                })
2079                .await
2080            {
2081                Ok(inner) => {
2082                    return Ok(ActivitySubscription {
2083                        inner,
2084                        finished: false,
2085                    })
2086                }
2087                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
2088                Err(err) => return Err(err),
2089            }
2090        }
2091    }
2092
2093    /// Follow the supervisor's spawn event stream (`supervisor.spawn_subscribe`) over
2094    /// channel 0, from just after `since` (a cursor copied from a snapshot or an event),
2095    /// or from now when `since` is `None`.
2096    ///
2097    /// The request is held open: the returned [`SpawnSubscription`] yields each event
2098    /// until the stream ends. A cursor the daemon refuses, and the daemon dropping a
2099    /// subscriber that fell behind, arrive as the stream's terminal error (see
2100    /// [`SpawnStreamError`]). A reconnect ends the stream; the caller resubscribes from
2101    /// the last cursor it received. Sending is retried until the consumer's call
2102    /// deadline, as for [`SubcConsumer::spawn_snapshot`].
2103    pub async fn spawn_subscribe(
2104        &self,
2105        since: Option<SpawnCursor>,
2106    ) -> Result<SpawnSubscription, CallError> {
2107        let deadline = Instant::now() + self.shared.opts.call_timeout;
2108        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSubscribe { since })
2109            .map_err(|err| {
2110                CallError::not_sent(format!(
2111                    "failed to encode supervisor.spawn_subscribe: {err}"
2112                ))
2113            })?;
2114        loop {
2115            self.shared.ensure_connected_for_call(deadline).await?;
2116            // Channel 0 has no route flow-control window; the subscription holds a
2117            // permit of its own so it is shaped like a route subscription.
2118            let permit = Arc::new(Semaphore::new(1))
2119                .acquire_owned()
2120                .await
2121                .map_err(|_| CallError::not_sent("spawn subscription permit closed"))?;
2122            match self
2123                .shared
2124                .send_subscription(SubscriptionSend {
2125                    expected_handle: None,
2126                    channel: 0,
2127                    epoch: 0,
2128                    body: body.clone(),
2129                    priority: Priority::Interactive,
2130                    admission_class: AdmissionClass::Normal,
2131                    event_buffer: SPAWN_EVENT_BUFFER,
2132                    deadline,
2133                    permit: RoutePermit::legacy(permit),
2134                })
2135                .await
2136            {
2137                Ok(inner) => {
2138                    return Ok(SpawnSubscription {
2139                        inner,
2140                        finished: false,
2141                    })
2142                }
2143                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
2144                Err(err) => return Err(err),
2145            }
2146        }
2147    }
2148
2149    /// Resolve the sole catalog claimant for a capability.
2150    ///
2151    /// Resolution is deliberately based only on the static capabilities mirror in
2152    /// `catalog.list`; module ids and role names are not fallback claims. Calling
2153    /// this method expresses singular intent, so a plural catalog result is an
2154    /// explicit ambiguity rather than an arbitrary choice.
2155    pub async fn resolve_provider(&self, capability: &str) -> Result<String, CallError> {
2156        let claimants = self.resolve_providers(capability).await?;
2157        match claimants.as_slice() {
2158            [] => Err(CallError::CapabilityUnprovided {
2159                capability: capability.to_string(),
2160            }),
2161            [claimant] => Ok(claimant.clone()),
2162            _ => Err(CallError::CapabilityAmbiguous {
2163                capability: capability.to_string(),
2164                claimants,
2165            }),
2166        }
2167    }
2168
2169    /// Resolve every catalog claimant for a capability in module-id order.
2170    ///
2171    /// The identifier is validated before any channel-0 request is made, so a
2172    /// typo cannot become a network-dependent "unprovided" result.
2173    pub async fn resolve_providers(&self, capability: &str) -> Result<Vec<String>, CallError> {
2174        validate_capability_for_resolution(capability)?;
2175        let catalog = self.catalog_list().await?;
2176        Ok(capability_claimants(&catalog, capability))
2177    }
2178
2179    /// Send one request using an already-opened route handle.
2180    /// `opts.scope` must be `None`: the handle's scope was selected at route open.
2181    pub async fn request(
2182        &self,
2183        handle: &RouteHandle,
2184        body: Vec<u8>,
2185        opts: CallOptions,
2186    ) -> Result<Vec<u8>, CallError> {
2187        self.request_inner(handle, body, opts, None).await
2188    }
2189
2190    /// Like [`Self::request`], with explicit cancellation of the in-flight request.
2191    ///
2192    /// The returned future is lazy and has the same result and deadline as `request`.
2193    /// Calling [`CancelHandle::cancel`] sends at most one header-only Cancel on the
2194    /// request's route; it does not stop waiting for the provider's Response or Error.
2195    /// Dropping the handle sends nothing. Dropping the future only removes its
2196    /// pending registration, **without sending Cancel**.
2197    ///
2198    /// ```no_run
2199    /// # async fn turn(consumer: &subc_client_rs::SubcConsumer,
2200    /// # route: &subc_client_rs::RouteHandle,
2201    /// # turn_stopped: impl std::future::Future<Output = ()>) -> Result<(), subc_client_rs::CallError> {
2202    /// let (cancel, reply) = consumer.request_cancellable(
2203    ///     route, b"work".to_vec(), subc_client_rs::CallOptions::default());
2204    /// tokio::pin!(reply);
2205    /// tokio::select! {
2206    ///     result = &mut reply => { let _body = result?; }
2207    ///     () = turn_stopped => {
2208    ///         cancel.cancel().await;
2209    ///         let _body = reply.await?; // Keep any final Response body.
2210    ///     }
2211    /// }
2212    /// # Ok(())
2213    /// # }
2214    /// ```
2215    pub fn request_cancellable(
2216        &self,
2217        handle: &RouteHandle,
2218        body: Vec<u8>,
2219        opts: CallOptions,
2220    ) -> (
2221        CancelHandle,
2222        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
2223    ) {
2224        let consumer = self;
2225        let handle = *handle;
2226        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2227        let future = async move {
2228            let guard = registration;
2229            consumer
2230                .request_inner(&handle, body, opts, Some(Arc::clone(&guard.state)))
2231                .await
2232        };
2233        (cancel, future)
2234    }
2235
2236    async fn request_inner(
2237        &self,
2238        handle: &RouteHandle,
2239        body: Vec<u8>,
2240        opts: CallOptions,
2241        cancel: Option<Arc<UnaryCancel>>,
2242    ) -> Result<Vec<u8>, CallError> {
2243        opts.reject_scope()?;
2244        let deadline = Instant::now() + opts.timeout;
2245        let route = self.shared.route_state(*handle)?;
2246        let permit = route.acquire(false, deadline, cancel.as_ref()).await?;
2247        let mut busy_delay = Duration::from_millis(25);
2248        loop {
2249            let result = self
2250                .shared
2251                .send_request_with_slot(
2252                    RequestSend {
2253                        binary: false,
2254                        expected_handle: Some(*handle),
2255                        channel: handle.channel,
2256                        epoch: handle.epoch,
2257                        body: body.clone(),
2258                        priority: opts.priority,
2259                        admission_class: opts.admission_class,
2260                        deadline,
2261                        retain_late_route_open: false,
2262                        route_open_reverse_requests: None,
2263                    },
2264                    cancel.clone(),
2265                    Some(Arc::clone(&permit)),
2266                )
2267                .await;
2268            match result? {
2269                TerminalFrame::Response { body, .. } => return Ok(body),
2270                TerminalFrame::StreamEnd => return Ok(Vec::new()),
2271                TerminalFrame::Error { body, flags }
2272                    if error_codes::is_route_busy_retryable(flags, &body.code, route.opted_in) =>
2273                {
2274                    if !self
2275                        .shared
2276                        .busy_backoff(deadline, busy_delay, cancel.as_ref())
2277                        .await
2278                    {
2279                        return Err(busy_error(&body));
2280                    }
2281                    busy_delay = (busy_delay * 2).min(Duration::from_secs(1));
2282                    self.shared.validate_current_handle(*handle)?;
2283                }
2284                TerminalFrame::Error { body, flags } => {
2285                    return Err(CallError::from_established_route_error(flags, body));
2286                }
2287            }
2288        }
2289    }
2290
2291    /// Start a held-open request using an already-opened route handle.
2292    /// `opts.scope` must be `None`: the handle's scope was selected at route open.
2293    pub async fn subscribe_route(
2294        &self,
2295        handle: &RouteHandle,
2296        body: Vec<u8>,
2297        opts: SubscribeOptions,
2298    ) -> Result<Subscription, CallError> {
2299        if opts.scope.is_some() {
2300            return Err(CallError::not_sent(
2301                "SubscribeOptions.scope is not supported on subscribe_route; select the scope when opening the route",
2302            ));
2303        }
2304        let deadline = Instant::now() + opts.route_open_timeout;
2305        let route = self.shared.route_state(*handle)?;
2306        let permit = route.acquire(true, deadline, None).await?;
2307        self.shared
2308            .send_subscription(SubscriptionSend {
2309                expected_handle: Some(*handle),
2310                channel: handle.channel,
2311                epoch: handle.epoch,
2312                body,
2313                priority: opts.priority,
2314                admission_class: opts.admission_class,
2315                event_buffer: opts.event_buffer,
2316                deadline,
2317                permit,
2318            })
2319            .await
2320    }
2321
2322    /// Poll status or liveness for exactly this route handle.
2323    /// A daemon refusal is returned as [`CallError::Module`] with its original body.
2324    pub async fn poll_route(
2325        &self,
2326        handle: &RouteHandle,
2327        kind: PollKind,
2328        timeout: Duration,
2329    ) -> Result<RoutePollResult, CallError> {
2330        let deadline = Instant::now() + timeout;
2331        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
2332            route_channel: handle.channel,
2333            route_epoch: handle.epoch,
2334            kind,
2335        })
2336        .map_err(|err| CallError::not_sent(format!("failed to encode route.poll: {err}")))?;
2337        let terminal = self
2338            .shared
2339            .send_request(RequestSend {
2340                binary: false,
2341                expected_handle: Some(*handle),
2342                channel: 0,
2343                epoch: 0,
2344                body,
2345                priority: Priority::Interactive,
2346                admission_class: AdmissionClass::Normal,
2347                deadline,
2348                retain_late_route_open: false,
2349                route_open_reverse_requests: None,
2350            })
2351            .await?;
2352        let body = match terminal {
2353            TerminalFrame::Response { body, .. } => body,
2354            TerminalFrame::Error { body, .. } => return Err(CallError::Module(body)),
2355            TerminalFrame::StreamEnd => {
2356                return Err(CallError::invalid_response(
2357                    "route.poll returned a non-response frame",
2358                ));
2359            }
2360        };
2361        let ClientControlResponse::RoutePoll {
2362            route_channel,
2363            route_epoch,
2364            status,
2365            live,
2366        } = serde_json::from_slice(&body).map_err(|err| {
2367            CallError::invalid_response(format!("failed to decode route.poll: {err}"))
2368        })?
2369        else {
2370            return Err(CallError::invalid_response(
2371                "route.poll returned an unexpected control response",
2372            ));
2373        };
2374        if route_channel != handle.channel || route_epoch != handle.epoch {
2375            return Err(CallError::invalid_response(
2376                "route.poll response echoed a different route handle",
2377            ));
2378        }
2379        self.shared.validate_current_handle(*handle)?;
2380        Ok(RoutePollResult {
2381            handle: *handle,
2382            status,
2383            live,
2384        })
2385    }
2386
2387    /// Locally observed count of unknown or stale route frames dropped by layer-2 validation.
2388    pub fn dropped_route_frames(&self) -> u64 {
2389        self.shared.lock_inner().dropped_route_frames
2390    }
2391
2392    /// Register a receiver for provider-originated Push frames on exactly one live route.
2393    ///
2394    /// Registering another receiver for the same route replaces and closes the prior receiver.
2395    /// The receiver closes when its route closes or the connection drops. A FULL buffer drops
2396    /// the overflowing push and counts it on `pushes_dropped_receiver_full` while the
2397    /// subscription survives (issue #40; push is a lossy latency optimization and polling
2398    /// remains the correctness backstop). The reader never waits for an application that is
2399    /// not draining pushes.
2400    pub fn push_events(
2401        &self,
2402        handle: &RouteHandle,
2403    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
2404        self.shared.register_push_events(*handle)
2405    }
2406
2407    /// Number of Push frames dropped because their live route has no active receiver.
2408    ///
2409    /// Push is a one-way latency optimization, not a durable feed: the client does not
2410    /// acknowledge it, and callers retain polling as their correctness backstop. Counting
2411    /// intentional default-path drops makes an application that has not opted in observable.
2412    pub fn pushes_dropped_no_receiver(&self) -> u64 {
2413        self.shared
2414            .pushes_dropped_no_receiver
2415            .load(Ordering::Relaxed)
2416    }
2417
2418    /// Pushes dropped because the registered receiver's bounded buffer was full.
2419    /// The subscription SURVIVES a burst (the receiver stays registered); this
2420    /// counter is the trace the burst leaves. Distinct from
2421    /// `pushes_dropped_no_receiver` because the remedies differ: full means
2422    /// drain faster or register with more capacity, no-receiver means nobody
2423    /// subscribed.
2424    pub fn pushes_dropped_receiver_full(&self) -> u64 {
2425        self.shared
2426            .pushes_dropped_receiver_full
2427            .load(Ordering::Relaxed)
2428    }
2429
2430    /// Register the consumer-level receiver for daemon-originated channel-0
2431    /// control pushes (`route.closing`, `route.closed`, and any op added
2432    /// later). Advisory by contract: GOODBYE remains the load-bearing
2433    /// route-death signal and nothing in the client's own lifecycle consumes
2434    /// these. Unrecognized ops are DELIVERED (the must-ignore choice belongs
2435    /// to the consumer); unparseable bodies are dropped and counted. The
2436    /// receiver survives reconnects. Registering again replaces the prior
2437    /// receiver; a full or closed receiver drops the push and counts it
2438    /// rather than blocking the reader.
2439    pub fn control_pushes(&self, capacity: usize) -> mpsc::Receiver<ControlPush> {
2440        let (sender, receiver) = mpsc::channel(capacity.max(1));
2441        self.shared.lock_inner().control_push_receiver = Some(sender);
2442        receiver
2443    }
2444
2445    /// Always-present count of dropped channel-0 control pushes (no receiver
2446    /// registered, receiver full or closed, or unparseable body). Emitted as a
2447    /// counter rather than silence so an application that has not opted in is
2448    /// observable, mirroring `pushes_dropped_no_receiver`.
2449    pub fn control_pushes_dropped(&self) -> u64 {
2450        self.shared.control_pushes_dropped.load(Ordering::Relaxed)
2451    }
2452
2453    /// Managed unary call. Route-open failures happen before the body is sent and are
2454    /// classified as `NotSent`; module handler Error frames are the only `Module` errors.
2455    ///
2456    /// A daemon refusal that proves the module never received the request
2457    /// (`unknown_channel`, `stale_route_epoch`, or `module_reloading` while the
2458    /// module drains for a restart, reload or disable) evicts the cached route,
2459    /// reopens it and resends the request once, within the call deadline and
2460    /// only if the call has not been cancelled. Reopening during a drain waits
2461    /// out the daemon's `route.open` refusals until the replacement process
2462    /// registers, so the resend reaches the new process. A second such refusal
2463    /// is returned as `CallError::Module`.
2464    pub async fn call(
2465        &self,
2466        target: RouteTarget,
2467        identity: BindIdentity,
2468        body: Vec<u8>,
2469        opts: CallOptions,
2470    ) -> Result<Vec<u8>, CallError> {
2471        self.call_with_reply(target, identity, body, opts)
2472            .await
2473            .map(CallReply::into_body)
2474    }
2475
2476    /// Like [`Self::call`], retaining the terminal Response's binary flag as well
2477    /// as its unchanged body bytes. A StreamEnd yields an empty, non-binary reply.
2478    pub async fn call_with_reply(
2479        &self,
2480        target: RouteTarget,
2481        identity: BindIdentity,
2482        body: Vec<u8>,
2483        opts: CallOptions,
2484    ) -> Result<CallReply, CallError> {
2485        self.call_inner(target, identity, (body, false), opts, None)
2486            .await
2487    }
2488
2489    /// Managed unary call with explicit cancellation, like [`Self::request_cancellable`].
2490    ///
2491    /// Uses the same route opening, options, errors and deadline as [`Self::call`].
2492    /// Once cancellation is requested, a dead-route or `module_reloading` refusal is
2493    /// returned rather than retrying work the caller has asked to stop. Cancellation during route opening
2494    /// is remembered and sent after the Request is queued. Dropping either value
2495    /// sends no Cancel; dropping the future removes its pending registration.
2496    pub fn call_cancellable(
2497        &self,
2498        target: RouteTarget,
2499        identity: BindIdentity,
2500        body: Vec<u8>,
2501        opts: CallOptions,
2502    ) -> (
2503        CancelHandle,
2504        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
2505    ) {
2506        let (cancel, reply) = self.call_cancellable_with_reply(target, identity, body, opts);
2507        (cancel, async move { reply.await.map(CallReply::into_body) })
2508    }
2509
2510    /// Like [`Self::call_cancellable`], retaining the terminal Response's binary
2511    /// flag and unchanged bytes in [`CallReply`]. Cancellation, retries, deadlines
2512    /// and drop behavior are identical. A StreamEnd yields an empty, non-binary reply.
2513    pub fn call_cancellable_with_reply(
2514        &self,
2515        target: RouteTarget,
2516        identity: BindIdentity,
2517        body: Vec<u8>,
2518        opts: CallOptions,
2519    ) -> (
2520        CancelHandle,
2521        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
2522    ) {
2523        let consumer = self;
2524        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2525        let future = async move {
2526            let guard = registration;
2527            consumer
2528                .call_inner(
2529                    target,
2530                    identity,
2531                    (body, false),
2532                    opts,
2533                    Some(Arc::clone(&guard.state)),
2534                )
2535                .await
2536        };
2537        (cancel, future)
2538    }
2539
2540    /// Sends a framed JSON object head and opaque payload with `FLAG_BINARY`.
2541    /// Only use this for management operations that declare `operation_payload`.
2542    /// The caller enforces the operation's limit; the codec only bounds the head.
2543    pub async fn call_framed_with_reply(
2544        &self,
2545        target: RouteTarget,
2546        identity: BindIdentity,
2547        head: serde_json::Value,
2548        payload: Vec<u8>,
2549        opts: CallOptions,
2550    ) -> Result<CallReply, CallError> {
2551        let body = subc_protocol::framed_body::encode(&head, &payload)
2552            .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
2553        self.call_inner(target, identity, (body, true), opts, None)
2554            .await
2555    }
2556
2557    /// Cancellable companion to [`Self::call_framed_with_reply`], with the same
2558    /// lazy send, cancellation, retry and deadline behavior as other managed calls.
2559    pub fn call_framed_cancellable_with_reply(
2560        &self,
2561        target: RouteTarget,
2562        identity: BindIdentity,
2563        head: serde_json::Value,
2564        payload: Vec<u8>,
2565        opts: CallOptions,
2566    ) -> (
2567        CancelHandle,
2568        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
2569    ) {
2570        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
2571        (cancel, async move {
2572            let guard = registration;
2573            let body = subc_protocol::framed_body::encode(&head, &payload)
2574                .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
2575            self.call_inner(
2576                target,
2577                identity,
2578                (body, true),
2579                opts,
2580                Some(Arc::clone(&guard.state)),
2581            )
2582            .await
2583        })
2584    }
2585
2586    async fn call_inner(
2587        &self,
2588        target: RouteTarget,
2589        identity: BindIdentity,
2590        body: (Vec<u8>, bool),
2591        opts: CallOptions,
2592        cancel: Option<Arc<UnaryCancel>>,
2593    ) -> Result<CallReply, CallError> {
2594        let mut history = CallAttemptHistory {
2595            never_forwarded: true,
2596            sent: false,
2597        };
2598        self.call_attempts(target, identity, body, opts, cancel, &mut history)
2599            .await
2600            .map_err(|err| {
2601                let err = if history.sent && matches!(err, CallError::StaleRouteHandle(_)) {
2602                    CallError::not_sent(err.to_string())
2603                } else {
2604                    err
2605                };
2606                err.with_never_forwarded(history.never_forwarded)
2607            })
2608    }
2609
2610    async fn call_attempts(
2611        &self,
2612        target: RouteTarget,
2613        identity: BindIdentity,
2614        body: (Vec<u8>, bool),
2615        opts: CallOptions,
2616        cancel: Option<Arc<UnaryCancel>>,
2617        history: &mut CallAttemptHistory,
2618    ) -> Result<CallReply, CallError> {
2619        let (body, binary) = body;
2620        let call_deadline = Instant::now() + opts.timeout;
2621        // Preserve the single resend policy even for older daemons whose
2622        // unmarked refusals cannot prove that the module never saw the request.
2623        let mut resent_after_unsent_refusal = false;
2624        let consumer_identity = self.shared.route_open_consumer_identity(&opts)?;
2625        let consumer_capabilities = route_open_consumer_capabilities(&opts);
2626        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
2627        let route_key = RouteKey::new(
2628            &target,
2629            &identity,
2630            consumer_identity.as_ref(),
2631            consumer_capabilities.as_deref(),
2632        )
2633        .with_role_versions(role_versions.as_ref())
2634        .with_scope(opts.scope.as_ref());
2635
2636        let route_open = RouteOpenParams {
2637            target: &target,
2638            identity: &identity,
2639            consumer_identity: &consumer_identity,
2640            consumer_capabilities: &consumer_capabilities,
2641            role_versions: &role_versions,
2642            reverse_requests: &opts.reverse_requests,
2643            scope: opts.scope.as_ref(),
2644        };
2645
2646        let mut busy_permit: Option<Arc<RoutePermit>> = None;
2647        let mut busy_delay = Duration::from_millis(25);
2648        loop {
2649            let route = self
2650                .shared
2651                .ensure_route(&route_key, &route_open, &opts, call_deadline)
2652                .await
2653                .map_err(request_not_sent_after_route_open_failure)?;
2654            if busy_permit
2655                .as_ref()
2656                .is_some_and(|permit| !permit.belongs_to(&route))
2657            {
2658                busy_permit.take();
2659            }
2660            let permit = match busy_permit.take() {
2661                Some(permit) => permit,
2662                None => route
2663                    .acquire(false, call_deadline, cancel.as_ref())
2664                    .await
2665                    .map_err(|err| {
2666                        if matches!(err, CallError::StaleRouteHandle(_)) {
2667                            self.shared.route_not_sent_error(route.handle)
2668                        } else {
2669                            err
2670                        }
2671                    })?,
2672            };
2673
2674            if !self.shared.route_is_current(&route_key, &route) {
2675                drop(permit);
2676                self.shared
2677                    .sleep_until_retry(call_deadline, opts.route_retry.base)
2678                    .await?;
2679                continue;
2680            }
2681
2682            // Snapshot trust for the route's generation before awaiting its reply;
2683            // a reconnect must not lend a newer daemon's guarantees to an old frame.
2684            let daemon_origin_trusted = {
2685                let inner = self.shared.lock_inner();
2686                inner.generation == route.handle.connection_token() && inner.daemon_origin_trusted
2687            };
2688            let response = self
2689                .shared
2690                .send_request_with_slot(
2691                    RequestSend {
2692                        expected_handle: Some(route.handle),
2693                        channel: route.handle.channel,
2694                        epoch: route.handle.epoch,
2695                        body: body.clone(),
2696                        binary,
2697                        priority: opts.priority,
2698                        admission_class: opts.admission_class,
2699                        deadline: call_deadline,
2700                        retain_late_route_open: false,
2701                        route_open_reverse_requests: None,
2702                    },
2703                    cancel.clone(),
2704                    Some(Arc::clone(&permit)),
2705                )
2706                .await;
2707
2708            history.sent |= response.is_ok();
2709            let proven_undelivered = match &response {
2710                Ok(TerminalFrame::Error { body, flags }) => {
2711                    is_refusal_on_route(daemon_origin_trusted, *flags, &body.code, route.opted_in)
2712                }
2713                Err(err) => {
2714                    err.never_forwarded() == Some(true)
2715                        || matches!(err, CallError::StaleRouteHandle(_))
2716                }
2717                _ => false,
2718            };
2719            history.never_forwarded &= proven_undelivered;
2720
2721            match response {
2722                Ok(TerminalFrame::Response { body, flags, .. }) => {
2723                    return Ok(CallReply {
2724                        body,
2725                        binary: flags.is_binary(),
2726                    });
2727                }
2728                Ok(TerminalFrame::StreamEnd) => {
2729                    return Ok(CallReply {
2730                        body: Vec::new(),
2731                        binary: false,
2732                    });
2733                }
2734                Ok(TerminalFrame::Error { body, flags })
2735                    if error_codes::is_route_busy_retryable(flags, &body.code, route.opted_in) =>
2736                {
2737                    if !self
2738                        .shared
2739                        .busy_backoff(call_deadline, busy_delay, cancel.as_ref())
2740                        .await
2741                    {
2742                        return Err(busy_error(&body));
2743                    }
2744                    busy_delay = (busy_delay * 2).min(Duration::from_secs(1));
2745                    busy_permit = Some(permit);
2746                    continue;
2747                }
2748                // Route-dead and drain refusals share one eviction/resend budget.
2749                // Only a trusted daemon-origin flag proves non-delivery; the retry
2750                // policy itself stays compatible with older daemons.
2751                Ok(TerminalFrame::Error { body, flags })
2752                    if (error_codes::is_established_route_dead(flags, &body.code)
2753                        || is_data_plane_drain_refusal(&body.code))
2754                        && !resent_after_unsent_refusal
2755                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested())
2756                        && Instant::now() < call_deadline =>
2757                {
2758                    resent_after_unsent_refusal = true;
2759                    self.shared.invalidate_route(&route_key, Some(route.handle));
2760                    continue;
2761                }
2762                Ok(TerminalFrame::Error { body, flags })
2763                    if is_daemon_refusal_before_forward(
2764                        daemon_origin_trusted,
2765                        flags,
2766                        &body.code,
2767                    ) =>
2768                {
2769                    return Err(CallError::not_sent_with_cause(
2770                        format!(
2771                            "daemon refused before forwarding: {} ({})",
2772                            body.code, body.message
2773                        ),
2774                        NotSentCause::DaemonRefusedBeforeForward { code: body.code },
2775                    ));
2776                }
2777                Ok(TerminalFrame::Error { body, flags }) => {
2778                    return Err(CallError::from_established_route_error(flags, body));
2779                }
2780                Err(err)
2781                    if err.is_not_sent()
2782                        && Instant::now() < call_deadline
2783                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested()) =>
2784                {
2785                    self.shared.invalidate_route(&route_key, Some(route.handle));
2786                    self.shared.ensure_connected_for_call(call_deadline).await?;
2787                    continue;
2788                }
2789                Err(err)
2790                    if err.outcome_cause() == Some(OutcomeUnknownCause::Deadline)
2791                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested()) =>
2792                {
2793                    self.shared.invalidate_route_with_deadline(
2794                        &route_key,
2795                        Some(route.handle),
2796                        true,
2797                    );
2798                    return Err(err);
2799                }
2800                Err(err) => return Err(err),
2801            }
2802        }
2803    }
2804
2805    /// Open a held-open subscription on a managed route.
2806    ///
2807    /// This opens or reuses the same `(target, identity, consumer_identity, consumer_capabilities, role_versions, scope)` route as
2808    /// [`SubcConsumer::call`], sends one Request that the provider keeps open, and
2809    /// returns a [`Subscription`] whose event receiver yields each matching
2810    /// `StreamData` payload. The request holds one route flow-control permit until
2811    /// `StreamEnd`, an Error frame, route teardown or connection loss. On negotiated
2812    /// routes, local backpressure and unsubscribe keep credit until a wire terminal.
2813    /// Reconnects reject the
2814    /// subscription; callers that need durable replay should resubscribe with their
2815    /// own cursor after observing the failure.
2816    pub async fn subscribe(
2817        &self,
2818        target: RouteTarget,
2819        identity: BindIdentity,
2820        body: Vec<u8>,
2821        opts: SubscribeOptions,
2822    ) -> Result<Subscription, CallError> {
2823        let open_deadline = Instant::now() + opts.route_open_timeout;
2824        let route_opts = CallOptions {
2825            scope: opts.scope.clone(),
2826            timeout: opts.route_open_timeout,
2827            priority: opts.priority,
2828            admission_class: opts.admission_class,
2829            route_retry: opts.route_retry,
2830            route_retry_deadline: opts.route_retry_deadline,
2831            consumer_identity: opts.consumer_identity.clone(),
2832            reverse_requests: opts.reverse_requests.clone(),
2833            role_versions: opts.role_versions.clone(),
2834        };
2835        let consumer_identity = self.shared.route_open_consumer_identity(&route_opts)?;
2836        let consumer_capabilities = route_open_consumer_capabilities(&route_opts);
2837        let role_versions = route_open_role_versions(route_opts.role_versions.as_ref());
2838        let route_key = RouteKey::new(
2839            &target,
2840            &identity,
2841            consumer_identity.as_ref(),
2842            consumer_capabilities.as_deref(),
2843        )
2844        .with_role_versions(role_versions.as_ref())
2845        .with_scope(opts.scope.as_ref());
2846
2847        let route_open = RouteOpenParams {
2848            target: &target,
2849            identity: &identity,
2850            consumer_identity: &consumer_identity,
2851            consumer_capabilities: &consumer_capabilities,
2852            role_versions: &role_versions,
2853            reverse_requests: &opts.reverse_requests,
2854            scope: opts.scope.as_ref(),
2855        };
2856
2857        loop {
2858            let route = self
2859                .shared
2860                .ensure_route(&route_key, &route_open, &route_opts, open_deadline)
2861                .await
2862                .map_err(request_not_sent_after_route_open_failure)?;
2863            let permit = route
2864                .acquire(true, open_deadline, None)
2865                .await
2866                .map_err(|err| {
2867                    if matches!(err, CallError::StaleRouteHandle(_)) {
2868                        self.shared.route_not_sent_error(route.handle)
2869                    } else {
2870                        err
2871                    }
2872                })?;
2873
2874            if !self.shared.route_is_current(&route_key, &route) {
2875                drop(permit);
2876                self.shared
2877                    .sleep_until_retry(open_deadline, opts.route_retry.base)
2878                    .await?;
2879                continue;
2880            }
2881
2882            match self
2883                .shared
2884                .send_subscription(SubscriptionSend {
2885                    expected_handle: Some(route.handle),
2886                    channel: route.handle.channel,
2887                    epoch: route.handle.epoch,
2888                    body: body.clone(),
2889                    priority: opts.priority,
2890                    admission_class: opts.admission_class,
2891                    event_buffer: opts.event_buffer,
2892                    deadline: open_deadline,
2893                    permit,
2894                })
2895                .await
2896            {
2897                Ok(subscription) => return Ok(subscription),
2898                Err(err) if err.is_not_sent() && Instant::now() < open_deadline => {
2899                    self.shared.invalidate_route(&route_key, Some(route.handle));
2900                    self.shared.ensure_connected_for_call(open_deadline).await?;
2901                    continue;
2902                }
2903                Err(err) => return Err(err),
2904            }
2905        }
2906    }
2907
2908    /// Tear down ONE route, keyed by its route-open identity tuple — the parity of the TS
2909    /// client's `closeRoute`. For a long-lived consumer that opens unbounded distinct
2910    /// routes (one per session), this releases a route on session-end without dropping
2911    /// the whole consumer: it drops the cached route, settles in-flight requests on it
2912    /// at-most-once (OutcomeUnknown if already sent, NotSent otherwise), and queues a
2913    /// route GOODBYE so the daemon releases it and notifies the module. When closing
2914    /// a cached route returns, its GOODBYE is queued ahead of any frame sent later on
2915    /// this connection, so the caller may release its per-route budget. If the
2916    /// connection died instead, the daemon releases all its routes on disconnect.
2917    /// `opts.scope` selects only that scope's cache entry; `None` selects only
2918    /// the unscoped entry. Calls and subscriptions use the same route cache.
2919    ///
2920    /// Idempotent: a no-op if the route was never opened or is already closed (callers
2921    /// over-call on session-end). NOT a permanent tombstone — a later `call()` for the
2922    /// same key opens a fresh route. The close-beats-reopen guard ensures a close that
2923    /// races an in-flight route.open WINS (the opened channel is GOODBYE'd, not cached).
2924    ///
2925    /// # Cancel safety
2926    /// Once the cached route is removed, dropping this future abandons any drain
2927    /// wait but still settles pending requests and queues its GOODBYE in the
2928    /// background. The handle stays installed until GOODBYE is queued, unless the
2929    /// connection dies. Cancellation does not queue a second GOODBYE if the close
2930    /// already completed.
2931    pub async fn close_route(
2932        &self,
2933        target: RouteTarget,
2934        identity: BindIdentity,
2935        opts: CloseRouteOptions,
2936    ) {
2937        let Ok(consumer_identity) = self.shared.close_route_consumer_identity(&opts) else {
2938            return;
2939        };
2940        let consumer_capabilities = close_route_consumer_capabilities(&opts);
2941        let key = RouteKey::new(
2942            &target,
2943            &identity,
2944            consumer_identity.as_ref(),
2945            consumer_capabilities.as_deref(),
2946        )
2947        .with_role_versions(route_open_role_versions(opts.role_versions.as_ref()).as_ref())
2948        .with_scope(opts.scope.as_ref());
2949        self.shared.close_route(&key, &opts).await;
2950    }
2951
2952    /// Close exactly this route handle. A stale connection token fails locally and emits no frame.
2953    /// `opts.scope` must be `None`: the handle already selects exactly one route.
2954    ///
2955    /// # Cancel safety
2956    /// After the handle is validated and its route removed, dropping this future
2957    /// abandons any drain wait but still settles pending requests and queues its
2958    /// GOODBYE in the background. The handle is uninstalled after queueing, or when
2959    /// the connection dies; a completed close never queues a second GOODBYE on drop.
2960    pub async fn close_handle(
2961        &self,
2962        handle: &RouteHandle,
2963        opts: CloseRouteOptions,
2964    ) -> Result<(), CallError> {
2965        if opts.scope.is_some() {
2966            return Err(CallError::not_sent(
2967                "CloseRouteOptions.scope is not supported on close_handle; the handle already selects the route",
2968            ));
2969        }
2970        self.shared.close_handle(*handle, &opts).await
2971    }
2972
2973    /// Current transport epoch: 1 on initial connect, then +1 per successful reconnect.
2974    pub fn current_epoch(&self) -> u64 {
2975        self.shared.lock_inner().epoch
2976    }
2977
2978    pub(crate) fn pool_reusable(&self) -> bool {
2979        !self.shared.close_token.is_cancelled()
2980    }
2981
2982    /// Register a connection-state callback. Callbacks are best-effort observability hooks.
2983    pub fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
2984        self.shared
2985            .lock_inner()
2986            .callbacks
2987            .push(Arc::new(Mutex::new(Box::new(cb))));
2988    }
2989
2990    /// Close the consumer and settle every pending caller.
2991    pub async fn close(&self) {
2992        self.shared.close_sync("consumer closed");
2993        tokio::task::yield_now().await;
2994    }
2995}
2996
2997impl Drop for SubcConsumer {
2998    fn drop(&mut self) {
2999        self.shared.close_sync("consumer dropped");
3000    }
3001}
3002
3003/// Error returned by [`SubcConsumer`]'s TCP and local connection constructors.
3004#[derive(Debug)]
3005pub enum ConsumerError {
3006    Discovery {
3007        source: connection_file::DiscoveryError,
3008    },
3009    ConnectionFile {
3010        path: PathBuf,
3011        source: ConnectionFileError,
3012    },
3013    /// No endpoint for the requested transport. [`SubcConsumer::connect_local`]
3014    /// returns this when the connection file has no `local_endpoint`.
3015    NoEndpoint {
3016        path: PathBuf,
3017    },
3018    Connect {
3019        path: PathBuf,
3020        endpoint: String,
3021        source: io::Error,
3022    },
3023    Auth {
3024        path: PathBuf,
3025        endpoint: String,
3026        source: AuthError,
3027    },
3028    Closed,
3029}
3030
3031impl ConsumerError {
3032    pub(crate) fn claim(error: crate::ClaimError) -> Self {
3033        Self::Connect {
3034            path: PathBuf::new(),
3035            endpoint: "claim binding".into(),
3036            source: io::Error::other(error),
3037        }
3038    }
3039}
3040
3041impl fmt::Display for ConsumerError {
3042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3043        match self {
3044            Self::Discovery { source } => source.fmt(f),
3045            Self::ConnectionFile { path, source } => write!(
3046                f,
3047                "failed to read subc connection file '{}': {source}",
3048                path.display()
3049            ),
3050            Self::NoEndpoint { path } => {
3051                write!(
3052                    f,
3053                    "subc connection file '{}' has no endpoint for the requested transport",
3054                    path.display()
3055                )
3056            }
3057            Self::Connect {
3058                path,
3059                endpoint,
3060                source,
3061            } => write!(
3062                f,
3063                "failed to connect to subc endpoint {endpoint} from '{}': {source}",
3064                path.display()
3065            ),
3066            Self::Auth {
3067                path,
3068                endpoint,
3069                source,
3070            } => write!(
3071                f,
3072                "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
3073                path.display()
3074            ),
3075            Self::Closed => write!(f, "consumer closed"),
3076        }
3077    }
3078}
3079
3080impl Error for ConsumerError {
3081    fn source(&self) -> Option<&(dyn Error + 'static)> {
3082        match self {
3083            Self::Discovery { source } => Some(source),
3084            Self::ConnectionFile { source, .. } => Some(source),
3085            Self::Connect { source, .. } => Some(source),
3086            Self::Auth { source, .. } => Some(source),
3087            Self::NoEndpoint { .. } | Self::Closed => None,
3088        }
3089    }
3090}
3091
3092/// Why a sent request has no observed terminal response.
3093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3094#[non_exhaustive]
3095pub enum OutcomeUnknownCause {
3096    /// The reply deadline elapsed after the request was sent.
3097    Deadline,
3098    /// The connection's writer closed or failed after send.
3099    WriterClosed,
3100    /// The caller closed the consumer while a request was pending.
3101    ConsumerClosed,
3102    /// The daemon connection failed or dropped.
3103    ConnectionFailed,
3104    /// The route ended; [`CallError::close_reason`] gives its reason.
3105    RouteEnded,
3106    /// An internal completion channel dropped or an unexpected completion arrived.
3107    CompletionFailed,
3108}
3109
3110#[derive(Debug, Clone)]
3111struct OutcomeUnknownSource {
3112    message: String,
3113    cause: OutcomeUnknownCause,
3114    route_reason: Option<RouteEnd>,
3115}
3116
3117impl fmt::Display for OutcomeUnknownSource {
3118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3119        f.write_str(&self.message)
3120    }
3121}
3122impl Error for OutcomeUnknownSource {}
3123
3124/// Why an attempt was classified as [`CallError::NotSent`]. For resend safety
3125/// across all attempts, also check [`CallError::never_forwarded`].
3126#[derive(Debug, Clone, PartialEq, Eq)]
3127#[non_exhaustive]
3128pub enum NotSentCause {
3129    /// The daemon or module refused route.open before the data request.
3130    RouteOpenRefused { code: String },
3131    /// Route opening ended without a usable answer, including cancellation.
3132    RouteOpenAbandoned,
3133    /// Local validation, connection state or flow control prevented queueing.
3134    BeforeQueue,
3135    /// The deadline elapsed waiting for the writer's cancel-safe queue send.
3136    WriterCapacity,
3137    /// The writer did not accept the request for transmission.
3138    WriterRejected,
3139    /// A control response could not be decoded or had an unexpected shape.
3140    InvalidResponse,
3141    /// No longer produced: since 0.34.2 a dropped completion channel, which
3142    /// can't prove non-delivery, is reported as [`CallError::OutcomeUnknown`]
3143    /// with [`OutcomeUnknownCause::CompletionFailed`]. Kept so existing
3144    /// matches still compile.
3145    CompletionFailed,
3146    /// A daemon-marked data-plane refusal proved this attempt was not forwarded.
3147    DaemonRefusedBeforeForward { code: String },
3148}
3149
3150#[derive(Debug, Clone)]
3151struct NotSentSource {
3152    message: String,
3153    cause: NotSentCause,
3154    never_forwarded: bool,
3155    route_reason: Option<RouteEnd>,
3156    refusal: Option<Box<RouteOpenRefused>>,
3157}
3158
3159impl fmt::Display for NotSentSource {
3160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3161        f.write_str(&self.message)
3162    }
3163}
3164impl Error for NotSentSource {}
3165
3166/// Managed call or subscription failure.
3167#[derive(Debug)]
3168pub enum CallError {
3169    /// Local compatibility policy refusal: the version retained from the
3170    /// connection file for this connection is not an exact numeric
3171    /// `major.minor.patch` version at least 0.39.0. Unrecognized strings,
3172    /// including prereleases and build suffixes, are refused too. This
3173    /// route-open attempt was refused before being queued for writing.
3174    /// The handshake authenticates the daemon ID, not this version metadata.
3175    DaemonTooOld { daemon_ver: String },
3176    /// A pre-send failure, proven non-delivery, or unusable reply or internal completion.
3177    /// Check [`CallError::never_forwarded`] before treating the whole call as safe to resend.
3178    NotSent(Box<dyn Error + Send + Sync>),
3179    /// The request body was accepted by the writer path, but no terminal response was observed.
3180    OutcomeUnknown(Box<dyn Error + Send + Sync>),
3181    /// The target module handler returned an Error frame. Application-level rejections
3182    /// are returned as ordinary successful response bytes and do not produce this variant.
3183    Module(ErrorBody),
3184    /// An Error frame reported that the established route is no longer usable.
3185    RouteDead(Box<ErrorBody>),
3186    /// A subscription event receiver stopped keeping up with its bounded channel.
3187    ///
3188    /// The reader task must never await a slow consumer while it is dispatching frames
3189    /// for the whole connection, so a full event channel terminates only that subscription.
3190    SubscriptionBackpressure(Box<dyn Error + Send + Sync>),
3191    /// The handle belongs to an earlier connection and no frame was emitted.
3192    StaleRouteHandle(RouteHandle),
3193    /// No registered catalog entry claims the requested capability.
3194    CapabilityUnprovided { capability: String },
3195    /// More than one registered catalog entry claims a singularly requested capability.
3196    CapabilityAmbiguous {
3197        capability: String,
3198        claimants: Vec<String>,
3199    },
3200    /// The resolver rejected a malformed capability identifier before querying the daemon.
3201    InvalidCapabilityIdentifier { capability: String },
3202}
3203
3204impl CallError {
3205    /// Whether an Error frame reported that the established route is no longer usable.
3206    /// This classification does not establish whether an earlier attempt was delivered.
3207    pub fn is_route_dead(&self) -> bool {
3208        matches!(self, Self::RouteDead(_))
3209    }
3210
3211    /// A typed terminal scope bind-proof refusal, if the daemon returned one.
3212    pub fn scope_bind_proof_refusal(&self) -> Option<ScopeBindProofRefusal> {
3213        match self.route_open_refusal()?.code.as_str() {
3214            error_codes::SCOPE_BIND_PROOF_REQUIRED => Some(ScopeBindProofRefusal::Required),
3215            error_codes::SCOPE_BIND_PROOF_MISMATCH => Some(ScopeBindProofRefusal::Mismatch),
3216            _ => None,
3217        }
3218    }
3219
3220    /// Why the route ended. The error remains `NotSent` or `OutcomeUnknown`:
3221    /// this reason never makes a sent call safe to resend.
3222    pub fn close_reason(&self) -> Option<&RouteEndReason> {
3223        self.route_end().map(|end| &end.reason)
3224    }
3225
3226    fn route_end(&self) -> Option<&RouteEnd> {
3227        match self {
3228            Self::NotSent(source) => source
3229                .downcast_ref::<NotSentSource>()?
3230                .route_reason
3231                .as_ref(),
3232            Self::OutcomeUnknown(source) => source
3233                .downcast_ref::<OutcomeUnknownSource>()?
3234                .route_reason
3235                .as_ref(),
3236            _ => None,
3237        }
3238    }
3239
3240    /// The daemon's recovery verdict from `route.closed`, if it carried one.
3241    /// `Some(true)` means the daemon will leave the module down until an operator
3242    /// acts. `None` means unknown: older daemons, client-side ends and non-route
3243    /// errors have no verdict. This flag does not change resend safety or the
3244    /// close reason's reopen disposition.
3245    pub fn terminal(&self) -> Option<bool> {
3246        self.route_end()?.terminal
3247    }
3248
3249    /// Why the outcome is unknown, without parsing the error's message.
3250    /// Errors constructed outside this crate with an untyped source return `None`.
3251    pub fn outcome_cause(&self) -> Option<OutcomeUnknownCause> {
3252        match self {
3253            Self::OutcomeUnknown(source) => source
3254                .downcast_ref::<OutcomeUnknownSource>()
3255                .map(|source| source.cause),
3256            _ => None,
3257        }
3258    }
3259
3260    /// Why the final attempt was classified as `NotSent`, without parsing its message.
3261    /// Returns `None` for other variants and externally constructed untyped errors.
3262    pub fn not_sent_cause(&self) -> Option<NotSentCause> {
3263        match self {
3264            Self::NotSent(source) => source
3265                .downcast_ref::<NotSentSource>()
3266                .map(|source| source.cause.clone()),
3267            _ => None,
3268        }
3269    }
3270
3271    /// Whether no attempt of this call may have reached the module.
3272    ///
3273    /// `Some(false)` means this or an earlier attempt may have been forwarded.
3274    /// For data-plane errors, only daemon-marked refusals prove non-delivery;
3275    /// unmarked replies remain conservative on older daemons. Managed calls
3276    /// include every attempt. Returns `None` except for crate-built `NotSent` errors.
3277    pub fn never_forwarded(&self) -> Option<bool> {
3278        match self {
3279            Self::NotSent(source) => source
3280                .downcast_ref::<NotSentSource>()
3281                .map(|source| source.never_forwarded),
3282            _ => None,
3283        }
3284    }
3285
3286    /// Return the stable machine-readable code for typed errors.
3287    pub fn code(&self) -> Option<&str> {
3288        match self {
3289            Self::Module(body) => Some(&body.code),
3290            Self::RouteDead(body) => Some(&body.code),
3291            Self::DaemonTooOld { .. } => Some("daemon_too_old"),
3292            Self::CapabilityUnprovided { .. } => Some("capability_unprovided"),
3293            Self::CapabilityAmbiguous { .. } => Some("capability_ambiguous"),
3294            Self::InvalidCapabilityIdentifier { .. } => Some("invalid_capability_identifier"),
3295            Self::NotSent(source) => match &source.downcast_ref::<NotSentSource>()?.cause {
3296                NotSentCause::DaemonRefusedBeforeForward { code }
3297                    if code == error_codes::ROUTE_BUSY =>
3298                {
3299                    Some(code)
3300                }
3301                _ => None,
3302            },
3303            Self::OutcomeUnknown(_)
3304            | Self::SubscriptionBackpressure(_)
3305            | Self::StaleRouteHandle(_) => None,
3306        }
3307    }
3308
3309    fn not_sent(reason: impl Into<String>) -> Self {
3310        Self::not_sent_with_cause(reason, NotSentCause::BeforeQueue)
3311    }
3312
3313    fn not_sent_with_cause(reason: impl Into<String>, cause: NotSentCause) -> Self {
3314        Self::NotSent(Box::new(NotSentSource {
3315            message: reason.into(),
3316            cause,
3317            never_forwarded: true,
3318            route_reason: None,
3319            refusal: None,
3320        }))
3321    }
3322
3323    fn with_never_forwarded(mut self, never_forwarded: bool) -> Self {
3324        if let Self::NotSent(source) = &mut self {
3325            if let Some(source) = source.downcast_mut::<NotSentSource>() {
3326                source.never_forwarded &= never_forwarded;
3327            }
3328        }
3329        self
3330    }
3331
3332    fn invalid_response(reason: impl Into<String>) -> Self {
3333        Self::not_sent_with_cause(reason, NotSentCause::InvalidResponse).with_never_forwarded(false)
3334    }
3335
3336    fn outcome_unknown(reason: impl Into<String>, cause: OutcomeUnknownCause) -> Self {
3337        Self::outcome_unknown_source(OutcomeUnknownSource {
3338            message: reason.into(),
3339            cause,
3340            route_reason: None,
3341        })
3342    }
3343
3344    fn outcome_unknown_source(source: OutcomeUnknownSource) -> Self {
3345        Self::OutcomeUnknown(Box::new(source))
3346    }
3347
3348    fn is_not_sent(&self) -> bool {
3349        matches!(self, Self::NotSent(_))
3350    }
3351
3352    /// The daemon's refusal body when this failure is a route.open the daemon
3353    /// refused, with its `code`, `message` and machine-readable `detail`
3354    /// intact, for example `module_warming` with
3355    /// `detail.reason = "required_capability_unprovided"`.
3356    ///
3357    /// When retryable refusals ran out the route-retry deadline, this is the
3358    /// most informative refusal seen during the retries, so a caller can tell
3359    /// "the module was reloading" from "the connection failed". Refusals rank:
3360    /// `module_reloading` / `module_warming`, then `delegation_not_registered`,
3361    /// then admission pressure (too many binds in flight), then anything else;
3362    /// at equal rank the later one wins. The failure is still `NotSent`: a
3363    /// refused route.open never delivered the request.
3364    pub fn route_open_refusal(&self) -> Option<&ErrorBody> {
3365        match self {
3366            Self::NotSent(err) => err
3367                .downcast_ref::<NotSentSource>()
3368                .and_then(|source| source.refusal.as_ref())
3369                .map(|refused| &refused.body),
3370            _ => None,
3371        }
3372    }
3373
3374    fn subscription_backpressure(reason: impl Into<String>) -> Self {
3375        Self::SubscriptionBackpressure(Box::new(SimpleError(reason.into())))
3376    }
3377}
3378
3379impl fmt::Display for CallError {
3380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3381        match self {
3382            Self::DaemonTooOld { daemon_ver } => write!(
3383                f,
3384                "daemon_too_old: route.open requires daemon 0.39.0 or newer (connected version: {daemon_ver})"
3385            ),
3386            Self::NotSent(err) => write!(f, "request not sent: {err}"),
3387            Self::OutcomeUnknown(err) => write!(f, "request outcome unknown: {err}"),
3388            Self::Module(body) => write!(f, "module error {}: {}", body.code, body.message),
3389            Self::RouteDead(body) => write!(f, "route dead {}: {}", body.code, body.message),
3390            Self::SubscriptionBackpressure(err) => {
3391                write!(f, "subscription event channel backpressure: {err}")
3392            }
3393            Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
3394            Self::CapabilityUnprovided { capability } => {
3395                write!(
3396                    f,
3397                    "capability_unprovided: no catalog claimant for {capability}"
3398                )
3399            }
3400            Self::CapabilityAmbiguous {
3401                capability,
3402                claimants,
3403            } => write!(
3404                f,
3405                "capability_ambiguous: multiple catalog claimants for {capability}: {claimants:?}"
3406            ),
3407            Self::InvalidCapabilityIdentifier { capability } => write!(
3408                f,
3409                "invalid_capability_identifier: malformed capability identifier {capability:?}"
3410            ),
3411        }
3412    }
3413}
3414
3415impl Error for CallError {
3416    fn source(&self) -> Option<&(dyn Error + 'static)> {
3417        match self {
3418            Self::NotSent(err)
3419            | Self::OutcomeUnknown(err)
3420            | Self::SubscriptionBackpressure(err) => Some(err.as_ref()),
3421            Self::Module(_)
3422            | Self::RouteDead(_)
3423            | Self::DaemonTooOld { .. }
3424            | Self::StaleRouteHandle(_)
3425            | Self::CapabilityUnprovided { .. }
3426            | Self::CapabilityAmbiguous { .. }
3427            | Self::InvalidCapabilityIdentifier { .. } => None,
3428        }
3429    }
3430}
3431
3432/// A route.open the daemon refused, kept typed inside [`CallError::NotSent`]
3433/// so the refusal's code and `detail` survive. Read it through
3434/// [`CallError::route_open_refusal`].
3435#[derive(Debug, Clone)]
3436struct RouteOpenRefused {
3437    target: String,
3438    body: ErrorBody,
3439    /// The last refusal of a retry loop, when it is not `body`: kept so the
3440    /// message still says what the daemon answered most recently.
3441    most_recent: Option<ErrorBody>,
3442}
3443
3444/// Terminal refusals requiring the caller to supply the scope's current proof.
3445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3446#[non_exhaustive]
3447pub enum ScopeBindProofRefusal {
3448    Required,
3449    Mismatch,
3450}
3451
3452impl fmt::Display for RouteOpenRefused {
3453    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3454        write!(
3455            f,
3456            "route.open failed for target {}: {}",
3457            self.target,
3458            DescribeRefusal(&self.body)
3459        )?;
3460        if let Some(most_recent) = &self.most_recent {
3461            write!(
3462                f,
3463                "; the most recent refusal was {}",
3464                DescribeRefusal(most_recent)
3465            )?;
3466        }
3467        Ok(())
3468    }
3469}
3470
3471impl Error for RouteOpenRefused {}
3472
3473/// A refusal as `code (reason r) (message)`, the reason read from
3474/// `detail.reason` and omitted when the daemon sent none.
3475struct DescribeRefusal<'a>(&'a ErrorBody);
3476
3477impl fmt::Display for DescribeRefusal<'_> {
3478    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3479        write!(f, "{}", self.0.code)?;
3480        if let Some(reason) = refusal_reason(self.0) {
3481            write!(f, " (reason {reason})")?;
3482        }
3483        write!(f, " ({})", self.0.message)
3484    }
3485}
3486
3487fn refusal_reason(body: &ErrorBody) -> Option<&str> {
3488    body.detail.as_ref()?.get("reason")?.as_str()
3489}
3490
3491/// The daemon's reasons for refusing a route.open because too many binds are
3492/// already in flight, on the consumer's connection or towards the target module
3493/// (`crates/subc-daemon/src/control/route_open.rs`, `route_open_capacity_refusal`
3494/// and `route_open_target_capacity_refusal`). Both are sent as `target_unavailable`.
3495const ADMISSION_PRESSURE_REASONS: [&str; 2] = ["open_admission_full", "target_binds_full"];
3496/// Markers in the messages of those same admission-pressure refusals. The
3497/// daemon currently logs the reason but leaves it out of the refusal's detail,
3498/// so the message is the only way to recognise them.
3499const ADMISSION_PRESSURE_MESSAGES: [&str; 2] =
3500    ["route.open binds in flight", "route.bind relays in flight"];
3501
3502/// How much a route.open refusal says about why the target was unreachable,
3503/// highest first: the module was changing state (reloading or warming); a
3504/// delegation was not registered; admission pressure; anything else.
3505fn route_open_refusal_rank(body: &ErrorBody) -> u8 {
3506    if body.code == error_codes::MODULE_RELOADING || body.code == error_codes::MODULE_WARMING {
3507        return 3;
3508    }
3509    let reason = refusal_reason(body);
3510    if body.code == "delegation_not_registered" || reason == Some("delegation_not_registered") {
3511        return 2;
3512    }
3513    if body.code == error_codes::TARGET_UNAVAILABLE {
3514        let admission_pressure = match reason {
3515            Some(reason) => ADMISSION_PRESSURE_REASONS.contains(&reason),
3516            None => ADMISSION_PRESSURE_MESSAGES
3517                .iter()
3518                .any(|marker| body.message.contains(marker)),
3519        };
3520        if admission_pressure {
3521            return 1;
3522        }
3523    }
3524    0
3525}
3526
3527/// The route.open refusals one retry loop has seen. When the deadline runs out,
3528/// the error is built from the best-ranked one: after a module restart the most
3529/// recent refusal is often admission pressure ("8 binds in flight"), which
3530/// points a reader at the consumer's concurrency when the module was simply down.
3531#[derive(Default)]
3532struct RouteOpenRefusals {
3533    best: Option<ErrorBody>,
3534    /// Set only while the latest refusal ranked below `best`.
3535    most_recent: Option<ErrorBody>,
3536}
3537
3538impl RouteOpenRefusals {
3539    fn record(&mut self, body: ErrorBody) {
3540        // At equal rank the newer refusal wins: it describes the target's latest state.
3541        let outranks = self
3542            .best
3543            .as_ref()
3544            .is_none_or(|best| route_open_refusal_rank(&body) >= route_open_refusal_rank(best));
3545        if outranks {
3546            self.best = Some(body);
3547            self.most_recent = None;
3548        } else {
3549            self.most_recent = Some(body);
3550        }
3551    }
3552
3553    fn into_error(self, target: String) -> Option<CallError> {
3554        let body = self.best?;
3555        Some(CallError::from_route_open_refusal(RouteOpenRefused {
3556            target,
3557            body,
3558            most_recent: self.most_recent,
3559        }))
3560    }
3561}
3562
3563/// The label a route.open refusal names its target by, the same spelling the
3564/// managed route cache uses.
3565fn route_target_label(target: &RouteTarget) -> String {
3566    match target {
3567        RouteTarget::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
3568        RouteTarget::ManagementSurface { module_id } => format!("management_surface:{module_id}"),
3569        RouteTarget::InternalService {
3570            module_id,
3571            service_id,
3572        } => format!("internal_service:{module_id}:{service_id}"),
3573    }
3574}
3575
3576impl CallError {
3577    fn route_open_refused(target: String, body: ErrorBody) -> Self {
3578        Self::from_route_open_refusal(RouteOpenRefused {
3579            target,
3580            body,
3581            most_recent: None,
3582        })
3583    }
3584
3585    fn from_route_open_refusal(refusal: RouteOpenRefused) -> Self {
3586        Self::NotSent(Box::new(NotSentSource {
3587            message: refusal.to_string(),
3588            cause: NotSentCause::RouteOpenRefused {
3589                code: refusal.body.code.clone(),
3590            },
3591            never_forwarded: true,
3592            route_reason: None,
3593            refusal: Some(Box::new(refusal)),
3594        }))
3595    }
3596}
3597
3598#[derive(Debug)]
3599struct SimpleError(String);
3600
3601impl fmt::Display for SimpleError {
3602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3603        f.write_str(&self.0)
3604    }
3605}
3606
3607impl Error for SimpleError {}
3608
3609type Callback = Arc<Mutex<Box<dyn Fn(ConnectionState) + Send + 'static>>>;
3610
3611type OpeningWaiter = oneshot::Sender<Result<RouteState, SharedCallFailure>>;
3612
3613/// An in-flight route.open for one key: the waiters parked behind the lead opener,
3614/// plus a `closed` flag a concurrent `close_route` flips so the lead opener refuses
3615/// to install its channel (the close-beats-reopen guard). The flag lives here, with
3616/// the in-flight open, so it vanishes when the open finishes — no lingering per-key
3617/// state to leak for a long-lived consumer with unbounded distinct routes.
3618struct Opening {
3619    waiters: Vec<OpeningWaiter>,
3620    closed: bool,
3621}
3622
3623struct Shared {
3624    claim_bound: bool,
3625    connection_file: PathBuf,
3626    operator_app_candidates: Option<Vec<PathBuf>>,
3627    opts: ConsumerOptions,
3628    transport: ConsumerTransport,
3629    identity_from_environment: bool,
3630    inner: Mutex<Inner>,
3631    notify: Notify,
3632    #[cfg(test)]
3633    before_wait: Mutex<Option<Box<dyn FnOnce() + Send>>>,
3634    close_token: CancellationToken,
3635    /// Epoch milliseconds of the last frame dispatched from the current connection.
3636    /// The liveness probe reads this to distinguish a healthy slow request from a
3637    /// socket that has silently stopped delivering inbound traffic.
3638    last_inbound_ms: AtomicU64,
3639    /// Only one deadline-triggered liveness probe may be active across generations.
3640    liveness_probe_running: AtomicBool,
3641    pushes_dropped_no_receiver: AtomicU64,
3642    /// Always-present drop counter for channel-0 control pushes (no receiver,
3643    /// receiver full/closed, or unparseable body). Before this surface existed
3644    /// the drop was SILENT -- not even a counter -- which is how #31's push
3645    /// family shipped unreachable to every Rust consumer (issue #35).
3646    control_pushes_dropped: AtomicU64,
3647    /// Pushes dropped because a registered receiver's bounded buffer was full
3648    /// at delivery time. Distinct from `pushes_dropped_no_receiver` because the
3649    /// operator remedies differ: full means the consumer is too slow (widen the
3650    /// buffer or drain faster), no-receiver means it never subscribed.
3651    pushes_dropped_receiver_full: AtomicU64,
3652    /// Random source in [0, 1) for retry jitter. Tests replace it with a seeded
3653    /// one so jittered delays are reproducible.
3654    random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
3655    /// One permit per route.open the consumer may have outstanding; see
3656    /// [`MAX_ROUTE_OPENS_IN_FLIGHT`]. tokio's semaphore grants permits in
3657    /// request order, which makes the wait first come first served. The consumer
3658    /// holds one connection at a time and a dropped connection fails every open
3659    /// in flight on it, so one semaphore is a per-connection limit.
3660    route_open_slots: Semaphore,
3661    // Serialize the first description lookup, not ordinary opens. The cached
3662    // result belongs to Inner's generation and is reset on reconnect.
3663    route_description: tokio::sync::Mutex<()>,
3664}
3665
3666struct Inner {
3667    generation: u64,
3668    daemon_origin_trusted: bool,
3669    daemon_ver: String,
3670    accepts_close_reasons: Option<bool>,
3671    epoch: u64,
3672    next_corr: Option<u64>,
3673    writer: Option<mpsc::Sender<WriteCommand>>,
3674    pending: HashMap<PendingKey, PendingEntry>,
3675    wire_slots: HashMap<PendingKey, Arc<RoutePermit>>,
3676    routes: HashMap<RouteKey, RouteState>,
3677    route_by_channel: HashMap<u16, RouteKey>,
3678    one_shot_routes: HashMap<u16, RouteState>,
3679    route_epochs: HashMap<u16, RouteHandle>,
3680    route_targets: HashMap<RouteHandle, RouteOpenTarget>,
3681    retired_routes: HashSet<RouteHandle>,
3682    retirement_goodbyes: HashSet<RouteHandle>,
3683    retirement_queue: VecDeque<RouteHandle>,
3684    retirement_notify: Arc<Notify>,
3685    retirement_task: Option<JoinHandle<()>>,
3686    route_modules: HashMap<u16, String>,
3687    route_end_reasons: HashMap<u16, (RouteEnd, bool)>,
3688    legacy_channel_reasons: HashMap<u16, RouteEnd>,
3689    push_event_receivers: HashMap<RouteHandle, mpsc::Sender<PushEvent>>,
3690    /// Consumer-level receiver for daemon-originated channel-0 control pushes
3691    /// (`route.closing`, `route.closed`, future ops). Connection-independent:
3692    /// control pushes are advisory daemon events, so the receiver survives
3693    /// reconnects rather than being keyed by generation.
3694    control_push_receiver: Option<mpsc::Sender<ControlPush>>,
3695    dropped_route_frames: u64,
3696    openings: HashMap<RouteKey, Opening>,
3697    callbacks: Vec<Callback>,
3698    closed: bool,
3699    reconnect: ReconnectState,
3700    restored_token: u64,
3701    reader_task: Option<JoinHandle<()>>,
3702    writer_task: Option<JoinHandle<()>>,
3703}
3704
3705impl Inner {
3706    fn record_route_end(&mut self, push: &ControlPush) {
3707        let Some(reason) = push.route_close_reason() else {
3708            return;
3709        };
3710        let end = RouteEnd {
3711            reason: RouteEndReason::Daemon(reason),
3712            terminal: (push.op == "route.closed")
3713                .then(|| {
3714                    push.body
3715                        .get("terminal")
3716                        .and_then(serde_json::Value::as_bool)
3717                })
3718                .flatten(),
3719        };
3720        if let Some(channels) = push.body.get("channels") {
3721            if let Some(channels) = channels.as_array() {
3722                for channel in channels
3723                    .iter()
3724                    .filter_map(|v| v.as_u64().and_then(|v| u16::try_from(v).ok()))
3725                {
3726                    let final_reason = push.op == "route.closed";
3727                    if final_reason
3728                        || !self
3729                            .route_end_reasons
3730                            .get(&channel)
3731                            .is_some_and(|(_, final_reason)| *final_reason)
3732                    {
3733                        self.route_end_reasons
3734                            .insert(channel, (end.clone(), final_reason));
3735                    }
3736                }
3737            }
3738        } else if let Some(module) = push.body.get("module_id").and_then(|v| v.as_str()) {
3739            for (&channel, target) in &self.route_modules {
3740                if target == module {
3741                    self.legacy_channel_reasons.insert(channel, end.clone());
3742                }
3743            }
3744        }
3745    }
3746
3747    fn route_end(&self, channel: u16) -> RouteEnd {
3748        self.route_end_reasons
3749            .get(&channel)
3750            .map(|(reason, _)| reason.clone())
3751            .or_else(|| self.legacy_channel_reasons.get(&channel).cloned())
3752            .unwrap_or_else(|| RouteEndReason::Unknown.into())
3753    }
3754
3755    #[cfg(test)]
3756    fn route_end_reason(&self, channel: u16) -> RouteEndReason {
3757        self.route_end(channel).reason
3758    }
3759
3760    fn cache_route(&mut self, key: RouteKey, route: RouteState) -> RouteState {
3761        let cached = self.routes.entry(key.clone()).or_insert(route).clone();
3762        let previous = self
3763            .route_by_channel
3764            .insert(cached.handle.channel, key.clone());
3765        debug_assert!(previous.as_ref().is_none_or(|previous| previous == &key));
3766        self.route_epochs
3767            .insert(cached.handle.channel, cached.handle);
3768        cached
3769    }
3770
3771    fn remove_route(&mut self, key: &RouteKey) -> Option<RouteState> {
3772        let route = self.evict_route(key)?;
3773        release_reverse_request_registry(route.handle);
3774        Some(route)
3775    }
3776
3777    fn evict_route(&mut self, key: &RouteKey) -> Option<RouteState> {
3778        let route = self.routes.remove(key)?;
3779        let indexed = self.route_by_channel.remove(&route.handle.channel);
3780        debug_assert_eq!(indexed.as_ref(), Some(key));
3781        Some(route)
3782    }
3783
3784    fn reap_retired_route(&mut self, handle: RouteHandle) {
3785        // A caller may be gone while its written correlation still owns credit.
3786        // Keep ingress for those tombstones as well as live pending callers.
3787        if !self.retired_routes.contains(&handle)
3788            || self
3789                .pending
3790                .keys()
3791                .chain(self.wire_slots.keys())
3792                .any(|key| {
3793                    key.generation == handle.connection_token()
3794                        && key.channel == handle.channel
3795                        && key.epoch == handle.epoch
3796                })
3797        {
3798            return;
3799        }
3800        // Pending keys carry only the wire identity. Use the retained handle
3801        // when releasing its reverse-request registry after retirement.
3802        let handle = *self
3803            .retired_routes
3804            .get(&handle)
3805            .expect("retired route exists");
3806        if self.retirement_goodbyes.contains(&handle) {
3807            if !self.queue_retirement_goodbye(handle) {
3808                // Keep the ingress handle occupied until the flusher queues the
3809                // GOODBYE, so a reopened route cannot take this channel first.
3810                return;
3811            }
3812            self.retirement_goodbyes.remove(&handle);
3813        }
3814        self.retired_routes.remove(&handle);
3815        if self.route_epochs.get(&handle.channel) == Some(&handle) {
3816            self.route_epochs.remove(&handle.channel);
3817            self.route_targets.remove(&handle);
3818            self.push_event_receivers.remove(&handle);
3819        }
3820        release_reverse_request_registry(handle);
3821    }
3822
3823    fn queue_retirement_goodbye(&mut self, handle: RouteHandle) -> bool {
3824        if self.generation != handle.connection_token()
3825            || self.route_epochs.get(&handle.channel) != Some(&handle)
3826            || self.writer.is_none()
3827        {
3828            return true;
3829        }
3830        if self.retirement_queue.is_empty() {
3831            let frame = Frame::build(
3832                FrameType::Goodbye,
3833                Flags::new(false, Priority::Interactive, false),
3834                handle.channel,
3835                handle.epoch,
3836                0,
3837                Vec::new(),
3838            )
3839            .expect("header-only route GOODBYE is valid");
3840            if self
3841                .writer
3842                .as_ref()
3843                .unwrap()
3844                .try_send(WriteCommand {
3845                    frame,
3846                    pending: None,
3847                })
3848                .is_ok()
3849            {
3850                return true;
3851            }
3852        }
3853        // Once one retirement is waiting, later retirements join the same FIFO
3854        // rather than overtaking it through the synchronous fast path.
3855        if !self.retirement_queue.contains(&handle) {
3856            self.retirement_queue.push_back(handle);
3857        }
3858        self.retirement_notify.notify_one();
3859        false
3860    }
3861
3862    fn remove_pending(&mut self, key: &PendingKey) -> Option<PendingEntry> {
3863        let entry = self.pending.remove(key);
3864        if entry.as_ref().is_some_and(|entry| !entry.accepted) {
3865            if let Some(slot) = self.wire_slots.remove(key) {
3866                slot.release();
3867            }
3868        }
3869        self.reap_retired_route(RouteHandle::new(key.channel, key.epoch, key.generation));
3870        entry
3871    }
3872
3873    fn release_wire_slots(&mut self, handle: RouteHandle) {
3874        self.wire_slots.retain(|key, slot| {
3875            let keep = key.generation != handle.connection_token()
3876                || key.channel != handle.channel
3877                || key.epoch != handle.epoch;
3878            if !keep {
3879                slot.release();
3880            }
3881            keep
3882        });
3883    }
3884
3885    fn remove_route_by_handle(&mut self, handle: RouteHandle) -> Option<RouteState> {
3886        if let Some(key) = self.route_by_channel.get(&handle.channel).cloned() {
3887            let matches = self
3888                .routes
3889                .get(&key)
3890                .is_some_and(|route| route.handle == handle);
3891            debug_assert!(matches);
3892            if matches {
3893                return self.remove_route(&key);
3894            }
3895        }
3896        let route = self
3897            .one_shot_routes
3898            .get(&handle.channel)
3899            .is_some_and(|route| route.handle == handle)
3900            .then(|| self.one_shot_routes.remove(&handle.channel))
3901            .flatten();
3902        if let Some(route) = &route {
3903            release_reverse_request_registry(route.handle);
3904        }
3905        route
3906    }
3907
3908    fn drain_routes(&mut self) -> Vec<RouteState> {
3909        self.route_targets.clear();
3910        for (_, slot) in self.wire_slots.drain() {
3911            slot.release();
3912        }
3913        self.retirement_goodbyes.clear();
3914        self.retirement_queue.clear();
3915        if let Some(task) = self.retirement_task.take() {
3916            task.abort();
3917        }
3918        for handle in self.retired_routes.drain() {
3919            release_reverse_request_registry(handle);
3920        }
3921        self.route_by_channel.clear();
3922        let routes = self
3923            .routes
3924            .drain()
3925            .map(|(_, route)| route)
3926            .chain(self.one_shot_routes.drain().map(|(_, route)| route))
3927            .collect::<Vec<_>>();
3928        for route in &routes {
3929            release_reverse_request_registry(route.handle);
3930        }
3931        routes
3932    }
3933
3934    fn close_routes(&mut self) {
3935        self.push_event_receivers.clear();
3936        for route in self.drain_routes() {
3937            route.close();
3938        }
3939    }
3940}
3941
3942impl Shared {
3943    fn new(connection_file: PathBuf, opts: ConsumerOptions) -> Self {
3944        Self::with_transport(connection_file, opts, ConsumerTransport::Tcp)
3945    }
3946
3947    fn with_transport(
3948        connection_file: PathBuf,
3949        opts: ConsumerOptions,
3950        transport: ConsumerTransport,
3951    ) -> Self {
3952        Self {
3953            claim_bound: crate::registration::bound(),
3954            connection_file,
3955            operator_app_candidates: None,
3956            opts,
3957            transport,
3958            identity_from_environment: true,
3959            inner: Mutex::new(Inner {
3960                generation: 1,
3961                daemon_origin_trusted: false,
3962                daemon_ver: String::new(),
3963                accepts_close_reasons: None,
3964                epoch: 1,
3965                next_corr: Some(1),
3966                writer: None,
3967                pending: HashMap::new(),
3968                wire_slots: HashMap::new(),
3969                routes: HashMap::new(),
3970                route_by_channel: HashMap::new(),
3971                one_shot_routes: HashMap::new(),
3972                route_epochs: HashMap::new(),
3973                route_targets: HashMap::new(),
3974                retired_routes: HashSet::new(),
3975                retirement_goodbyes: HashSet::new(),
3976                retirement_queue: VecDeque::new(),
3977                retirement_notify: Arc::new(Notify::new()),
3978                retirement_task: None,
3979                route_modules: HashMap::new(),
3980                route_end_reasons: HashMap::new(),
3981                legacy_channel_reasons: HashMap::new(),
3982                push_event_receivers: HashMap::new(),
3983                control_push_receiver: None,
3984                dropped_route_frames: 0,
3985                openings: HashMap::new(),
3986                callbacks: Vec::new(),
3987                closed: false,
3988                reconnect: ReconnectState::Idle,
3989                restored_token: 0,
3990                reader_task: None,
3991                writer_task: None,
3992            }),
3993            notify: Notify::new(),
3994            #[cfg(test)]
3995            before_wait: Mutex::new(None),
3996            close_token: CancellationToken::new(),
3997            last_inbound_ms: AtomicU64::new(0),
3998            liveness_probe_running: AtomicBool::new(false),
3999            pushes_dropped_no_receiver: AtomicU64::new(0),
4000            control_pushes_dropped: AtomicU64::new(0),
4001            pushes_dropped_receiver_full: AtomicU64::new(0),
4002            random_unit: Box::new(default_random_unit),
4003            route_open_slots: Semaphore::new(MAX_ROUTE_OPENS_IN_FLIGHT),
4004            route_description: tokio::sync::Mutex::new(()),
4005        }
4006    }
4007
4008    /// "Equal jitter": keep half of `delay` and randomize the other half. Every
4009    /// route on a connection is closed together when its module drains, so
4010    /// without jitter they all retry in lock step and reach the daemon as one
4011    /// burst each round; reconnects after a daemon restart herd the same way.
4012    fn jittered(&self, delay: Duration) -> Duration {
4013        let unit = (self.random_unit)();
4014        let unit = if unit.is_finite() {
4015            unit.clamp(0.0, 1.0)
4016        } else {
4017            0.0
4018        };
4019        let half = delay / 2;
4020        half + half.mul_f64(unit)
4021    }
4022
4023    /// One route.open exchange, paced by [`MAX_ROUTE_OPENS_IN_FLIGHT`]. The
4024    /// wait for a free slot ends at `deadline` like the exchange itself.
4025    async fn paced_route_open(
4026        self: &Arc<Self>,
4027        body: Vec<u8>,
4028        deadline: Instant,
4029        reverse_requests: Option<ReverseRequestRegistry>,
4030    ) -> Result<TerminalFrame, CallError> {
4031        let _slot = match timeout_at(deadline, self.route_open_slots.acquire()).await {
4032            Ok(Ok(permit)) => permit,
4033            Ok(Err(_)) => return Err(CallError::not_sent("consumer closed")),
4034            Err(_) => {
4035                return Err(CallError::not_sent(format!(
4036                    "deadline elapsed waiting for one of {MAX_ROUTE_OPENS_IN_FLIGHT} route.open slots"
4037                )));
4038            }
4039        };
4040        self.control_call(body, deadline, true, reverse_requests)
4041            .await
4042    }
4043
4044    fn lock_inner(&self) -> MutexGuard<'_, Inner> {
4045        self.inner
4046            .lock()
4047            .unwrap_or_else(|poisoned| poisoned.into_inner())
4048    }
4049
4050    fn install_initial(self: &Arc<Self>, opened: OpenedConnection) -> Result<(), ConsumerError> {
4051        self.install_connection(opened, InstallKind::Initial)
4052            .map(|_| ())
4053    }
4054
4055    fn install_reconnected(
4056        self: &Arc<Self>,
4057        opened: OpenedConnection,
4058    ) -> Result<(u64, u64), ConsumerError> {
4059        let generation_epoch = self.install_connection(opened, InstallKind::Reconnect)?;
4060        self.notify.notify_waiters();
4061        Ok(generation_epoch)
4062    }
4063
4064    fn install_connection(
4065        self: &Arc<Self>,
4066        opened: OpenedConnection,
4067        kind: InstallKind,
4068    ) -> Result<(u64, u64), ConsumerError> {
4069        if self.close_token.is_cancelled() {
4070            return Err(ConsumerError::Closed);
4071        }
4072
4073        let (reader, writer) = tokio::io::split(opened.stream);
4074        let (tx, rx) = mpsc::channel(EGRESS_BUFFER);
4075        let (generation, epoch, old_reader, old_writer) = {
4076            let mut inner = self.lock_inner();
4077            if inner.closed {
4078                return Err(ConsumerError::Closed);
4079            }
4080            let (generation, epoch) = match kind {
4081                InstallKind::Initial => (inner.generation, inner.epoch),
4082                InstallKind::Reconnect => {
4083                    inner.generation = inner
4084                        .generation
4085                        .checked_add(1)
4086                        .ok_or(ConsumerError::Closed)?;
4087                    inner.epoch = inner.epoch.checked_add(1).ok_or(ConsumerError::Closed)?;
4088                    (inner.generation, inner.epoch)
4089                }
4090            };
4091            inner.close_routes();
4092            inner.route_epochs.clear();
4093            inner.route_targets.clear();
4094            inner.route_modules.clear();
4095            inner.route_end_reasons.clear();
4096            inner.legacy_channel_reasons.clear();
4097            inner.next_corr = Some(1);
4098            inner.writer = Some(tx);
4099            inner.daemon_origin_trusted = opened.daemon_origin_trusted;
4100            inner.daemon_ver = opened.daemon_ver;
4101            inner.accepts_close_reasons = None;
4102            self.last_inbound_ms.store(0, Ordering::Release);
4103            (
4104                generation,
4105                epoch,
4106                inner.reader_task.take(),
4107                inner.writer_task.take(),
4108            )
4109        };
4110
4111        if let Some(handle) = old_reader {
4112            handle.abort();
4113        }
4114        if let Some(handle) = old_writer {
4115            handle.abort();
4116        }
4117
4118        let reader_shared = Arc::clone(self);
4119        let reader_task = tokio::spawn(async move {
4120            reader_loop(reader_shared, reader, generation).await;
4121        });
4122        let writer_shared = Arc::clone(self);
4123        let writer_task = tokio::spawn(async move {
4124            writer_loop(writer_shared, writer, rx, generation).await;
4125        });
4126
4127        {
4128            let mut inner = self.lock_inner();
4129            if inner.closed || inner.generation != generation {
4130                reader_task.abort();
4131                writer_task.abort();
4132                return Err(ConsumerError::Closed);
4133            }
4134            inner.reader_task = Some(reader_task);
4135            inner.writer_task = Some(writer_task);
4136            let retirement_shared = Arc::clone(self);
4137            let retirement_notify = Arc::clone(&inner.retirement_notify);
4138            inner.retirement_task = Some(tokio::spawn(async move {
4139                retirement_goodbye_loop(retirement_shared, generation, retirement_notify).await;
4140            }));
4141        }
4142
4143        Ok((generation, epoch))
4144    }
4145
4146    async fn ensure_connected_for_call(
4147        self: &Arc<Self>,
4148        deadline: Instant,
4149    ) -> Result<(), CallError> {
4150        loop {
4151            if Instant::now() >= deadline {
4152                return Err(CallError::not_sent(
4153                    "call deadline elapsed waiting for reconnection",
4154                ));
4155            }
4156            // Created BEFORE the state is read, and that ordering is the fix.
4157            // Reconnect completion wakes waiters with `notify_waiters()`, which
4158            // reaches only `Notified` futures that already exist and stores no
4159            // permit. A future created after the lock is released misses a
4160            // reconnect that finishes in between, and the caller then sleeps
4161            // until its deadline on a healthy connection. (`enable()` is kept
4162            // for `notify_one` semantics; for `notify_waiters` creation alone
4163            // is what registers the waiter.)
4164            let notified = self.notify.notified();
4165            tokio::pin!(notified);
4166            let action = {
4167                let mut inner = self.lock_inner();
4168                notified.as_mut().enable();
4169                if inner.closed {
4170                    return Err(CallError::not_sent("consumer closed"));
4171                }
4172                if inner.writer.is_some() {
4173                    return Ok(());
4174                }
4175                let generation = inner.generation;
4176                let reconnect_is_live = match &inner.reconnect {
4177                    ReconnectState::Idle => false,
4178                    ReconnectState::Inline { generation: active } => *active == generation,
4179                    ReconnectState::Background {
4180                        generation: active,
4181                        task,
4182                    } => *active == generation && !task.is_finished(),
4183                };
4184                if reconnect_is_live {
4185                    EnsureAction::Wait
4186                } else {
4187                    let stale_task =
4188                        match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4189                            ReconnectState::Background { task, .. } => Some(task),
4190                            ReconnectState::Idle | ReconnectState::Inline { .. } => None,
4191                        };
4192                    inner.reconnect = ReconnectState::Inline { generation };
4193                    EnsureAction::Lead {
4194                        generation,
4195                        stale_task,
4196                    }
4197                }
4198            };
4199
4200            match action {
4201                EnsureAction::Wait => {
4202                    #[cfg(test)]
4203                    {
4204                        let hook = self.before_wait.lock().unwrap().take();
4205                        if let Some(hook) = hook {
4206                            hook();
4207                        }
4208                    }
4209                    timeout_at(deadline, notified).await.map_err(|_| {
4210                        CallError::not_sent("call deadline elapsed waiting for reconnection")
4211                    })?;
4212                }
4213                EnsureAction::Lead {
4214                    generation,
4215                    stale_task,
4216                } => {
4217                    if let Some(handle) = stale_task {
4218                        handle.abort();
4219                    }
4220                    let mut guard = InlineReconnectGuard::new(Arc::clone(self), generation);
4221                    let result = timeout_at(deadline, self.reconnect_with_retry(generation)).await;
4222                    guard.finish();
4223                    return match result {
4224                        Ok(Ok(())) => Ok(()),
4225                        Ok(Err(err)) => Err(CallError::not_sent(err.to_string())),
4226                        Err(_) => Err(CallError::not_sent(
4227                            "call deadline elapsed waiting for reconnection",
4228                        )),
4229                    };
4230                }
4231            }
4232        }
4233    }
4234
4235    fn spawn_reconnect(self: &Arc<Self>, generation: u64) -> bool {
4236        // Reconnect ownership is fenced by the dropped transport generation. A
4237        // newer drop replaces an older attempt instead of letting that attempt
4238        // block recovery for the newer transport.
4239        let stale_task = {
4240            let mut inner = self.lock_inner();
4241            if inner.closed || inner.writer.is_some() || inner.generation != generation {
4242                return false;
4243            }
4244            let should_spawn = match &inner.reconnect {
4245                ReconnectState::Idle => true,
4246                ReconnectState::Inline { generation: active } => *active < generation,
4247                ReconnectState::Background {
4248                    generation: active,
4249                    task,
4250                } => *active < generation || (*active == generation && task.is_finished()),
4251            };
4252            if !should_spawn {
4253                return false;
4254            }
4255
4256            let stale_task = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4257                ReconnectState::Background { task, .. } => Some(task),
4258                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
4259            };
4260            let shared = Arc::clone(self);
4261            let handle = tokio::spawn(async move {
4262                let _result = shared.reconnect_with_retry(generation).await;
4263                shared.finish_background_reconnect(generation);
4264            });
4265            inner.reconnect = ReconnectState::Background {
4266                generation,
4267                task: handle,
4268            };
4269            stale_task
4270        };
4271        if let Some(handle) = stale_task {
4272            handle.abort();
4273        }
4274        true
4275    }
4276
4277    fn reconnect_attempt_is_current(&self, generation: u64) -> bool {
4278        let inner = self.lock_inner();
4279        !inner.closed
4280            && inner.writer.is_none()
4281            && inner.generation == generation
4282            && matches!(
4283                &inner.reconnect,
4284                ReconnectState::Inline { generation: active }
4285                    | ReconnectState::Background {
4286                        generation: active,
4287                        ..
4288                    } if *active == generation
4289            )
4290    }
4291
4292    fn finish_inline_reconnect(&self, generation: u64) {
4293        let finished = {
4294            let mut inner = self.lock_inner();
4295            if matches!(
4296                &inner.reconnect,
4297                ReconnectState::Inline { generation: active } if *active == generation
4298            ) {
4299                inner.reconnect = ReconnectState::Idle;
4300                true
4301            } else {
4302                false
4303            }
4304        };
4305        if finished {
4306            self.notify.notify_waiters();
4307        }
4308    }
4309
4310    fn finish_background_reconnect(&self, generation: u64) {
4311        let completed_task = {
4312            let mut inner = self.lock_inner();
4313            if !matches!(
4314                &inner.reconnect,
4315                ReconnectState::Background { generation: active, .. } if *active == generation
4316            ) {
4317                None
4318            } else {
4319                match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
4320                    ReconnectState::Background { task, .. } => Some(task),
4321                    ReconnectState::Idle | ReconnectState::Inline { .. } => unreachable!(),
4322                }
4323            }
4324        };
4325        if completed_task.is_some() {
4326            drop(completed_task);
4327            self.notify.notify_waiters();
4328        }
4329    }
4330
4331    fn schedule_restored(self: &Arc<Self>, generation: u64, epoch: u64) {
4332        let token = {
4333            let mut inner = self.lock_inner();
4334            inner.restored_token = inner.restored_token.saturating_add(1);
4335            inner.restored_token
4336        };
4337        let shared = Arc::clone(self);
4338        tokio::spawn(async move {
4339            tokio::select! {
4340                () = shared.close_token.cancelled() => {}
4341                () = sleep(shared.opts.restored_debounce) => {
4342                    let should_emit = {
4343                        let inner = shared.lock_inner();
4344                        !inner.closed
4345                            && inner.generation == generation
4346                            && inner.epoch == epoch
4347                            && inner.restored_token == token
4348                            && inner.writer.is_some()
4349                    };
4350                    if should_emit {
4351                        shared.emit_connection_state(ConnectionState::Restored { epoch });
4352                    }
4353                }
4354            }
4355        });
4356    }
4357
4358    fn install_one_shot_route(&self, route: RouteState) -> Result<(), CallError> {
4359        let handle = route.handle;
4360        let mut inner = self.lock_inner();
4361        if inner.closed || inner.generation != handle.connection_token() || inner.writer.is_none() {
4362            return Err(CallError::StaleRouteHandle(handle));
4363        }
4364        // The socket reader installs the handle for a route.open response before
4365        // the waiter resolves (so a request the provider sends right after the
4366        // bind is routed), so this route's own channel is normally present
4367        // already, holding exactly this handle. Only a different handle on the
4368        // channel is a collision.
4369        if inner
4370            .route_epochs
4371            .get(&handle.channel)
4372            .is_some_and(|existing| *existing != handle)
4373        {
4374            return Err(CallError::not_sent(
4375                "daemon returned a route channel already in use",
4376            ));
4377        }
4378        inner.one_shot_routes.insert(handle.channel, route);
4379        inner.route_epochs.insert(handle.channel, handle);
4380        Ok(())
4381    }
4382
4383    async fn ensure_route(
4384        self: &Arc<Self>,
4385        key: &RouteKey,
4386        route_open: &RouteOpenParams<'_>,
4387        opts: &CallOptions,
4388        call_deadline: Instant,
4389    ) -> Result<RouteState, CallError> {
4390        loop {
4391            let action = {
4392                let mut inner = self.lock_inner();
4393                if inner.closed {
4394                    return Err(CallError::not_sent("consumer closed"));
4395                }
4396                if let Some(route) = inner.routes.get(key) {
4397                    if route.handle.connection_token() == inner.generation && inner.writer.is_some()
4398                    {
4399                        return Ok(route.clone());
4400                    }
4401                }
4402                if let Some(opening) = inner.openings.get_mut(key) {
4403                    let (tx, rx) = oneshot::channel();
4404                    opening.waiters.push(tx);
4405                    RouteOpenAction::Wait(rx)
4406                } else {
4407                    inner.openings.insert(
4408                        key.clone(),
4409                        Opening {
4410                            waiters: Vec::new(),
4411                            closed: false,
4412                        },
4413                    );
4414                    RouteOpenAction::Lead
4415                }
4416            };
4417
4418            match action {
4419                RouteOpenAction::Wait(rx) => match timeout_at(call_deadline, rx).await {
4420                    Ok(Ok(Ok(route))) => return Ok(route),
4421                    Ok(Ok(Err(err))) => return Err(err.into_call_error()),
4422                    Ok(Err(_)) => continue,
4423                    Err(_) => {
4424                        return Err(CallError::not_sent_with_cause(
4425                            "call deadline elapsed waiting for route.open",
4426                            NotSentCause::RouteOpenAbandoned,
4427                        ));
4428                    }
4429                },
4430                RouteOpenAction::Lead => {
4431                    let mut guard = OpeningGuard::new(Arc::clone(self), key.clone());
4432                    let result = self
4433                        .open_route_with_retry(key, route_open, opts, call_deadline)
4434                        .await
4435                        .map_err(SharedCallFailure::from);
4436                    guard.finish(result.clone());
4437                    return result.map_err(SharedCallFailure::into_call_error);
4438                }
4439            }
4440        }
4441    }
4442
4443    async fn open_route_with_retry(
4444        self: &Arc<Self>,
4445        key: &RouteKey,
4446        route_open: &RouteOpenParams<'_>,
4447        opts: &CallOptions,
4448        call_deadline: Instant,
4449    ) -> Result<RouteState, CallError> {
4450        let route_deadline = (Instant::now() + opts.route_retry_deadline).min(call_deadline);
4451        let mut attempt = 0usize;
4452        // The retryable refusals seen so far. When the deadline ends the retries,
4453        // the caller gets the most informative of them rather than a bare
4454        // "deadline elapsed", so "the module was reloading" stays
4455        // distinguishable from "the connection failed".
4456        let mut refusals = RouteOpenRefusals::default();
4457        // An attempt that ends because the deadline passed hands back the kept
4458        // refusal. That covers an attempt that never left the client (NotSent)
4459        // and one the daemon received but had not answered by the deadline
4460        // (OutcomeUnknown with the Deadline cause): a busy daemon can answer
4461        // the final retry a few milliseconds late, and the refusals before it
4462        // still say why the route never opened. Dropping the unanswered
4463        // attempt's own outcome is safe: route.open requests are sent with
4464        // `retain_late_route_open`, so a late acceptance is closed again with
4465        // a GOODBYE instead of being handed to anyone.
4466        let expired = |err: CallError, refusals: &mut RouteOpenRefusals| {
4467            let ended_by_deadline =
4468                err.is_not_sent() || err.outcome_cause() == Some(OutcomeUnknownCause::Deadline);
4469            if ended_by_deadline && Instant::now() >= route_deadline {
4470                if let Some(refused) = std::mem::take(refusals).into_error(key.target_label()) {
4471                    return refused;
4472                }
4473            }
4474            err
4475        };
4476        loop {
4477            attempt = attempt.saturating_add(1);
4478            let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
4479                busy_refusals: Some(true),
4480                target: route_open.target.clone(),
4481                identity: route_open.identity.clone(),
4482                consumer_identity: route_open.consumer_identity.clone(),
4483                consumer_capabilities: route_open.consumer_capabilities.clone(),
4484                role_versions: route_open.role_versions.clone(),
4485                admission_facts: None,
4486                scope: route_open.scope.cloned(),
4487            })
4488            .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;
4489            match self
4490                .paced_route_open(
4491                    body,
4492                    route_deadline,
4493                    Some(route_open.reverse_requests.clone()),
4494                )
4495                .await
4496            {
4497                Ok(TerminalFrame::Response {
4498                    generation, body, ..
4499                }) => {
4500                    let (response, _) = decode_route_open_response(&body).map_err(|err| {
4501                        CallError::not_sent_with_cause(
4502                            format!("failed to decode route.open response: {err}"),
4503                            NotSentCause::RouteOpenAbandoned,
4504                        )
4505                    })?;
4506                    let ClientControlResponse::RouteOpen {
4507                        route_channel,
4508                        route_epoch,
4509                        request_window,
4510                        watch_window,
4511                        ..
4512                    } = response
4513                    else {
4514                        return Err(CallError::not_sent_with_cause(
4515                            "route.open returned an unexpected control response",
4516                            NotSentCause::RouteOpenAbandoned,
4517                        ));
4518                    };
4519                    let handle = self
4520                        .ingress_handle(generation, route_channel, route_epoch)
4521                        .unwrap_or_else(|| {
4522                            RouteHandle::new_consumer(
4523                                route_channel,
4524                                route_epoch,
4525                                generation,
4526                                route_open.reverse_requests.clone(),
4527                            )
4528                        });
4529                    let route = RouteState::windows(handle, request_window, watch_window);
4530                    let install = {
4531                        let mut inner = self.lock_inner();
4532                        if inner.closed {
4533                            return Err(CallError::not_sent("consumer closed"));
4534                        }
4535                        // Close-beats-reopen guard: a close_route may have flipped this
4536                        // opening's `closed` flag WHILE this route.open was in flight. If
4537                        // so, close wins — do NOT cache the channel; GOODBYE it below and
4538                        // fail as NotSent (the route was closed before the open landed).
4539                        let closed_during_open = inner.openings.get(key).is_some_and(|o| o.closed);
4540                        if closed_during_open
4541                            || inner.generation != generation
4542                            || inner.writer.is_none()
4543                        {
4544                            RouteInstall::Discard {
4545                                closed: closed_during_open,
4546                            }
4547                        } else {
4548                            let cached = inner.cache_route(key.clone(), route.clone());
4549                            RouteInstall::Cached(cached)
4550                        }
4551                    };
4552                    match install {
4553                        RouteInstall::Cached(cached) => return Ok(cached),
4554                        RouteInstall::Discard { closed } => {
4555                            if closed {
4556                                // GOODBYE the channel we opened so the daemon/module don't
4557                                // leak it, then report the close as a NotSent failure.
4558                                self.send_route_goodbye(route.handle, true);
4559                                self.uninstall_route_handle(route.handle);
4560                                return Err(CallError::not_sent_with_cause(
4561                                    "route was closed before route.open completed",
4562                                    NotSentCause::RouteOpenAbandoned,
4563                                ));
4564                            }
4565                            // Stale generation / writer gone: fall through to retry.
4566                        }
4567                    }
4568                    self.sleep_until_retry(route_deadline, self.jittered(opts.route_retry.base))
4569                        .await?;
4570                }
4571                Ok(TerminalFrame::Error { body, .. }) => {
4572                    // The deadline is the ONLY binder for retryable refusals.
4573                    // An attempt cap used to share this condition, and because
4574                    // the capped backoff sums to seconds it strictly dominated
4575                    // the deadline — the advertised reload patience was never
4576                    // delivered, and module restarts whose reload exceeded a
4577                    // few seconds failed every managed caller. A restart
4578                    // legitimately keeps routes refused for about a minute;
4579                    // capped per-attempt backoff bounds pressure.
4580                    if !error_codes::is_retryable_route_open_refusal(&body) {
4581                        return Err(CallError::route_open_refused(key.target_label(), body));
4582                    }
4583                    refusals.record(body);
4584                    if Instant::now() >= route_deadline {
4585                        // A refusal was just recorded, so the fallback is unreachable.
4586                        return Err(std::mem::take(&mut refusals)
4587                            .into_error(key.target_label())
4588                            .unwrap_or_else(|| {
4589                                CallError::not_sent("route.open retry deadline elapsed")
4590                            }));
4591                    }
4592                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
4593                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
4594                        return Err(expired(err, &mut refusals));
4595                    }
4596                    continue;
4597                }
4598                Ok(TerminalFrame::StreamEnd) => {
4599                    return Err(CallError::not_sent_with_cause(
4600                        "route.open returned StreamEnd",
4601                        NotSentCause::RouteOpenAbandoned,
4602                    ));
4603                }
4604                Err(err) if err.is_not_sent() && Instant::now() < route_deadline => {
4605                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
4606                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
4607                        return Err(expired(err, &mut refusals));
4608                    }
4609                }
4610                Err(err) => return Err(expired(err, &mut refusals)),
4611            }
4612        }
4613
4614        #[allow(unreachable_code)]
4615        Err(CallError::not_sent(format!(
4616            "route.open retry deadline elapsed for target {}",
4617            key.target_label()
4618        )))
4619    }
4620
4621    async fn sleep_until_retry(&self, deadline: Instant, delay: Duration) -> Result<(), CallError> {
4622        if Instant::now() >= deadline {
4623            return Err(CallError::not_sent("retry deadline elapsed"));
4624        }
4625        let bounded = delay.min(deadline.saturating_duration_since(Instant::now()));
4626        tokio::select! {
4627            () = self.close_token.cancelled() => Err(CallError::not_sent("consumer closed")),
4628            () = sleep(bounded) => Ok(()),
4629        }
4630    }
4631
4632    async fn control_call(
4633        self: &Arc<Self>,
4634        body: Vec<u8>,
4635        deadline: Instant,
4636        retain_late_route_open: bool,
4637        route_open_reverse_requests: Option<ReverseRequestRegistry>,
4638    ) -> Result<TerminalFrame, CallError> {
4639        self.ensure_connected_for_call(deadline).await?;
4640        if retain_late_route_open {
4641            {
4642                let inner = self.lock_inner();
4643                if !daemon_version_at_least(&inner.daemon_ver, (0, 39, 0)) {
4644                    return Err(CallError::DaemonTooOld {
4645                        daemon_ver: inner.daemon_ver.clone(),
4646                    });
4647                }
4648            }
4649            self.describe_route_close_reasons(deadline).await?;
4650        }
4651        self.send_request(RequestSend {
4652            binary: false,
4653            expected_handle: None,
4654            channel: 0,
4655            epoch: 0,
4656            body,
4657            priority: Priority::Interactive,
4658            admission_class: AdmissionClass::Normal,
4659            deadline,
4660            retain_late_route_open,
4661            route_open_reverse_requests,
4662        })
4663        .await
4664    }
4665
4666    async fn describe_route_close_reasons(
4667        self: &Arc<Self>,
4668        deadline: Instant,
4669    ) -> Result<(), CallError> {
4670        let _lookup = timeout_at(deadline, self.route_description.lock())
4671            .await
4672            .map_err(|_| CallError::not_sent("deadline waiting for server.describe"))?;
4673        loop {
4674            self.ensure_connected_for_call(deadline).await?;
4675            let generation = {
4676                let inner = self.lock_inner();
4677                if inner.accepts_close_reasons.is_some() {
4678                    return Ok(());
4679                }
4680                inner.generation
4681            };
4682            // Description is advisory. A refused, malformed or unanswered lookup
4683            // must not prevent opening routes to a daemon that predates the key.
4684            let reply = self
4685                .send_request(RequestSend {
4686                    binary: false,
4687                    expected_handle: None,
4688                    channel: 0,
4689                    epoch: 0,
4690                    body: br#"{"op":"server.describe"}"#.to_vec(),
4691                    priority: Priority::Interactive,
4692                    admission_class: AdmissionClass::Normal,
4693                    deadline: deadline.min(Instant::now() + CAPABILITY_PROBE_TIMEOUT),
4694                    retain_late_route_open: false,
4695                    route_open_reverse_requests: None,
4696                })
4697                .await;
4698            let supported = match reply {
4699                Ok(TerminalFrame::Response { body, .. }) => {
4700                    matches!(serde_json::from_slice::<ClientControlResponse>(&body),
4701                        Ok(ClientControlResponse::ServerDescribe { capabilities, .. })
4702                        if capabilities.iter().any(|cap| cap == ROUTE_CLOSE_REASONS_CAPABILITY))
4703                }
4704                _ => false,
4705            };
4706            let mut inner = self.lock_inner();
4707            if inner.generation == generation {
4708                inner.accepts_close_reasons = Some(supported);
4709                return Ok(());
4710            }
4711        }
4712    }
4713
4714    async fn send_request(
4715        self: &Arc<Self>,
4716        request: RequestSend,
4717    ) -> Result<TerminalFrame, CallError> {
4718        self.send_request_cancellable(request, None).await
4719    }
4720
4721    fn allocate_request(
4722        self: &Arc<Self>,
4723        expected_handle: Option<RouteHandle>,
4724        channel: u16,
4725        epoch: u32,
4726    ) -> Result<(PendingKey, mpsc::Sender<WriteCommand>), CallError> {
4727        let mut inner = self.lock_inner();
4728        if inner.closed {
4729            return Err(CallError::not_sent("consumer closed"));
4730        }
4731        let generation = inner.generation;
4732        if let Some(expected) = expected_handle {
4733            let route_pair_matches =
4734                channel == 0 || (expected.channel == channel && expected.epoch == epoch);
4735            if expected.connection_token() != generation
4736                || !route_pair_matches
4737                || inner.route_epochs.get(&expected.channel) != Some(&expected)
4738                || inner.retired_routes.contains(&expected)
4739            {
4740                return Err(CallError::StaleRouteHandle(expected));
4741            }
4742        }
4743        let Some(writer) = inner.writer.clone() else {
4744            return Err(CallError::not_sent("subc connection is down before send"));
4745        };
4746        let Some(corr) = inner.next_corr else {
4747            drop(inner);
4748            self.handle_generation_drop(
4749                generation,
4750                "channel-0 correlation allocator exhausted".to_string(),
4751            );
4752            return Err(CallError::not_sent(
4753                "correlation allocator exhausted; connection closed",
4754            ));
4755        };
4756        inner.next_corr = corr.checked_add(1);
4757        Ok((
4758            PendingKey {
4759                generation,
4760                channel,
4761                epoch,
4762                corr,
4763            },
4764            writer,
4765        ))
4766    }
4767
4768    async fn send_request_cancellable(
4769        self: &Arc<Self>,
4770        request: RequestSend,
4771        cancel: Option<Arc<UnaryCancel>>,
4772    ) -> Result<TerminalFrame, CallError> {
4773        self.send_request_with_slot(request, cancel, None).await
4774    }
4775
4776    async fn send_request_with_slot(
4777        self: &Arc<Self>,
4778        request: RequestSend,
4779        cancel: Option<Arc<UnaryCancel>>,
4780        slot: Option<Arc<RoutePermit>>,
4781    ) -> Result<TerminalFrame, CallError> {
4782        let RequestSend {
4783            expected_handle,
4784            channel,
4785            epoch,
4786            body,
4787            binary,
4788            priority,
4789            admission_class,
4790            deadline,
4791            retain_late_route_open,
4792            route_open_reverse_requests,
4793        } = request;
4794        if Instant::now() >= deadline {
4795            return Err(CallError::not_sent(
4796                "call deadline elapsed before request was sent",
4797            ));
4798        }
4799        let slot = match (slot, expected_handle) {
4800            (Some(slot), _) => Some(slot),
4801            (None, Some(handle)) if channel != 0 => match self.route_state(handle) {
4802                Ok(route) if route.opted_in => {
4803                    Some(route.acquire(false, deadline, cancel.as_ref()).await?)
4804                }
4805                _ => None,
4806            },
4807            (None, _) => None,
4808        };
4809        let (key, writer) = self.allocate_request(expected_handle, channel, epoch)?;
4810        let generation = key.generation;
4811
4812        let mut frame = Frame::build(
4813            FrameType::Request,
4814            Flags::new(binary, priority, false).with_admission_class(admission_class),
4815            channel,
4816            epoch,
4817            key.corr,
4818            body,
4819        )
4820        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
4821        let (tx, rx) = oneshot::channel();
4822        {
4823            let mut inner = self.lock_inner();
4824            if inner.closed || inner.generation != generation || inner.writer.is_none() {
4825                return Err(CallError::not_sent(
4826                    "connection changed before request registration",
4827                ));
4828            }
4829            // Check the version retained for the authenticated connection under
4830            // the same lock as registration, so reconnecting cannot send a
4831            // rootless identity after a check on a different connection.
4832            if retain_late_route_open && !daemon_version_at_least(&inner.daemon_ver, (0, 39, 0)) {
4833                return Err(CallError::DaemonTooOld {
4834                    daemon_ver: inner.daemon_ver.clone(),
4835                });
4836            }
4837            if retain_late_route_open {
4838                let supported = inner.accepts_close_reasons.ok_or_else(|| {
4839                    CallError::not_sent("connection changed before route.open capability discovery")
4840                })?;
4841                let mut body: serde_json::Value = serde_json::from_slice(&frame.body)
4842                    .map_err(|err| CallError::not_sent(format!("invalid route.open: {err}")))?;
4843                RouteOpenRequestExt::new()
4844                    .with_accepts_close_reasons(supported.then(|| {
4845                        ACCEPTED_CLOSE_REASONS
4846                            .iter()
4847                            .map(|reason| (*reason).to_string())
4848                            .collect()
4849                    }))
4850                    .write_to(&mut body)
4851                    .map_err(|err| CallError::not_sent(format!("invalid route.open: {err}")))?;
4852                frame = Frame::build(
4853                    FrameType::Request,
4854                    frame.header.flags,
4855                    channel,
4856                    epoch,
4857                    key.corr,
4858                    serde_json::to_vec(&body)
4859                        .map_err(|err| CallError::not_sent(err.to_string()))?,
4860                )
4861                .map_err(|err| CallError::not_sent(err.to_string()))?;
4862            }
4863            if let Some(expected) = expected_handle {
4864                if inner.route_epochs.get(&expected.channel) != Some(&expected)
4865                    || inner.retired_routes.contains(&expected)
4866                {
4867                    return Err(CallError::StaleRouteHandle(expected));
4868                }
4869            }
4870            let expected_control_handle = (channel == 0 && !retain_late_route_open)
4871                .then_some(expected_handle)
4872                .flatten();
4873            inner.pending.insert(
4874                key,
4875                PendingEntry::unary(
4876                    tx,
4877                    retain_late_route_open,
4878                    expected_control_handle,
4879                    route_open_reverse_requests,
4880                ),
4881            );
4882            if let Some(slot) = slot.filter(|slot| slot.opted_in()) {
4883                inner.wire_slots.insert(key, slot);
4884            }
4885            if retain_late_route_open {
4886                inner.pending.get_mut(&key).unwrap().route_open_module =
4887                    serde_json::from_slice::<serde_json::Value>(&frame.body)
4888                        .ok()
4889                        .and_then(|body| {
4890                            body.get("target")?
4891                                .get("module_id")?
4892                                .as_str()
4893                                .map(str::to_string)
4894                        });
4895            }
4896        }
4897        let mut registration =
4898            PendingRegistration::new(Arc::clone(self), key, retain_late_route_open);
4899        registration.unary_cancel = cancel.clone();
4900
4901        match timeout_at(
4902            deadline,
4903            writer.send(WriteCommand {
4904                frame,
4905                pending: Some(key),
4906            }),
4907        )
4908        .await
4909        {
4910            Ok(Ok(())) => {}
4911            Ok(Err(_)) => {
4912                let accepted = registration.remove_pending().unwrap_or(false);
4913                return Err(classify_failure(
4914                    accepted,
4915                    "writer task closed before accepting request",
4916                    OutcomeUnknownCause::WriterClosed,
4917                ));
4918            }
4919            Err(_) => {
4920                let accepted = registration.remove_pending().unwrap_or(false);
4921                return Err(classify_failure_with_not_sent_cause(
4922                    accepted,
4923                    "call deadline elapsed waiting for writer capacity",
4924                    OutcomeUnknownCause::Deadline,
4925                    NotSentCause::WriterCapacity,
4926                ));
4927            }
4928        }
4929
4930        if let Some(cancel) = cancel {
4931            cancel.activate(key, priority, deadline);
4932            if cancel.requested() {
4933                cancel.cancel().await;
4934            }
4935        }
4936
4937        self.wait_for_reply(registration, rx, deadline).await
4938    }
4939
4940    async fn wait_for_reply(
4941        self: &Arc<Self>,
4942        mut registration: PendingRegistration,
4943        rx: oneshot::Receiver<PendingResult>,
4944        deadline: Instant,
4945    ) -> Result<TerminalFrame, CallError> {
4946        let key = registration.key;
4947        let channel = key.channel;
4948        // After writer handoff, settle_pending, a connection drop or close_sync may already
4949        // have removed the entry and still be settling it. Its absence cannot prove that the
4950        // request was not written, so a missing entry is classified as possibly written.
4951        tokio::select! {
4952            result = timeout_at(deadline, rx) => match result {
4953                Ok(Ok(result)) => {
4954                    registration.disarm();
4955                    result.into_call_result()
4956                }
4957                Ok(Err(_)) => {
4958                    // The entry was settled without a result, so the request may already
4959                    // have been written: report the outcome as unknown, never `NotSent`.
4960                    registration.disarm();
4961                    Err(CallError::outcome_unknown(
4962                        "pending response channel closed",
4963                        OutcomeUnknownCause::CompletionFailed,
4964                    ))
4965                }
4966                Err(_) => {
4967                    let accepted = if registration.retain_on_drop {
4968                        registration.disarm();
4969                        self.pending_accepted(key).unwrap_or(true)
4970                    } else {
4971                        registration.remove_pending().unwrap_or(true)
4972                    };
4973                    if accepted {
4974                        // Removing the pending entry prevents an explicit cancel
4975                        // from queueing afterward. If it won that race, its sent
4976                        // state is already visible and the deadline sends nothing.
4977                        let cancel_sent = registration.unary_cancel.as_ref().is_some_and(|cancel| cancel.sent());
4978                        if !cancel_sent && self.lock_inner().wire_slots.contains_key(&key) {
4979                            self.send_cancel(RouteHandle::new(key.channel, key.epoch, key.generation), key.corr, Priority::Interactive);
4980                        }
4981                        self.spawn_liveness_probe();
4982                    }
4983                    Err(classify_failure(
4984                        accepted,
4985                        format!("request on channel {channel} timed out at its deadline"),
4986                        OutcomeUnknownCause::Deadline,
4987                    ))
4988                }
4989            },
4990            () = self.close_token.cancelled() => {
4991                let accepted = registration.remove_pending().unwrap_or(true);
4992                Err(classify_failure(accepted, "consumer closed while request was pending", OutcomeUnknownCause::ConsumerClosed))
4993            }
4994        }
4995    }
4996
4997    /// Probe a connection retained after an accepted request reaches its reply deadline.
4998    ///
4999    /// Deadline timeouts deliberately keep a connection because scheduler pressure can delay
5000    /// an otherwise healthy reply. A channel-0 Ping plus any later inbound frame separates that
5001    /// case from a half-open socket, which would otherwise pin every subsequent request.
5002    fn spawn_liveness_probe(self: &Arc<Self>) {
5003        if self.liveness_probe_running.swap(true, Ordering::AcqRel) {
5004            return;
5005        }
5006
5007        let allocation = {
5008            let mut inner = self.lock_inner();
5009            // A pending CHANNEL-0 request suspends the probe: the daemon's
5010            // connection loop is FIFO and some channel-0 handlers park it
5011            // inline for seconds (route.open awaits the module bind ack for up
5012            // to route_bind_relay_timeout, ~12s in production), during which
5013            // our Ping sits unread in the daemon's socket buffer. Silence is
5014            // then explained by our own control op, and convicting would tear
5015            // down a healthy connection mid-bind. The gate is local knowledge
5016            // (we always know our own pendings) and re-arms on the next
5017            // deadline settle; the same check runs again before conviction.
5018            let control_pending = inner
5019                .pending
5020                .keys()
5021                .any(|key| key.generation == inner.generation && key.channel == 0);
5022            if inner.closed || control_pending || !matches!(&inner.reconnect, ReconnectState::Idle)
5023            {
5024                None
5025            } else {
5026                match (inner.next_corr, inner.writer.clone()) {
5027                    (Some(corr), Some(writer)) => {
5028                        inner.next_corr = corr.checked_add(1);
5029                        Some((inner.generation, corr, writer))
5030                    }
5031                    (None, _) | (_, None) => None,
5032                }
5033            }
5034        };
5035        let Some((generation, corr, writer)) = allocation else {
5036            self.liveness_probe_running.store(false, Ordering::Release);
5037            return;
5038        };
5039
5040        let t0 = epoch_millis();
5041        let ping = match Frame::build(
5042            FrameType::Ping,
5043            Flags::new(false, Priority::Interactive, false),
5044            0,
5045            0,
5046            corr,
5047            Vec::new(),
5048        ) {
5049            Ok(ping) => ping,
5050            Err(_) => {
5051                self.liveness_probe_running.store(false, Ordering::Release);
5052                return;
5053            }
5054        };
5055        let window = self.opts.liveness_probe_window;
5056        let shared = Arc::clone(self);
5057        tokio::spawn(async move {
5058            let window_end = Instant::now() + window;
5059            // A write failure proves nothing in the healthy direction: it may be the
5060            // first sign of the same broken transport. Let the inbound window decide.
5061            let _ = timeout_at(
5062                window_end,
5063                writer.send(WriteCommand {
5064                    frame: ping,
5065                    pending: None,
5066                }),
5067            )
5068            .await;
5069            sleep_until(window_end).await;
5070
5071            let control_pending_now = {
5072                let inner = shared.lock_inner();
5073                inner
5074                    .pending
5075                    .keys()
5076                    .any(|key| key.generation == generation && key.channel == 0)
5077            };
5078            if !shared.close_token.is_cancelled()
5079                && !control_pending_now // a control op begun during the window explains the silence
5080                && shared.generation_is_current(generation)
5081                && shared.last_inbound_ms.load(Ordering::Acquire) < t0
5082            {
5083                shared.handle_generation_drop(
5084                    generation,
5085                    format!(
5086                        "liveness probe convicted a half-open socket: no inbound frame for {}ms after a channel-0 Ping",
5087                        window.as_millis()
5088                    ),
5089                );
5090            }
5091            shared
5092                .liveness_probe_running
5093                .store(false, Ordering::Release);
5094        });
5095    }
5096
5097    async fn send_subscription(
5098        self: &Arc<Self>,
5099        subscription: SubscriptionSend,
5100    ) -> Result<Subscription, CallError> {
5101        let SubscriptionSend {
5102            expected_handle,
5103            channel,
5104            epoch,
5105            body,
5106            priority,
5107            admission_class,
5108            event_buffer,
5109            deadline,
5110            permit,
5111        } = subscription;
5112        if Instant::now() >= deadline {
5113            return Err(CallError::not_sent(
5114                "subscription deadline elapsed before request was sent",
5115            ));
5116        }
5117        let (generation, corr, writer) = {
5118            let mut inner = self.lock_inner();
5119            if inner.closed {
5120                return Err(CallError::not_sent("consumer closed"));
5121            }
5122            let generation = inner.generation;
5123            if let Some(expected) = expected_handle {
5124                if expected.connection_token() != generation
5125                    || expected.channel != channel
5126                    || expected.epoch != epoch
5127                    || inner.route_epochs.get(&channel) != Some(&expected)
5128                    || inner.retired_routes.contains(&expected)
5129                {
5130                    return Err(CallError::StaleRouteHandle(expected));
5131                }
5132            }
5133            let Some(writer) = inner.writer.clone() else {
5134                return Err(CallError::not_sent("subc connection is down before send"));
5135            };
5136            let Some(corr) = inner.next_corr else {
5137                drop(inner);
5138                self.handle_generation_drop(
5139                    generation,
5140                    "correlation allocator exhausted".to_string(),
5141                );
5142                return Err(CallError::not_sent(
5143                    "correlation allocator exhausted; connection closed",
5144                ));
5145            };
5146            inner.next_corr = corr.checked_add(1);
5147            (generation, corr, writer)
5148        };
5149
5150        // Mark held subscriptions so module drains leave them out of the quiescence wait.
5151        let frame = Frame::build(
5152            FrameType::Request,
5153            Flags(
5154                Flags::new(false, priority, false)
5155                    .with_admission_class(admission_class)
5156                    .0
5157                    | FLAG_SUBSCRIPTION,
5158            ),
5159            channel,
5160            epoch,
5161            corr,
5162            body,
5163        )
5164        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
5165        let key = PendingKey {
5166            generation,
5167            channel,
5168            epoch,
5169            corr,
5170        };
5171        let position = Arc::new(SubscriptionPosition {
5172            key: Mutex::new(key),
5173            stop: CancellationToken::new(),
5174        });
5175        let retry = permit.opted_in().then(|| SubscriptionRetry {
5176            frame: frame.clone(),
5177            deadline,
5178            delay: Duration::from_millis(25),
5179            position: Arc::clone(&position),
5180        });
5181        let (events_tx, events_rx) = mpsc::channel(event_buffer.max(1));
5182        let (closed_tx, closed_rx) = oneshot::channel();
5183        let (ended_tx, ended_rx) = watch::channel(None);
5184        {
5185            let mut inner = self.lock_inner();
5186            if inner.closed || inner.generation != generation || inner.writer.is_none() {
5187                return Err(CallError::not_sent(
5188                    "connection changed before subscription registration",
5189                ));
5190            }
5191            if let Some(expected) = expected_handle {
5192                if inner.route_epochs.get(&expected.channel) != Some(&expected)
5193                    || inner.retired_routes.contains(&expected)
5194                {
5195                    return Err(CallError::StaleRouteHandle(expected));
5196                }
5197            }
5198            if permit.opted_in() {
5199                inner.wire_slots.insert(key, Arc::clone(&permit));
5200            }
5201            let mut entry =
5202                PendingEntry::subscription(events_tx, closed_tx, ended_tx, permit, priority);
5203            entry.retry = retry;
5204            inner.pending.insert(key, entry);
5205        }
5206        let mut registration = PendingRegistration::new(Arc::clone(self), key, false);
5207
5208        match timeout_at(
5209            deadline,
5210            writer.send(WriteCommand {
5211                frame,
5212                pending: Some(key),
5213            }),
5214        )
5215        .await
5216        {
5217            Ok(Ok(())) => {}
5218            Ok(Err(_)) => {
5219                let accepted = registration.remove_pending().unwrap_or(false);
5220                return Err(classify_failure(
5221                    accepted,
5222                    "writer task closed before accepting subscription request",
5223                    OutcomeUnknownCause::WriterClosed,
5224                ));
5225            }
5226            Err(_) => {
5227                let accepted = registration.remove_pending().unwrap_or(false);
5228                return Err(classify_failure_with_not_sent_cause(
5229                    accepted,
5230                    "subscription deadline elapsed waiting for writer capacity",
5231                    OutcomeUnknownCause::Deadline,
5232                    NotSentCause::WriterCapacity,
5233                ));
5234            }
5235        }
5236
5237        registration.disarm();
5238        Ok(Subscription {
5239            events: events_rx,
5240            closed: SubscriptionClosed { rx: closed_rx },
5241            ended: ended_rx,
5242            cancel: SubscriptionCancel::new(Arc::clone(self), position, priority),
5243        })
5244    }
5245
5246    fn unsubscribe_subscription(
5247        &self,
5248        position: &SubscriptionPosition,
5249        priority: Priority,
5250    ) -> Result<(), CallError> {
5251        let key = *position.key.lock().unwrap_or_else(|err| err.into_inner());
5252        let handle = RouteHandle::new(key.channel, key.epoch, key.generation);
5253        self.validate_current_handle(handle)?;
5254        let (key, entry) = {
5255            let mut inner = self.lock_inner();
5256            let key = *position.key.lock().unwrap_or_else(|err| err.into_inner());
5257            position.stop.cancel();
5258            let entry = inner.pending.remove(&key);
5259            if entry.as_ref().is_some_and(|entry| !entry.accepted) {
5260                if let Some(slot) = inner.wire_slots.remove(&key) {
5261                    slot.release();
5262                }
5263            }
5264            // Keep retired-route ingress until its advisory Cancel is queued.
5265            (key, entry)
5266        };
5267        if let Some(entry) = entry {
5268            let should_cancel = entry.accepted || entry.retry.is_none();
5269            entry.settle_subscription_result(Ok(()));
5270            if should_cancel {
5271                self.send_cancel(handle, key.corr, priority);
5272            }
5273            self.lock_inner().reap_retired_route(handle);
5274        }
5275        Ok(())
5276    }
5277
5278    fn route_stream_data(&self, key: PendingKey, body: Vec<u8>) {
5279        let overflow = {
5280            let mut inner = self.lock_inner();
5281            let Some(entry) = inner.pending.get(&key) else {
5282                return;
5283            };
5284            match entry.try_send_stream_data(body) {
5285                Ok(()) | Err(StreamDataDelivery::NotSubscription) => return,
5286                Err(StreamDataDelivery::Full) => {
5287                    let priority = entry
5288                        .subscription_priority()
5289                        .unwrap_or(Priority::Interactive);
5290                    let entry = inner.pending.remove(&key);
5291                    entry.map(|entry| {
5292                        (
5293                            entry,
5294                            priority,
5295                            "subscription event channel filled; reader dropped the stream instead of blocking",
5296                        )
5297                    })
5298                }
5299                Err(StreamDataDelivery::Closed) => {
5300                    let priority = entry
5301                        .subscription_priority()
5302                        .unwrap_or(Priority::Interactive);
5303                    let entry = inner.pending.remove(&key);
5304                    entry.map(|entry| {
5305                        (
5306                            entry,
5307                            priority,
5308                            "subscription event receiver closed before the stream ended",
5309                        )
5310                    })
5311                }
5312            }
5313        };
5314
5315        if let Some((entry, priority, reason)) = overflow {
5316            entry.settle_call_error(CallError::subscription_backpressure(reason));
5317            self.send_cancel(
5318                RouteHandle::new(key.channel, key.epoch, key.generation),
5319                key.corr,
5320                priority,
5321            );
5322            self.lock_inner().reap_retired_route(RouteHandle::new(
5323                key.channel,
5324                key.epoch,
5325                key.generation,
5326            ));
5327        }
5328    }
5329
5330    fn register_push_events(
5331        &self,
5332        handle: RouteHandle,
5333    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
5334        let (events_tx, events_rx) = mpsc::channel(DEFAULT_PUSH_EVENT_BUFFER);
5335        let mut inner = self.lock_inner();
5336        if inner.closed
5337            || inner.generation != handle.connection_token()
5338            || inner.writer.is_none()
5339            || inner.route_epochs.get(&handle.channel) != Some(&handle)
5340        {
5341            return Err(CallError::StaleRouteHandle(handle));
5342        }
5343        inner.push_event_receivers.insert(handle, events_tx);
5344        Ok(events_rx)
5345    }
5346
5347    fn route_push(&self, handle: RouteHandle, body: Vec<u8>) {
5348        let should_count_drop = {
5349            let mut inner = self.lock_inner();
5350            if inner.closed
5351                || inner.generation != handle.connection_token()
5352                || inner.route_epochs.get(&handle.channel) != Some(&handle)
5353            {
5354                // Deliberately uncounted: a push against a stale epoch or dead
5355                // generation has no live subscriber by definition, and the
5356                // counters below claim delivery loss on LIVE routes only.
5357                return;
5358            }
5359            match inner.push_event_receivers.get(&handle) {
5360                None => DroppedPush::NoReceiver,
5361                Some(events) => match events.try_send(PushEvent { handle, body }) {
5362                    Ok(()) => DroppedPush::Delivered,
5363                    Err(mpsc::error::TrySendError::Closed(_)) => {
5364                        inner.push_event_receivers.remove(&handle);
5365                        DroppedPush::NoReceiver
5366                    }
5367                    // A burst KEEPS the subscription (issue #40). This used to
5368                    // remove the receiver -- documented as loss-signaling via
5369                    // recv()->None -- but the fleet's real push consumers are
5370                    // idempotent wake nudges, where one missed event costs a
5371                    // poll cycle and a lost subscription costs every later wake
5372                    // until a re-register path that history says is where bugs
5373                    // live. Matches control_push below; the drop is counted on
5374                    // its own counter so a too-slow consumer is diagnosable as
5375                    // such rather than filed under "never subscribed".
5376                    Err(mpsc::error::TrySendError::Full(_)) => DroppedPush::ReceiverFull,
5377                },
5378            }
5379        };
5380        match should_count_drop {
5381            DroppedPush::Delivered => {}
5382            DroppedPush::NoReceiver => {
5383                self.pushes_dropped_no_receiver
5384                    .fetch_add(1, Ordering::Relaxed);
5385            }
5386            DroppedPush::ReceiverFull => {
5387                self.pushes_dropped_receiver_full
5388                    .fetch_add(1, Ordering::Relaxed);
5389            }
5390        }
5391    }
5392
5393    /// Deliver a daemon-originated channel-0 control push to the registered
5394    /// consumer receiver, or count the drop. Never blocks the reader.
5395    fn control_push(&self, body: &[u8]) {
5396        let parsed = serde_json::from_slice::<serde_json::Value>(body)
5397            .ok()
5398            .and_then(|value| {
5399                let op = value.get("op")?.as_str()?.to_string();
5400                Some(ControlPush { op, body: value })
5401            });
5402        let delivered = match parsed {
5403            None => false,
5404            Some(push) => {
5405                let mut inner = self.lock_inner();
5406                inner.record_route_end(&push);
5407                match inner.control_push_receiver.as_ref() {
5408                    None => false,
5409                    Some(sender) => match sender.try_send(push) {
5410                        Ok(()) => true,
5411                        Err(mpsc::error::TrySendError::Closed(_)) => {
5412                            inner.control_push_receiver = None;
5413                            false
5414                        }
5415                        Err(mpsc::error::TrySendError::Full(_)) => false,
5416                    },
5417                }
5418            }
5419        };
5420        if !delivered {
5421            self.control_pushes_dropped.fetch_add(1, Ordering::Relaxed);
5422        }
5423    }
5424
5425    fn send_cancel(&self, handle: RouteHandle, corr: u64, priority: Priority) {
5426        let writer = {
5427            let inner = self.lock_inner();
5428            if inner.closed
5429                || inner.generation != handle.connection_token()
5430                || !route_is_installed(&inner, handle)
5431            {
5432                return;
5433            }
5434            inner.writer.clone()
5435        };
5436        let Some(writer) = writer else {
5437            return;
5438        };
5439        let Ok(frame) = Frame::build(
5440            FrameType::Cancel,
5441            Flags::new(false, priority, false),
5442            handle.channel,
5443            handle.epoch,
5444            corr,
5445            Vec::new(),
5446        ) else {
5447            return;
5448        };
5449        let _ = writer.try_send(WriteCommand {
5450            frame,
5451            pending: None,
5452        });
5453    }
5454
5455    fn mark_pending_accepted(&self, key: PendingKey) -> bool {
5456        let mut inner = self.lock_inner();
5457        if inner.closed || inner.generation != key.generation {
5458            return false;
5459        }
5460        let Some(entry) = inner.pending.get_mut(&key) else {
5461            return false;
5462        };
5463        if entry
5464            .send_deadline
5465            .is_some_and(|deadline| Instant::now() >= deadline)
5466        {
5467            let entry = inner.remove_pending(&key).unwrap();
5468            drop(inner);
5469            entry.settle_call_error(CallError::not_sent_with_cause(
5470                "call deadline elapsed before request was sent",
5471                NotSentCause::WriterRejected,
5472            ));
5473            return false;
5474        }
5475        entry.accepted = true;
5476        true
5477    }
5478
5479    fn settle_pending(self: &Arc<Self>, key: PendingKey, terminal: PendingTerminal) {
5480        let (entry, retry) = {
5481            let mut inner = self.lock_inner();
5482            let entry = inner.remove_pending(&key);
5483            let slot = inner.wire_slots.remove(&key);
5484            let busy = matches!(&terminal, PendingTerminal::Error { body, flags }
5485                if error_codes::is_route_busy_retryable(*flags, &body.code, slot.as_ref().is_some_and(|slot| slot.opted_in())))
5486                && entry
5487                    .as_ref()
5488                    .is_some_and(|entry| !entry.completion_is_closed());
5489            if let Some(slot) = slot {
5490                if !busy {
5491                    slot.release();
5492                }
5493            }
5494            if busy && entry.as_ref().is_some_and(|entry| entry.retry.is_some()) {
5495                let mut entry = entry.unwrap();
5496                entry.accepted = false;
5497                let retry = entry.retry.clone();
5498                inner.pending.insert(key, entry);
5499                (None, retry)
5500            } else {
5501                inner.reap_retired_route(RouteHandle::new(key.channel, key.epoch, key.generation));
5502                (entry, None)
5503            }
5504        };
5505        if let Some(retry) = retry {
5506            let shared = Arc::clone(self);
5507            tokio::spawn(async move {
5508                shared.retry_subscription(key, retry, terminal).await;
5509            });
5510            return;
5511        }
5512        let Some(entry) = entry else {
5513            return;
5514        };
5515        if entry.retain_late_route_open && entry.completion_is_closed() {
5516            if let PendingTerminal::Response {
5517                generation, body, ..
5518            } = &terminal
5519            {
5520                if let Ok(ClientControlResponse::RouteOpen {
5521                    route_channel,
5522                    route_epoch,
5523                    ..
5524                }) = serde_json::from_slice::<ClientControlResponse>(body)
5525                {
5526                    let handle = RouteHandle::new(route_channel, route_epoch, *generation);
5527                    self.send_route_goodbye(handle, true);
5528                    self.uninstall_route_handle(handle);
5529                }
5530            }
5531            return;
5532        }
5533        entry.settle_terminal(key, terminal);
5534    }
5535
5536    fn pending_accepted(&self, key: PendingKey) -> Option<bool> {
5537        self.lock_inner()
5538            .pending
5539            .get(&key)
5540            .map(|entry| entry.accepted)
5541    }
5542
5543    fn handle_generation_drop(self: &Arc<Self>, generation: u64, reason: String) {
5544        self.handle_generation_drop_with_cause(
5545            generation,
5546            reason,
5547            OutcomeUnknownCause::ConnectionFailed,
5548        );
5549    }
5550
5551    fn handle_generation_drop_with_cause(
5552        self: &Arc<Self>,
5553        generation: u64,
5554        reason: String,
5555        cause: OutcomeUnknownCause,
5556    ) {
5557        let (should_emit, pending, callbacks) = {
5558            let mut inner = self.lock_inner();
5559            if inner.closed || inner.generation != generation || inner.writer.is_none() {
5560                return;
5561            }
5562            inner.writer = None;
5563            inner.restored_token = inner.restored_token.saturating_add(1);
5564            inner.close_routes();
5565            inner.route_epochs.clear();
5566            inner.route_modules.clear();
5567            inner.route_end_reasons.clear();
5568            inner.legacy_channel_reasons.clear();
5569            let pending = drain_pending_generation(&mut inner.pending, generation);
5570            // An opening belongs to its lead caller, not to a socket generation:
5571            // the caller may still be retrying after this transport is replaced.
5572            // Keep its waiters and close flag until its OpeningGuard finishes, so
5573            // a new caller cannot start a competing open for the same key.
5574            let callbacks = inner.callbacks.clone();
5575            (true, pending, callbacks)
5576        };
5577
5578        if should_emit {
5579            settle_route_pending_entries_with_cause(
5580                pending,
5581                reason.clone(),
5582                RouteEndReason::ConnectionLost,
5583                cause,
5584            );
5585            emit_callbacks(callbacks, ConnectionState::Dropped);
5586            self.notify.notify_waiters();
5587            let _ = self.spawn_reconnect(generation);
5588        }
5589    }
5590
5591    fn close_sync(&self, reason: &str) {
5592        let (pending, openings, routes, reader, writer, reconnect) = {
5593            let mut inner = self.lock_inner();
5594            if inner.closed {
5595                return;
5596            }
5597            inner.closed = true;
5598            // Disconnect releases every daemon route, including retirements
5599            // whose GOODBYEs are still waiting for writer capacity. Preserve
5600            // the best-effort shutdown send for retirements not yet reaped.
5601            let retirements = inner
5602                .retirement_goodbyes
5603                .iter()
5604                .copied()
5605                .collect::<Vec<_>>();
5606            for handle in retirements {
5607                inner.queue_retirement_goodbye(handle);
5608            }
5609            inner.writer = None;
5610            inner.route_epochs.clear();
5611            inner.route_modules.clear();
5612            inner.route_end_reasons.clear();
5613            inner.legacy_channel_reasons.clear();
5614            inner.push_event_receivers.clear();
5615            self.close_token.cancel();
5616            let reconnect = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
5617                ReconnectState::Background { task, .. } => Some(task),
5618                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
5619            };
5620            (
5621                inner
5622                    .pending
5623                    .drain()
5624                    .map(|(_, entry)| entry)
5625                    .collect::<Vec<_>>(),
5626                inner
5627                    .openings
5628                    .drain()
5629                    .map(|(_, opening)| opening.waiters)
5630                    .collect::<Vec<_>>(),
5631                inner.drain_routes(),
5632                inner.reader_task.take(),
5633                inner.writer_task.take(),
5634                reconnect,
5635            )
5636        };
5637        for route in routes {
5638            route.close();
5639        }
5640        if let Some(handle) = reader {
5641            handle.abort();
5642        }
5643        if let Some(mut handle) = writer {
5644            // Let already queued GOODBYEs reach the socket, but never leave
5645            // a writer blocked on an unresponsive peer alive after close.
5646            if let Ok(runtime) = tokio::runtime::Handle::try_current() {
5647                runtime.spawn(async move {
5648                    if tokio::time::timeout(Duration::from_millis(250), &mut handle)
5649                        .await
5650                        .is_err()
5651                    {
5652                        handle.abort();
5653                    }
5654                });
5655            } else {
5656                handle.abort();
5657            }
5658        }
5659        if let Some(handle) = reconnect {
5660            handle.abort();
5661        }
5662        settle_pending_entries(pending, reason.to_string());
5663        fail_openings(openings, SharedCallFailure::not_sent(reason.to_string()));
5664        self.notify.notify_waiters();
5665    }
5666
5667    fn validate_current_handle(&self, handle: RouteHandle) -> Result<(), CallError> {
5668        let inner = self.lock_inner();
5669        if inner.closed
5670            || inner.generation != handle.connection_token()
5671            || inner.writer.is_none()
5672            || !route_is_installed(&inner, handle)
5673        {
5674            Err(CallError::StaleRouteHandle(handle))
5675        } else {
5676            Ok(())
5677        }
5678    }
5679
5680    fn route_state(&self, handle: RouteHandle) -> Result<RouteState, CallError> {
5681        let inner = self.lock_inner();
5682        if inner.closed
5683            || inner.generation != handle.connection_token()
5684            || inner.writer.is_none()
5685            || inner.route_epochs.get(&handle.channel) != Some(&handle)
5686        {
5687            return Err(CallError::StaleRouteHandle(handle));
5688        }
5689
5690        let route = inner
5691            .route_by_channel
5692            .get(&handle.channel)
5693            .and_then(|key| inner.routes.get(key))
5694            .or_else(|| inner.one_shot_routes.get(&handle.channel));
5695        debug_assert!(route.is_none_or(|route| route.handle == handle));
5696        route
5697            .filter(|route| route.handle == handle)
5698            .cloned()
5699            .ok_or(CallError::StaleRouteHandle(handle))
5700    }
5701
5702    fn route_is_current(&self, key: &RouteKey, route: &RouteState) -> bool {
5703        let inner = self.lock_inner();
5704        if inner.closed
5705            || inner.generation != route.handle.connection_token()
5706            || inner.writer.is_none()
5707        {
5708            return false;
5709        }
5710        inner.routes.get(key).is_some_and(|cached| {
5711            cached.handle == route.handle && Arc::ptr_eq(&cached.sem, &route.sem)
5712        })
5713    }
5714
5715    fn invalidate_route(&self, key: &RouteKey, expected_handle: Option<RouteHandle>) {
5716        self.invalidate_route_with_deadline(key, expected_handle, false);
5717    }
5718
5719    /// An accepted call's response deadline cannot prove non-delivery, so it
5720    /// must not trigger a resend. Retiring its route instead lets the next call
5721    /// recover even when the connection-wide Ping still succeeds. A module that
5722    /// is merely slower than the deadline makes the next call open a fresh
5723    /// route. Calls already pending on the retired route still receive their
5724    /// replies until they settle.
5725    fn invalidate_route_with_deadline(
5726        &self,
5727        key: &RouteKey,
5728        expected_handle: Option<RouteHandle>,
5729        response_deadline_expired: bool,
5730    ) {
5731        let removed = {
5732            let mut inner = self.lock_inner();
5733            match inner.routes.get(key) {
5734                Some(route) if expected_handle.is_none_or(|expected| expected == route.handle) => {
5735                    let removed = inner.evict_route(key);
5736                    if let Some(route) = &removed {
5737                        // Eviction stops new calls, but siblings may already be
5738                        // executing or awaiting their own refusal. Keep ingress
5739                        // until those pending entries settle; never resend them
5740                        // merely because another call was refused.
5741                        inner.retired_routes.insert(route.handle);
5742                        if response_deadline_expired {
5743                            inner.retirement_goodbyes.insert(route.handle);
5744                            // Closing this route releases slots retained for outstanding calls.
5745                            // A module that never answers must not block the route's GOODBYE.
5746                            inner.release_wire_slots(route.handle);
5747                            let pending_calls = inner
5748                                .pending
5749                                .keys()
5750                                .filter(|pending| {
5751                                    pending.generation == route.handle.connection_token()
5752                                        && pending.channel == route.handle.channel
5753                                        && pending.epoch == route.handle.epoch
5754                                })
5755                                .count();
5756                            tracing::warn!(
5757                                target_module = %key.target_label(),
5758                                channel = route.handle.channel,
5759                                epoch = route.handle.epoch,
5760                                pending_calls,
5761                                "retiring route after call response deadline"
5762                            );
5763                        }
5764                        inner.reap_retired_route(route.handle);
5765                    }
5766                    removed
5767                }
5768                _ => None,
5769            }
5770        };
5771        if let Some(route) = removed {
5772            route.close();
5773        }
5774    }
5775
5776    fn finish_opening(&self, key: &RouteKey, result: Result<RouteState, SharedCallFailure>) {
5777        let opening = self.lock_inner().openings.remove(key);
5778        for waiter in opening.map(|o| o.waiters).unwrap_or_default() {
5779            let _ = waiter.send(result.clone());
5780        }
5781    }
5782
5783    async fn close_handle(
5784        self: &Arc<Self>,
5785        handle: RouteHandle,
5786        opts: &CloseRouteOptions,
5787    ) -> Result<(), CallError> {
5788        self.validate_current_handle(handle)?;
5789        let route = {
5790            let mut inner = self.lock_inner();
5791            inner.route_end_reasons.insert(
5792                handle.channel,
5793                (RouteEndReason::ClosedByCaller.into(), true),
5794            );
5795            inner.remove_route_by_handle(handle)
5796        };
5797        let mut closing = RouteCloseGuard::new(
5798            Arc::clone(self),
5799            handle,
5800            route,
5801            "route closed by close_handle",
5802        );
5803        if opts.drain {
5804            self.drain_channel(handle, opts.drain_timeout).await;
5805        }
5806        closing.close_pending();
5807        self.queue_route_goodbye(handle).await;
5808        closing.finish();
5809        Ok(())
5810    }
5811
5812    /// Tear down one route by key. See [`SubcConsumer::close_route`].
5813    async fn close_route(self: &Arc<Self>, key: &RouteKey, opts: &CloseRouteOptions) {
5814        // Under the lock: flip the close-beats-reopen flag on any in-flight open for
5815        // this key (so a lead-opener whose channel hasn't been cached yet refuses to
5816        // install it), and remove the cached route if one exists.
5817        let route = {
5818            let mut inner = self.lock_inner();
5819            if let Some(opening) = inner.openings.get_mut(key) {
5820                opening.closed = true;
5821            }
5822            let route = inner.remove_route(key);
5823            if let Some(route) = &route {
5824                inner.route_end_reasons.insert(
5825                    route.handle.channel,
5826                    (RouteEndReason::ClosedByCaller.into(), true),
5827                );
5828            }
5829            route
5830        };
5831
5832        // Nothing cached: either never opened (idempotent no-op) or still opening (the
5833        // racing lead-opener will see the flag and GOODBYE whatever channel it opens).
5834        let Some(route) = route else {
5835            return;
5836        };
5837        let handle = route.handle;
5838        let mut closing = RouteCloseGuard::new(
5839            Arc::clone(self),
5840            handle,
5841            Some(route),
5842            "route closed by close_route",
5843        );
5844
5845        if opts.drain {
5846            // Wait for in-flight UNARY requests on this channel to settle naturally,
5847            // bounded by drain_timeout, before tearing the route down.
5848            self.drain_channel(handle, opts.drain_timeout).await;
5849        }
5850
5851        // Closing the semaphore makes any not-yet-sent acquire() return Err -> the
5852        // caller classifies it NotSent. Already-sent pending requests are settled
5853        // at-most-once (OutcomeUnknown if the writer accepted their bytes).
5854        closing.close_pending();
5855
5856        // Fail pending requests and release their slots before waiting for the
5857        // writer. Keep the ingress handle installed until GOODBYE is queued,
5858        // preventing channel reuse from overtaking the old route's teardown.
5859        self.queue_route_goodbye(handle).await;
5860        closing.finish();
5861    }
5862
5863    fn uninstall_route_handle(&self, handle: RouteHandle) {
5864        let mut inner = self.lock_inner();
5865        inner.release_wire_slots(handle);
5866        inner.retired_routes.remove(&handle);
5867        inner.retirement_goodbyes.remove(&handle);
5868        if inner.route_epochs.get(&handle.channel) == Some(&handle) {
5869            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
5870            inner.route_targets.remove(&handle);
5871            inner.push_event_receivers.remove(&handle);
5872            release_reverse_request_registry(installed);
5873        }
5874    }
5875
5876    fn route_not_sent_error(&self, handle: RouteHandle) -> CallError {
5877        let inner = self.lock_inner();
5878        let reason = if inner.generation != handle.connection_token() || inner.writer.is_none() {
5879            RouteEndReason::ConnectionLost.into()
5880        } else {
5881            inner.route_end(handle.channel)
5882        };
5883        CallError::NotSent(Box::new(NotSentSource {
5884            message: "route flow-control semaphore closed".into(),
5885            cause: NotSentCause::BeforeQueue,
5886            never_forwarded: true,
5887            route_reason: Some(reason),
5888            refusal: None,
5889        }))
5890    }
5891
5892    /// Settle every pending request on this handle as OutcomeUnknown if the writer
5893    /// accepted its bytes, or NotSent otherwise, preserving the route ending cause.
5894    fn fail_channel_pending(
5895        &self,
5896        handle: RouteHandle,
5897        reason: &str,
5898        close_reason: RouteEndReason,
5899    ) {
5900        let entries = {
5901            let mut inner = self.lock_inner();
5902            inner.release_wire_slots(handle);
5903            inner
5904                .route_end_reasons
5905                .insert(handle.channel, (close_reason.clone().into(), true));
5906            drain_pending_handle(&mut inner.pending, handle, true)
5907        };
5908        settle_route_pending_entries(entries, reason.to_string(), close_reason);
5909    }
5910
5911    /// Resolve once every in-flight unary pending on `channel` has settled, or the
5912    /// timeout elapses. Polls the pending map (entries are removed on settle); the
5913    /// volume here is tiny (a route window is small) so a short poll is adequate.
5914    async fn drain_channel(&self, handle: RouteHandle, timeout: Duration) {
5915        let deadline = Instant::now() + timeout;
5916        loop {
5917            let has_inflight = {
5918                let inner = self.lock_inner();
5919                inner.pending.iter().any(|(key, entry)| {
5920                    key.generation == handle.connection_token()
5921                        && key.channel == handle.channel
5922                        && key.epoch == handle.epoch
5923                        && !entry.is_subscription()
5924                })
5925            };
5926            if !has_inflight || Instant::now() >= deadline {
5927                return;
5928            }
5929            sleep(Duration::from_millis(5)).await;
5930        }
5931    }
5932
5933    async fn queue_route_goodbye(self: &Arc<Self>, handle: RouteHandle) {
5934        let frame = Frame::build(
5935            FrameType::Goodbye,
5936            Flags::new(false, Priority::Interactive, false),
5937            handle.channel,
5938            handle.epoch,
5939            0,
5940            Vec::new(),
5941        )
5942        .expect("header-only route GOODBYE is valid");
5943        loop {
5944            let changed = self.notify.notified();
5945            tokio::pin!(changed);
5946            changed.as_mut().enable();
5947            let writer = {
5948                let inner = self.lock_inner();
5949                // A missing writer or changed generation means the connection
5950                // is dead: the daemon releases every route on that connection,
5951                // so no GOODBYE is needed. A removed handle was already closed.
5952                if inner.closed
5953                    || inner.generation != handle.connection_token()
5954                    || inner.route_epochs.get(&handle.channel) != Some(&handle)
5955                {
5956                    return;
5957                }
5958                let Some(writer) = inner.writer.clone() else {
5959                    return;
5960                };
5961                writer
5962            };
5963            // Request deadlines bound other awaited writes, but there is no
5964            // writer-stall timeout: a live connection must admit this teardown
5965            // before its caller can release route budget.
5966            tokio::select! {
5967                result = writer.reserve() => {
5968                    let Ok(permit) = result else {
5969                        self.handle_generation_drop(
5970                            handle.connection_token(),
5971                            "writer closed before route GOODBYE".into(),
5972                        );
5973                        return;
5974                    };
5975                    let inner = self.lock_inner();
5976                    if !inner.closed
5977                        && inner.generation == handle.connection_token()
5978                        && inner.writer.as_ref().is_some_and(|current| current.same_channel(&writer))
5979                        && inner.route_epochs.get(&handle.channel) == Some(&handle)
5980                    {
5981                        permit.send(WriteCommand { frame, pending: None });
5982                    }
5983                    return;
5984                }
5985                _ = &mut changed => {}
5986                _ = self.close_token.cancelled() => return,
5987            }
5988        }
5989    }
5990
5991    /// Queue a header-only route GOODBYE if `handle` is still live on this connection.
5992    /// Late successful route.open cleanup sets `close_on_failure`: orphan prevention then
5993    /// requires closing the connection when the GOODBYE cannot enter the writer queue.
5994    fn send_route_goodbye(self: &Arc<Self>, handle: RouteHandle, close_on_failure: bool) -> bool {
5995        let writer = {
5996            let inner = self.lock_inner();
5997            if inner.closed
5998                || inner.generation != handle.connection_token()
5999                || inner.route_epochs.get(&handle.channel) != Some(&handle)
6000            {
6001                return false;
6002            }
6003            inner.writer.clone()
6004        };
6005        let Some(writer) = writer else {
6006            return false;
6007        };
6008        let Ok(frame) = Frame::build(
6009            FrameType::Goodbye,
6010            Flags::new(false, Priority::Interactive, false),
6011            handle.channel,
6012            handle.epoch,
6013            0,
6014            Vec::new(),
6015        ) else {
6016            return false;
6017        };
6018        if writer
6019            .try_send(WriteCommand {
6020                frame,
6021                pending: None,
6022            })
6023            .is_ok()
6024        {
6025            return true;
6026        }
6027        if close_on_failure {
6028            self.handle_generation_drop(
6029                handle.connection_token(),
6030                "failed to queue late route.open cleanup GOODBYE".to_string(),
6031            );
6032        }
6033        false
6034    }
6035
6036    fn emit_connection_state(&self, state: ConnectionState) {
6037        let callbacks = self.lock_inner().callbacks.clone();
6038        emit_callbacks(callbacks, state);
6039    }
6040}
6041
6042#[derive(Clone, Copy)]
6043enum InstallKind {
6044    Initial,
6045    Reconnect,
6046}
6047
6048enum EnsureAction {
6049    Wait,
6050    Lead {
6051        generation: u64,
6052        stale_task: Option<JoinHandle<()>>,
6053    },
6054}
6055
6056/// The reconnect state is fenced by the generation whose transport failed. A
6057/// newer generation can replace an older attempt, and completion only changes
6058/// the state when its generation still owns the slot.
6059enum ReconnectState {
6060    Idle,
6061    Inline {
6062        generation: u64,
6063    },
6064    Background {
6065        generation: u64,
6066        task: JoinHandle<()>,
6067    },
6068}
6069
6070/// Outcome of the install decision after a route.open response arrives, taken under
6071/// the inner lock so a racing close_route is observed atomically.
6072enum RouteInstall {
6073    /// Install (or reuse) the cached route and return it.
6074    Cached(RouteState),
6075    /// Do not install. `closed` => a close_route won the race (GOODBYE + NotSent);
6076    /// otherwise the generation moved (retry the open).
6077    Discard { closed: bool },
6078}
6079
6080enum RouteOpenAction {
6081    Wait(oneshot::Receiver<Result<RouteState, SharedCallFailure>>),
6082    Lead,
6083}
6084
6085struct RouteOpenParams<'a> {
6086    target: &'a RouteTarget,
6087    identity: &'a BindIdentity,
6088    consumer_identity: &'a Option<ConsumerIdentity>,
6089    consumer_capabilities: &'a Option<Vec<String>>,
6090    /// Already normalized: an empty map is `None` here, as in the route key.
6091    role_versions: &'a Option<BTreeMap<String, String>>,
6092    reverse_requests: &'a ReverseRequestRegistry,
6093    /// The scope every route.open for this key asks to be admitted under, so a
6094    /// reopen after the route drops carries the same selector as the first open.
6095    scope: Option<&'a ScopeSelector>,
6096}
6097
6098struct CallAttemptHistory {
6099    never_forwarded: bool,
6100    sent: bool,
6101}
6102
6103struct RequestSend {
6104    expected_handle: Option<RouteHandle>,
6105    channel: u16,
6106    epoch: u32,
6107    body: Vec<u8>,
6108    binary: bool,
6109    priority: Priority,
6110    admission_class: AdmissionClass,
6111    deadline: Instant,
6112    retain_late_route_open: bool,
6113    route_open_reverse_requests: Option<ReverseRequestRegistry>,
6114}
6115
6116struct SubscriptionSend {
6117    expected_handle: Option<RouteHandle>,
6118    channel: u16,
6119    epoch: u32,
6120    body: Vec<u8>,
6121    priority: Priority,
6122    admission_class: AdmissionClass,
6123    event_buffer: usize,
6124    deadline: Instant,
6125    permit: Arc<RoutePermit>,
6126}
6127
6128struct SubscriptionPosition {
6129    key: Mutex<PendingKey>,
6130    stop: CancellationToken,
6131}
6132
6133#[derive(Clone)]
6134struct SubscriptionRetry {
6135    frame: Frame,
6136    deadline: Instant,
6137    delay: Duration,
6138    position: Arc<SubscriptionPosition>,
6139}
6140
6141struct RouteCloseGuard {
6142    shared: Arc<Shared>,
6143    handle: RouteHandle,
6144    route: Option<RouteState>,
6145    reason: &'static str,
6146    finished: bool,
6147}
6148
6149impl RouteCloseGuard {
6150    fn new(
6151        shared: Arc<Shared>,
6152        handle: RouteHandle,
6153        route: Option<RouteState>,
6154        reason: &'static str,
6155    ) -> Self {
6156        Self {
6157            shared,
6158            handle,
6159            route,
6160            reason,
6161            finished: false,
6162        }
6163    }
6164
6165    fn close_pending(&self) {
6166        if let Some(route) = &self.route {
6167            route.close();
6168        }
6169        self.shared
6170            .fail_channel_pending(self.handle, self.reason, RouteEndReason::ClosedByCaller);
6171    }
6172
6173    fn finish(&mut self) {
6174        self.shared.uninstall_route_handle(self.handle);
6175        self.finished = true;
6176    }
6177}
6178
6179impl Drop for RouteCloseGuard {
6180    fn drop(&mut self) {
6181        if self.finished {
6182            return;
6183        }
6184        // An abandoned drain must not leave requests or their in-flight permits
6185        // waiting on the caller. Retirement owns GOODBYE admission once the close is dropped.
6186        self.close_pending();
6187        let mut inner = self.shared.lock_inner();
6188        if inner.closed
6189            || inner.generation != self.handle.connection_token()
6190            || inner.writer.is_none()
6191            || inner.route_epochs.get(&self.handle.channel) != Some(&self.handle)
6192        {
6193            return;
6194        }
6195        inner.retired_routes.insert(self.handle);
6196        inner.retirement_goodbyes.insert(self.handle);
6197        // Reaping tries synchronous admission first; otherwise the connection's
6198        // FIFO flusher keeps the handle installed until its GOODBYE is queued.
6199        inner.reap_retired_route(self.handle);
6200    }
6201}
6202
6203struct OpeningGuard {
6204    shared: Arc<Shared>,
6205    key: RouteKey,
6206    finished: bool,
6207}
6208
6209impl OpeningGuard {
6210    fn new(shared: Arc<Shared>, key: RouteKey) -> Self {
6211        Self {
6212            shared,
6213            key,
6214            finished: false,
6215        }
6216    }
6217
6218    fn finish(&mut self, result: Result<RouteState, SharedCallFailure>) {
6219        self.shared.finish_opening(&self.key, result);
6220        self.finished = true;
6221    }
6222}
6223
6224impl Drop for OpeningGuard {
6225    fn drop(&mut self) {
6226        if !self.finished {
6227            self.shared.finish_opening(
6228                &self.key,
6229                Err(SharedCallFailure::not_sent(
6230                    "route.open future was cancelled",
6231                )),
6232            );
6233        }
6234    }
6235}
6236
6237struct InlineReconnectGuard {
6238    shared: Arc<Shared>,
6239    generation: u64,
6240    finished: bool,
6241}
6242
6243impl InlineReconnectGuard {
6244    fn new(shared: Arc<Shared>, generation: u64) -> Self {
6245        Self {
6246            shared,
6247            generation,
6248            finished: false,
6249        }
6250    }
6251
6252    fn finish(&mut self) {
6253        self.shared.finish_inline_reconnect(self.generation);
6254        self.finished = true;
6255    }
6256}
6257
6258impl Drop for InlineReconnectGuard {
6259    fn drop(&mut self) {
6260        if !self.finished {
6261            self.shared.finish_inline_reconnect(self.generation);
6262        }
6263    }
6264}
6265
6266#[derive(Clone)]
6267struct RouteState {
6268    handle: RouteHandle,
6269    sem: Arc<Semaphore>,
6270    watch_sem: Option<Arc<Semaphore>>,
6271    opted_in: bool,
6272}
6273
6274#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6275struct RouteKey {
6276    target: RouteTargetKey,
6277    harness: String,
6278    session: String,
6279    consumer_identity: Option<ConsumerIdentityKey>,
6280    consumer_capabilities: Option<ConsumerCapabilitiesKey>,
6281    /// The role versions the route was opened with; `None` for a route that
6282    /// declared none. Part of the key so a legacy route and a versioned one to
6283    /// the same target are never shared: the provider chose its wire shape
6284    /// from these at bind. A `BTreeMap` is already in canonical order.
6285    role_versions: Option<BTreeMap<String, String>>,
6286    /// The scope the route was admitted under; `None` for an unscoped route.
6287    /// Part of the key so a route bound to one session's scope (or one epoch
6288    /// of it) is never reused for another, nor for an unscoped caller.
6289    scope: Option<ScopeKey>,
6290}
6291
6292impl RouteKey {
6293    fn new(
6294        target: &RouteTarget,
6295        identity: &BindIdentity,
6296        consumer_identity: Option<&ConsumerIdentity>,
6297        consumer_capabilities: Option<&[String]>,
6298    ) -> Self {
6299        Self {
6300            target: RouteTargetKey::from(target),
6301            harness: identity.harness.clone(),
6302            session: identity.session.clone(),
6303            consumer_identity: consumer_identity.map(ConsumerIdentityKey::from),
6304            consumer_capabilities: consumer_capabilities.map(ConsumerCapabilitiesKey::from_slice),
6305            role_versions: None,
6306            scope: None,
6307        }
6308    }
6309
6310    fn with_role_versions(mut self, role_versions: Option<&BTreeMap<String, String>>) -> Self {
6311        self.role_versions = role_versions.cloned();
6312        self
6313    }
6314
6315    fn with_scope(mut self, scope: Option<&ScopeSelector>) -> Self {
6316        self.scope = scope.map(ScopeKey::from);
6317        self
6318    }
6319
6320    fn target_label(&self) -> String {
6321        match &self.target {
6322            RouteTargetKey::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
6323            RouteTargetKey::ManagementSurface { module_id } => {
6324                format!("management_surface:{module_id}")
6325            }
6326            RouteTargetKey::InternalService {
6327                module_id,
6328                service_id,
6329            } => format!("internal_service:{module_id}:{service_id}"),
6330        }
6331    }
6332}
6333
6334#[derive(Clone, Hash, PartialEq, Eq)]
6335struct ConsumerIdentityKey {
6336    module_id: String,
6337    launch_nonce: String,
6338}
6339
6340// Hand-written so the launch nonce is never printed. The nonce is the credential
6341// that attributes a connection to a supervised module, and a derived Debug would
6342// write it into any log line or panic message that formats this value. This key sits
6343// inside the route cache key, which is formatted in logs.
6344impl fmt::Debug for ConsumerIdentityKey {
6345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6346        f.debug_struct("ConsumerIdentityKey")
6347            .field("module_id", &self.module_id)
6348            .field(
6349                "launch_nonce",
6350                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
6351            )
6352            .finish()
6353    }
6354}
6355
6356impl From<&ConsumerIdentity> for ConsumerIdentityKey {
6357    fn from(value: &ConsumerIdentity) -> Self {
6358        Self {
6359            module_id: value.module_id.clone(),
6360            launch_nonce: value.launch_nonce.clone(),
6361        }
6362    }
6363}
6364
6365/// Every field of a [`ScopeSelector`], in hashable form.
6366#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6367struct ScopeKey {
6368    /// The owner principal as its JSON encoding. `Principal` is not `Hash`,
6369    /// and matching on its variants here would stop compiling when the
6370    /// protocol crate adds one; the tagged encoding is unique per principal.
6371    owner: String,
6372    scope_ref: String,
6373    scope_epoch: Option<u64>,
6374    bind_proof_digest: Option<[u8; 32]>,
6375}
6376
6377impl From<&ScopeSelector> for ScopeKey {
6378    fn from(value: &ScopeSelector) -> Self {
6379        Self {
6380            owner: serde_json::to_string(&value.owner)
6381                .unwrap_or_else(|_| format!("{:?}", value.owner)),
6382            scope_ref: value.scope_ref.clone(),
6383            scope_epoch: value.scope_epoch,
6384            bind_proof_digest: value
6385                .bind_proof
6386                .as_ref()
6387                .map(|proof| Sha256::digest(proof.as_bytes()).into()),
6388        }
6389    }
6390}
6391
6392#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6393struct ConsumerCapabilitiesKey {
6394    values: Vec<String>,
6395}
6396
6397impl ConsumerCapabilitiesKey {
6398    fn from_slice(values: &[String]) -> Self {
6399        let mut values = values.to_vec();
6400        values.sort();
6401        values.dedup();
6402        Self { values }
6403    }
6404}
6405
6406#[derive(Debug, Clone, Hash, PartialEq, Eq)]
6407enum RouteTargetKey {
6408    ToolProvider {
6409        module_id: String,
6410    },
6411    ManagementSurface {
6412        module_id: String,
6413    },
6414    InternalService {
6415        module_id: String,
6416        service_id: String,
6417    },
6418}
6419
6420impl From<&RouteTarget> for RouteTargetKey {
6421    fn from(value: &RouteTarget) -> Self {
6422        match value {
6423            RouteTarget::ToolProvider { module_id } => Self::ToolProvider {
6424                module_id: module_id.clone(),
6425            },
6426            RouteTarget::ManagementSurface { module_id } => Self::ManagementSurface {
6427                module_id: module_id.clone(),
6428            },
6429            RouteTarget::InternalService {
6430                module_id,
6431                service_id,
6432            } => Self::InternalService {
6433                module_id: module_id.clone(),
6434                service_id: service_id.clone(),
6435            },
6436        }
6437    }
6438}
6439
6440#[derive(Debug, Clone)]
6441struct SharedCallFailure {
6442    kind: FailureKind,
6443}
6444
6445impl SharedCallFailure {
6446    fn not_sent(message: impl Into<String>) -> Self {
6447        CallError::not_sent_with_cause(message, NotSentCause::RouteOpenAbandoned).into()
6448    }
6449
6450    fn into_call_error(self) -> CallError {
6451        match self.kind {
6452            FailureKind::NotSent(source) => CallError::NotSent(Box::new(source)),
6453            FailureKind::OutcomeUnknown(source) => CallError::outcome_unknown_source(source),
6454            FailureKind::DaemonTooOld(daemon_ver) => CallError::DaemonTooOld { daemon_ver },
6455        }
6456    }
6457}
6458
6459impl From<CallError> for SharedCallFailure {
6460    fn from(value: CallError) -> Self {
6461        match value {
6462            CallError::DaemonTooOld { daemon_ver } => Self {
6463                kind: FailureKind::DaemonTooOld(daemon_ver),
6464            },
6465            CallError::NotSent(err) => Self {
6466                kind: FailureKind::NotSent(
6467                    err.downcast_ref::<NotSentSource>()
6468                        .expect("crate-built route.open failure has a typed source")
6469                        .clone(),
6470                ),
6471            },
6472            CallError::OutcomeUnknown(err) => Self {
6473                kind: FailureKind::OutcomeUnknown(
6474                    err.downcast_ref::<OutcomeUnknownSource>()
6475                        .cloned()
6476                        .unwrap_or_else(|| OutcomeUnknownSource {
6477                            message: err.to_string(),
6478                            cause: OutcomeUnknownCause::CompletionFailed,
6479                            route_reason: None,
6480                        }),
6481                ),
6482            },
6483            CallError::Module(body) => Self {
6484                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
6485                    message: format!(
6486                        "unexpected module error during route.open: {} ({})",
6487                        body.code, body.message
6488                    ),
6489                    cause: OutcomeUnknownCause::CompletionFailed,
6490                    route_reason: None,
6491                }),
6492            },
6493            error @ CallError::RouteDead(_) => CallError::outcome_unknown(
6494                format!("unexpected established-route error during route.open: {error}"),
6495                OutcomeUnknownCause::CompletionFailed,
6496            )
6497            .into(),
6498            CallError::SubscriptionBackpressure(err) => Self {
6499                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
6500                    message: err.to_string(),
6501                    cause: OutcomeUnknownCause::CompletionFailed,
6502                    route_reason: None,
6503                }),
6504            },
6505            CallError::StaleRouteHandle(handle) => {
6506                CallError::not_sent(format!("stale route handle: {handle:?}")).into()
6507            }
6508            error @ (CallError::CapabilityUnprovided { .. }
6509            | CallError::CapabilityAmbiguous { .. }
6510            | CallError::InvalidCapabilityIdentifier { .. }) => {
6511                CallError::not_sent(error.to_string()).into()
6512            }
6513        }
6514    }
6515}
6516
6517#[derive(Debug, Clone)]
6518enum FailureKind {
6519    NotSent(NotSentSource),
6520    OutcomeUnknown(OutcomeUnknownSource),
6521    DaemonTooOld(String),
6522}
6523
6524#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
6525struct PendingKey {
6526    generation: u64,
6527    channel: u16,
6528    epoch: u32,
6529    corr: u64,
6530}
6531
6532struct PendingEntry {
6533    accepted: bool,
6534    send_deadline: Option<Instant>,
6535    retain_late_route_open: bool,
6536    expected_control_handle: Option<RouteHandle>,
6537    route_open_reverse_requests: Option<ReverseRequestRegistry>,
6538    route_open_module: Option<String>,
6539    retry: Option<SubscriptionRetry>,
6540    completion: PendingCompletion,
6541}
6542
6543enum PendingCompletion {
6544    Unary(oneshot::Sender<PendingResult>),
6545    Subscription {
6546        events: mpsc::Sender<Vec<u8>>,
6547        closed: oneshot::Sender<Result<(), CallError>>,
6548        ended: watch::Sender<Option<SubscriptionEnd>>,
6549        _permit: Arc<RoutePermit>,
6550        priority: Priority,
6551    },
6552}
6553
6554enum StreamDataDelivery {
6555    NotSubscription,
6556    Full,
6557    Closed,
6558}
6559
6560impl PendingEntry {
6561    fn unary(
6562        tx: oneshot::Sender<PendingResult>,
6563        retain_late_route_open: bool,
6564        expected_control_handle: Option<RouteHandle>,
6565        route_open_reverse_requests: Option<ReverseRequestRegistry>,
6566    ) -> Self {
6567        Self {
6568            accepted: false,
6569            send_deadline: None,
6570            retain_late_route_open,
6571            expected_control_handle,
6572            route_open_reverse_requests,
6573            route_open_module: None,
6574            retry: None,
6575            completion: PendingCompletion::Unary(tx),
6576        }
6577    }
6578
6579    fn subscription(
6580        events: mpsc::Sender<Vec<u8>>,
6581        closed: oneshot::Sender<Result<(), CallError>>,
6582        ended: watch::Sender<Option<SubscriptionEnd>>,
6583        permit: Arc<RoutePermit>,
6584        priority: Priority,
6585    ) -> Self {
6586        Self {
6587            accepted: false,
6588            send_deadline: None,
6589            retain_late_route_open: false,
6590            expected_control_handle: None,
6591            route_open_reverse_requests: None,
6592            route_open_module: None,
6593            retry: None,
6594            completion: PendingCompletion::Subscription {
6595                events,
6596                closed,
6597                ended,
6598                _permit: permit,
6599                priority,
6600            },
6601        }
6602    }
6603
6604    fn completion_is_closed(&self) -> bool {
6605        match &self.completion {
6606            PendingCompletion::Unary(tx) => tx.is_closed(),
6607            PendingCompletion::Subscription { closed, .. } => closed.is_closed(),
6608        }
6609    }
6610
6611    fn is_subscription(&self) -> bool {
6612        matches!(&self.completion, PendingCompletion::Subscription { .. })
6613    }
6614
6615    fn subscription_priority(&self) -> Option<Priority> {
6616        match &self.completion {
6617            PendingCompletion::Subscription { priority, .. } => Some(*priority),
6618            PendingCompletion::Unary(_) => None,
6619        }
6620    }
6621
6622    fn try_send_stream_data(&self, body: Vec<u8>) -> Result<(), StreamDataDelivery> {
6623        let PendingCompletion::Subscription { events, .. } = &self.completion else {
6624            return Err(StreamDataDelivery::NotSubscription);
6625        };
6626        events.try_send(body).map_err(|err| match err {
6627            mpsc::error::TrySendError::Full(_) => StreamDataDelivery::Full,
6628            mpsc::error::TrySendError::Closed(_) => StreamDataDelivery::Closed,
6629        })
6630    }
6631
6632    fn settle_failure(self, reason: String) {
6633        if let Some(retry) = &self.retry {
6634            retry.position.stop.cancel();
6635        }
6636        let err = classify_failure(self.accepted, reason, OutcomeUnknownCause::ConsumerClosed);
6637        match self.completion {
6638            PendingCompletion::Unary(tx) => {
6639                let _ = tx.send(PendingResult::CallError(err));
6640            }
6641            PendingCompletion::Subscription { closed, ended, .. } => {
6642                let _ = ended.send(Some(SubscriptionEnd::RouteClosed {
6643                    reason: RouteEndReason::ClosedByCaller,
6644                }));
6645                let _ = closed.send(Err(err));
6646            }
6647        }
6648    }
6649
6650    fn settle_call_error(self, err: CallError) {
6651        if let Some(retry) = &self.retry {
6652            retry.position.stop.cancel();
6653        }
6654        match self.completion {
6655            PendingCompletion::Unary(tx) => {
6656                let _ = tx.send(PendingResult::CallError(err));
6657            }
6658            PendingCompletion::Subscription { closed, ended, .. } => {
6659                let end = if let Some(reason) = err.close_reason() {
6660                    match reason {
6661                        RouteEndReason::ConnectionLost => SubscriptionEnd::ConnectionLost,
6662                        reason => SubscriptionEnd::RouteClosed {
6663                            reason: reason.clone(),
6664                        },
6665                    }
6666                } else if matches!(err, CallError::SubscriptionBackpressure(_)) {
6667                    SubscriptionEnd::Backpressure
6668                } else {
6669                    SubscriptionEnd::ConnectionLost
6670                };
6671                let _ = ended.send(Some(end));
6672                let _ = closed.send(Err(err));
6673            }
6674        }
6675    }
6676
6677    fn settle_subscription_result(self, result: Result<(), CallError>) {
6678        if let Some(retry) = &self.retry {
6679            retry.position.stop.cancel();
6680        }
6681        match self.completion {
6682            PendingCompletion::Subscription { closed, ended, .. } => {
6683                let _ = ended.send(Some(SubscriptionEnd::Cancelled));
6684                let _ = closed.send(result);
6685            }
6686            PendingCompletion::Unary(tx) => {
6687                let _ = tx.send(PendingResult::Failure {
6688                    accepted: self.accepted,
6689                    reason: "subscription cancel matched a unary request".to_string(),
6690                });
6691            }
6692        }
6693    }
6694}
6695
6696struct PendingRegistration {
6697    shared: Arc<Shared>,
6698    key: PendingKey,
6699    active: bool,
6700    retain_on_drop: bool,
6701    unary_cancel: Option<Arc<UnaryCancel>>,
6702}
6703
6704impl PendingRegistration {
6705    fn new(shared: Arc<Shared>, key: PendingKey, retain_on_drop: bool) -> Self {
6706        Self {
6707            shared,
6708            key,
6709            active: true,
6710            retain_on_drop,
6711            unary_cancel: None,
6712        }
6713    }
6714
6715    fn remove_pending(&mut self) -> Option<bool> {
6716        if !self.active {
6717            return None;
6718        }
6719        self.active = false;
6720        self.shared
6721            .lock_inner()
6722            .remove_pending(&self.key)
6723            .map(|entry| entry.accepted)
6724    }
6725
6726    fn disarm(&mut self) {
6727        self.active = false;
6728    }
6729}
6730
6731impl Drop for PendingRegistration {
6732    fn drop(&mut self) {
6733        if self.retain_on_drop {
6734            self.disarm();
6735        } else {
6736            let _ = self.remove_pending();
6737        }
6738    }
6739}
6740
6741enum PendingResult {
6742    Terminal(PendingTerminal),
6743    CallError(CallError),
6744    Failure { accepted: bool, reason: String },
6745}
6746
6747impl PendingResult {
6748    fn into_call_result(self) -> Result<TerminalFrame, CallError> {
6749        match self {
6750            Self::Terminal(terminal) => Ok(terminal.into_terminal_frame()),
6751            Self::CallError(err) => Err(err),
6752            Self::Failure { accepted, reason } => Err(classify_failure(
6753                accepted,
6754                reason,
6755                OutcomeUnknownCause::CompletionFailed,
6756            )),
6757        }
6758    }
6759}
6760
6761enum PendingTerminal {
6762    Response {
6763        generation: u64,
6764        body: Vec<u8>,
6765        flags: Flags,
6766    },
6767    Error {
6768        body: ErrorBody,
6769        flags: Flags,
6770    },
6771    StreamEnd,
6772}
6773
6774impl PendingTerminal {
6775    fn into_terminal_frame(self) -> TerminalFrame {
6776        match self {
6777            Self::Response {
6778                generation,
6779                body,
6780                flags,
6781            } => TerminalFrame::Response {
6782                generation,
6783                body,
6784                flags,
6785            },
6786            Self::Error { body, flags } => TerminalFrame::Error { body, flags },
6787            Self::StreamEnd => TerminalFrame::StreamEnd,
6788        }
6789    }
6790}
6791
6792#[derive(Debug)]
6793enum TerminalFrame {
6794    Response {
6795        generation: u64,
6796        body: Vec<u8>,
6797        flags: Flags,
6798    },
6799    Error {
6800        body: ErrorBody,
6801        flags: Flags,
6802    },
6803    StreamEnd,
6804}
6805
6806struct WriteCommand {
6807    frame: Frame,
6808    pending: Option<PendingKey>,
6809}
6810
6811trait ConsumerStream: AsyncRead + AsyncWrite + Unpin + Send {}
6812impl<T: AsyncRead + AsyncWrite + Unpin + Send> ConsumerStream for T {}
6813
6814struct OpenedConnection {
6815    stream: Box<dyn ConsumerStream>,
6816    daemon_origin_trusted: bool,
6817    daemon_ver: String,
6818}
6819
6820async fn open_connection(
6821    path: &Path,
6822    deadline: Duration,
6823    transport: ConsumerTransport,
6824    operator_candidates: Option<&[PathBuf]>,
6825) -> Result<OpenedConnection, ConsumerError> {
6826    let path = operator_candidates
6827        .map(crate::operator_app::owned_candidate)
6828        .unwrap_or(path);
6829    if transport == ConsumerTransport::Local {
6830        let read =
6831            connection_file::read_for_client_with_local_endpoint(path).map_err(|source| {
6832                ConsumerError::ConnectionFile {
6833                    path: path.to_path_buf(),
6834                    source,
6835                }
6836            })?;
6837        let endpoint = read
6838            .local_endpoint
6839            .ok_or_else(|| ConsumerError::NoEndpoint {
6840                path: path.to_path_buf(),
6841            })?;
6842        let label = match &endpoint {
6843            connection_file::LocalEndpoint::Unix { path } => path.display().to_string(),
6844            connection_file::LocalEndpoint::Pipe { name } => name.clone(),
6845            _ => "unsupported local endpoint".to_owned(),
6846        };
6847        crate::registration::check_consumer_dial()?;
6848        let mut stream =
6849            connect_local(&endpoint)
6850                .await
6851                .map_err(|source| ConsumerError::Connect {
6852                    path: path.to_path_buf(),
6853                    endpoint: label.clone(),
6854                    source,
6855                })?;
6856        authenticate_client(&mut stream, &read.info, deadline)
6857            .await
6858            .map_err(|source| ConsumerError::Auth {
6859                path: path.to_path_buf(),
6860                endpoint: label,
6861                source,
6862            })?;
6863        crate::registration::bind_consumer(&mut stream, deadline)
6864            .await
6865            .map_err(ConsumerError::claim)?;
6866        return Ok(OpenedConnection {
6867            stream,
6868            daemon_origin_trusted: trusts_daemon_origin(&read.info.daemon_ver),
6869            daemon_ver: read.info.daemon_ver,
6870        });
6871    }
6872    let conn =
6873        connection_file::read_for_client(path).map_err(|source| ConsumerError::ConnectionFile {
6874            path: path.to_path_buf(),
6875            source,
6876        })?;
6877    open_connection_with_info(path, &conn, deadline).await
6878}
6879
6880async fn connect_local(
6881    endpoint: &connection_file::LocalEndpoint,
6882) -> io::Result<Box<dyn ConsumerStream>> {
6883    match endpoint {
6884        #[cfg(unix)]
6885        connection_file::LocalEndpoint::Unix { path } => {
6886            Ok(Box::new(tokio::net::UnixStream::connect(path).await?))
6887        }
6888        #[cfg(windows)]
6889        connection_file::LocalEndpoint::Pipe { name } => Ok(Box::new(
6890            tokio::net::windows::named_pipe::ClientOptions::new().open(name)?,
6891        )),
6892        _ => Err(io::Error::new(
6893            io::ErrorKind::Unsupported,
6894            "unsupported local endpoint kind",
6895        )),
6896    }
6897}
6898
6899async fn open_connection_with_info(
6900    path: &Path,
6901    conn: &connection_file::ConnectionInfo,
6902    deadline: Duration,
6903) -> Result<OpenedConnection, ConsumerError> {
6904    let endpoint = conn
6905        .endpoints
6906        .first()
6907        .ok_or_else(|| ConsumerError::NoEndpoint {
6908            path: path.to_path_buf(),
6909        })?;
6910    let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
6911    crate::registration::check_consumer_dial()?;
6912    let mut stream = TcpStream::connect(&endpoint_label)
6913        .await
6914        .map_err(|source| ConsumerError::Connect {
6915            path: path.to_path_buf(),
6916            endpoint: endpoint_label.clone(),
6917            source,
6918        })?;
6919    // Consumers send a request and wait for its reply, so there is no following
6920    // write for Nagle to coalesce with -- it can only hold the request back until
6921    // an ACK returns. Both ends of the hop must disable it for either to help.
6922    //
6923    // Dropped rather than logged for the same reason as the module path: no logging
6924    // dependency here, and a socket too broken to take the option fails the
6925    // handshake on the next line with a typed error.
6926    let _ = stream.set_nodelay(true);
6927    authenticate_client(&mut stream, conn, deadline)
6928        .await
6929        .map_err(|source| ConsumerError::Auth {
6930            path: path.to_path_buf(),
6931            endpoint: endpoint_label,
6932            source,
6933        })?;
6934    crate::registration::bind_consumer(&mut stream, deadline)
6935        .await
6936        .map_err(ConsumerError::claim)?;
6937    Ok(OpenedConnection {
6938        stream: Box::new(stream),
6939        daemon_origin_trusted: trusts_daemon_origin(&conn.daemon_ver),
6940        daemon_ver: conn.daemon_ver.clone(),
6941    })
6942}
6943
6944fn dispatch_reverse_request(shared: &Arc<Shared>, frame: Frame, handle: RouteHandle) {
6945    let method = serde_json::from_slice::<serde_json::Value>(&frame.body)
6946        .ok()
6947        .and_then(|body| body.get("method")?.as_str().map(str::to_string));
6948    let method_family = method
6949        .as_deref()
6950        .and_then(|method| method.split('/').next())
6951        .filter(|family| !family.is_empty())
6952        .map(str::to_string);
6953    let handler = method_family.as_deref().and_then(|family| {
6954        route_reverse_request_registry(handle.reverse_request_registry_id())
6955            .ok()?
6956            .handler(family)
6957    });
6958    let generation = handle.connection_token();
6959    let shared = Arc::clone(shared);
6960
6961    tokio::spawn(async move {
6962        let (frame_type, body) = if let (Some(handler), Some(method)) = (handler, method) {
6963            let request_body = frame.body.clone();
6964            let corr = frame.header.corr;
6965            match tokio::spawn(async move {
6966                handler(request_body, ReverseRequestContext { corr, method }).await
6967            })
6968            .await
6969            {
6970                Ok(Ok(body)) => (FrameType::Response, body),
6971                Ok(Err(err)) => (
6972                    FrameType::Error,
6973                    serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, err.to_string()))
6974                        .unwrap_or_default(),
6975                ),
6976                Err(err) => (
6977                    FrameType::Error,
6978                    serde_json::to_vec(&ErrorBody::new(
6979                        REVERSE_REQUEST_UNHANDLED,
6980                        join_error_message(err),
6981                    ))
6982                    .unwrap_or_default(),
6983                ),
6984            }
6985        } else {
6986            let message = method_family.map_or_else(
6987                || "reverse request has no valid method".to_string(),
6988                |family| format!("no reverse-request handler is registered for {family}"),
6989            );
6990            (
6991                FrameType::Error,
6992                serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, message))
6993                    .unwrap_or_default(),
6994            )
6995        };
6996
6997        if shared.ingress_handle(generation, handle.channel, handle.epoch) != Some(handle) {
6998            return;
6999        }
7000        let reply = match Frame::build_with_version(
7001            frame.header.ver,
7002            frame_type,
7003            Flags::new(false, Priority::Interactive, false),
7004            handle.channel,
7005            handle.epoch,
7006            frame.header.corr,
7007            body,
7008        ) {
7009            Ok(reply) => reply,
7010            Err(_) => return,
7011        };
7012        let writer = shared.lock_inner().writer.clone();
7013        if let Some(writer) = writer {
7014            let _ = writer
7015                .send(WriteCommand {
7016                    frame: reply,
7017                    pending: None,
7018                })
7019                .await;
7020        }
7021    });
7022}
7023
7024fn join_error_message(error: tokio::task::JoinError) -> String {
7025    if !error.is_panic() {
7026        return error.to_string();
7027    }
7028    let payload = error.into_panic();
7029    if let Some(message) = payload.downcast_ref::<String>() {
7030        return message.clone();
7031    }
7032    if let Some(message) = payload.downcast_ref::<&str>() {
7033        return (*message).to_string();
7034    }
7035    "reverse-request handler panicked".to_string()
7036}
7037
7038async fn reader_loop<R: AsyncRead + Unpin>(shared: Arc<Shared>, mut reader: R, generation: u64) {
7039    loop {
7040        match read_frame(&mut reader).await {
7041            Ok(Some(frame)) => {
7042                if !dispatch_frame(&shared, generation, frame).await {
7043                    return;
7044                }
7045            }
7046            Ok(None) => {
7047                shared.handle_generation_drop(generation, "subc connection closed".to_string());
7048                return;
7049            }
7050            Err(err) => {
7051                shared.handle_generation_drop(generation, err.to_string());
7052                return;
7053            }
7054        }
7055    }
7056}
7057
7058async fn dispatch_frame(shared: &Arc<Shared>, generation: u64, frame: Frame) -> bool {
7059    if !shared.record_inbound_if_current(generation) {
7060        return false;
7061    }
7062    if frame.header.channel != 0
7063        && !shared.validate_ingress_handle(generation, frame.header.channel, frame.header.epoch)
7064    {
7065        return true;
7066    }
7067
7068    if frame.header.ty == FrameType::Request && frame.header.channel != 0 {
7069        if let Some(handle) =
7070            shared.ingress_handle(generation, frame.header.channel, frame.header.epoch)
7071        {
7072            dispatch_reverse_request(shared, frame, handle);
7073        }
7074        return true;
7075    }
7076
7077    let key = PendingKey {
7078        generation,
7079        channel: frame.header.channel,
7080        epoch: frame.header.epoch,
7081        corr: frame.header.corr,
7082    };
7083
7084    if frame.header.channel == 0 && frame.header.ty == FrameType::Response {
7085        if let Some(expected) = shared.pending_expected_control_handle(key) {
7086            let echoes_expected = matches!(
7087                serde_json::from_slice::<ClientControlResponse>(&frame.body),
7088                Ok(ClientControlResponse::RoutePoll {
7089                    route_channel,
7090                    route_epoch,
7091                    ..
7092                }) if route_channel == expected.channel && route_epoch == expected.epoch
7093            );
7094            if !echoes_expected {
7095                shared.count_dropped_route_frame();
7096                return true;
7097            }
7098        }
7099    }
7100
7101    // A route.open handle is published before its waiter is resolved. The socket reader
7102    // cannot consume a following same-route frame until this synchronous install finishes.
7103    if frame.header.channel == 0
7104        && frame.header.ty == FrameType::Response
7105        && shared.pending_expects_route_open(key)
7106    {
7107        if let Ok((
7108            ClientControlResponse::RouteOpen {
7109                route_channel,
7110                route_epoch,
7111                ..
7112            },
7113            authority,
7114        )) = decode_route_open_response(&frame.body)
7115        {
7116            let reverse_requests = shared
7117                .pending_route_open_reverse_requests(key)
7118                .unwrap_or_default();
7119            let module = shared
7120                .lock_inner()
7121                .pending
7122                .get(&key)
7123                .and_then(|entry| entry.route_open_module.clone());
7124            let handle =
7125                RouteHandle::new_consumer(route_channel, route_epoch, generation, reverse_requests);
7126            shared.install_ingress_handle(handle);
7127            if let Some(target) = authority.target {
7128                let mut inner = shared.lock_inner();
7129                if inner.route_epochs.get(&handle.channel) == Some(&handle) {
7130                    inner.route_targets.insert(handle, target);
7131                }
7132            }
7133            if let Some(module) = module {
7134                shared
7135                    .lock_inner()
7136                    .route_modules
7137                    .insert(route_channel, module);
7138            }
7139        }
7140    }
7141
7142    match frame.header.ty {
7143        FrameType::Response => shared.settle_pending(
7144            key,
7145            PendingTerminal::Response {
7146                generation,
7147                body: frame.body,
7148                flags: frame.header.flags,
7149            },
7150        ),
7151        FrameType::Error => {
7152            let body =
7153                serde_json::from_slice::<ErrorBody>(&frame.body).unwrap_or_else(|err| ErrorBody {
7154                    code: "invalid_error_body".to_string(),
7155                    message: err.to_string(),
7156                    detail: None,
7157                });
7158            shared.settle_pending(
7159                key,
7160                PendingTerminal::Error {
7161                    body,
7162                    flags: frame.header.flags,
7163                },
7164            );
7165        }
7166        FrameType::StreamEnd => shared.settle_pending(key, PendingTerminal::StreamEnd),
7167        FrameType::StreamData => shared.route_stream_data(key, frame.body),
7168        FrameType::Push if frame.header.channel == 0 => {
7169            shared.control_push(&frame.body);
7170        }
7171        FrameType::Push => shared.route_push(
7172            RouteHandle::new(frame.header.channel, frame.header.epoch, generation),
7173            frame.body,
7174        ),
7175        FrameType::Goodbye if frame.header.channel == 0 => {
7176            shared.handle_generation_drop(generation, "subc sent GOODBYE".to_string());
7177            return false;
7178        }
7179        FrameType::Goodbye => {
7180            let handle = RouteHandle::new(frame.header.channel, frame.header.epoch, generation);
7181            let close_reason = shared.lock_inner().route_end(handle.channel);
7182            shared.invalidate_routes_for_handle(handle);
7183            let pending = {
7184                let mut inner = shared.lock_inner();
7185                drain_pending_handle(&mut inner.pending, handle, true)
7186            };
7187            settle_route_pending_entries(pending, "route closed by subc".to_string(), close_reason);
7188        }
7189        FrameType::Ping if frame.header.channel == 0 => {
7190            if let Ok(pong) = Frame::build_with_version(
7191                frame.header.ver,
7192                FrameType::Pong,
7193                frame.header.flags,
7194                0,
7195                0,
7196                frame.header.corr,
7197                Vec::new(),
7198            ) {
7199                let writer = shared.lock_inner().writer.clone();
7200                if let Some(writer) = writer {
7201                    let _ = writer
7202                        .send(WriteCommand {
7203                            frame: pong,
7204                            pending: None,
7205                        })
7206                        .await;
7207                }
7208            }
7209        }
7210        _ => {}
7211    }
7212    true
7213}
7214
7215impl Shared {
7216    /// Stamp after holding the same state lock that guards generation changes, so a
7217    /// late frame from an older reader can never vouch for a newly installed socket.
7218    ///
7219    /// PLACEMENT IS LOAD-BEARING: the single caller sits on the frame-read
7220    /// return, the one point every inbound frame passes before demux -- which
7221    /// is why one stamp suffices. A future fast path or drain-and-dispatch
7222    /// refactor that hands frames onward without crossing that point makes the
7223    /// stamp skippable, and the liveness watermark quietly stops meaning "the
7224    /// link delivered bytes": the cheapest correctness property in this file
7225    /// and the easiest to lose in a refactor.
7226    fn record_inbound_if_current(&self, generation: u64) -> bool {
7227        let inner = self.lock_inner();
7228        if inner.closed || inner.generation != generation || inner.writer.is_none() {
7229            return false;
7230        }
7231        self.last_inbound_ms
7232            .store(epoch_millis(), Ordering::Release);
7233        true
7234    }
7235
7236    fn generation_is_current(&self, generation: u64) -> bool {
7237        let inner = self.lock_inner();
7238        !inner.closed && inner.generation == generation && inner.writer.is_some()
7239    }
7240
7241    fn pending_expected_control_handle(&self, key: PendingKey) -> Option<RouteHandle> {
7242        self.lock_inner()
7243            .pending
7244            .get(&key)
7245            .and_then(|entry| entry.expected_control_handle)
7246    }
7247
7248    fn count_dropped_route_frame(&self) {
7249        let mut inner = self.lock_inner();
7250        inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
7251    }
7252
7253    fn pending_expects_route_open(&self, key: PendingKey) -> bool {
7254        self.lock_inner()
7255            .pending
7256            .get(&key)
7257            .is_some_and(|entry| entry.retain_late_route_open)
7258    }
7259
7260    fn pending_route_open_reverse_requests(
7261        &self,
7262        key: PendingKey,
7263    ) -> Option<ReverseRequestRegistry> {
7264        self.lock_inner()
7265            .pending
7266            .get(&key)
7267            .and_then(|entry| entry.route_open_reverse_requests.clone())
7268    }
7269
7270    fn ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> Option<RouteHandle> {
7271        let inner = self.lock_inner();
7272        let handle = inner.route_epochs.get(&channel).copied()?;
7273        (handle.connection_token() == generation && handle.epoch == epoch).then_some(handle)
7274    }
7275
7276    fn validate_ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> bool {
7277        let mut inner = self.lock_inner();
7278        let expected = RouteHandle::new(channel, epoch, generation);
7279        if inner.route_epochs.get(&channel) == Some(&expected) {
7280            true
7281        } else {
7282            inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
7283            false
7284        }
7285    }
7286
7287    fn install_ingress_handle(&self, handle: RouteHandle) {
7288        let mut inner = self.lock_inner();
7289        if !inner.closed && inner.generation == handle.connection_token() && inner.writer.is_some()
7290        {
7291            inner.route_end_reasons.remove(&handle.channel);
7292            inner.legacy_channel_reasons.remove(&handle.channel);
7293            inner.route_modules.remove(&handle.channel);
7294            if let Some(previous) = inner.route_epochs.insert(handle.channel, handle) {
7295                inner.route_targets.remove(&previous);
7296                if previous.reverse_request_registry_id() != handle.reverse_request_registry_id() {
7297                    release_reverse_request_registry(previous);
7298                }
7299            }
7300        }
7301    }
7302
7303    fn invalidate_routes_for_handle(&self, handle: RouteHandle) {
7304        let removed = {
7305            let mut inner = self.lock_inner();
7306            if inner.route_epochs.get(&handle.channel) != Some(&handle) {
7307                return;
7308            }
7309            inner.release_wire_slots(handle);
7310            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
7311            inner.route_targets.remove(&handle);
7312            inner.retired_routes.remove(&handle);
7313            inner.retirement_goodbyes.remove(&handle);
7314            inner.push_event_receivers.remove(&handle);
7315            release_reverse_request_registry(installed);
7316            inner
7317                .remove_route_by_handle(handle)
7318                .into_iter()
7319                .collect::<Vec<_>>()
7320        };
7321        for route in removed {
7322            route.close();
7323        }
7324    }
7325}
7326
7327async fn retirement_goodbye_loop(shared: Arc<Shared>, generation: u64, notify: Arc<Notify>) {
7328    loop {
7329        let notified = notify.notified();
7330        let next = {
7331            let inner = shared.lock_inner();
7332            if inner.closed || inner.generation != generation || inner.writer.is_none() {
7333                return;
7334            }
7335            inner
7336                .retirement_queue
7337                .front()
7338                .map(|handle| (*handle, inner.writer.as_ref().unwrap().clone()))
7339        };
7340        let Some((handle, writer)) = next else {
7341            notified.await;
7342            continue;
7343        };
7344        let Ok(permit) = writer.reserve().await else {
7345            shared.handle_generation_drop(
7346                generation,
7347                "writer closed before retirement GOODBYE".into(),
7348            );
7349            return;
7350        };
7351        let mut inner = shared.lock_inner();
7352        if inner.closed || inner.generation != generation || inner.writer.is_none() {
7353            return;
7354        }
7355        if inner.retirement_queue.front() != Some(&handle) {
7356            continue;
7357        }
7358        inner.retirement_queue.pop_front();
7359        inner.retirement_goodbyes.remove(&handle);
7360        if inner.route_epochs.get(&handle.channel) == Some(&handle) {
7361            let frame = Frame::build(
7362                FrameType::Goodbye,
7363                Flags::new(false, Priority::Interactive, false),
7364                handle.channel,
7365                handle.epoch,
7366                0,
7367                Vec::new(),
7368            )
7369            .expect("header-only route GOODBYE is valid");
7370            // Queue admission and uninstallation share the lock. No new route
7371            // can claim this channel between those operations.
7372            permit.send(WriteCommand {
7373                frame,
7374                pending: None,
7375            });
7376        }
7377        inner.reap_retired_route(handle);
7378    }
7379}
7380
7381async fn writer_loop<W>(
7382    shared: Arc<Shared>,
7383    writer: W,
7384    mut rx: mpsc::Receiver<WriteCommand>,
7385    generation: u64,
7386) where
7387    W: AsyncWrite + Unpin,
7388{
7389    let mut writer = BufWriter::new(writer);
7390    while let Some(command) = rx.recv().await {
7391        if let Some(key) = command.pending {
7392            if !shared.mark_pending_accepted(key) {
7393                continue;
7394            }
7395        }
7396        if let Err(err) = write_frame(&mut writer, &command.frame).await {
7397            shared.handle_generation_drop_with_cause(
7398                generation,
7399                err.to_string(),
7400                OutcomeUnknownCause::WriterClosed,
7401            );
7402            return;
7403        }
7404        while let Ok(command) = rx.try_recv() {
7405            if let Some(key) = command.pending {
7406                if !shared.mark_pending_accepted(key) {
7407                    continue;
7408                }
7409            }
7410            if let Err(err) = write_frame(&mut writer, &command.frame).await {
7411                shared.handle_generation_drop_with_cause(
7412                    generation,
7413                    err.to_string(),
7414                    OutcomeUnknownCause::WriterClosed,
7415                );
7416                return;
7417            }
7418        }
7419        if let Err(err) = writer.flush().await.map_err(FrameIoError::Io) {
7420            shared.handle_generation_drop_with_cause(
7421                generation,
7422                err.to_string(),
7423                OutcomeUnknownCause::WriterClosed,
7424            );
7425            return;
7426        }
7427    }
7428}
7429
7430impl Shared {
7431    fn implicit_consumer_identity(&self) -> Option<ConsumerIdentity> {
7432        // Operator-app connections must not even consult the launch environment:
7433        // the nonce accessor can consume an inherited credential descriptor.
7434        if self.identity_from_environment && !self.claim_bound {
7435            consumer_identity_from_env()
7436        } else {
7437            None
7438        }
7439    }
7440
7441    fn activity_read_body(&self, request: impl serde::Serialize) -> Result<Vec<u8>, CallError> {
7442        #[derive(serde::Serialize)]
7443        struct ReadRequest<T> {
7444            #[serde(flatten)]
7445            request: T,
7446            #[serde(skip_serializing_if = "Option::is_none")]
7447            consumer_identity: Option<ConsumerIdentity>,
7448        }
7449        serde_json::to_vec(&ReadRequest {
7450            request,
7451            consumer_identity: self.implicit_consumer_identity(),
7452        })
7453        .map_err(|err| CallError::not_sent(format!("failed to encode activity read: {err}")))
7454    }
7455
7456    fn route_open_consumer_identity(
7457        &self,
7458        opts: &CallOptions,
7459    ) -> Result<Option<ConsumerIdentity>, CallError> {
7460        if self.claim_bound && opts.consumer_identity.is_some() {
7461            // Legacy nonce identities cannot describe a claim-bound connection.
7462            return Err(CallError::not_sent(
7463                "consumer identity conflicts with connection binding",
7464            ));
7465        }
7466        Ok(opts
7467            .consumer_identity
7468            .clone()
7469            .or_else(|| self.implicit_consumer_identity()))
7470    }
7471
7472    fn close_route_consumer_identity(
7473        &self,
7474        opts: &CloseRouteOptions,
7475    ) -> Result<Option<ConsumerIdentity>, CallError> {
7476        if self.claim_bound && opts.consumer_identity.is_some() {
7477            return Err(CallError::not_sent(
7478                "consumer identity conflicts with connection binding",
7479            ));
7480        }
7481        Ok(opts
7482            .consumer_identity
7483            .clone()
7484            .or_else(|| self.implicit_consumer_identity()))
7485    }
7486}
7487
7488fn route_open_consumer_capabilities(opts: &CallOptions) -> Option<Vec<String>> {
7489    opts.reverse_requests.seal();
7490    let mut capabilities = opts.reverse_requests.capabilities();
7491    capabilities.extend(opts.consumer_capabilities());
7492    capabilities.sort();
7493    capabilities.dedup();
7494    (!capabilities.is_empty()).then_some(capabilities)
7495}
7496
7497/// The role versions a route is opened and keyed with. An empty map declares
7498/// nothing, and the daemon forwards it as no field at all, so it is folded
7499/// into `None` here: otherwise `Some({})` and `None` would key two routes the
7500/// provider cannot tell apart.
7501fn route_open_role_versions(
7502    role_versions: Option<&BTreeMap<String, String>>,
7503) -> Option<BTreeMap<String, String>> {
7504    role_versions
7505        .filter(|role_versions| !role_versions.is_empty())
7506        .cloned()
7507}
7508
7509fn close_route_consumer_capabilities(opts: &CloseRouteOptions) -> Option<Vec<String>> {
7510    opts.reverse_requests.seal();
7511    let mut capabilities = opts.reverse_requests.capabilities();
7512    capabilities.extend(opts.consumer_capabilities());
7513    capabilities.sort();
7514    capabilities.dedup();
7515    (!capabilities.is_empty()).then_some(capabilities)
7516}
7517
7518fn consumer_identity_from_env() -> Option<ConsumerIdentity> {
7519    let module_id = std::env::var(SUBC_MODULE_ID_ENV)
7520        .ok()
7521        .filter(|value| !value.is_empty())?;
7522    // Through the process's one cached accessor, never a second read of the
7523    // descriptor. An accessor error (for example a process a module spawned,
7524    // which inherits the descriptor variable but not the pipe) opens the
7525    // route without identity: it never falls back to the environment copy,
7526    // because presenting the module's nonce is exactly what such a process
7527    // must no longer be able to do.
7528    let launch_nonce = crate::launch_nonce()
7529        .ok()
7530        .flatten()
7531        .map(|nonce| nonce.value().to_string())?;
7532    Some(ConsumerIdentity {
7533        module_id,
7534        launch_nonce,
7535    })
7536}
7537
7538fn validate_capability_for_resolution(capability: &str) -> Result<(), CallError> {
7539    if is_valid_capability_identifier(capability) {
7540        Ok(())
7541    } else {
7542        Err(CallError::InvalidCapabilityIdentifier {
7543            capability: capability.to_string(),
7544        })
7545    }
7546}
7547
7548fn capability_claimants(catalog: &CatalogList, capability: &str) -> Vec<String> {
7549    let mut claimants = catalog
7550        .modules
7551        .iter()
7552        .filter(|module| {
7553            module.capabilities.as_ref().is_some_and(|capabilities| {
7554                capabilities
7555                    .provides
7556                    .iter()
7557                    .any(|claim| claim == capability)
7558            })
7559        })
7560        .map(|module| module.module_id.clone())
7561        .collect::<Vec<_>>();
7562    claimants.sort();
7563    claimants
7564}
7565
7566fn epoch_millis() -> u64 {
7567    u64::try_from(
7568        SystemTime::now()
7569            .duration_since(UNIX_EPOCH)
7570            .unwrap_or_default()
7571            .as_millis(),
7572    )
7573    .unwrap_or(u64::MAX)
7574}
7575
7576/// Reclassify a route-open failure seen by a managed `call` or `subscribe`.
7577///
7578/// `ensure_route` reports the route.open control request's own outcome, which
7579/// is `OutcomeUnknown` when that request was written but its reply did not
7580/// arrive before the deadline: the daemon may or may not have opened the
7581/// channel. The caller's request body, however, is only written after a route
7582/// is in hand, so when no route came back the body provably never left the
7583/// client. From the caller's point of view that is `NotSent`, and reporting
7584/// `OutcomeUnknown` would wrongly tell it a non-idempotent operation might
7585/// have run. A route.open reply that arrives after its waiter gave up is still
7586/// cleaned up: `settle_pending` sends that channel a GOODBYE instead of caching
7587/// it, so reporting `NotSent` here leaves no route open behind.
7588/// A uniform value in [0, 1) for retry jitter. Jitter needs spread, not
7589/// unpredictability, so this hashes a counter with std's randomly keyed hasher
7590/// instead of taking a dependency on a random-number crate.
7591fn default_random_unit() -> f64 {
7592    use std::hash::{BuildHasher, RandomState};
7593    static COUNTER: AtomicU64 = AtomicU64::new(0);
7594    let bits = RandomState::new().hash_one(COUNTER.fetch_add(1, Ordering::Relaxed));
7595    // The top 53 bits fill an f64 mantissa exactly.
7596    (bits >> 11) as f64 / (1u64 << 53) as f64
7597}
7598
7599fn request_not_sent_after_route_open_failure(err: CallError) -> CallError {
7600    match err {
7601        CallError::OutcomeUnknown(source) => CallError::not_sent_with_cause(
7602            format!("request not sent: route.open did not complete ({source})"),
7603            NotSentCause::RouteOpenAbandoned,
7604        ),
7605        other => other,
7606    }
7607}
7608
7609fn classify_failure(
7610    accepted: bool,
7611    reason: impl Into<String>,
7612    cause: OutcomeUnknownCause,
7613) -> CallError {
7614    classify_failure_with_not_sent_cause(accepted, reason, cause, NotSentCause::WriterRejected)
7615}
7616
7617fn classify_failure_with_not_sent_cause(
7618    accepted: bool,
7619    reason: impl Into<String>,
7620    cause: OutcomeUnknownCause,
7621    not_sent_cause: NotSentCause,
7622) -> CallError {
7623    if accepted {
7624        CallError::outcome_unknown(reason, cause)
7625    } else {
7626        CallError::not_sent_with_cause(reason, not_sent_cause)
7627    }
7628}
7629
7630fn settle_route_pending_entries(
7631    entries: Vec<PendingEntry>,
7632    message: String,
7633    reason: impl Into<RouteEnd>,
7634) {
7635    let reason = reason.into();
7636    let cause = if reason.reason == RouteEndReason::ConnectionLost {
7637        OutcomeUnknownCause::ConnectionFailed
7638    } else {
7639        OutcomeUnknownCause::RouteEnded
7640    };
7641    settle_route_pending_entries_with_cause(entries, message, reason, cause);
7642}
7643
7644fn settle_route_pending_entries_with_cause(
7645    entries: Vec<PendingEntry>,
7646    message: String,
7647    reason: impl Into<RouteEnd>,
7648    cause: OutcomeUnknownCause,
7649) {
7650    let reason = reason.into();
7651    for entry in entries {
7652        let err = if entry.accepted {
7653            CallError::outcome_unknown_source(OutcomeUnknownSource {
7654                message: message.clone(),
7655                cause,
7656                route_reason: Some(reason.clone()),
7657            })
7658        } else {
7659            CallError::NotSent(Box::new(NotSentSource {
7660                message: message.clone(),
7661                cause: NotSentCause::WriterRejected,
7662                never_forwarded: true,
7663                route_reason: Some(reason.clone()),
7664                refusal: None,
7665            }))
7666        };
7667        entry.settle_call_error(err);
7668    }
7669}
7670
7671fn settle_pending_entries(entries: Vec<PendingEntry>, reason: String) {
7672    for entry in entries {
7673        entry.settle_failure(reason.clone());
7674    }
7675}
7676
7677fn drain_pending_generation(
7678    pending: &mut HashMap<PendingKey, PendingEntry>,
7679    generation: u64,
7680) -> Vec<PendingEntry> {
7681    let keys = pending
7682        .keys()
7683        .copied()
7684        .filter(|key| key.generation == generation)
7685        .collect::<Vec<_>>();
7686    keys.into_iter()
7687        .filter_map(|key| pending.remove(&key))
7688        .collect()
7689}
7690
7691fn drain_pending_handle(
7692    pending: &mut HashMap<PendingKey, PendingEntry>,
7693    handle: RouteHandle,
7694    include_subscriptions: bool,
7695) -> Vec<PendingEntry> {
7696    let keys = pending
7697        .iter()
7698        .filter_map(|(key, entry)| {
7699            (key.generation == handle.connection_token()
7700                && key.channel == handle.channel
7701                && key.epoch == handle.epoch
7702                && (include_subscriptions || !entry.is_subscription()))
7703            .then_some(*key)
7704        })
7705        .collect::<Vec<_>>();
7706    keys.into_iter()
7707        .filter_map(|key| pending.remove(&key))
7708        .collect()
7709}
7710
7711fn fail_openings(openings: Vec<Vec<OpeningWaiter>>, failure: SharedCallFailure) {
7712    for waiters in openings {
7713        for waiter in waiters {
7714            let _ = waiter.send(Err(failure.clone()));
7715        }
7716    }
7717}
7718
7719fn emit_callbacks(callbacks: Vec<Callback>, state: ConnectionState) {
7720    for callback in callbacks {
7721        if let Ok(callback) = callback.lock() {
7722            callback(state.clone());
7723        }
7724    }
7725}
7726
7727/// The route-open retry predicate, defined once in `subc_protocol::error_codes`
7728/// so consumers with their own connection layer share it rather than copy it.
7729pub fn is_retryable_route_open_code(code: &str) -> bool {
7730    error_codes::is_retryable_route_open(code)
7731}
7732
7733/// Whether a data-plane ERROR answering a managed call's request is the
7734/// daemon's drain refusal, `module_reloading`, which the call may resend once
7735/// after reopening the route.
7736///
7737/// On an established route the daemon answers `module_reloading` only when the
7738/// module's endpoint is draining and the request could not take a route
7739/// credit, and it answers BEFORE forwarding (`ForwardBackend::handle_bound` in
7740/// subc-daemon's `router.rs`), so the module never received the request and a
7741/// resend cannot run it twice. The protocol documents that guarantee on
7742/// `error_codes::MODULE_RELOADING`.
7743///
7744/// Kept apart from `error_codes::is_established_route_dead` on purpose. That
7745/// shared predicate decides route DEATH, and other consumers map it to their
7746/// own custody, provider or suspect verdicts; adding a drain code there would
7747/// change those verdicts on a protocol bump. Here the code only earns the same
7748/// remedy (evict, reopen, resend once) inside this client's unary call path.
7749fn is_data_plane_drain_refusal(code: &str) -> bool {
7750    code == error_codes::MODULE_RELOADING
7751}
7752
7753// 0.37.15 is the first daemon that marks its own errors and strips the bit from module frames.
7754const DAEMON_ORIGIN_MIN_VERSION: (u64, u64, u64) = (0, 37, 15);
7755
7756/// Whether a connected daemon strips forged `DAEMON_ORIGIN` flags from module
7757/// frames: only exact numeric `major.minor.patch` versions at least 0.37.15.
7758/// Unknown versions, including pre-release and build suffixes, fail closed.
7759///
7760/// Pass the version from the same `ConnectionInfo` used by a successful
7761/// `authenticate_client` handshake. That handshake checks the daemon id against
7762/// the file, but its HMAC does not cover the version itself. Do not re-read the
7763/// file to classify a connection that is already authenticated.
7764pub fn trusts_daemon_origin(daemon_ver: &str) -> bool {
7765    daemon_version_at_least(daemon_ver, DAEMON_ORIGIN_MIN_VERSION)
7766}
7767
7768fn daemon_version_at_least(daemon_ver: &str, minimum: (u64, u64, u64)) -> bool {
7769    let mut components = daemon_ver.split('.');
7770    let mut next = || {
7771        let component = components.next()?;
7772        if component.is_empty() || !component.bytes().all(|byte| byte.is_ascii_digit()) {
7773            return None;
7774        }
7775        component.parse::<u64>().ok()
7776    };
7777    let version = (next(), next(), next());
7778    match version {
7779        (Some(major), Some(minor), Some(patch)) if components.next().is_none() => {
7780            (major, minor, patch) >= minimum
7781        }
7782        _ => false,
7783    }
7784}
7785
7786/// Whether an Error frame proves that its request was never forwarded.
7787///
7788/// This covers only `module_reloading`, `unknown_channel` and
7789/// `stale_route_epoch` with `DAEMON_ORIGIN`, when `daemon_origin_trusted` came
7790/// from [`trusts_daemon_origin`] for this connection's authenticated daemon
7791/// (0.37.15 or later). It proves only this attempt, not any earlier attempts of
7792/// a call. For managed calls use [`CallError::never_forwarded`] instead.
7793/// Unmarked errors and untrusted daemon versions never prove non-delivery.
7794/// This helper cannot see route negotiation and does not classify `route_busy`;
7795/// SDK-managed requests on opted-in routes handle that refusal internally.
7796pub fn is_daemon_refusal_before_forward(
7797    daemon_origin_trusted: bool,
7798    flags: Flags,
7799    code: &str,
7800) -> bool {
7801    daemon_origin_trusted
7802        && flags.is_daemon_origin()
7803        && matches!(
7804            code,
7805            error_codes::MODULE_RELOADING
7806                | error_codes::UNKNOWN_CHANNEL
7807                | error_codes::STALE_ROUTE_EPOCH
7808        )
7809}
7810
7811/// Whether `handle` names a route installed on the current connection. Channel 0 is the
7812/// connection's own control channel: it is never installed as a route and is current for
7813/// as long as the connection is, so a held channel-0 request (the spawn stream) can be
7814/// cancelled like a route subscription.
7815fn route_is_installed(inner: &Inner, handle: RouteHandle) -> bool {
7816    handle.channel == 0 || inner.route_epochs.get(&handle.channel) == Some(&handle)
7817}
7818
7819fn is_retryable_catalog_transport_error(err: &CallError) -> bool {
7820    matches!(err, CallError::NotSent(_) | CallError::OutcomeUnknown(_))
7821}
7822
7823impl From<FrameBuildError> for CallError {
7824    fn from(err: FrameBuildError) -> Self {
7825        Self::not_sent(err.to_string())
7826    }
7827}
7828
7829#[cfg(test)]
7830mod local_transport_tests;
7831
7832#[cfg(test)]
7833mod tests {
7834    use super::*;
7835
7836    mod busy_refusals_tests;
7837    mod not_sent_tests;
7838    mod route_close_tests;
7839    mod route_deadline_tests;
7840
7841    #[derive(Clone)]
7842    struct InstrumentedWriter {
7843        state: Arc<InstrumentedWriterState>,
7844        fail_flush: bool,
7845    }
7846
7847    #[derive(Default)]
7848    struct InstrumentedWriterState {
7849        bytes: Mutex<Vec<u8>>,
7850        flushes: std::sync::atomic::AtomicUsize,
7851    }
7852
7853    impl InstrumentedWriter {
7854        fn new(fail_flush: bool) -> Self {
7855            Self {
7856                state: Arc::new(InstrumentedWriterState::default()),
7857                fail_flush,
7858            }
7859        }
7860
7861        fn bytes(&self) -> Vec<u8> {
7862            self.state
7863                .bytes
7864                .lock()
7865                .unwrap_or_else(|poisoned| poisoned.into_inner())
7866                .clone()
7867        }
7868
7869        fn flush_count(&self) -> usize {
7870            self.state.flushes.load(Ordering::SeqCst)
7871        }
7872    }
7873
7874    impl AsyncWrite for InstrumentedWriter {
7875        fn poll_write(
7876            self: Pin<&mut Self>,
7877            _cx: &mut Context<'_>,
7878            buf: &[u8],
7879        ) -> Poll<io::Result<usize>> {
7880            self.state
7881                .bytes
7882                .lock()
7883                .unwrap_or_else(|poisoned| poisoned.into_inner())
7884                .extend_from_slice(buf);
7885            Poll::Ready(Ok(buf.len()))
7886        }
7887
7888        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
7889            self.state.flushes.fetch_add(1, Ordering::SeqCst);
7890            if self.fail_flush {
7891                Poll::Ready(Err(io::Error::new(
7892                    io::ErrorKind::BrokenPipe,
7893                    "instrumented flush failure",
7894                )))
7895            } else {
7896                Poll::Ready(Ok(()))
7897            }
7898        }
7899
7900        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
7901            Poll::Ready(Ok(()))
7902        }
7903    }
7904
7905    fn writer_test_shared() -> Arc<Shared> {
7906        Arc::new(reader_skew_tests::legacy_shared(
7907            PathBuf::from("/tmp/does-not-exist"),
7908            ConsumerOptions {
7909                reconnect_backoff: RetryBackoff {
7910                    max_attempts: 1,
7911                    ..RetryBackoff::default()
7912                },
7913                ..ConsumerOptions::default()
7914            },
7915        ))
7916    }
7917
7918    fn reverse_test_shared(
7919        reverse_requests: ReverseRequestRegistry,
7920    ) -> (Arc<Shared>, mpsc::Receiver<WriteCommand>, RouteHandle) {
7921        let shared = writer_test_shared();
7922        let (writer, receiver) = mpsc::channel(16);
7923        let handle = RouteHandle::new_consumer(17, 3, 1, reverse_requests);
7924        {
7925            let mut inner = shared.lock_inner();
7926            inner.writer = Some(writer);
7927            inner.daemon_ver = "0.39.0".into();
7928            inner.route_epochs.insert(handle.channel, handle);
7929        }
7930        (shared, receiver, handle)
7931    }
7932
7933    fn reverse_request_frame(handle: RouteHandle, corr: u64, body: Vec<u8>) -> Frame {
7934        Frame::build(
7935            FrameType::Request,
7936            Flags::new(false, Priority::Interactive, false),
7937            handle.channel,
7938            handle.epoch,
7939            corr,
7940            body,
7941        )
7942        .unwrap()
7943    }
7944
7945    #[tokio::test]
7946    async fn binary_reply_request_preserves_flagged_non_utf8_bytes() {
7947        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
7948        let consumer = SubcConsumer {
7949            shared: Arc::clone(&shared),
7950        };
7951        shared
7952            .install_one_shot_route(RouteState {
7953                handle,
7954                sem: Arc::new(Semaphore::new(1)),
7955                watch_sem: None,
7956                opted_in: false,
7957            })
7958            .unwrap();
7959        let request = tokio::spawn(async move {
7960            consumer
7961                .request(&handle, b"bytes".to_vec(), CallOptions::default())
7962                .await
7963        });
7964        let command = receiver.recv().await.unwrap();
7965        let bytes = vec![0, 0xff, 0x80, b'{'];
7966        let frame = Frame::build(
7967            FrameType::Response,
7968            Flags::new(true, Priority::Interactive, false),
7969            handle.channel,
7970            handle.epoch,
7971            command.frame.header.corr,
7972            bytes.clone(),
7973        )
7974        .unwrap();
7975        assert!(dispatch_frame(&shared, 1, frame).await);
7976        assert_eq!(request.await.unwrap().unwrap(), bytes);
7977    }
7978
7979    async fn capture_route_open(
7980        reverse_requests: ReverseRequestRegistry,
7981    ) -> (serde_json::Value, RouteHandle) {
7982        capture_route_open_with_options(CallOptions {
7983            reverse_requests,
7984            ..CallOptions::default()
7985        })
7986        .await
7987    }
7988
7989    async fn capture_route_open_with_options(
7990        opts: CallOptions,
7991    ) -> (serde_json::Value, RouteHandle) {
7992        let shared = writer_test_shared();
7993        let (writer, mut receiver) = mpsc::channel(4);
7994        shared.lock_inner().writer = Some(writer);
7995        shared.lock_inner().daemon_ver = "0.39.0".into();
7996        let consumer = SubcConsumer {
7997            shared: Arc::clone(&shared),
7998        };
7999        let task = tokio::spawn(async move {
8000            consumer
8001                .open_route(
8002                    RouteTarget::ToolProvider {
8003                        module_id: "reverse-provider".to_string(),
8004                    },
8005                    BindIdentity::new("test".to_string(), "reverse".to_string()),
8006                    opts,
8007                )
8008                .await
8009        });
8010        let command = receiver.recv().await.expect("route.open frame");
8011        let request = serde_json::from_slice(&command.frame.body).unwrap();
8012        let response_body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
8013            request_window: None,
8014            watch_window: None,
8015            route_channel: 17,
8016            route_epoch: 3,
8017        })
8018        .unwrap();
8019        assert!(
8020            dispatch_frame(
8021                &shared,
8022                1,
8023                response_frame(0, 0, command.frame.header.corr, response_body),
8024            )
8025            .await
8026        );
8027        let handle = task.await.unwrap().unwrap();
8028        (request, handle)
8029    }
8030
8031    /// Keep held subscriptions marked for drain accounting without marking ordinary requests.
8032    #[tokio::test]
8033    async fn held_subscriptions_set_the_flag_but_ordinary_requests_do_not() {
8034        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
8035        let call_shared = Arc::clone(&shared);
8036        let call = tokio::spawn(async move {
8037            call_shared
8038                .send_request(RequestSend {
8039                    binary: false,
8040                    expected_handle: Some(handle),
8041                    channel: handle.channel,
8042                    epoch: handle.epoch,
8043                    body: b"ordinary".to_vec(),
8044                    priority: Priority::Interactive,
8045                    admission_class: AdmissionClass::Normal,
8046                    deadline: Instant::now() + Duration::from_secs(1),
8047                    retain_late_route_open: false,
8048                    route_open_reverse_requests: None,
8049                })
8050                .await
8051        });
8052        let ordinary = receiver.recv().await.unwrap();
8053        assert_eq!(ordinary.frame.header.encode()[6] & FLAG_SUBSCRIPTION, 0);
8054        assert!(
8055            dispatch_frame(
8056                &shared,
8057                1,
8058                response_frame(
8059                    handle.channel,
8060                    handle.epoch,
8061                    ordinary.frame.header.corr,
8062                    Vec::new()
8063                ),
8064            )
8065            .await
8066        );
8067        assert!(call.await.unwrap().is_ok());
8068
8069        let permit = Arc::new(Semaphore::new(1)).acquire_owned().await.unwrap();
8070        let subscription = Arc::clone(&shared)
8071            .send_subscription(SubscriptionSend {
8072                expected_handle: Some(handle),
8073                channel: handle.channel,
8074                epoch: handle.epoch,
8075                body: b"held".to_vec(),
8076                priority: Priority::Interactive,
8077                admission_class: AdmissionClass::Normal,
8078                event_buffer: 1,
8079                deadline: Instant::now() + Duration::from_secs(1),
8080                permit: RoutePermit::legacy(permit),
8081            })
8082            .await
8083            .unwrap();
8084        let held = receiver.recv().await.unwrap();
8085        assert_ne!(
8086            held.frame.header.encode()[6] & FLAG_SUBSCRIPTION,
8087            0,
8088            "a held-open subscription must be marked for drain accounting"
8089        );
8090        drop(subscription);
8091        release_reverse_request_registry(handle);
8092    }
8093
8094    #[tokio::test]
8095    async fn registered_handlers_derive_route_open_consumer_capabilities() {
8096        let registry = ReverseRequestRegistry::new();
8097        registry
8098            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
8099            .unwrap();
8100        let (request, handle) = capture_route_open(registry).await;
8101        assert_eq!(
8102            request.get("consumer_capabilities"),
8103            Some(&serde_json::json!(["elicitation"]))
8104        );
8105        release_reverse_request_registry(handle);
8106    }
8107
8108    #[tokio::test]
8109    async fn declared_consumer_capabilities_merge_with_handler_families_on_route_open() {
8110        let registry = ReverseRequestRegistry::new();
8111        registry
8112            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
8113            .unwrap();
8114        let opts = CallOptions {
8115            reverse_requests: registry,
8116            ..CallOptions::default()
8117        }
8118        .with_consumer_capability("tool-result/v1")
8119        .unwrap()
8120        .with_consumer_capability("elicitation")
8121        .unwrap()
8122        .with_consumer_capability("tool-result/v1")
8123        .unwrap();
8124
8125        let (request, handle) = capture_route_open_with_options(opts).await;
8126        assert_eq!(
8127            request.get("consumer_capabilities"),
8128            Some(&serde_json::json!(["elicitation", "tool-result/v1"]))
8129        );
8130        release_reverse_request_registry(handle);
8131    }
8132
8133    #[test]
8134    fn invalid_consumer_capability_declarations_are_rejected_before_route_open() {
8135        let (shared, mut receiver) = {
8136            let shared = writer_test_shared();
8137            let (writer, receiver) = mpsc::channel(4);
8138            shared.lock_inner().writer = Some(writer);
8139            shared.lock_inner().daemon_ver = "0.39.0".into();
8140            (shared, receiver)
8141        };
8142        let too_long = "x".repeat(65);
8143        for invalid in [
8144            String::new(),
8145            "content v1".to_string(),
8146            "content\tv1".to_string(),
8147            "content\nv1".to_string(),
8148            "cöntent/v1".to_string(),
8149            "content/\u{7f}v1".to_string(),
8150            too_long,
8151        ] {
8152            let error = CallOptions::default()
8153                .with_consumer_capability(invalid.clone())
8154                .expect_err("invalid declarations must not produce route options");
8155            assert_eq!(error.capability(), invalid);
8156            assert!(
8157                receiver.try_recv().is_err(),
8158                "invalid declaration {invalid:?} must be rejected before any frame is queued"
8159            );
8160        }
8161        let close_error = CloseRouteOptions::default()
8162            .with_consumer_capability("bad value")
8163            .expect_err("close-route declarations use the same validation");
8164        assert_eq!(close_error.capability(), "bad value");
8165        let call_options = CallOptions::default()
8166            .with_consumer_capability("tool-result/v1")
8167            .unwrap();
8168        assert_eq!(
8169            call_options.consumer_capabilities(),
8170            vec!["tool-result/v1".to_string()]
8171        );
8172        let close_options = CloseRouteOptions::default()
8173            .with_consumer_capability("tool-result/v1")
8174            .unwrap();
8175        assert_eq!(
8176            close_options.consumer_capabilities(),
8177            vec!["tool-result/v1".to_string()]
8178        );
8179        shared.close_sync("test complete");
8180    }
8181
8182    #[tokio::test]
8183    async fn no_handlers_omit_consumer_capabilities_from_route_open() {
8184        let (request, handle) = capture_route_open(ReverseRequestRegistry::new()).await;
8185        assert!(!request
8186            .as_object()
8187            .unwrap()
8188            .contains_key("consumer_capabilities"));
8189        release_reverse_request_registry(handle);
8190    }
8191
8192    #[tokio::test]
8193    async fn reverse_request_without_handler_returns_typed_error_instead_of_silence() {
8194        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
8195        let body = serde_json::to_vec(&serde_json::json!({
8196            "jsonrpc": "2.0",
8197            "id": 1,
8198            "method": "elicitation/create",
8199            "params": {}
8200        }))
8201        .unwrap();
8202        assert!(dispatch_frame(&shared, 1, reverse_request_frame(handle, 800, body)).await);
8203        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8204            .await
8205            .unwrap()
8206            .unwrap()
8207            .frame;
8208        assert_eq!(reply.header.ty, FrameType::Error);
8209        assert_eq!(reply.header.corr, 800);
8210        let error: ErrorBody = serde_json::from_slice(&reply.body).unwrap();
8211        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
8212        release_reverse_request_registry(handle);
8213    }
8214
8215    #[tokio::test]
8216    async fn reverse_request_round_trip_preserves_raw_body_corr_and_response() {
8217        let registry = ReverseRequestRegistry::new();
8218        let seen = Arc::new(Mutex::new(None));
8219        let seen_by_handler = Arc::clone(&seen);
8220        let response = br#"{"jsonrpc":"2.0","id":9,"result":{"accepted":true}}"#.to_vec();
8221        let expected_response = response.clone();
8222        registry
8223            .on_request("elicitation", move |body, ctx| {
8224                *seen_by_handler
8225                    .lock()
8226                    .unwrap_or_else(|poisoned| poisoned.into_inner()) =
8227                    Some((body, ctx.corr, ctx.method));
8228                let response = response.clone();
8229                async move { response }
8230            })
8231            .unwrap();
8232        let (shared, mut receiver, handle) = reverse_test_shared(registry);
8233        let request_body =
8234            br#"{"jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"z":1,"a":2}}"#
8235                .to_vec();
8236        assert!(
8237            dispatch_frame(
8238                &shared,
8239                1,
8240                reverse_request_frame(handle, 801, request_body.clone()),
8241            )
8242            .await
8243        );
8244        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8245            .await
8246            .unwrap()
8247            .unwrap()
8248            .frame;
8249        assert_eq!(reply.header.ty, FrameType::Response);
8250        assert_eq!(reply.header.corr, 801);
8251        assert_eq!(reply.body, expected_response);
8252        assert_eq!(
8253            seen.lock()
8254                .unwrap_or_else(|poisoned| poisoned.into_inner())
8255                .clone(),
8256            Some((request_body, 801, "elicitation/create".to_string()))
8257        );
8258        release_reverse_request_registry(handle);
8259    }
8260
8261    #[tokio::test]
8262    async fn panicking_reverse_handler_returns_typed_refusal_and_sibling_request_resolves() {
8263        let registry = ReverseRequestRegistry::new();
8264        registry
8265            .on_request("sampling", |_body, _ctx| async move {
8266                panic!("person prompt exploded");
8267            })
8268            .unwrap();
8269        let (shared, mut receiver, handle) = reverse_test_shared(registry);
8270        let sibling_shared = Arc::clone(&shared);
8271        let sibling = tokio::spawn(async move {
8272            sibling_shared
8273                .send_request(RequestSend {
8274                    binary: false,
8275                    expected_handle: Some(handle),
8276                    channel: handle.channel,
8277                    epoch: handle.epoch,
8278                    body: b"sibling".to_vec(),
8279                    priority: Priority::Interactive,
8280                    admission_class: AdmissionClass::Normal,
8281                    deadline: Instant::now() + Duration::from_secs(1),
8282                    retain_late_route_open: false,
8283                    route_open_reverse_requests: None,
8284                })
8285                .await
8286        });
8287        let sibling_request = receiver.recv().await.unwrap();
8288        let reverse_body = serde_json::to_vec(&serde_json::json!({
8289            "method": "sampling/createMessage",
8290            "params": {}
8291        }))
8292        .unwrap();
8293        assert!(
8294            dispatch_frame(&shared, 1, reverse_request_frame(handle, 802, reverse_body),).await
8295        );
8296        assert!(
8297            dispatch_frame(
8298                &shared,
8299                1,
8300                response_frame(
8301                    handle.channel,
8302                    handle.epoch,
8303                    sibling_request.frame.header.corr,
8304                    b"ok".to_vec(),
8305                ),
8306            )
8307            .await
8308        );
8309        assert!(matches!(
8310            sibling.await.unwrap().unwrap(),
8311            TerminalFrame::Response { body, .. } if body == b"ok"
8312        ));
8313        let refusal = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
8314            .await
8315            .unwrap()
8316            .unwrap()
8317            .frame;
8318        assert_eq!(refusal.header.ty, FrameType::Error);
8319        let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
8320        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
8321        assert!(error.message.contains("person prompt exploded"));
8322        assert!(shared.generation_is_current(1));
8323        release_reverse_request_registry(handle);
8324    }
8325
8326    fn reservation_stand_in(
8327        credit: usize,
8328        capacity: usize,
8329    ) -> (
8330        Arc<Shared>,
8331        SubcConsumer,
8332        mpsc::Receiver<WriteCommand>,
8333        RouteHandle,
8334        Arc<Semaphore>,
8335    ) {
8336        let shared = writer_test_shared();
8337        let (writer, rx) = mpsc::channel(capacity);
8338        shared.lock_inner().writer = Some(writer);
8339        shared.lock_inner().daemon_ver = "0.39.0".into();
8340        let handle = RouteHandle::new(5, 3, 1);
8341        let sem = Arc::new(Semaphore::new(credit));
8342        shared
8343            .install_one_shot_route(RouteState {
8344                handle,
8345                sem: Arc::clone(&sem),
8346                watch_sem: None,
8347                opted_in: false,
8348            })
8349            .unwrap();
8350        let consumer = SubcConsumer {
8351            shared: Arc::clone(&shared),
8352        };
8353        (shared, consumer, rx, handle, sem)
8354    }
8355
8356    #[tokio::test]
8357    async fn reservation_send_is_synchronous_and_uses_prevalidated_body() {
8358        let oversized = vec![0; subc_protocol::MAX_FRAME_BODY_LEN as usize + 1];
8359        assert!(matches!(
8360            RequestBody::new(oversized),
8361            Err(CallError::NotSent(_))
8362        ));
8363        let body = RequestBody::new(b"valid".to_vec()).unwrap();
8364        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8365        let reserved = consumer
8366            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8367            .await
8368            .unwrap();
8369        let corr = reserved.correlation_id();
8370        assert_eq!(shared.lock_inner().writer.as_ref().unwrap().capacity(), 0);
8371        assert!(rx.try_recv().is_err());
8372
8373        // A concrete tuple proves send returns without awaiting. Inspect the
8374        // writer queue before running the writer or polling PendingReply.
8375        let (sent_corr, reply): (CorrelationId, PendingReply) =
8376            reserved.send(body, CallOptions::default());
8377        assert_eq!(sent_corr, corr);
8378        let command = rx.try_recv().expect("send must enqueue without yielding");
8379        assert_eq!(command.frame.body, b"valid");
8380        assert_eq!(command.frame.header.corr, corr);
8381        assert_eq!(sem.available_permits(), 0);
8382        assert!(shared.mark_pending_accepted(command.pending.unwrap()));
8383        dispatch_frame(
8384            &shared,
8385            1,
8386            response_frame(handle.channel, handle.epoch, corr, b"reply".to_vec()),
8387        )
8388        .await;
8389        assert_eq!(reply.await.unwrap(), b"reply");
8390        assert_eq!(sem.available_permits(), 1);
8391        consumer.close().await;
8392    }
8393
8394    #[tokio::test]
8395    async fn pending_reply_classifies_established_route_error() {
8396        for (body, route_dead) in established_route_errors() {
8397            let (shared, consumer, mut rx, handle, _) = reservation_stand_in(1, 1);
8398            let reserved = consumer
8399                .reserve(&handle, Instant::now() + Duration::from_secs(1))
8400                .await
8401                .unwrap();
8402            let (_, reply) = reserved.send(
8403                RequestBody::new(b"request".to_vec()).unwrap(),
8404                CallOptions::default(),
8405            );
8406            let request = rx.recv().await.unwrap().frame;
8407            assert!(dispatch_frame(&shared, 1, route_error(&request, &body, route_dead)).await);
8408            let error = reply.await.unwrap_err();
8409            assert_eq!(error.is_route_dead(), route_dead, "{error:?}");
8410            assert_eq!(error.code(), Some(body.code.as_str()));
8411            match error {
8412                CallError::RouteDead(received) if route_dead => assert_eq!(*received, body),
8413                CallError::Module(received) if !route_dead => assert_eq!(received, body),
8414                other => panic!("unexpected call error: {other:?}"),
8415            }
8416        }
8417    }
8418
8419    #[tokio::test]
8420    async fn reservation_drop_releases_route_credit_and_writer_capacity_without_sending() {
8421        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8422        let deadline = Instant::now() + Duration::from_secs(1);
8423        let first = consumer.reserve(&handle, deadline).await.unwrap();
8424        let second = consumer.reserve(&handle, deadline);
8425        tokio::pin!(second);
8426        assert_pending(second.as_mut()).await;
8427        assert_eq!(sem.available_permits(), 0);
8428        drop(first);
8429        let second = timeout_at(deadline, second).await.unwrap().unwrap();
8430        drop(second);
8431        assert_eq!(sem.available_permits(), 1);
8432        assert_eq!(shared.lock_inner().writer.as_ref().unwrap().capacity(), 1);
8433        assert!(shared.lock_inner().pending.is_empty());
8434        assert!(rx.try_recv().is_err());
8435        consumer.close().await;
8436    }
8437
8438    #[tokio::test]
8439    async fn reservation_route_closed_before_send_matches_an_ordinary_unwritten_request() {
8440        let (shared, consumer, mut rx, handle, _) = reservation_stand_in(2, 4);
8441        let reserved = consumer
8442            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8443            .await
8444            .unwrap();
8445        let ordinary = consumer.request(&handle, b"ordinary".to_vec(), CallOptions::default());
8446        tokio::pin!(ordinary);
8447        assert_pending(ordinary.as_mut()).await;
8448        let ordinary_command = rx.try_recv().unwrap();
8449        assert_eq!(ordinary_command.frame.body, b"ordinary");
8450        consumer
8451            .close_handle(&handle, CloseRouteOptions::default())
8452            .await
8453            .unwrap();
8454        let (_, reply) = reserved.send(
8455            RequestBody::new(b"reserved".to_vec()).unwrap(),
8456            CallOptions::default(),
8457        );
8458        let ordinary_error = ordinary.await.unwrap_err();
8459        let reserved_error = reply.await.unwrap_err();
8460        assert!(matches!(reserved_error, CallError::NotSent(_)));
8461        assert_eq!(
8462            reserved_error.close_reason(),
8463            Some(&RouteEndReason::ClosedByCaller)
8464        );
8465        assert_eq!(reserved_error.to_string(), ordinary_error.to_string());
8466        assert_eq!(reserved_error.close_reason(), ordinary_error.close_reason());
8467
8468        rx.close();
8469        let writer = InstrumentedWriter::new(false);
8470        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8471        let bytes = writer.bytes();
8472        let mut bytes = bytes.as_slice();
8473        let frame = read_frame(&mut bytes).await.unwrap().unwrap();
8474        assert_eq!(frame.header.ty, FrameType::Goodbye);
8475        assert!(
8476            bytes.is_empty(),
8477            "the closed route's reserved request must not be written"
8478        );
8479        consumer.close().await;
8480    }
8481
8482    #[tokio::test]
8483    async fn reservation_connection_loss_after_send_preserves_existing_errors() {
8484        for written in [false, true] {
8485            let (shared, consumer, rx, handle, sem) = reservation_stand_in(1, 1);
8486            let reserved = consumer
8487                .reserve(&handle, Instant::now() + Duration::from_secs(1))
8488                .await
8489                .unwrap();
8490            let (_, reply) = reserved.send(
8491                RequestBody::new(b"request".to_vec()).unwrap(),
8492                CallOptions::default(),
8493            );
8494            let writer = InstrumentedWriter::new(written);
8495            if !written {
8496                shared.handle_generation_drop(1, "connection lost before dequeue".to_string());
8497            }
8498            writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8499            let err = reply.await.unwrap_err();
8500            assert_eq!(err.close_reason(), Some(&RouteEndReason::ConnectionLost));
8501            if written {
8502                // `outcome_cause` answers only for `OutcomeUnknown`, so this also
8503                // checks the variant without adding a spelling the
8504                // outcome_unknown_inventory test would have to count.
8505                assert_eq!(err.outcome_cause(), Some(OutcomeUnknownCause::WriterClosed));
8506                assert!(!writer.bytes().is_empty());
8507            } else {
8508                assert!(matches!(err, CallError::NotSent(_)));
8509                assert!(writer.bytes().is_empty());
8510            }
8511            assert_eq!(sem.available_permits(), 1);
8512            consumer.close().await;
8513        }
8514    }
8515
8516    #[tokio::test]
8517    async fn reservation_correlations_are_unique_and_match_frames_written_out_of_order() {
8518        let (shared, consumer, mut rx, handle, _) = reservation_stand_in(3, 3);
8519        let deadline = Instant::now() + Duration::from_secs(1);
8520        let first = consumer.reserve(&handle, deadline).await.unwrap();
8521        let second = consumer.reserve(&handle, deadline).await.unwrap();
8522        let third = consumer.reserve(&handle, deadline).await.unwrap();
8523        let ids = [
8524            first.correlation_id(),
8525            second.correlation_id(),
8526            third.correlation_id(),
8527        ];
8528        assert_eq!(ids.into_iter().collect::<HashSet<_>>().len(), 3);
8529        let opts = CallOptions {
8530            priority: Priority::Background,
8531            admission_class: AdmissionClass::Expedite,
8532            ..CallOptions::default()
8533        };
8534        let mut replies = Vec::new();
8535        for (reserved, expected_id, body) in [
8536            (third, ids[2], "third"),
8537            (first, ids[0], "first"),
8538            (second, ids[1], "second"),
8539        ] {
8540            let (corr, reply) = reserved.send(
8541                RequestBody::new(body.as_bytes().to_vec()).unwrap(),
8542                opts.clone(),
8543            );
8544            assert_eq!(corr, expected_id);
8545            replies.push((corr, body, reply));
8546        }
8547        rx.close();
8548        let writer = InstrumentedWriter::new(false);
8549        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8550        let bytes = writer.bytes();
8551        let mut bytes = bytes.as_slice();
8552        for (corr, body, reply) in replies {
8553            let frame = read_frame(&mut bytes).await.unwrap().unwrap();
8554            assert_eq!(frame.header.ty, FrameType::Request);
8555            assert_eq!(frame.header.corr, corr);
8556            assert_eq!(frame.header.channel, handle.channel);
8557            assert_eq!(frame.header.epoch, handle.epoch);
8558            assert_eq!(
8559                frame.header.flags,
8560                Flags::new(false, Priority::Background, false)
8561                    .with_admission_class(AdmissionClass::Expedite)
8562            );
8563            assert_eq!(frame.body, body.as_bytes());
8564            dispatch_frame(
8565                &shared,
8566                1,
8567                response_frame(handle.channel, handle.epoch, corr, body.as_bytes().to_vec()),
8568            )
8569            .await;
8570            assert_eq!(reply.await.unwrap(), body.as_bytes());
8571        }
8572        assert!(bytes.is_empty());
8573        consumer.close().await;
8574    }
8575
8576    #[tokio::test(start_paused = true)]
8577    async fn reservation_deadline_before_send_prevents_writing_without_polling_reply() {
8578        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8579        let reserved = consumer
8580            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8581            .await
8582            .unwrap();
8583        tokio::time::advance(Duration::from_secs(2)).await;
8584        let (_, reply) = reserved.send(
8585            RequestBody::new(b"expired".to_vec()).unwrap(),
8586            CallOptions::default(),
8587        );
8588        rx.close();
8589        let writer = InstrumentedWriter::new(false);
8590        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8591        assert!(writer.bytes().is_empty());
8592        assert!(matches!(reply.await, Err(CallError::NotSent(_))));
8593        assert_eq!(sem.available_permits(), 1);
8594        consumer.close().await;
8595    }
8596
8597    #[tokio::test(start_paused = true)]
8598    async fn reservation_deadline_bounds_writer_capacity_and_releases_credit() {
8599        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(2, 1);
8600        let first = consumer
8601            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8602            .await
8603            .unwrap();
8604        let second = consumer
8605            .reserve(&handle, Instant::now() + Duration::from_millis(25))
8606            .await;
8607        assert!(matches!(second, Err(CallError::NotSent(_))));
8608        assert_eq!(sem.available_permits(), 1);
8609        drop(first);
8610        assert_eq!(sem.available_permits(), 2);
8611        assert!(shared.lock_inner().pending.is_empty());
8612        assert!(rx.try_recv().is_err());
8613        consumer.close().await;
8614    }
8615
8616    #[tokio::test]
8617    async fn reservation_reconnect_during_writer_capacity_wait_fails_promptly_without_writing() {
8618        let (shared, consumer, mut old_rx, handle, sem) = reservation_stand_in(1, 1);
8619        let old_writer = shared.lock_inner().writer.clone().unwrap();
8620        let held_capacity = old_writer.reserve_owned().await.unwrap();
8621        let reserve = consumer.reserve(&handle, Instant::now() + Duration::from_secs(60));
8622        tokio::pin!(reserve);
8623        assert_pending(reserve.as_mut()).await;
8624        assert_eq!(sem.available_permits(), 0);
8625
8626        let mut replacement_rx = drop_and_replace_test_transport(&shared);
8627        assert_ne!(shared.lock_inner().generation, handle.connection_token());
8628        drop(held_capacity);
8629        let result = std::future::poll_fn(|cx| Poll::Ready(reserve.as_mut().poll(cx))).await;
8630        assert!(matches!(
8631            result,
8632            Poll::Ready(Err(CallError::StaleRouteHandle(stale))) if stale == handle
8633        ));
8634        assert!(shared.lock_inner().pending.is_empty());
8635        assert_eq!(sem.available_permits(), 1);
8636        assert!(old_rx.try_recv().is_err());
8637        assert!(replacement_rx.try_recv().is_err());
8638
8639        old_rx.close();
8640        replacement_rx.close();
8641        let writer = InstrumentedWriter::new(false);
8642        writer_loop(
8643            Arc::clone(&shared),
8644            writer.clone(),
8645            old_rx,
8646            handle.connection_token(),
8647        )
8648        .await;
8649        let generation = shared.lock_inner().generation;
8650        writer_loop(
8651            Arc::clone(&shared),
8652            writer.clone(),
8653            replacement_rx,
8654            generation,
8655        )
8656        .await;
8657        assert!(writer.bytes().is_empty());
8658        consumer.close().await;
8659    }
8660
8661    #[tokio::test]
8662    async fn reservation_reply_drop_cleans_up_without_polling() {
8663        let (shared, consumer, mut rx, handle, sem) = reservation_stand_in(1, 1);
8664        let reserved = consumer
8665            .reserve(&handle, Instant::now() + Duration::from_secs(1))
8666            .await
8667            .unwrap();
8668        let (_, reply) = reserved.send(
8669            RequestBody::new(b"request".to_vec()).unwrap(),
8670            CallOptions::default(),
8671        );
8672        drop(reply);
8673        assert!(shared.lock_inner().pending.is_empty());
8674        assert_eq!(sem.available_permits(), 1);
8675        rx.close();
8676        let writer = InstrumentedWriter::new(false);
8677        writer_loop(Arc::clone(&shared), writer.clone(), rx, 1).await;
8678        assert!(writer.bytes().is_empty());
8679        consumer.close().await;
8680    }
8681
8682    #[tokio::test]
8683    async fn writer_batches_ready_frames_into_one_flush() {
8684        const FRAME_COUNT: usize = 8;
8685
8686        let shared = writer_test_shared();
8687        let (live_writer, _live_rx) = mpsc::channel(1);
8688        let (tx, rx) = mpsc::channel(FRAME_COUNT + 1);
8689        let instrumented = InstrumentedWriter::new(false);
8690        let observer = instrumented.clone();
8691        let mut expected = Vec::with_capacity(FRAME_COUNT);
8692        let mut keys = Vec::with_capacity(FRAME_COUNT);
8693
8694        {
8695            let mut inner = shared.lock_inner();
8696            inner.writer = Some(live_writer);
8697            inner.daemon_ver = "0.39.0".into();
8698            for index in 0..FRAME_COUNT {
8699                let corr = index as u64 + 1;
8700                let frame = response_frame(7, 1, corr, vec![index as u8; index + 1]);
8701                let key = PendingKey {
8702                    generation: 1,
8703                    channel: 7,
8704                    epoch: 1,
8705                    corr,
8706                };
8707                let (pending_tx, _pending_rx) = oneshot::channel();
8708                inner
8709                    .pending
8710                    .insert(key, PendingEntry::unary(pending_tx, false, None, None));
8711                expected.push(frame.clone());
8712                keys.push(key);
8713                tx.try_send(WriteCommand {
8714                    frame,
8715                    pending: Some(key),
8716                })
8717                .expect("the burst should fit in the writer queue");
8718                if index == 0 {
8719                    tx.try_send(WriteCommand {
8720                        frame: response_frame(7, 1, 999, b"skip".to_vec()),
8721                        pending: Some(PendingKey {
8722                            generation: 1,
8723                            channel: 7,
8724                            epoch: 1,
8725                            corr: 999,
8726                        }),
8727                    })
8728                    .expect("the skipped command should fit in the writer queue");
8729                }
8730            }
8731        }
8732        drop(tx);
8733
8734        writer_loop(Arc::clone(&shared), instrumented, rx, 1).await;
8735
8736        {
8737            let inner = shared.lock_inner();
8738            for key in keys {
8739                assert!(
8740                    inner.pending.get(&key).is_some_and(|entry| entry.accepted),
8741                    "every written command must be marked accepted"
8742                );
8743            }
8744        }
8745
8746        let mut wire = std::io::Cursor::new(observer.bytes());
8747        for expected_frame in expected {
8748            let actual = read_frame(&mut wire)
8749                .await
8750                .expect("the emitted frame should decode")
8751                .expect("the emitted frame should be present");
8752            assert_eq!(actual, expected_frame);
8753        }
8754        assert!(
8755            read_frame(&mut wire)
8756                .await
8757                .expect("the end of the emitted burst should be clean")
8758                .is_none(),
8759            "the writer must not emit extra frames"
8760        );
8761
8762        let flush_count = observer.flush_count();
8763        assert_eq!(
8764            flush_count, 1,
8765            "a ready burst must be coalesced into one flush"
8766        );
8767        shared.close_sync("test complete");
8768    }
8769
8770    #[tokio::test]
8771    async fn writer_flush_failure_drops_generation_and_preserves_acceptance_classification() {
8772        let shared = writer_test_shared();
8773        let (live_writer, _live_rx) = mpsc::channel(1);
8774        let accepted_key = PendingKey {
8775            generation: 1,
8776            channel: 3,
8777            epoch: 1,
8778            corr: 1,
8779        };
8780        let not_sent_key = PendingKey {
8781            corr: 2,
8782            ..accepted_key
8783        };
8784        let (accepted_tx, accepted_rx) = oneshot::channel();
8785        let (not_sent_tx, not_sent_rx) = oneshot::channel();
8786        {
8787            let mut inner = shared.lock_inner();
8788            inner.writer = Some(live_writer);
8789            inner.daemon_ver = "0.39.0".into();
8790            inner.pending.insert(
8791                accepted_key,
8792                PendingEntry::unary(accepted_tx, false, None, None),
8793            );
8794            inner.pending.insert(
8795                not_sent_key,
8796                PendingEntry::unary(not_sent_tx, false, None, None),
8797            );
8798        }
8799
8800        let (tx, rx) = mpsc::channel(1);
8801        tx.send(WriteCommand {
8802            frame: response_frame(3, 1, accepted_key.corr, b"accepted".to_vec()),
8803            pending: Some(accepted_key),
8804        })
8805        .await
8806        .unwrap();
8807        drop(tx);
8808
8809        writer_loop(Arc::clone(&shared), InstrumentedWriter::new(true), rx, 1).await;
8810
8811        assert!(
8812            shared.lock_inner().writer.is_none(),
8813            "a flush failure must drop the active generation"
8814        );
8815        let accepted_error = accepted_rx
8816            .await
8817            .expect("the accepted request should be settled")
8818            .into_call_result()
8819            .unwrap_err();
8820        assert!(matches!(accepted_error, CallError::OutcomeUnknown(_)));
8821        assert_eq!(
8822            accepted_error.outcome_cause(),
8823            Some(OutcomeUnknownCause::WriterClosed)
8824        );
8825        let not_sent_error = not_sent_rx
8826            .await
8827            .expect("the unwritten request should be settled")
8828            .into_call_result()
8829            .unwrap_err();
8830        assert!(matches!(not_sent_error, CallError::NotSent(_)));
8831        assert_eq!(not_sent_error.outcome_cause(), None);
8832        shared.close_sync("test complete");
8833    }
8834
8835    #[tokio::test]
8836    async fn consumer_close_attaches_outcome_cause_to_pending_call() {
8837        let shared = writer_test_shared();
8838        let (writer, _writer_rx) = mpsc::channel(1);
8839        shared.lock_inner().writer = Some(writer);
8840        shared.lock_inner().daemon_ver = "0.39.0".into();
8841        let (tx, rx) = oneshot::channel();
8842        let mut entry = PendingEntry::unary(tx, false, None, None);
8843        entry.accepted = true;
8844        shared.lock_inner().pending.insert(
8845            PendingKey {
8846                generation: 1,
8847                channel: 3,
8848                epoch: 1,
8849                corr: 1,
8850            },
8851            entry,
8852        );
8853        let consumer = SubcConsumer { shared };
8854        consumer.close().await;
8855        let err = rx.await.unwrap().into_call_result().unwrap_err();
8856        assert_eq!(
8857            err.outcome_cause(),
8858            Some(OutcomeUnknownCause::ConsumerClosed)
8859        );
8860        assert_eq!(err.to_string(), "request outcome unknown: consumer closed");
8861        assert_eq!(err.close_reason(), None);
8862    }
8863
8864    #[tokio::test]
8865    async fn subscription_completion_drop_attaches_outcome_cause() {
8866        let (tx, rx) = oneshot::channel();
8867        let closed = SubscriptionClosed { rx };
8868        drop(tx);
8869        let err = closed.await.unwrap_err();
8870        assert_eq!(
8871            err.outcome_cause(),
8872            Some(OutcomeUnknownCause::CompletionFailed)
8873        );
8874        assert_eq!(
8875            err.to_string(),
8876            "request outcome unknown: subscription closed result channel dropped"
8877        );
8878    }
8879
8880    #[test]
8881    fn reconnect_classifier_treats_auth_failure_as_transient() {
8882        // Key rotation across a daemon restart on the fixed port: a client racing
8883        // the restart reads the pre-rotation file, connects, and fails the proof.
8884        // That must be retryable — each retry re-reads the file, so the next
8885        // attempt picks up the rotated key. Treating it as a permanent impostor
8886        // verdict would turn every daemon restart into a permanent client wedge.
8887        let auth = ConsumerError::Auth {
8888            path: PathBuf::from("/tmp/subc-connection.json"),
8889            endpoint: "127.0.0.1:8757".to_string(),
8890            source: subc_transport::AuthError::InvalidServerProof,
8891        };
8892        assert!(is_reconnect_transient(&auth), "rotation race must retry");
8893
8894        // Absent file mid-restart stays transient; malformed file stays permanent.
8895        let absent = ConsumerError::ConnectionFile {
8896            path: PathBuf::from("/tmp/subc-connection.json"),
8897            source: ConnectionFileError::Io {
8898                op: "read",
8899                path: PathBuf::from("/tmp/subc-connection.json"),
8900                source: io::Error::new(io::ErrorKind::NotFound, "gone"),
8901            },
8902        };
8903        assert!(is_reconnect_transient(&absent));
8904    }
8905
8906    #[tokio::test]
8907    async fn newer_drop_supersedes_reconnect_and_ignores_stale_completion() {
8908        let shared = Arc::new(reader_skew_tests::legacy_shared(
8909            PathBuf::from("/tmp/does-not-exist"),
8910            ConsumerOptions::default(),
8911        ));
8912        let stale_task = tokio::spawn(std::future::pending::<()>());
8913        {
8914            let mut inner = shared.lock_inner();
8915            inner.generation = 2;
8916            inner.reconnect = ReconnectState::Background {
8917                generation: 1,
8918                task: stale_task,
8919            };
8920        }
8921
8922        assert!(shared.spawn_reconnect(2));
8923        assert!(matches!(
8924            &shared.lock_inner().reconnect,
8925            ReconnectState::Background { generation, .. } if *generation == 2
8926        ));
8927
8928        shared.finish_background_reconnect(1);
8929        assert!(matches!(
8930            &shared.lock_inner().reconnect,
8931            ReconnectState::Background { generation, .. } if *generation == 2
8932        ));
8933        shared.close_sync("test complete");
8934    }
8935
8936    #[test]
8937    fn retryable_route_open_codes_are_code_specific() {
8938        for code in [
8939            "module_reloading",
8940            "module_warming",
8941            "target_unavailable",
8942            "module_timeout",
8943        ] {
8944            assert!(is_retryable_route_open_code(code), "{code} should retry");
8945        }
8946        // "No module of this id is registered or supervised here" is a typo or
8947        // an undeployed peer: the daemon reports a configured-but-late target
8948        // with module_warming/target_unavailable, so retrying unknown_module
8949        // in place only papers over an unsupervised module's HELLO race.
8950        assert!(
8951            !is_retryable_route_open_code(error_codes::UNKNOWN_MODULE),
8952            "unknown_module is terminal"
8953        );
8954        assert!(!is_retryable_route_open_code(error_codes::MODULE_REMOVED));
8955        assert!(!is_retryable_route_open_code("invalid_project_root"));
8956        assert!(!is_retryable_route_open_code("route_rejected"));
8957        assert!(
8958            !is_retryable_route_open_code("capability_forbidden"),
8959            "a capability policy refusal must not enter the route.open retry set"
8960        );
8961    }
8962
8963    #[test]
8964    fn two_routes_record_distinct_reasons_and_reuse_clears_channel() {
8965        let shared = Arc::new(reader_skew_tests::legacy_shared(
8966            PathBuf::new(),
8967            ConsumerOptions::default(),
8968        ));
8969        let (writer, _rx) = mpsc::channel(8);
8970        shared.lock_inner().writer = Some(writer);
8971        shared.lock_inner().daemon_ver = "0.39.0".into();
8972        shared.install_ingress_handle(RouteHandle::new(7, 1, 1));
8973        shared.install_ingress_handle(RouteHandle::new(9, 1, 1));
8974        {
8975            let mut inner = shared.lock_inner();
8976            inner.route_modules.insert(7, "provider".into());
8977            inner.route_modules.insert(9, "provider".into());
8978        }
8979        shared.control_push(br#"{"op":"route.closed","module_id":"provider","channels":[7],"reason":"scope_ended"}"#);
8980        shared.control_push(
8981            br#"{"op":"route.closing","module_id":"provider","channels":[9],"reason":"restart"}"#,
8982        );
8983        shared.control_push(
8984            br#"{"op":"route.closing","module_id":"provider","channels":[7],"reason":"crash"}"#,
8985        );
8986        assert_eq!(
8987            shared.lock_inner().route_end_reason(7),
8988            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded)
8989        );
8990        assert_eq!(
8991            shared.lock_inner().route_end_reason(9),
8992            RouteEndReason::Daemon(RouteCloseReason::Restart)
8993        );
8994        shared.control_push(
8995            br#"{"op":"route.closed","module_id":"provider","channels":[9],"reason":"crash"}"#,
8996        );
8997        assert_eq!(
8998            shared.lock_inner().route_end_reason(9),
8999            RouteEndReason::Daemon(RouteCloseReason::Crash)
9000        );
9001        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"disable"}"#);
9002        shared.install_ingress_handle(RouteHandle::new(7, 2, 1));
9003        assert_eq!(
9004            shared.lock_inner().route_end_reason(7),
9005            RouteEndReason::Unknown
9006        );
9007        assert_eq!(shared.lock_inner().route_end(7).terminal, None);
9008    }
9009
9010    #[test]
9011    fn legacy_route_push_falls_back_only_when_channels_are_absent() {
9012        let shared = reader_skew_tests::legacy_shared(PathBuf::new(), ConsumerOptions::default());
9013        shared
9014            .lock_inner()
9015            .route_modules
9016            .insert(7, "provider".into());
9017        shared.control_push(
9018            br#"{"op":"route.closed","module_id":"provider","channels":[],"reason":"crash"}"#,
9019        );
9020        assert_eq!(
9021            shared.lock_inner().route_end_reason(7),
9022            RouteEndReason::Unknown
9023        );
9024        shared.control_push(br#"{"op":"route.closing","module_id":"provider","reason":"restart"}"#);
9025        assert_eq!(
9026            shared.lock_inner().route_end_reason(7),
9027            RouteEndReason::Daemon(RouteCloseReason::Restart)
9028        );
9029        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"crash"}"#);
9030        assert_eq!(
9031            shared.lock_inner().route_end_reason(7),
9032            RouteEndReason::Daemon(RouteCloseReason::Crash)
9033        );
9034    }
9035
9036    #[tokio::test]
9037    async fn sdk_teardown_paths_attach_caller_and_connection_loss_reasons() {
9038        for local in [true, false] {
9039            let shared = Arc::new(reader_skew_tests::legacy_shared(
9040                PathBuf::new(),
9041                ConsumerOptions::default(),
9042            ));
9043            let (writer, _writer_rx) = mpsc::channel(8);
9044            shared.lock_inner().writer = Some(writer);
9045            shared.lock_inner().daemon_ver = "0.39.0".into();
9046            let handle = RouteHandle::new(7, 1, 1);
9047            shared.install_ingress_handle(handle);
9048            let (tx, rx) = oneshot::channel();
9049            let mut entry = PendingEntry::unary(tx, false, None, None);
9050            entry.accepted = true;
9051            shared.lock_inner().pending.insert(
9052                PendingKey {
9053                    generation: 1,
9054                    channel: 7,
9055                    epoch: 1,
9056                    corr: 1,
9057                },
9058                entry,
9059            );
9060            if local {
9061                shared
9062                    .close_handle(handle, &CloseRouteOptions::default())
9063                    .await
9064                    .unwrap();
9065            } else {
9066                shared.handle_generation_drop(1, "connection gone".into());
9067            }
9068            let err = rx.await.unwrap().into_call_result().err().unwrap();
9069            assert!(matches!(err, CallError::OutcomeUnknown(_)));
9070            assert_eq!(
9071                err.outcome_cause(),
9072                Some(if local {
9073                    OutcomeUnknownCause::RouteEnded
9074                } else {
9075                    OutcomeUnknownCause::ConnectionFailed
9076                })
9077            );
9078            let shared_failure = SharedCallFailure::from(err);
9079            let err = shared_failure.into_call_error();
9080            assert_eq!(
9081                err.close_reason(),
9082                Some(&if local {
9083                    RouteEndReason::ClosedByCaller
9084                } else {
9085                    RouteEndReason::ConnectionLost
9086                })
9087            );
9088            shared.close_sync("test complete");
9089        }
9090    }
9091
9092    #[tokio::test]
9093    async fn route_end_reasons_preserve_pending_retry_classes() {
9094        for reason in [
9095            RouteEndReason::ClosedByCaller,
9096            RouteEndReason::ConnectionLost,
9097            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded),
9098            RouteEndReason::Unknown,
9099        ] {
9100            for accepted in [false, true] {
9101                let (tx, rx) = oneshot::channel();
9102                let mut entry = PendingEntry::unary(tx, false, None, None);
9103                entry.accepted = accepted;
9104                settle_route_pending_entries(vec![entry], "route ended".into(), reason.clone());
9105                let err = rx.await.unwrap().into_call_result().err().unwrap();
9106                assert_eq!(err.close_reason(), Some(&reason));
9107                assert_eq!(err.terminal(), None);
9108                assert_eq!(matches!(err, CallError::OutcomeUnknown(_)), accepted);
9109                assert_eq!(matches!(err, CallError::NotSent(_)), !accepted);
9110            }
9111        }
9112    }
9113
9114    #[test]
9115    fn route_closing_does_not_supply_or_overwrite_a_terminal_verdict() {
9116        let shared = Shared::new(PathBuf::new(), ConsumerOptions::default());
9117        shared.control_push(
9118            br#"{"op":"route.closing","channels":[7],"reason":"restart","terminal":true}"#,
9119        );
9120        assert_eq!(shared.lock_inner().route_end(7).terminal, None);
9121        shared.control_push(
9122            br#"{"op":"route.closed","channels":[7],"reason":"restart","terminal":false}"#,
9123        );
9124        shared.control_push(
9125            br#"{"op":"route.closing","channels":[7],"reason":"restart","terminal":true}"#,
9126        );
9127        assert_eq!(shared.lock_inner().route_end(7).terminal, Some(false));
9128        assert_eq!(CallError::not_sent("not a route end").terminal(), None);
9129    }
9130
9131    #[test]
9132    fn route_close_reason_classifier_accepts_capability_denied_and_fails_closed_for_unknown() {
9133        assert_eq!(
9134            RouteCloseReason::from_wire("capability_denied"),
9135            RouteCloseReason::CapabilityDenied
9136        );
9137        assert_eq!(
9138            RouteCloseReason::from_wire("capability_denied").disposition(),
9139            RouteCloseDisposition::MustNotReopen
9140        );
9141        assert_eq!(
9142            RouteCloseReason::from_wire("future_policy_reason").disposition(),
9143            RouteCloseDisposition::MustNotReopen,
9144            "an unknown close reason must receive the strictest handling"
9145        );
9146        assert_eq!(
9147            RouteCloseReason::from_wire("reload").disposition(),
9148            RouteCloseDisposition::MayReopen,
9149            "control proves the classifier can distinguish a conservative default"
9150        );
9151    }
9152
9153    #[tokio::test]
9154    async fn module_removed_fails_fast_while_module_reloading_retries_at_the_same_route_open_call_site(
9155    ) {
9156        // Serves rejections with `code` until the caller settles, returning
9157        // (attempts_served, result). The retryable arm must keep retrying past
9158        // any attempt count until the DEADLINE binds — the attempt cap in the
9159        // options below is deliberately tiny so a regression that re-couples
9160        // attempts into the retry condition (the 3.1s-effective-budget defect)
9161        // stops the loop at 2 and fails the `> 2` assertion by name.
9162        async fn reject_route_open_attempts(code: &str, deadline: Duration) -> (usize, CallError) {
9163            let shared = Arc::new(reader_skew_tests::legacy_shared(
9164                PathBuf::from("/tmp/does-not-exist"),
9165                ConsumerOptions::default(),
9166            ));
9167            let (writer, mut receiver) = mpsc::channel(4);
9168            {
9169                let mut inner = shared.lock_inner();
9170                inner.writer = Some(writer);
9171                inner.daemon_ver = "0.39.0".into();
9172            }
9173            let consumer = SubcConsumer {
9174                shared: Arc::clone(&shared),
9175            };
9176            let target = RouteTarget::ToolProvider {
9177                module_id: "retry-polarity".to_string(),
9178            };
9179            let identity = BindIdentity::new("test".to_string(), code.to_string());
9180            let options = CallOptions {
9181                timeout: Duration::from_secs(2),
9182                route_retry: RetryBackoff {
9183                    base: Duration::ZERO,
9184                    cap: Duration::ZERO,
9185                    max_attempts: 2,
9186                },
9187                route_retry_deadline: deadline,
9188                ..CallOptions::default()
9189            };
9190            let mut task =
9191                tokio::spawn(async move { consumer.open_route(target, identity, options).await });
9192
9193            let mut attempts = 0usize;
9194            let result = loop {
9195                tokio::select! {
9196                    command = receiver.recv() => {
9197                        // The consumer tears the writer down when the open
9198                        // settles, so a closed channel here means the task is
9199                        // finishing — join it rather than treating the race as
9200                        // a broken harness.
9201                        let Some(command) = command else {
9202                            break task.await.unwrap().expect_err("route.open must reject");
9203                        };
9204                        attempts += 1;
9205                        let body =
9206                            serde_json::to_vec(&ErrorBody::new(code, "test rejection")).unwrap();
9207                        assert!(
9208                            dispatch_frame(
9209                                &shared,
9210                                1,
9211                                Frame::build(
9212                                    FrameType::Error,
9213                                    Flags::new(false, Priority::Interactive, false),
9214                                    0,
9215                                    0,
9216                                    command.frame.header.corr,
9217                                    body,
9218                                )
9219                                .unwrap(),
9220                            )
9221                            .await
9222                        );
9223                    }
9224                    joined = &mut task => {
9225                        break joined.unwrap().expect_err("route.open must reject");
9226                    }
9227                }
9228            };
9229            assert!(
9230                receiver.try_recv().is_err(),
9231                "a settled route.open must not queue another attempt"
9232            );
9233            (attempts, result)
9234        }
9235
9236        let (reloading_attempts, reloading) =
9237            reject_route_open_attempts(error_codes::MODULE_RELOADING, Duration::from_millis(150))
9238                .await;
9239        assert!(matches!(reloading, CallError::NotSent(_)));
9240        assert!(
9241            reloading_attempts > 2,
9242            "reloading retries must run until the deadline, not an attempt cap \
9243             (served {reloading_attempts} attempts against max_attempts=2)"
9244        );
9245
9246        let (removed_attempts, removed) =
9247            reject_route_open_attempts(error_codes::MODULE_REMOVED, Duration::from_millis(150))
9248                .await;
9249        assert!(matches!(removed, CallError::NotSent(_)));
9250        assert_eq!(
9251            removed_attempts, 1,
9252            "terminal codes settle on the first answer"
9253        );
9254    }
9255
9256    /// splitmix64 over a counter: a seeded stand-in for the consumer's random
9257    /// source, so jittered delays are reproducible.
9258    fn seeded_random(seed: u64) -> Box<dyn Fn() -> f64 + Send + Sync> {
9259        let state = AtomicU64::new(seed);
9260        Box::new(move || {
9261            let mut z = state
9262                .fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
9263                .wrapping_add(0x9E37_79B9_7F4A_7C15);
9264            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
9265            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
9266            z ^= z >> 31;
9267            (z >> 11) as f64 / (1u64 << 53) as f64
9268        })
9269    }
9270
9271    /// A consumer wired to an in-memory writer, standing in for a daemon that
9272    /// the test answers by hand.
9273    fn route_open_stand_in(
9274        random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
9275    ) -> (Arc<Shared>, Arc<SubcConsumer>, mpsc::Receiver<WriteCommand>) {
9276        let mut shared = reader_skew_tests::legacy_shared(
9277            PathBuf::from("/tmp/does-not-exist"),
9278            ConsumerOptions::default(),
9279        );
9280        shared.random_unit = random_unit;
9281        let shared = Arc::new(shared);
9282        let (writer, receiver) = mpsc::channel(64);
9283        shared.lock_inner().writer = Some(writer);
9284        shared.lock_inner().daemon_ver = "0.39.0".into();
9285        let consumer = Arc::new(SubcConsumer {
9286            shared: Arc::clone(&shared),
9287        });
9288        (shared, consumer, receiver)
9289    }
9290
9291    fn restart_target(module_id: &str) -> RouteTarget {
9292        RouteTarget::ToolProvider {
9293            module_id: module_id.to_string(),
9294        }
9295    }
9296
9297    fn restart_identity() -> BindIdentity {
9298        BindIdentity::new("test".to_string(), "restart".to_string())
9299    }
9300
9301    /// The daemon's answer to one route.open: accept it on `channel`, or refuse
9302    /// it with `refusal`.
9303    fn route_open_answer(corr: u64, channel: u16, refusal: Option<ErrorBody>) -> Frame {
9304        match refusal {
9305            None => response_frame(
9306                0,
9307                0,
9308                corr,
9309                serde_json::to_vec(&ClientControlResponse::RouteOpen {
9310                    request_window: None,
9311                    watch_window: None,
9312                    route_channel: channel,
9313                    route_epoch: 1,
9314                })
9315                .unwrap(),
9316            ),
9317            Some(body) => Frame::build(
9318                FrameType::Error,
9319                Flags::new(false, Priority::Interactive, false),
9320                0,
9321                0,
9322                corr,
9323                serde_json::to_vec(&body).unwrap(),
9324            )
9325            .unwrap(),
9326        }
9327    }
9328
9329    /// Answer every route.open the consumer writes, as `answer` decides from the
9330    /// open's target module, until `task` finishes.
9331    async fn answer_route_opens<T>(
9332        shared: &Arc<Shared>,
9333        receiver: &mut mpsc::Receiver<WriteCommand>,
9334        task: &mut JoinHandle<T>,
9335        mut answer: impl FnMut(&str) -> Option<ErrorBody>,
9336    ) -> T {
9337        let mut next_channel = 40u16;
9338        loop {
9339            tokio::select! {
9340                command = receiver.recv() => {
9341                    let Some(command) = command else {
9342                        return (&mut *task).await.unwrap();
9343                    };
9344                    let request: serde_json::Value =
9345                        serde_json::from_slice(&command.frame.body).unwrap();
9346                    let module_id = request["target"]["module_id"].as_str().unwrap().to_string();
9347                    next_channel += 1;
9348                    let frame = route_open_answer(
9349                        command.frame.header.corr,
9350                        next_channel,
9351                        answer(&module_id),
9352                    );
9353                    assert!(dispatch_frame(shared, 1, frame).await);
9354                }
9355                joined = &mut *task => return joined.unwrap(),
9356            }
9357        }
9358    }
9359
9360    fn reloading() -> ErrorBody {
9361        ErrorBody::new(error_codes::MODULE_RELOADING, "module is reloading")
9362    }
9363
9364    fn drain_call<'a>(
9365        consumer: &'a SubcConsumer,
9366        body: &'static [u8],
9367    ) -> impl Future<Output = Result<Vec<u8>, CallError>> + 'a {
9368        consumer.call(
9369            restart_target("plexus"),
9370            restart_identity(),
9371            body.to_vec(),
9372            CallOptions {
9373                timeout: Duration::from_secs(5),
9374                ..CallOptions::default()
9375            },
9376        )
9377    }
9378
9379    async fn refuse_during_drain(shared: &Arc<Shared>, request: &Frame) {
9380        let frame = Frame::build(
9381            FrameType::Error,
9382            request.header.flags,
9383            request.header.channel,
9384            request.header.epoch,
9385            request.header.corr,
9386            serde_json::to_vec(&reloading()).unwrap(),
9387        )
9388        .unwrap();
9389        assert!(dispatch_frame(shared, 1, frame).await);
9390    }
9391
9392    async fn reply_to_drain_call(shared: &Arc<Shared>, request: Frame) {
9393        assert_eq!(request.header.ty, FrameType::Request);
9394        assert!(
9395            dispatch_frame(
9396                shared,
9397                1,
9398                response_frame(
9399                    request.header.channel,
9400                    request.header.epoch,
9401                    request.header.corr,
9402                    request.body,
9403                ),
9404            )
9405            .await
9406        );
9407    }
9408
9409    #[tokio::test(start_paused = true)]
9410    async fn shared_route_drain_delivers_both_refusals_and_resends_both_calls() {
9411        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9412        let (_, old) = open_answered(
9413            &shared,
9414            &consumer,
9415            &mut receiver,
9416            None,
9417            41,
9418            "initial shared route",
9419        )
9420        .await;
9421        let mut seed = Box::pin(drain_call(&consumer, b"seed"));
9422        assert_pending(seed.as_mut()).await;
9423        reply_to_drain_call(&shared, receiver.recv().await.unwrap().frame).await;
9424        assert_eq!(seed.await.unwrap(), b"seed");
9425        shared.control_push(
9426            &serde_json::to_vec(&serde_json::json!({
9427                "op": "route.closing", "module_id": "plexus",
9428                "channels": [old.channel], "terminal": false
9429            }))
9430            .unwrap(),
9431        );
9432        let mut first = Box::pin(drain_call(&consumer, b"first"));
9433        let mut second = Box::pin(drain_call(&consumer, b"second"));
9434        assert_pending(first.as_mut()).await;
9435        assert_pending(second.as_mut()).await;
9436        let first_command = receiver.recv().await.unwrap();
9437        let second_command = receiver.recv().await.unwrap();
9438        // Observing a frame at the daemon means the real writer accepted it.
9439        assert!(shared.mark_pending_accepted(first_command.pending.unwrap()));
9440        assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
9441        let first_request = first_command.frame;
9442        let second_request = second_command.frame;
9443        assert_eq!(first_request.header.channel, old.channel);
9444        assert_eq!(second_request.header.channel, old.channel);
9445
9446        refuse_during_drain(&shared, &first_request).await;
9447        assert_pending(first.as_mut()).await;
9448        // Holding route.open unanswered is the barrier: the first call has
9449        // invalidated the old route before its sibling's refusal arrives.
9450        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
9451        refuse_during_drain(&shared, &second_request).await;
9452        for (ty, channel, epoch, corr) in [
9453            (FrameType::Goodbye, old.channel, old.epoch, 0),
9454            (FrameType::Ping, 0, 0, 991),
9455        ] {
9456            let frame = Frame::build(
9457                ty,
9458                Flags::new(false, Priority::Interactive, false),
9459                channel,
9460                epoch,
9461                corr,
9462                Vec::new(),
9463            )
9464            .unwrap();
9465            assert!(dispatch_frame(&shared, 1, frame).await);
9466        }
9467        // The same dispatcher used by the socket reader emits Pong only after
9468        // processing the second refusal and the old-route GOODBYE.
9469        let pong = receiver.recv().await.unwrap().frame;
9470        assert_eq!(pong.header.ty, FrameType::Pong);
9471        assert_eq!(pong.header.corr, 991);
9472        assert_pending(second.as_mut()).await;
9473        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
9474        assert_pending(first.as_mut()).await;
9475        assert_pending(second.as_mut()).await;
9476        while let Ok(command) = receiver.try_recv() {
9477            assert_eq!(command.frame.header.channel, 42);
9478            reply_to_drain_call(&shared, command.frame).await;
9479        }
9480        assert_eq!(first.await.expect("first call resends"), b"first");
9481        assert_eq!(
9482            second.await.expect("second refusal must not time out"),
9483            b"second"
9484        );
9485        assert!(shared.lock_inner().pending.is_empty());
9486    }
9487
9488    #[tokio::test(start_paused = true)]
9489    async fn shared_route_drain_preserves_unrefused_reply_without_resending() {
9490        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9491        let (_, old) = open_answered(
9492            &shared,
9493            &consumer,
9494            &mut receiver,
9495            None,
9496            41,
9497            "initial shared route",
9498        )
9499        .await;
9500        let mut first = Box::pin(drain_call(&consumer, b"refused"));
9501        let mut second = Box::pin(drain_call(&consumer, b"executing"));
9502        assert_pending(first.as_mut()).await;
9503        assert_pending(second.as_mut()).await;
9504        let first_request = receiver.recv().await.unwrap().frame;
9505        let second_request = receiver.recv().await.unwrap().frame;
9506        let executing_corr = second_request.header.corr;
9507        assert_eq!(second_request.header.channel, old.channel);
9508        let mut executing_requests = 1;
9509
9510        refuse_during_drain(&shared, &first_request).await;
9511        assert_pending(first.as_mut()).await;
9512        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
9513        assert_pending(second.as_mut()).await;
9514        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
9515        assert_pending(first.as_mut()).await;
9516        assert_pending(second.as_mut()).await;
9517        while let Ok(command) = receiver.try_recv() {
9518            assert_eq!(command.frame.header.ty, FrameType::Request);
9519            // Managed resends allocate a new corr; count the logical request's
9520            // body as well so an unsafe resend cannot hide behind a new corr.
9521            if command.frame.header.corr == executing_corr || command.frame.body == b"executing" {
9522                executing_requests += 1;
9523            }
9524            reply_to_drain_call(&shared, command.frame).await;
9525        }
9526        reply_to_drain_call(&shared, second_request).await;
9527        assert_eq!(first.await.expect("refused call resends"), b"refused");
9528        assert_eq!(
9529            second.await.expect("real old-route reply arrives"),
9530            b"executing"
9531        );
9532        assert_eq!(executing_requests, 1, "unrefused call must never resend");
9533    }
9534
9535    #[tokio::test(start_paused = true)]
9536    async fn invalidated_route_ingress_is_uninstalled_after_last_pending_settles() {
9537        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9538        let (_, old) = open_answered(
9539            &shared,
9540            &consumer,
9541            &mut receiver,
9542            None,
9543            41,
9544            "initial shared route",
9545        )
9546        .await;
9547        let mut first = Box::pin(drain_call(&consumer, b"first"));
9548        let mut second = Box::pin(drain_call(&consumer, b"second"));
9549        assert_pending(first.as_mut()).await;
9550        assert_pending(second.as_mut()).await;
9551        let first_request = receiver.recv().await.unwrap().frame;
9552        let second_request = receiver.recv().await.unwrap().frame;
9553        refuse_during_drain(&shared, &first_request).await;
9554        assert_pending(first.as_mut()).await;
9555        let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9556        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
9557        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_ok());
9558        reply_to_drain_call(&shared, second_request).await;
9559        assert_eq!(second.await.unwrap(), b"second");
9560        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
9561        assert!(shared.lock_inner().retired_routes.is_empty());
9562        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_err());
9563        drop(first);
9564    }
9565
9566    #[tokio::test(start_paused = true)]
9567    async fn invalidated_route_ingress_cleans_up_on_drop_deadline_goodbye_and_disconnect() {
9568        for ending in ["drop", "deadline", "goodbye", "disconnect"] {
9569            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9570            let (_, old) = open_answered(
9571                &shared,
9572                &consumer,
9573                &mut receiver,
9574                None,
9575                41,
9576                "initial shared route",
9577            )
9578            .await;
9579            let mut first = Box::pin(drain_call(&consumer, b"refused"));
9580            let mut second = Box::pin(drain_call(&consumer, b"executing"));
9581            assert_pending(first.as_mut()).await;
9582            assert_pending(second.as_mut()).await;
9583            let first_request = receiver.recv().await.unwrap().frame;
9584            let second_command = receiver.recv().await.unwrap();
9585            assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
9586            refuse_during_drain(&shared, &first_request).await;
9587            assert_pending(first.as_mut()).await;
9588            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9589            match ending {
9590                "drop" => drop(second),
9591                "deadline" => {
9592                    assert_eq!(
9593                        second.await.unwrap_err().outcome_cause(),
9594                        Some(OutcomeUnknownCause::Deadline)
9595                    );
9596                }
9597                "goodbye" => {
9598                    let frame = Frame::build(
9599                        FrameType::Goodbye,
9600                        Flags::new(false, Priority::Interactive, false),
9601                        old.channel,
9602                        old.epoch,
9603                        0,
9604                        Vec::new(),
9605                    )
9606                    .unwrap();
9607                    assert!(dispatch_frame(&shared, 1, frame).await);
9608                    assert_eq!(
9609                        second.await.unwrap_err().outcome_cause(),
9610                        Some(OutcomeUnknownCause::RouteEnded)
9611                    );
9612                }
9613                "disconnect" => {
9614                    shared.handle_generation_drop(1, "test disconnect".into());
9615                    assert_eq!(
9616                        second.await.unwrap_err().outcome_cause(),
9617                        Some(OutcomeUnknownCause::ConnectionFailed)
9618                    );
9619                }
9620                _ => unreachable!(),
9621            }
9622            assert_eq!(
9623                shared.ingress_handle(1, old.channel, old.epoch),
9624                None,
9625                "{ending}"
9626            );
9627            assert!(shared.lock_inner().retired_routes.is_empty(), "{ending}");
9628            assert!(
9629                route_reverse_request_registry(old.reverse_request_registry_id()).is_err(),
9630                "{ending}"
9631            );
9632            drop(first);
9633        }
9634    }
9635
9636    #[tokio::test(start_paused = true)]
9637    async fn invalidated_route_subscription_cancel_and_overflow_uninstall_ingress() {
9638        for overflow in [false, true] {
9639            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9640            let (_, old) = open_answered(
9641                &shared,
9642                &consumer,
9643                &mut receiver,
9644                None,
9645                41,
9646                "initial shared route",
9647            )
9648            .await;
9649            let mut subscription = consumer
9650                .subscribe_route(&old, b"watch".to_vec(), SubscribeOptions::default())
9651                .await
9652                .unwrap();
9653            let request = receiver.recv().await.unwrap().frame;
9654            let mut call = Box::pin(drain_call(&consumer, b"refused"));
9655            assert_pending(call.as_mut()).await;
9656            let refused = receiver.recv().await.unwrap().frame;
9657            refuse_during_drain(&shared, &refused).await;
9658            assert_pending(call.as_mut()).await;
9659            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
9660            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
9661            assert!(matches!(
9662                consumer
9663                    .request(&old, b"new".to_vec(), CallOptions::default())
9664                    .await,
9665                Err(CallError::StaleRouteHandle(_))
9666            ));
9667            if overflow {
9668                for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
9669                    assert!(
9670                        dispatch_frame(
9671                            &shared,
9672                            1,
9673                            watch_terminal(&request, FrameType::StreamData, vec![1])
9674                        )
9675                        .await
9676                    );
9677                }
9678                assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
9679            } else {
9680                subscription.unsubscribe().unwrap();
9681                assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
9682            }
9683            assert_eq!(
9684                receiver.recv().await.unwrap().frame.header.ty,
9685                FrameType::Cancel
9686            );
9687            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
9688            assert!(shared.lock_inner().retired_routes.is_empty());
9689            drop(call);
9690        }
9691    }
9692
9693    #[tokio::test(start_paused = true)]
9694    async fn route_open_stops_after_one_refusal_when_the_module_is_not_expected_back() {
9695        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9696        let refusal = ErrorBody::new(error_codes::TARGET_UNAVAILABLE, "module is disabled")
9697            .with_detail(serde_json::json!({"state": "disabled", "expected_back": false}));
9698        let mut task = tokio::spawn(async move {
9699            consumer
9700                .open_route(
9701                    restart_target("disabled"),
9702                    restart_identity(),
9703                    CallOptions::default(),
9704                )
9705                .await
9706        });
9707        let mut opens = 0;
9708        let result = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9709            opens += 1;
9710            (opens == 1).then(|| refusal.clone())
9711        })
9712        .await;
9713
9714        assert_eq!(opens, 1, "the daemon said the target would not recover");
9715        assert_eq!(result.unwrap_err().route_open_refusal(), Some(&refusal));
9716    }
9717
9718    #[tokio::test(start_paused = true)]
9719    async fn route_open_retries_when_expected_back_is_true_or_absent() {
9720        for expected_back in [Some(true), None] {
9721            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9722            let mut refusal = ErrorBody::new(error_codes::TARGET_UNAVAILABLE, "module is stopped");
9723            refusal.detail = expected_back.map(|value| serde_json::json!({"expected_back": value}));
9724            let mut task = tokio::spawn(async move {
9725                consumer
9726                    .open_route(
9727                        restart_target("stopped"),
9728                        restart_identity(),
9729                        CallOptions::default(),
9730                    )
9731                    .await
9732            });
9733            let mut opens = 0;
9734            let result = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9735                opens += 1;
9736                (opens == 1).then(|| refusal.clone())
9737            })
9738            .await;
9739
9740            assert!(result.is_ok(), "{expected_back:?}: {result:?}");
9741            assert_eq!(opens, 2, "{expected_back:?}");
9742        }
9743    }
9744
9745    #[tokio::test(start_paused = true)]
9746    async fn the_default_retry_deadline_outlasts_a_60s_restart_and_the_open_succeeds() {
9747        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
9748        let started = Instant::now();
9749        // A call deadline past the retry deadline, so the retry deadline is
9750        // the one under test.
9751        let options = CallOptions {
9752            timeout: Duration::from_secs(120),
9753            ..CallOptions::default()
9754        };
9755        let mut task = tokio::spawn(async move {
9756            consumer
9757                .open_route(restart_target("restarting"), restart_identity(), options)
9758                .await
9759        });
9760        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9761            (started.elapsed() < Duration::from_secs(60)).then(reloading)
9762        })
9763        .await;
9764        let handle =
9765            opened.unwrap_or_else(|err| panic!("the open must survive the restart: {err}"));
9766        assert!(handle.channel > 40);
9767        assert!(started.elapsed() >= Duration::from_secs(60));
9768    }
9769
9770    #[tokio::test(start_paused = true)]
9771    async fn a_call_timeout_shorter_than_the_retry_deadline_ends_the_retries_at_the_call_timeout() {
9772        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(2));
9773        let started = Instant::now();
9774        let options = CallOptions {
9775            timeout: Duration::from_secs(10),
9776            ..CallOptions::default()
9777        };
9778        let mut task = tokio::spawn(async move {
9779            consumer
9780                .open_route(restart_target("restarting"), restart_identity(), options)
9781                .await
9782        });
9783        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9784            (started.elapsed() < Duration::from_secs(60)).then(reloading)
9785        })
9786        .await
9787        .expect_err("the call timeout must end the retries before the module is back");
9788        let elapsed = started.elapsed();
9789        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
9790        assert!(
9791            elapsed >= Duration::from_secs(9) && elapsed <= Duration::from_secs(10),
9792            "the retries must stop at the 10s call timeout, stopped after {elapsed:?}"
9793        );
9794    }
9795
9796    #[tokio::test(start_paused = true)]
9797    async fn two_routes_refused_together_retry_at_different_jittered_times() {
9798        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(42));
9799        let started = Instant::now();
9800        let mut task = tokio::spawn(async move {
9801            let alpha = consumer.open_route(
9802                restart_target("alpha"),
9803                restart_identity(),
9804                CallOptions::default(),
9805            );
9806            let beta = consumer.open_route(
9807                restart_target("beta"),
9808                restart_identity(),
9809                CallOptions::default(),
9810            );
9811            let (alpha, beta) = tokio::join!(alpha, beta);
9812            (alpha.is_ok(), beta.is_ok())
9813        });
9814        let mut first_open = HashMap::<String, Duration>::new();
9815        let mut retried_at = HashMap::<String, Duration>::new();
9816        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |module_id| {
9817            let at = started.elapsed();
9818            if first_open.contains_key(module_id) {
9819                retried_at.insert(module_id.to_string(), at);
9820                None
9821            } else {
9822                first_open.insert(module_id.to_string(), at);
9823                Some(reloading())
9824            }
9825        })
9826        .await;
9827        assert_eq!(opened, (true, true));
9828        assert_eq!(first_open["alpha"], first_open["beta"], "refused together");
9829        // Equal jitter keeps half of the 100ms base delay and randomizes the rest.
9830        for at in retried_at.values() {
9831            assert!(
9832                *at >= Duration::from_millis(50) && *at <= Duration::from_millis(100),
9833                "retry at {at:?} is outside the jitter window"
9834            );
9835        }
9836        assert_ne!(
9837            retried_at["alpha"], retried_at["beta"],
9838            "routes refused together must not retry in lock step"
9839        );
9840    }
9841
9842    #[tokio::test(start_paused = true)]
9843    async fn twenty_concurrent_opens_never_have_more_than_eight_outstanding_at_the_daemon() {
9844        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(3));
9845        let mut task = tokio::spawn(async move {
9846            let mut opens = tokio::task::JoinSet::new();
9847            for i in 0..20 {
9848                let consumer = Arc::clone(&consumer);
9849                opens.spawn(async move {
9850                    consumer
9851                        .open_route(
9852                            restart_target(&format!("module-{i}")),
9853                            restart_identity(),
9854                            CallOptions::default(),
9855                        )
9856                        .await
9857                });
9858            }
9859            let mut opened = 0usize;
9860            while let Some(result) = opens.join_next().await {
9861                result.unwrap().unwrap();
9862                opened += 1;
9863            }
9864            opened
9865        });
9866        // Hold every open until the consumer has gone quiet, so everything it
9867        // is willing to send at once is outstanding together; then answer them.
9868        let mut held = Vec::new();
9869        let mut max_outstanding = 0usize;
9870        let mut next_channel = 40u16;
9871        let opened = loop {
9872            tokio::select! {
9873                command = receiver.recv() => {
9874                    // The writer closes when the last consumer handle drops,
9875                    // which means every open has settled.
9876                    let Some(command) = command else {
9877                        break (&mut task).await.unwrap();
9878                    };
9879                    held.push(command.frame.header.corr);
9880                    max_outstanding = max_outstanding.max(held.len());
9881                }
9882                () = sleep(Duration::from_millis(25)), if !held.is_empty() => {
9883                    for corr in held.drain(..) {
9884                        next_channel += 1;
9885                        assert!(dispatch_frame(&shared, 1, route_open_answer(corr, next_channel, None)).await);
9886                    }
9887                }
9888                joined = &mut task => break joined.unwrap(),
9889            }
9890        };
9891        assert_eq!(opened, 20);
9892        assert_eq!(max_outstanding, MAX_ROUTE_OPENS_IN_FLIGHT);
9893    }
9894
9895    #[tokio::test(start_paused = true)]
9896    async fn an_exhausted_deadline_names_module_reloading_not_the_later_admission_pressure() {
9897        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(4));
9898        let options = CallOptions {
9899            route_retry_deadline: Duration::from_secs(5),
9900            ..CallOptions::default()
9901        };
9902        let mut task = tokio::spawn(async move {
9903            consumer
9904                .open_route(restart_target("restarting"), restart_identity(), options)
9905                .await
9906        });
9907        let mut opens = 0usize;
9908        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
9909            opens += 1;
9910            Some(if opens <= 2 {
9911                reloading().with_detail(serde_json::json!({ "reason": "restart" }))
9912            } else {
9913                ErrorBody::new(
9914                    error_codes::TARGET_UNAVAILABLE,
9915                    "connection already has 8 route.open binds in flight (limit 8); retry after one settles",
9916                )
9917            })
9918        })
9919        .await
9920        .expect_err("the module never comes back");
9921        assert!(opens > 2);
9922        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
9923        assert_eq!(
9924            err.route_open_refusal().map(|body| body.code.as_str()),
9925            Some(error_codes::MODULE_RELOADING)
9926        );
9927        let message = err.to_string();
9928        assert!(
9929            message.starts_with(
9930                "request not sent: route.open failed for target tool_provider:restarting: \
9931                 module_reloading (reason restart) (module is reloading); \
9932                 the most recent refusal was target_unavailable"
9933            ),
9934            "got {message}"
9935        );
9936    }
9937
9938    #[tokio::test]
9939    async fn close_route_flips_inflight_opening_so_a_racing_open_discards() {
9940        // The load-bearing close-beats-reopen guard, in isolation: a close that lands
9941        // while a route.open is in flight (channel not yet cached) must flip the
9942        // opening's `closed` flag, so the lead opener re-checks it before installing and
9943        // GOODBYEs the channel it opened instead of caching it.
9944        let shared = Arc::new(reader_skew_tests::legacy_shared(
9945            PathBuf::from("/tmp/does-not-exist"),
9946            ConsumerOptions::default(),
9947        ));
9948        let key = RouteKey::new(
9949            &RouteTarget::ToolProvider {
9950                module_id: "m".into(),
9951            },
9952            &BindIdentity::new("h", "s"),
9953            None,
9954            None,
9955        );
9956        // Simulate an in-flight lead open: an openings entry exists, not yet closed,
9957        // with no cached route (channel hasn't been installed yet).
9958        shared.lock_inner().openings.insert(
9959            key.clone(),
9960            Opening {
9961                waiters: Vec::new(),
9962                closed: false,
9963            },
9964        );
9965
9966        // close_route with no cached route is an idempotent no-op on routes, but MUST
9967        // flip the in-flight opening's flag so the racing open discards.
9968        shared
9969            .close_route(&key, &CloseRouteOptions::default())
9970            .await;
9971        assert!(
9972            shared
9973                .lock_inner()
9974                .openings
9975                .get(&key)
9976                .is_some_and(|o| o.closed),
9977            "close_route must flip the in-flight opening's closed flag (close-beats-reopen)"
9978        );
9979
9980        // And closing a key with neither a route nor an in-flight open is a no-op.
9981        let absent = RouteKey::new(
9982            &RouteTarget::ToolProvider {
9983                module_id: "absent".into(),
9984            },
9985            &BindIdentity::new("h", "s"),
9986            None,
9987            None,
9988        );
9989        shared
9990            .close_route(&absent, &CloseRouteOptions::default())
9991            .await;
9992    }
9993
9994    #[test]
9995    fn route_key_is_structured() {
9996        let target = RouteTarget::InternalService {
9997            module_id: "a\0b".into(),
9998            service_id: "svc".into(),
9999        };
10000        let identity = BindIdentity::new("h", "s");
10001        let key = RouteKey::new(&target, &identity, None, None);
10002        assert!(matches!(key.target, RouteTargetKey::InternalService { .. }));
10003    }
10004
10005    async fn assert_pending(mut future: Pin<&mut (impl Future + ?Sized)>) {
10006        assert!(
10007            std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx).is_pending())).await
10008        );
10009    }
10010
10011    /// Replace only the transport, leaving the actual generation-drop cleanup in use.
10012    fn drop_and_replace_test_transport(shared: &Arc<Shared>) -> mpsc::Receiver<WriteCommand> {
10013        let generation = shared.lock_inner().generation;
10014        // Keep the background supervisor from touching a real connection file.
10015        shared.lock_inner().reconnect = ReconnectState::Inline { generation };
10016        shared.handle_generation_drop(generation, "test connection drop".into());
10017        let (writer, receiver) = mpsc::channel(64);
10018        let mut inner = shared.lock_inner();
10019        inner.generation += 1;
10020        inner.epoch += 1;
10021        inner.next_corr = Some(1);
10022        inner.writer = Some(writer);
10023        inner.daemon_ver = "0.39.0".into();
10024        inner.reconnect = ReconnectState::Idle;
10025        receiver
10026    }
10027
10028    #[tokio::test(start_paused = true)]
10029    async fn route_open_single_flight_survives_generation_drop_during_backoff() {
10030        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
10031        let opts = CallOptions::default();
10032        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10033        tokio::pin!(opener);
10034        assert_pending(opener.as_mut()).await;
10035        let first = receiver.try_recv().unwrap();
10036        assert!(
10037            dispatch_frame(
10038                &shared,
10039                1,
10040                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
10041            )
10042            .await
10043        );
10044        assert_pending(opener.as_mut()).await;
10045
10046        // A caller already waiting and one arriving after the drop must both stay
10047        // behind the same lead opener, including its unfinished retry backoff.
10048        let waiting = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10049        tokio::pin!(waiting);
10050        assert_pending(waiting.as_mut()).await;
10051        let mut receiver = drop_and_replace_test_transport(&shared);
10052        assert_pending(waiting.as_mut()).await;
10053        let arriving = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10054        tokio::pin!(arriving);
10055        assert_pending(arriving.as_mut()).await;
10056        assert!(
10057            receiver.try_recv().is_err(),
10058            "a second opener bypassed the backoff"
10059        );
10060
10061        tokio::time::advance(opts.route_retry.base).await;
10062        assert_pending(opener.as_mut()).await;
10063        let retry = receiver.try_recv().unwrap();
10064        assert!(
10065            dispatch_frame(
10066                &shared,
10067                2,
10068                route_open_answer(retry.frame.header.corr, 42, None),
10069            )
10070            .await
10071        );
10072        let handle = opener.await.unwrap();
10073        assert_eq!(waiting.await.unwrap(), handle);
10074        assert_eq!(arriving.await.unwrap(), handle);
10075        assert!(
10076            receiver.try_recv().is_err(),
10077            "more than one retry was emitted"
10078        );
10079        let inner = shared.lock_inner();
10080        assert!(inner.openings.is_empty());
10081        assert_eq!(inner.routes.len(), 1);
10082        assert_eq!(inner.route_epochs.len(), 1);
10083    }
10084
10085    #[tokio::test(start_paused = true)]
10086    async fn close_route_during_backoff_survives_generation_drop() {
10087        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
10088        let opts = CallOptions::default();
10089        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
10090        tokio::pin!(opener);
10091        assert_pending(opener.as_mut()).await;
10092        let first = receiver.try_recv().unwrap();
10093        assert!(
10094            dispatch_frame(
10095                &shared,
10096                1,
10097                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
10098            )
10099            .await
10100        );
10101        assert_pending(opener.as_mut()).await;
10102        consumer
10103            .close_route(
10104                restart_target("m"),
10105                restart_identity(),
10106                CloseRouteOptions::default(),
10107            )
10108            .await;
10109        let mut receiver = drop_and_replace_test_transport(&shared);
10110        tokio::time::advance(opts.route_retry.base).await;
10111        assert_pending(opener.as_mut()).await;
10112        let retry = receiver.try_recv().unwrap();
10113        assert!(
10114            dispatch_frame(
10115                &shared,
10116                2,
10117                route_open_answer(retry.frame.header.corr, 42, None),
10118            )
10119            .await
10120        );
10121        let err = opener.await.expect_err("close must win over the retry");
10122        assert!(matches!(err, CallError::NotSent(_)));
10123        let goodbye = receiver
10124            .try_recv()
10125            .expect("discarded route must get GOODBYE");
10126        assert_eq!(goodbye.frame.header.ty, FrameType::Goodbye);
10127        assert_eq!(goodbye.frame.header.channel, 42);
10128        assert!(receiver.try_recv().is_err());
10129        let inner = shared.lock_inner();
10130        assert!(inner.routes.is_empty());
10131        assert!(inner.route_epochs.is_empty());
10132        assert!(inner.openings.is_empty());
10133    }
10134
10135    fn route_teardown_stand_in() -> (
10136        Arc<Shared>,
10137        SubcConsumer,
10138        mpsc::Receiver<WriteCommand>,
10139        tokio::io::DuplexStream,
10140        RouteKey,
10141        RouteState,
10142    ) {
10143        let shared = writer_test_shared();
10144        let (stream, peer) = tokio::io::duplex(1024);
10145        shared
10146            .install_initial(OpenedConnection {
10147                stream: Box::new(stream),
10148                daemon_origin_trusted: true,
10149                daemon_ver: "0.39.0".into(),
10150            })
10151            .unwrap();
10152        let (writer, rx) = mpsc::channel(1);
10153        writer
10154            .try_send(WriteCommand {
10155                frame: response_frame(0, 0, 99, b"filler".to_vec()),
10156                pending: None,
10157            })
10158            .unwrap();
10159        let key = RouteKey::new(&restart_target("teardown"), &restart_identity(), None, None);
10160        let route = RouteState {
10161            handle: RouteHandle::new(17, 23, 1),
10162            sem: Arc::new(Semaphore::new(1)),
10163            watch_sem: None,
10164            opted_in: false,
10165        };
10166        {
10167            let mut inner = shared.lock_inner();
10168            inner.writer = Some(writer);
10169            inner.cache_route(key.clone(), route.clone());
10170        }
10171        let consumer = SubcConsumer {
10172            shared: Arc::clone(&shared),
10173        };
10174        (shared, consumer, rx, peer, key, route)
10175    }
10176
10177    async fn assert_reopened_request_after_goodbye(
10178        shared: &Arc<Shared>,
10179        consumer: &SubcConsumer,
10180        rx: &mut mpsc::Receiver<WriteCommand>,
10181        old: RouteHandle,
10182    ) {
10183        let reopened = RouteHandle::new(old.channel, old.epoch + 1, old.connection_token());
10184        shared
10185            .install_one_shot_route(RouteState {
10186                handle: reopened,
10187                sem: Arc::new(Semaphore::new(1)),
10188                watch_sem: None,
10189                opted_in: false,
10190            })
10191            .unwrap();
10192        let request = consumer.request(&reopened, b"reopened".to_vec(), CallOptions::default());
10193        tokio::pin!(request);
10194        assert_pending(request.as_mut()).await;
10195        let command = rx.recv().await.unwrap();
10196        assert_eq!(command.frame.header.ty, FrameType::Goodbye);
10197        assert_eq!(
10198            (command.frame.header.channel, command.frame.header.epoch),
10199            (old.channel, old.epoch)
10200        );
10201        assert_pending(request.as_mut()).await;
10202        let command = rx.recv().await.unwrap();
10203        assert_eq!(command.frame.header.ty, FrameType::Request);
10204        assert_eq!(command.frame.header.channel, reopened.channel);
10205        assert_eq!(command.frame.header.epoch, reopened.epoch);
10206        dispatch_frame(
10207            shared,
10208            reopened.connection_token(),
10209            response_frame(
10210                reopened.channel,
10211                reopened.epoch,
10212                command.frame.header.corr,
10213                Vec::new(),
10214            ),
10215        )
10216        .await;
10217        request.await.unwrap();
10218    }
10219
10220    #[tokio::test]
10221    async fn route_teardown_close_waits_for_goodbye_before_channel_reuse() {
10222        for by_handle in [false, true] {
10223            let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10224            let close = async {
10225                if by_handle {
10226                    consumer
10227                        .close_handle(&route.handle, CloseRouteOptions::default())
10228                        .await
10229                        .unwrap();
10230                } else {
10231                    consumer
10232                        .close_route(
10233                            restart_target("teardown"),
10234                            restart_identity(),
10235                            CloseRouteOptions::default(),
10236                        )
10237                        .await;
10238                }
10239            };
10240            tokio::pin!(close);
10241            assert_pending(close.as_mut()).await;
10242            assert!(route.sem.is_closed());
10243            assert!(!shared.lock_inner().routes.contains_key(&key));
10244            assert_eq!(
10245                shared.lock_inner().route_epochs.get(&route.handle.channel),
10246                Some(&route.handle)
10247            );
10248            let mut reopened = route.clone();
10249            reopened.handle = RouteHandle::new(route.handle.channel, route.handle.epoch + 1, 1);
10250            assert!(shared.install_one_shot_route(reopened).is_err());
10251            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10252            close.await;
10253            assert_reopened_request_after_goodbye(&shared, &consumer, &mut rx, route.handle).await;
10254            consumer.close().await;
10255        }
10256    }
10257
10258    #[tokio::test]
10259    async fn route_teardown_retirement_waits_for_goodbye_before_channel_reuse() {
10260        let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10261        shared.invalidate_route_with_deadline(&key, Some(route.handle), true);
10262        assert!(route.sem.is_closed());
10263        assert_eq!(
10264            shared.lock_inner().route_epochs.get(&route.handle.channel),
10265            Some(&route.handle)
10266        );
10267        let mut reopened = route.clone();
10268        reopened.handle = RouteHandle::new(route.handle.channel, route.handle.epoch + 1, 1);
10269        assert!(shared.install_one_shot_route(reopened).is_err());
10270        assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10271        tokio::time::timeout(Duration::from_secs(1), async {
10272            while shared
10273                .lock_inner()
10274                .route_epochs
10275                .contains_key(&route.handle.channel)
10276            {
10277                tokio::task::yield_now().await;
10278            }
10279        })
10280        .await
10281        .expect("retirement must queue its GOODBYE after writer capacity frees");
10282        assert_reopened_request_after_goodbye(&shared, &consumer, &mut rx, route.handle).await;
10283        consumer.close().await;
10284    }
10285
10286    #[tokio::test]
10287    async fn route_teardown_retirements_flush_in_order() {
10288        let (shared, consumer, mut rx, _peer, first_key, first) = route_teardown_stand_in();
10289        let second_key = RouteKey::new(&restart_target("second"), &restart_identity(), None, None);
10290        let mut second = first.clone();
10291        second.handle = RouteHandle::new(first.handle.channel + 1, 31, 1);
10292        shared
10293            .lock_inner()
10294            .cache_route(second_key.clone(), second.clone());
10295        shared.invalidate_route_with_deadline(&first_key, Some(first.handle), true);
10296        shared.invalidate_route_with_deadline(&second_key, Some(second.handle), true);
10297        assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10298        for handle in [first.handle, second.handle] {
10299            let command = tokio::time::timeout(Duration::from_secs(1), rx.recv())
10300                .await
10301                .unwrap()
10302                .unwrap();
10303            assert_eq!(command.frame.header.ty, FrameType::Goodbye);
10304            assert_eq!(
10305                (command.frame.header.channel, command.frame.header.epoch),
10306                (handle.channel, handle.epoch)
10307            );
10308            assert!(!shared
10309                .lock_inner()
10310                .route_epochs
10311                .contains_key(&handle.channel));
10312        }
10313        assert!(shared.lock_inner().retirement_queue.is_empty());
10314        assert!(shared.lock_inner().retirement_goodbyes.is_empty());
10315        assert!(rx.try_recv().is_err());
10316        consumer.close().await;
10317    }
10318
10319    #[tokio::test]
10320    async fn route_teardown_dead_connection_ends_writer_wait_and_discards_retirements() {
10321        for death in 0..3 {
10322            let (shared, consumer, mut rx, _peer, key, route) = route_teardown_stand_in();
10323            let opts = CloseRouteOptions::default();
10324            let close = shared.close_route(&key, &opts);
10325            tokio::pin!(close);
10326            assert_pending(close.as_mut()).await;
10327            match death {
10328                0 => rx.close(),
10329                1 => shared.handle_generation_drop(1, "test connection lost".into()),
10330                _ => shared.close_sync("test connection closed"),
10331            }
10332            tokio::time::timeout(Duration::from_secs(1), close)
10333                .await
10334                .unwrap();
10335            assert!(!shared
10336                .lock_inner()
10337                .route_epochs
10338                .contains_key(&route.handle.channel));
10339            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10340            assert!(rx.try_recv().is_err());
10341            consumer.close().await;
10342
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            if death == 1 {
10346                shared.handle_generation_drop(1, "test connection lost".into());
10347            } else {
10348                consumer.close().await;
10349            }
10350            assert!(shared.lock_inner().retirement_queue.is_empty());
10351            assert!(shared.lock_inner().retirement_goodbyes.is_empty());
10352            assert_eq!(rx.recv().await.unwrap().frame.body, b"filler");
10353            assert!(rx.try_recv().is_err());
10354            consumer.close().await;
10355        }
10356    }
10357
10358    #[tokio::test]
10359    async fn route_channel_index_tracks_lookup_close_and_generation_drop() {
10360        let shared = writer_test_shared();
10361        let (writer, _rx) = mpsc::channel(32);
10362        let mut expected = Vec::new();
10363        {
10364            let mut inner = shared.lock_inner();
10365            inner.writer = Some(writer);
10366            inner.daemon_ver = "0.39.0".into();
10367            for channel in 1..=8 {
10368                let key = RouteKey::new(
10369                    &RouteTarget::ToolProvider {
10370                        module_id: format!("module-{channel}"),
10371                    },
10372                    &BindIdentity::new("test", format!("session-{channel}")),
10373                    None,
10374                    None,
10375                );
10376                let route = RouteState {
10377                    handle: RouteHandle::new(channel, channel.into(), 1),
10378                    sem: Arc::new(Semaphore::new(DEFAULT_ROUTE_WINDOW)),
10379                    watch_sem: None,
10380                    opted_in: false,
10381                };
10382                inner.cache_route(key.clone(), route.clone());
10383                expected.push((key, route));
10384            }
10385        }
10386
10387        for (key, expected_route) in &expected {
10388            let resolved = shared
10389                .route_state(expected_route.handle)
10390                .expect("an indexed route handle should resolve");
10391            assert_eq!(resolved.handle, expected_route.handle);
10392            assert!(Arc::ptr_eq(&resolved.sem, &expected_route.sem));
10393
10394            let inner = shared.lock_inner();
10395            assert_eq!(
10396                inner.route_by_channel.get(&expected_route.handle.channel),
10397                Some(key)
10398            );
10399            assert_eq!(
10400                inner.route_epochs.get(&expected_route.handle.channel),
10401                Some(&expected_route.handle)
10402            );
10403            assert!(inner
10404                .routes
10405                .get(key)
10406                .is_some_and(|route| route.handle == expected_route.handle));
10407        }
10408
10409        let (closed_key, closed_route) = &expected[3];
10410        shared
10411            .close_route(closed_key, &CloseRouteOptions::default())
10412            .await;
10413        {
10414            let inner = shared.lock_inner();
10415            assert!(!inner.routes.contains_key(closed_key));
10416            assert!(!inner
10417                .route_by_channel
10418                .contains_key(&closed_route.handle.channel));
10419            assert!(!inner
10420                .route_epochs
10421                .contains_key(&closed_route.handle.channel));
10422        }
10423        assert!(matches!(
10424            shared.route_state(closed_route.handle),
10425            Err(CallError::StaleRouteHandle(handle)) if handle == closed_route.handle
10426        ));
10427
10428        shared.handle_generation_drop(1, "test generation dropped".into());
10429        {
10430            let inner = shared.lock_inner();
10431            assert!(inner.routes.is_empty());
10432            assert!(inner.route_by_channel.is_empty());
10433            assert!(inner.route_epochs.is_empty());
10434        }
10435        shared.close_sync("test complete");
10436    }
10437
10438    #[tokio::test]
10439    async fn stale_push_is_not_delivered_after_connection_generation_changes() {
10440        let shared = writer_test_shared();
10441        let old_handle = RouteHandle::new(7, 1, 1);
10442        let (writer, _writer_rx) = mpsc::channel(1);
10443        {
10444            let mut inner = shared.lock_inner();
10445            inner.writer = Some(writer);
10446            inner.daemon_ver = "0.39.0".into();
10447            inner.route_epochs.insert(old_handle.channel, old_handle);
10448        }
10449        let mut pushes = shared
10450            .register_push_events(old_handle)
10451            .expect("the old live route should accept a receiver");
10452
10453        {
10454            let mut inner = shared.lock_inner();
10455            inner.generation = 2;
10456            inner.close_routes();
10457            inner.route_epochs.clear();
10458            inner.route_modules.clear();
10459            inner.route_end_reasons.clear();
10460            inner.legacy_channel_reasons.clear();
10461        }
10462        shared.route_push(old_handle, b"stale".to_vec());
10463
10464        assert!(
10465            pushes.recv().await.is_none(),
10466            "connection teardown must end the old receiver before a stale Push can arrive"
10467        );
10468        shared.close_sync("test complete");
10469    }
10470
10471    #[test]
10472    fn route_key_canonicalizes_consumer_capabilities() {
10473        let target = RouteTarget::ToolProvider {
10474            module_id: "aft".into(),
10475        };
10476        let identity = BindIdentity::new("h", "s");
10477        let left = RouteKey::new(
10478            &target,
10479            &identity,
10480            None,
10481            Some(&["sampling".to_string(), "elicitation".to_string()]),
10482        );
10483        let right = RouteKey::new(
10484            &target,
10485            &identity,
10486            None,
10487            Some(&[
10488                "elicitation".to_string(),
10489                "sampling".to_string(),
10490                "sampling".to_string(),
10491            ]),
10492        );
10493        assert_eq!(left, right);
10494    }
10495
10496    #[tokio::test]
10497    async fn routes_with_and_without_declared_consumer_capabilities_are_kept_apart() {
10498        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(10));
10499        let (undeclared_request, undeclared) = open_answered_with(
10500            &shared,
10501            &consumer,
10502            &mut receiver,
10503            CallOptions::default(),
10504            74,
10505            "the undeclared route opens first",
10506        )
10507        .await;
10508        assert!(undeclared_request.get("consumer_capabilities").is_none());
10509
10510        let declared_opts = CallOptions::default()
10511            .with_consumer_capability("tool-result/v1")
10512            .unwrap();
10513        let (declared_request, declared) = open_answered_with(
10514            &shared,
10515            &consumer,
10516            &mut receiver,
10517            declared_opts.clone(),
10518            75,
10519            "a declared open must not reuse the undeclared route",
10520        )
10521        .await;
10522        assert_eq!(
10523            declared_request["consumer_capabilities"],
10524            serde_json::json!(["tool-result/v1"])
10525        );
10526        assert_ne!(undeclared, declared);
10527
10528        assert_eq!(
10529            consumer
10530                .open_route(restart_target("plexus"), restart_identity(), declared_opts)
10531                .await
10532                .unwrap(),
10533            declared,
10534            "the same declaration must reuse its cached route"
10535        );
10536        assert_eq!(
10537            consumer
10538                .open_route(
10539                    restart_target("plexus"),
10540                    restart_identity(),
10541                    CallOptions::default(),
10542                )
10543                .await
10544                .unwrap(),
10545            undeclared,
10546            "an undeclared open must continue to reuse only its own route"
10547        );
10548        assert!(
10549            receiver.try_recv().is_err(),
10550            "both subsequent opens are cache hits"
10551        );
10552        shared.close_sync("test complete");
10553    }
10554
10555    fn scope_selector(owner: &str, scope_ref: &str, scope_epoch: u64) -> ScopeSelector {
10556        ScopeSelector::new(
10557            subc_protocol::Principal::Reserved {
10558                module_id: owner.to_string(),
10559            },
10560            scope_ref.to_string(),
10561            Some(scope_epoch),
10562        )
10563    }
10564
10565    #[test]
10566    fn route_key_separates_scopes_by_owner_ref_and_epoch_and_from_unscoped() {
10567        let target = RouteTarget::ToolProvider {
10568            module_id: "plexus".into(),
10569        };
10570        let identity = BindIdentity::new("h", "s");
10571        let key = |scope: Option<ScopeSelector>| {
10572            RouteKey::new(&target, &identity, None, None).with_scope(scope.as_ref())
10573        };
10574        let base = key(Some(scope_selector("owner", "session-a", 1)));
10575        assert_eq!(base, key(Some(scope_selector("owner", "session-a", 1))));
10576        for (label, other) in [
10577            ("epoch", key(Some(scope_selector("owner", "session-a", 2)))),
10578            ("ref", key(Some(scope_selector("owner", "session-b", 1)))),
10579            ("owner", key(Some(scope_selector("other", "session-a", 1)))),
10580            ("unscoped", key(None)),
10581        ] {
10582            assert_ne!(base, other, "a different {label} must be a different route");
10583        }
10584        let mut no_epoch = scope_selector("owner", "session-a", 1);
10585        no_epoch.scope_epoch = None;
10586        assert_ne!(base, key(Some(no_epoch)));
10587    }
10588
10589    /// The next route.open the consumer writes, skipping any other frame
10590    /// (a GOODBYE, a cancel). Fails the test by name if none arrives, which is
10591    /// what a cache hit that should have been a miss looks like.
10592    async fn next_route_open(
10593        receiver: &mut mpsc::Receiver<WriteCommand>,
10594        why: &str,
10595    ) -> (u64, serde_json::Value) {
10596        loop {
10597            let command = tokio::time::timeout(Duration::from_secs(2), receiver.recv())
10598                .await
10599                .unwrap_or_else(|_| panic!("no route.open was sent: {why}"))
10600                .expect("writer channel open");
10601            if command.frame.header.channel != 0 || command.frame.header.ty != FrameType::Request {
10602                continue;
10603            }
10604            let request: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
10605            if request["op"] == "route.open" {
10606                return (command.frame.header.corr, request);
10607            }
10608        }
10609    }
10610
10611    /// Open a route (scoped when `scope` is set) through the stand-in daemon,
10612    /// accept its route.open on `channel`, and return the open's body and handle.
10613    async fn open_answered(
10614        shared: &Arc<Shared>,
10615        consumer: &Arc<SubcConsumer>,
10616        receiver: &mut mpsc::Receiver<WriteCommand>,
10617        scope: Option<ScopeSelector>,
10618        channel: u16,
10619        why: &str,
10620    ) -> (serde_json::Value, RouteHandle) {
10621        let consumer = Arc::clone(consumer);
10622        let task = tokio::spawn(async move {
10623            match scope {
10624                Some(scope) => {
10625                    consumer
10626                        .open_route_scoped(
10627                            restart_target("plexus"),
10628                            restart_identity(),
10629                            scope,
10630                            CallOptions::default(),
10631                        )
10632                        .await
10633                }
10634                None => {
10635                    consumer
10636                        .open_route(
10637                            restart_target("plexus"),
10638                            restart_identity(),
10639                            CallOptions::default(),
10640                        )
10641                        .await
10642                }
10643            }
10644        });
10645        let (corr, request) = next_route_open(receiver, why).await;
10646        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
10647        let handle = task.await.unwrap().expect("the stand-in accepted the open");
10648        (request, handle)
10649    }
10650
10651    /// Open an unscoped `plexus` route with `opts` through the stand-in
10652    /// daemon, accept its route.open on `channel`, and return the open's body
10653    /// and handle.
10654    async fn open_answered_with(
10655        shared: &Arc<Shared>,
10656        consumer: &Arc<SubcConsumer>,
10657        receiver: &mut mpsc::Receiver<WriteCommand>,
10658        opts: CallOptions,
10659        channel: u16,
10660        why: &str,
10661    ) -> (serde_json::Value, RouteHandle) {
10662        let consumer = Arc::clone(consumer);
10663        let task = tokio::spawn(async move {
10664            consumer
10665                .open_route(restart_target("plexus"), restart_identity(), opts)
10666                .await
10667        });
10668        let (corr, request) = next_route_open(receiver, why).await;
10669        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
10670        let handle = task.await.unwrap().expect("the stand-in accepted the open");
10671        (request, handle)
10672    }
10673
10674    fn with_role_versions(entries: &[(&str, &str)]) -> CallOptions {
10675        CallOptions {
10676            role_versions: Some(
10677                entries
10678                    .iter()
10679                    .map(|(role, version)| (role.to_string(), version.to_string()))
10680                    .collect(),
10681            ),
10682            ..CallOptions::default()
10683        }
10684    }
10685
10686    /// A provider picks its wire shape from the role versions at bind, so a
10687    /// legacy route and a versioned one to the same target must never be
10688    /// shared, while the same declaration again (and an empty map, which
10689    /// declares nothing) reuses the route it matches.
10690    #[tokio::test]
10691    async fn routes_differing_only_in_role_versions_are_kept_apart() {
10692        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
10693        let (legacy_request, legacy) = open_answered_with(
10694            &shared,
10695            &consumer,
10696            &mut receiver,
10697            CallOptions::default(),
10698            71,
10699            "first, legacy open",
10700        )
10701        .await;
10702        assert!(
10703            legacy_request.get("role_versions").is_none(),
10704            "{legacy_request}"
10705        );
10706
10707        let (v1_request, v1) = open_answered_with(
10708            &shared,
10709            &consumer,
10710            &mut receiver,
10711            with_role_versions(&[("tool-provider", "v1")]),
10712            72,
10713            "a v1 open must not reuse the legacy route",
10714        )
10715        .await;
10716        assert_eq!(
10717            v1_request["role_versions"],
10718            serde_json::json!({ "tool-provider": "v1" })
10719        );
10720        assert_ne!(legacy, v1);
10721
10722        let (v2_request, v2) = open_answered_with(
10723            &shared,
10724            &consumer,
10725            &mut receiver,
10726            with_role_versions(&[("tool-provider", "v2")]),
10727            73,
10728            "a v2 open must not reuse the v1 route",
10729        )
10730        .await;
10731        assert_eq!(
10732            v2_request["role_versions"],
10733            serde_json::json!({ "tool-provider": "v2" })
10734        );
10735        assert!(![legacy, v1].contains(&v2));
10736
10737        let open = |opts: CallOptions| {
10738            let consumer = Arc::clone(&consumer);
10739            async move {
10740                consumer
10741                    .open_route(restart_target("plexus"), restart_identity(), opts)
10742                    .await
10743                    .unwrap()
10744            }
10745        };
10746        assert_eq!(
10747            open(with_role_versions(&[("tool-provider", "v1")])).await,
10748            v1
10749        );
10750        assert_eq!(open(CallOptions::default()).await, legacy);
10751        assert_eq!(
10752            open(CallOptions {
10753                role_versions: Some(BTreeMap::new()),
10754                ..CallOptions::default()
10755            })
10756            .await,
10757            legacy,
10758            "an empty map declares nothing and reuses the legacy route"
10759        );
10760        assert!(
10761            receiver.try_recv().is_err(),
10762            "a cache hit must not send a route.open"
10763        );
10764        shared.close_sync("test complete");
10765    }
10766
10767    #[tokio::test]
10768    async fn scoped_routes_are_cached_per_owner_ref_and_epoch_and_apart_from_unscoped() {
10769        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(8));
10770        let selector = scope_selector("owner", "session-a", 1);
10771        let (request, first) = open_answered(
10772            &shared,
10773            &consumer,
10774            &mut receiver,
10775            Some(selector.clone()),
10776            61,
10777            "first scoped open",
10778        )
10779        .await;
10780        assert_eq!(request["scope"], serde_json::to_value(&selector).unwrap());
10781
10782        // The same selector again is a cache hit: no route.open, same handle.
10783        let again = consumer
10784            .open_route_scoped(
10785                restart_target("plexus"),
10786                restart_identity(),
10787                selector,
10788                CallOptions::default(),
10789            )
10790            .await
10791            .unwrap();
10792        assert_eq!(again, first);
10793        assert!(
10794            receiver.try_recv().is_err(),
10795            "a cache hit must not send a route.open"
10796        );
10797
10798        let mut handles = vec![first];
10799        for (channel, scope, why) in [
10800            (
10801                62,
10802                Some(scope_selector("owner", "session-a", 2)),
10803                "another epoch of the same scope must open its own route",
10804            ),
10805            (
10806                63,
10807                Some(scope_selector("owner", "session-b", 1)),
10808                "another scope ref must open its own route",
10809            ),
10810            (
10811                64,
10812                Some(scope_selector("other-owner", "session-a", 1)),
10813                "another owner's scope must open its own route",
10814            ),
10815            (65, None, "an unscoped open must not reuse a scoped route"),
10816        ] {
10817            let expected_scope = scope
10818                .as_ref()
10819                .map(|scope| serde_json::to_value(scope).unwrap());
10820            let (request, handle) =
10821                open_answered(&shared, &consumer, &mut receiver, scope, channel, why).await;
10822            assert_eq!(
10823                request.get("scope").cloned(),
10824                expected_scope,
10825                "the route.open must carry exactly the requested scope: {why}"
10826            );
10827            assert!(!handles.contains(&handle), "{why}");
10828            handles.push(handle);
10829        }
10830        shared.close_sync("test complete");
10831    }
10832
10833    #[tokio::test]
10834    async fn a_dropped_scoped_route_reopens_with_the_same_selector() {
10835        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(7));
10836        let selector = scope_selector("owner", "session-a", 3);
10837        let (first_request, first) = open_answered(
10838            &shared,
10839            &consumer,
10840            &mut receiver,
10841            Some(selector.clone()),
10842            51,
10843            "first scoped open",
10844        )
10845        .await;
10846
10847        // The daemon ends the route, as it does when the provider restarts.
10848        let goodbye = Frame::build(
10849            FrameType::Goodbye,
10850            Flags::new(false, Priority::Interactive, false),
10851            first.channel,
10852            first.epoch,
10853            0,
10854            Vec::new(),
10855        )
10856        .unwrap();
10857        assert!(dispatch_frame(&shared, 1, goodbye).await);
10858        assert!(matches!(
10859            shared.route_state(first),
10860            Err(CallError::StaleRouteHandle(_))
10861        ));
10862
10863        let (second_request, second) = open_answered(
10864            &shared,
10865            &consumer,
10866            &mut receiver,
10867            Some(selector.clone()),
10868            52,
10869            "the reopen after the route dropped",
10870        )
10871        .await;
10872        assert_eq!(
10873            first_request["scope"],
10874            serde_json::to_value(&selector).unwrap()
10875        );
10876        assert_eq!(second_request["scope"], first_request["scope"]);
10877        assert_ne!(second, first);
10878        shared.close_sync("test complete");
10879    }
10880
10881    /// Refuse every scoped route.open with `code` until the open settles, and
10882    /// return how many attempts were served and the error the caller got.
10883    async fn refuse_scoped_opens(code: &str) -> (usize, CallError) {
10884        refuse_scoped_operation(code, "open").await
10885    }
10886
10887    async fn refuse_scoped_operation(code: &str, operation: &str) -> (usize, CallError) {
10888        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
10889        let selector = scope_selector("owner", "session-a", 1);
10890        let options = CallOptions {
10891            scope: Some(selector.clone()),
10892            timeout: Duration::from_secs(2),
10893            route_retry: RetryBackoff {
10894                base: Duration::ZERO,
10895                cap: Duration::ZERO,
10896                max_attempts: 2,
10897            },
10898            route_retry_deadline: Duration::from_millis(150),
10899            ..CallOptions::default()
10900        };
10901        let operation = operation.to_string();
10902        let mut task = tokio::spawn(async move {
10903            match operation.as_str() {
10904                "call" => consumer
10905                    .call(
10906                        restart_target("plexus"),
10907                        restart_identity(),
10908                        b"{}".to_vec(),
10909                        options,
10910                    )
10911                    .await
10912                    .map(|_| ()),
10913                "subscribe" => consumer
10914                    .subscribe(
10915                        restart_target("plexus"),
10916                        restart_identity(),
10917                        b"{}".to_vec(),
10918                        SubscribeOptions {
10919                            scope: options.scope,
10920                            route_open_timeout: options.timeout,
10921                            route_retry: options.route_retry,
10922                            route_retry_deadline: options.route_retry_deadline,
10923                            ..SubscribeOptions::default()
10924                        },
10925                    )
10926                    .await
10927                    .map(|_| ()),
10928                "open" => consumer
10929                    .open_route_scoped(
10930                        restart_target("plexus"),
10931                        restart_identity(),
10932                        scope_selector("owner", "session-a", 1),
10933                        options,
10934                    )
10935                    .await
10936                    .map(|_| ()),
10937                _ => unreachable!(),
10938            }
10939        });
10940        let mut attempts = 0usize;
10941        let err = loop {
10942            tokio::select! {
10943                command = receiver.recv() => {
10944                    let Some(command) = command else {
10945                        break task.await.unwrap().expect_err("route.open must be refused");
10946                    };
10947                    let open: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
10948                    assert_eq!(open["scope"], serde_json::to_value(&selector).unwrap());
10949                    attempts += 1;
10950                    let frame = route_open_answer(
10951                        command.frame.header.corr,
10952                        0,
10953                        Some(ErrorBody::new(code, "test refusal")),
10954                    );
10955                    assert!(dispatch_frame(&shared, 1, frame).await);
10956                }
10957                joined = &mut task => {
10958                    break joined.unwrap().expect_err("route.open must be refused");
10959                }
10960            }
10961        };
10962        shared.close_sync("test complete");
10963        (attempts, err)
10964    }
10965
10966    #[tokio::test]
10967    async fn scoped_managed_operations_retry_only_transient_scope_refusals() {
10968        for operation in ["call", "subscribe"] {
10969            for (code, retryable) in [
10970                (error_codes::SCOPE_NOT_SYNCED, true),
10971                (error_codes::SCOPE_CHANGED, true),
10972                (error_codes::SCOPE_ENDED, false),
10973                (error_codes::SCOPE_NOT_LIVE, false),
10974                (error_codes::SCOPE_EPOCH_REQUIRED, false),
10975                (error_codes::SCOPE_NOT_CARRIER, false),
10976            ] {
10977                let (attempts, err) = refuse_scoped_operation(code, operation).await;
10978                if retryable {
10979                    assert!(attempts > 1, "{operation}: {code} must be retried");
10980                } else {
10981                    assert_eq!(attempts, 1, "{operation}: {code} must be terminal");
10982                }
10983                assert!(matches!(err, CallError::NotSent(_)), "{operation}: {err}");
10984                assert_eq!(err.never_forwarded(), Some(true));
10985                assert_eq!(err.route_open_refusal().unwrap().code, code);
10986            }
10987        }
10988    }
10989
10990    #[tokio::test]
10991    async fn scoped_open_retries_not_synced_and_changed_and_ends_on_the_terminal_scope_codes() {
10992        for code in [error_codes::SCOPE_NOT_SYNCED, error_codes::SCOPE_CHANGED] {
10993            let (attempts, err) = refuse_scoped_opens(code).await;
10994            assert!(attempts > 1, "{code} must be retried, served {attempts}");
10995            assert_eq!(
10996                err.route_open_refusal().map(|body| body.code.as_str()),
10997                Some(code)
10998            );
10999        }
11000        for code in [
11001            error_codes::SCOPE_ENDED,
11002            error_codes::SCOPE_NOT_LIVE,
11003            error_codes::SCOPE_EPOCH_REQUIRED,
11004            error_codes::SCOPE_NOT_CARRIER,
11005        ] {
11006            let (attempts, err) = refuse_scoped_opens(code).await;
11007            assert_eq!(attempts, 1, "{code} is terminal and must not be retried");
11008            assert!(matches!(err, CallError::NotSent(_)));
11009            assert_eq!(
11010                err.route_open_refusal().map(|body| body.code.as_str()),
11011                Some(code)
11012            );
11013        }
11014    }
11015
11016    /// The daemon refuses the first route.open with `module_warming`, then the
11017    /// retry is written and accepted but never answered, so the retry deadline
11018    /// expires while that attempt is still waiting. The caller must still get
11019    /// the refusal it already received, as `NotSent`, rather than the bare
11020    /// "timed out at its deadline" of the unanswered attempt. A busy daemon
11021    /// that answers the final retry a few milliseconds late hits this path.
11022    #[tokio::test]
11023    async fn refusal_survives_a_retry_still_in_flight_at_the_deadline() {
11024        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(11));
11025        let options = CallOptions {
11026            timeout: Duration::from_secs(5),
11027            route_retry: RetryBackoff {
11028                base: Duration::ZERO,
11029                cap: Duration::ZERO,
11030                max_attempts: 2,
11031            },
11032            route_retry_deadline: Duration::from_millis(300),
11033            ..CallOptions::default()
11034        };
11035        let mut task = tokio::spawn(async move {
11036            consumer
11037                .open_route(restart_target("warming"), restart_identity(), options)
11038                .await
11039        });
11040        let generation = shared.lock_inner().generation;
11041        let refusal = ErrorBody {
11042            code: error_codes::MODULE_WARMING.to_string(),
11043            message: "warming is not ready".to_string(),
11044            detail: Some(serde_json::json!({"reason": "required_capability_unprovided"})),
11045        };
11046        let mut attempts = 0usize;
11047        let mut held = false;
11048        let err = loop {
11049            tokio::select! {
11050                command = receiver.recv() => {
11051                    let Some(command) = command else {
11052                        break task.await.unwrap().expect_err("route.open must fail");
11053                    };
11054                    if command.frame.header.ty != FrameType::Request {
11055                        continue;
11056                    }
11057                    attempts += 1;
11058                    if attempts == 1 {
11059                        let frame = route_open_answer(
11060                            command.frame.header.corr,
11061                            0,
11062                            Some(refusal.clone()),
11063                        );
11064                        assert!(dispatch_frame(&shared, generation, frame).await);
11065                    } else {
11066                        // What the writer task does once the frame is on the
11067                        // socket: from here a timeout is OutcomeUnknown.
11068                        held = shared.mark_pending_accepted(
11069                            command.pending.expect("a route.open is a pending request"),
11070                        );
11071                    }
11072                }
11073                joined = &mut task => {
11074                    break joined.unwrap().expect_err("route.open must fail");
11075                }
11076            }
11077        };
11078        shared.close_sync("test complete");
11079        assert_eq!(
11080            attempts, 2,
11081            "one refused attempt, then one held past the deadline"
11082        );
11083        assert!(
11084            held,
11085            "the second attempt must be accepted and left unanswered"
11086        );
11087        assert!(
11088            err.is_not_sent(),
11089            "a refused route never delivered the request: {err}"
11090        );
11091        let body = err
11092            .route_open_refusal()
11093            .unwrap_or_else(|| panic!("the refusal must survive the deadline: {err}"));
11094        assert_eq!(body.code, error_codes::MODULE_WARMING);
11095        assert_eq!(body.detail, refusal.detail);
11096    }
11097
11098    #[test]
11099    fn every_scope_close_reason_must_not_reopen() {
11100        for reason in [
11101            subc_protocol::RouteCloseReason::ScopeEnded,
11102            subc_protocol::RouteCloseReason::ScopeCarrierRemoved,
11103            subc_protocol::RouteCloseReason::ScopeDelegationChanged,
11104            subc_protocol::RouteCloseReason::ScopeParentEnded,
11105        ] {
11106            let wire = serde_json::to_value(reason).unwrap();
11107            let wire = wire.as_str().expect("a close reason is a string");
11108            assert!(wire.starts_with("scope_"), "{wire}");
11109            assert_eq!(
11110                RouteCloseReason::from_wire(wire).disposition(),
11111                RouteCloseDisposition::MustNotReopen,
11112                "a route closed for {wire} must not be reopened"
11113            );
11114        }
11115    }
11116
11117    // The fake module receives the queued Request and injects frames through the
11118    // same dispatcher as the socket reader, without a daemon process.
11119    async fn watch_subscribed() -> (
11120        SubcConsumer,
11121        mpsc::Receiver<WriteCommand>,
11122        Subscription,
11123        Frame,
11124    ) {
11125        let (shared, mut rx, handle) = reverse_test_shared(ReverseRequestRegistry::new());
11126        shared.lock_inner().one_shot_routes.insert(
11127            handle.channel,
11128            RouteState {
11129                handle,
11130                sem: Arc::new(Semaphore::new(1)),
11131                watch_sem: None,
11132                opted_in: false,
11133            },
11134        );
11135        let consumer = SubcConsumer { shared };
11136        let subscription = consumer
11137            .subscribe_route(&handle, b"watch".to_vec(), SubscribeOptions::default())
11138            .await
11139            .unwrap();
11140        let request = rx.recv().await.unwrap().frame;
11141        (consumer, rx, subscription, request)
11142    }
11143
11144    fn watch_terminal(request: &Frame, ty: FrameType, body: Vec<u8>) -> Frame {
11145        Frame::build(
11146            ty,
11147            Flags::new(false, Priority::Interactive, false),
11148            request.header.channel,
11149            request.header.epoch,
11150            request.header.corr,
11151            body,
11152        )
11153        .unwrap()
11154    }
11155
11156    fn established_route_errors() -> [(ErrorBody, bool); 3] {
11157        [
11158            (error_codes::STALE_ROUTE_EPOCH, true),
11159            (error_codes::UNKNOWN_CHANNEL, true),
11160            ("no_grant", false),
11161        ]
11162        .map(|(code, route_dead)| {
11163            (
11164                ErrorBody {
11165                    code: code.into(),
11166                    message: "request rejected".into(),
11167                    detail: Some(serde_json::json!({"channel": 5})),
11168                },
11169                route_dead,
11170            )
11171        })
11172    }
11173
11174    fn route_error(request: &Frame, body: &ErrorBody, daemon_origin: bool) -> Frame {
11175        let mut frame =
11176            watch_terminal(request, FrameType::Error, serde_json::to_vec(body).unwrap());
11177        if daemon_origin {
11178            frame.header.flags = frame.header.flags.with_daemon_origin();
11179        }
11180        frame
11181    }
11182
11183    #[tokio::test]
11184    async fn subscription_classifies_established_route_error() {
11185        for (body, route_dead) in established_route_errors() {
11186            let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11187            assert!(
11188                dispatch_frame(
11189                    &consumer.shared,
11190                    1,
11191                    route_error(&request, &body, route_dead)
11192                )
11193                .await
11194            );
11195            let end = subscription.ended().await;
11196            assert_eq!(end.is_route_dead(), route_dead, "{end:?}");
11197            let error = subscription.closed().await.unwrap_err();
11198            assert_eq!(error.is_route_dead(), route_dead, "{error:?}");
11199            if route_dead {
11200                assert_eq!(end, SubscriptionEnd::RouteDead(body.clone()));
11201                assert!(matches!(error, CallError::RouteDead(received) if *received == body));
11202            } else {
11203                assert_eq!(end, SubscriptionEnd::Error(body.clone()));
11204                assert!(matches!(error, CallError::Module(received) if received == body));
11205            }
11206        }
11207
11208        let (shared, _consumer, mut rx, _, _) = reservation_stand_in(1, 1);
11209        let permit = Arc::new(Semaphore::new(1)).acquire_owned().await.unwrap();
11210        let mut subscription = shared
11211            .send_subscription(SubscriptionSend {
11212                expected_handle: None,
11213                channel: 0,
11214                epoch: 0,
11215                body: b"watch".to_vec(),
11216                priority: Priority::Interactive,
11217                admission_class: AdmissionClass::Normal,
11218                event_buffer: 1,
11219                deadline: Instant::now() + Duration::from_secs(1),
11220                permit: RoutePermit::legacy(permit),
11221            })
11222            .await
11223            .unwrap();
11224        let request = rx.recv().await.unwrap().frame;
11225        let [(body, _), ..] = established_route_errors();
11226        assert!(dispatch_frame(&shared, 1, route_error(&request, &body, true)).await);
11227        assert_eq!(
11228            subscription.ended().await,
11229            SubscriptionEnd::Error(body.clone())
11230        );
11231        assert!(
11232            matches!(subscription.closed().await, Err(CallError::Module(received)) if received == body)
11233        );
11234    }
11235
11236    #[tokio::test]
11237    async fn subscription_ended_preserves_response_body_and_closed_stays_ok() {
11238        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11239        let body = vec![0, 255, 128, 1, 10];
11240        assert!(
11241            dispatch_frame(
11242                &consumer.shared,
11243                1,
11244                watch_terminal(&request, FrameType::Response, body.clone())
11245            )
11246            .await
11247        );
11248        subscription.closed().await.unwrap();
11249        assert_eq!(
11250            subscription.ended().await,
11251            SubscriptionEnd::Response(body.clone())
11252        );
11253        subscription.unsubscribe().unwrap();
11254        assert_eq!(subscription.ended().await, SubscriptionEnd::Response(body));
11255        assert_eq!(subscription.events().recv().await, None);
11256    }
11257
11258    #[tokio::test]
11259    async fn subscription_ended_distinguishes_empty_response_from_stream_end() {
11260        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11261        assert!(
11262            dispatch_frame(
11263                &consumer.shared,
11264                1,
11265                watch_terminal(&request, FrameType::Response, Vec::new())
11266            )
11267            .await
11268        );
11269        assert_eq!(
11270            subscription.ended().await,
11271            SubscriptionEnd::Response(Vec::new())
11272        );
11273        subscription.closed().await.unwrap();
11274    }
11275
11276    #[tokio::test]
11277    async fn subscription_ended_reports_stream_end_and_closed_stays_ok() {
11278        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11279        assert!(
11280            dispatch_frame(
11281                &consumer.shared,
11282                1,
11283                watch_terminal(&request, FrameType::StreamEnd, Vec::new())
11284            )
11285            .await
11286        );
11287        assert_eq!(subscription.ended().await, SubscriptionEnd::StreamEnd);
11288        subscription.closed().await.unwrap();
11289    }
11290
11291    #[tokio::test]
11292    async fn subscription_ended_reports_module_error_code_and_detail() {
11293        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11294        let error = ErrorBody {
11295            code: "no_grant".to_string(),
11296            message: "not accepted: no grant".to_string(),
11297            detail: Some(serde_json::json!({"capability": "watch"})),
11298        };
11299        assert!(
11300            dispatch_frame(
11301                &consumer.shared,
11302                1,
11303                watch_terminal(
11304                    &request,
11305                    FrameType::Error,
11306                    serde_json::to_vec(&error).unwrap()
11307                )
11308            )
11309            .await
11310        );
11311        assert_eq!(
11312            subscription.ended().await,
11313            SubscriptionEnd::Error(error.clone())
11314        );
11315        let CallError::Module(closed_error) = subscription.closed().await.unwrap_err() else {
11316            panic!("closed must still return the module error");
11317        };
11318        assert_eq!(closed_error, error);
11319        subscription.unsubscribe().unwrap();
11320        assert_eq!(subscription.ended().await, SubscriptionEnd::Error(error));
11321    }
11322
11323    #[tokio::test]
11324    async fn subscription_ended_reports_unsubscribe_as_cancelled_and_ignores_late_terminal() {
11325        let (consumer, mut rx, mut subscription, request) = watch_subscribed().await;
11326        subscription.unsubscribe().unwrap();
11327        subscription.unsubscribe().unwrap();
11328        subscription.closed().await.unwrap();
11329        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
11330        let cancel = rx.recv().await.unwrap().frame;
11331        assert_eq!(cancel.header.ty, FrameType::Cancel);
11332        assert_eq!(cancel.header.corr, request.header.corr);
11333        assert!(rx.try_recv().is_err());
11334        assert!(
11335            dispatch_frame(
11336                &consumer.shared,
11337                1,
11338                watch_terminal(&request, FrameType::Response, b"late".to_vec())
11339            )
11340            .await
11341        );
11342        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
11343    }
11344
11345    #[tokio::test]
11346    async fn subscription_ended_retains_route_close_reason() {
11347        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11348        let push = Frame::build(FrameType::Push, Flags::new(false, Priority::Interactive, false), 0, 0, 0,
11349            serde_json::to_vec(&serde_json::json!({"op": "route.closed", "module_id": "watch", "reason": "capability_denied", "channels": [request.header.channel]})).unwrap()).unwrap();
11350        assert!(dispatch_frame(&consumer.shared, 1, push).await);
11351        assert!(
11352            dispatch_frame(
11353                &consumer.shared,
11354                1,
11355                watch_terminal(&request, FrameType::Goodbye, Vec::new())
11356            )
11357            .await
11358        );
11359        let reason = RouteEndReason::Daemon(RouteCloseReason::CapabilityDenied);
11360        assert_eq!(
11361            subscription.ended().await,
11362            SubscriptionEnd::RouteClosed {
11363                reason: reason.clone()
11364            }
11365        );
11366        assert_eq!(
11367            subscription.closed().await.unwrap_err().close_reason(),
11368            Some(&reason)
11369        );
11370    }
11371
11372    #[tokio::test]
11373    async fn subscription_ended_reports_connection_loss() {
11374        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
11375        consumer
11376            .shared
11377            .handle_generation_drop(1, "fake connection lost".to_string());
11378        assert_eq!(subscription.ended().await, SubscriptionEnd::ConnectionLost);
11379        assert!(subscription.closed().await.is_err());
11380    }
11381
11382    #[tokio::test]
11383    async fn subscription_ended_waiter_wakes_on_stream_end() {
11384        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11385        let (end, dispatched) = tokio::join!(subscription.ended(), async {
11386            tokio::task::yield_now().await;
11387            dispatch_frame(
11388                &consumer.shared,
11389                1,
11390                watch_terminal(&request, FrameType::StreamEnd, Vec::new()),
11391            )
11392            .await
11393        });
11394        assert!(dispatched);
11395        assert_eq!(end, SubscriptionEnd::StreamEnd);
11396        subscription.closed().await.unwrap();
11397    }
11398
11399    #[tokio::test]
11400    async fn subscription_ended_reports_backpressure_without_hiding_closed_error() {
11401        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
11402        for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
11403            assert!(
11404                dispatch_frame(
11405                    &consumer.shared,
11406                    1,
11407                    watch_terminal(&request, FrameType::StreamData, vec![1])
11408                )
11409                .await
11410            );
11411        }
11412        assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
11413        assert!(matches!(
11414            subscription.closed().await,
11415            Err(CallError::SubscriptionBackpressure(_))
11416        ));
11417    }
11418
11419    #[tokio::test]
11420    async fn subscription_ended_reports_client_close_as_route_closed_by_caller() {
11421        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
11422        consumer.close().await;
11423        assert_eq!(
11424            subscription.ended().await,
11425            SubscriptionEnd::RouteClosed {
11426                reason: RouteEndReason::ClosedByCaller
11427            }
11428        );
11429        assert!(subscription.closed().await.is_err());
11430    }
11431
11432    #[test]
11433    fn drain_pending_channel_can_skip_subscriptions() {
11434        let mut pending = HashMap::new();
11435        let generation = 7;
11436        let channel = 11;
11437        let handle = RouteHandle::new(channel, 3, generation);
11438        let unary_key = PendingKey {
11439            generation,
11440            channel,
11441            epoch: handle.epoch,
11442            corr: 1,
11443        };
11444        let subscription_key = PendingKey {
11445            generation,
11446            channel,
11447            epoch: handle.epoch,
11448            corr: 2,
11449        };
11450        let (unary_tx, _unary_rx) = oneshot::channel();
11451        pending.insert(unary_key, PendingEntry::unary(unary_tx, false, None, None));
11452
11453        let (events_tx, _events_rx) = mpsc::channel(1);
11454        let (closed_tx, _closed_rx) = oneshot::channel();
11455        let (ended_tx, _ended_rx) = watch::channel(None);
11456        let permit = Arc::new(Semaphore::new(1))
11457            .try_acquire_owned()
11458            .expect("test semaphore permit should be available");
11459        pending.insert(
11460            subscription_key,
11461            PendingEntry::subscription(
11462                events_tx,
11463                closed_tx,
11464                ended_tx,
11465                RoutePermit::legacy(permit),
11466                Priority::Interactive,
11467            ),
11468        );
11469
11470        let drained = drain_pending_handle(&mut pending, handle, false);
11471        assert_eq!(drained.len(), 1);
11472        assert!(pending.contains_key(&subscription_key));
11473
11474        let drained = drain_pending_handle(&mut pending, handle, true);
11475        assert_eq!(drained.len(), 1);
11476        assert!(pending.is_empty());
11477    }
11478
11479    fn response_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
11480        Frame::build(
11481            FrameType::Response,
11482            Flags::new(false, Priority::Interactive, false),
11483            channel,
11484            epoch,
11485            corr,
11486            body,
11487        )
11488        .unwrap()
11489    }
11490
11491    #[tokio::test]
11492    async fn stale_epoch_ingress_drops_without_settling_matching_corr() {
11493        let shared = Arc::new(reader_skew_tests::legacy_shared(
11494            PathBuf::from("/tmp/does-not-exist"),
11495            ConsumerOptions::default(),
11496        ));
11497        let (writer, _rx) = mpsc::channel(4);
11498        let current = RouteHandle::new(9, 2, 1);
11499        let stale_key = PendingKey {
11500            generation: 1,
11501            channel: 9,
11502            epoch: 1,
11503            corr: 77,
11504        };
11505        let key = PendingKey {
11506            generation: 1,
11507            channel: 9,
11508            epoch: 2,
11509            corr: 77,
11510        };
11511        let (stale_tx, mut stale_response) = oneshot::channel();
11512        let (tx, mut response) = oneshot::channel();
11513        {
11514            let mut inner = shared.lock_inner();
11515            inner.writer = Some(writer);
11516            inner.daemon_ver = "0.39.0".into();
11517            inner.route_epochs.insert(9, current);
11518            inner
11519                .pending
11520                .insert(stale_key, PendingEntry::unary(stale_tx, false, None, None));
11521            inner
11522                .pending
11523                .insert(key, PendingEntry::unary(tx, false, None, None));
11524        }
11525
11526        assert!(dispatch_frame(&shared, 1, response_frame(9, 1, 77, b"stale".to_vec())).await);
11527        assert!(matches!(
11528            response.try_recv(),
11529            Err(oneshot::error::TryRecvError::Empty)
11530        ));
11531        assert!(matches!(
11532            stale_response.try_recv(),
11533            Err(oneshot::error::TryRecvError::Empty)
11534        ));
11535        assert!(shared.lock_inner().pending.contains_key(&stale_key));
11536        assert!(shared.lock_inner().pending.contains_key(&key));
11537        assert_eq!(shared.lock_inner().dropped_route_frames, 1);
11538
11539        assert!(dispatch_frame(&shared, 1, response_frame(9, 2, 77, b"current".to_vec())).await);
11540        let PendingResult::Terminal(PendingTerminal::Response { body, .. }) =
11541            response.await.unwrap()
11542        else {
11543            panic!("current epoch must settle its own pending request");
11544        };
11545        assert_eq!(body, b"current");
11546        assert!(shared.lock_inner().pending.contains_key(&stale_key));
11547    }
11548
11549    #[tokio::test]
11550    async fn route_poll_response_must_echo_expected_handle_before_settling() {
11551        let shared = Arc::new(reader_skew_tests::legacy_shared(
11552            PathBuf::from("/tmp/does-not-exist"),
11553            ConsumerOptions::default(),
11554        ));
11555        let (writer, _rx) = mpsc::channel(4);
11556        let handle = RouteHandle::new(3, 9, 1);
11557        let key = PendingKey {
11558            generation: 1,
11559            channel: 0,
11560            epoch: 0,
11561            corr: 88,
11562        };
11563        let (tx, mut response) = oneshot::channel();
11564        {
11565            let mut inner = shared.lock_inner();
11566            inner.writer = Some(writer);
11567            inner.daemon_ver = "0.39.0".into();
11568            inner.route_epochs.insert(handle.channel, handle);
11569            inner
11570                .pending
11571                .insert(key, PendingEntry::unary(tx, false, Some(handle), None));
11572        }
11573        let wrong = serde_json::to_vec(&ClientControlResponse::RoutePoll {
11574            route_channel: handle.channel,
11575            route_epoch: handle.epoch + 1,
11576            status: Some("wrong".to_string()),
11577            live: Some(true),
11578        })
11579        .unwrap();
11580        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, wrong)).await);
11581        assert!(matches!(
11582            response.try_recv(),
11583            Err(oneshot::error::TryRecvError::Empty)
11584        ));
11585        assert!(shared.lock_inner().pending.contains_key(&key));
11586
11587        let correct = serde_json::to_vec(&ClientControlResponse::RoutePoll {
11588            route_channel: handle.channel,
11589            route_epoch: handle.epoch,
11590            status: Some("ready".to_string()),
11591            live: Some(true),
11592        })
11593        .unwrap();
11594        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, correct)).await);
11595        assert!(matches!(
11596            response.await.unwrap(),
11597            PendingResult::Terminal(PendingTerminal::Response { .. })
11598        ));
11599    }
11600
11601    #[tokio::test]
11602    async fn stale_connection_handle_emits_no_request_cancel_or_goodbye() {
11603        let shared = Arc::new(reader_skew_tests::legacy_shared(
11604            PathBuf::from("/tmp/does-not-exist"),
11605            ConsumerOptions::default(),
11606        ));
11607        let (writer, mut rx) = mpsc::channel(4);
11608        let stale = RouteHandle::new(4, 1, 1);
11609        let current = RouteHandle::new(4, 1, 2);
11610        {
11611            let mut inner = shared.lock_inner();
11612            inner.generation = 2;
11613            inner.writer = Some(writer);
11614            inner.daemon_ver = "0.39.0".into();
11615            inner.route_epochs.insert(4, current);
11616        }
11617
11618        let err = shared
11619            .send_request(RequestSend {
11620                binary: false,
11621                expected_handle: Some(stale),
11622                channel: stale.channel,
11623                epoch: stale.epoch,
11624                body: b"request".to_vec(),
11625                priority: Priority::Interactive,
11626                admission_class: AdmissionClass::Normal,
11627                deadline: Instant::now() + Duration::from_millis(10),
11628                retain_late_route_open: false,
11629                route_open_reverse_requests: None,
11630            })
11631            .await
11632            .unwrap_err();
11633        assert!(matches!(err, CallError::StaleRouteHandle(handle) if handle == stale));
11634        shared.send_cancel(stale, 8, Priority::Interactive);
11635        assert!(!shared.send_route_goodbye(stale, false));
11636        assert!(
11637            rx.try_recv().is_err(),
11638            "stale operations must not queue frames"
11639        );
11640    }
11641
11642    #[tokio::test]
11643    async fn route_poll_refusal_preserves_daemon_code_message_and_detail() {
11644        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
11645        let handle = RouteHandle::new(3, 9, 1);
11646        shared
11647            .lock_inner()
11648            .route_epochs
11649            .insert(handle.channel, handle);
11650        let poll = consumer.poll_route(&handle, PollKind::Liveness, Duration::from_secs(1));
11651        tokio::pin!(poll);
11652        assert_pending(poll.as_mut()).await;
11653        let request = receiver.try_recv().unwrap();
11654        let refusal = ErrorBody {
11655            code: "unknown_route".into(),
11656            message: "the route is no longer present".into(),
11657            detail: Some(serde_json::json!({ "route_channel": 3, "route_epoch": 9 })),
11658        };
11659        assert!(
11660            dispatch_frame(
11661                &shared,
11662                1,
11663                channel_zero_frame(
11664                    FrameType::Error,
11665                    request.frame.header.corr,
11666                    serde_json::to_vec(&refusal).unwrap(),
11667                ),
11668            )
11669            .await
11670        );
11671        let err = poll.await.unwrap_err();
11672        assert_eq!(err.code(), Some("unknown_route"));
11673        let CallError::Module(body) = err else {
11674            panic!("a delivered refusal must not be classified as a send failure");
11675        };
11676        assert_eq!(body.code, refusal.code);
11677        assert_eq!(body.message, refusal.message);
11678        assert_eq!(body.detail, refusal.detail);
11679    }
11680
11681    #[tokio::test]
11682    async fn late_route_open_queues_goodbye_and_full_queue_closes_connection() {
11683        let shared = Arc::new(reader_skew_tests::legacy_shared(
11684            PathBuf::from("/tmp/does-not-exist"),
11685            ConsumerOptions::default(),
11686        ));
11687        let (writer, mut rx) = mpsc::channel(2);
11688        let key = PendingKey {
11689            generation: 1,
11690            channel: 0,
11691            epoch: 0,
11692            corr: 41,
11693        };
11694        let (tx, response) = oneshot::channel();
11695        drop(response);
11696        {
11697            let mut inner = shared.lock_inner();
11698            inner.writer = Some(writer);
11699            inner.daemon_ver = "0.39.0".into();
11700            inner
11701                .pending
11702                .insert(key, PendingEntry::unary(tx, true, None, None));
11703        }
11704        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
11705            request_window: None,
11706            watch_window: None,
11707            route_channel: 12,
11708            route_epoch: 7,
11709        })
11710        .unwrap();
11711        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 41, body)).await);
11712        let cleanup = rx.recv().await.unwrap().frame;
11713        assert_eq!(cleanup.header.ty, FrameType::Goodbye);
11714        assert_eq!((cleanup.header.channel, cleanup.header.epoch), (12, 7));
11715
11716        let shared = Arc::new(reader_skew_tests::legacy_shared(
11717            PathBuf::from("/tmp/does-not-exist"),
11718            ConsumerOptions {
11719                reconnect_backoff: RetryBackoff {
11720                    max_attempts: 1,
11721                    ..RetryBackoff::default()
11722                },
11723                ..ConsumerOptions::default()
11724            },
11725        ));
11726        let (writer, _rx) = mpsc::channel(1);
11727        let filler = response_frame(0, 0, 1, Vec::new());
11728        writer
11729            .try_send(WriteCommand {
11730                frame: filler,
11731                pending: None,
11732            })
11733            .unwrap();
11734        let key = PendingKey {
11735            generation: 1,
11736            channel: 0,
11737            epoch: 0,
11738            corr: 42,
11739        };
11740        let (tx, response) = oneshot::channel();
11741        drop(response);
11742        {
11743            let mut inner = shared.lock_inner();
11744            inner.writer = Some(writer);
11745            inner.daemon_ver = "0.39.0".into();
11746            inner
11747                .pending
11748                .insert(key, PendingEntry::unary(tx, true, None, None));
11749        }
11750        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
11751            request_window: None,
11752            watch_window: None,
11753            route_channel: 13,
11754            route_epoch: 8,
11755        })
11756        .unwrap();
11757        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 42, body)).await);
11758        assert!(shared.lock_inner().writer.is_none());
11759    }
11760
11761    #[tokio::test]
11762    async fn correlation_allocator_emits_max_once_then_closes_without_reuse() {
11763        let shared = Arc::new(reader_skew_tests::legacy_shared(
11764            PathBuf::from("/tmp/does-not-exist"),
11765            ConsumerOptions {
11766                reconnect_backoff: RetryBackoff {
11767                    max_attempts: 1,
11768                    ..RetryBackoff::default()
11769                },
11770                ..ConsumerOptions::default()
11771            },
11772        ));
11773        let (writer, mut rx) = mpsc::channel(4);
11774        {
11775            let mut inner = shared.lock_inner();
11776            inner.writer = Some(writer);
11777            inner.daemon_ver = "0.39.0".into();
11778            inner.next_corr = Some(u64::MAX);
11779        }
11780        let request_shared = Arc::clone(&shared);
11781        let request = tokio::spawn(async move {
11782            request_shared
11783                .send_request(RequestSend {
11784                    binary: false,
11785                    expected_handle: None,
11786                    channel: 0,
11787                    epoch: 0,
11788                    body: Vec::new(),
11789                    priority: Priority::Interactive,
11790                    admission_class: AdmissionClass::Normal,
11791                    deadline: Instant::now() + Duration::from_secs(1),
11792                    retain_late_route_open: false,
11793                    route_open_reverse_requests: None,
11794                })
11795                .await
11796        });
11797        let command = rx.recv().await.unwrap();
11798        assert_eq!(command.frame.header.corr, u64::MAX);
11799        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, u64::MAX, Vec::new()),).await);
11800        assert!(request.await.unwrap().is_ok());
11801
11802        let exhausted = shared
11803            .send_request(RequestSend {
11804                binary: false,
11805                expected_handle: None,
11806                channel: 0,
11807                epoch: 0,
11808                body: Vec::new(),
11809                priority: Priority::Interactive,
11810                admission_class: AdmissionClass::Normal,
11811                deadline: Instant::now() + Duration::from_millis(10),
11812                retain_late_route_open: false,
11813                route_open_reverse_requests: None,
11814            })
11815            .await
11816            .unwrap_err();
11817        assert!(matches!(exhausted, CallError::NotSent(_)));
11818        assert!(rx.try_recv().is_err());
11819        assert!(shared.lock_inner().writer.is_none());
11820    }
11821
11822    #[tokio::test]
11823    async fn managed_call_deadline_bounds_flow_control_wait() {
11824        let shared = Arc::new(reader_skew_tests::legacy_shared(
11825            PathBuf::from("/tmp/does-not-exist"),
11826            ConsumerOptions::default(),
11827        ));
11828        let (writer, mut rx) = mpsc::channel(4);
11829        let target = RouteTarget::ToolProvider {
11830            module_id: "flow-controlled".to_string(),
11831        };
11832        let identity = BindIdentity::new("test".to_string(), "deadline".to_string());
11833        let consumer_identity = Some(ConsumerIdentity {
11834            module_id: "caller".to_string(),
11835            launch_nonce: "nonce".to_string(),
11836        });
11837        let first_opts = CallOptions {
11838            timeout: Duration::from_secs(1),
11839            consumer_identity: consumer_identity.clone(),
11840            ..CallOptions::default()
11841        };
11842        let second_opts = CallOptions {
11843            timeout: Duration::from_millis(25),
11844            consumer_identity,
11845            ..CallOptions::default()
11846        };
11847        let key = RouteKey::new(
11848            &target,
11849            &identity,
11850            first_opts.consumer_identity.as_ref(),
11851            None,
11852        );
11853        let handle = RouteHandle::new(5, 3, 1);
11854        {
11855            let mut inner = shared.lock_inner();
11856            inner.writer = Some(writer);
11857            inner.daemon_ver = "0.39.0".into();
11858            inner.cache_route(
11859                key,
11860                RouteState {
11861                    handle,
11862                    sem: Arc::new(Semaphore::new(1)),
11863                    watch_sem: None,
11864                    opted_in: false,
11865                },
11866            );
11867        }
11868
11869        let first = tokio::spawn({
11870            let consumer = SubcConsumer {
11871                shared: Arc::clone(&shared),
11872            };
11873            let target = target.clone();
11874            let identity = identity.clone();
11875            async move {
11876                consumer
11877                    .call(target, identity, b"first".to_vec(), first_opts)
11878                    .await
11879            }
11880        });
11881        let first_frame = rx
11882            .recv()
11883            .await
11884            .expect("the first request should enter the fake daemon queue");
11885        assert_eq!(first_frame.frame.header.ty, FrameType::Request);
11886        assert_eq!(first_frame.frame.body, b"first");
11887        assert!(shared.mark_pending_accepted(
11888            first_frame
11889                .pending
11890                .expect("request commands retain their pending key"),
11891        ));
11892
11893        let consumer = SubcConsumer {
11894            shared: Arc::clone(&shared),
11895        };
11896        let result = tokio::time::timeout(
11897            Duration::from_millis(250),
11898            consumer.call(target, identity, b"second".to_vec(), second_opts),
11899        )
11900        .await
11901        .expect("a flow-controlled call must finish at its own deadline")
11902        .unwrap_err();
11903        assert!(matches!(result, CallError::NotSent(_)));
11904        assert!(
11905            rx.try_recv().is_err(),
11906            "the timed-out second request must not reach the fake daemon"
11907        );
11908
11909        first.abort();
11910        let _ = first.await;
11911    }
11912
11913    #[tokio::test]
11914    async fn admitted_route_open_emits_one_frame_without_retrying_daemon_errors() {
11915        let shared = Arc::new(reader_skew_tests::legacy_shared(
11916            PathBuf::from("/tmp/does-not-exist"),
11917            ConsumerOptions {
11918                call_timeout: Duration::from_secs(1),
11919                ..ConsumerOptions::default()
11920            },
11921        ));
11922        let (writer, mut rx) = mpsc::channel(4);
11923        {
11924            let mut inner = shared.lock_inner();
11925            inner.writer = Some(writer);
11926            inner.daemon_ver = "0.39.0".into();
11927        }
11928
11929        let consumer = SubcConsumer {
11930            shared: Arc::clone(&shared),
11931        };
11932        let target = RouteTarget::ToolProvider {
11933            module_id: "admitted-target".to_string(),
11934        };
11935        let identity = BindIdentity::new("test".to_string(), "admitted".to_string());
11936        let task = tokio::spawn(async move {
11937            consumer
11938                .open_route_with_admission_facts(
11939                    target,
11940                    identity,
11941                    serde_json::json!({"schema": 1, "verified_class": "member"}),
11942                )
11943                .await
11944        });
11945
11946        let command = rx.recv().await.expect("one route.open must be queued");
11947        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
11948        let ClientControlRequest::RouteOpen {
11949            admission_facts, ..
11950        } = request
11951        else {
11952            panic!("expected route.open")
11953        };
11954        assert_eq!(
11955            admission_facts,
11956            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
11957        );
11958
11959        let error_body = serde_json::to_vec(&ErrorBody {
11960            code: "admission_facts_not_permitted".to_string(),
11961            message: "not permitted".to_string(),
11962            detail: None,
11963        })
11964        .unwrap();
11965        assert!(
11966            dispatch_frame(
11967                &shared,
11968                1,
11969                Frame::build(
11970                    FrameType::Error,
11971                    Flags::new(false, Priority::Interactive, false),
11972                    0,
11973                    0,
11974                    command.frame.header.corr,
11975                    error_body,
11976                )
11977                .unwrap(),
11978            )
11979            .await
11980        );
11981        let result = task.await.unwrap();
11982        assert!(matches!(result, Err(CallError::NotSent(_))));
11983        assert!(rx.try_recv().is_err(), "one-shot route.open must not retry");
11984    }
11985
11986    /// Drive one admitted route.open to success on a test writer and return the
11987    /// route.open request that was sent, the resolved handle, and the writer.
11988    async fn open_admitted_route_for_test(
11989        opts: Option<CallOptions>,
11990    ) -> (
11991        Arc<Shared>,
11992        SubcConsumer,
11993        ClientControlRequest,
11994        Result<RouteHandle, CallError>,
11995        mpsc::Receiver<WriteCommand>,
11996    ) {
11997        let shared = writer_test_shared();
11998        let (writer, mut rx) = mpsc::channel(8);
11999        let generation = {
12000            let mut inner = shared.lock_inner();
12001            inner.writer = Some(writer);
12002            inner.daemon_ver = "0.39.0".into();
12003            inner.generation
12004        };
12005        let consumer = SubcConsumer {
12006            shared: Arc::clone(&shared),
12007        };
12008        let target = RouteTarget::ToolProvider {
12009            module_id: "cerebellum".to_string(),
12010        };
12011        let identity = BindIdentity::new("test".to_string(), "admitted".to_string());
12012        let facts = serde_json::json!({"schema": 1, "verified_class": "member"});
12013        // The consumer is returned from the task and kept alive by the caller:
12014        // dropping it closes the connection, after which no frame is dispatched.
12015        let task = tokio::spawn(async move {
12016            let result = match opts {
12017                Some(opts) => {
12018                    consumer
12019                        .open_route_with_admission_facts_and_options(target, identity, facts, opts)
12020                        .await
12021                }
12022                None => {
12023                    consumer
12024                        .open_route_with_admission_facts(target, identity, facts)
12025                        .await
12026                }
12027            };
12028            (consumer, result)
12029        });
12030        let command = rx.recv().await.expect("one route.open must be queued");
12031        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
12032        let response = serde_json::to_vec(&ClientControlResponse::RouteOpen {
12033            request_window: None,
12034            watch_window: None,
12035            route_channel: 21,
12036            route_epoch: 4,
12037        })
12038        .unwrap();
12039        assert!(
12040            dispatch_frame(
12041                &shared,
12042                generation,
12043                Frame::build(
12044                    FrameType::Response,
12045                    Flags::new(false, Priority::Interactive, false),
12046                    0,
12047                    0,
12048                    command.frame.header.corr,
12049                    response,
12050                )
12051                .unwrap(),
12052            )
12053            .await
12054        );
12055        let (consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
12056            .await
12057            .expect("admitted route.open resolves")
12058            .unwrap();
12059        (shared, consumer, request, result, rx)
12060    }
12061
12062    #[tokio::test]
12063    async fn admitted_route_open_refusal_keeps_the_daemon_code_and_detail() {
12064        let shared = writer_test_shared();
12065        let (writer, mut rx) = mpsc::channel(8);
12066        let generation = {
12067            let mut inner = shared.lock_inner();
12068            inner.writer = Some(writer);
12069            inner.daemon_ver = "0.39.0".into();
12070            inner.generation
12071        };
12072        let consumer = SubcConsumer {
12073            shared: Arc::clone(&shared),
12074        };
12075        let task = tokio::spawn(async move {
12076            let result = consumer
12077                .open_route_with_admission_facts(
12078                    RouteTarget::ToolProvider {
12079                        module_id: "cerebellum".to_string(),
12080                    },
12081                    BindIdentity::new("test".to_string(), "admitted".to_string()),
12082                    serde_json::json!({"schema": 1, "verified_class": "member"}),
12083                )
12084                .await;
12085            (consumer, result)
12086        });
12087        let command = rx.recv().await.expect("one route.open must be queued");
12088        let refusal = ErrorBody {
12089            code: "module_warming".to_string(),
12090            message: "cerebellum is not ready".to_string(),
12091            detail: Some(serde_json::json!({"reason": "declared_not_ready"})),
12092        };
12093        assert!(
12094            dispatch_frame(
12095                &shared,
12096                generation,
12097                Frame::build(
12098                    FrameType::Error,
12099                    Flags::new(false, Priority::Interactive, false),
12100                    0,
12101                    0,
12102                    command.frame.header.corr,
12103                    serde_json::to_vec(&refusal).unwrap(),
12104                )
12105                .unwrap(),
12106            )
12107            .await
12108        );
12109        let (_consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
12110            .await
12111            .expect("admitted route.open resolves")
12112            .unwrap();
12113        let error = result.expect_err("a refused open is an error");
12114        assert!(
12115            error.is_not_sent(),
12116            "a refused open never reached the module: {error}"
12117        );
12118        let body = error
12119            .route_open_refusal()
12120            .unwrap_or_else(|| panic!("the refusal's code must survive: {error}"));
12121        assert_eq!(body.code, "module_warming");
12122        assert_eq!(
12123            body.detail,
12124            Some(serde_json::json!({"reason": "declared_not_ready"}))
12125        );
12126        assert!(
12127            error.to_string().contains("tool_provider:cerebellum"),
12128            "the error names its target: {error}"
12129        );
12130    }
12131
12132    #[tokio::test]
12133    async fn admitted_route_without_options_opens_and_declares_no_reverse_capabilities() {
12134        let (_shared, _consumer, request, result, _rx) = open_admitted_route_for_test(None).await;
12135        let ClientControlRequest::RouteOpen {
12136            consumer_capabilities,
12137            admission_facts,
12138            ..
12139        } = request
12140        else {
12141            panic!("expected route.open")
12142        };
12143        assert_eq!(consumer_capabilities, None);
12144        assert!(admission_facts.is_some());
12145        let handle = result.expect("admitted route opens");
12146        assert_eq!((handle.channel, handle.epoch), (21, 4));
12147    }
12148
12149    // An admitted route opened with handlers declares their capabilities and
12150    // delivers the provider's reverse requests to them, replying under the
12151    // provider's own correlation id: the browser plane's consent prompts arrive
12152    // as elicitation on exactly this kind of route.
12153    #[tokio::test]
12154    async fn admitted_route_with_options_delivers_elicitation_to_its_handler() {
12155        let opts = CallOptions::default();
12156        let seen = Arc::new(Mutex::new(None));
12157        let seen_by_handler = Arc::clone(&seen);
12158        let reply_body = br#"{"jsonrpc":"2.0","id":3,"result":{"action":"accept"}}"#.to_vec();
12159        let expected_reply = reply_body.clone();
12160        opts.reverse_requests
12161            .on_request("elicitation", move |body, ctx| {
12162                *seen_by_handler
12163                    .lock()
12164                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((body, ctx.corr));
12165                let reply_body = reply_body.clone();
12166                async move { reply_body }
12167            })
12168            .unwrap();
12169
12170        let (shared, _consumer, request, result, mut rx) =
12171            open_admitted_route_for_test(Some(opts)).await;
12172        let ClientControlRequest::RouteOpen {
12173            consumer_capabilities,
12174            admission_facts,
12175            ..
12176        } = request
12177        else {
12178            panic!("expected route.open")
12179        };
12180        assert_eq!(consumer_capabilities, Some(vec!["elicitation".to_string()]));
12181        assert_eq!(
12182            admission_facts,
12183            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
12184        );
12185        let handle = result.expect("admitted route opens");
12186
12187        let request_body =
12188            br#"{"jsonrpc":"2.0","id":3,"method":"elicitation/create","params":{}}"#.to_vec();
12189        assert!(
12190            dispatch_frame(
12191                &shared,
12192                handle.connection_token(),
12193                reverse_request_frame(handle, 900, request_body.clone()),
12194            )
12195            .await
12196        );
12197        let reply = tokio::time::timeout(Duration::from_secs(1), rx.recv())
12198            .await
12199            .expect("the handler replies")
12200            .unwrap()
12201            .frame;
12202        assert_eq!(reply.header.ty, FrameType::Response);
12203        assert_eq!(reply.header.corr, 900);
12204        assert_eq!(reply.header.channel, 21);
12205        assert_eq!(reply.body, expected_reply);
12206        assert_eq!(
12207            seen.lock()
12208                .unwrap_or_else(|poisoned| poisoned.into_inner())
12209                .clone(),
12210            Some((request_body, 900))
12211        );
12212    }
12213
12214    #[tokio::test]
12215    async fn route_open_waiter_deadline_is_not_sent_without_writing() {
12216        let shared = Arc::new(reader_skew_tests::legacy_shared(
12217            PathBuf::from("/tmp/does-not-exist"),
12218            ConsumerOptions::default(),
12219        ));
12220        let (writer, mut rx) = mpsc::channel(4);
12221        let target = RouteTarget::ToolProvider {
12222            module_id: "single-flight".to_string(),
12223        };
12224        let identity = BindIdentity::new("test".to_string(), "route-open".to_string());
12225        let opts = CallOptions {
12226            timeout: Duration::from_millis(25),
12227            consumer_identity: Some(ConsumerIdentity {
12228                module_id: "caller".to_string(),
12229                launch_nonce: "nonce".to_string(),
12230            }),
12231            ..CallOptions::default()
12232        };
12233        let key = RouteKey::new(&target, &identity, opts.consumer_identity.as_ref(), None);
12234        {
12235            let mut inner = shared.lock_inner();
12236            inner.writer = Some(writer);
12237            inner.daemon_ver = "0.39.0".into();
12238            inner.openings.insert(
12239                key,
12240                Opening {
12241                    waiters: Vec::new(),
12242                    closed: false,
12243                },
12244            );
12245        }
12246
12247        let consumer = SubcConsumer { shared };
12248        let result = tokio::time::timeout(
12249            Duration::from_millis(250),
12250            consumer.open_route(target, identity, opts),
12251        )
12252        .await
12253        .expect("a route.open waiter must finish at its own deadline")
12254        .unwrap_err();
12255        assert!(matches!(result, CallError::NotSent(_)));
12256        assert!(
12257            rx.try_recv().is_err(),
12258            "a timed-out route.open waiter must not write a control frame"
12259        );
12260    }
12261
12262    // A route.open whose control reply never arrives before the deadline has an
12263    // unknown outcome of its own (the daemon may have opened the channel), but
12264    // the managed call's request body was never written. The call and the
12265    // subscription must therefore report NotSent, not OutcomeUnknown: callers
12266    // use that distinction to decide whether a non-idempotent retry is safe.
12267    async fn managed_op_with_unanswered_route_open(subscribe: bool) -> CallError {
12268        let shared = Arc::new(reader_skew_tests::legacy_shared(
12269            PathBuf::from("/tmp/does-not-exist"),
12270            ConsumerOptions::default(),
12271        ));
12272        let (writer, mut rx) = mpsc::channel(4);
12273        {
12274            let mut inner = shared.lock_inner();
12275            inner.writer = Some(writer);
12276            inner.daemon_ver = "0.39.0".into();
12277        }
12278        let consumer = SubcConsumer {
12279            shared: Arc::clone(&shared),
12280        };
12281        let target = RouteTarget::ToolProvider {
12282            module_id: "slow-route-open".to_string(),
12283        };
12284        let identity = BindIdentity::new("test".to_string(), "slow-route-open".to_string());
12285        let task = tokio::spawn(async move {
12286            if subscribe {
12287                consumer
12288                    .subscribe(
12289                        target,
12290                        identity,
12291                        b"{}".to_vec(),
12292                        SubscribeOptions {
12293                            route_open_timeout: Duration::from_millis(200),
12294                            route_retry_deadline: Duration::from_millis(100),
12295                            ..SubscribeOptions::default()
12296                        },
12297                    )
12298                    .await
12299                    .map(|_| ())
12300            } else {
12301                consumer
12302                    .call(
12303                        target,
12304                        identity,
12305                        b"{}".to_vec(),
12306                        CallOptions {
12307                            timeout: Duration::from_millis(200),
12308                            route_retry_deadline: Duration::from_millis(100),
12309                            ..CallOptions::default()
12310                        },
12311                    )
12312                    .await
12313                    .map(|_| ())
12314            }
12315        });
12316
12317        // Play the writer task: accept the route.open onto the wire (so the
12318        // consumer knows the control frame left) and then never answer it,
12319        // which is what a daemon under load looks like from the client.
12320        let command = rx.recv().await.expect("route.open must be queued");
12321        assert_eq!(command.frame.header.channel, 0);
12322        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
12323        assert!(matches!(request, ClientControlRequest::RouteOpen { .. }));
12324        assert!(shared.mark_pending_accepted(command.pending.expect("route.open is tracked")));
12325
12326        let err = tokio::time::timeout(Duration::from_secs(2), task)
12327            .await
12328            .expect("the managed op must settle at its own deadline")
12329            .unwrap()
12330            .expect_err("an unanswered route.open cannot yield a route");
12331        while let Ok(command) = rx.try_recv() {
12332            assert_eq!(
12333                command.frame.header.channel, 0,
12334                "no data-plane frame may be written without an open route"
12335            );
12336        }
12337        err
12338    }
12339
12340    #[tokio::test]
12341    async fn call_whose_route_open_times_out_after_send_is_not_sent() {
12342        let err = managed_op_with_unanswered_route_open(false).await;
12343        assert!(
12344            matches!(err, CallError::NotSent(_)),
12345            "call body never left the client, got {err:?}"
12346        );
12347    }
12348
12349    #[tokio::test]
12350    async fn subscribe_whose_route_open_times_out_after_send_is_not_sent() {
12351        let err = managed_op_with_unanswered_route_open(true).await;
12352        assert!(
12353            matches!(err, CallError::NotSent(_)),
12354            "subscription request never left the client, got {err:?}"
12355        );
12356    }
12357
12358    #[tokio::test]
12359    async fn route_poll_deadline_bounds_writer_capacity() {
12360        let shared = Arc::new(reader_skew_tests::legacy_shared(
12361            PathBuf::from("/tmp/does-not-exist"),
12362            ConsumerOptions::default(),
12363        ));
12364        let (writer, mut rx) = mpsc::channel(1);
12365        let handle = RouteHandle::new(8, 4, 1);
12366        writer
12367            .try_send(WriteCommand {
12368                frame: response_frame(0, 0, 99, Vec::new()),
12369                pending: None,
12370            })
12371            .expect("the fake daemon queue should accept its filler frame");
12372        {
12373            let mut inner = shared.lock_inner();
12374            inner.writer = Some(writer);
12375            inner.daemon_ver = "0.39.0".into();
12376            inner.route_epochs.insert(handle.channel, handle);
12377        }
12378
12379        let consumer = SubcConsumer { shared };
12380        let result = tokio::time::timeout(
12381            Duration::from_millis(250),
12382            consumer.poll_route(&handle, PollKind::Liveness, Duration::from_millis(25)),
12383        )
12384        .await
12385        .expect("a control request must finish at its own deadline")
12386        .unwrap_err();
12387        assert!(matches!(result, CallError::NotSent(_)));
12388        assert_eq!(
12389            rx.recv()
12390                .await
12391                .expect("the filler must still be the only queued frame")
12392                .frame
12393                .header
12394                .corr,
12395            99
12396        );
12397        assert!(
12398            rx.try_recv().is_err(),
12399            "the timed-out control request must not reach the fake daemon"
12400        );
12401    }
12402
12403    #[tokio::test]
12404    async fn subscription_deadline_bounds_writer_capacity() {
12405        let shared = Arc::new(reader_skew_tests::legacy_shared(
12406            PathBuf::from("/tmp/does-not-exist"),
12407            ConsumerOptions::default(),
12408        ));
12409        let (writer, mut rx) = mpsc::channel(1);
12410        let handle = RouteHandle::new(9, 2, 1);
12411        let route_sem = Arc::new(Semaphore::new(1));
12412        writer
12413            .try_send(WriteCommand {
12414                frame: response_frame(0, 0, 100, Vec::new()),
12415                pending: None,
12416            })
12417            .expect("the fake daemon queue should accept its filler frame");
12418        {
12419            let mut inner = shared.lock_inner();
12420            inner.writer = Some(writer);
12421            inner.daemon_ver = "0.39.0".into();
12422            inner.cache_route(
12423                RouteKey::new(
12424                    &RouteTarget::ToolProvider {
12425                        module_id: "subscriptions".to_string(),
12426                    },
12427                    &BindIdentity::new("test".to_string(), "subscription".to_string()),
12428                    None,
12429                    None,
12430                ),
12431                RouteState {
12432                    handle,
12433                    sem: Arc::clone(&route_sem),
12434                    watch_sem: None,
12435                    opted_in: false,
12436                },
12437            );
12438        }
12439
12440        let consumer = SubcConsumer { shared };
12441        let result = tokio::time::timeout(
12442            Duration::from_millis(250),
12443            consumer.subscribe_route(
12444                &handle,
12445                b"subscribe".to_vec(),
12446                SubscribeOptions {
12447                    route_open_timeout: Duration::from_millis(25),
12448                    ..SubscribeOptions::default()
12449                },
12450            ),
12451        )
12452        .await
12453        .expect("a subscription must finish at its route-open deadline");
12454        let result = match result {
12455            Ok(_) => panic!("a subscription blocked before writing must time out"),
12456            Err(err) => err,
12457        };
12458        assert!(matches!(result, CallError::NotSent(_)));
12459        assert_eq!(
12460            rx.recv()
12461                .await
12462                .expect("the filler must still be the only queued frame")
12463                .frame
12464                .header
12465                .corr,
12466            100
12467        );
12468        assert!(
12469            rx.try_recv().is_err(),
12470            "the timed-out subscription must not reach the fake daemon"
12471        );
12472        assert!(
12473            route_sem.try_acquire().is_ok(),
12474            "a pre-write subscription timeout must release its route credit"
12475        );
12476    }
12477
12478    #[test]
12479    fn catalog_list_deserializes_golden_reply_and_ignores_unknown_fields() {
12480        let mut reply: serde_json::Value = serde_json::from_str(include_str!(
12481            "../../subc-control/tests/golden/client_control_response_catalog_list.json"
12482        ))
12483        .expect("the catalog.list golden reply must be valid JSON");
12484        reply["future_top_level"] = serde_json::json!(true);
12485        reply["modules"][0]["future_module_field"] = serde_json::json!("ignored");
12486
12487        let catalog: CatalogList =
12488            serde_json::from_value(reply).expect("catalog.list should tolerate additive fields");
12489        assert_eq!(catalog.generation, 7);
12490        assert_eq!(catalog.modules.len(), 1);
12491        assert!(catalog.subc_ops.iter().any(|op| op == "catalog.list"));
12492
12493        let tools = catalog.modules[0]
12494            .roles
12495            .iter()
12496            .find_map(|role| match role {
12497                subc_protocol::manifest::ProviderRole::ToolProvider { tools, .. } => Some(tools),
12498                _ => None,
12499            })
12500            .expect("the golden module must advertise a tool_provider role");
12501        let tool = tools
12502            .first()
12503            .expect("the golden tool_provider role must advertise a tool");
12504        assert!(!tool.name.is_empty());
12505        assert_eq!(
12506            tool.schema.get("type").and_then(serde_json::Value::as_str),
12507            Some("object")
12508        );
12509        assert!(matches!(
12510            tool.execution_mode,
12511            subc_protocol::manifest::ExecutionMode::Pure
12512        ));
12513    }
12514
12515    #[tokio::test]
12516    async fn catalog_list_sends_an_unfiltered_channel_zero_request() {
12517        let shared = Arc::new(reader_skew_tests::legacy_shared(
12518            PathBuf::from("/tmp/does-not-exist"),
12519            ConsumerOptions::default(),
12520        ));
12521        let (writer, mut rx) = mpsc::channel(1);
12522        shared.lock_inner().writer = Some(writer);
12523        shared.lock_inner().daemon_ver = "0.39.0".into();
12524
12525        let consumer = SubcConsumer {
12526            shared: Arc::clone(&shared),
12527        };
12528        let request = tokio::spawn(async move { consumer.catalog_list().await });
12529        let command = rx
12530            .recv()
12531            .await
12532            .expect("catalog.list must queue a channel-0 request");
12533        assert_eq!(command.frame.header.channel, 0);
12534        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
12535        assert_eq!(body["op"], "catalog.list");
12536        assert!(
12537            body.get("module_id").is_none(),
12538            "catalog.list must request the complete catalog without a module filter"
12539        );
12540
12541        let response = serde_json::to_vec(&ClientControlResponse::CatalogList {
12542            generation: 9,
12543            modules: Vec::new(),
12544            subc_ops: vec!["catalog.list".to_string()],
12545        })
12546        .unwrap();
12547        assert!(
12548            dispatch_frame(
12549                &shared,
12550                1,
12551                response_frame(0, 0, command.frame.header.corr, response),
12552            )
12553            .await
12554        );
12555        let catalog = request.await.unwrap().unwrap();
12556        assert_eq!(catalog.generation, 9);
12557        assert!(catalog.modules.is_empty());
12558    }
12559
12560    #[tokio::test]
12561    async fn spawn_snapshot_sends_a_channel_zero_request_and_returns_the_snapshot() {
12562        let shared = Arc::new(reader_skew_tests::legacy_shared(
12563            PathBuf::from("/tmp/does-not-exist"),
12564            ConsumerOptions::default(),
12565        ));
12566        let (writer, mut rx) = mpsc::channel(1);
12567        shared.lock_inner().writer = Some(writer);
12568        shared.lock_inner().daemon_ver = "0.39.0".into();
12569
12570        let consumer = SubcConsumer {
12571            shared: Arc::clone(&shared),
12572        };
12573        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
12574        let command = rx
12575            .recv()
12576            .await
12577            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
12578        assert_eq!(command.frame.header.channel, 0);
12579        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
12580        assert_eq!(body["op"], "supervisor.spawn_snapshot");
12581
12582        let snapshot = SpawnSnapshot {
12583            cursor: SpawnCursor {
12584                daemon_incarnation: "incarnation-a".to_string(),
12585                seq: 41,
12586            },
12587            ring_bound: 256,
12588            live: vec![LiveSpawn {
12589                module_id: "participant".to_string(),
12590                spawn_generation: 3,
12591                pid: 4242,
12592                spawned_at_ms: 1_700_000_000_000,
12593            }],
12594        };
12595        let response = serde_json::to_vec(&ClientControlResponse::SupervisorSpawnSnapshot {
12596            snapshot: snapshot.clone(),
12597        })
12598        .unwrap();
12599        assert!(
12600            dispatch_frame(
12601                &shared,
12602                1,
12603                response_frame(0, 0, command.frame.header.corr, response),
12604            )
12605            .await
12606        );
12607        assert_eq!(request.await.unwrap().unwrap(), snapshot);
12608    }
12609
12610    #[tokio::test]
12611    async fn spawn_snapshot_refusal_keeps_the_daemon_code() {
12612        let shared = Arc::new(reader_skew_tests::legacy_shared(
12613            PathBuf::from("/tmp/does-not-exist"),
12614            ConsumerOptions::default(),
12615        ));
12616        let (writer, mut rx) = mpsc::channel(1);
12617        shared.lock_inner().writer = Some(writer);
12618        shared.lock_inner().daemon_ver = "0.39.0".into();
12619
12620        let consumer = SubcConsumer {
12621            shared: Arc::clone(&shared),
12622        };
12623        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
12624        let command = rx
12625            .recv()
12626            .await
12627            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
12628        let refusal = serde_json::to_vec(&ErrorBody {
12629            code: "op_not_permitted".to_string(),
12630            message: "refused by the test".to_string(),
12631            detail: None,
12632        })
12633        .unwrap();
12634        let frame = Frame::build(
12635            FrameType::Error,
12636            Flags::new(false, Priority::Interactive, false),
12637            0,
12638            0,
12639            command.frame.header.corr,
12640            refusal,
12641        )
12642        .unwrap();
12643        assert!(dispatch_frame(&shared, 1, frame).await);
12644        let error = request.await.unwrap().unwrap_err();
12645        assert_eq!(error.code(), Some("op_not_permitted"));
12646    }
12647
12648    fn spawn_cursor(seq: u64) -> SpawnCursor {
12649        SpawnCursor {
12650            daemon_incarnation: "incarnation-a".to_string(),
12651            seq,
12652        }
12653    }
12654
12655    fn spawn_event(seq: u64, kind: SpawnEventKind, generation: u64) -> SpawnEvent {
12656        SpawnEvent {
12657            cursor: spawn_cursor(seq),
12658            kind,
12659            module_id: "participant".to_string(),
12660            spawn_generation: generation,
12661            pid: 4242,
12662            exit_code: (kind == SpawnEventKind::Exited).then_some(0),
12663            exit_signal: None,
12664        }
12665    }
12666
12667    fn channel_zero_frame(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
12668        Frame::build(
12669            ty,
12670            Flags::new(false, Priority::Interactive, false),
12671            0,
12672            0,
12673            corr,
12674            body,
12675        )
12676        .unwrap()
12677    }
12678
12679    fn spawn_error_frame(corr: u64, code: &str, detail: serde_json::Value) -> Frame {
12680        channel_zero_frame(
12681            FrameType::Error,
12682            corr,
12683            serde_json::to_vec(&ErrorBody {
12684                code: code.to_string(),
12685                message: "sent by the test".to_string(),
12686                detail: Some(detail),
12687            })
12688            .unwrap(),
12689        )
12690    }
12691
12692    /// A consumer over the writer-test harness, subscribed from `since`, with the
12693    /// request frame it queued.
12694    async fn spawn_subscribed(
12695        since: Option<SpawnCursor>,
12696    ) -> (
12697        Arc<Shared>,
12698        mpsc::Receiver<WriteCommand>,
12699        SpawnSubscription,
12700        Frame,
12701    ) {
12702        let shared = writer_test_shared();
12703        let (writer, mut rx) = mpsc::channel(8);
12704        shared.lock_inner().writer = Some(writer);
12705        shared.lock_inner().daemon_ver = "0.39.0".into();
12706        let consumer = SubcConsumer {
12707            shared: Arc::clone(&shared),
12708        };
12709        let subscription = consumer
12710            .spawn_subscribe(since)
12711            .await
12712            .expect("supervisor.spawn_subscribe must be sent");
12713        std::mem::forget(consumer);
12714        let command = rx
12715            .recv()
12716            .await
12717            .expect("supervisor.spawn_subscribe must queue a channel-0 request");
12718        (shared, rx, subscription, command.frame)
12719    }
12720
12721    #[tokio::test]
12722    async fn spawn_subscribe_sends_its_cursor_on_channel_zero_and_yields_events_until_stream_end() {
12723        let (shared, _rx, mut subscription, request) =
12724            spawn_subscribed(Some(spawn_cursor(7))).await;
12725        assert_eq!(request.header.channel, 0);
12726        assert_eq!(request.header.ty, FrameType::Request);
12727        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
12728        assert_eq!(
12729            body,
12730            serde_json::json!({
12731                "op": "supervisor.spawn_subscribe",
12732                "since": {"daemon_incarnation": "incarnation-a", "seq": 7},
12733            })
12734        );
12735
12736        let corr = request.header.corr;
12737        let events = [
12738            spawn_event(8, SpawnEventKind::Exited, 3),
12739            spawn_event(9, SpawnEventKind::Spawned, 4),
12740        ];
12741        for event in &events {
12742            let body = serde_json::to_vec(event).unwrap();
12743            assert!(
12744                dispatch_frame(
12745                    &shared,
12746                    1,
12747                    channel_zero_frame(FrameType::StreamData, corr, body)
12748                )
12749                .await
12750            );
12751        }
12752        assert!(
12753            dispatch_frame(
12754                &shared,
12755                1,
12756                channel_zero_frame(FrameType::StreamEnd, corr, Vec::new())
12757            )
12758            .await
12759        );
12760        assert_eq!(subscription.next().await.unwrap(), Some(events[0].clone()));
12761        assert_eq!(subscription.next().await.unwrap(), Some(events[1].clone()));
12762        assert_eq!(subscription.next().await.unwrap(), None);
12763        assert_eq!(
12764            subscription.next().await.unwrap(),
12765            None,
12766            "a finished stream stays finished"
12767        );
12768    }
12769
12770    #[tokio::test]
12771    async fn spawn_subscribe_without_a_cursor_omits_since() {
12772        let (_shared, _rx, _subscription, request) = spawn_subscribed(None).await;
12773        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
12774        assert_eq!(
12775            body,
12776            serde_json::json!({"op": "supervisor.spawn_subscribe"})
12777        );
12778    }
12779
12780    #[tokio::test]
12781    async fn spawn_cursor_refusals_surface_as_coded_errors_with_their_detail() {
12782        let (shared, _rx, mut subscription, request) =
12783            spawn_subscribed(Some(spawn_cursor(7))).await;
12784        let frame = spawn_error_frame(
12785            request.header.corr,
12786            "spawn_cursor_incarnation_mismatch",
12787            serde_json::json!({"current_daemon_incarnation": "incarnation-b"}),
12788        );
12789        assert!(dispatch_frame(&shared, 1, frame).await);
12790        let error = subscription.next().await.unwrap_err();
12791        assert_eq!(error.code(), Some("spawn_cursor_incarnation_mismatch"));
12792        let SpawnStreamError::CursorIncarnationMismatch {
12793            current_daemon_incarnation,
12794            body,
12795        } = &error
12796        else {
12797            panic!("expected the incarnation refusal, got {error:?}");
12798        };
12799        assert_eq!(current_daemon_incarnation, "incarnation-b");
12800        assert_eq!(body.code, "spawn_cursor_incarnation_mismatch");
12801        assert_eq!(subscription.next().await.unwrap(), None);
12802
12803        let (shared, _rx, mut subscription, request) =
12804            spawn_subscribed(Some(spawn_cursor(1))).await;
12805        let frame = spawn_error_frame(
12806            request.header.corr,
12807            "spawn_cursor_too_old",
12808            serde_json::json!({"oldest_retained_cursor": spawn_cursor(90)}),
12809        );
12810        assert!(dispatch_frame(&shared, 1, frame).await);
12811        let error = subscription.next().await.unwrap_err();
12812        assert_eq!(error.code(), Some("spawn_cursor_too_old"));
12813        let SpawnStreamError::CursorTooOld {
12814            oldest_retained_cursor,
12815            ..
12816        } = &error
12817        else {
12818            panic!("expected the too-old refusal, got {error:?}");
12819        };
12820        assert_eq!(oldest_retained_cursor, &spawn_cursor(90));
12821    }
12822
12823    #[tokio::test]
12824    async fn a_lagged_spawn_stream_yields_its_queued_events_then_the_lag_error() {
12825        let (shared, _rx, mut subscription, request) =
12826            spawn_subscribed(Some(spawn_cursor(7))).await;
12827        let corr = request.header.corr;
12828        let queued = spawn_event(8, SpawnEventKind::Exited, 3);
12829        assert!(
12830            dispatch_frame(
12831                &shared,
12832                1,
12833                channel_zero_frame(
12834                    FrameType::StreamData,
12835                    corr,
12836                    serde_json::to_vec(&queued).unwrap()
12837                ),
12838            )
12839            .await
12840        );
12841        let frame = spawn_error_frame(
12842            corr,
12843            "spawn_subscriber_lagged",
12844            serde_json::json!({"first_undelivered_cursor": spawn_cursor(9)}),
12845        );
12846        assert!(dispatch_frame(&shared, 1, frame).await);
12847        assert_eq!(subscription.next().await.unwrap(), Some(queued));
12848        let error = subscription.next().await.unwrap_err();
12849        assert_eq!(error.code(), Some("spawn_subscriber_lagged"));
12850        let SpawnStreamError::SubscriberLagged {
12851            first_undelivered_cursor,
12852            ..
12853        } = &error
12854        else {
12855            panic!("expected the lag error, got {error:?}");
12856        };
12857        assert_eq!(first_undelivered_cursor, &spawn_cursor(9));
12858    }
12859
12860    #[tokio::test]
12861    async fn dropping_a_spawn_subscription_sends_a_channel_zero_cancel_for_its_corr() {
12862        let (_shared, mut rx, subscription, request) =
12863            spawn_subscribed(Some(spawn_cursor(7))).await;
12864        drop(subscription);
12865        let cancel = tokio::time::timeout(Duration::from_secs(1), rx.recv())
12866            .await
12867            .expect("dropping the subscription must queue a Cancel")
12868            .expect("the writer stays open");
12869        assert_eq!(cancel.frame.header.ty, FrameType::Cancel);
12870        assert_eq!(cancel.frame.header.channel, 0);
12871        assert_eq!(cancel.frame.header.corr, request.header.corr);
12872    }
12873
12874    #[tokio::test]
12875    async fn reconnect_completion_between_wait_decision_and_registration_wakes_caller() {
12876        let shared = Arc::new(reader_skew_tests::legacy_shared(
12877            PathBuf::from("/tmp/subc-client-rs-reconnect-wakeup"),
12878            ConsumerOptions::default(),
12879        ));
12880        let (sender, _receiver) = mpsc::channel(EGRESS_BUFFER);
12881        {
12882            let mut inner = shared.lock_inner();
12883            inner.reconnect = ReconnectState::Inline {
12884                generation: inner.generation,
12885            };
12886        }
12887        let completing = Arc::clone(&shared);
12888        *shared.before_wait.lock().unwrap() = Some(Box::new(move || {
12889            completing.lock_inner().writer = Some(sender);
12890            completing.lock_inner().daemon_ver = "0.39.0".into();
12891            completing.notify.notify_waiters();
12892        }));
12893
12894        let result = shared
12895            .ensure_connected_for_call(Instant::now() + Duration::from_millis(30))
12896            .await;
12897        assert!(
12898            result.is_ok(),
12899            "connected caller should not time out: {result:?}"
12900        );
12901        assert!(shared.before_wait.lock().unwrap().is_none());
12902    }
12903
12904    #[tokio::test]
12905    async fn catalog_list_deadline_is_not_sent_when_reconnection_stays_down() {
12906        let shared = Arc::new(reader_skew_tests::legacy_shared(
12907            PathBuf::from("/tmp/subc-client-rs-catalog-list-unavailable"),
12908            ConsumerOptions {
12909                call_timeout: Duration::from_millis(25),
12910                reconnect_backoff: RetryBackoff {
12911                    base: Duration::from_millis(1),
12912                    cap: Duration::from_millis(1),
12913                    max_attempts: 100,
12914                },
12915                ..ConsumerOptions::default()
12916            },
12917        ));
12918        let consumer = SubcConsumer { shared };
12919        let result = tokio::time::timeout(Duration::from_millis(250), consumer.catalog_list())
12920            .await
12921            .expect("catalog.list must finish at its configured deadline")
12922            .unwrap_err();
12923        assert!(matches!(result, CallError::NotSent(_)));
12924    }
12925
12926    fn consumer_with_malformed_connection_file(
12927    ) -> (cortexkit_test_support::ScratchDir, SubcConsumer) {
12928        let temp = cortexkit_test_support::ScratchDir::new("consumer-malformed-connection");
12929        let path = temp.path().join("connection.json");
12930        std::fs::write(&path, b"not JSON").unwrap();
12931        #[cfg(unix)]
12932        {
12933            use std::os::unix::fs::PermissionsExt;
12934            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
12935        }
12936        let shared = Arc::new(reader_skew_tests::legacy_shared(
12937            path,
12938            ConsumerOptions {
12939                call_timeout: Duration::from_millis(100),
12940                reconnect_backoff: RetryBackoff {
12941                    base: Duration::from_millis(20),
12942                    cap: Duration::from_millis(40),
12943                    max_attempts: 6,
12944                },
12945                ..ConsumerOptions::default()
12946            },
12947        ));
12948        (temp, SubcConsumer { shared })
12949    }
12950
12951    // A malformed file fails synchronously. Keep the clock running so an unpaced
12952    // retry loop reaches its deadline instead of hanging a paused-time runtime.
12953    #[tokio::test]
12954    async fn catalog_list_backs_off_after_malformed_connection_file_and_close_cancels_it() {
12955        let (_temp, consumer) = consumer_with_malformed_connection_file();
12956        let call = consumer.catalog_list();
12957        tokio::pin!(call);
12958        assert_pending(call.as_mut()).await;
12959        consumer.close().await;
12960        let err = call.await.unwrap_err();
12961        assert!(matches!(err, CallError::NotSent(_)));
12962        assert!(err.to_string().contains("consumer closed"));
12963    }
12964
12965    #[tokio::test]
12966    async fn spawn_snapshot_backs_off_after_malformed_connection_file_and_close_cancels_it() {
12967        let (_temp, consumer) = consumer_with_malformed_connection_file();
12968        let call = consumer.spawn_snapshot();
12969        tokio::pin!(call);
12970        assert_pending(call.as_mut()).await;
12971        consumer.close().await;
12972        let err = call.await.unwrap_err();
12973        assert!(matches!(err, CallError::NotSent(_)));
12974        assert!(err.to_string().contains("consumer closed"));
12975    }
12976}
12977
12978#[cfg(test)]
12979mod launch_nonce_redaction_tests {
12980    use super::*;
12981
12982    const NONCE: &str = "nonce-f00dfeed1234abcd";
12983
12984    #[test]
12985    fn option_types_and_route_keys_never_print_the_nonce() {
12986        let identity = ConsumerIdentity {
12987            module_id: "wernicke".to_string(),
12988            launch_nonce: NONCE.to_string(),
12989        };
12990        let call = CallOptions {
12991            consumer_identity: Some(identity.clone()),
12992            ..CallOptions::default()
12993        };
12994        let key = ConsumerIdentityKey::from(&identity);
12995        for printed in [format!("{call:?}"), format!("{key:?}")] {
12996            assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
12997        }
12998    }
12999}