Skip to main content

subc_client_rs/
lib.rs

1#![forbid(unsafe_code)]
2
3pub mod activity;
4mod agent_commands;
5pub mod config;
6mod control_ops;
7mod live_upgrade;
8pub use agent_commands::AgentCommandsError;
9#[cfg(any(test, feature = "test-support"))]
10use live_upgrade::connection_serve_future_with_options;
11use live_upgrade::register_connection;
12#[cfg(test)]
13use live_upgrade::registration_channel_exit_code;
14pub use live_upgrade::ResumeScopeSync;
15pub use subc_protocol::session::{AgentCommandFinished, AgentCommandRoot};
16pub mod consumer;
17mod operator_app;
18pub mod policy_cache;
19#[cfg(any(test, feature = "test-support"))]
20mod stand_in;
21#[cfg(feature = "test-support")]
22pub mod test_support;
23pub use activity::*;
24pub use consumer::{
25    is_retryable_route_open_code, AppOpenError, CallError, CallOptions, CallReply, CancelHandle,
26    CancelOutcome, CatalogList, CatalogSubscription, CloseRouteOptions, ConfigApplyResponse,
27    ConfigEdit, ConfigEditAction, ConfigFileError, ConfigFileErrorLayer, ConfigModule,
28    ConfigModulesResponse, ConfigPlanRefusal, ConfigPlanView, ConfigSchemaResponse,
29    ConfigSettingsLayer, ConfigShowResponse, ConfigStatus, ConfigSubscription, ConfigThrough,
30    ConfigWatchEvent, ConnectionFacts, ConnectionState, ConsumerCapabilityError, ConsumerError,
31    ConsumerOptions, ControlPush, CorrelationId, Digest, HealthProbeResponse, NotSentCause,
32    OutcomeUnknownCause, PendingReply, PushEvent, RequestBody, RequestReservation, RetryBackoff,
33    ReverseRequestContext, ReverseRequestError, ReverseRequestRegistrationError,
34    ReverseRequestRegistry, RouteCloseDisposition, RouteCloseReason, RouteEndReason,
35    RouteOpenTarget, RouteOpenTargetKind, RoutePollResult, ScopeBindProofRefusal, ScopeSelector,
36    ServerDescription, SpawnStreamError, SpawnSubscription, StderrTailResponse, SubcConsumer,
37    SubscribeOptions, Subscription, SubscriptionClosed, SubscriptionEnd, SupervisorAck,
38    SupervisorEntry, SupervisorHealthResponse, SupervisorListResponse,
39    SupervisorProvenanceResponse, ACCEPTED_CLOSE_REASONS, DEFAULT_CALL_TIMEOUT,
40    DEFAULT_LIVENESS_PROBE_WINDOW, DEFAULT_ROUTE_RETRY_DEADLINE, SPAWN_CURSOR_INCARNATION_MISMATCH,
41    SPAWN_CURSOR_TOO_OLD, SPAWN_SUBSCRIBER_LAGGED,
42};
43pub use operator_app::{operator_app_candidates, operator_app_path, OperatorAppPathError};
44pub use policy_cache::{
45    PolicyResolveError, PolicyResolver, PolicyResolverConfig, PolicyResolverFootprint,
46    PolicyVerdict, ProjectRef, Subject, DEFAULT_POLICY_RESOLVER_MODULE_ID,
47};
48pub use subc_control::{AppOpenReply, AppOpenStatus, CatalogOrigin, CatalogWatchResponse};
49pub use subc_control::{
50    ScopeRef, ScopeWatchEvent, ScopeWatchPush, ScopeWatchResponse, ScopeWatchSelector,
51    ScopeWatchState, ScopeWatchStatus,
52};
53
54mod module_subscription;
55pub use module_subscription::ScopeSubscription;
56
57use std::{
58    collections::{BTreeMap, HashMap, VecDeque},
59    env,
60    error::Error,
61    ffi::OsString,
62    fmt,
63    future::Future,
64    io,
65    panic::{catch_unwind, AssertUnwindSafe},
66    path::{Path, PathBuf},
67    pin::Pin,
68    sync::{
69        atomic::{AtomicBool, AtomicU64, Ordering},
70        Arc, Mutex,
71    },
72    time::{Duration, SystemTime, UNIX_EPOCH},
73};
74
75pub use async_trait::async_trait;
76pub use subc_control::{CatalogEntry, ConsumerIdentity};
77mod scope_served_by;
78pub use scope_served_by::{ScopeServedByAnswer, ScopeServedByReply};
79pub mod registration;
80mod route_authorize;
81pub use route_authorize::{
82    RouteAuthorizeExpected, RouteAuthorizeOutcome, RouteAuthorizeResponse, RouteAuthorizeScope,
83};
84mod request_pools;
85pub use registration::ClaimError;
86use request_pools::{wait_for_permit, DispatchPools, PermitWaitOutcome, WaitingRequest};
87pub use request_pools::{RequestClass, RequestPool, RequestPoolSnapshot, RequestPools};
88/// The one launch-nonce reader for a module process: `launch_nonce()` reads
89/// the inherited Unix descriptor, the Windows named pipe, or, when neither is
90/// named, the `SUBC_LAUNCH_NONCE` environment copy once and caches it. The SDK's
91/// HELLO and route opens go through it too; a module's own readers must as well.
92/// Read before spawning children so they cannot inherit an unread Unix pipe
93/// containing the module's credential.
94pub use subc_os::launch_nonce;
95use subc_protocol::{
96    call_mode::derive_call_mode,
97    error_codes,
98    manifest::ModuleManifest,
99    scope::{
100        ScopeEnd, ScopeEndResult, ScopeEnded, ScopeRecord, ScopeRecordResult, ScopeStamp,
101        ScopeStatus, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP, SCOPE_SYNC_OP,
102    },
103    session::{
104        ModuleControlCommand, ModuleControlRequest, ModuleControlRequestFromModule,
105        ModuleControlResponse, ModuleControlResponseToModule, OperatorConfirmKind,
106        OperatorConfirmReply, OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK,
107        MODULE_TO_SUBC_OP_CATALOG_UPDATE, MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS,
108    },
109    BindIdentity, ErrorBody, Flags, Frame, FrameBuildError, FrameType, ModuleHelloAckBody,
110    ModuleHelloBody, Principal, Priority, RouteTarget, PROTOCOL_VERSION, SUBC_MODULE_ID_ENV,
111};
112pub use subc_protocol::{
113    call_mode::{CallMode, CALL_MODES_CAPABILITY},
114    manifest::{
115        build_provenance, CapabilityDeclarations, CapabilityNeed, CapabilityRequirement,
116        ExecutionMode, LaunchNonceSource, ManifestProvenance, ProvenanceFormError, ProviderRole,
117        Tool, PROVENANCE_SENTINELS,
118    },
119    session::{HealthReport, HealthStatus},
120    AdmissionClass, MachineId, SUBC_PROTOCOL_CRATE_VERSION,
121};
122pub use subc_transport::connection_file::{
123    discover, discovery_candidates, Discovered, DiscoveryError,
124};
125
126use subc_transport::{
127    authenticate_client, connection_file, read_frame, write_frame, AuthError, ConnectionFileError,
128    FrameIoError,
129};
130use tokio::{
131    io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufWriter},
132    net::TcpStream,
133    sync::{mpsc, oneshot},
134    time::{timeout, timeout_at, Instant},
135};
136use tokio_util::{
137    sync::{CancellationToken, WaitForCancellationFuture},
138    task::TaskTracker,
139};
140
141const AUTH_DEADLINE: Duration = Duration::from_secs(2);
142const CATALOG_UPDATE_TIMEOUT: Duration = Duration::from_secs(10);
143const OPERATOR_CONFIRM_TIMEOUT: Duration = Duration::from_secs(290);
144const OPERATOR_CONFIRM_OP: &str = "operator.confirm";
145const EGRESS_BUFFER: usize = 64;
146const HANDLER_TASK_CAPACITY: usize = 64;
147/// A full dispatcher is normal during a burst. Report dispatch impairment only
148/// once a data request has waited more than two seconds for a handler slot.
149const DISPATCH_SATURATION_WAIT: Duration = Duration::from_secs(2);
150const HELLO_CORR: u64 = 1;
151const DEFAULT_WRITER_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
152/// When a module's daemon connection ends (GOODBYE, EOF, reset, or module stop),
153/// how long the serve loop waits for each `on_draining` hook it already
154/// spawned to start running before it cancels requests and calls
155/// `on_connection_end`. The wait is only for the hook's first step, which is
156/// normally immediate; the bound matters because the daemon kills a module
157/// that has not exited within its stop timeout after GOODBYE, and a hook that
158/// blocks its thread must not hold the shutdown up that long.
159const DRAINING_HOOK_START_LIMIT: Duration = Duration::from_secs(2);
160static NEXT_MODULE_CONNECTION_TOKEN: AtomicU64 = AtomicU64::new(1);
161/// The connection token of a [`RouteHandle::detached`] handle. Module
162/// connection tokens start at 1 (above) and a consumer's generation starts at
163/// 1 and only grows, so no live connection ever has this token.
164const DETACHED_CONNECTION_TOKEN: u64 = 0;
165
166type RequestKey = (u16, u32, u64);
167type InFlight = Arc<Mutex<HashMap<RequestKey, CancellationToken>>>;
168
169/// Immutable identity of one route binding on one live connection.
170///
171/// Only `channel` and `epoch` are serialized. The private connection token prevents
172/// work retained from an earlier connection from acting on a later connection that
173/// happens to reuse the same wire pair.
174#[derive(Clone, Copy)]
175pub struct RouteHandle {
176    pub channel: u16,
177    pub epoch: u32,
178    connection_token: u64,
179    reverse_request_registry_id: u64,
180}
181
182impl RouteHandle {
183    /// A handle for `channel` and `epoch` that belongs to no connection, for
184    /// building values in tests, such as a [`RouteBindRequest`] passed to a
185    /// module's own `on_bind`. It is never bound to a connection and cannot
186    /// become one.
187    ///
188    /// Every operation that would reach a connection fails with the error
189    /// it returns for a closed or stale route, and sends nothing:
190    /// [`ModuleHandle::push`] returns [`SubcModuleError::StaleRouteHandle`];
191    /// [`SubcConsumer::request`], [`SubcConsumer::subscribe_route`],
192    /// [`SubcConsumer::poll_route`], [`SubcConsumer::push_events`] and
193    /// [`SubcConsumer::close_handle`] return [`CallError::StaleRouteHandle`];
194    /// [`Self::on_request`] and [`Self::on_request_fallible`] return
195    /// [`ReverseRequestRegistrationError::NotConsumerRoute`].
196    pub fn detached(channel: u16, epoch: u32) -> Self {
197        Self::new(channel, epoch, DETACHED_CONNECTION_TOKEN)
198    }
199
200    pub(crate) fn new(channel: u16, epoch: u32, connection_token: u64) -> Self {
201        Self {
202            channel,
203            epoch,
204            connection_token,
205            reverse_request_registry_id: 0,
206        }
207    }
208
209    pub(crate) fn new_consumer(
210        channel: u16,
211        epoch: u32,
212        connection_token: u64,
213        reverse_requests: ReverseRequestRegistry,
214    ) -> Self {
215        reverse_requests.seal();
216        Self {
217            channel,
218            epoch,
219            connection_token,
220            reverse_request_registry_id: consumer::install_reverse_request_registry(
221                reverse_requests,
222            ),
223        }
224    }
225
226    pub(crate) fn connection_token(self) -> u64 {
227        self.connection_token
228    }
229
230    pub fn on_request<F, Fut>(
231        &self,
232        method_family: impl Into<String>,
233        handler: F,
234    ) -> Result<(), ReverseRequestRegistrationError>
235    where
236        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
237        Fut: Future<Output = Vec<u8>> + Send + 'static,
238    {
239        consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
240            .on_request(method_family, handler)
241    }
242
243    pub fn on_request_fallible<F, Fut>(
244        &self,
245        method_family: impl Into<String>,
246        handler: F,
247    ) -> Result<(), ReverseRequestRegistrationError>
248    where
249        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
250        Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
251    {
252        consumer::route_reverse_request_registry(self.reverse_request_registry_id)?
253            .on_request_fallible(method_family, handler)
254    }
255
256    pub(crate) fn reverse_request_registry_id(self) -> u64 {
257        self.reverse_request_registry_id
258    }
259}
260
261impl PartialEq for RouteHandle {
262    fn eq(&self, other: &Self) -> bool {
263        self.channel == other.channel
264            && self.epoch == other.epoch
265            && self.connection_token == other.connection_token
266    }
267}
268
269impl Eq for RouteHandle {}
270
271impl std::hash::Hash for RouteHandle {
272    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
273        std::hash::Hash::hash(&self.channel, state);
274        std::hash::Hash::hash(&self.epoch, state);
275        std::hash::Hash::hash(&self.connection_token, state);
276    }
277}
278
279impl fmt::Debug for RouteHandle {
280    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281        f.debug_struct("RouteHandle")
282            .field("channel", &self.channel)
283            .field("epoch", &self.epoch)
284            .finish_non_exhaustive()
285    }
286}
287/// A single read-lock snapshot of bound and pending project routes.
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub struct LiveRootsSnapshot {
290    pub roots: Vec<subc_protocol::session::LiveRoot>,
291    pub unknown_root_bindings: u64,
292    pub total_bindings: u64,
293}
294
295/// The daemon's answer to an accepted [`ModuleHandle::scope_sync`].
296///
297/// A refusal of the whole sync is never a reply: it is
298/// [`ScopeCallError::Refused`], and the daemon changed nothing.
299#[derive(Debug, Clone, PartialEq, Eq)]
300#[non_exhaustive]
301pub struct ScopeSyncReply {
302    /// The generation the daemon accepted, echoed from the request.
303    pub generation: u64,
304    /// One result per record sent, in request order. A record refused on its
305    /// own merits is here with outcome `refused` and its code; the rest of the
306    /// sync still applied.
307    pub results: Vec<ScopeRecordResult>,
308    /// Scopes of this owner that the sync ended, by leaving them out, sending
309    /// a higher epoch for the same ref, or sweeping their expired deadlines.
310    pub ended: Vec<ScopeEnded>,
311}
312
313/// The daemon's answer to an accepted [`ModuleHandle::scope_apply`].
314///
315/// A refusal of the whole delta is [`ScopeCallError::Refused`]; nothing changed.
316#[derive(Debug, Clone, PartialEq, Eq)]
317#[non_exhaustive]
318pub struct ScopeApplyReply {
319    /// The generation the daemon accepted, echoed from the request.
320    pub generation: u64,
321    /// One result per upsert, in request order, including per-record refusals.
322    pub results: Vec<ScopeRecordResult>,
323    /// One result per requested end, in request order. A ref not live at the
324    /// named epoch has outcome `not_live`, which does not refuse the delta.
325    pub end_results: Vec<ScopeEndResult>,
326    /// Scopes this call ended, once each, through explicit ends, higher-epoch
327    /// upserts, or the calling owner's expiry sweep.
328    pub ended: Vec<ScopeEnded>,
329}
330
331/// The daemon's answer to [`ModuleHandle::scope_describe`] about one
332/// `(owner, ref)`.
333#[derive(Debug, Clone, PartialEq, Eq)]
334#[non_exhaustive]
335pub struct ScopeDescribeReply {
336    pub status: ScopeStatus,
337    /// The live epoch, or for `ended` the most recent epoch that ended.
338    pub scope_epoch: Option<u64>,
339    /// Identifies the daemon process that answered. A different value means
340    /// the daemon restarted, and owners re-sync after a restart.
341    pub daemon_incarnation: String,
342    /// Whether the owner has synced since this daemon incarnation started.
343    pub owner_synced: bool,
344    /// Whether the owner is a module in the daemon's supervised roster.
345    pub owner_configured: bool,
346    /// The stamped fields, present only when `status` is `live`. The daemon
347    /// includes `attributes.on_behalf_of_agent` only when this module's manifest
348    /// provides `scope-on-behalf-of/v1`; the field is attribution, never authority.
349    pub scope: Option<ScopeStamp>,
350}
351
352// The protocol's module-control enum predates the separately typed authorization
353// reply. Keep both wire types in the same correlation table and deadline path.
354#[derive(Debug, serde::Deserialize)]
355#[serde(untagged)]
356enum ModuleControlReply {
357    Control(Box<ModuleControlResponseToModule>),
358    RouteAuthorize(RouteAuthorizeResponse),
359}
360
361impl ModuleControlReply {
362    fn control(self) -> Result<ModuleControlResponseToModule, CatalogUpdateError> {
363        match self {
364            Self::Control(reply) => Ok(*reply),
365            other => Err(CatalogUpdateError::Protocol(format!(
366                "unexpected module control response: {other:?}"
367            ))),
368        }
369    }
370}
371
372type CatalogUpdateReply = oneshot::Sender<Result<ModuleControlReply, CatalogUpdateError>>;
373type CatalogUpdateWaiter = oneshot::Receiver<Result<ModuleControlReply, CatalogUpdateError>>;
374type CatalogUpdateRequest = (u64, mpsc::Sender<Frame>, CatalogUpdateWaiter);
375type OperatorConfirmRequestWaiter = (u64, mpsc::Sender<Frame>, oneshot::Receiver<Frame>);
376
377/// Future returned by [`serve_with_handle`] that runs the module until GOODBYE or EOF.
378pub type ModuleServeFuture = Pin<Box<dyn Future<Output = Result<(), SubcModuleError>> + Send>>;
379
380#[derive(Clone)]
381struct RequestDispatcher {
382    in_flight: InFlight,
383    control_slots: Arc<tokio::sync::Semaphore>,
384    /// The connection's handler-slot pools, shared with its [`ModuleHandle`]
385    /// so the module can read their figures.
386    pools: Arc<DispatchPools>,
387    /// One receiver per `on_draining` hook spawned on this connection, resolved
388    /// once that hook has started running. The connection waits on them before
389    /// acting on its end, so a hook is always called before the GOODBYE that
390    /// follows its drain is handled.
391    draining_hooks: Arc<Mutex<Vec<oneshot::Receiver<()>>>>,
392    /// Set after the first channel-0 push this SDK could not decode has been
393    /// logged, so a daemon that repeats a newer push cannot flood the log.
394    undecodable_push_logged: Arc<AtomicBool>,
395    failure: Arc<Mutex<Option<SubcModuleError>>>,
396    failed: CancellationToken,
397    tasks: TaskTracker,
398    aborts: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
399    data_tasks: TaskTracker,
400    data_aborts: Arc<Mutex<Vec<tokio::task::AbortHandle>>>,
401    undelivered_replies: Arc<AtomicU64>,
402}
403
404impl RequestDispatcher {
405    /// A dispatcher with the default pool only, as a module that declares no
406    /// classifier gets.
407    #[cfg(test)]
408    fn new() -> Self {
409        Self::with_pools(Arc::new(DispatchPools::new(RequestPools::new())))
410    }
411
412    fn with_pools(pools: Arc<DispatchPools>) -> Self {
413        Self {
414            in_flight: Arc::new(Mutex::new(HashMap::new())),
415            control_slots: Arc::new(tokio::sync::Semaphore::new(16)),
416            pools,
417            draining_hooks: Arc::new(Mutex::new(Vec::new())),
418            undecodable_push_logged: Arc::new(AtomicBool::new(false)),
419            failure: Arc::new(Mutex::new(None)),
420            failed: CancellationToken::new(),
421            tasks: TaskTracker::new(),
422            aborts: Arc::new(Mutex::new(Vec::new())),
423            data_tasks: TaskTracker::new(),
424            data_aborts: Arc::new(Mutex::new(Vec::new())),
425            undelivered_replies: Arc::new(AtomicU64::new(0)),
426        }
427    }
428
429    fn fail(&self, error: SubcModuleError) {
430        let mut failure = self.failure.lock().unwrap_or_else(|e| e.into_inner());
431        if failure.is_none() {
432            *failure = Some(error);
433        }
434        self.failed.cancel();
435    }
436
437    fn take_failure(&self) -> Option<SubcModuleError> {
438        self.failure
439            .lock()
440            .unwrap_or_else(|e| e.into_inner())
441            .take()
442    }
443
444    fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
445        let task = self.tasks.spawn(future);
446        let mut aborts = self.aborts.lock().unwrap_or_else(|e| e.into_inner());
447        aborts.retain(|task| !task.is_finished());
448        aborts.push(task.abort_handle());
449    }
450
451    fn abort_all(&self) {
452        live_upgrade::abort_tasks(&self.aborts);
453        live_upgrade::abort_tasks(&self.data_aborts);
454    }
455
456    fn fold_health(&self, mut report: HealthReport) -> HealthReport {
457        if let Some(saturation) = self.pools.saturation() {
458            if report.status == HealthStatus::Ok {
459                report.status = HealthStatus::Degraded;
460            }
461            report.detail = Some(match report.detail {
462                Some(detail) => format!("{saturation}; {detail}"),
463                None => saturation,
464            });
465        }
466        report
467    }
468
469    /// Wait, within [`DRAINING_HOOK_START_LIMIT`], until every `on_draining`
470    /// hook spawned on this connection has started. Only the start is awaited:
471    /// a hook may still be finishing its work after the connection has ended.
472    async fn wait_for_draining_hooks_to_start(&self) {
473        let started = std::mem::take(
474            &mut *self
475                .draining_hooks
476                .lock()
477                .unwrap_or_else(|poisoned| poisoned.into_inner()),
478        );
479        let deadline = tokio::time::Instant::now() + DRAINING_HOOK_START_LIMIT;
480        for hook in started {
481            // A dropped sender means the hook task ended (or panicked) before
482            // reporting; either way there is nothing left to wait for.
483            if tokio::time::timeout_at(deadline, hook).await.is_err() {
484                return;
485            }
486        }
487    }
488
489    /// Cancel every request still in flight and refuse ones still waiting for a
490    /// handler slot, as a route's GOODBYE does for that route's requests. Run
491    /// when the connection ends: each request task holds a sender to the egress
492    /// channel, so until they finish the writer never sees the channel close.
493    fn cancel_all(&self) {
494        self.pools.close();
495        let cancelled = match self.in_flight.lock() {
496            Ok(guard) => guard.values().cloned().collect::<Vec<_>>(),
497            Err(poisoned) => poisoned.into_inner().values().cloned().collect(),
498        };
499        for cancellation in cancelled {
500            cancellation.cancel();
501        }
502    }
503}
504
505/// Cloneable handle for module-originated control RPCs on channel 0.
506#[derive(Clone)]
507pub struct ModuleHandle {
508    generations: Arc<live_upgrade::Generations>,
509}
510
511/// A daemon `module.draining` notice, including whether requests still arrive.
512#[derive(Debug, Clone, PartialEq, Eq)]
513#[non_exhaustive]
514pub struct DrainNotice {
515    pub reason: RouteCloseReason,
516    pub deadline: SystemTime,
517    /// Admission is still open. Persist accepted work before answering it.
518    pub accepting: bool,
519}
520
521/// Why the daemon could not acknowledge `module.drain_ready`.
522#[derive(Debug)]
523#[non_exhaustive]
524pub enum DrainReadyError {
525    Unsupported,
526    Refused(Box<ErrorBody>),
527    ConnectionClosed,
528    Timeout,
529    Protocol(String),
530}
531
532impl fmt::Display for DrainReadyError {
533    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534        match self {
535            Self::Unsupported => f.write_str("daemon does not support accepting drains"),
536            Self::Refused(body) => {
537                write!(f, "drain ready refused: {} ({})", body.message, body.code)
538            }
539            Self::ConnectionClosed => {
540                f.write_str("connection closed before drain ready acknowledgement")
541            }
542            Self::Timeout => f.write_str("drain ready acknowledgement timed out"),
543            Self::Protocol(message) => write!(f, "invalid drain ready reply: {message}"),
544        }
545    }
546}
547
548impl std::error::Error for DrainReadyError {}
549
550impl ModuleHandle {
551    /// After an accepting drain notice, tell the daemon there is no long work
552    /// left. The daemon will close admission and begin restarting this module.
553    /// Nothing is sent if the daemon did not negotiate accepting drains.
554    pub async fn drain_ready(&self) -> Result<(), DrainReadyError> {
555        use subc_protocol::session::{ModuleDrainReady, ACCEPTING_DRAIN_CAPABILITY};
556
557        let shared = self.shared();
558        if !shared
559            .daemon_capabilities
560            .iter()
561            .any(|cap| cap == ACCEPTING_DRAIN_CAPABILITY)
562        {
563            return Err(DrainReadyError::Unsupported);
564        }
565        let body = serde_json::to_vec(&ModuleDrainReady::Ready {})
566            .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
567        let (corr, writer, rx) = {
568            let mut inner = shared.lock_inner();
569            if inner.closed {
570                return Err(DrainReadyError::ConnectionClosed);
571            }
572            let writer = inner
573                .writer
574                .clone()
575                .ok_or(DrainReadyError::ConnectionClosed)?;
576            let corr =
577                next_module_control_corr(&mut inner).ok_or(DrainReadyError::ConnectionClosed)?;
578            let (tx, rx) = oneshot::channel();
579            inner.pending_drain_ready.insert(corr, tx);
580            (corr, writer, rx)
581        };
582        struct Waiter<'a>(&'a ModuleHandleShared, u64);
583        impl Drop for Waiter<'_> {
584            fn drop(&mut self) {
585                self.0.lock_inner().pending_drain_ready.remove(&self.1);
586            }
587        }
588        let _waiter = Waiter(&shared, corr);
589        let frame = Frame::build_with_version(
590            shared.negotiated_ver,
591            FrameType::Request,
592            control_flags(),
593            0,
594            0,
595            corr,
596            body,
597        )
598        .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
599        let reply = timeout(CATALOG_UPDATE_TIMEOUT, async {
600            shared
601                .queue_request(&writer, frame)
602                .await
603                .map_err(|err| match err {
604                    CatalogUpdateError::Rejected(body) => DrainReadyError::Refused(Box::new(body)),
605                    _ => DrainReadyError::ConnectionClosed,
606                })?;
607            rx.await.map_err(|_| DrainReadyError::ConnectionClosed)
608        })
609        .await
610        .map_err(|_| DrainReadyError::Timeout)??;
611        match reply.header.ty {
612            FrameType::Response => {
613                serde_json::from_slice::<ModuleDrainReady>(&reply.body)
614                    .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
615                self.fence_consumer_dials();
616                Ok(())
617            }
618            FrameType::Error => {
619                let body = serde_json::from_slice(&reply.body)
620                    .map_err(|err| DrainReadyError::Protocol(err.to_string()))?;
621                Err(DrainReadyError::Refused(Box::new(body)))
622            }
623            ty => Err(DrainReadyError::Protocol(format!(
624                "unexpected terminal frame: {ty:?}"
625            ))),
626        }
627    }
628}
629
630struct ModuleHandleShared {
631    registration: registration::Session,
632    negotiated_ver: u8,
633    daemon_capabilities: Vec<String>,
634    supports_catalog_update: bool,
635    supports_role_declarations_update: bool,
636    supports_live_roots: bool,
637    supports_agent_commands: bool,
638    supports_scope_sync: bool,
639    supports_scope_apply: bool,
640    supports_scope_describe: bool,
641    supports_scope_watch: bool,
642    supports_route_authorize: bool,
643    supports_operator_confirm: bool,
644    supports_activity: bool,
645    connection_runtime: tokio::runtime::Handle,
646    connection_token: u64,
647    live_routes: Mutex<HashMap<u16, RouteHandle>>,
648    dropped_route_frames: AtomicU64,
649    close_token: CancellationToken,
650    upgrade_notice: CancellationToken,
651    /// The handler-slot pools this connection's dispatcher uses. Replaced once,
652    /// with the pools the module's handler declares, before serving starts.
653    dispatch_pools: Mutex<Arc<DispatchPools>>,
654    catalog_send: tokio::sync::Mutex<()>,
655    config: config::Session,
656    served_control_ops: std::sync::OnceLock<Vec<String>>,
657    inner: Mutex<ModuleHandleState>,
658}
659
660struct ModuleHandleState {
661    pending_control_streams: HashMap<u64, module_subscription::ControlStreamSender>,
662    pending_claim_calls: HashMap<u64, oneshot::Sender<Frame>>,
663    writer: Option<mpsc::Sender<Frame>>,
664    next_corr: Option<u64>,
665    pending_catalog_updates: HashMap<u64, CatalogUpdateReply>,
666    pending_operator_confirms: HashMap<u64, oneshot::Sender<Frame>>,
667    pending_activity_records: HashMap<u64, oneshot::Sender<Frame>>,
668    pending_scope_served_by: HashMap<u64, oneshot::Sender<Frame>>,
669    pending_config_calls: HashMap<u64, oneshot::Sender<Frame>>,
670    pending_agent_commands: HashMap<u64, oneshot::Sender<Frame>>,
671    pending_drain_ready: HashMap<u64, oneshot::Sender<Frame>>,
672    current_provides: Option<Vec<ProviderRole>>,
673    catalog_changes: VecDeque<CatalogChange>,
674    upgrade: live_upgrade::UpgradeState,
675    closed: bool,
676}
677
678struct CatalogChange {
679    corr: u64,
680    update: CatalogManifestChange,
681    outcome: Option<CatalogChangeOutcome>,
682}
683
684enum CatalogManifestChange {
685    Catalog {
686        provides: Vec<ProviderRole>,
687        capabilities: Option<CapabilityDeclarations>,
688        ready: Option<bool>,
689    },
690    RoleDeclarations(BTreeMap<String, serde_json::Map<String, serde_json::Value>>),
691}
692
693enum CatalogChangeOutcome {
694    AcceptedCatalog,
695    AcceptedRoleDeclarations,
696    Rejected,
697    Unknown,
698}
699
700struct CatalogUpdateGuard {
701    shared: Arc<ModuleHandleShared>,
702    corr: u64,
703}
704
705impl Drop for CatalogUpdateGuard {
706    fn drop(&mut self) {
707        self.shared.remove_pending_catalog_update(self.corr);
708    }
709}
710
711impl ModuleHandle {
712    fn new(
713        ack: &ModuleHelloAckBody,
714        writer: mpsc::Sender<Frame>,
715        connection_token: u64,
716        close_token: CancellationToken,
717        connection_runtime: tokio::runtime::Handle,
718    ) -> Self {
719        Self {
720            generations: Arc::new(live_upgrade::Generations::new(
721                ack,
722                Arc::new(ModuleHandleShared::new(
723                    ack,
724                    writer,
725                    connection_token,
726                    close_token,
727                    connection_runtime,
728                )),
729            )),
730        }
731    }
732}
733
734impl ModuleHandleShared {
735    fn new(
736        ack: &ModuleHelloAckBody,
737        writer: mpsc::Sender<Frame>,
738        connection_token: u64,
739        close_token: CancellationToken,
740        connection_runtime: tokio::runtime::Handle,
741    ) -> Self {
742        Self {
743            registration: registration::Session::default(),
744            negotiated_ver: ack.negotiated_ver,
745            daemon_capabilities: ack.subc_capabilities.clone(),
746            supports_catalog_update: ack
747                .subc_ops
748                .iter()
749                .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE),
750            supports_role_declarations_update: ack
751                .subc_ops
752                .iter()
753                .any(|op| op == MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS),
754            supports_live_roots: ack.subc_ops.iter().any(|op| op == "supervisor.live_roots"),
755            supports_agent_commands: ack
756                .subc_ops
757                .iter()
758                .any(|op| op == "supervisor.agent_commands"),
759            supports_scope_sync: ack.subc_ops.iter().any(|op| op == SCOPE_SYNC_OP),
760            supports_scope_apply: ack.subc_ops.iter().any(|op| op == SCOPE_APPLY_OP),
761            supports_scope_describe: ack.subc_ops.iter().any(|op| op == SCOPE_DESCRIBE_OP),
762            supports_scope_watch: ack
763                .subc_ops
764                .iter()
765                .any(|op| op == subc_control::ops::SCOPE_WATCH),
766            supports_route_authorize: ack
767                .subc_ops
768                .iter()
769                .any(|op| op == subc_protocol::scope::ROUTE_AUTHORIZE_OP),
770            supports_operator_confirm: ack.subc_ops.iter().any(|op| op == OPERATOR_CONFIRM_OP),
771            supports_activity: ack
772                .subc_capabilities
773                .iter()
774                .any(|capability| capability == ACTIVITY_LEDGER_CAPABILITY),
775            connection_runtime,
776            connection_token,
777            live_routes: Mutex::new(HashMap::new()),
778            dropped_route_frames: AtomicU64::new(0),
779            close_token,
780            upgrade_notice: CancellationToken::new(),
781            dispatch_pools: Mutex::new(Arc::new(DispatchPools::new(RequestPools::new()))),
782            catalog_send: tokio::sync::Mutex::new(()),
783            config: config::Session::default(),
784            served_control_ops: std::sync::OnceLock::new(),
785            inner: Mutex::new(ModuleHandleState {
786                pending_control_streams: HashMap::new(),
787                pending_claim_calls: HashMap::new(),
788                writer: Some(writer),
789                next_corr: Some(HELLO_CORR + 1),
790                pending_catalog_updates: HashMap::new(),
791                pending_operator_confirms: HashMap::new(),
792                pending_activity_records: HashMap::new(),
793                pending_scope_served_by: HashMap::new(),
794                pending_config_calls: HashMap::new(),
795                pending_agent_commands: HashMap::new(),
796                pending_drain_ready: HashMap::new(),
797                current_provides: None,
798                catalog_changes: VecDeque::new(),
799                upgrade: live_upgrade::UpgradeState::default(),
800                closed: false,
801            }),
802        }
803    }
804}
805
806impl ModuleHandle {
807    /// The current connection's machine id, as delivered on HELLO_ACK. A
808    /// reference held across a resume remains valid for the earlier connection.
809    ///
810    /// `None` means the daemon did not send one (it predates the machine id, or
811    /// was embedded without one) or sent a malformed value. Read that as "the
812    /// daemon has not named this machine", never as "no machine", and never mint
813    /// a substitute. The id is a name, never an authority: see [`MachineId`].
814    pub fn machine_id(&self) -> Option<&MachineId> {
815        self.generations.metadata().machine_id.as_ref()
816    }
817
818    /// The daemon capability identifiers delivered in this connection's HELLO_ACK.
819    ///
820    /// The list preserves the daemon's order and unknown capability identifiers.
821    /// A reference held across a resume remains valid for the earlier connection.
822    pub fn daemon_capabilities(&self) -> &[String] {
823        &self.generations.metadata().capabilities
824    }
825
826    /// The current connection's storage descriptor, if supplied by HELLO_ACK.
827    /// A reference held across resume still describes the earlier connection.
828    pub fn storage(&self) -> Option<&serde_json::Value> {
829        self.generations.metadata().storage.as_ref()
830    }
831
832    /// Whether this daemon advertised `capability` in this connection's HELLO_ACK.
833    ///
834    /// Scope owners should check
835    /// `daemon_supports(subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1)`
836    /// before setting `ScopeRecord.bind_proof_sha256` on records sent over
837    /// this connection.
838    ///
839    /// Daemons before 0.50.33 list `config.settings/v1` and
840    /// `config.settings.projects/v1` only in `server.describe`. Modules that
841    /// support those versions must check `server.describe` as well.
842    pub fn daemon_supports(&self, capability: &str) -> bool {
843        let shared = self.shared();
844        shared
845            .daemon_capabilities
846            .iter()
847            .any(|advertised| advertised == capability)
848    }
849
850    /// Resolves once this module's connection to the daemon has closed: after a
851    /// channel-0 GOODBYE, EOF, or a connection error. A module ends its own
852    /// background work on it, so nothing outlives the connection. This future
853    /// observes the connection current when it was created, even across resume.
854    pub fn closed(&self) -> impl Future<Output = ()> + Send + 'static {
855        let shared = self.shared();
856        shared.close_token.clone().cancelled_owned()
857    }
858
859    /// Whether this module's connection to the daemon has closed.
860    pub fn is_closed(&self) -> bool {
861        let shared = self.shared();
862        shared.close_token.is_cancelled()
863    }
864
865    /// Ask the daemon to replace this module's advertised provider roles in place.
866    ///
867    /// The returned result resolves when the daemon ACKs the update, rejects it with
868    /// a typed channel-0 Error frame, the request times out, or the connection dies.
869    pub async fn catalog_update(
870        &self,
871        provides: Vec<ProviderRole>,
872    ) -> Result<(), CatalogUpdateError> {
873        self.catalog_update_inner(Some(provides), None, None).await
874    }
875
876    /// Replace this module's complete registered role-declaration map in place.
877    ///
878    /// An empty map (`{}` on the wire) clears all declarations. Requires
879    /// subc-daemon 0.44.9 or later; returns [`CatalogUpdateError::NotSupported`]
880    /// without sending when HELLO_ACK does not advertise the operation. Invalid
881    /// declarations are refused by the daemon as [`CatalogUpdateError::Rejected`],
882    /// preserving the previous map and the refusal's code and reason.
883    pub async fn update_role_declarations(
884        &self,
885        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
886    ) -> Result<(), CatalogUpdateError> {
887        let shared = self.shared();
888        shared.check_upgrade_fence()?;
889        if !shared.supports_role_declarations_update {
890            return Err(CatalogUpdateError::NotSupported);
891        }
892        let body = serde_json::to_vec(
893            &ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations {
894                role_declarations: serde_json::to_value(&role_declarations)
895                    .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?,
896            },
897        )
898        .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
899        let send_guard = shared.catalog_send.lock().await;
900        let (corr, writer, rx) = shared.begin_catalog_update()?;
901        let _pending = CatalogUpdateGuard {
902            shared: shared.clone(),
903            corr,
904        };
905        let frame = Frame::build_with_version(
906            shared.negotiated_ver,
907            FrameType::Request,
908            control_flags(),
909            0,
910            0,
911            corr,
912            body,
913        )
914        .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
915        shared
916            .queue_catalog_change(
917                &writer,
918                frame,
919                CatalogManifestChange::RoleDeclarations(role_declarations),
920            )
921            .await?;
922        drop(send_guard);
923        match timeout(CATALOG_UPDATE_TIMEOUT, rx).await {
924            Ok(Ok(Ok(reply))) => match reply.control()? {
925                ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {} => Ok(()),
926                _ => Err(CatalogUpdateError::Protocol(
927                    "unexpected catalog.update_role_declarations response".into(),
928                )),
929            },
930            Ok(Ok(Err(err))) => Err(err),
931            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
932            Err(_) => Err(CatalogUpdateError::Timeout),
933        }
934    }
935
936    /// Replace provider roles and attest a new static capability declaration.
937    ///
938    /// The declaration must be the same static metadata emitted by the module's
939    /// current manifest; this update exists so the daemon can reconcile live routes
940    /// when that attested metadata changes.
941    pub async fn catalog_update_with_capabilities(
942        &self,
943        provides: Vec<ProviderRole>,
944        capabilities: CapabilityDeclarations,
945    ) -> Result<(), CatalogUpdateError> {
946        self.catalog_update_inner(Some(provides), Some(capabilities), None)
947            .await
948    }
949
950    /// Change readiness without changing provider roles or capability declarations.
951    ///
952    /// Register with `ready(false)`, start polling the serving future immediately,
953    /// and do slow startup work on another task before calling `set_ready(true)`.
954    /// Setting readiness to false refuses new binds but leaves existing routes up.
955    /// Requires subc-daemon 0.20.3 or later (including subc-daemon 0.38.x).
956    ///
957    /// Returns [`CatalogUpdateError::Protocol`] without sending if the current roles
958    /// are unknown: a catalog replacement is still in flight, or an earlier update
959    /// timed out, was cancelled or had an undecodable reply. After an uncertain result, a successful
960    /// explicit catalog replacement establishes the roles again.
961    pub async fn set_ready(&self, ready: bool) -> Result<(), CatalogUpdateError> {
962        self.catalog_update_inner(None, None, Some(ready)).await
963    }
964
965    async fn catalog_update_inner(
966        &self,
967        provides: Option<Vec<ProviderRole>>,
968        capabilities: Option<CapabilityDeclarations>,
969        ready: Option<bool>,
970    ) -> Result<(), CatalogUpdateError> {
971        let shared = self.shared();
972        shared.check_upgrade_fence()?;
973        if !shared.supports_catalog_update {
974            return Err(CatalogUpdateError::NotSupported);
975        }
976
977        // Order role snapshots and outbound updates together, but release the lock
978        // before waiting for ACKs so existing concurrent catalog RPCs still work.
979        let send_guard = shared.catalog_send.lock().await;
980        let provides = match provides {
981            Some(provides) => provides,
982            None => {
983                let inner = shared.lock_inner();
984                if inner.closed {
985                    return Err(CatalogUpdateError::ConnectionClosed);
986                }
987                inner
988                    .current_provides
989                    .as_ref()
990                    .filter(|_| {
991                        !inner.catalog_changes.iter().any(|change| {
992                            matches!(change.update, CatalogManifestChange::Catalog { .. })
993                        })
994                    })
995                    .cloned()
996                    .ok_or_else(|| {
997                        CatalogUpdateError::Protocol(
998                            "current provider roles are unknown or a catalog update is in flight"
999                                .into(),
1000                        )
1001                    })?
1002            }
1003        };
1004        let body = serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
1005            provides: provides.clone(),
1006            capabilities: capabilities.clone(),
1007            ready,
1008        })
1009        .map_err(|err| {
1010            CatalogUpdateError::Protocol(format!(
1011                "failed to encode catalog.update request body: {err}"
1012            ))
1013        })?;
1014        let (corr, writer, rx) = shared.begin_catalog_update()?;
1015        let _pending = CatalogUpdateGuard {
1016            shared: shared.clone(),
1017            corr,
1018        };
1019        let frame = Frame::build_with_version(
1020            shared.negotiated_ver,
1021            FrameType::Request,
1022            control_flags(),
1023            0,
1024            0,
1025            corr,
1026            body,
1027        )
1028        .map_err(|err| {
1029            shared.remove_pending_catalog_update(corr);
1030            CatalogUpdateError::Protocol(format!(
1031                "failed to build catalog.update request frame: {err}"
1032            ))
1033        })?;
1034
1035        shared
1036            .queue_catalog_change(
1037                &writer,
1038                frame,
1039                CatalogManifestChange::Catalog {
1040                    provides,
1041                    capabilities,
1042                    ready,
1043                },
1044            )
1045            .await?;
1046        drop(send_guard);
1047
1048        match timeout(CATALOG_UPDATE_TIMEOUT, async {
1049            rx.await
1050                .map(|reply| reply.and_then(ModuleControlReply::control))
1051        })
1052        .await
1053        {
1054            Ok(Ok(Ok(ModuleControlResponseToModule::CatalogUpdate {}))) => Ok(()),
1055            Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
1056                "unexpected catalog.update response".into(),
1057            )),
1058            Ok(Ok(Err(err))) => Err(err),
1059            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
1060            Err(_) => {
1061                shared.remove_pending_catalog_update(corr);
1062                Err(CatalogUpdateError::Timeout)
1063            }
1064        }
1065    }
1066
1067    /// Snapshot the roots served by this module's routable endpoint.
1068    pub async fn live_roots(&self) -> Result<LiveRootsSnapshot, CatalogUpdateError> {
1069        let shared = self.shared();
1070        shared.check_upgrade_fence()?;
1071        if !shared.supports_live_roots {
1072            return Err(CatalogUpdateError::NotSupported);
1073        }
1074        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {})
1075            .map_err(|err| CatalogUpdateError::Protocol(err.to_string()))?;
1076        let (corr, writer, rx) = shared.begin_catalog_update()?;
1077        let frame = Frame::build_with_version(
1078            shared.negotiated_ver,
1079            FrameType::Request,
1080            control_flags(),
1081            0,
1082            0,
1083            corr,
1084            body,
1085        )
1086        .map_err(|err| {
1087            shared.remove_pending_catalog_update(corr);
1088            CatalogUpdateError::Protocol(err.to_string())
1089        })?;
1090        if let Err(error) = shared.queue_request(&writer, frame).await {
1091            shared.remove_pending_catalog_update(corr);
1092            return Err(error);
1093        }
1094        match timeout(CATALOG_UPDATE_TIMEOUT, async {
1095            rx.await
1096                .map(|reply| reply.and_then(ModuleControlReply::control))
1097        })
1098        .await
1099        {
1100            Ok(Ok(Ok(ModuleControlResponseToModule::LiveRoots {
1101                roots,
1102                unknown_root_bindings,
1103                total_bindings,
1104            }))) => Ok(LiveRootsSnapshot {
1105                roots,
1106                unknown_root_bindings,
1107                total_bindings,
1108            }),
1109            Ok(Ok(Ok(_))) => Err(CatalogUpdateError::Protocol(
1110                "unexpected live_roots response".into(),
1111            )),
1112            Ok(Ok(Err(err))) => Err(err),
1113            Ok(Err(_)) => Err(CatalogUpdateError::ConnectionClosed),
1114            Err(_) => {
1115                shared.remove_pending_catalog_update(corr);
1116                Err(CatalogUpdateError::Timeout)
1117            }
1118        }
1119    }
1120
1121    /// Register this module's full scope set with the daemon (`scope.sync`).
1122    ///
1123    /// Owners can set [`ScopeRecord::workdir`] and [`ScopeRecord::project_id`] with
1124    /// the record builders after discovering `scope-workdir/v1`. These fields
1125    /// attribute the session and grant no authority.
1126    ///
1127    /// The owner is this module; nothing in the request names it. `scopes` is
1128    /// the whole set: a live scope left out ends. `generation` must be larger
1129    /// than the last one the daemon accepted from this owner's sync authority,
1130    /// or the sync is refused with `scope_sync_stale`.
1131    ///
1132    /// A refusal of the whole sync comes back as [`ScopeCallError::Refused`]
1133    /// carrying the daemon's code (see `subc_protocol::error_codes`, e.g.
1134    /// `SCOPE_SYNC_STALE`, `SCOPE_SYNC_NOT_AUTHORITY`), and nothing changed.
1135    /// Only a module the daemon itself launched can hold sync authority.
1136    pub async fn scope_sync(
1137        &self,
1138        generation: u64,
1139        scopes: Vec<ScopeRecord>,
1140    ) -> Result<ScopeSyncReply, ScopeCallError> {
1141        let shared = self.shared();
1142        live_upgrade::ScopeRequest::check_fence(&shared)?;
1143        if !shared.supports_scope_sync {
1144            return Err(ScopeCallError::NotSupported { op: SCOPE_SYNC_OP });
1145        }
1146        let request = ModuleControlRequestFromModule::ScopeSync { generation, scopes };
1147        let reply = live_upgrade::ScopeRequest::call(&shared, SCOPE_SYNC_OP, &request).await?;
1148        live_upgrade::ScopeRequest::decode_sync(reply)
1149    }
1150
1151    /// Apply a delta to this module's scope set (`scope.apply`).
1152    ///
1153    /// This connection must first have established sync authority through an
1154    /// accepted [`Self::scope_sync`]. `generation` shares the full-sync sequence
1155    /// and must exceed the last accepted generation. Unnamed scopes stay live;
1156    /// `end` ends only the named ref at the named epoch.
1157    ///
1158    /// Whole-call refusals return [`ScopeCallError::Refused`] without changing
1159    /// the set or generation. Per-record refusals and `not_live` ends remain in
1160    /// the reply. Without `scope.apply` in HELLO_ACK, nothing is sent.
1161    pub async fn scope_apply(
1162        &self,
1163        generation: u64,
1164        upsert: Vec<ScopeRecord>,
1165        end: Vec<ScopeEnd>,
1166    ) -> Result<ScopeApplyReply, ScopeCallError> {
1167        let shared = self.shared();
1168        live_upgrade::ScopeRequest::check_fence(&shared)?;
1169        if !shared.supports_scope_apply {
1170            return Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP });
1171        }
1172        let request = ModuleControlRequestFromModule::ScopeApply {
1173            generation,
1174            upsert,
1175            end,
1176        };
1177        match live_upgrade::ScopeRequest::call(&shared, SCOPE_APPLY_OP, &request)
1178            .await?
1179            .control()
1180            .map_err(ScopeCallError::from_control_error)?
1181        {
1182            ModuleControlResponseToModule::ScopeApply {
1183                generation,
1184                results,
1185                end_results,
1186                ended,
1187            } => Ok(ScopeApplyReply {
1188                generation,
1189                results,
1190                end_results,
1191                ended,
1192            }),
1193            other => Err(ScopeCallError::Protocol(format!(
1194                "unexpected {SCOPE_APPLY_OP} response: {other:?}"
1195            ))),
1196        }
1197    }
1198
1199    /// Read one scope's current state (`scope.describe`). Any registered
1200    /// module may read any owner's scope.
1201    ///
1202    /// An unknown ref is not an error: the daemon answers it with status
1203    /// `not_live`. `owner_synced` says whether the owner has synced since this
1204    /// daemon started (if so, the scope is gone), and `owner_configured` whether
1205    /// the owner is a module the daemon supervises (if not, it never will sync).
1206    pub async fn scope_describe(
1207        &self,
1208        owner: Principal,
1209        scope_ref: String,
1210    ) -> Result<ScopeDescribeReply, ScopeCallError> {
1211        let shared = self.shared();
1212        live_upgrade::ScopeRequest::check_fence(&shared)?;
1213        if !shared.supports_scope_describe {
1214            return Err(ScopeCallError::NotSupported {
1215                op: SCOPE_DESCRIBE_OP,
1216            });
1217        }
1218        let request = ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref };
1219        match live_upgrade::ScopeRequest::call(&shared, SCOPE_DESCRIBE_OP, &request)
1220            .await?
1221            .control()
1222            .map_err(ScopeCallError::from_control_error)?
1223        {
1224            ModuleControlResponseToModule::ScopeDescribe {
1225                status,
1226                scope_epoch,
1227                daemon_incarnation,
1228                owner_synced,
1229                owner_configured,
1230                scope,
1231            } => Ok(ScopeDescribeReply {
1232                status,
1233                scope_epoch,
1234                daemon_incarnation,
1235                owner_synced,
1236                owner_configured,
1237                scope,
1238            }),
1239            other => Err(ScopeCallError::Protocol(format!(
1240                "unexpected {SCOPE_DESCRIBE_OP} response: {other:?}"
1241            ))),
1242        }
1243    }
1244
1245    /// Ask the operator to authorise one in-flight, unchanged write.
1246    ///
1247    /// Every error means the module must refuse the write. `Ok(())` authorises
1248    /// only the write this call was made for; it must never be cached or reused.
1249    /// The daemon checks the summary and whether this module may ask for the
1250    /// caller's route. No failure is retried.
1251    ///
1252    /// A consumer call that may trigger confirmation must set
1253    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1254    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1255    /// accepted request.
1256    pub async fn confirm_operator(
1257        &self,
1258        summary: &str,
1259        caller_route: &RouteHandle,
1260    ) -> Result<(), OperatorConfirmError> {
1261        self.confirm_operator_with_deadline(summary, caller_route, OPERATOR_CONFIRM_TIMEOUT)
1262            .await
1263    }
1264
1265    /// Ask the operator to authorise one in-flight, unchanged write for a named
1266    /// management operation.
1267    ///
1268    /// This sends the same `operator.confirm` request as [`Self::confirm_operator`],
1269    /// with `kind` set to `"operation"` and `operation` set to the given name.
1270    /// It shares the same deadline, withdrawal-on-drop and error mapping: every
1271    /// error means the module must refuse the write, and `Ok(())` authorises
1272    /// only the write this call was made for; it must never be cached or reused.
1273    ///
1274    /// A later daemon may answer without a prompt only when the name is listed
1275    /// in this module's manifest `confirm_operations`; the daemon decides.
1276    /// Naming an operation the module did not declare still prompts; it is not
1277    /// refused.
1278    /// An empty name is refused locally as
1279    /// [`OperatorConfirmError::OperationInvalid`] without sending anything.
1280    ///
1281    /// A consumer call that may trigger confirmation must set
1282    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1283    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1284    /// accepted request.
1285    pub async fn confirm_operation(
1286        &self,
1287        summary: &str,
1288        caller_route: &RouteHandle,
1289        operation: &str,
1290    ) -> Result<(), OperatorConfirmError> {
1291        if operation.is_empty() {
1292            return Err(OperatorConfirmError::OperationInvalid);
1293        }
1294        self.confirm_operation_with_deadline(
1295            summary,
1296            caller_route,
1297            operation,
1298            OPERATOR_CONFIRM_TIMEOUT,
1299        )
1300        .await
1301    }
1302
1303    /// Ask the operator to authorise pairing or enrolling a device or credential.
1304    ///
1305    /// This sends the same `operator.confirm` request as [`Self::confirm_operator`],
1306    /// with `kind` set to `"enrollment"`. It shares the same deadline,
1307    /// withdrawal-on-drop and error mapping: every error means the module must
1308    /// refuse the enrollment, and `Ok(())` authorises only the enrollment this
1309    /// call was made for; it must never be cached or reused.
1310    ///
1311    /// The daemon never approves an enrollment without an operator prompt; it
1312    /// may still refuse one before prompting, as for any confirmation. A
1313    /// daemon built against subc-protocol before 0.33.5 ignores the kind and
1314    /// treats the request as [`Self::confirm_operator`] does.
1315    ///
1316    /// A consumer call that may trigger confirmation must set
1317    /// [`CallOptions::timeout`] to at least 300 seconds. This helper waits up to
1318    /// 290 seconds, including egress backpressure, and dropping it withdraws an
1319    /// accepted request.
1320    pub async fn confirm_enrollment(
1321        &self,
1322        summary: &str,
1323        caller_route: &RouteHandle,
1324    ) -> Result<(), OperatorConfirmError> {
1325        self.confirm_inner(
1326            summary,
1327            caller_route,
1328            Some(OperatorConfirmKind::Enrollment),
1329            None,
1330            OPERATOR_CONFIRM_TIMEOUT,
1331        )
1332        .await
1333    }
1334
1335    pub(crate) async fn confirm_operator_with_deadline(
1336        &self,
1337        summary: &str,
1338        caller_route: &RouteHandle,
1339        duration: Duration,
1340    ) -> Result<(), OperatorConfirmError> {
1341        self.confirm_inner(summary, caller_route, None, None, duration)
1342            .await
1343    }
1344
1345    async fn confirm_operation_with_deadline(
1346        &self,
1347        summary: &str,
1348        caller_route: &RouteHandle,
1349        operation: &str,
1350        duration: Duration,
1351    ) -> Result<(), OperatorConfirmError> {
1352        self.confirm_inner(
1353            summary,
1354            caller_route,
1355            Some(OperatorConfirmKind::Operation),
1356            Some(operation.to_owned()),
1357            duration,
1358        )
1359        .await
1360    }
1361
1362    async fn confirm_inner(
1363        &self,
1364        summary: &str,
1365        caller_route: &RouteHandle,
1366        kind: Option<OperatorConfirmKind>,
1367        operation: Option<String>,
1368        duration: Duration,
1369    ) -> Result<(), OperatorConfirmError> {
1370        let shared = self.shared();
1371        if caller_route.connection_token() != shared.connection_token {
1372            return Err(OperatorConfirmError::NotPermitted);
1373        }
1374        if !shared.supports_operator_confirm {
1375            return Err(OperatorConfirmError::Unsupported);
1376        }
1377        // Use the same absolute deadline for both capacity and the reply: a
1378        // slow writer must not extend the time a confirmation can remain live.
1379        let deadline = Instant::now() + duration;
1380        let body = serde_json::to_vec(
1381            &OperatorConfirmRequest::new(summary, caller_route.channel, caller_route.epoch)
1382                .with_kind(kind)
1383                .with_operation(operation),
1384        )
1385        .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1386        let (corr, writer, rx) = shared.begin_operator_confirm()?;
1387        let mut guard = OperatorConfirmGuard {
1388            shared: Arc::clone(&shared),
1389            runtime: shared.connection_runtime.clone(),
1390            writer: writer.clone(),
1391            corr,
1392            accepted: false,
1393            armed: true,
1394        };
1395        let frame = Frame::build_with_version(
1396            shared.negotiated_ver,
1397            FrameType::Request,
1398            control_flags(),
1399            0,
1400            0,
1401            corr,
1402            body,
1403        )
1404        .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1405        tokio::select! {
1406            result = timeout_at(deadline, shared.queue_request(&writer, frame)) => {
1407                result.map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1408                    .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1409            }
1410            _ = shared.close_token.cancelled() => {
1411                return Err(OperatorConfirmError::PresenceUnavailable);
1412            }
1413        }
1414        guard.accepted = true;
1415        let reply = timeout_at(deadline, rx)
1416            .await
1417            .map_err(|_| OperatorConfirmError::PresenceUnavailable)?
1418            .map_err(|_| OperatorConfirmError::PresenceUnavailable)?;
1419        guard.armed = false;
1420        match reply.header.ty {
1421            FrameType::Response => {
1422                match serde_json::from_slice::<OperatorConfirmReply>(&reply.body) {
1423                    Ok(body) if body.outcome == "confirmed" => Ok(()),
1424                    _ => Err(OperatorConfirmError::PresenceUnavailable),
1425                }
1426            }
1427            FrameType::Error => match serde_json::from_slice::<ErrorBody>(&reply.body) {
1428                Ok(body) => Err(match body.code.as_str() {
1429                    error_codes::OPERATOR_DECLINED => {
1430                        let detail = body.detail.as_ref();
1431                        if detail
1432                            .and_then(|detail| detail.get("reason"))
1433                            .and_then(serde_json::Value::as_str)
1434                            == Some("backoff")
1435                        {
1436                            OperatorConfirmError::Backoff {
1437                                retry_after_ms: detail
1438                                    .and_then(|detail| detail.get("retry_after_ms"))
1439                                    .and_then(serde_json::Value::as_u64),
1440                            }
1441                        } else {
1442                            OperatorConfirmError::Declined
1443                        }
1444                    }
1445                    error_codes::OPERATOR_PRESENCE_UNAVAILABLE
1446                        if body
1447                            .detail
1448                            .as_ref()
1449                            .and_then(|detail| detail.get("reason"))
1450                            .and_then(serde_json::Value::as_str)
1451                            == Some("unsupported_platform") =>
1452                    {
1453                        OperatorConfirmError::PresenceUnsupportedPlatform
1454                    }
1455                    error_codes::OPERATOR_SUMMARY_INVALID => OperatorConfirmError::SummaryInvalid,
1456                    error_codes::OPERATOR_REQUEST_NOT_PERMITTED | "not_registered" => {
1457                        OperatorConfirmError::NotPermitted
1458                    }
1459                    "unsupported_control_frame" => OperatorConfirmError::Unsupported,
1460                    _ => OperatorConfirmError::PresenceUnavailable,
1461                }),
1462                Err(_) => Err(OperatorConfirmError::PresenceUnavailable),
1463            },
1464            _ => Err(OperatorConfirmError::PresenceUnavailable),
1465        }
1466    }
1467
1468    /// Emit an uncorrelated Push on a live route.
1469    pub async fn push(
1470        &self,
1471        handle: &RouteHandle,
1472        body: Vec<u8>,
1473        admission_class: Option<AdmissionClass>,
1474    ) -> Result<(), SubcModuleError> {
1475        let shared = self.shared();
1476        self.validate_route(*handle)?;
1477        let writer = shared
1478            .lock_inner()
1479            .writer
1480            .clone()
1481            .ok_or(SubcModuleError::WriterClosed)?;
1482        let frame = Frame::build_with_version(
1483            shared.negotiated_ver,
1484            FrameType::Push,
1485            data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
1486            handle.channel,
1487            handle.epoch,
1488            0,
1489            body,
1490        )
1491        .map_err(SubcModuleError::FrameBuild)?;
1492        shared
1493            .queue_request(&writer, frame)
1494            .await
1495            .map_err(|_| SubcModuleError::WriterClosed)
1496    }
1497
1498    /// Number of unknown or stale route frames silently dropped by endpoint validation.
1499    pub fn dropped_route_frames(&self) -> u64 {
1500        let shared = self.shared();
1501        shared.dropped_route_frames.load(Ordering::Relaxed)
1502    }
1503
1504    fn validate_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1505        let shared = self.shared();
1506        if handle.connection_token() != shared.connection_token {
1507            return Err(SubcModuleError::StaleRouteHandle(handle));
1508        }
1509        let routes = shared
1510            .live_routes
1511            .lock()
1512            .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1513        if routes.get(&handle.channel) == Some(&handle) {
1514            Ok(())
1515        } else {
1516            Err(SubcModuleError::StaleRouteHandle(handle))
1517        }
1518    }
1519
1520    fn install_route(&self, handle: RouteHandle) -> Result<(), SubcModuleError> {
1521        let shared = self.shared();
1522        shared
1523            .live_routes
1524            .lock()
1525            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1526            .insert(handle.channel, handle);
1527        Ok(())
1528    }
1529
1530    fn installed_route(&self, channel: u16) -> Result<Option<RouteHandle>, SubcModuleError> {
1531        let shared = self.shared();
1532        let route = shared
1533            .live_routes
1534            .lock()
1535            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1536            .get(&channel)
1537            .copied();
1538        Ok(route)
1539    }
1540
1541    fn remove_route(&self, handle: RouteHandle) -> Result<bool, SubcModuleError> {
1542        let shared = self.shared();
1543        let mut routes = shared
1544            .live_routes
1545            .lock()
1546            .map_err(|_| SubcModuleError::InFlightPoisoned)?;
1547        if routes.get(&handle.channel) == Some(&handle) {
1548            routes.remove(&handle.channel);
1549            Ok(true)
1550        } else {
1551            Ok(false)
1552        }
1553    }
1554
1555    fn validate_ingress(&self, channel: u16, epoch: u32) -> Result<bool, SubcModuleError> {
1556        let shared = self.shared();
1557        let handle = RouteHandle::new(channel, epoch, shared.connection_token);
1558        let valid = shared
1559            .live_routes
1560            .lock()
1561            .map_err(|_| SubcModuleError::InFlightPoisoned)?
1562            .get(&channel)
1563            == Some(&handle);
1564        if !valid {
1565            shared.dropped_route_frames.fetch_add(1, Ordering::Relaxed);
1566        }
1567        Ok(valid)
1568    }
1569
1570    fn route_handle(&self, channel: u16, epoch: u32) -> RouteHandle {
1571        let shared = self.shared();
1572        RouteHandle::new(channel, epoch, shared.connection_token)
1573    }
1574
1575    fn handle_control_reply(&self, frame: Frame) -> bool {
1576        let shared = self.shared();
1577        let Some(frame) = self.handle_control_stream_frame(frame) else {
1578            return true;
1579        };
1580        if let Some(reply) = shared
1581            .lock_inner()
1582            .pending_drain_ready
1583            .remove(&frame.header.corr)
1584        {
1585            let _ = reply.send(frame);
1586            return true;
1587        }
1588        let claim_reply = shared
1589            .lock_inner()
1590            .pending_claim_calls
1591            .remove(&frame.header.corr);
1592        if let Some(reply) = claim_reply {
1593            let _ = reply.send(frame);
1594            return true;
1595        }
1596        let config_reply = shared
1597            .lock_inner()
1598            .pending_config_calls
1599            .remove(&frame.header.corr);
1600        if let Some(reply) = config_reply {
1601            let _ = reply.send(frame);
1602            return true;
1603        }
1604        if let Some(reply) = shared
1605            .lock_inner()
1606            .pending_agent_commands
1607            .remove(&frame.header.corr)
1608        {
1609            let _ = reply.send(frame);
1610            return true;
1611        }
1612        let served_by_reply = shared
1613            .lock_inner()
1614            .pending_scope_served_by
1615            .remove(&frame.header.corr);
1616        if let Some(reply) = served_by_reply {
1617            let _ = reply.send(frame);
1618            return true;
1619        }
1620        let activity_reply = shared
1621            .lock_inner()
1622            .pending_activity_records
1623            .remove(&frame.header.corr);
1624        if let Some(reply) = activity_reply {
1625            let _ = reply.send(frame);
1626            return true;
1627        }
1628        let operator_reply = shared
1629            .lock_inner()
1630            .pending_operator_confirms
1631            .remove(&frame.header.corr);
1632        if let Some(reply) = operator_reply {
1633            let _ = reply.send(frame);
1634            return true;
1635        }
1636        let Some(reply) = shared.take_pending_catalog_update(frame.header.corr) else {
1637            return false;
1638        };
1639        let result = match frame.header.ty {
1640            FrameType::Response => serde_json::from_slice::<ModuleControlReply>(&frame.body)
1641                .map_err(|err| {
1642                    CatalogUpdateError::Protocol(format!(
1643                        "invalid module control response body: {err}"
1644                    ))
1645                }),
1646            FrameType::Error => match serde_json::from_slice::<ErrorBody>(&frame.body) {
1647                Ok(body) => Err(match body.code.as_str() {
1648                    "catalog_update_frozen_field" => CatalogUpdateError::FrozenField(body),
1649                    "not_registered" => CatalogUpdateError::NotRegistered(body),
1650                    _ => CatalogUpdateError::Rejected(body),
1651                }),
1652                Err(err) => Err(CatalogUpdateError::Protocol(format!(
1653                    "invalid catalog.update error body: {err}"
1654                ))),
1655            },
1656            ty => Err(CatalogUpdateError::Protocol(format!(
1657                "unexpected catalog.update terminal frame: {ty:?}"
1658            ))),
1659        };
1660        let outcome = match &result {
1661            Ok(ModuleControlReply::Control(reply)) => match reply.as_ref() {
1662                ModuleControlResponseToModule::CatalogUpdate {} => {
1663                    CatalogChangeOutcome::AcceptedCatalog
1664                }
1665                ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {} => {
1666                    CatalogChangeOutcome::AcceptedRoleDeclarations
1667                }
1668                _ => CatalogChangeOutcome::Unknown,
1669            },
1670            Err(CatalogUpdateError::FrozenField(_))
1671            | Err(CatalogUpdateError::NotRegistered(_))
1672            | Err(CatalogUpdateError::Rejected(_)) => CatalogChangeOutcome::Rejected,
1673            _ => CatalogChangeOutcome::Unknown,
1674        };
1675        shared.finish_catalog_change(frame.header.corr, outcome);
1676        let _ = reply.send(result);
1677        true
1678    }
1679
1680    fn close_connection(&self) {
1681        let shared = self.shared();
1682        shared.close_connection();
1683    }
1684}
1685
1686impl ModuleHandleShared {
1687    fn begin_catalog_update(&self) -> Result<CatalogUpdateRequest, CatalogUpdateError> {
1688        self.begin_control_call(false)
1689    }
1690
1691    fn begin_control_call(
1692        &self,
1693        resume_sync: bool,
1694    ) -> Result<CatalogUpdateRequest, CatalogUpdateError> {
1695        let mut inner = self.lock_inner();
1696        if !resume_sync && inner.upgrade.fenced() {
1697            return Err(CatalogUpdateError::Rejected(live_upgrade::upgrade_refusal()));
1698        }
1699        if inner.closed {
1700            return Err(CatalogUpdateError::ConnectionClosed);
1701        }
1702        let Some(writer) = inner.writer.clone() else {
1703            drop(inner);
1704            self.close_connection();
1705            return Err(CatalogUpdateError::ConnectionClosed);
1706        };
1707        let Some(corr) = next_module_control_corr(&mut inner) else {
1708            drop(inner);
1709            self.close_connection();
1710            return Err(CatalogUpdateError::ConnectionClosed);
1711        };
1712        let (tx, rx) = oneshot::channel();
1713        inner.pending_catalog_updates.insert(corr, tx);
1714        Ok((corr, writer, rx))
1715    }
1716
1717    fn begin_operator_confirm(&self) -> Result<OperatorConfirmRequestWaiter, OperatorConfirmError> {
1718        let mut inner = self.lock_inner();
1719        if inner.closed || inner.upgrade.fenced() {
1720            return Err(OperatorConfirmError::PresenceUnavailable);
1721        }
1722        let Some(writer) = inner.writer.clone() else {
1723            drop(inner);
1724            self.close_connection();
1725            return Err(OperatorConfirmError::PresenceUnavailable);
1726        };
1727        let Some(corr) = next_module_control_corr(&mut inner) else {
1728            drop(inner);
1729            self.close_connection();
1730            return Err(OperatorConfirmError::PresenceUnavailable);
1731        };
1732        let (tx, rx) = oneshot::channel();
1733        inner.pending_operator_confirms.insert(corr, tx);
1734        Ok((corr, writer, rx))
1735    }
1736
1737    fn take_pending_catalog_update(&self, corr: u64) -> Option<CatalogUpdateReply> {
1738        self.lock_inner().pending_catalog_updates.remove(&corr)
1739    }
1740
1741    fn remove_pending_catalog_update(&self, corr: u64) {
1742        let removed = self
1743            .lock_inner()
1744            .pending_catalog_updates
1745            .remove(&corr)
1746            .is_some();
1747        if removed {
1748            self.finish_catalog_change(corr, CatalogChangeOutcome::Unknown);
1749        }
1750    }
1751
1752    fn finish_catalog_change(&self, corr: u64, outcome: CatalogChangeOutcome) {
1753        let mut inner = self.lock_inner();
1754        if let Some(change) = inner
1755            .catalog_changes
1756            .iter_mut()
1757            .find(|change| change.corr == corr)
1758        {
1759            change.outcome = Some(outcome);
1760        }
1761        // Replies may arrive out of order. Apply their effects in send order,
1762        // including replies whose caller dropped its waiting future.
1763        while inner
1764            .catalog_changes
1765            .front()
1766            .is_some_and(|change| change.outcome.is_some())
1767        {
1768            let change = inner.catalog_changes.pop_front().expect("completed change");
1769            match (change.outcome.expect("completed outcome"), change.update) {
1770                (
1771                    CatalogChangeOutcome::AcceptedCatalog,
1772                    CatalogManifestChange::Catalog {
1773                        provides,
1774                        capabilities,
1775                        ready,
1776                    },
1777                ) => {
1778                    inner.current_provides = Some(provides.clone());
1779                    inner.upgrade.update_manifest(|manifest| {
1780                        manifest.provides = provides;
1781                        if capabilities.is_some() {
1782                            manifest.capabilities = capabilities;
1783                        }
1784                        if ready.is_some() {
1785                            manifest.ready = ready;
1786                        }
1787                    });
1788                }
1789                (
1790                    CatalogChangeOutcome::AcceptedRoleDeclarations,
1791                    CatalogManifestChange::RoleDeclarations(declarations),
1792                ) => {
1793                    inner
1794                        .upgrade
1795                        .update_manifest(|manifest| manifest.role_declarations = declarations);
1796                }
1797                (
1798                    CatalogChangeOutcome::Unknown | CatalogChangeOutcome::AcceptedRoleDeclarations,
1799                    CatalogManifestChange::Catalog { .. },
1800                ) => inner.current_provides = None,
1801                _ => {}
1802            }
1803        }
1804    }
1805
1806    fn close_connection(&self) {
1807        let pending = {
1808            let mut inner = self.lock_inner();
1809            if inner.closed {
1810                return;
1811            }
1812            inner.closed = true;
1813            inner.writer = None;
1814            inner.catalog_changes.clear();
1815            self.close_token.cancel();
1816            // Dropping these senders wakes raw-frame waiters immediately.
1817            inner.pending_operator_confirms.clear();
1818            inner.pending_activity_records.clear();
1819            inner.pending_scope_served_by.clear();
1820            inner.pending_drain_ready.clear();
1821            inner.pending_config_calls.clear();
1822            inner.pending_agent_commands.clear();
1823            inner.pending_claim_calls.clear();
1824            inner.pending_control_streams.clear();
1825            inner
1826                .pending_catalog_updates
1827                .drain()
1828                .map(|(_, reply)| reply)
1829                .collect::<Vec<_>>()
1830        };
1831        self.clear_live_routes();
1832        for reply in pending {
1833            let _ = reply.send(Err(CatalogUpdateError::ConnectionClosed));
1834        }
1835    }
1836
1837    fn clear_live_routes(&self) {
1838        if let Ok(mut routes) = self.live_routes.lock() {
1839            routes.clear();
1840        }
1841    }
1842
1843    fn lock_inner(&self) -> std::sync::MutexGuard<'_, ModuleHandleState> {
1844        self.inner
1845            .lock()
1846            .unwrap_or_else(|poisoned| poisoned.into_inner())
1847    }
1848}
1849
1850fn next_module_control_corr(inner: &mut ModuleHandleState) -> Option<u64> {
1851    let corr = inner.next_corr?;
1852    inner.next_corr = corr.checked_add(1);
1853    Some(corr)
1854}
1855
1856struct OperatorConfirmGuard {
1857    shared: Arc<ModuleHandleShared>,
1858    runtime: tokio::runtime::Handle,
1859    writer: mpsc::Sender<Frame>,
1860    corr: u64,
1861    accepted: bool,
1862    armed: bool,
1863}
1864
1865impl Drop for OperatorConfirmGuard {
1866    fn drop(&mut self) {
1867        if !self.armed {
1868            return;
1869        }
1870        self.shared
1871            .lock_inner()
1872            .pending_operator_confirms
1873            .remove(&self.corr);
1874        if !self.accepted {
1875            return;
1876        }
1877        let Ok(cancel) = Frame::build_with_version(
1878            self.shared.negotiated_ver,
1879            FrameType::Cancel,
1880            control_flags(),
1881            0,
1882            0,
1883            self.corr,
1884            Vec::new(),
1885        ) else {
1886            return;
1887        };
1888        match self.writer.try_send(cancel) {
1889            Ok(()) | Err(mpsc::error::TrySendError::Closed(_)) => {}
1890            Err(mpsc::error::TrySendError::Full(cancel)) => {
1891                // The connection owns this task even if the future was polled
1892                // on another runtime or dropped from a plain thread. A full
1893                // egress buffer delays withdrawal; it must not discard it.
1894                let writer = self.writer.clone();
1895                self.runtime.spawn(async move {
1896                    let _ = writer.send(cancel).await;
1897                });
1898            }
1899        }
1900    }
1901}
1902
1903/// Failure to authorise a write through [`ModuleHandle::confirm_operator`],
1904/// [`ModuleHandle::confirm_operation`] or [`ModuleHandle::confirm_enrollment`].
1905/// Every variant requires the module to refuse the write, with one exception
1906/// described on [`OperatorConfirmError::PresenceUnsupportedPlatform`].
1907#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1908#[non_exhaustive]
1909pub enum OperatorConfirmError {
1910    Declined,
1911    /// The daemon did not ask because a recent decline is still in effect.
1912    /// Older daemons omit the remaining cooldown, so `retry_after_ms` may be absent.
1913    Backoff {
1914        retry_after_ms: Option<u64>,
1915    },
1916    /// The daemon could not get an answer from the operator: the prompt
1917    /// failed or timed out, the connection dropped, or the reply was unknown
1918    /// or malformed. A withdrawn prompt can instead come back as
1919    /// [`OperatorConfirmError::Declined`].
1920    PresenceUnavailable,
1921    /// The daemon has no operator prompt on this platform (today Linux), so
1922    /// it showed none. It answered `operator_presence_unavailable` with
1923    /// `detail.reason` `unsupported_platform`. Every other
1924    /// `operator_presence_unavailable` reply stays
1925    /// [`OperatorConfirmError::PresenceUnavailable`].
1926    ///
1927    /// Like every variant, this refuses the write by default. A module may
1928    /// treat it differently only where its owner has ruled that, on a platform
1929    /// without a prompt, a confirmation typed by a person in a local app
1930    /// counts, and the product says so. It must never treat a
1931    /// `PresenceUnavailable` that way.
1932    PresenceUnsupportedPlatform,
1933    SummaryInvalid,
1934    /// The operation name for [`ModuleHandle::confirm_operation`] was empty.
1935    /// Operation names have no lexical grammar in Rust; membership in the
1936    /// module's manifest `confirm_operations` is decided by the daemon, which
1937    /// prompts for any name it does not recognise. Only the empty string can
1938    /// never name an operation, so it is refused before sending.
1939    OperationInvalid,
1940    NotPermitted,
1941    Unsupported,
1942}
1943
1944impl fmt::Display for OperatorConfirmError {
1945    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946        f.write_str(match self {
1947            Self::Declined => "operator declined the write",
1948            Self::Backoff { retry_after_ms: None } => {
1949                "operator confirmation refused without asking: a recent decline holds new prompts for a short time"
1950            }
1951            Self::PresenceUnavailable => "operator confirmation is unavailable",
1952            Self::PresenceUnsupportedPlatform => {
1953                "operator confirmation has no prompt on this platform"
1954            }
1955            Self::SummaryInvalid => "operator confirmation summary is invalid",
1956            Self::OperationInvalid => "operator confirmation operation is invalid",
1957            Self::NotPermitted => "operator confirmation is not permitted for this route",
1958            Self::Unsupported => "daemon does not support operator confirmation",
1959            Self::Backoff {
1960                retry_after_ms: Some(_),
1961            } => return write!(
1962                f,
1963                "operator confirmation refused without asking: a recent decline holds new prompts for {} s",
1964                self.backoff_seconds().expect("backoff retry duration is present")
1965            ),
1966        })
1967    }
1968}
1969
1970impl OperatorConfirmError {
1971    fn backoff_seconds(&self) -> Option<u64> {
1972        match self {
1973            Self::Backoff {
1974                retry_after_ms: Some(milliseconds),
1975            } => Some(milliseconds / 1_000 + u64::from(!milliseconds.is_multiple_of(1_000))),
1976            _ => None,
1977        }
1978    }
1979}
1980
1981impl Error for OperatorConfirmError {}
1982
1983/// Errors returned by [`ModuleHandle::catalog_update`], [`ModuleHandle::set_ready`]
1984/// and [`ModuleHandle::update_role_declarations`].
1985/// An announced upgrade rejects new calls locally with `module_reloading` and
1986/// `detail.reason` set to `daemon_upgrade`; no request was sent.
1987#[derive(Debug)]
1988pub enum CatalogUpdateError {
1989    NotSupported,
1990    FrozenField(ErrorBody),
1991    NotRegistered(ErrorBody),
1992    Rejected(ErrorBody),
1993    Timeout,
1994    ConnectionClosed,
1995    Protocol(String),
1996}
1997
1998impl fmt::Display for CatalogUpdateError {
1999    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2000        match self {
2001            Self::NotSupported => write!(
2002                f,
2003                "daemon HELLO_ACK did not advertise catalog.update support"
2004            ),
2005            Self::FrozenField(body) => {
2006                write!(f, "catalog.update rejected frozen field: {}", body.message)
2007            }
2008            Self::NotRegistered(body) => write!(
2009                f,
2010                "catalog.update requires a registered module: {}",
2011                body.message
2012            ),
2013            Self::Rejected(body) => write!(
2014                f,
2015                "catalog.update rejected by subc: {} ({})",
2016                body.code, body.message
2017            ),
2018            Self::Timeout => write!(f, "catalog.update timed out waiting for an ACK"),
2019            Self::ConnectionClosed => {
2020                write!(f, "subc connection closed before catalog.update completed")
2021            }
2022            Self::Protocol(message) => write!(f, "catalog.update protocol error: {message}"),
2023        }
2024    }
2025}
2026
2027impl Error for CatalogUpdateError {}
2028
2029/// Errors returned by [`ModuleHandle::scope_sync`], [`ModuleHandle::scope_apply`] and
2030/// [`ModuleHandle::scope_describe`].
2031///
2032/// Non-exhaustive so a later failure kind can be added without breaking
2033/// callers' matches. Match the variants you handle, and treat any other variant
2034/// as a call whose effect you cannot know: after `scope_sync` or `scope_apply`,
2035/// send a full `scope_sync` at a higher generation rather than assume the change
2036/// did or did not apply.
2037#[derive(Debug, Clone, PartialEq, Eq)]
2038#[non_exhaustive]
2039pub enum ScopeCallError {
2040    /// HELLO_ACK did not advertise the operation (or its required capability),
2041    /// so nothing was sent.
2042    NotSupported { op: &'static str },
2043    /// The daemon sent a channel-0 Error frame, or the SDK refused to send the
2044    /// request during an announced upgrade (`module_reloading`). Compare `code` against
2045    /// the constants in
2046    /// `subc_protocol::error_codes` (`SCOPE_SYNC_STALE`,
2047    /// `SCOPE_SYNC_NOT_AUTHORITY`, `SCOPE_LIVE_LIMIT_EXCEEDED`, ...).
2048    Refused { code: String, message: String },
2049    /// No reply arrived in time. The daemon may still have applied the change.
2050    Timeout,
2051    /// The connection closed before a reply arrived.
2052    ConnectionClosed,
2053    /// The reply could not be read, or was a reply to a different op.
2054    Protocol(String),
2055}
2056
2057impl ScopeCallError {
2058    /// The daemon's error code, when the daemon refused the request.
2059    pub fn code(&self) -> Option<&str> {
2060        match self {
2061            Self::Refused { code, .. } => Some(code),
2062            _ => None,
2063        }
2064    }
2065
2066    /// Convert an error from the pending-reply handling that scope calls share
2067    /// with `catalog_update`, which reports failures as `CatalogUpdateError`.
2068    /// For a daemon Error frame, keep the daemon's code and message whatever
2069    /// the code is.
2070    fn from_control_error(err: CatalogUpdateError) -> Self {
2071        match err {
2072            CatalogUpdateError::FrozenField(body)
2073            | CatalogUpdateError::NotRegistered(body)
2074            | CatalogUpdateError::Rejected(body) => Self::Refused {
2075                code: body.code,
2076                message: body.message,
2077            },
2078            CatalogUpdateError::Timeout => Self::Timeout,
2079            CatalogUpdateError::ConnectionClosed => Self::ConnectionClosed,
2080            CatalogUpdateError::Protocol(message) => Self::Protocol(message),
2081            // The shared reply handling never returns this: whether the
2082            // daemon supports an op is checked before the request is sent.
2083            CatalogUpdateError::NotSupported => {
2084                Self::Protocol("unexpected NotSupported from the control reply table".into())
2085            }
2086        }
2087    }
2088}
2089
2090impl fmt::Display for ScopeCallError {
2091    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2092        match self {
2093            Self::NotSupported { op } => {
2094                write!(f, "daemon HELLO_ACK did not advertise {op} support")
2095            }
2096            Self::Refused { code, message } => {
2097                write!(f, "subc refused the request: {code} ({message})")
2098            }
2099            Self::Timeout => write!(f, "timed out waiting for the daemon's reply"),
2100            Self::ConnectionClosed => {
2101                write!(f, "subc connection closed before the daemon replied")
2102            }
2103            Self::Protocol(message) => write!(f, "scope call protocol error: {message}"),
2104        }
2105    }
2106}
2107
2108impl Error for ScopeCallError {}
2109
2110/// Trait implemented by a module for its business logic. The serve functions in
2111/// this crate own all wire-protocol plumbing.
2112///
2113/// # Stopping cleanly: drains
2114///
2115/// Before stopping a module, the daemon sends a drain notice, closes route
2116/// admission, and waits for in-flight requests before sending GOODBYE. In an
2117/// ordinary drain admission closes before the notice. An opted-in restart or
2118/// reload may instead send a [`DrainNotice`] with `accepting: true`. Admission
2119/// then stays open until [`ModuleHandle::drain_ready`] or the deadline. Persist
2120/// work accepted in that phase before answering it.
2121///
2122/// Requests the daemon forwarded are counted by the daemon itself. Work it
2123/// cannot see (a job a request started in the background, a batch being
2124/// flushed) holds an ordinary drain open only if the module says so. The module does
2125/// that with a counter it reports in its health answer (a "health gauge"),
2126/// and a manifest entry telling the daemon that the counter means "busy": a
2127/// `Busy` self-signal anchored to those health gauges. Declare it, and report those
2128/// gauges in [`ModuleHandler::health`]'s `metrics` above zero until the work
2129/// has finished. During a drain the daemon probes `health` and waits until
2130/// every declared gauge reads 0 (or the deadline passes); a declared gauge
2131/// missing from the report counts as busy. The manifest entry, as built by the
2132/// `echo-module` example in this crate:
2133///
2134/// ```
2135/// use subc_protocol::manifest::{
2136///     ModuleManifest, SelfSignalDeclaration, SelfSignalEffect, SelfSignalKind, SignalAnchor,
2137/// };
2138///
2139/// let manifest = ModuleManifest::builder("my-module", "1.0.0")
2140///     .self_signals(Some(vec![SelfSignalDeclaration {
2141///         name: "background_work".to_string(),
2142///         kind: SelfSignalKind::Busy,
2143///         effect: SelfSignalEffect::Observe,
2144///         anchored_to: SignalAnchor::HealthGauges {
2145///             gauges: vec!["background_jobs".to_string()],
2146///         },
2147///         cadence: None,
2148///         domain: None,
2149///         note: None,
2150///     }]))
2151///     .build();
2152/// # let _ = manifest;
2153/// ```
2154///
2155/// and `health` then reports `{"background_jobs": <count>}` in `metrics`. Count
2156/// only work whose result would still be delivered if it finished during the
2157/// drain; see [`SelfSignalDeclaration::kind`](subc_protocol::manifest::SelfSignalDeclaration::kind).
2158#[async_trait]
2159pub trait ModuleHandler: Send + Sync + 'static {
2160    /// Handle a data-plane request on a route channel. Return a unary response, a
2161    /// typed error, or stream interim events via [`RequestCtx::emit`] and return
2162    /// [`HandlerOutcome::Streamed`]. Each request runs in its own task so one slow
2163    /// handler cannot head-of-line-block another route.
2164    async fn handle(&self, ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome;
2165
2166    /// Called after each HELLO_ACK so the module can inspect the ack body for
2167    /// negotiated capabilities and any storage descriptor supplied by the daemon.
2168    async fn on_hello_ack(&self, _ack: &ModuleHelloAckBody) {}
2169
2170    /// Supply a full scope sync to send before dispatching any resumed frames.
2171    /// The handle exposes the new ACK metadata, but cannot send RPCs in this
2172    /// hook. Make calls and reopen routes in [`Self::on_reconnected`] instead.
2173    async fn resume_scope_sync(&self, _handle: &ModuleHandle) -> Option<ResumeScopeSync> {
2174        None
2175    }
2176
2177    /// Rebuild connection-local state after an announced daemon upgrade. The
2178    /// reader and config session are already running. A refused scope sync is
2179    /// reported here and does not end the connection.
2180    async fn on_reconnected(
2181        &self,
2182        _handle: &ModuleHandle,
2183        _scope_sync: Option<Result<ScopeSyncReply, ScopeCallError>>,
2184    ) {
2185    }
2186
2187    /// Extra daemon-to-module operations served on channel 0, such as `consent/v1`.
2188    /// Read and validated once before HELLO: names must be nonempty ASCII names
2189    /// using letters, digits, `.`, `_`, `-` or `/`, with no empty segments.
2190    /// Duplicates and SDK-owned `health.check`, `config.review` and `route.bind`
2191    /// are refused with [`SubcModuleError::InvalidControlOp`] before advertising.
2192    fn control_ops(&self) -> Vec<String> {
2193        Vec::new()
2194    }
2195
2196    /// Handle a declared control op with its entire decoded JSON request body.
2197    /// The control name is the body's `op` string; for a protocol-tagged request
2198    /// with no `op`, such as `consent/v1`, it is the body's `protocol` string.
2199    /// Return a JSON RESPONSE body or an [`ErrorBody`] carrying a wire error code
2200    /// and message. Runs off the reader, independently of routes, health and
2201    /// config review, with at most 16 concurrent calls per connection and no
2202    /// queue; overload returns `resource_exhausted`. There is no SDK time limit.
2203    ///
2204    /// CANCEL for this request's correlation, or disconnect, signals `cancel`.
2205    /// A reply produced after cancellation is discarded. Cooperate with the
2206    /// signal to release resources promptly; a cancelled call still holds its
2207    /// slot until it returns, and connection teardown eventually aborts it.
2208    async fn on_control_request(
2209        &self,
2210        _op: &str,
2211        _body: serde_json::Value,
2212        _cancel: CancellationToken,
2213    ) -> Result<serde_json::Value, ErrorBody> {
2214        Err(ErrorBody::new(
2215            "unsupported_op",
2216            "no control handler implemented",
2217        ))
2218    }
2219
2220    /// Opt in once per connection. The SDK advertises `config.review`, declares
2221    /// these locations, and fetches immutable views before calling `config_apply`.
2222    /// Returning `None` leaves the existing module wire and file reader unchanged.
2223    fn config_declaration(&self) -> Option<config::ConfigDeclareRequest> {
2224        None
2225    }
2226
2227    /// Pure review of supplied snapshots and base. Do not read mutable files,
2228    /// environment, network or secrets here. Runs off the connection reader.
2229    async fn config_review(
2230        &self,
2231        _request: config::ConfigReviewRequest,
2232    ) -> config::ConfigReviewReply {
2233        config::ConfigReviewReply::new(
2234            vec![],
2235            vec![config::ConfigReviewRefusal::new(
2236                "value_invalid",
2237                vec![],
2238                vec!["module has no config review implementation".into()],
2239            )],
2240        )
2241    }
2242
2243    /// Atomically apply a complete view, or leave the previous view intact and
2244    /// return secret-free NACK reasons. Readiness is included in a successful
2245    /// return. Runs off the reader; health and drain hooks remain independent.
2246    async fn config_apply(&self, _view: config::ConfigView) -> Result<(), Vec<String>> {
2247        Err(vec!["module has no config apply implementation".into()])
2248    }
2249
2250    /// Use the module's existing file reader. Called only for an opted-in module
2251    /// whose HELLO_ACK lacks `config.gate`, never after a gate refusal.
2252    async fn config_files(&self) {}
2253
2254    /// Observe wire status and refusals without ending the serving connection.
2255    async fn on_config_state(&self, _state: config::ConfigState) {}
2256
2257    /// Observe transport, malformed-reply and other config errors. These never
2258    /// authorize a file fallback or end the module connection.
2259    async fn on_config_error(&self, error: config::ConfigError) {
2260        tracing::warn!(%error, "module configuration request failed");
2261    }
2262
2263    /// Observe refusals and protocol errors for a named project refresh.
2264    /// Keep the project's last good view, or use the user view if none exists.
2265    /// By default, forwards to [`Self::on_config_error`].
2266    async fn on_project_config_error(&self, _project_id: String, error: config::ConfigError) {
2267        self.on_config_error(error).await;
2268    }
2269
2270    /// Decide a route.bind. This hook is decision-only and must not emit route traffic.
2271    async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
2272        BindDecision::accept()
2273    }
2274
2275    /// Called after an accepted bind ACK is queued and the handle is installed.
2276    async fn on_bound(&self, _handle: &RouteHandle) {}
2277
2278    /// Return cheap in-memory health for the module.
2279    ///
2280    /// The default reports `Ok` with the detail "no health implementation;
2281    /// inherited default". The detail lets an operator reading
2282    /// `ck health <module>` tell "measured, nothing wrong" from "nobody
2283    /// measured", but the daemon decides on the status alone and never parses
2284    /// the detail, so to the daemon the default looks like a module that checked
2285    /// itself and found nothing wrong. It stays a default because health is
2286    /// optional: a module that advertises no health capability is never probed,
2287    /// so the value is never read. A module that does advertise health and
2288    /// keeps this default can report no fault beyond the serve helper's own
2289    /// saturation check.
2290    ///
2291    /// The serve helper calls this when the daemon sends `health.check`, on a
2292    /// task of its own rather than in a handler-slot pool, so a health check
2293    /// never waits behind the requests it reports on. It then folds in
2294    /// dispatch saturation: if every slot of a pool is in use and a request
2295    /// has waited more than two seconds for one, an `Ok` reply becomes
2296    /// `Degraded`, and the pool's slot count and oldest wait are prepended to
2297    /// `detail` (naming the pool when the module declared a long-held pool in
2298    /// [`ModuleHandler::request_pools`]). A `Degraded` or `Failing` status,
2299    /// the module's own detail and its metrics are kept.
2300    ///
2301    /// An implementation must not block: no blocking lock, no disk access and
2302    /// no subprocess on this path. Derive the status from signals the dispatch
2303    /// path already records in memory, such as a monotonic heartbeat or the age
2304    /// of the oldest queued item. A health reply that waits on a slow shared
2305    /// resource stalls under exactly the conditions it is meant to report,
2306    /// because that resource is what degrades first.
2307    async fn health(&self) -> HealthReport {
2308        // Say that nobody measured, rather than that everything is fine.
2309        //
2310        // The status stays Ok because a module advertising no health capability
2311        // is never probed, and one that advertises health but has nothing to
2312        // report is not unhealthy. What changes is that the report identifies
2313        // itself as the inherited default, so an operator reading
2314        // `ck health <module>` can tell "measured, nothing wrong" from "nobody
2315        // wrote a health path" -- which were previously the same bytes.
2316        //
2317        // `detail` is carried verbatim by the daemon and rendered for humans;
2318        // nothing parses it, so this is display-only and cannot change any
2319        // supervision decision.
2320        HealthReport {
2321            detail: Some("no health implementation; inherited default".to_string()),
2322            ..HealthReport::ok()
2323        }
2324    }
2325
2326    /// A route was torn down, rejected, or abandoned before its bind ACK was queued.
2327    async fn on_route_gone(&self, _handle: &RouteHandle) {}
2328
2329    /// How this module's data requests share handler slots. Called once per
2330    /// connection, before the serve loop reads its first frame after HELLO_ACK.
2331    ///
2332    /// Each data request waits for a slot before [`ModuleHandler::handle`]
2333    /// runs and holds it until `handle` returns. The default is one pool of
2334    /// 64 slots for every request, waited for in arrival order. A module whose
2335    /// requests can be held for minutes should declare a long-held pool for
2336    /// them, so they cannot take every slot and leave short requests queued
2337    /// behind them where the daemon cannot see:
2338    ///
2339    /// ```
2340    /// use subc_client_rs::{RequestClass, RequestPools};
2341    ///
2342    /// fn request_pools() -> RequestPools {
2343    ///     RequestPools::new().with_long_held(16, |body| {
2344    ///         if body.starts_with(br#"{"op":"research.run""#) {
2345    ///             RequestClass::long_held().with_op("research.run")
2346    ///         } else {
2347    ///             RequestClass::default_pool()
2348    ///         }
2349    ///     })
2350    /// }
2351    /// # let _ = request_pools();
2352    /// ```
2353    ///
2354    /// A request that waits two seconds for a slot is logged once at WARN
2355    /// while it is still waiting. While the connection is open, a request
2356    /// cancelled while waiting is answered `cancelled` at once; when the
2357    /// connection ends, waiting requests end without a reply, as before.
2358    /// [`ModuleHandle::request_pool_snapshots`]
2359    /// reports each pool's figures. Health checks never use a pool.
2360    fn request_pools(&self) -> RequestPools {
2361        RequestPools::new()
2362    }
2363
2364    /// The daemon has started draining this module: it will stop it for
2365    /// `reason` (a restart, reload, disable, or the daemon's own shutdown), and
2366    /// usually has already stopped admitting new routes to it. Modules that
2367    /// opt in to accepting drains should implement [`Self::on_draining_notice`]
2368    /// instead, to distinguish the two kinds of notice.
2369    ///
2370    /// `deadline` is the wall-clock time by which the module must be done. It
2371    /// is "no later than", never a grant of that much time: the daemon enforces
2372    /// its own ceiling on a monotonic clock and tears the connection down when
2373    /// that runs out, and after the host sleeps the ceiling can fall before
2374    /// this wall-clock time does. Aim to finish early.
2375    ///
2376    /// Called once for each drain notice the daemon sends, on its own task, so
2377    /// a slow hook never holds up pings, requests, or the GOODBYE that ends the
2378    /// drain. It is started before that GOODBYE is handled (and before
2379    /// [`ModuleHandler::on_connection_end`]). Connection teardown aborts hooks
2380    /// that have not finished within the drain budget.
2381    async fn on_draining(&self, _reason: RouteCloseReason, _deadline: SystemTime) {}
2382
2383    /// Like [`Self::on_draining`], with the per-notice route admission state.
2384    /// The default forwards to `on_draining` for existing handlers.
2385    async fn on_draining_notice(&self, notice: DrainNotice) {
2386        self.on_draining(notice.reason, notice.deadline).await;
2387    }
2388
2389    /// The connection ended orderly: a daemon GOODBYE is a planned stop, EOF
2390    /// or Reset means the daemon went away without one, and `Closed` is a
2391    /// module stop. Called once, after request tasks have finished or been
2392    /// cancelled. A module that wants a different exit code for an unannounced
2393    /// end can decide here. Not called for handler or protocol failures. A
2394    /// later, unexpected writer failure can still make serving return an error.
2395    async fn on_connection_end(&self, _end: ConnectionEnd) {}
2396}
2397
2398/// How a registered module's daemon connection ended. After the handshake, EOF
2399/// and socket disconnects are orderly ends on every platform: serving calls
2400/// `on_connection_end` and returns `Ok(())`. Handshake, handler, protocol and
2401/// other transport failures return errors.
2402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2403#[non_exhaustive]
2404pub enum ConnectionEnd {
2405    /// The daemon sent GOODBYE on channel 0: a planned stop.
2406    Goodbye,
2407    /// The daemon closed the connection without GOODBYE.
2408    Eof,
2409    /// The socket was reset or aborted, or its writer disconnected. This is how
2410    /// Windows reports a daemon that died, which Unix reports as [`Self::Eof`].
2411    Reset,
2412    /// The module closed the connection itself, including a [`ModuleStopHandle`] stop.
2413    Closed,
2414}
2415
2416impl ConnectionEnd {
2417    /// Stable lower-case name for logs: `goodbye`, `eof`, `reset`, `closed`.
2418    pub fn as_str(self) -> &'static str {
2419        match self {
2420            Self::Goodbye => "goodbye",
2421            Self::Eof => "eof",
2422            Self::Reset => "reset",
2423            Self::Closed => "closed",
2424        }
2425    }
2426}
2427
2428impl std::fmt::Display for ConnectionEnd {
2429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2430        f.write_str(self.as_str())
2431    }
2432}
2433
2434/// The terminal result of a module request handler.
2435#[derive(Debug, Clone, PartialEq)]
2436pub enum HandlerOutcome {
2437    /// Send a Response frame carrying these bytes.
2438    Response(Vec<u8>),
2439    /// Send an Error frame carrying an [`ErrorBody`] with this code and message.
2440    Error { code: String, message: String },
2441    /// Send an Error frame with stable machine-readable detail.
2442    ErrorWithDetail {
2443        code: String,
2444        message: String,
2445        detail: serde_json::Value,
2446    },
2447    /// The handler emitted stream data with [`RequestCtx::emit`]; the serve code
2448    /// sends the StreamEnd terminal frame.
2449    Streamed,
2450}
2451
2452/// Per-request context. Retains the full route handle and correlation id, provides
2453/// interim stream emission, and exposes a cancellation signal.
2454#[derive(Clone)]
2455pub struct RequestCtx {
2456    handle: RouteHandle,
2457    corr: u64,
2458    ver: u8,
2459    egress: mpsc::Sender<Frame>,
2460    module_handle: ModuleHandle,
2461    cancelled: CancellationToken,
2462    binary_reply: Arc<AtomicBool>,
2463    request_flags: Flags,
2464    request_body: Arc<[u8]>,
2465    /// True until the terminal frame is queued. [`RequestCtx::push`] checks and
2466    /// sends under this lock, and the terminal path clears it under the same
2467    /// lock, so no push can reach the wire after the call's last frame even
2468    /// when another task holds a clone of this context.
2469    open: Arc<tokio::sync::Mutex<bool>>,
2470}
2471
2472impl RequestCtx {
2473    /// Clone the connection's control handle, for readiness and other module RPCs.
2474    pub fn module_handle(&self) -> ModuleHandle {
2475        self.module_handle.clone()
2476    }
2477
2478    /// Decodes a framed request only when ingress carried `FLAG_BINARY`.
2479    /// Call this only for management operations that declared `operation_payload`.
2480    /// Return a malformed body's named error as a refusal before doing any work;
2481    /// the serve helper deliberately leaves that policy to the handler.
2482    pub fn request_payload(
2483        &self,
2484    ) -> Result<Option<(serde_json::Value, &[u8])>, subc_protocol::framed_body::FramedBodyError>
2485    {
2486        if !self.request_flags.is_binary() {
2487            return Ok(None);
2488        }
2489        subc_protocol::framed_body::decode(&self.request_body).map(Some)
2490    }
2491
2492    /// Full route handle retained from ingress.
2493    pub fn route_handle(&self) -> RouteHandle {
2494        self.handle
2495    }
2496
2497    /// Correlation id for this request.
2498    pub fn corr(&self) -> u64 {
2499        self.corr
2500    }
2501
2502    /// Declare this request's terminal [`HandlerOutcome::Response`] as raw bytes,
2503    /// not JSON, by setting `FLAG_BINARY` on its frame.
2504    ///
2505    /// Mark a reply only when the operation's contract defines a raw-byte reply,
2506    /// never for JSON contracts such as tool results or JSON management replies.
2507    /// The body is sent unchanged either way; the flag only declares that it is
2508    /// not JSON, and the daemon forwards it as is. The delivered frame is still
2509    /// bounded by [`subc_protocol::MAX_DELIVERED_FRAME_LEN`], including its header.
2510    ///
2511    /// All clones of this request's context share the mark; other requests do not.
2512    /// It has no effect on errors, interim stream frames, or `Streamed` outcomes.
2513    pub fn mark_binary_reply(&self) {
2514        self.binary_reply.store(true, Ordering::Relaxed);
2515    }
2516
2517    /// Emit an interim StreamData frame on this request's `(channel, corr)`. Once
2518    /// the request is cancelled or its route is gone, late emits are dropped.
2519    pub async fn emit(&self, body: Vec<u8>) -> Result<(), SubcModuleError> {
2520        self.emit_with_admission(body, None).await
2521    }
2522
2523    /// Send a Push on this request's `(channel, corr)` without ending the call.
2524    ///
2525    /// This is how a provider sends tool-provider call keepalives
2526    /// (`{"kind":"keepalive"}`) or progress while the call runs: a consumer
2527    /// resets its silence timer on any Push carrying the call's correlation.
2528    /// Unlike [`RequestCtx::emit`], which drops late frames silently, this
2529    /// refuses with [`SubcModuleError::RequestEnded`] once the request was
2530    /// cancelled or its terminal frame was queued, so a keepalive loop knows
2531    /// to stop.
2532    pub async fn push(&self, body: Vec<u8>) -> Result<(), SubcModuleError> {
2533        let open = self.open.lock().await;
2534        if !*open || self.cancelled.is_cancelled() {
2535            return Err(SubcModuleError::RequestEnded);
2536        }
2537        self.send_frame(FrameType::Push, data_flags(), body).await
2538    }
2539
2540    /// Emit StreamData with an explicit admission class. `None` means NORMAL.
2541    pub async fn emit_with_admission(
2542        &self,
2543        body: Vec<u8>,
2544        admission_class: Option<AdmissionClass>,
2545    ) -> Result<(), SubcModuleError> {
2546        self.module_handle.validate_route(self.handle)?;
2547        if self.cancelled.is_cancelled() {
2548            return Ok(());
2549        }
2550        self.send_frame(
2551            FrameType::StreamData,
2552            data_flags().with_admission_class(admission_class.unwrap_or(AdmissionClass::Normal)),
2553            body,
2554        )
2555        .await
2556    }
2557
2558    /// Completes when the other side sends Cancel for this request or the route
2559    /// is torn down. An announced daemon upgrade lets already running data
2560    /// handlers finish without cancelling them at disconnect.
2561    pub fn cancelled(&self) -> WaitForCancellationFuture<'_> {
2562        self.cancelled.cancelled()
2563    }
2564
2565    /// Return a cloneable cancellation token for code that prefers token polling.
2566    pub fn cancellation_token(&self) -> CancellationToken {
2567        self.cancelled.clone()
2568    }
2569
2570    async fn send_frame(
2571        &self,
2572        frame_type: FrameType,
2573        flags: Flags,
2574        body: Vec<u8>,
2575    ) -> Result<(), SubcModuleError> {
2576        self.module_handle.validate_route(self.handle)?;
2577        let (frame_type, flags, body) = bounded_terminal(frame_type, flags, body)?;
2578        let frame = Frame::build_with_version(
2579            self.ver,
2580            frame_type,
2581            flags,
2582            self.handle.channel,
2583            self.handle.epoch,
2584            self.corr,
2585            body,
2586        )
2587        .map_err(SubcModuleError::FrameBuild)?;
2588        send_outbound(&self.egress, frame).await
2589    }
2590}
2591
2592/// Adds one to `counter` and returns the value it held before, or `None` once
2593/// the counter is at `u64::MAX`. Written as a compare-exchange loop rather than
2594/// with `fetch_update` (deprecated in Rust 1.99) or its replacement
2595/// `try_update` (absent before 1.99), so it builds on both toolchains.
2596fn checked_increment(counter: &AtomicU64) -> Option<u64> {
2597    let mut current = counter.load(Ordering::Relaxed);
2598    loop {
2599        let next = current.checked_add(1)?;
2600        match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) {
2601            Ok(previous) => return Some(previous),
2602            Err(actual) => current = actual,
2603        }
2604    }
2605}
2606
2607/// Route-bind request delivered on channel 0.
2608///
2609/// `#[non_exhaustive]` so it can gain fields in a later release without
2610/// breaking the handlers that read it. The SDK builds it from the daemon's
2611/// bind; code outside this crate (a module's own tests of its `on_bind`)
2612/// builds one with [`RouteBindRequest::new`] and the `with_*` setters.
2613#[derive(Debug, Clone)]
2614#[non_exhaustive]
2615pub struct RouteBindRequest {
2616    pub handle: RouteHandle,
2617    pub target: RouteTarget,
2618    pub identity: BindIdentity,
2619    pub principal: Option<Principal>,
2620    /// Consumer-declared reverse-request families and provider-contract
2621    /// capabilities for this bind. For example, `tool-result/v1` declares that a
2622    /// consumer understands the tool-provider content result format. This is an
2623    /// unverified declaration, not a privilege grant; providers treat an absent
2624    /// field as no declared capability. Known MCP method-family values today
2625    /// are "elicitation", "sampling", and "roots".
2626    pub consumer_capabilities: Option<Vec<String>>,
2627    /// The versions of provider roles the consumer declared it speaks on this
2628    /// route, role name to version (`{"tool-provider": "v1"}`), as the daemon
2629    /// forwarded them. A declaration, not a verified privilege: use it to pick
2630    /// which version of a role's wire shape to speak. `None` means the consumer
2631    /// declared none (a legacy consumer, or a daemon that predates the field);
2632    /// it is never an empty map.
2633    pub role_versions: Option<std::collections::BTreeMap<String, String>>,
2634    /// Opaque admission facts relayed by subc from its configured carrier.
2635    pub admission_facts: Option<serde_json::Value>,
2636    /// The daemon's stamp of the scope the route was admitted under (owner,
2637    /// ref, epoch, kind, attributes), copied from the bind unchanged. It is
2638    /// the daemon's, never the opener's. `attributes.on_behalf_of_agent` is
2639    /// attribution only, never authority, consent or access to per-agent handles.
2640    /// A target must declare `scope-on-behalf-of/v1` to receive that field. The stamp
2641    /// is fixed for the route's life: a change that revokes authority closes
2642    /// the route. `None` means the route was opened without a scope, or by a
2643    /// daemon that predates scopes.
2644    pub scope: Option<ScopeStamp>,
2645    /// The daemon's call mode, or the mode derived from `scope` when an older
2646    /// daemon omits it. Providers must refuse [`CallMode::Unknown`].
2647    pub call_mode: CallMode,
2648    /// The daemon's facts about the connection that opened this route, read
2649    /// from the same bind. Like the scope stamp, they are the daemon's, never
2650    /// the opener's.
2651    ///
2652    /// - `observed_peer` is sent only when this module's manifest lists
2653    ///   `observed-peer/v1` in `capabilities.provides`. It is then always
2654    ///   present, possibly with status `unobserved`; only an `observed` status
2655    ///   carries the peer's identity.
2656    /// - `operator_app` is sent only when the manifest lists `operator-app/v1`,
2657    ///   the daemon's operator-app policy for this platform is switched on,
2658    ///   and the daemon recognised the connection as an operator app when it
2659    ///   was made. It records that recognition at connection time. It is not
2660    ///   authority: a write on the person's behalf still asks the daemon with
2661    ///   `operator.confirm`. Released daemons switch this policy off, so they
2662    ///   never send it yet.
2663    ///
2664    /// - `caller` is sent only for `caller-attestation/v1`. Automatic provider
2665    ///   permission grants require a well-formed caller with claim `own` and `first_party: true`.
2666    ///   An absent or incomplete caller establishes no first-party mark.
2667    ///
2668    /// - `peer_build` is sent only for `peer-build/v1`, when the opener is
2669    ///   `reserved:callosum` and its phone build claim was exactly `production`.
2670    ///   Otherwise it is absent; the opener's raw `build_class` is never relayed.
2671    ///
2672    /// The peer keys decode together. If they don't decode, the bind still
2673    /// reaches [`ModuleHandler::on_bind`] with all absent and a warning is
2674    /// logged, so a handler that admits only on `operator_app` refuses it.
2675    pub peer: subc_protocol::peer::RouteBindPeer,
2676}
2677
2678impl RouteBindRequest {
2679    /// A bind with the members every bind has and every optional one absent:
2680    /// no principal, no consumer capabilities, no role versions, no admission
2681    /// facts and no scope. The call mode is classic. Set fields with the
2682    /// `with_*` methods.
2683    pub fn new(handle: RouteHandle, target: RouteTarget, identity: BindIdentity) -> Self {
2684        Self {
2685            handle,
2686            target,
2687            identity,
2688            principal: None,
2689            consumer_capabilities: None,
2690            role_versions: None,
2691            admission_facts: None,
2692            scope: None,
2693            call_mode: derive_call_mode(None),
2694            peer: subc_protocol::peer::RouteBindPeer::new(),
2695        }
2696    }
2697
2698    /// Set [`Self::peer`] to synthetic daemon facts, for testing a handler.
2699    /// It checks nothing: a real bind's facts come only from the daemon.
2700    pub fn with_peer(mut self, peer: subc_protocol::peer::RouteBindPeer) -> Self {
2701        self.peer = peer;
2702        self
2703    }
2704
2705    /// The daemon's attested phone build fact, present only for `peer-build/v1`.
2706    /// A supporting daemon sends only `production`, otherwise the key is absent.
2707    pub fn peer_build(&self) -> Option<&str> {
2708        self.peer.peer_build.as_deref()
2709    }
2710
2711    /// Set [`Self::principal`].
2712    pub fn with_principal(mut self, principal: Principal) -> Self {
2713        self.principal = Some(principal);
2714        self
2715    }
2716
2717    /// Set [`Self::consumer_capabilities`].
2718    pub fn with_consumer_capabilities(mut self, consumer_capabilities: Vec<String>) -> Self {
2719        self.consumer_capabilities = Some(consumer_capabilities);
2720        self
2721    }
2722
2723    /// Set [`Self::role_versions`].
2724    pub fn with_role_versions(
2725        mut self,
2726        role_versions: std::collections::BTreeMap<String, String>,
2727    ) -> Self {
2728        self.role_versions = Some(role_versions);
2729        self
2730    }
2731
2732    /// Set [`Self::admission_facts`].
2733    pub fn with_admission_facts(mut self, admission_facts: serde_json::Value) -> Self {
2734        self.admission_facts = Some(admission_facts);
2735        self
2736    }
2737
2738    /// Set [`Self::scope`] and derive its call mode. To override the derived
2739    /// mode, call [`Self::with_call_mode`] afterwards.
2740    pub fn with_scope(mut self, scope: ScopeStamp) -> Self {
2741        self.call_mode = derive_call_mode(Some(&scope));
2742        self.scope = Some(scope);
2743        self
2744    }
2745
2746    /// Set [`Self::call_mode`], overriding the mode derived from the scope.
2747    pub fn with_call_mode(mut self, call_mode: CallMode) -> Self {
2748        self.call_mode = call_mode;
2749        self
2750    }
2751}
2752
2753/// Decision returned by [`ModuleHandler::on_bind`].
2754#[derive(Debug, Clone)]
2755pub struct BindDecision {
2756    kind: BindDecisionKind,
2757}
2758
2759impl BindDecision {
2760    /// Accept the route.bind request.
2761    pub fn accept() -> Self {
2762        Self {
2763            kind: BindDecisionKind::Accept,
2764        }
2765    }
2766
2767    /// Reject the route.bind request with a typed Error frame.
2768    pub fn reject(code: impl Into<String>, message: impl Into<String>) -> Self {
2769        Self {
2770            kind: BindDecisionKind::Reject {
2771                code: code.into(),
2772                message: message.into(),
2773                detail: None,
2774            },
2775        }
2776    }
2777
2778    /// Reject the route.bind request with a typed Error frame whose `detail`
2779    /// carries the code's machine-readable fields, such as `bind_busy`'s
2780    /// `reason` and `retry_after_ms`. Pass a JSON object: a JSON `null` is
2781    /// dropped on the way, since an absent detail and a null one encode the
2782    /// same. The daemon relays the code, message and detail to the opener,
2783    /// so the detail must never hold secrets.
2784    pub fn reject_with_detail(
2785        code: impl Into<String>,
2786        message: impl Into<String>,
2787        detail: serde_json::Value,
2788    ) -> Self {
2789        Self {
2790            kind: BindDecisionKind::Reject {
2791                code: code.into(),
2792                message: message.into(),
2793                detail: Some(detail),
2794            },
2795        }
2796    }
2797}
2798
2799#[derive(Debug, Clone)]
2800enum BindDecisionKind {
2801    Accept,
2802    Reject {
2803        code: String,
2804        message: String,
2805        detail: Option<serde_json::Value>,
2806    },
2807}
2808
2809/// Run a module to completion. Reads `--subc <connection-file>` from args, uses
2810/// `SUBC_MODULE_ID` when set by the process that launched the module, connects,
2811/// authenticates, sends HELLO, waits for HELLO_ACK, then serves frames until
2812/// GOODBYE, clean EOF or a socket disconnect. How it ended is passed to
2813/// [`ModuleHandler::on_connection_end`].
2814/// A validated inherited registration channel replaces TCP when available.
2815/// It is never reconnected; its end exits the process after the lifecycle hook
2816/// and teardown, so the supervisor can restart the module with a new channel.
2817pub async fn serve<H>(manifest: ModuleManifest, handler: H) -> Result<(), SubcModuleError>
2818where
2819    H: ModuleHandler,
2820{
2821    ServeOptions::default().serve(manifest, handler).await
2822}
2823
2824/// A cooperative stop signal that can be created before connecting to the daemon.
2825/// Clones share the same, irreversible stop request. Await the serving future
2826/// after calling [`stop`](Self::stop); dropping it does not perform teardown.
2827#[derive(Clone, Debug, Default)]
2828pub struct ModuleStopHandle {
2829    token: CancellationToken,
2830}
2831
2832impl ModuleStopHandle {
2833    pub fn new() -> Self {
2834        Self::default()
2835    }
2836
2837    /// Stop the handshake or stop admitting requests, drain accepted work, send
2838    /// GOODBYE and flush. The serving future completes the teardown.
2839    pub fn stop(&self) {
2840        self.token.cancel();
2841    }
2842}
2843
2844/// Configuration for a module's connection lifecycle. Existing `serve*`
2845/// functions use the defaults; use these builder methods to customize serving.
2846#[derive(Clone, Debug)]
2847#[non_exhaustive]
2848pub struct ServeOptions {
2849    registration_channel: bool,
2850    prefix_child: bool,
2851    writer_drain_timeout: Duration,
2852    stop_handle: ModuleStopHandle,
2853    live_upgrade: bool,
2854    connection_file: Option<PathBuf>,
2855}
2856
2857impl Default for ServeOptions {
2858    fn default() -> Self {
2859        Self {
2860            writer_drain_timeout: DEFAULT_WRITER_DRAIN_TIMEOUT,
2861            registration_channel: false,
2862            prefix_child: false,
2863            stop_handle: ModuleStopHandle::new(),
2864            live_upgrade: false,
2865            connection_file: None,
2866        }
2867    }
2868}
2869
2870impl ServeOptions {
2871    /// Set the writer drain budget (default: two seconds). A module stop also
2872    /// gives in-flight handlers up to this long to finish before sending
2873    /// GOODBYE, then gives the writer its own budget to flush. Other connection
2874    /// ends cancel handlers immediately unless an upgrade was announced. Work still running at a drain
2875    /// deadline is aborted.
2876    ///
2877    /// Keep the combined handler and writer waits below the daemon's per-module
2878    /// stop budget: the daemon caps it at 25 seconds, and a module may be
2879    /// configured with less. Leave room for lifecycle hooks as well.
2880    pub fn with_writer_drain_timeout(mut self, timeout: Duration) -> Self {
2881        self.writer_drain_timeout = timeout;
2882        self
2883    }
2884
2885    /// Install a stop handle created before calling `serve` or `serve_with`,
2886    /// so a stop also interrupts connection establishment and HELLO.
2887    pub fn with_stop_handle(mut self, handle: ModuleStopHandle) -> Self {
2888        self.stop_handle = handle;
2889        self
2890    }
2891
2892    /// Serve using the same launch arguments and environment as [`serve`].
2893    pub async fn serve<H: ModuleHandler>(
2894        self,
2895        mut manifest: ModuleManifest,
2896        handler: H,
2897    ) -> Result<(), SubcModuleError> {
2898        let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2899        if let Some(module_id) = module_id_from_env()? {
2900            manifest.module_id = module_id;
2901        }
2902        self.serve_with(&connection_file, manifest, handler).await
2903    }
2904
2905    /// Serve with an explicit connection file and an unchanged manifest.
2906    pub async fn serve_with<H: ModuleHandler>(
2907        self,
2908        connection_file: &Path,
2909        manifest: ModuleManifest,
2910        handler: H,
2911    ) -> Result<(), SubcModuleError> {
2912        if let Some((_handle, future)) = self
2913            .serve_with_handle(connection_file, manifest, handler)
2914            .await?
2915        {
2916            future.await?;
2917        }
2918        Ok(())
2919    }
2920
2921    /// Connect and register using the same launch inputs as [`Self::serve`],
2922    /// returning a cloneable handle and the future that keeps the module serving.
2923    ///
2924    /// Reads `--subc <connection-file>` (or `--subc=<connection-file>`) from argv
2925    /// and overrides the manifest's module id with `SUBC_MODULE_ID` when present.
2926    /// Uses this options value's stop handle and writer drain timeout. A requested
2927    /// stop before registration completes returns `Ok(None)`; this is an expected
2928    /// outcome, not a connection error.
2929    ///
2930    /// The returned serve future **must be awaited or spawned**. A module can give
2931    /// the returned handle to its handler's shared state before starting that future.
2932    /// Spawn the serve future before slow startup work or awaiting control RPCs:
2933    /// it reads their replies and answers health and stop.
2934    pub async fn serve_from_env_with_handle<H: ModuleHandler>(
2935        self,
2936        mut manifest: ModuleManifest,
2937        handler: H,
2938    ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2939        let connection_file = parse_subc_arg(env::args_os().skip(1))?;
2940        if let Some(module_id) = module_id_from_env()? {
2941            manifest.module_id = module_id;
2942        }
2943        self.serve_with_handle(&connection_file, manifest, handler)
2944            .await
2945    }
2946
2947    /// Connect with an explicit connection file and an unchanged manifest,
2948    /// returning a cloneable handle and the future that keeps the module serving.
2949    ///
2950    /// Uses this options value's stop handle and writer drain timeout. A requested
2951    /// stop before registration completes returns `Ok(None)`; this is an expected
2952    /// outcome, not a connection error.
2953    ///
2954    /// The returned serve future **must be awaited or spawned**. A module can give
2955    /// the returned handle to its handler's shared state before starting that future.
2956    /// Spawn the serve future before slow startup work or awaiting control RPCs:
2957    /// it reads their replies and answers health and stop.
2958    pub async fn serve_with_handle<H: ModuleHandler>(
2959        self,
2960        connection_file: &Path,
2961        manifest: ModuleManifest,
2962        handler: H,
2963    ) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
2964        prepare_connection(connection_file, manifest, handler, self).await
2965    }
2966}
2967
2968/// Connect and register using the same launch inputs as [`serve`], returning a
2969/// cloneable handle and the future that keeps the module serving.
2970///
2971/// Reads `--subc <connection-file>` (or `--subc=<connection-file>`) from argv
2972/// and overrides the manifest's module id with `SUBC_MODULE_ID` when present.
2973/// Authentication, the launch-secret pipe, HELLO and their errors are identical
2974/// to [`serve`]. Unlike [`serve_with_handle`], the caller need not duplicate
2975/// argument parsing or launch-environment handling.
2976///
2977/// The returned serve future **must be awaited or spawned**. A module can give
2978/// the returned handle to its handler's shared state before starting that future,
2979/// so the handler can call [`ModuleHandle::confirm_operator`] or
2980/// [`ModuleHandle::set_ready`]. Spawn the serve future before slow startup work
2981/// or awaiting control RPCs: it reads their replies and answers health and stop.
2982pub async fn serve_from_env_with_handle<H>(
2983    manifest: ModuleManifest,
2984    handler: H,
2985) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
2986where
2987    H: ModuleHandler,
2988{
2989    ServeOptions::default()
2990        .serve_from_env_with_handle(manifest, handler)
2991        .await?
2992        .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
2993}
2994
2995/// Run a module with an explicit connection-file path. The manifest is sent as
2996/// provided; callers that need a nonstandard module id should set it before calling.
2997pub async fn serve_with<H>(
2998    connection_file: &Path,
2999    manifest: ModuleManifest,
3000    handler: H,
3001) -> Result<(), SubcModuleError>
3002where
3003    H: ModuleHandler,
3004{
3005    ServeOptions::default()
3006        .serve_with(connection_file, manifest, handler)
3007        .await
3008}
3009
3010/// Connect, register the module, and return a cloneable handle plus the future that
3011/// must be awaited or spawned to keep serving the connection.
3012pub async fn serve_with_handle<H>(
3013    connection_file: &Path,
3014    manifest: ModuleManifest,
3015    handler: H,
3016) -> Result<(ModuleHandle, ModuleServeFuture), SubcModuleError>
3017where
3018    H: ModuleHandler,
3019{
3020    ServeOptions::default()
3021        .serve_with_handle(connection_file, manifest, handler)
3022        .await?
3023        .ok_or(SubcModuleError::ConnectionClosedBeforeHelloAck)
3024}
3025
3026async fn prepare_connection<H: ModuleHandler>(
3027    connection_file: &Path,
3028    manifest: ModuleManifest,
3029    handler: H,
3030    mut options: ServeOptions,
3031) -> Result<Option<(ModuleHandle, ModuleServeFuture)>, SubcModuleError> {
3032    if options.live_upgrade {
3033        options.connection_file = Some(connection_file.to_owned());
3034    }
3035    options.registration_channel = registration::adopt(&manifest.module_id)?;
3036    let stream = tokio::select! {
3037        biased;
3038        () = options.stop_handle.token.cancelled() => return Ok(None),
3039        stream = async {
3040            let claim = if registration::supervised() && !options.registration_channel {
3041                registration::prefix_claim(&manifest.module_id).await
3042                    .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?
3043            } else {
3044                None
3045            };
3046            let mut stream = connect_to_subc(connection_file, options.registration_channel).await?;
3047            if let Some(claim) = claim {
3048                registration::present_claim(&mut stream, claim, AUTH_DEADLINE).await
3049                    .map_err(|error| registration::serve_claim_error(&manifest.module_id, error))?;
3050                options.prefix_child = true;
3051            }
3052            Ok::<_, SubcModuleError>(stream)
3053        } => stream?,
3054    };
3055    register_connection(stream, manifest, handler, options).await
3056}
3057
3058// Both real connections and the in-memory test stand-in run this lifecycle,
3059// including request cancellation, connection-end hooks and the writer drain.
3060#[cfg(any(test, feature = "test-support"))]
3061fn connection_serve_future<R, H>(
3062    read_half: R,
3063    tx: mpsc::Sender<Frame>,
3064    handler: Arc<H>,
3065    handle: ModuleHandle,
3066    writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3067) -> ModuleServeFuture
3068where
3069    R: AsyncRead + Unpin + Send + 'static,
3070    H: ModuleHandler,
3071{
3072    connection_serve_future_with_options(
3073        read_half,
3074        tx,
3075        handler,
3076        handle,
3077        writer,
3078        ServeOptions::default(),
3079        None,
3080    )
3081}
3082
3083async fn module_loop<R, H>(
3084    mut reader: R,
3085    egress: &mpsc::Sender<Frame>,
3086    handler: Arc<H>,
3087    module_handle: ModuleHandle,
3088    dispatcher: &RequestDispatcher,
3089    stop: &ModuleStopHandle,
3090) -> Result<ConnectionEnd, SubcModuleError>
3091where
3092    R: AsyncRead + Unpin,
3093    H: ModuleHandler,
3094{
3095    serve_frames(
3096        &mut reader,
3097        egress,
3098        &handler,
3099        &module_handle,
3100        dispatcher,
3101        stop,
3102    )
3103    .await
3104}
3105
3106async fn serve_frames<R, H>(
3107    reader: &mut R,
3108    egress: &mpsc::Sender<Frame>,
3109    handler: &Arc<H>,
3110    module_handle: &ModuleHandle,
3111    dispatcher: &RequestDispatcher,
3112    stop: &ModuleStopHandle,
3113) -> Result<ConnectionEnd, SubcModuleError>
3114where
3115    R: AsyncRead + Unpin,
3116    H: ModuleHandler,
3117{
3118    let shared = module_handle.shared();
3119    loop {
3120        let read = tokio::select! {
3121            biased;
3122            () = dispatcher.failed.cancelled() => return Err(dispatcher.take_failure().expect("failure signalled")),
3123            () = stop.token.cancelled() => return Ok(ConnectionEnd::Closed),
3124            () = shared.close_token.cancelled() => return Ok(ConnectionEnd::Closed),
3125            read = read_frame(reader) => read,
3126        };
3127        let frame = match read {
3128            Ok(Some(frame)) => frame,
3129            // Clean EOF: the daemon closed the connection.
3130            Ok(None) => return Ok(ConnectionEnd::Eof),
3131            // A killed daemon can close with FIN on Unix and RST on Windows.
3132            // Both end serving and run the same connection-end teardown hook.
3133            Err(FrameIoError::Io(error)) if is_disconnect(&error) => {
3134                return Ok(ConnectionEnd::Reset);
3135            }
3136            Err(err) => return Err(SubcModuleError::FrameIo(err)),
3137        };
3138        if !handle_frame(
3139            frame,
3140            egress,
3141            Arc::clone(handler),
3142            dispatcher.clone(),
3143            module_handle.clone(),
3144        )
3145        .await?
3146        {
3147            // handle_frame returns false only for a channel-0 GOODBYE.
3148            return Ok(ConnectionEnd::Goodbye);
3149        }
3150    }
3151}
3152
3153async fn handle_frame<H>(
3154    frame: Frame,
3155    egress: &mpsc::Sender<Frame>,
3156    handler: Arc<H>,
3157    dispatcher: RequestDispatcher,
3158    module_handle: ModuleHandle,
3159) -> Result<bool, SubcModuleError>
3160where
3161    H: ModuleHandler,
3162{
3163    if frame.header.channel != 0
3164        && !module_handle.validate_ingress(frame.header.channel, frame.header.epoch)?
3165    {
3166        return Ok(true);
3167    }
3168    match frame.header.ty {
3169        FrameType::Ping if frame.header.channel == 0 => {
3170            let pong = Frame::build_with_version(
3171                frame.header.ver,
3172                FrameType::Pong,
3173                frame.header.flags,
3174                0,
3175                0,
3176                frame.header.corr,
3177                Vec::new(),
3178            )
3179            .map_err(SubcModuleError::FrameBuild)?;
3180            send_outbound(egress, pong).await?;
3181            Ok(true)
3182        }
3183        FrameType::Goodbye if frame.header.channel == 0 => Ok(false),
3184        FrameType::Goodbye => {
3185            let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3186            if module_handle.remove_route(handle)? {
3187                cancel_handle(&dispatcher.in_flight, handle)?;
3188                handler.on_route_gone(&handle).await;
3189            }
3190            Ok(true)
3191        }
3192        FrameType::Response if frame.header.channel == 0 => {
3193            let _ = module_handle.handle_control_reply(frame);
3194            Ok(true)
3195        }
3196        FrameType::Error | FrameType::StreamData | FrameType::StreamEnd
3197            if frame.header.channel == 0 =>
3198        {
3199            let _ = module_handle.handle_control_reply(frame);
3200            Ok(true)
3201        }
3202        FrameType::Cancel => {
3203            handle_cancel(frame, &dispatcher.in_flight)?;
3204            Ok(true)
3205        }
3206        FrameType::Request if frame.header.channel == 0 => {
3207            handle_control_request(frame, egress, handler, dispatcher, module_handle.clone())
3208                .await?;
3209            Ok(true)
3210        }
3211        FrameType::Request => {
3212            spawn_data_request(frame, egress.clone(), handler, dispatcher, module_handle)?;
3213            Ok(true)
3214        }
3215        FrameType::Push if frame.header.channel == 0 => {
3216            if config::changed(&frame, &module_handle) {
3217                return Ok(true);
3218            }
3219            handle_control_push(&frame, handler, &dispatcher, &module_handle);
3220            Ok(true)
3221        }
3222        _ => Ok(true),
3223    }
3224}
3225
3226/// Dispatch known channel-0 commands without closing on newer commands.
3227fn handle_control_push<H>(
3228    frame: &Frame,
3229    handler: Arc<H>,
3230    dispatcher: &RequestDispatcher,
3231    module_handle: &ModuleHandle,
3232) where
3233    H: ModuleHandler,
3234{
3235    match serde_json::from_slice::<ModuleControlCommand>(&frame.body) {
3236        Ok(ModuleControlCommand::Draining {
3237            reason,
3238            deadline_ms,
3239        }) => {
3240            let accepting = matches!(
3241                serde_json::from_slice(&frame.body),
3242                Ok(subc_protocol::session::AcceptingDrainCommand::Draining {
3243                    accepting: true,
3244                    ..
3245                })
3246            );
3247            if !accepting {
3248                module_handle.fence_consumer_dials();
3249            }
3250            let started = spawn_draining_hook(
3251                handler,
3252                DrainNotice {
3253                    reason: sdk_route_close_reason(reason),
3254                    deadline: drain_deadline(deadline_ms),
3255                    accepting,
3256                },
3257                dispatcher,
3258            );
3259            dispatcher
3260                .draining_hooks
3261                .lock()
3262                .unwrap_or_else(|poisoned| poisoned.into_inner())
3263                .push(started);
3264        }
3265        Ok(ModuleControlCommand::Upgrading { reconnect_by_ms }) => {
3266            module_handle.announce_upgrade(reconnect_by_ms)
3267        }
3268        Err(error) => {
3269            if !dispatcher
3270                .undecodable_push_logged
3271                .swap(true, Ordering::Relaxed)
3272            {
3273                let op = serde_json::from_slice::<serde_json::Value>(&frame.body)
3274                    .ok()
3275                    .and_then(|body| body.get("op")?.as_str().map(str::to_string));
3276                tracing::warn!(
3277                    op = op.as_deref().unwrap_or("<none>"),
3278                    error = %error,
3279                    "ignoring a channel-0 push from subc that this SDK cannot decode; \
3280                     further undecodable pushes on this connection are ignored without logging"
3281                );
3282            }
3283        }
3284    }
3285}
3286
3287/// Run the drain hook on its own task, so a slow hook cannot stall the frame
3288/// reader. The returned receiver resolves once the hook has been polled for
3289/// the first time, i.e. has run up to its first await.
3290fn spawn_draining_hook<H>(
3291    handler: Arc<H>,
3292    notice: DrainNotice,
3293    dispatcher: &RequestDispatcher,
3294) -> oneshot::Receiver<()>
3295where
3296    H: ModuleHandler,
3297{
3298    let (started_tx, started_rx) = oneshot::channel();
3299    dispatcher.spawn(async move {
3300        let mut hook = handler.on_draining_notice(notice);
3301        let mut started_tx = Some(started_tx);
3302        std::future::poll_fn(|cx| {
3303            let poll = hook.as_mut().poll(cx);
3304            if let Some(started) = started_tx.take() {
3305                let _ = started.send(());
3306            }
3307            poll
3308        })
3309        .await;
3310    });
3311    started_rx
3312}
3313
3314/// Convert the wire reason into this crate's public [`RouteCloseReason`], via
3315/// its wire name so a reason this crate has no variant for arrives as
3316/// [`RouteCloseReason::Unknown`] rather than being dropped.
3317fn sdk_route_close_reason(reason: subc_protocol::RouteCloseReason) -> RouteCloseReason {
3318    match serde_json::to_value(reason) {
3319        Ok(serde_json::Value::String(wire)) => RouteCloseReason::from_wire(&wire),
3320        _ => RouteCloseReason::Unknown(format!("{reason:?}")),
3321    }
3322}
3323
3324/// The drain deadline as a wall-clock time. A value too large for this
3325/// platform's clock becomes "now": the deadline is a "no later than", so
3326/// reading it early is the safe direction.
3327fn drain_deadline(deadline_ms: u64) -> SystemTime {
3328    UNIX_EPOCH
3329        .checked_add(Duration::from_millis(deadline_ms))
3330        .unwrap_or_else(SystemTime::now)
3331}
3332
3333fn spawn_data_request<H>(
3334    frame: Frame,
3335    egress: mpsc::Sender<Frame>,
3336    handler: Arc<H>,
3337    dispatcher: RequestDispatcher,
3338    module_handle: ModuleHandle,
3339) -> Result<(), SubcModuleError>
3340where
3341    H: ModuleHandler,
3342{
3343    let handle = module_handle.route_handle(frame.header.channel, frame.header.epoch);
3344    let corr = frame.header.corr;
3345    let cancellation = CancellationToken::new();
3346    {
3347        let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3348        guard.insert((handle.channel, handle.epoch, corr), cancellation.clone());
3349    }
3350
3351    let ctx = RequestCtx {
3352        handle,
3353        corr,
3354        ver: frame.header.ver,
3355        egress,
3356        module_handle,
3357        cancelled: cancellation,
3358        binary_reply: Arc::new(AtomicBool::new(false)),
3359        request_flags: frame.header.flags,
3360        request_body: Arc::from(frame.body.as_slice()),
3361        open: Arc::new(tokio::sync::Mutex::new(true)),
3362    };
3363    let body = frame.body;
3364    let in_flight = Arc::clone(&dispatcher.in_flight);
3365    // The module's classifier picks the pool from the raw body before the
3366    // request takes a slot; the SDK passes the body on without interpreting it.
3367    let (pool, op) = dispatcher.pools.classify(&body);
3368    let pool = pool.clone();
3369    let wait = pool.start_waiting((handle.channel, handle.epoch, corr));
3370    dispatcher.clone().spawn_data(async move {
3371        let waiting = WaitingRequest {
3372            op,
3373            channel: handle.channel,
3374            corr,
3375        };
3376        let permit = match wait_for_permit(&pool, wait, waiting, &ctx.cancelled).await {
3377            PermitWaitOutcome::Acquired(permit) => Some(permit),
3378            // Cancelled while waiting: answered below at once, without a
3379            // slot, rather than after one frees.
3380            PermitWaitOutcome::Cancelled => None,
3381            PermitWaitOutcome::Closed => {
3382                // A closed dispatcher means connection teardown will release every route credit.
3383                dispatcher
3384                    .undelivered_replies
3385                    .fetch_add(1, Ordering::Relaxed);
3386                if let Ok(mut guard) = in_flight.lock() {
3387                    guard.remove(&(handle.channel, handle.epoch, corr));
3388                }
3389                return;
3390            }
3391        };
3392        // A slot and the cancellation can become ready together and the slot
3393        // is taken first, so check again before running the handler.
3394        let outcome = if permit.is_none() || ctx.cancelled.is_cancelled() {
3395            Ok(HandlerOutcome::Error {
3396                code: "cancelled".to_string(),
3397                message: "request cancelled".to_string(),
3398            })
3399        } else {
3400            catch_handler_panic(async { handler.handle(ctx.clone(), body).await }).await
3401        };
3402        let panicked = outcome.is_err();
3403        let outcome = outcome.unwrap_or_else(|()| HandlerOutcome::Error {
3404            code: "internal".to_string(),
3405            message: "module handler panicked".to_string(),
3406        });
3407        match send_handler_outcome(&ctx, outcome).await {
3408            // A route GOODBYE/rebind withdraws the reply destination. Dropping
3409            // that late terminal is intentional; an egress failure on a live
3410            // route is not. A panic remains fatal even if its route is gone.
3411            Err(SubcModuleError::StaleRouteHandle(_)) if !panicked => {}
3412            Err(error) => {
3413                if matches!(error, SubcModuleError::WriterClosed) {
3414                    dispatcher
3415                        .undelivered_replies
3416                        .fetch_add(1, Ordering::Relaxed);
3417                }
3418                dispatcher.fail(error);
3419            }
3420            Ok(()) if panicked => dispatcher.fail(SubcModuleError::HandlerPanic),
3421            Ok(()) => {}
3422        }
3423        if let Ok(mut guard) = in_flight.lock() {
3424            guard.remove(&(handle.channel, handle.epoch, corr));
3425        }
3426    });
3427    Ok(())
3428}
3429
3430fn spawn_health_request<H>(
3431    frame: Frame,
3432    egress: mpsc::Sender<Frame>,
3433    handler: Arc<H>,
3434    dispatcher: RequestDispatcher,
3435) -> Result<(), SubcModuleError>
3436where
3437    H: ModuleHandler,
3438{
3439    let channel = frame.header.channel;
3440    let epoch = frame.header.epoch;
3441    let corr = frame.header.corr;
3442    let ver = frame.header.ver;
3443    let cancellation = CancellationToken::new();
3444    {
3445        let mut guard = lock_in_flight(&dispatcher.in_flight)?;
3446        guard.insert((channel, epoch, corr), cancellation.clone());
3447    }
3448
3449    let in_flight = Arc::clone(&dispatcher.in_flight);
3450    dispatcher.clone().spawn(async move {
3451        // Health must not queue behind the data work whose liveness it reports.
3452        // Registration and cancellation still use the same in-flight registry.
3453        if !cancellation.is_cancelled() {
3454            let result = async {
3455                let report = catch_handler_panic(async { handler.health().await }).await;
3456                let panicked = report.is_err();
3457                let (ty, body) = match report {
3458                    Ok(report) => (
3459                        FrameType::Response,
3460                        serde_json::to_vec(&ModuleControlResponse::from(
3461                            dispatcher.fold_health(report),
3462                        ))?,
3463                    ),
3464                    Err(()) => (
3465                        FrameType::Error,
3466                        serde_json::to_vec(&ErrorBody::new("internal", "module handler panicked"))?,
3467                    ),
3468                };
3469                let (ty, flags, body) = bounded_terminal(ty, control_flags(), body)?;
3470                let frame = Frame::build_with_version(ver, ty, flags, channel, epoch, corr, body)
3471                    .map_err(SubcModuleError::FrameBuild)?;
3472                send_outbound(&egress, frame).await?;
3473                if panicked {
3474                    return Err(SubcModuleError::HandlerPanic);
3475                }
3476                Ok(())
3477            }
3478            .await;
3479            if let Err(error) = result {
3480                if matches!(error, SubcModuleError::WriterClosed) {
3481                    dispatcher
3482                        .undelivered_replies
3483                        .fetch_add(1, Ordering::Relaxed);
3484                }
3485                dispatcher.fail(error);
3486            }
3487        }
3488        if let Ok(mut guard) = in_flight.lock() {
3489            guard.remove(&(channel, epoch, corr));
3490        }
3491    });
3492    Ok(())
3493}
3494
3495async fn send_handler_outcome(
3496    ctx: &RequestCtx,
3497    outcome: HandlerOutcome,
3498) -> Result<(), SubcModuleError> {
3499    // Held until the terminal frame is queued; see `RequestCtx::open`.
3500    let mut open = ctx.open.lock().await;
3501    *open = false;
3502    match outcome {
3503        HandlerOutcome::Response(body) => {
3504            let flags = Flags::new(
3505                ctx.binary_reply.load(Ordering::Relaxed),
3506                Priority::Interactive,
3507                false,
3508            );
3509            ctx.send_frame(FrameType::Response, flags, body).await
3510        }
3511        HandlerOutcome::Error { code, message } => {
3512            let body = serde_json::to_vec(&ErrorBody::new(code, message))
3513                .map_err(SubcModuleError::Json)?;
3514            ctx.send_frame(FrameType::Error, data_flags(), body).await
3515        }
3516        HandlerOutcome::ErrorWithDetail {
3517            code,
3518            message,
3519            detail,
3520        } => {
3521            let body = serde_json::to_vec(&ErrorBody::new(code, message).with_detail(detail))
3522                .map_err(SubcModuleError::Json)?;
3523            ctx.send_frame(FrameType::Error, data_flags(), body).await
3524        }
3525        HandlerOutcome::Streamed => {
3526            ctx.send_frame(FrameType::StreamEnd, data_flags(), Vec::new())
3527                .await
3528        }
3529    }
3530}
3531
3532/// Catch unwinds across every poll, including construction of the handler future.
3533/// Never expose the panic payload on the wire: it may contain request data.
3534async fn catch_handler_panic<F: Future>(future: F) -> Result<F::Output, ()> {
3535    let mut future = std::pin::pin!(future);
3536    std::future::poll_fn(
3537        |cx| match catch_unwind(AssertUnwindSafe(|| future.as_mut().poll(cx))) {
3538            Ok(poll) => poll.map(Ok),
3539            Err(_) => std::task::Poll::Ready(Err(())),
3540        },
3541    )
3542    .await
3543}
3544
3545fn bounded_terminal(
3546    ty: FrameType,
3547    flags: Flags,
3548    body: Vec<u8>,
3549) -> Result<(FrameType, Flags, Vec<u8>), SubcModuleError> {
3550    let size = subc_protocol::HEADER_LEN + body.len();
3551    let limit = subc_protocol::MAX_DELIVERED_FRAME_LEN;
3552    if matches!(ty, FrameType::Response | FrameType::Error) && size > limit {
3553        let body = serde_json::to_vec(
3554            &ErrorBody::new("frame_too_large", "module reply exceeds frame limit")
3555                .with_detail(serde_json::json!({ "size": size, "limit": limit })),
3556        )?;
3557        // Keep the original priority: a control-plane reply stays passive.
3558        return Ok((FrameType::Error, flags, body));
3559    }
3560    Ok((ty, flags, body))
3561}
3562
3563fn handle_cancel(frame: Frame, in_flight: &InFlight) -> Result<(), SubcModuleError> {
3564    let guard = lock_in_flight(in_flight)?;
3565    if let Some(cancellation) =
3566        guard.get(&(frame.header.channel, frame.header.epoch, frame.header.corr))
3567    {
3568        cancellation.cancel();
3569    }
3570    Ok(())
3571}
3572
3573fn cancel_handle(in_flight: &InFlight, handle: RouteHandle) -> Result<(), SubcModuleError> {
3574    let cancelled = {
3575        let mut guard = lock_in_flight(in_flight)?;
3576        let keys = guard
3577            .keys()
3578            .copied()
3579            .filter(|(channel, epoch, _)| *channel == handle.channel && *epoch == handle.epoch)
3580            .collect::<Vec<_>>();
3581        keys.into_iter()
3582            .filter_map(|key| guard.remove(&key))
3583            .collect::<Vec<_>>()
3584    };
3585    for cancellation in cancelled {
3586        cancellation.cancel();
3587    }
3588    Ok(())
3589}
3590
3591async fn handle_control_request<H>(
3592    frame: Frame,
3593    egress: &mpsc::Sender<Frame>,
3594    handler: Arc<H>,
3595    dispatcher: RequestDispatcher,
3596    module_handle: ModuleHandle,
3597) -> Result<(), SubcModuleError>
3598where
3599    H: ModuleHandler,
3600{
3601    if control_ops::request(
3602        &frame,
3603        egress,
3604        Arc::clone(&handler),
3605        &dispatcher,
3606        &module_handle,
3607    )
3608    .await?
3609    {
3610        return Ok(());
3611    }
3612    if config::review(
3613        &frame,
3614        egress,
3615        Arc::clone(&handler),
3616        &dispatcher,
3617        &module_handle,
3618    ) {
3619        return Ok(());
3620    }
3621    // A control request this SDK cannot decode (most likely a newer daemon's
3622    // field or operation) is refused on its own correlation id, and the
3623    // connection stays up. Returning the decode error would end the serve loop,
3624    // so one unknown field on one route.bind would stop the whole module, and
3625    // the next such bind after its respawn would stop it again.
3626    let request = match serde_json::from_slice::<ModuleControlRequest>(&frame.body) {
3627        Ok(request) => request,
3628        Err(error) => {
3629            let body = serde_json::to_vec(&ErrorBody::new(
3630                "invalid_request",
3631                format!("control request could not be decoded by this module: {error}"),
3632            ))
3633            .map_err(SubcModuleError::Json)?;
3634            let refusal = Frame::build_with_version(
3635                frame.header.ver,
3636                FrameType::Error,
3637                control_flags(),
3638                0,
3639                0,
3640                frame.header.corr,
3641                body,
3642            )
3643            .map_err(SubcModuleError::FrameBuild)?;
3644            send_outbound(egress, refusal).await?;
3645            return Ok(());
3646        }
3647    };
3648    match request {
3649        ModuleControlRequest::RouteBind {
3650            route_channel,
3651            epoch,
3652            target,
3653            identity,
3654            principal,
3655            consumer_capabilities,
3656            role_versions,
3657            admission_facts,
3658            scope,
3659            call_mode,
3660        } => {
3661            // Implicit-replace rule (wire spec 3.3.0): the daemon never rebinds a live
3662            // channel, but its route-gone GOODBYE to modules is best-effort, so a bind
3663            // can arrive for a channel this endpoint still believes installed. A
3664            // strictly higher epoch proves the daemon freed the old binding: tear the
3665            // stale install down locally and proceed. Equal or lower epoch is a
3666            // protocol violation the daemon cannot produce: reject the bind.
3667            if let Some(stale) = module_handle.installed_route(route_channel)? {
3668                if epoch <= stale.epoch {
3669                    let body = serde_json::to_vec(&ErrorBody::new(
3670                        "route_rejected",
3671                        format!(
3672                            "route.bind epoch {epoch} does not supersede installed epoch {} on channel {route_channel}",
3673                            stale.epoch
3674                        ),
3675                    ))
3676                    .map_err(SubcModuleError::Json)?;
3677                    let reject = Frame::build_with_version(
3678                        frame.header.ver,
3679                        FrameType::Error,
3680                        control_flags(),
3681                        0,
3682                        0,
3683                        frame.header.corr,
3684                        body,
3685                    )
3686                    .map_err(SubcModuleError::FrameBuild)?;
3687                    send_outbound(egress, reject).await?;
3688                    return Ok(());
3689                }
3690                if module_handle.remove_route(stale)? {
3691                    cancel_handle(&dispatcher.in_flight, stale)?;
3692                    handler.on_route_gone(&stale).await;
3693                }
3694            }
3695            let handle = module_handle.route_handle(route_channel, epoch);
3696            // The peer keys sit beside the bind's members in the same body.
3697            // They decode as one value: if any is malformed all read as
3698            // absent, and the bind still goes to `on_bind`, which decides.
3699            let peer =
3700                match serde_json::from_slice::<subc_protocol::peer::RouteBindPeer>(&frame.body) {
3701                    Ok(peer) => peer,
3702                    Err(error) => {
3703                        tracing::warn!(
3704                            channel = route_channel,
3705                            epoch,
3706                            %error,
3707                            "route.bind peer keys did not decode; treating them as absent"
3708                        );
3709                        subc_protocol::peer::RouteBindPeer::new()
3710                    }
3711                };
3712            let req = RouteBindRequest {
3713                handle,
3714                target,
3715                identity,
3716                principal,
3717                consumer_capabilities,
3718                role_versions,
3719                admission_facts,
3720                call_mode: call_mode.unwrap_or_else(|| derive_call_mode(scope.as_ref())),
3721                scope,
3722                peer,
3723            };
3724            let decision = handler.on_bind(&req).await;
3725            match decision.kind {
3726                BindDecisionKind::Accept => {
3727                    let response = match serde_json::to_vec(&ModuleControlResponse::RouteBindAck {})
3728                        .map_err(SubcModuleError::Json)
3729                        .and_then(|body| {
3730                            Frame::build_with_version(
3731                                frame.header.ver,
3732                                FrameType::Response,
3733                                control_flags(),
3734                                0,
3735                                0,
3736                                frame.header.corr,
3737                                body,
3738                            )
3739                            .map_err(SubcModuleError::FrameBuild)
3740                        }) {
3741                        Ok(response) => response,
3742                        Err(err) => {
3743                            handler.on_route_gone(&handle).await;
3744                            return Err(err);
3745                        }
3746                    };
3747                    if let Err(err) = send_outbound(egress, response).await {
3748                        handler.on_route_gone(&handle).await;
3749                        return Err(err);
3750                    }
3751                    if let Err(err) = module_handle.install_route(handle) {
3752                        handler.on_route_gone(&handle).await;
3753                        return Err(err);
3754                    }
3755                    handler.on_bound(&handle).await;
3756                }
3757                BindDecisionKind::Reject {
3758                    code,
3759                    message,
3760                    detail,
3761                } => {
3762                    let body = match detail {
3763                        Some(detail) => ErrorBody::new(code, message).with_detail(detail),
3764                        None => ErrorBody::new(code, message),
3765                    };
3766                    let result = serde_json::to_vec(&body)
3767                        .map_err(SubcModuleError::Json)
3768                        .and_then(|body| {
3769                            Frame::build_with_version(
3770                                frame.header.ver,
3771                                FrameType::Error,
3772                                control_flags(),
3773                                0,
3774                                0,
3775                                frame.header.corr,
3776                                body,
3777                            )
3778                            .map_err(SubcModuleError::FrameBuild)
3779                        });
3780                    let result = match result {
3781                        Ok(response) => send_outbound(egress, response).await,
3782                        Err(err) => Err(err),
3783                    };
3784                    handler.on_route_gone(&handle).await;
3785                    result?;
3786                }
3787            }
3788        }
3789        ModuleControlRequest::HealthCheck {} => {
3790            spawn_health_request(frame, egress.clone(), handler, dispatcher)?;
3791        }
3792    }
3793    Ok(())
3794}
3795
3796async fn expect_hello_ack<R>(reader: &mut R) -> Result<ModuleHelloAckBody, SubcModuleError>
3797where
3798    R: AsyncRead + Unpin,
3799{
3800    let Some(frame) = read_frame(reader).await.map_err(SubcModuleError::FrameIo)? else {
3801        return Err(SubcModuleError::ConnectionClosedBeforeHelloAck);
3802    };
3803    match frame.header.ty {
3804        FrameType::HelloAck => serde_json::from_slice(&frame.body).map_err(SubcModuleError::Json),
3805        FrameType::Error => {
3806            let body =
3807                serde_json::from_slice::<ErrorBody>(&frame.body).map_err(SubcModuleError::Json)?;
3808            Err(SubcModuleError::HelloRejected { body })
3809        }
3810        ty => Err(SubcModuleError::UnexpectedHelloAck { ty }),
3811    }
3812}
3813
3814/// Owned byte transport for a module connection, before or after authentication.
3815pub trait ModuleStream: AsyncRead + AsyncWrite + Unpin + Send {}
3816impl<T: AsyncRead + AsyncWrite + Unpin + Send> ModuleStream for T {}
3817
3818async fn connect_to_subc(
3819    connection_file_path: &Path,
3820    registration_channel: bool,
3821) -> Result<Box<dyn ModuleStream>, SubcModuleError> {
3822    let conn = connection_file::read_for_client(connection_file_path).map_err(|source| {
3823        SubcModuleError::ConnectionFile {
3824            path: connection_file_path.to_path_buf(),
3825            source,
3826        }
3827    })?;
3828    if let Some(mut stream) = if registration_channel {
3829        registration::take_stream()?
3830    } else {
3831        None
3832    } {
3833        authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3834            .await
3835            .map_err(|source| SubcModuleError::Auth {
3836                path: connection_file_path.to_path_buf(),
3837                endpoint: "registration channel".into(),
3838                source,
3839            })?;
3840        return Ok(stream);
3841    }
3842    let endpoint = conn
3843        .endpoints
3844        .first()
3845        .ok_or_else(|| SubcModuleError::NoEndpoint {
3846            path: connection_file_path.to_path_buf(),
3847        })?;
3848    let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
3849    let mut stream = connect_endpoint(&endpoint.host, endpoint.port)
3850        .await
3851        .map_err(|source| SubcModuleError::Connect {
3852            path: connection_file_path.to_path_buf(),
3853            endpoint: endpoint_label.clone(),
3854            source,
3855        })?;
3856    // This socket carries the module's replies back to the daemon, so Nagle here
3857    // delays every response rather than every request -- the same cost on the
3858    // return leg. Both ends of the hop have to disable it for either to help.
3859    //
3860    // The result is deliberately dropped rather than logged: this crate takes no
3861    // logging dependency, and the only ways setting a socket option on a
3862    // just-connected stream fail leave the socket unusable, which the handshake on
3863    // the very next line reports as a typed Auth error. Swallowing it here would
3864    // hide nothing that stays hidden.
3865    let _ = stream.set_nodelay(true);
3866    authenticate_client(&mut stream, &conn, AUTH_DEADLINE)
3867        .await
3868        .map_err(|source| SubcModuleError::Auth {
3869            path: connection_file_path.to_path_buf(),
3870            endpoint: endpoint_label,
3871            source,
3872        })?;
3873    Ok(Box::new(stream))
3874}
3875
3876async fn connect_endpoint(host: &str, port: u16) -> io::Result<TcpStream> {
3877    let host = host
3878        .strip_prefix('[')
3879        .and_then(|h| h.strip_suffix(']'))
3880        .unwrap_or(host);
3881    TcpStream::connect((host, port)).await
3882}
3883
3884async fn send_goodbye(tx: &mpsc::Sender<Frame>) -> Result<(), SubcModuleError> {
3885    let frame = Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new())
3886        .map_err(SubcModuleError::FrameBuild)?;
3887    send_outbound(tx, frame).await
3888}
3889
3890fn is_disconnect(error: &io::Error) -> bool {
3891    matches!(
3892        error.kind(),
3893        io::ErrorKind::ConnectionReset
3894            | io::ErrorKind::ConnectionAborted
3895            | io::ErrorKind::BrokenPipe
3896    )
3897}
3898
3899fn writer_ended(
3900    result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3901) -> SubcModuleError {
3902    match result {
3903        Ok(Ok(())) => SubcModuleError::WriterClosed,
3904        Ok(Err(error)) => SubcModuleError::FrameIo(error.error),
3905        Err(error) => SubcModuleError::WriterTask(error),
3906    }
3907}
3908
3909fn writer_connection_end(
3910    result: Result<Result<(), WriterFailure>, tokio::task::JoinError>,
3911) -> Result<ConnectionEnd, SubcModuleError> {
3912    match writer_ended(result) {
3913        SubcModuleError::FrameIo(FrameIoError::Io(error)) if is_disconnect(&error) => {
3914            Ok(ConnectionEnd::Reset)
3915        }
3916        error => Err(error),
3917    }
3918}
3919
3920async fn finish_writer(
3921    mut writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3922    deadline: Instant,
3923) -> (Result<(), SubcModuleError>, usize) {
3924    match timeout_at(deadline, &mut writer).await {
3925        Ok(Ok(Ok(()))) => (Ok(()), 0),
3926        Ok(Ok(Err(failure))) => (
3927            Err(SubcModuleError::FrameIo(failure.error)),
3928            failure.undelivered_replies,
3929        ),
3930        Ok(Err(error)) => (Err(SubcModuleError::WriterTask(error)), 0),
3931        Err(_) => {
3932            writer.abort();
3933            let _ = writer.await;
3934            (Ok(()), 0)
3935        }
3936    }
3937}
3938
3939struct WriterFailure {
3940    error: FrameIoError,
3941    undelivered_replies: usize,
3942}
3943
3944/// [`finish_writer`] for a connection the module ends itself: once the writer
3945/// has flushed and shut down the sending side, drain the reader as
3946/// [`drain_until_peer_closes`] describes. A writer that failed means the socket
3947/// is already broken, so there is nothing to drain.
3948async fn finish_writer_and_drain<R>(
3949    writer: tokio::task::JoinHandle<Result<(), WriterFailure>>,
3950    reader: &mut R,
3951    deadline: Instant,
3952) -> (Result<(), SubcModuleError>, usize)
3953where
3954    R: AsyncRead + Unpin,
3955{
3956    let flushed = finish_writer(writer, deadline).await;
3957    if flushed.0.is_ok() {
3958        drain_until_peer_closes(reader, deadline).await;
3959    }
3960    flushed
3961}
3962
3963/// Orderly close for a connection the module ends itself (a stop, an internal
3964/// close or a module-side error), called once the writer has flushed its last
3965/// frame and shut down the sending side.
3966///
3967/// Closing a TCP socket while received bytes are still unread makes the OS
3968/// send a reset (RST) instead of an orderly FIN. Linux and Windows do this;
3969/// where an OS does not, the drain below only waits for a close that comes
3970/// anyway. A daemon that receives the reset can fail its next read with
3971/// `ConnectionReset` and lose data it had not read yet, including the module's
3972/// GOODBYE, so a planned stop would look like a crash. Frames the daemon sent
3973/// after the module stopped reading (a PING, a request, its own GOODBYE) are
3974/// exactly such unread bytes. So keep reading and discarding until the daemon
3975/// closes its side, which it does once it reads the module's FIN.
3976///
3977/// `deadline` is the writer drain deadline, so a daemon that never closes
3978/// cannot hold the stop past the drain budget. Read errors end the drain: the
3979/// socket is already broken and nothing is left to protect.
3980async fn drain_until_peer_closes<R>(reader: &mut R, deadline: Instant)
3981where
3982    R: AsyncRead + Unpin,
3983{
3984    if Instant::now() >= deadline {
3985        return;
3986    }
3987    let mut discard = [0u8; 4096];
3988    let _ = timeout_at(deadline, async {
3989        while let Ok(read) = reader.read(&mut discard).await {
3990            if read == 0 {
3991                break;
3992            }
3993        }
3994    })
3995    .await;
3996}
3997
3998fn is_reply(frame: &Frame) -> bool {
3999    matches!(
4000        frame.header.ty,
4001        FrameType::Response | FrameType::Error | FrameType::StreamEnd
4002    )
4003}
4004
4005async fn drain_writer<W>(write_half: W, mut rx: mpsc::Receiver<Frame>) -> Result<(), WriterFailure>
4006where
4007    W: AsyncWrite + Unpin,
4008{
4009    let mut writer = BufWriter::new(write_half);
4010    let mut pending_replies = 0;
4011    let result = async {
4012        while let Some(frame) = rx.recv().await {
4013            pending_replies += usize::from(is_reply(&frame));
4014            write_frame(&mut writer, &frame).await?;
4015            while let Ok(frame) = rx.try_recv() {
4016                pending_replies += usize::from(is_reply(&frame));
4017                write_frame(&mut writer, &frame).await?;
4018            }
4019            writer.flush().await.map_err(FrameIoError::Io)?;
4020            pending_replies = 0;
4021        }
4022        writer.flush().await.map_err(FrameIoError::Io)?;
4023        // Every sender is gone, so nothing more will be written: shut down the
4024        // sending side so the daemon reads a FIN (EOF) right after the last
4025        // frame, typically the module's GOODBYE. The socket stays open for
4026        // reading, which `drain_until_peer_closes` relies on. When the daemon
4027        // ended the connection first, this sends the same FIN that dropping
4028        // the socket would. A failure here only means the socket is already
4029        // broken; whatever was flushed has been handed to the OS, so it is
4030        // not an undelivered-frame error.
4031        let _ = writer.shutdown().await;
4032        Ok(())
4033    }
4034    .await;
4035    result.map_err(|error| {
4036        rx.close();
4037        while let Ok(frame) = rx.try_recv() {
4038            pending_replies += usize::from(is_reply(&frame));
4039        }
4040        WriterFailure {
4041            error,
4042            undelivered_replies: pending_replies,
4043        }
4044    })
4045}
4046
4047async fn send_outbound(egress: &mpsc::Sender<Frame>, frame: Frame) -> Result<(), SubcModuleError> {
4048    egress
4049        .send(frame)
4050        .await
4051        .map_err(|_| SubcModuleError::WriterClosed)
4052}
4053
4054fn parse_subc_arg(args: impl IntoIterator<Item = OsString>) -> Result<PathBuf, SubcModuleError> {
4055    let mut args = args.into_iter();
4056    while let Some(arg) = args.next() {
4057        if arg == "--subc" {
4058            let value = args.next().ok_or(SubcModuleError::MissingSubcValue)?;
4059            return Ok(PathBuf::from(value));
4060        }
4061        if let Some(raw) = arg.to_str().and_then(|arg| arg.strip_prefix("--subc=")) {
4062            if raw.is_empty() {
4063                return Err(SubcModuleError::MissingSubcValue);
4064            }
4065            return Ok(PathBuf::from(raw));
4066        }
4067    }
4068    Err(SubcModuleError::MissingSubcArg)
4069}
4070
4071fn module_id_from_env() -> Result<Option<String>, SubcModuleError> {
4072    match env::var(SUBC_MODULE_ID_ENV) {
4073        Ok(value) if !value.trim().is_empty() => Ok(Some(value)),
4074        Ok(_) => Err(SubcModuleError::EmptyModuleIdEnv),
4075        Err(env::VarError::NotPresent) => Ok(None),
4076        Err(env::VarError::NotUnicode(value)) => {
4077            Err(SubcModuleError::NonUnicodeModuleIdEnv { value })
4078        }
4079    }
4080}
4081
4082fn lock_in_flight(
4083    in_flight: &InFlight,
4084) -> Result<std::sync::MutexGuard<'_, HashMap<RequestKey, CancellationToken>>, SubcModuleError> {
4085    in_flight
4086        .lock()
4087        .map_err(|_| SubcModuleError::InFlightPoisoned)
4088}
4089
4090fn control_flags() -> Flags {
4091    Flags::new(false, Priority::Passive, false)
4092}
4093
4094fn data_flags() -> Flags {
4095    Flags::new(false, Priority::Interactive, false)
4096}
4097
4098#[derive(Debug)]
4099#[non_exhaustive]
4100pub enum SubcModuleError {
4101    /// A module declared a malformed, duplicate or SDK-owned control operation.
4102    InvalidControlOp(String),
4103    /// A daemon reused an outstanding channel-0 request's correlation.
4104    DuplicateControlCorrelation(u64),
4105    RegistrationChannel(io::Error),
4106    MissingSubcArg,
4107    MissingSubcValue,
4108    EmptyModuleIdEnv,
4109    NonUnicodeModuleIdEnv {
4110        value: OsString,
4111    },
4112    ConnectionFile {
4113        path: PathBuf,
4114        source: ConnectionFileError,
4115    },
4116    NoEndpoint {
4117        path: PathBuf,
4118    },
4119    Connect {
4120        path: PathBuf,
4121        endpoint: String,
4122        source: io::Error,
4123    },
4124    Auth {
4125        path: PathBuf,
4126        endpoint: String,
4127        source: AuthError,
4128    },
4129    FrameIo(FrameIoError),
4130    FrameBuild(FrameBuildError),
4131    Json(serde_json::Error),
4132    WriterClosed,
4133    /// A request handler panicked. Its payload is never sent to the daemon.
4134    HandlerPanic,
4135    StaleRouteHandle(RouteHandle),
4136    ConnectionTokenExhausted,
4137    WriterTask(tokio::task::JoinError),
4138    InFlightPoisoned,
4139    ConnectionClosedBeforeHelloAck,
4140    UnexpectedHelloAck {
4141        ty: FrameType,
4142    },
4143    HelloRejected {
4144        body: ErrorBody,
4145    },
4146    /// The descriptor named for the launch nonce could not be read. HELLO is
4147    /// not sent without it, and the environment copy is not tried instead.
4148    LaunchNonce(launch_nonce::LaunchNonceError),
4149    /// [`RequestCtx::push`] after the request was cancelled or answered.
4150    /// Nothing was sent.
4151    RequestEnded,
4152}
4153
4154impl fmt::Display for SubcModuleError {
4155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4156        match self {
4157            Self::InvalidControlOp(op) => {
4158                write!(f, "invalid or reserved control operation: {op:?}")
4159            }
4160            Self::DuplicateControlCorrelation(corr) => {
4161                write!(f, "duplicate in-flight control correlation: {corr}")
4162            }
4163            Self::RegistrationChannel(error) => write!(f, "registration channel: {error}"),
4164            Self::MissingSubcArg => write!(f, "missing required --subc <connection-file> argument"),
4165            Self::MissingSubcValue => write!(f, "--subc requires a connection-file path value"),
4166            Self::EmptyModuleIdEnv => write!(f, "{SUBC_MODULE_ID_ENV} must not be empty when set"),
4167            Self::NonUnicodeModuleIdEnv { value } => write!(
4168                f,
4169                "{SUBC_MODULE_ID_ENV} must be valid UTF-8, got '{}'",
4170                value.to_string_lossy()
4171            ),
4172            Self::ConnectionFile { path, source } => write!(
4173                f,
4174                "failed to read subc connection file '{}': {source}",
4175                path.display()
4176            ),
4177            Self::NoEndpoint { path } => write!(
4178                f,
4179                "subc connection file '{}' has no endpoints",
4180                path.display()
4181            ),
4182            Self::Connect {
4183                path,
4184                endpoint,
4185                source,
4186            } => write!(
4187                f,
4188                "failed to connect to subc endpoint {endpoint} from '{}': {source}",
4189                path.display()
4190            ),
4191            Self::Auth {
4192                path,
4193                endpoint,
4194                source,
4195            } => write!(
4196                f,
4197                "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
4198                path.display()
4199            ),
4200            Self::FrameIo(err) => fmt::Display::fmt(err, f),
4201            Self::FrameBuild(err) => write!(f, "frame build error: {err}"),
4202            Self::Json(err) => write!(f, "JSON error: {err}"),
4203            Self::WriterClosed => write!(f, "module writer task closed"),
4204            Self::HandlerPanic => write!(f, "module handler panicked"),
4205            Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
4206            Self::ConnectionTokenExhausted => write!(f, "module connection token exhausted"),
4207            Self::WriterTask(err) => write!(f, "module writer task failed: {err}"),
4208            Self::InFlightPoisoned => write!(f, "in-flight registry lock poisoned"),
4209            Self::ConnectionClosedBeforeHelloAck => write!(f, "connection closed before HELLO_ACK"),
4210            Self::UnexpectedHelloAck { ty } => write!(f, "expected HELLO_ACK, got {ty:?}"),
4211            Self::HelloRejected { body } => write!(
4212                f,
4213                "HELLO rejected by subc: {} ({})",
4214                body.code, body.message
4215            ),
4216            Self::LaunchNonce(err) => write!(f, "launch nonce unavailable: {err}"),
4217            Self::RequestEnded => write!(f, "request already cancelled or answered"),
4218        }
4219    }
4220}
4221
4222impl Error for SubcModuleError {
4223    fn source(&self) -> Option<&(dyn Error + 'static)> {
4224        match self {
4225            Self::RegistrationChannel(error) => Some(error),
4226            Self::ConnectionFile { source, .. } => Some(source),
4227            Self::Connect { source, .. } => Some(source),
4228            Self::Auth { source, .. } => Some(source),
4229            Self::FrameIo(err) => Some(err),
4230            Self::FrameBuild(err) => Some(err),
4231            Self::Json(err) => Some(err),
4232            Self::LaunchNonce(err) => Some(err),
4233            Self::WriterTask(err) => Some(err),
4234            Self::MissingSubcArg
4235            | Self::InvalidControlOp(_)
4236            | Self::DuplicateControlCorrelation(_)
4237            | Self::MissingSubcValue
4238            | Self::EmptyModuleIdEnv
4239            | Self::NonUnicodeModuleIdEnv { .. }
4240            | Self::NoEndpoint { .. }
4241            | Self::WriterClosed
4242            | Self::HandlerPanic
4243            | Self::StaleRouteHandle(_)
4244            | Self::ConnectionTokenExhausted
4245            | Self::InFlightPoisoned
4246            | Self::ConnectionClosedBeforeHelloAck
4247            | Self::UnexpectedHelloAck { .. }
4248            | Self::HelloRejected { .. }
4249            | Self::RequestEnded => None,
4250        }
4251    }
4252}
4253
4254impl From<serde_json::Error> for SubcModuleError {
4255    fn from(err: serde_json::Error) -> Self {
4256        Self::Json(err)
4257    }
4258}
4259
4260#[cfg(test)]
4261mod call_mode_tests;
4262
4263#[cfg(test)]
4264mod tests {
4265    use std::sync::atomic::{AtomicUsize, Ordering};
4266
4267    use serde_json::json;
4268
4269    use subc_protocol::manifest::{Concurrency, ExecutionMode, IdentityScope, Tool};
4270    use tokio::sync::Semaphore;
4271    use tokio::time::{advance, timeout};
4272
4273    use super::*;
4274
4275    struct EchoHandler;
4276
4277    #[async_trait]
4278    impl ModuleHandler for EchoHandler {
4279        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
4280            HandlerOutcome::Response(body)
4281        }
4282    }
4283
4284    struct BlockingHandler {
4285        entered: Arc<AtomicUsize>,
4286        release: Semaphore,
4287        report: HealthReport,
4288    }
4289
4290    #[async_trait]
4291    impl ModuleHandler for BlockingHandler {
4292        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
4293            self.entered.fetch_add(1, Ordering::SeqCst);
4294            self.release.acquire().await.unwrap().forget();
4295            HandlerOutcome::Streamed
4296        }
4297
4298        async fn health(&self) -> HealthReport {
4299            self.report.clone()
4300        }
4301    }
4302
4303    fn health_request(corr: u64) -> Frame {
4304        Frame::build(
4305            FrameType::Request,
4306            control_flags(),
4307            0,
4308            0,
4309            corr,
4310            serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).unwrap(),
4311        )
4312        .unwrap()
4313    }
4314
4315    fn data_request(channel: u16, corr: u64) -> Frame {
4316        Frame::build(
4317            FrameType::Request,
4318            data_flags(),
4319            channel,
4320            1,
4321            corr,
4322            b"opaque".to_vec(),
4323        )
4324        .unwrap()
4325    }
4326
4327    fn catalog_update_response(corr: u64) -> Frame {
4328        Frame::build(
4329            FrameType::Response,
4330            control_flags(),
4331            0,
4332            0,
4333            corr,
4334            serde_json::to_vec(&ModuleControlResponseToModule::CatalogUpdate {}).unwrap(),
4335        )
4336        .unwrap()
4337    }
4338
4339    fn test_module_handle(subc_ops: &[&str]) -> (ModuleHandle, mpsc::Receiver<Frame>) {
4340        let (tx, rx) = mpsc::channel(4);
4341        let ack = ModuleHelloAckBody {
4342            resume_token: None,
4343            negotiated_ver: PROTOCOL_VERSION,
4344            subc_ops: subc_ops.iter().map(|op| (*op).to_string()).collect(),
4345            subc_capabilities: Vec::new(),
4346            storage: None,
4347            machine_id: None,
4348        };
4349        (
4350            ModuleHandle::new(
4351                &ack,
4352                tx,
4353                1,
4354                CancellationToken::new(),
4355                tokio::runtime::Handle::current(),
4356            ),
4357            rx,
4358        )
4359    }
4360
4361    #[tokio::test]
4362    async fn accepting_drain_ready_requires_negotiation_and_uses_channel_zero() {
4363        let (legacy, mut silent) = test_module_handle(&[]);
4364        assert!(matches!(
4365            legacy.drain_ready().await,
4366            Err(DrainReadyError::Unsupported)
4367        ));
4368        assert!(silent.try_recv().is_err());
4369
4370        let (tx, mut rx) = mpsc::channel(1);
4371        let handle = ModuleHandle::new(
4372            &ModuleHelloAckBody {
4373                resume_token: None,
4374                negotiated_ver: PROTOCOL_VERSION,
4375                subc_ops: vec!["module.drain_ready".into()],
4376                subc_capabilities: vec!["accepting-drain/v1".into()],
4377                storage: None,
4378                machine_id: None,
4379            },
4380            tx,
4381            1,
4382            CancellationToken::new(),
4383            tokio::runtime::Handle::current(),
4384        );
4385        let (result, ()) = tokio::join!(handle.drain_ready(), async {
4386            let request = rx.recv().await.unwrap();
4387            assert_eq!(
4388                (
4389                    request.header.ty,
4390                    request.header.channel,
4391                    request.header.epoch
4392                ),
4393                (FrameType::Request, 0, 0)
4394            );
4395            assert_eq!(request.body, br#"{"op":"module.drain_ready"}"#);
4396            assert!(handle.handle_control_reply(control_reply(
4397                FrameType::Response,
4398                request.header.corr,
4399                request.body
4400            )));
4401        });
4402        result.unwrap();
4403    }
4404
4405    #[test]
4406    fn module_handle_exposes_the_acked_machine_id_and_none_otherwise() {
4407        let runtime = tokio::runtime::Runtime::new().unwrap();
4408        let handle_for = |machine_id: Option<&str>| {
4409            let (tx, _rx) = mpsc::channel(1);
4410            let ack = ModuleHelloAckBody {
4411                resume_token: None,
4412                negotiated_ver: PROTOCOL_VERSION,
4413                subc_ops: Vec::new(),
4414                subc_capabilities: Vec::new(),
4415                storage: None,
4416                machine_id: machine_id.map(str::to_owned),
4417            };
4418            ModuleHandle::new(
4419                &ack,
4420                tx,
4421                1,
4422                CancellationToken::new(),
4423                runtime.handle().clone(),
4424            )
4425        };
4426        assert_eq!(
4427            handle_for(Some("0123456789abcdef0123456789abcdef"))
4428                .machine_id()
4429                .map(MachineId::as_str),
4430            Some("0123456789abcdef0123456789abcdef")
4431        );
4432        // An older daemon sends nothing, and nothing is invented in its place.
4433        assert_eq!(handle_for(None).machine_id(), None);
4434        assert_eq!(handle_for(Some("not-a-machine-id")).machine_id(), None);
4435    }
4436
4437    fn test_provider_role(tool_names: &[&str]) -> ProviderRole {
4438        ProviderRole::ToolProvider {
4439            tools: tool_names
4440                .iter()
4441                .map(|name| Tool {
4442                    name: (*name).to_string(),
4443                    description: None,
4444                    execution_mode: ExecutionMode::Pure,
4445                    schema: json!({"type": "object"}),
4446                })
4447                .collect(),
4448            identity_scope: vec![IdentityScope::Project],
4449            concurrency: Concurrency::ModuleManaged,
4450            emits_push: false,
4451            sub_supervises: false,
4452        }
4453    }
4454
4455    #[tokio::test]
4456    async fn catalog_update_fails_fast_when_hello_ack_does_not_advertise_support() {
4457        let (handle, mut rx) = test_module_handle(&[]);
4458
4459        let error = handle
4460            .catalog_update(vec![test_provider_role(&["a"])])
4461            .await
4462            .unwrap_err();
4463        assert!(matches!(error, CatalogUpdateError::NotSupported));
4464        assert!(matches!(
4465            handle.set_ready(true).await,
4466            Err(CatalogUpdateError::NotSupported)
4467        ));
4468        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
4469    }
4470
4471    #[tokio::test]
4472    async fn catalog_update_demuxes_multiple_in_flight_requests() {
4473        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4474        let first_handle = handle.clone();
4475        let second_handle = handle.clone();
4476        let first = tokio::spawn(async move {
4477            first_handle
4478                .catalog_update(vec![test_provider_role(&["a"])])
4479                .await
4480        });
4481        let second = tokio::spawn(async move {
4482            second_handle
4483                .catalog_update(vec![test_provider_role(&["b"])])
4484                .await
4485        });
4486
4487        let first_frame = timeout(Duration::from_secs(1), rx.recv())
4488            .await
4489            .unwrap()
4490            .unwrap();
4491        let second_frame = timeout(Duration::from_secs(1), rx.recv())
4492            .await
4493            .unwrap()
4494            .unwrap();
4495        assert_eq!(first_frame.header.ty, FrameType::Request);
4496        assert_eq!(first_frame.header.channel, 0);
4497        assert_eq!(second_frame.header.ty, FrameType::Request);
4498        assert_eq!(second_frame.header.channel, 0);
4499        assert_ne!(first_frame.header.corr, second_frame.header.corr);
4500
4501        let (earlier, later) =
4502            if json_body(&first_frame.body)["provides"] == json!([test_provider_role(&["a"])]) {
4503                (first, second)
4504            } else {
4505                (second, first)
4506            };
4507        assert!(handle.handle_control_reply(catalog_update_response(second_frame.header.corr)));
4508        assert!(later.await.unwrap().is_ok());
4509        assert!(handle.handle_control_reply(catalog_update_response(first_frame.header.corr)));
4510        assert!(earlier.await.unwrap().is_ok());
4511
4512        let expected = json_body(&second_frame.body)["provides"].clone();
4513        let (result, ()) = tokio::join!(handle.set_ready(true), async {
4514            let frame = rx.recv().await.unwrap();
4515            assert_eq!(json_body(&frame.body)["provides"], expected);
4516            assert_eq!(json_body(&frame.body)["ready"], true);
4517            handle.handle_control_reply(catalog_update_response(frame.header.corr));
4518        });
4519        result.unwrap();
4520    }
4521
4522    fn json_body(body: &[u8]) -> serde_json::Value {
4523        serde_json::from_slice(body).unwrap()
4524    }
4525
4526    #[tokio::test]
4527    async fn role_declarations_update_requires_its_own_advertised_op() {
4528        for ops in [vec![], vec![MODULE_TO_SUBC_OP_CATALOG_UPDATE]] {
4529            let (handle, mut rx) = test_module_handle(&ops);
4530            assert!(matches!(
4531                handle.update_role_declarations(BTreeMap::new()).await,
4532                Err(CatalogUpdateError::NotSupported)
4533            ));
4534            assert!(matches!(
4535                rx.try_recv(),
4536                Err(mpsc::error::TryRecvError::Empty)
4537            ));
4538        }
4539    }
4540
4541    #[tokio::test]
4542    async fn role_declarations_update_sends_map_and_preserves_refusal() {
4543        let (handle, mut rx) =
4544            test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS]);
4545        let initial_roles = vec![test_provider_role(&["original"])];
4546        handle.shared().lock_inner().current_provides = Some(initial_roles.clone());
4547        for declarations in [
4548            json!({"media-provider/v1": {"engines": ["image"]}}),
4549            json!({}),
4550        ] {
4551            let map = serde_json::from_value(declarations.clone()).unwrap();
4552            let (result, ()) = tokio::join!(handle.update_role_declarations(map), async {
4553                let frame = rx.recv().await.unwrap();
4554                assert_eq!(frame.header.ty, FrameType::Request);
4555                assert_eq!(frame.header.channel, 0);
4556                assert_eq!(
4557                    json_body(&frame.body),
4558                    json!({"op": "catalog.update_role_declarations", "role_declarations": declarations})
4559                );
4560                handle.handle_control_reply(control_reply(
4561                    FrameType::Response,
4562                    frame.header.corr,
4563                    serde_json::to_vec(&json!({"op": "catalog.update_role_declarations"})).unwrap(),
4564                ));
4565            });
4566            result.unwrap();
4567        }
4568        let (result, ()) = tokio::join!(handle.update_role_declarations(BTreeMap::new()), async {
4569            let frame = rx.recv().await.unwrap();
4570            handle.handle_control_reply(control_reply(FrameType::Error, frame.header.corr,
4571                serde_json::to_vec(&json!({"code": "invalid_role_declarations", "message": "role_declarations key must use capability-name grammar"})).unwrap()));
4572        });
4573        let Err(CatalogUpdateError::Rejected(body)) = result else {
4574            panic!("expected typed refusal")
4575        };
4576        assert_eq!(body.code, "invalid_role_declarations");
4577        assert_eq!(
4578            body.message,
4579            "role_declarations key must use capability-name grammar"
4580        );
4581        assert_eq!(
4582            handle.shared().lock_inner().current_provides,
4583            Some(initial_roles)
4584        );
4585    }
4586
4587    async fn ack_catalog_update(
4588        handle: &ModuleHandle,
4589        rx: &mut mpsc::Receiver<Frame>,
4590        provides: &[ProviderRole],
4591        ready: Option<bool>,
4592        capabilities: Option<&CapabilityDeclarations>,
4593    ) {
4594        let frame = rx.recv().await.unwrap();
4595        let mut expected = json!({"op": "catalog.update", "provides": provides});
4596        if let Some(ready) = ready {
4597            expected["ready"] = json!(ready);
4598        }
4599        if let Some(capabilities) = capabilities {
4600            expected["capabilities"] = json!(capabilities);
4601        }
4602        assert_eq!(json_body(&frame.body), expected);
4603        let mut wire = format!(
4604            r#"{{"op":"catalog.update","provides":{}"#,
4605            serde_json::to_string(provides).unwrap()
4606        );
4607        if let Some(capabilities) = capabilities {
4608            wire.push_str(&format!(
4609                r#","capabilities":{}"#,
4610                serde_json::to_string(capabilities).unwrap()
4611            ));
4612        }
4613        if let Some(ready) = ready {
4614            wire.push_str(&format!(r#","ready":{ready}"#));
4615        }
4616        wire.push('}');
4617        assert_eq!(frame.body, wire.as_bytes());
4618        assert!(handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4619    }
4620
4621    #[tokio::test]
4622    async fn catalog_update_set_ready_preserves_registered_and_replaced_roles() {
4623        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4624        let initial = vec![test_provider_role(&["initial", "second"])];
4625        handle.shared().lock_inner().current_provides = Some(initial.clone());
4626        let (result, ()) = tokio::join!(
4627            handle.set_ready(true),
4628            ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4629        );
4630        result.unwrap();
4631
4632        let replaced = vec![test_provider_role(&["replacement"])];
4633        let (result, ()) = tokio::join!(
4634            handle.catalog_update(replaced.clone()),
4635            ack_catalog_update(&handle, &mut rx, &replaced, None, None)
4636        );
4637        result.unwrap();
4638        let (result, ()) = tokio::join!(
4639            handle.set_ready(false),
4640            ack_catalog_update(&handle, &mut rx, &replaced, Some(false), None)
4641        );
4642        result.unwrap();
4643
4644        let attested = vec![test_provider_role(&["attested"])];
4645        let capabilities = CapabilityDeclarations {
4646            provides: vec!["test.capability".into()],
4647            requires: Vec::new(),
4648            must_never_reach: Vec::new(),
4649        };
4650        let (result, ()) = tokio::join!(
4651            handle.catalog_update_with_capabilities(attested.clone(), capabilities.clone()),
4652            ack_catalog_update(&handle, &mut rx, &attested, None, Some(&capabilities))
4653        );
4654        result.unwrap();
4655        let (result, ()) = tokio::join!(
4656            handle.set_ready(true),
4657            ack_catalog_update(&handle, &mut rx, &attested, Some(true), None)
4658        );
4659        result.unwrap();
4660    }
4661
4662    #[tokio::test]
4663    async fn catalog_update_set_ready_refuses_unknown_or_in_flight_roles() {
4664        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4665        assert!(matches!(
4666            handle.set_ready(true).await,
4667            Err(CatalogUpdateError::Protocol(_))
4668        ));
4669        assert!(rx.try_recv().is_err());
4670
4671        let updating = handle.clone();
4672        let update = tokio::spawn(async move {
4673            updating
4674                .catalog_update(vec![test_provider_role(&["new"])])
4675                .await
4676        });
4677        let frame = rx.recv().await.unwrap();
4678        assert!(matches!(
4679            handle.set_ready(true).await,
4680            Err(CatalogUpdateError::Protocol(_))
4681        ));
4682        assert!(rx.try_recv().is_err());
4683        update.abort();
4684        assert!(update.await.unwrap_err().is_cancelled());
4685        assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4686        assert!(matches!(
4687            handle.set_ready(true).await,
4688            Err(CatalogUpdateError::Protocol(_))
4689        ));
4690
4691        let roles = vec![test_provider_role(&["recovered"])];
4692        let (result, ()) = tokio::join!(
4693            handle.catalog_update(roles.clone()),
4694            ack_catalog_update(&handle, &mut rx, &roles, None, None)
4695        );
4696        result.unwrap();
4697        let (result, ()) = tokio::join!(
4698            handle.set_ready(true),
4699            ack_catalog_update(&handle, &mut rx, &roles, Some(true), None)
4700        );
4701        result.unwrap();
4702    }
4703
4704    #[tokio::test(start_paused = true)]
4705    async fn catalog_update_set_ready_timeout_does_not_replay_stale_roles() {
4706        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4707        handle.shared().lock_inner().current_provides = Some(vec![test_provider_role(&["old"])]);
4708        assert!(matches!(
4709            handle
4710                .catalog_update(vec![test_provider_role(&["new"])])
4711                .await,
4712            Err(CatalogUpdateError::Timeout)
4713        ));
4714        let frame = rx.recv().await.unwrap();
4715        assert!(!handle.handle_control_reply(catalog_update_response(frame.header.corr)));
4716        assert!(matches!(
4717            handle.set_ready(true).await,
4718            Err(CatalogUpdateError::Protocol(_))
4719        ));
4720        assert!(rx.try_recv().is_err());
4721    }
4722
4723    #[tokio::test]
4724    async fn catalog_update_set_ready_rejection_retains_last_accepted_roles() {
4725        let (handle, mut rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
4726        let initial = vec![test_provider_role(&["kept"])];
4727        handle.shared().lock_inner().current_provides = Some(initial.clone());
4728        let (result, ()) = tokio::join!(
4729            handle.catalog_update(vec![test_provider_role(&["rejected"])]),
4730            async {
4731                let frame = rx.recv().await.unwrap();
4732                handle.handle_control_reply(control_reply(
4733                    FrameType::Error,
4734                    frame.header.corr,
4735                    br#"{"code":"catalog_update_frozen_field","message":"frozen"}"#.to_vec(),
4736                ));
4737            }
4738        );
4739        assert!(matches!(result, Err(CatalogUpdateError::FrozenField(_))));
4740        let (result, ()) = tokio::join!(
4741            handle.set_ready(true),
4742            ack_catalog_update(&handle, &mut rx, &initial, Some(true), None)
4743        );
4744        result.unwrap();
4745    }
4746
4747    fn control_reply(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
4748        Frame::build(ty, control_flags(), 0, 0, corr, body).unwrap()
4749    }
4750
4751    async fn authorize_for_test(
4752        handle: &ModuleHandle,
4753    ) -> Result<RouteAuthorizeResponse, ScopeCallError> {
4754        handle
4755            .route_authorize(
4756                Principal::Direct,
4757                RouteAuthorizeScope::new(
4758                    Principal::Reserved {
4759                        module_id: "owner".into(),
4760                    },
4761                    "stored-scope",
4762                    7,
4763                ),
4764                "target".into(),
4765                RouteAuthorizeExpected::new(
4766                    subc_protocol::scope::ScopeKind::Head,
4767                    &subc_protocol::scope::ScopeAttributes::default(),
4768                ),
4769            )
4770            .await
4771    }
4772
4773    #[tokio::test]
4774    async fn route_authorize_requires_advertised_operation() {
4775        let (tx, mut rx) = mpsc::channel(4);
4776        let ack = ModuleHelloAckBody {
4777            resume_token: None,
4778            negotiated_ver: PROTOCOL_VERSION,
4779            subc_ops: vec![],
4780            // A module-provided capability is not the daemon's op advertisement.
4781            subc_capabilities: vec![subc_protocol::scope::ROUTE_AUTHORIZE_CAPABILITY.into()],
4782            storage: None,
4783            machine_id: None,
4784        };
4785        let handle = ModuleHandle::new(
4786            &ack,
4787            tx,
4788            1,
4789            CancellationToken::new(),
4790            tokio::runtime::Handle::current(),
4791        );
4792        let result = timeout(Duration::from_millis(100), authorize_for_test(&handle))
4793            .await
4794            .expect("an unsupported operation must return without sending or awaiting a reply");
4795        assert_eq!(
4796            result,
4797            Err(ScopeCallError::NotSupported {
4798                op: subc_protocol::scope::ROUTE_AUTHORIZE_OP,
4799            })
4800        );
4801        assert!(
4802            rx.try_recv().is_err(),
4803            "unsupported calls must send nothing"
4804        );
4805    }
4806
4807    #[tokio::test]
4808    async fn route_authorize_decodes_every_answer_and_permission_refusal() {
4809        use RouteAuthorizeOutcome::*;
4810        let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4811        for (wire, outcome, code) in [
4812            ("authorized", Authorized, None),
4813            ("scope_ended", ScopeEnded, Some("scope_not_live")),
4814            ("indeterminate", Indeterminate, Some("scope_not_synced")),
4815            ("epoch_changed", EpochChanged, Some("scope_ended")),
4816            ("claim_changed", ClaimChanged, None),
4817            (
4818                "proof_required",
4819                ProofRequired,
4820                Some("scope_bind_proof_required"),
4821            ),
4822            ("not_authorized", NotAuthorized, Some("scope_not_carrier")),
4823            ("target_absent", TargetAbsent, None),
4824        ] {
4825            let caller = handle.clone();
4826            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4827            let request = rx.recv().await.unwrap();
4828            assert_eq!(request.header.ty, FrameType::Request);
4829            assert_eq!(request.header.channel, 0);
4830            assert_eq!(request.header.ver, PROTOCOL_VERSION);
4831            assert_eq!(
4832                serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
4833                serde_json::json!({
4834                    "op": "route.authorize", "principal": {"kind": "direct"},
4835                    "scope": {"owner": {"kind": "reserved", "module_id": "owner"},
4836                              "ref": "stored-scope", "epoch": 7},
4837                    "target": "target", "expected": {"kind": "head"}
4838                })
4839            );
4840            let content_version = (outcome == Authorized).then_some("sha256:content");
4841            let mut body = serde_json::json!({
4842                "op": "route.authorize", "outcome": wire, "message": "judgment"
4843            });
4844            if let Some(code) = code {
4845                body["route_open_code"] = code.into();
4846            }
4847            if let Some(version) = content_version {
4848                body["content_version"] = version.into();
4849            }
4850            assert!(handle.handle_control_reply(control_reply(
4851                FrameType::Response,
4852                request.header.corr,
4853                serde_json::to_vec(&body).unwrap(),
4854            )));
4855            let reply = pending.await.unwrap().unwrap();
4856            assert_eq!(reply.outcome, outcome);
4857            assert_eq!(reply.message, "judgment");
4858            assert_eq!(reply.route_open_code.as_deref(), code);
4859            assert_eq!(reply.content_version.as_deref(), content_version);
4860        }
4861
4862        for (code, message) in [
4863            ("route_authorize_not_permitted", "not the configured owner"),
4864            ("not_registered", "connection is not registered"),
4865            ("unexpected", "a future daemon call refusal"),
4866        ] {
4867            let caller = handle.clone();
4868            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4869            let request = rx.recv().await.unwrap();
4870            assert!(handle.handle_control_reply(control_reply(
4871                FrameType::Error,
4872                request.header.corr,
4873                serde_json::to_vec(&serde_json::json!({"code": code, "message": message})).unwrap(),
4874            )));
4875            assert_eq!(
4876                pending.await.unwrap(),
4877                Err(ScopeCallError::Refused {
4878                    code: code.into(),
4879                    message: message.into(),
4880                })
4881            );
4882        }
4883    }
4884
4885    #[tokio::test]
4886    async fn route_authorize_rejects_malformed_and_unexpected_replies() {
4887        let (handle, mut rx) = test_module_handle(&[subc_protocol::scope::ROUTE_AUTHORIZE_OP]);
4888        for (ty, body) in [
4889            (FrameType::Response, r#"{"op":"catalog.update"}"#),
4890            (
4891                FrameType::Response,
4892                r#"{"op":"route.authorize","outcome":"authorized"}"#,
4893            ),
4894            (
4895                FrameType::Response,
4896                r#"{"op":"route.authorize","outcome":"future","message":"new"}"#,
4897            ),
4898            (FrameType::Error, "not json"),
4899            (FrameType::Request, "{}"),
4900        ] {
4901            let caller = handle.clone();
4902            let pending = tokio::spawn(async move { authorize_for_test(&caller).await });
4903            let request = rx.recv().await.unwrap();
4904            assert!(handle.handle_control_reply(control_reply(
4905                ty,
4906                request.header.corr,
4907                body.as_bytes().to_vec(),
4908            )));
4909            assert!(
4910                matches!(pending.await.unwrap(), Err(ScopeCallError::Protocol(_))),
4911                "{body}"
4912            );
4913        }
4914    }
4915
4916    #[tokio::test]
4917    async fn scope_served_by_requires_capability_and_decodes_open_replies() {
4918        let (unsupported, mut rx) = test_module_handle(&[subc_control::SCOPE_SERVED_BY_OP]);
4919        assert_eq!(
4920            unsupported
4921                .scope_served_by("s".into(), 1, "tool".into())
4922                .await,
4923            Err(ScopeCallError::NotSupported {
4924                op: subc_control::SCOPE_SERVED_BY_OP
4925            })
4926        );
4927        assert!(rx.try_recv().is_err());
4928        let (tx, mut rx) = mpsc::channel(4);
4929        let ack = ModuleHelloAckBody {
4930            resume_token: None,
4931            negotiated_ver: PROTOCOL_VERSION,
4932            subc_ops: vec![],
4933            subc_capabilities: vec![subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.into()],
4934            storage: None,
4935            machine_id: None,
4936        };
4937        let handle = ModuleHandle::new(
4938            &ack,
4939            tx,
4940            1,
4941            CancellationToken::new(),
4942            tokio::runtime::Handle::current(),
4943        );
4944        for answer in ["served", "not_served", "unknown", "future"] {
4945            let caller = handle.clone();
4946            let pending =
4947                tokio::spawn(
4948                    async move { caller.scope_served_by("s".into(), 7, "tool".into()).await },
4949                );
4950            let request = rx.recv().await.unwrap();
4951            let decoded: subc_control::ScopeServedByRequest =
4952                serde_json::from_slice(&request.body).unwrap();
4953            assert_eq!(
4954                (
4955                    decoded.scope_ref.as_str(),
4956                    decoded.scope_epoch,
4957                    decoded.module_id.as_str()
4958                ),
4959                ("s", 7, "tool")
4960            );
4961            assert!(handle.handle_control_reply(control_reply(FrameType::Response, request.header.corr,
4962                serde_json::to_vec(&serde_json::json!({"op":"scope.served_by", "answer":answer, "daemon_incarnation":"d"})).unwrap())));
4963            let reply = pending.await.unwrap().unwrap();
4964            assert_eq!(reply.daemon_incarnation, "d");
4965            assert_eq!(serde_json::to_value(reply.answer).unwrap(), answer);
4966        }
4967        let caller = handle.clone();
4968        let pending =
4969            tokio::spawn(async move { caller.scope_served_by("s".into(), 7, "tool".into()).await });
4970        let request = rx.recv().await.unwrap();
4971        assert!(handle.handle_control_reply(control_reply(
4972            FrameType::Error,
4973            request.header.corr,
4974            serde_json::to_vec(&serde_json::json!({"code":"not_registered", "message":"gone"}))
4975                .unwrap()
4976        )));
4977        assert_eq!(
4978            pending.await.unwrap().unwrap_err().code(),
4979            Some("not_registered")
4980        );
4981    }
4982
4983    fn owner() -> Principal {
4984        Principal::Reserved {
4985            module_id: "owner".to_string(),
4986        }
4987    }
4988
4989    mod scope_watch {
4990        use super::*;
4991        include!("module_subscription_tests.rs");
4992    }
4993
4994    /// Each scope op is gated on its own `subc_ops` entry: a daemon that
4995    /// lists one but not the other gets only the one it listed, and a gated
4996    /// call sends nothing.
4997    #[tokio::test]
4998    async fn scope_ops_fail_fast_when_hello_ack_does_not_advertise_them() {
4999        let (handle, mut rx) = test_module_handle(&[]);
5000        assert_eq!(
5001            handle.scope_sync(1, Vec::new()).await.unwrap_err(),
5002            ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5003        );
5004        assert_eq!(
5005            handle
5006                .scope_describe(owner(), "s".to_string())
5007                .await
5008                .unwrap_err(),
5009            ScopeCallError::NotSupported {
5010                op: SCOPE_DESCRIBE_OP
5011            }
5012        );
5013        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5014
5015        let (describe_only, mut rx) = test_module_handle(&[SCOPE_DESCRIBE_OP]);
5016        assert_eq!(
5017            describe_only.scope_sync(1, Vec::new()).await.unwrap_err(),
5018            ScopeCallError::NotSupported { op: SCOPE_SYNC_OP }
5019        );
5020        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5021
5022        let (sync_only, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5023        assert_eq!(
5024            sync_only
5025                .scope_describe(owner(), "s".to_string())
5026                .await
5027                .unwrap_err(),
5028            ScopeCallError::NotSupported {
5029                op: SCOPE_DESCRIBE_OP
5030            }
5031        );
5032        assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5033    }
5034
5035    #[tokio::test]
5036    async fn scope_apply_sends_nothing_without_its_own_advertised_op() {
5037        for ops in [&[][..], &[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP][..]] {
5038            let (handle, mut rx) = test_module_handle(ops);
5039            assert_eq!(
5040                handle.scope_apply(2, Vec::new(), Vec::new()).await,
5041                Err(ScopeCallError::NotSupported { op: SCOPE_APPLY_OP })
5042            );
5043            assert!(timeout(Duration::from_millis(75), rx.recv()).await.is_err());
5044        }
5045    }
5046
5047    #[tokio::test]
5048    async fn scope_apply_sends_the_delta_and_preserves_per_entry_outcomes() {
5049        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5050        let apply = tokio::spawn({
5051            let handle = handle.clone();
5052            async move {
5053                handle
5054                    .scope_apply(
5055                        2,
5056                        vec![ScopeRecord::new(
5057                            "run",
5058                            1,
5059                            subc_protocol::scope::ScopeKind::Ephemeral,
5060                        )
5061                        .with_expires_at_ms(Some(12345))
5062                        .with_workdir(Some("/session/folder".into()))
5063                        .with_project_id(Some("project:1".into()))],
5064                        vec![ScopeEnd::new("old", 3), ScopeEnd::new("missing", 1)],
5065                    )
5066                    .await
5067            }
5068        });
5069        let request = timeout(Duration::from_secs(1), rx.recv())
5070            .await
5071            .unwrap()
5072            .unwrap();
5073        assert_eq!(request.header.ty, FrameType::Request);
5074        assert_eq!(request.header.channel, 0);
5075        assert_eq!(
5076            serde_json::from_slice::<serde_json::Value>(&request.body).unwrap(),
5077            serde_json::json!({
5078                "op": "scope.apply", "generation": 2,
5079                "upsert": [{"ref": "run", "scope_epoch": 1, "kind": "ephemeral", "expires_at_ms": 12345,
5080                    "workdir": "/session/folder", "project_id": "project:1"}],
5081                "end": [{"ref": "old", "scope_epoch": 3}, {"ref": "missing", "scope_epoch": 1}]
5082            })
5083        );
5084        let body = serde_json::to_vec(&serde_json::json!({
5085            "op": "scope.apply", "generation": 2,
5086            "results": [{"ref": "run", "scope_epoch": 1, "outcome": "refused", "code": "scope_expired"}],
5087            "end_results": [
5088                {"ref": "old", "scope_epoch": 3, "outcome": "ended"},
5089                {"ref": "missing", "scope_epoch": 1, "outcome": "not_live"}
5090            ],
5091            "ended": [{"ref": "old", "scope_epoch": 3}]
5092        }))
5093        .unwrap();
5094        assert!(handle.handle_control_reply(control_reply(
5095            FrameType::Response,
5096            request.header.corr,
5097            body
5098        )));
5099        let reply = apply.await.unwrap().unwrap();
5100        assert_eq!(reply.generation, 2);
5101        assert_eq!(reply.results.len(), 1);
5102        assert_eq!(reply.results[0].scope_ref, "run");
5103        assert_eq!(
5104            reply.results[0].outcome,
5105            subc_protocol::scope::ScopeRecordOutcome::Refused
5106        );
5107        assert_eq!(reply.results[0].code.as_deref(), Some("scope_expired"));
5108        assert_eq!(reply.end_results.len(), 2);
5109        assert_eq!(reply.end_results[0].scope_ref, "old");
5110        assert_eq!(reply.end_results[0].scope_epoch, 3);
5111        assert_eq!(
5112            reply.end_results[0].outcome,
5113            subc_protocol::scope::ScopeEndOutcome::Ended
5114        );
5115        assert_eq!(reply.end_results[1].scope_ref, "missing");
5116        assert_eq!(
5117            reply.end_results[1].outcome,
5118            subc_protocol::scope::ScopeEndOutcome::NotLive
5119        );
5120        assert_eq!(reply.ended.len(), 1);
5121        assert_eq!(reply.ended[0].scope_ref, "old");
5122        assert_eq!(reply.ended[0].scope_epoch, 3);
5123    }
5124
5125    #[tokio::test]
5126    async fn scope_apply_rejects_a_reply_for_another_op() {
5127        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5128        let apply = tokio::spawn({
5129            let handle = handle.clone();
5130            async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5131        });
5132        let request = timeout(Duration::from_secs(1), rx.recv())
5133            .await
5134            .unwrap()
5135            .unwrap();
5136        let body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5137            generation: 2,
5138            results: Vec::new(),
5139            ended: Vec::new(),
5140        })
5141        .unwrap();
5142        assert!(handle.handle_control_reply(control_reply(
5143            FrameType::Response,
5144            request.header.corr,
5145            body
5146        )));
5147        assert!(matches!(
5148            apply.await.unwrap(),
5149            Err(ScopeCallError::Protocol(_))
5150        ));
5151    }
5152
5153    #[tokio::test]
5154    async fn scope_apply_preserves_whole_call_refusal_codes() {
5155        let (handle, mut rx) = test_module_handle(&[SCOPE_APPLY_OP]);
5156        for code in [
5157            subc_protocol::error_codes::SCOPE_SYNC_REQUIRED,
5158            subc_protocol::error_codes::SCOPE_SYNC_STALE,
5159            subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5160            "not_registered",
5161        ] {
5162            let apply = tokio::spawn({
5163                let handle = handle.clone();
5164                async move { handle.scope_apply(2, Vec::new(), Vec::new()).await }
5165            });
5166            let request = timeout(Duration::from_secs(1), rx.recv())
5167                .await
5168                .unwrap()
5169                .unwrap();
5170            let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5171            assert!(handle.handle_control_reply(control_reply(
5172                FrameType::Error,
5173                request.header.corr,
5174                body
5175            )));
5176            let error = apply.await.unwrap().unwrap_err();
5177            assert_eq!(
5178                error,
5179                ScopeCallError::Refused {
5180                    code: code.to_string(),
5181                    message: "why".to_string()
5182                }
5183            );
5184            assert_eq!(error.code(), Some(code));
5185        }
5186    }
5187
5188    /// A reply carrying another op's body is not taken as an answer.
5189    #[tokio::test]
5190    async fn a_scope_reply_of_another_op_is_a_protocol_error() {
5191        let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP]);
5192        let sync = tokio::spawn({
5193            let handle = handle.clone();
5194            async move { handle.scope_sync(1, Vec::new()).await }
5195        });
5196        let request = timeout(Duration::from_secs(1), rx.recv())
5197            .await
5198            .unwrap()
5199            .unwrap();
5200        let describe_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeDescribe {
5201            status: ScopeStatus::NotLive,
5202            scope_epoch: None,
5203            daemon_incarnation: "i".to_string(),
5204            owner_synced: false,
5205            owner_configured: false,
5206            scope: None,
5207        })
5208        .unwrap();
5209        assert!(handle.handle_control_reply(control_reply(
5210            FrameType::Response,
5211            request.header.corr,
5212            describe_body
5213        )));
5214        assert!(matches!(
5215            sync.await.unwrap(),
5216            Err(ScopeCallError::Protocol(_))
5217        ));
5218
5219        let describe = tokio::spawn({
5220            let handle = handle.clone();
5221            async move { handle.scope_describe(owner(), "s".to_string()).await }
5222        });
5223        let request = timeout(Duration::from_secs(1), rx.recv())
5224            .await
5225            .unwrap()
5226            .unwrap();
5227        let sync_body = serde_json::to_vec(&ModuleControlResponseToModule::ScopeSync {
5228            generation: 1,
5229            results: Vec::new(),
5230            ended: Vec::new(),
5231        })
5232        .unwrap();
5233        assert!(handle.handle_control_reply(control_reply(
5234            FrameType::Response,
5235            request.header.corr,
5236            sync_body
5237        )));
5238        assert!(matches!(
5239            describe.await.unwrap(),
5240            Err(ScopeCallError::Protocol(_))
5241        ));
5242    }
5243
5244    /// Every Error-frame code reaches the caller as sent, including codes the
5245    /// reply handling shared with `catalog_update` sorts into its own
5246    /// `CatalogUpdateError` variants (`not_registered`).
5247    #[tokio::test]
5248    async fn a_scope_error_frame_keeps_the_daemons_code_and_message() {
5249        let (handle, mut rx) = test_module_handle(&[SCOPE_SYNC_OP]);
5250        for code in [
5251            subc_protocol::error_codes::SCOPE_SYNC_STALE,
5252            subc_protocol::error_codes::SCOPE_SYNC_NOT_AUTHORITY,
5253            "not_registered",
5254        ] {
5255            let sync = tokio::spawn({
5256                let handle = handle.clone();
5257                async move { handle.scope_sync(1, Vec::new()).await }
5258            });
5259            let request = timeout(Duration::from_secs(1), rx.recv())
5260                .await
5261                .unwrap()
5262                .unwrap();
5263            let body = serde_json::to_vec(&ErrorBody::new(code, "why")).unwrap();
5264            assert!(handle.handle_control_reply(control_reply(
5265                FrameType::Error,
5266                request.header.corr,
5267                body
5268            )));
5269            let error = sync.await.unwrap().unwrap_err();
5270            assert_eq!(
5271                error,
5272                ScopeCallError::Refused {
5273                    code: code.to_string(),
5274                    message: "why".to_string()
5275                }
5276            );
5277            assert_eq!(error.code(), Some(code));
5278        }
5279    }
5280
5281    /// A route.bind whose scope stamp carries a field this SDK does not know
5282    /// (a newer daemon's attribute) must be refused on its own correlation id,
5283    /// and the module must keep serving: the next control request is answered.
5284    #[tokio::test]
5285    async fn an_undecodable_control_request_is_refused_and_the_module_keeps_serving() {
5286        let (tx, mut rx) = mpsc::channel(4);
5287        let handler = Arc::new(EchoHandler);
5288        let dispatcher = RequestDispatcher::new();
5289        let (module_handle, _unused_rx) = test_module_handle(&[]);
5290        // A well-formed bind from this SDK's own types, then one scope
5291        // attribute this SDK does not know, so that is the only defect.
5292        let mut body: serde_json::Value =
5293            serde_json::from_slice(&route_bind_frame(9, 1, 41).body).unwrap();
5294        body["scope"] = serde_json::json!({
5295            "owner": { "kind": "reserved", "module_id": "prefrontal-core" },
5296            "ref": "s",
5297            "scope_epoch": 1,
5298            "kind": "head",
5299            "attributes": { "a_field_from_a_newer_daemon": "x" },
5300            "owner_authorized": true
5301        });
5302        let body = serde_json::to_vec(&body).unwrap();
5303        let bind = Frame::build(FrameType::Request, control_flags(), 0, 0, 41, body).unwrap();
5304
5305        let kept_serving = handle_frame(
5306            bind,
5307            &tx,
5308            Arc::clone(&handler),
5309            dispatcher.clone(),
5310            module_handle.clone(),
5311        )
5312        .await
5313        .expect("an undecodable control request must not end the module");
5314        assert!(kept_serving);
5315        let refusal = timeout(Duration::from_secs(1), rx.recv())
5316            .await
5317            .unwrap()
5318            .unwrap();
5319        assert_eq!(refusal.header.ty, FrameType::Error);
5320        assert_eq!(refusal.header.corr, 41);
5321        let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
5322        assert_eq!(error.code, "invalid_request");
5323        // Prove the refusal is about the unknown attribute, not some other
5324        // defect in this fixture.
5325        assert!(
5326            error.message.contains("a_field_from_a_newer_daemon"),
5327            "{}",
5328            error.message
5329        );
5330
5331        assert!(
5332            handle_frame(health_request(42), &tx, handler, dispatcher, module_handle)
5333                .await
5334                .unwrap()
5335        );
5336        let health = timeout(Duration::from_secs(1), rx.recv())
5337            .await
5338            .unwrap()
5339            .unwrap();
5340        assert_eq!(health.header.ty, FrameType::Response);
5341        assert_eq!(health.header.corr, 42);
5342    }
5343
5344    #[tokio::test]
5345    async fn default_health_check_answers_ok() {
5346        let (tx, mut rx) = mpsc::channel(4);
5347        let handler = Arc::new(EchoHandler);
5348        let dispatcher = RequestDispatcher::new();
5349        let (module_handle, _unused_rx) = test_module_handle(&[]);
5350
5351        assert!(
5352            handle_frame(health_request(77), &tx, handler, dispatcher, module_handle)
5353                .await
5354                .unwrap()
5355        );
5356
5357        let response = timeout(Duration::from_secs(1), rx.recv())
5358            .await
5359            .unwrap()
5360            .unwrap();
5361        assert_eq!(response.header.ty, FrameType::Response);
5362        assert_eq!(response.header.channel, 0);
5363        assert_eq!(response.header.corr, 77);
5364
5365        // Assert the PROPERTIES that matter rather than byte-equality with
5366        // HealthReport::ok(). Comparing against the constructor made this test a
5367        // restatement of the implementation: it reddened on any change to the
5368        // default without saying which property had broken.
5369        let parsed = serde_json::from_slice::<ModuleControlResponse>(&response.body).unwrap();
5370        let ModuleControlResponse::HealthCheck { status, detail, .. } = parsed else {
5371            panic!("expected a health.check response");
5372        };
5373        // A module that never implemented health is not UNHEALTHY -- the daemon
5374        // must not escalate on it.
5375        assert_eq!(status, HealthStatus::Ok);
5376        // ...but the report must SAY that nobody measured, so an operator can
5377        // tell it from a real all-clear. Substring rather than exact text: the
5378        // wording is for humans and nothing parses it.
5379        assert!(
5380            detail
5381                .as_deref()
5382                .is_some_and(|d| d.contains("no health implementation")),
5383            "the inherited default must identify itself, got {detail:?}"
5384        );
5385    }
5386
5387    struct DispatchHarness {
5388        tx: mpsc::Sender<Frame>,
5389        rx: mpsc::Receiver<Frame>,
5390        handler: Arc<BlockingHandler>,
5391        dispatcher: RequestDispatcher,
5392        module_handle: ModuleHandle,
5393    }
5394
5395    impl DispatchHarness {
5396        fn new(report: HealthReport) -> Self {
5397            let (tx, rx) = mpsc::channel(HANDLER_TASK_CAPACITY + 4);
5398            let (module_handle, _unused_rx) = test_module_handle(&[]);
5399            module_handle
5400                .install_route(RouteHandle::new(7, 1, 1))
5401                .unwrap();
5402            Self {
5403                tx,
5404                rx,
5405                handler: Arc::new(BlockingHandler {
5406                    entered: Arc::new(AtomicUsize::new(0)),
5407                    release: Semaphore::new(0),
5408                    report,
5409                }),
5410                dispatcher: RequestDispatcher::new(),
5411                module_handle,
5412            }
5413        }
5414
5415        async fn request(&self, corr: u64) {
5416            handle_frame(
5417                data_request(7, corr),
5418                &self.tx,
5419                Arc::clone(&self.handler),
5420                self.dispatcher.clone(),
5421                self.module_handle.clone(),
5422            )
5423            .await
5424            .unwrap();
5425        }
5426
5427        async fn wait_for_entered(&self, count: usize) {
5428            timeout(Duration::from_secs(1), async {
5429                while self.handler.entered.load(Ordering::SeqCst) != count {
5430                    tokio::task::yield_now().await;
5431                }
5432            })
5433            .await
5434            .expect("data handlers should acquire the available slots");
5435        }
5436
5437        async fn saturate(&self) {
5438            for corr in 1..=HANDLER_TASK_CAPACITY as u64 {
5439                self.request(corr).await;
5440            }
5441            self.wait_for_entered(HANDLER_TASK_CAPACITY).await;
5442            self.request(HANDLER_TASK_CAPACITY as u64 + 1).await;
5443            tokio::task::yield_now().await;
5444            assert_eq!(self.dispatcher.pools.default.permits.available_permits(), 0);
5445            assert_eq!(
5446                self.dispatcher.pools.default.waiting.lock().unwrap().len(),
5447                1
5448            );
5449            assert_eq!(
5450                self.handler.entered.load(Ordering::SeqCst),
5451                HANDLER_TASK_CAPACITY
5452            );
5453        }
5454
5455        async fn health(&mut self, corr: u64) -> HealthReport {
5456            handle_frame(
5457                health_request(corr),
5458                &self.tx,
5459                Arc::clone(&self.handler),
5460                self.dispatcher.clone(),
5461                self.module_handle.clone(),
5462            )
5463            .await
5464            .unwrap();
5465            let frame = timeout(Duration::from_millis(100), self.rx.recv())
5466                .await
5467                .expect("health.check must answer within 100 ms while data slots are busy")
5468                .unwrap();
5469            assert_eq!(frame.header.ty, FrameType::Response);
5470            assert_eq!(frame.header.channel, 0);
5471            assert_eq!(frame.header.corr, corr);
5472            serde_json::from_slice::<ModuleControlResponse>(&frame.body)
5473                .unwrap()
5474                .health_report()
5475                .unwrap()
5476        }
5477
5478        async fn release(&mut self, count: usize) {
5479            self.handler.release.add_permits(count);
5480            for _ in 0..count {
5481                let frame = timeout(Duration::from_secs(1), self.rx.recv())
5482                    .await
5483                    .unwrap()
5484                    .unwrap();
5485                assert_eq!(frame.header.ty, FrameType::StreamEnd);
5486                assert_eq!(frame.header.channel, 7);
5487            }
5488            assert!(self
5489                .dispatcher
5490                .pools
5491                .default
5492                .waiting
5493                .lock()
5494                .unwrap()
5495                .is_empty());
5496            assert!(self.dispatcher.in_flight.lock().unwrap().is_empty());
5497            assert_eq!(
5498                self.dispatcher.pools.default.permits.available_permits(),
5499                HANDLER_TASK_CAPACITY
5500            );
5501        }
5502    }
5503
5504    #[tokio::test(start_paused = true)]
5505    async fn health_check_answers_degraded_under_saturation_and_recovers() {
5506        let own_report = HealthReport {
5507            status: HealthStatus::Ok,
5508            detail: Some("module gauges healthy".to_string()),
5509            metrics: Some(json!({"transforms": 64})),
5510        };
5511        let mut harness = DispatchHarness::new(own_report.clone());
5512        harness.saturate().await;
5513        // A brief burst is not dispatch impairment, even with no slot free.
5514        assert_eq!(harness.health(899).await, own_report);
5515        // Advance the real dispatch stamp's monotonic clock, not a test-only
5516        // health gauge. Keeping handlers blocked proves the transport isolation.
5517        advance(Duration::from_millis(7300)).await;
5518        let report = harness.health(900).await;
5519        assert_eq!(report.status, HealthStatus::Degraded);
5520        assert_eq!(report.metrics, own_report.metrics);
5521        assert_eq!(
5522            report.detail.as_deref(),
5523            Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module gauges healthy")
5524        );
5525
5526        harness.release(HANDLER_TASK_CAPACITY + 1).await;
5527        assert_eq!(harness.health(901).await, own_report);
5528    }
5529
5530    #[tokio::test(start_paused = true)]
5531    async fn health_check_preserves_failing_under_saturation() {
5532        let mut harness = DispatchHarness::new(HealthReport {
5533            status: HealthStatus::Failing,
5534            detail: Some("module dispatch heartbeat stale".to_string()),
5535            metrics: Some(json!({"heartbeat_age_s": 12})),
5536        });
5537        harness.saturate().await;
5538        advance(Duration::from_millis(7300)).await;
5539        let report = harness.health(900).await;
5540        assert_eq!(report.status, HealthStatus::Failing);
5541        assert_eq!(report.metrics, Some(json!({"heartbeat_age_s": 12})));
5542        assert_eq!(
5543            report.detail.as_deref(),
5544            Some("request dispatch saturated: 64/64 in use, oldest waiting 7.3 s; module dispatch heartbeat stale")
5545        );
5546        harness.release(HANDLER_TASK_CAPACITY + 1).await;
5547    }
5548
5549    #[tokio::test(start_paused = true)]
5550    async fn health_check_passes_module_report_through_with_free_permits() {
5551        for status in [
5552            HealthStatus::Ok,
5553            HealthStatus::Degraded,
5554            HealthStatus::Failing,
5555        ] {
5556            let own_report = HealthReport {
5557                status,
5558                detail: Some("module's own assessment".to_string()),
5559                metrics: Some(json!({"gauge": 42})),
5560            };
5561            let mut harness = DispatchHarness::new(own_report.clone());
5562            harness.request(1).await;
5563            harness.wait_for_entered(1).await;
5564            advance(Duration::from_millis(7300)).await;
5565            assert_eq!(harness.health(900).await, own_report);
5566            harness.release(1).await;
5567        }
5568    }
5569
5570    struct CorrBlockingHandler {
5571        entered: Arc<Mutex<Vec<u64>>>,
5572        release_first: Arc<Semaphore>,
5573    }
5574
5575    #[async_trait]
5576    impl ModuleHandler for CorrBlockingHandler {
5577        async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5578            let corr = ctx.corr();
5579            self.entered.lock().unwrap().push(corr);
5580            if corr == 1 {
5581                self.release_first.acquire().await.unwrap().forget();
5582            }
5583            HandlerOutcome::Response(Vec::new())
5584        }
5585    }
5586
5587    /// A request cancelled while it waits for a handler slot is answered
5588    /// `cancelled` at once: it does not wait for a slot to free just to say
5589    /// so, it never takes one, and its handler never runs.
5590    #[tokio::test]
5591    async fn cancelled_capacity_queued_data_request_is_answered_without_waiting_for_a_slot() {
5592        let (tx, mut rx) = mpsc::channel(4);
5593        let entered = Arc::new(Mutex::new(Vec::new()));
5594        let release_first = Arc::new(Semaphore::new(0));
5595        let handler = Arc::new(CorrBlockingHandler {
5596            entered: Arc::clone(&entered),
5597            release_first: Arc::clone(&release_first),
5598        });
5599        let dispatcher = RequestDispatcher::with_pools(Arc::new(
5600            DispatchPools::with_default_limit(1, RequestPools::new()),
5601        ));
5602        let (module_handle, _unused_rx) = test_module_handle(&[]);
5603        module_handle
5604            .install_route(RouteHandle::new(7, 1, 1))
5605            .unwrap();
5606
5607        handle_frame(
5608            data_request(7, 1),
5609            &tx,
5610            Arc::clone(&handler),
5611            dispatcher.clone(),
5612            module_handle.clone(),
5613        )
5614        .await
5615        .unwrap();
5616        timeout(Duration::from_secs(1), async {
5617            while entered.lock().unwrap().as_slice() != [1] {
5618                tokio::task::yield_now().await;
5619            }
5620        })
5621        .await
5622        .unwrap();
5623
5624        handle_frame(
5625            data_request(7, 2),
5626            &tx,
5627            Arc::clone(&handler),
5628            dispatcher.clone(),
5629            module_handle.clone(),
5630        )
5631        .await
5632        .unwrap();
5633        timeout(Duration::from_secs(1), async {
5634            while !dispatcher
5635                .in_flight
5636                .lock()
5637                .unwrap()
5638                .contains_key(&(7, 1, 2))
5639            {
5640                tokio::task::yield_now().await;
5641            }
5642        })
5643        .await
5644        .unwrap();
5645        handle_frame(
5646            Frame::build(FrameType::Cancel, data_flags(), 7, 1, 2, Vec::new()).unwrap(),
5647            &tx,
5648            Arc::clone(&handler),
5649            dispatcher.clone(),
5650            module_handle,
5651        )
5652        .await
5653        .unwrap();
5654        assert!(
5655            dispatcher
5656                .in_flight
5657                .lock()
5658                .unwrap()
5659                .get(&(7, 1, 2))
5660                .unwrap()
5661                .is_cancelled(),
5662            "cancel must land while the second request waits for handler capacity"
5663        );
5664
5665        // The first request still holds the only slot, so the answer below
5666        // cannot have come from a slot freeing.
5667        let cancelled = timeout(Duration::from_secs(1), rx.recv())
5668            .await
5669            .expect("a request cancelled while waiting must be answered without waiting for a slot")
5670            .unwrap();
5671        assert_eq!(cancelled.header.ty, FrameType::Error);
5672        assert_eq!(cancelled.header.channel, 7);
5673        assert_eq!(cancelled.header.epoch, 1);
5674        assert_eq!(cancelled.header.corr, 2);
5675        assert_eq!(
5676            serde_json::from_slice::<ErrorBody>(&cancelled.body).unwrap(),
5677            ErrorBody {
5678                code: "cancelled".to_string(),
5679                message: "request cancelled".to_string(),
5680                detail: None,
5681            }
5682        );
5683        timeout(Duration::from_secs(1), async {
5684            while dispatcher
5685                .in_flight
5686                .lock()
5687                .unwrap()
5688                .contains_key(&(7, 1, 2))
5689            {
5690                tokio::task::yield_now().await;
5691            }
5692        })
5693        .await
5694        .unwrap();
5695        assert_eq!(dispatcher.pools.default.permits.available_permits(), 0);
5696        assert!(dispatcher.pools.default.waiting.lock().unwrap().is_empty());
5697        assert_eq!(*entered.lock().unwrap(), vec![1]);
5698
5699        release_first.add_permits(1);
5700        let response = timeout(Duration::from_secs(1), rx.recv())
5701            .await
5702            .unwrap()
5703            .unwrap();
5704        assert_eq!(response.header.ty, FrameType::Response);
5705        assert_eq!(response.header.corr, 1);
5706        timeout(Duration::from_secs(1), async {
5707            while !dispatcher.in_flight.lock().unwrap().is_empty() {
5708                tokio::task::yield_now().await;
5709            }
5710        })
5711        .await
5712        .unwrap();
5713        assert_eq!(*entered.lock().unwrap(), vec![1]);
5714        assert_eq!(dispatcher.pools.default.permits.available_permits(), 1);
5715        assert!(timeout(Duration::from_millis(50), rx.recv()).await.is_err());
5716    }
5717
5718    #[tokio::test]
5719    async fn cancelled_terminal_is_not_sent_after_route_teardown() {
5720        let (tx, mut rx) = mpsc::channel(1);
5721        let (module_handle, _unused_rx) = test_module_handle(&[]);
5722        let handle = RouteHandle::new(7, 1, 1);
5723        module_handle.install_route(handle).unwrap();
5724        let ctx = RequestCtx {
5725            handle,
5726            corr: 2,
5727            ver: PROTOCOL_VERSION,
5728            egress: tx,
5729            module_handle: module_handle.clone(),
5730            cancelled: CancellationToken::new(),
5731            binary_reply: Arc::new(AtomicBool::new(false)),
5732            request_flags: Flags::new(false, Priority::Interactive, false),
5733            request_body: Arc::from([]),
5734            open: Arc::new(tokio::sync::Mutex::new(true)),
5735        };
5736        assert!(module_handle.remove_route(handle).unwrap());
5737
5738        let result = send_handler_outcome(
5739            &ctx,
5740            HandlerOutcome::Error {
5741                code: "cancelled".to_string(),
5742                message: "request cancelled".to_string(),
5743            },
5744        )
5745        .await;
5746
5747        assert!(matches!(
5748            result,
5749            Err(SubcModuleError::StaleRouteHandle(stale)) if stale == handle
5750        ));
5751        assert!(rx.try_recv().is_err());
5752    }
5753
5754    #[tokio::test]
5755    async fn push_rides_the_call_correlation_until_the_terminal_frame() {
5756        let (tx, mut rx) = mpsc::channel(4);
5757        let (module_handle, _unused_rx) = test_module_handle(&[]);
5758        let handle = RouteHandle::new(7, 1, 1);
5759        module_handle.install_route(handle).unwrap();
5760        let ctx = RequestCtx {
5761            handle,
5762            corr: 9,
5763            ver: PROTOCOL_VERSION,
5764            egress: tx,
5765            module_handle: module_handle.clone(),
5766            cancelled: CancellationToken::new(),
5767            binary_reply: Arc::new(AtomicBool::new(false)),
5768            request_flags: Flags::new(false, Priority::Interactive, false),
5769            request_body: Arc::from([]),
5770            open: Arc::new(tokio::sync::Mutex::new(true)),
5771        };
5772        // A keepalive loop usually runs on its own task with a clone.
5773        let keepalive = ctx.clone();
5774
5775        keepalive
5776            .push(br#"{"kind":"keepalive"}"#.to_vec())
5777            .await
5778            .unwrap();
5779        let push = rx.try_recv().unwrap();
5780        assert_eq!(push.header.ty, FrameType::Push);
5781        assert_eq!(
5782            (push.header.channel, push.header.epoch, push.header.corr),
5783            (7, 1, 9)
5784        );
5785        assert_eq!(push.body, br#"{"kind":"keepalive"}"#);
5786
5787        send_handler_outcome(&ctx, HandlerOutcome::Response(b"{}".to_vec()))
5788            .await
5789            .unwrap();
5790        assert_eq!(rx.try_recv().unwrap().header.ty, FrameType::Response);
5791
5792        assert!(matches!(
5793            keepalive.push(b"{}".to_vec()).await,
5794            Err(SubcModuleError::RequestEnded)
5795        ));
5796        assert!(rx.try_recv().is_err());
5797    }
5798
5799    #[tokio::test]
5800    async fn push_is_refused_once_the_request_is_cancelled() {
5801        let (tx, mut rx) = mpsc::channel(4);
5802        let (module_handle, _unused_rx) = test_module_handle(&[]);
5803        let handle = RouteHandle::new(7, 1, 1);
5804        module_handle.install_route(handle).unwrap();
5805        let cancelled = CancellationToken::new();
5806        let ctx = RequestCtx {
5807            handle,
5808            corr: 9,
5809            ver: PROTOCOL_VERSION,
5810            egress: tx,
5811            module_handle,
5812            cancelled: cancelled.clone(),
5813            binary_reply: Arc::new(AtomicBool::new(false)),
5814            request_flags: Flags::new(false, Priority::Interactive, false),
5815            request_body: Arc::from([]),
5816            open: Arc::new(tokio::sync::Mutex::new(true)),
5817        };
5818        cancelled.cancel();
5819
5820        assert!(matches!(
5821            ctx.push(b"{}".to_vec()).await,
5822            Err(SubcModuleError::RequestEnded)
5823        ));
5824        assert!(rx.try_recv().is_err());
5825    }
5826
5827    struct CountingHandler {
5828        calls: Arc<AtomicUsize>,
5829    }
5830
5831    #[async_trait]
5832    impl ModuleHandler for CountingHandler {
5833        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5834            self.calls.fetch_add(1, Ordering::SeqCst);
5835            HandlerOutcome::Response(Vec::new())
5836        }
5837    }
5838
5839    #[tokio::test]
5840    async fn endpoint_validation_drops_stale_request_before_handler_dispatch() {
5841        let (tx, mut rx) = mpsc::channel(4);
5842        let calls = Arc::new(AtomicUsize::new(0));
5843        let handler = Arc::new(CountingHandler {
5844            calls: Arc::clone(&calls),
5845        });
5846        let dispatcher = RequestDispatcher::new();
5847        let (module_handle, _unused_rx) = test_module_handle(&[]);
5848        module_handle
5849            .install_route(RouteHandle::new(7, 2, 1))
5850            .unwrap();
5851        let stale = Frame::build(FrameType::Request, data_flags(), 7, 1, 55, Vec::new()).unwrap();
5852
5853        assert!(
5854            handle_frame(stale, &tx, handler, dispatcher, module_handle.clone())
5855                .await
5856                .unwrap()
5857        );
5858        tokio::task::yield_now().await;
5859        assert_eq!(calls.load(Ordering::SeqCst), 0);
5860        assert_eq!(module_handle.dropped_route_frames(), 1);
5861        assert!(rx.try_recv().is_err());
5862    }
5863
5864    struct BindOrderingHandler {
5865        module_handle: ModuleHandle,
5866        bind_emit_rejected: Arc<AtomicUsize>,
5867        bound: Arc<AtomicUsize>,
5868        cleanup: Arc<AtomicUsize>,
5869    }
5870
5871    #[async_trait]
5872    impl ModuleHandler for BindOrderingHandler {
5873        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5874            HandlerOutcome::Response(Vec::new())
5875        }
5876
5877        async fn on_bind(&self, req: &RouteBindRequest) -> BindDecision {
5878            if matches!(
5879                self.module_handle
5880                    .push(&req.handle, b"too-early".to_vec(), None)
5881                    .await,
5882                Err(SubcModuleError::StaleRouteHandle(_))
5883            ) {
5884                self.bind_emit_rejected.fetch_add(1, Ordering::SeqCst);
5885            }
5886            BindDecision::accept()
5887        }
5888
5889        async fn on_bound(&self, handle: &RouteHandle) {
5890            self.bound.fetch_add(1, Ordering::SeqCst);
5891            self.module_handle
5892                .push(handle, b"bound".to_vec(), Some(AdmissionClass::Expedite))
5893                .await
5894                .unwrap();
5895        }
5896
5897        async fn on_route_gone(&self, _handle: &RouteHandle) {
5898            self.cleanup.fetch_add(1, Ordering::SeqCst);
5899        }
5900    }
5901
5902    fn route_bind_frame(channel: u16, epoch: u32, corr: u64) -> Frame {
5903        let body = serde_json::to_vec(&ModuleControlRequest::RouteBind {
5904            route_channel: channel,
5905            epoch,
5906            target: RouteTarget::ToolProvider {
5907                module_id: "provider".to_string(),
5908            },
5909            identity: BindIdentity::new("test".to_string(), "bind".to_string()),
5910            principal: None,
5911            consumer_capabilities: None,
5912            role_versions: None,
5913            admission_facts: None,
5914            scope: None,
5915            call_mode: None,
5916        })
5917        .unwrap();
5918        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5919    }
5920
5921    #[tokio::test]
5922    async fn on_bound_runs_only_after_ack_queue_and_handle_install() {
5923        let (module_handle, mut rx) = test_module_handle(&[]);
5924        let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
5925        let bind_emit_rejected = Arc::new(AtomicUsize::new(0));
5926        let bound = Arc::new(AtomicUsize::new(0));
5927        let cleanup = Arc::new(AtomicUsize::new(0));
5928        let handler = Arc::new(BindOrderingHandler {
5929            module_handle: module_handle.clone(),
5930            bind_emit_rejected: Arc::clone(&bind_emit_rejected),
5931            bound: Arc::clone(&bound),
5932            cleanup: Arc::clone(&cleanup),
5933        });
5934
5935        assert!(handle_frame(
5936            route_bind_frame(8, 4, 90),
5937            &tx,
5938            handler,
5939            RequestDispatcher::new(),
5940            module_handle.clone(),
5941        )
5942        .await
5943        .unwrap());
5944        assert_eq!(bind_emit_rejected.load(Ordering::SeqCst), 1);
5945        assert_eq!(bound.load(Ordering::SeqCst), 1);
5946        assert_eq!(cleanup.load(Ordering::SeqCst), 0);
5947
5948        let ack = rx.recv().await.unwrap();
5949        let push = rx.recv().await.unwrap();
5950        assert_eq!(ack.header.ty, FrameType::Response);
5951        assert_eq!(ack.header.channel, 0);
5952        assert_eq!(push.header.ty, FrameType::Push);
5953        assert_eq!((push.header.channel, push.header.epoch), (8, 4));
5954        assert_eq!(
5955            push.header.flags.admission_class(),
5956            Some(AdmissionClass::Expedite)
5957        );
5958
5959        let captured = RouteHandle::new(8, 4, 1);
5960        assert!(module_handle.remove_route(captured).unwrap());
5961        let stale = module_handle
5962            .push(&captured, Vec::new(), None)
5963            .await
5964            .unwrap_err();
5965        assert!(matches!(stale, SubcModuleError::StaleRouteHandle(_)));
5966        assert!(rx.try_recv().is_err());
5967    }
5968
5969    struct RejectingHandler {
5970        bound: Arc<AtomicUsize>,
5971        cleanup: Arc<AtomicUsize>,
5972    }
5973
5974    #[async_trait]
5975    impl ModuleHandler for RejectingHandler {
5976        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
5977            HandlerOutcome::Response(Vec::new())
5978        }
5979
5980        async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
5981            BindDecision::reject("no", "rejected")
5982        }
5983
5984        async fn on_bound(&self, _handle: &RouteHandle) {
5985            self.bound.fetch_add(1, Ordering::SeqCst);
5986        }
5987
5988        async fn on_route_gone(&self, _handle: &RouteHandle) {
5989            self.cleanup.fetch_add(1, Ordering::SeqCst);
5990        }
5991    }
5992
5993    #[tokio::test]
5994    async fn rejected_bind_cleans_up_without_installing_or_calling_on_bound() {
5995        let (module_handle, mut rx) = test_module_handle(&[]);
5996        let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
5997        let bound = Arc::new(AtomicUsize::new(0));
5998        let cleanup = Arc::new(AtomicUsize::new(0));
5999        let handler = Arc::new(RejectingHandler {
6000            bound: Arc::clone(&bound),
6001            cleanup: Arc::clone(&cleanup),
6002        });
6003        handle_frame(
6004            route_bind_frame(6, 3, 91),
6005            &tx,
6006            handler,
6007            RequestDispatcher::new(),
6008            module_handle.clone(),
6009        )
6010        .await
6011        .unwrap();
6012        let refusal = rx.recv().await.unwrap();
6013        assert_eq!(refusal.header.ty, FrameType::Error);
6014        // A plain rejection keeps its detail-free bytes.
6015        assert_eq!(refusal.body, br#"{"code":"no","message":"rejected"}"#);
6016        assert_eq!(bound.load(Ordering::SeqCst), 0);
6017        assert_eq!(cleanup.load(Ordering::SeqCst), 1);
6018        assert!(matches!(
6019            module_handle.validate_route(RouteHandle::new(6, 3, 1)),
6020            Err(SubcModuleError::StaleRouteHandle(_))
6021        ));
6022    }
6023
6024    struct BusyHandler;
6025
6026    #[async_trait]
6027    impl ModuleHandler for BusyHandler {
6028        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6029            HandlerOutcome::Response(Vec::new())
6030        }
6031
6032        async fn on_bind(&self, _req: &RouteBindRequest) -> BindDecision {
6033            BindDecision::reject_with_detail(
6034                "bind_busy",
6035                "a read is still running on this root",
6036                serde_json::json!({"reason": "reader", "retry_after_ms": 2000}),
6037            )
6038        }
6039    }
6040
6041    #[tokio::test]
6042    async fn rejected_bind_carries_its_detail_to_the_daemon() {
6043        let (module_handle, mut rx) = test_module_handle(&[]);
6044        let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
6045        handle_frame(
6046            route_bind_frame(6, 3, 92),
6047            &tx,
6048            Arc::new(BusyHandler),
6049            RequestDispatcher::new(),
6050            module_handle.clone(),
6051        )
6052        .await
6053        .unwrap();
6054        let refusal = rx.recv().await.unwrap();
6055        assert_eq!(refusal.header.ty, FrameType::Error);
6056        let body: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
6057        assert_eq!(body.code, "bind_busy");
6058        assert_eq!(
6059            body.detail,
6060            Some(serde_json::json!({"reason": "reader", "retry_after_ms": 2000}))
6061        );
6062    }
6063
6064    struct RebindCountingHandler {
6065        bound: Arc<AtomicUsize>,
6066        cleanup: Arc<AtomicUsize>,
6067    }
6068
6069    #[async_trait]
6070    impl ModuleHandler for RebindCountingHandler {
6071        async fn handle(&self, _ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6072            HandlerOutcome::Response(Vec::new())
6073        }
6074
6075        async fn on_bound(&self, _handle: &RouteHandle) {
6076            self.bound.fetch_add(1, Ordering::SeqCst);
6077        }
6078
6079        async fn on_route_gone(&self, _handle: &RouteHandle) {
6080            self.cleanup.fetch_add(1, Ordering::SeqCst);
6081        }
6082    }
6083
6084    // Wire spec 3.3.0: a bind on an installed channel with a strictly higher epoch
6085    // replaces the stale install (the daemon freed that binding; its route-gone
6086    // GOODBYE is best-effort and can be dropped), firing the replaced install's
6087    // route-gone teardown. Equal-or-lower epoch is a protocol violation: rejected,
6088    // installed route untouched.
6089    #[tokio::test]
6090    async fn rebind_on_installed_channel_replaces_on_higher_epoch_only() {
6091        let (module_handle, mut rx) = test_module_handle(&[]);
6092        let tx = module_handle.shared().lock_inner().writer.clone().unwrap();
6093        let bound = Arc::new(AtomicUsize::new(0));
6094        let cleanup = Arc::new(AtomicUsize::new(0));
6095        let handler = Arc::new(RebindCountingHandler {
6096            bound: Arc::clone(&bound),
6097            cleanup: Arc::clone(&cleanup),
6098        });
6099
6100        // Install epoch 4 on channel 8.
6101        handle_frame(
6102            route_bind_frame(8, 4, 90),
6103            &tx,
6104            Arc::clone(&handler),
6105            RequestDispatcher::new(),
6106            module_handle.clone(),
6107        )
6108        .await
6109        .unwrap();
6110        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6111        assert_eq!(
6112            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6113            (1, 0)
6114        );
6115
6116        // Same epoch: rejected, install untouched, no teardown fired.
6117        handle_frame(
6118            route_bind_frame(8, 4, 91),
6119            &tx,
6120            Arc::clone(&handler),
6121            RequestDispatcher::new(),
6122            module_handle.clone(),
6123        )
6124        .await
6125        .unwrap();
6126        let reject = rx.recv().await.unwrap();
6127        assert_eq!(reject.header.ty, FrameType::Error);
6128        assert_eq!(
6129            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6130            (1, 0)
6131        );
6132        module_handle
6133            .validate_route(RouteHandle::new(8, 4, 1))
6134            .expect("epoch-4 install must survive the rejected rebind");
6135
6136        // Lower epoch: same rejection shape.
6137        handle_frame(
6138            route_bind_frame(8, 3, 92),
6139            &tx,
6140            Arc::clone(&handler),
6141            RequestDispatcher::new(),
6142            module_handle.clone(),
6143        )
6144        .await
6145        .unwrap();
6146        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Error);
6147        assert_eq!(
6148            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6149            (1, 0)
6150        );
6151
6152        // Strictly higher epoch: implicit replace — stale install torn down
6153        // (route-gone fired exactly once), new epoch installed and bound.
6154        handle_frame(
6155            route_bind_frame(8, 5, 93),
6156            &tx,
6157            Arc::clone(&handler),
6158            RequestDispatcher::new(),
6159            module_handle.clone(),
6160        )
6161        .await
6162        .unwrap();
6163        assert_eq!(rx.recv().await.unwrap().header.ty, FrameType::Response);
6164        assert_eq!(
6165            (bound.load(Ordering::SeqCst), cleanup.load(Ordering::SeqCst)),
6166            (2, 1)
6167        );
6168        assert!(matches!(
6169            module_handle.validate_route(RouteHandle::new(8, 4, 1)),
6170            Err(SubcModuleError::StaleRouteHandle(_))
6171        ));
6172        module_handle
6173            .validate_route(RouteHandle::new(8, 5, 1))
6174            .expect("epoch-5 install must be live after implicit replace");
6175    }
6176
6177    #[tokio::test]
6178    async fn module_control_corr_is_monotonic_and_exhausts_without_wrap() {
6179        let (module_handle, _rx) = test_module_handle(&[MODULE_TO_SUBC_OP_CATALOG_UPDATE]);
6180        let shared = module_handle.shared();
6181        let mut inner = shared.lock_inner();
6182        inner.next_corr = Some(u64::MAX);
6183        assert_eq!(next_module_control_corr(&mut inner), Some(u64::MAX));
6184        assert_eq!(next_module_control_corr(&mut inner), None);
6185    }
6186}
6187
6188/// How a served module ends when its connection closes, driven against a stand-in
6189/// daemon on a framed in-memory connection with the real writer task and drain.
6190#[cfg(test)]
6191mod module_close_tests {
6192    use std::time::Instant;
6193
6194    use tokio::{io::DuplexStream, sync::Notify};
6195
6196    use super::stand_in::{serve_against_stand_in_with_ops, Served};
6197    use super::*;
6198
6199    /// How the test handler treats the one request it is given.
6200    #[derive(Clone, Copy)]
6201    enum Hold {
6202        /// Hold the request open until it is cancelled, then answer.
6203        UntilCancelled,
6204        /// Hold the request open forever, whatever happens.
6205        IgnoringCancellation,
6206    }
6207
6208    struct HoldingHandler {
6209        hold: Hold,
6210        entered: Arc<Notify>,
6211        token: Arc<Mutex<Option<CancellationToken>>>,
6212    }
6213
6214    #[async_trait]
6215    impl ModuleHandler for HoldingHandler {
6216        async fn handle(&self, ctx: RequestCtx, _body: Vec<u8>) -> HandlerOutcome {
6217            *self.token.lock().unwrap() = Some(ctx.cancellation_token());
6218            self.entered.notify_one();
6219            match self.hold {
6220                Hold::UntilCancelled => {
6221                    ctx.cancelled().await;
6222                    HandlerOutcome::Error {
6223                        code: "cancelled".to_string(),
6224                        message: "request cancelled".to_string(),
6225                    }
6226                }
6227                Hold::IgnoringCancellation => std::future::pending().await,
6228            }
6229        }
6230    }
6231
6232    /// Serve `handler` on the shared stand-in and hand its framed connection to the test.
6233    async fn serve_against_stand_in<H: ModuleHandler>(handler: H) -> Served {
6234        serve_against_stand_in_with_ops(|_| handler, &[]).await
6235    }
6236
6237    async fn send(daemon: &mut DuplexStream, frame: Frame) {
6238        write_frame(daemon, &frame).await.unwrap();
6239        daemon.flush().await.unwrap();
6240    }
6241
6242    /// Bind route 7/1 and send one data request on it, returning once the
6243    /// handler holds it.
6244    async fn hold_one_request(served: &mut Served, entered: &Notify) {
6245        let bind = serde_json::to_vec(&ModuleControlRequest::RouteBind {
6246            route_channel: 7,
6247            epoch: 1,
6248            target: RouteTarget::ToolProvider {
6249                module_id: "close-test".to_string(),
6250            },
6251            identity: BindIdentity::new("test".to_string(), "close".to_string()),
6252            principal: None,
6253            consumer_capabilities: None,
6254            role_versions: None,
6255            admission_facts: None,
6256            scope: None,
6257            call_mode: None,
6258        })
6259        .unwrap();
6260        send(
6261            &mut served.daemon,
6262            Frame::build(FrameType::Request, control_flags(), 0, 0, 2, bind).unwrap(),
6263        )
6264        .await;
6265        loop {
6266            let frame = read_frame(&mut served.daemon).await.unwrap().unwrap();
6267            if frame.header.channel == 0 && frame.header.corr == 2 {
6268                assert_eq!(
6269                    frame.header.ty,
6270                    FrameType::Response,
6271                    "route.bind must be acked"
6272                );
6273                break;
6274            }
6275        }
6276        send(
6277            &mut served.daemon,
6278            Frame::build(FrameType::Request, data_flags(), 7, 1, 10, b"hold".to_vec()).unwrap(),
6279        )
6280        .await;
6281        timeout(Duration::from_secs(2), entered.notified())
6282            .await
6283            .expect("the handler must receive the request");
6284    }
6285
6286    fn goodbye() -> Frame {
6287        Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 0, Vec::new()).unwrap()
6288    }
6289
6290    fn holding(
6291        hold: Hold,
6292    ) -> (
6293        HoldingHandler,
6294        Arc<Notify>,
6295        Arc<Mutex<Option<CancellationToken>>>,
6296    ) {
6297        let entered = Arc::new(Notify::new());
6298        let token = Arc::new(Mutex::new(None));
6299        let handler = HoldingHandler {
6300            hold,
6301            entered: Arc::clone(&entered),
6302            token: Arc::clone(&token),
6303        };
6304        (handler, entered, token)
6305    }
6306
6307    #[tokio::test]
6308    async fn goodbye_cancels_an_open_request_and_the_serve_future_completes() {
6309        let (handler, entered, token) = holding(Hold::UntilCancelled);
6310        let mut served = serve_against_stand_in(handler).await;
6311        hold_one_request(&mut served, &entered).await;
6312
6313        let started = Instant::now();
6314        send(&mut served.daemon, goodbye()).await;
6315        let result = timeout(Duration::from_secs(5), &mut served.serve)
6316            .await
6317            .expect("a held request must not keep the serve future alive after GOODBYE");
6318        result.unwrap().unwrap();
6319        assert!(
6320            token.lock().unwrap().as_ref().unwrap().is_cancelled(),
6321            "GOODBYE must cancel the request's token"
6322        );
6323        // Well inside the writer's drain limit: the handler answered its
6324        // cancellation, so nothing had to be aborted.
6325        assert!(
6326            started.elapsed() < DEFAULT_WRITER_DRAIN_TIMEOUT,
6327            "closing took {:?}",
6328            started.elapsed()
6329        );
6330    }
6331
6332    #[tokio::test]
6333    async fn a_handler_ignoring_cancellation_cannot_keep_the_serve_future_alive() {
6334        let (handler, entered, _token) = holding(Hold::IgnoringCancellation);
6335        let mut served = serve_against_stand_in(handler).await;
6336        hold_one_request(&mut served, &entered).await;
6337
6338        let started = Instant::now();
6339        send(&mut served.daemon, goodbye()).await;
6340        let result = timeout(
6341            DEFAULT_WRITER_DRAIN_TIMEOUT + Duration::from_secs(3),
6342            &mut served.serve,
6343        )
6344        .await
6345        .expect("the writer drain must be bounded");
6346        result.unwrap().unwrap();
6347        assert!(started.elapsed() >= DEFAULT_WRITER_DRAIN_TIMEOUT);
6348    }
6349
6350    #[tokio::test]
6351    async fn closed_resolves_after_goodbye() {
6352        let served = serve_against_stand_in(EchoHandler).await;
6353        let mut served = served;
6354        assert!(!served.handle.is_closed());
6355        let closed = served.handle.closed();
6356        send(&mut served.daemon, goodbye()).await;
6357        timeout(Duration::from_secs(2), closed)
6358            .await
6359            .expect("closed() must resolve after GOODBYE");
6360        assert!(served.handle.is_closed());
6361    }
6362
6363    #[tokio::test]
6364    async fn closed_resolves_after_eof() {
6365        let Served {
6366            daemon,
6367            handle,
6368            serve: _serve,
6369        } = serve_against_stand_in(EchoHandler).await;
6370        assert!(!handle.is_closed());
6371        drop(daemon);
6372        timeout(Duration::from_secs(2), handle.closed())
6373            .await
6374            .expect("closed() must resolve after EOF");
6375        assert!(handle.is_closed());
6376    }
6377
6378    struct EchoHandler;
6379
6380    #[async_trait]
6381    impl ModuleHandler for EchoHandler {
6382        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6383            HandlerOutcome::Response(body)
6384        }
6385    }
6386
6387    /// Records every `on_connection_end` call, so a test can assert both the
6388    /// cause and that it was reported exactly once.
6389    #[derive(Clone, Default)]
6390    struct EndRecorder(Arc<Mutex<Vec<ConnectionEnd>>>);
6391
6392    #[async_trait]
6393    impl ModuleHandler for EndRecorder {
6394        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6395            HandlerOutcome::Response(body)
6396        }
6397        async fn on_connection_end(&self, end: ConnectionEnd) {
6398            self.0.lock().unwrap().push(end);
6399        }
6400    }
6401
6402    async fn reported_end(recorder: &EndRecorder, served: &mut Served) -> Vec<ConnectionEnd> {
6403        timeout(Duration::from_secs(5), &mut served.serve)
6404            .await
6405            .expect("serving must end")
6406            .unwrap()
6407            .unwrap();
6408        recorder.0.lock().unwrap().clone()
6409    }
6410
6411    #[tokio::test]
6412    async fn a_daemon_goodbye_is_reported_as_goodbye() {
6413        let recorder = EndRecorder::default();
6414        let mut served = serve_against_stand_in(recorder.clone()).await;
6415        send(&mut served.daemon, goodbye()).await;
6416        assert_eq!(
6417            reported_end(&recorder, &mut served).await,
6418            vec![ConnectionEnd::Goodbye]
6419        );
6420    }
6421
6422    #[tokio::test]
6423    async fn a_daemon_closing_without_goodbye_is_reported_as_eof() {
6424        let recorder = EndRecorder::default();
6425        let mut served = serve_against_stand_in(recorder.clone()).await;
6426        served.daemon.shutdown().await.unwrap();
6427        assert_eq!(
6428            reported_end(&recorder, &mut served).await,
6429            vec![ConnectionEnd::Eof]
6430        );
6431    }
6432
6433    /// What a drain-recording handler saw, in the order it saw it.
6434    #[derive(Debug, Clone, PartialEq)]
6435    enum Seen {
6436        Draining(RouteCloseReason, SystemTime),
6437        End(ConnectionEnd),
6438    }
6439
6440    /// Records drain notices and the connection end. With `park` set, the
6441    /// drain hook never returns after recording, to stand for a slow hook.
6442    #[derive(Clone, Default)]
6443    struct DrainRecorder {
6444        seen: Arc<Mutex<Vec<Seen>>>,
6445        park: bool,
6446    }
6447
6448    #[async_trait]
6449    impl ModuleHandler for DrainRecorder {
6450        async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6451            HandlerOutcome::Response(body)
6452        }
6453        async fn on_draining(&self, reason: RouteCloseReason, deadline: SystemTime) {
6454            self.seen
6455                .lock()
6456                .unwrap()
6457                .push(Seen::Draining(reason, deadline));
6458            if self.park {
6459                std::future::pending::<()>().await;
6460            }
6461        }
6462        async fn on_connection_end(&self, end: ConnectionEnd) {
6463            self.seen.lock().unwrap().push(Seen::End(end));
6464        }
6465    }
6466
6467    fn control_push(body: &[u8]) -> Frame {
6468        Frame::build(FrameType::Push, control_flags(), 0, 0, 0, body.to_vec()).unwrap()
6469    }
6470
6471    fn draining_push(reason: subc_protocol::RouteCloseReason, deadline_ms: u64) -> Frame {
6472        control_push(
6473            &serde_json::to_vec(&ModuleControlCommand::Draining {
6474                reason,
6475                deadline_ms,
6476            })
6477            .unwrap(),
6478        )
6479    }
6480
6481    #[tokio::test]
6482    async fn accepting_drain_notice_exposes_the_marker_only_on_that_notice() {
6483        struct Recorder(Arc<Mutex<Vec<bool>>>);
6484
6485        #[async_trait]
6486        impl ModuleHandler for Recorder {
6487            async fn handle(&self, _ctx: RequestCtx, body: Vec<u8>) -> HandlerOutcome {
6488                HandlerOutcome::Response(body)
6489            }
6490
6491            async fn on_draining_notice(&self, notice: DrainNotice) {
6492                self.0.lock().unwrap().push(notice.accepting);
6493            }
6494        }
6495
6496        let recorded = Arc::new(Mutex::new(Vec::new()));
6497        let mut served = serve_against_stand_in(Recorder(recorded.clone())).await;
6498        send(&mut served.daemon, control_push(br#"{"op":"module.draining","reason":"restart","deadline_ms":1000,"accepting":true}"#)).await;
6499        ping_is_answered(&mut served, 90).await;
6500        send(
6501            &mut served.daemon,
6502            draining_push(subc_protocol::RouteCloseReason::Restart, 1000),
6503        )
6504        .await;
6505        send(&mut served.daemon, goodbye()).await;
6506        timeout(Duration::from_secs(5), &mut served.serve)
6507            .await
6508            .unwrap()
6509            .unwrap()
6510            .unwrap();
6511        assert_eq!(*recorded.lock().unwrap(), [true, false]);
6512    }
6513
6514    /// Send a channel-0 PING and require the PONG, proving the frame reader
6515    /// is still serving.
6516    async fn ping_is_answered(served: &mut Served, corr: u64) {
6517        send(
6518            &mut served.daemon,
6519            Frame::build(FrameType::Ping, control_flags(), 0, 0, corr, Vec::new()).unwrap(),
6520        )
6521        .await;
6522        let pong = timeout(Duration::from_secs(2), read_frame(&mut served.daemon))
6523            .await
6524            .expect("the module must answer PING")
6525            .unwrap()
6526            .expect("the module must not close the connection");
6527        assert_eq!(pong.header.ty, FrameType::Pong);
6528        assert_eq!(pong.header.corr, corr);
6529    }
6530
6531    /// The daemon sends `module.draining` and, once the drain settles, GOODBYE;
6532    /// with nothing to wait for, both can land in one read. The hook runs on its
6533    /// own task, and must still be called before the GOODBYE is acted on.
6534    #[tokio::test]
6535    async fn a_drain_notice_calls_on_draining_before_the_goodbye_that_follows_it() {
6536        let recorder = DrainRecorder::default();
6537        let mut served = serve_against_stand_in(recorder.clone()).await;
6538        // Any fixed value works; this one (2100-01-01T00:00:00Z) is far enough
6539        // ahead to be plainly a future deadline.
6540        let deadline_ms = 4_102_444_800_000;
6541        write_frame(
6542            &mut served.daemon,
6543            &draining_push(subc_protocol::RouteCloseReason::Restart, deadline_ms),
6544        )
6545        .await
6546        .unwrap();
6547        write_frame(&mut served.daemon, &goodbye()).await.unwrap();
6548        served.daemon.flush().await.unwrap();
6549
6550        timeout(Duration::from_secs(5), &mut served.serve)
6551            .await
6552            .expect("serving must end after GOODBYE")
6553            .unwrap()
6554            .unwrap();
6555        assert_eq!(
6556            *recorder.seen.lock().unwrap(),
6557            vec![
6558                Seen::Draining(
6559                    RouteCloseReason::Restart,
6560                    UNIX_EPOCH + Duration::from_millis(deadline_ms)
6561                ),
6562                Seen::End(ConnectionEnd::Goodbye),
6563            ]
6564        );
6565    }
6566
6567    /// A drain lasts until the daemon's deadline, and the daemon keeps pinging
6568    /// through it; a hook still busy must not stop the module answering.
6569    #[tokio::test]
6570    async fn a_drain_hook_that_never_returns_does_not_stop_the_frame_reader() {
6571        let recorder = DrainRecorder {
6572            park: true,
6573            ..DrainRecorder::default()
6574        };
6575        let mut served = serve_against_stand_in(recorder.clone()).await;
6576        send(
6577            &mut served.daemon,
6578            draining_push(subc_protocol::RouteCloseReason::Reload, 1),
6579        )
6580        .await;
6581        ping_is_answered(&mut served, 41).await;
6582        assert!(matches!(
6583            recorder.seen.lock().unwrap().as_slice(),
6584            [Seen::Draining(RouteCloseReason::Reload, _)]
6585        ));
6586
6587        send(&mut served.daemon, goodbye()).await;
6588        timeout(Duration::from_secs(5), &mut served.serve)
6589            .await
6590            .expect("a parked drain hook must not keep the serve future alive")
6591            .unwrap()
6592            .unwrap();
6593    }
6594
6595    /// A channel-0 push this SDK cannot decode (a newer daemon's command, or a
6596    /// malformed body) is ignored: no hook is called and the connection keeps
6597    /// serving.
6598    #[tokio::test]
6599    async fn an_undecodable_channel_zero_push_is_ignored_and_the_connection_stays_up() {
6600        let recorder = DrainRecorder::default();
6601        let mut served = serve_against_stand_in(recorder.clone()).await;
6602        send(
6603            &mut served.daemon,
6604            control_push(br#"{"op":"module.some_future_command","x":1}"#),
6605        )
6606        .await;
6607        send(&mut served.daemon, control_push(b"not json")).await;
6608        send(
6609            &mut served.daemon,
6610            control_push(br#"{"op":"module.draining","reason":"restart"}"#),
6611        )
6612        .await;
6613        ping_is_answered(&mut served, 42).await;
6614        assert!(!served.handle.is_closed());
6615        assert!(!served.serve.is_finished());
6616        assert!(recorder.seen.lock().unwrap().is_empty());
6617    }
6618
6619    #[tokio::test]
6620    async fn a_module_closing_its_own_connection_is_reported_as_closed() {
6621        let recorder = EndRecorder::default();
6622        let mut served = serve_against_stand_in(recorder.clone()).await;
6623        served.handle.close_connection();
6624        assert_eq!(
6625            reported_end(&recorder, &mut served).await,
6626            vec![ConnectionEnd::Closed]
6627        );
6628    }
6629}
6630
6631#[cfg(test)]
6632mod operator_confirm_tests;
6633
6634#[cfg(test)]
6635mod binary_reply_tests;
6636
6637#[cfg(test)]
6638mod serve_lifecycle_tests;
6639
6640#[cfg(test)]
6641mod request_pool_tests;
6642
6643#[cfg(test)]
6644mod detailed_error_body_tests {
6645    use serde_json::json;
6646
6647    use subc_protocol::ErrorBody;
6648
6649    /// The wire bytes a detail-carrying module error serializes to are pinned
6650    /// here because subc-mcp and route consumers parse them; the shape predates
6651    /// ErrorBody.detail and must not drift now that ErrorBody subsumes it.
6652    #[test]
6653    fn detailed_error_body_keeps_code_message_and_detail() {
6654        let body = ErrorBody::new("bad_request", "invalid envelope")
6655            .with_detail(json!({"reason": "missing_server"}));
6656
6657        assert_eq!(
6658            serde_json::to_value(body).unwrap(),
6659            json!({
6660                "code": "bad_request",
6661                "message": "invalid envelope",
6662                "detail": {"reason": "missing_server"},
6663            })
6664        );
6665    }
6666
6667    /// A detail-less body serializes byte-identically to the pre-detail wire:
6668    /// deserializing the old two-field shape and re-serializing adds nothing.
6669    #[test]
6670    fn detail_less_error_body_is_byte_identical_to_the_pre_detail_wire() {
6671        let old_wire = r#"{"code":"cancelled","message":"caller cancelled"}"#;
6672        let parsed: ErrorBody = serde_json::from_str(old_wire).unwrap();
6673        assert_eq!(parsed.detail, None);
6674        assert_eq!(serde_json::to_string(&parsed).unwrap(), old_wire);
6675    }
6676}
6677
6678// A reserved module may scrub its launch nonce before it opens a daemon
6679// connection. The retained copy exists only for encoding that module's HELLO.
6680static RETAINED_LAUNCH_NONCE: std::sync::OnceLock<String> = std::sync::OnceLock::new();
6681
6682/// Retain a reserved module's launch nonce for its HELLO after the module has
6683/// scrubbed the nonce from the process environment.
6684pub fn retain_launch_nonce_for_hello(launch_nonce: String) -> Result<(), String> {
6685    RETAINED_LAUNCH_NONCE
6686        .set(launch_nonce)
6687        .map_err(|_| "launch nonce was already retained for this process".to_string())
6688}
6689
6690fn retained_launch_nonce() -> Option<String> {
6691    RETAINED_LAUNCH_NONCE.get().cloned()
6692}
6693
6694/// The cached launch-nonce source (`fd`, `pipe` or `env`), or `None` when no
6695/// nonce is available. The SDK records this in the registration message's
6696/// `manifest.provenance.launch_nonce_source`; the daemon stores that declaration
6697/// for `ck provenance` to display. A module constructing that record can use:
6698/// `.with_launch_nonce_source(subc_client_rs::launch_nonce_source())`.
6699pub fn launch_nonce_source() -> Option<LaunchNonceSource> {
6700    launch_nonce()
6701        .ok()
6702        .flatten()
6703        .map(|nonce| LaunchNonceSource::from_wire_name(nonce.source().as_str()))
6704}
6705
6706/// Fill in `launch_nonce_source` on a module's declared provenance, so
6707/// `ck provenance` can tell a module reading the pipe from one still reading
6708/// the environment variable. Only when the module declared provenance and left the field
6709/// unset. A registration channel supplies authority without sending a nonce,
6710/// but an unstamped launch may still supply a legacy nonce whose source is
6711/// diagnostic. Otherwise the nonce HELLO carries must be the one the accessor
6712/// read: a module-retained nonce may have come from somewhere else.
6713fn stamp_launch_nonce_source(manifest: &mut ModuleManifest, sent: Option<&str>) {
6714    let Some(provenance) = manifest.provenance.as_mut() else {
6715        return;
6716    };
6717    if provenance.launch_nonce_source.is_some() {
6718        return;
6719    }
6720    if let Ok(Some(nonce)) = launch_nonce() {
6721        // A re-export may send the owner's legacy nonce, but cannot claim the
6722        // launched module's nonce provenance.
6723        let launched = registration::is_launched_module(&manifest.module_id).unwrap_or(false);
6724        if launched && (registration::supervised() || sent == Some(nonce.value())) {
6725            provenance.launch_nonce_source =
6726                Some(LaunchNonceSource::from_wire_name(nonce.source().as_str()));
6727        }
6728    }
6729}
6730
6731#[cfg(test)]
6732mod checked_increment_tests {
6733    use super::checked_increment;
6734    use std::sync::atomic::{AtomicU64, Ordering};
6735
6736    #[test]
6737    fn returns_the_previous_value_and_stops_at_the_maximum() {
6738        let counter = AtomicU64::new(7);
6739        assert_eq!(checked_increment(&counter), Some(7));
6740        assert_eq!(counter.load(Ordering::Relaxed), 8);
6741
6742        let full = AtomicU64::new(u64::MAX);
6743        assert_eq!(checked_increment(&full), None);
6744        assert_eq!(
6745            full.load(Ordering::Relaxed),
6746            u64::MAX,
6747            "an exhausted counter is left unchanged"
6748        );
6749    }
6750}