Skip to main content

subc_daemon/
control.rs

1#[path = "control/list_diagnostics.rs"]
2pub(crate) mod list_diagnostics;
3mod route_open_refusal_log;
4
5use std::{
6    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
7    fmt,
8    net::SocketAddr,
9    path::{Path, PathBuf},
10    sync::{Arc, Mutex, RwLock},
11    time::{Duration, Instant as StdInstant},
12};
13
14use crate::scopes::admission::denied_capability;
15use serde::{Deserialize, Serialize};
16use subc_control::{
17    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
18    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
19    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PendingReloadVerdict, PollKind,
20    ReloadPathAgreement, ReloadPathUnavailableReason, RouteCloseReason, SpawnCursor,
21    StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance, SupervisorEntry,
22    SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
23    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
24};
25use subc_protocol::{
26    call_mode::{derive_call_mode, CALL_MODES_CAPABILITY},
27    error_codes,
28    manifest::{
29        validate_hello_capability_grammar, validate_hello_confirm_operations,
30        validate_hello_display_name, validate_hello_event_declarations,
31        validate_hello_flow_operations, validate_hello_operation_deferral,
32        validate_hello_rich_ui_descriptor, validate_hello_role_declarations,
33        validate_hello_self_signal_declarations, validate_role_declarations_value,
34        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
35        ProviderRole,
36    },
37    peer::{
38        ObservedPeer, RouteBindPeer, OBSERVED_PEER_CAPABILITY, OPERATOR_APP_CAPABILITY,
39        PEER_BUILD_CAPABILITY,
40    },
41    provider_declarations::ProviderDeclarations,
42    scope::{
43        ScopeEnd, ScopeRecord, ScopeRecordOutcome, ScopeRecordResult, ScopeSelector,
44        CAP_ROUTE_ROLE_VERSIONS_V1, CAP_SCOPES_V1, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP,
45        SCOPE_SYNC_OP,
46    },
47    session::{
48        validate_role_versions, HealthReport, ModuleControlPush, ModuleControlRequest,
49        ModuleControlRequestFromModule, ModuleControlResponse, ModuleControlResponseToModule,
50        OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK, MODULE_TO_SUBC_OP_CATALOG_UPDATE,
51        MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS, ROLE_VERSIONS_FIELD,
52    },
53    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
54    Priority, RouteTarget, PROTOCOL_VERSION,
55};
56use tokio::time::{timeout_at, Instant};
57use tracing::{debug, info, instrument::WithSubscriber, warn};
58
59use crate::{
60    caller_identity::CallerIdentity,
61    capability_requirements::{
62        log_duplicate_claim_events, log_manifest_change, log_requirement_events,
63        CapabilityRequirementEvaluator, CapabilityVerdict, DuplicateClaimSource, RegisteredModule,
64        RequirementStatus, RuntimeModule,
65    },
66    child_roster::DaemonShutdownFlag,
67    daemon_config::{PrivilegedOperatorPrompt, RestartRequiredSection},
68    forwarding::{
69        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
70        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
71        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
72    },
73    observability::{
74        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
75    },
76    privileged_prompt::{prompt_text, PrivilegedOperation},
77    provenance::{
78        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
79    },
80    registry::{ChannelState, ConnectionId, RegistrationEndReason, Registry, RegistryError},
81    router::{daemon_error_flags, RouteCtx, RouterError},
82    scopes::{HelloLaunchNonces, ScopeRecords, ScopeTable},
83    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
84    stderr_tail::{CaptureState, TailEntry},
85    supervise::{
86        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, ReservedHelloVerification,
87        SpawnSubscribeRefusal, SupervisorHandle, SwapHelloAdmission,
88    },
89    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
90};
91
92/// Lowest envelope version this subc build will negotiate.
93///
94/// Module HELLO negotiation is exact: peers must use the daemon's locked
95/// protocol version. Older and newer peers receive `version_unsupported` and
96/// are not registered.
97pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
98
99mod route_open;
100use route_open::is_routable_role;
101use route_open::principal_label;
102#[cfg(test)]
103use route_open::RouteBindAdmission;
104pub(crate) use route_open::RouteBindBreakers;
105pub(crate) use route_open::RouteBindConcurrency;
106use route_open::RouteOpenCaller;
107use route_open::RouteOpenRequest;
108use route_open::RouteOpenTimings;
109pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN;
110pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD;
111pub use route_open::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT;
112
113mod server_describe;
114use server_describe::subc_ops;
115use server_describe::CAP_ADMISSION_FACTS_RELAY;
116use server_describe::CAP_CHANNEL_LIFECYCLE;
117use server_describe::CAP_MANIFEST_REGISTRATION;
118use server_describe::CAP_PING_PONG;
119use server_describe::CAP_SESSION_ATTACH;
120
121mod supervisor_operations;
122use supervisor_operations::launch_spec_agreement;
123#[cfg(test)]
124use supervisor_operations::reload_verdict;
125use supervisor_operations::DaemonProvenanceFacts;
126use supervisor_operations::ModuleControlRpcGuard;
127use supervisor_operations::DEFAULT_HEALTH_PROBE_TIMEOUT;
128
129mod activity;
130#[cfg(test)]
131use activity::ActivityRequestPause;
132
133mod scopes;
134#[cfg(test)]
135use scopes::ScopeOutcomeCounts;
136
137mod module_operations;
138use module_operations::is_known_module_request_op;
139use module_operations::manifest_concurrency;
140#[cfg(test)]
141use module_operations::manifest_concurrency_was_defaulted;
142#[cfg(test)]
143use module_operations::module_baseline_control_ops;
144use module_operations::module_control_request_op;
145use module_operations::module_registration_grants_op;
146use module_operations::parse_module_control_request_from_module;
147#[cfg(all(test, unix, feature = "test-support"))]
148use module_operations::MODULE_TO_SUBC_UNADVERTISED_OPS;
149mod advertised_ops;
150use advertised_ops::*;
151mod caller_attestation;
152mod channel_operations;
153#[cfg(all(test, unix, feature = "test-support"))]
154#[path = "control/channel_operations_tests.rs"]
155mod channel_operations_tests;
156pub(crate) mod claims;
157#[cfg(test)]
158#[path = "control/config_advertisement_tests.rs"]
159mod config_advertisement_tests;
160mod config_gate;
161#[path = "operator_apps/connection.rs"]
162mod peer_identity;
163use caller_attestation::scope_acts_for_another;
164mod activity_reservations;
165#[cfg(all(test, unix, feature = "test-support"))]
166#[path = "control/caller_attestation_tests.rs"]
167mod caller_attestation_tests;
168mod capability_census;
169use capability_census::append_capability_problem_detail;
170use capability_census::capability_census_trigger;
171mod route_bind_settlement;
172mod scope_expiry;
173mod scope_watch;
174mod usage;
175
176mod agent_commands;
177pub(crate) mod catalog;
178mod policy_root;
179mod rescan_checked;
180pub(crate) mod upgrade_in_place;
181use rescan_checked::RescanMode;
182use rescan_checked::SupervisorRescanContext;
183
184const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
185
186/// A test hold: signal arrival, then wait for release on the holding thread.
187#[cfg(test)]
188type TestPause = (
189    tokio::sync::oneshot::Sender<()>,
190    std::sync::mpsc::Receiver<()>,
191);
192
193/// A test hook run once at a fixed point in a handler.
194#[cfg(test)]
195type TestHook = Box<dyn FnOnce() + Send>;
196
197/// A test hold for async code: signal arrival, then await release.
198#[cfg(test)]
199type AsyncTestPause = (
200    tokio::sync::oneshot::Sender<()>,
201    tokio::sync::oneshot::Receiver<()>,
202);
203
204/// Accept-time diagnostics, kept apart from peer observations used for trust.
205#[derive(Clone)]
206pub(crate) enum RouteOpenerConnection {
207    Local(Option<subc_os::local_peer::DiagnosticProcess>),
208    Tcp,
209}
210
211/// Real channel-0 control handler for subc itself.
212#[derive(Clone)]
213pub struct ControlHandler {
214    #[cfg(test)]
215    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
216    /// Holds connection cleanup at a numbered point: 0 is just after the agent
217    /// declaration queue closes, 1 just after the registration channel is
218    /// forgotten.
219    #[cfg(test)]
220    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
221    /// Runs once in `route.open`'s launch-nonce attestation, right after the
222    /// nonce is resolved, to interleave a nonce withdrawal there.
223    #[cfg(test)]
224    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
225    /// Holds a registration channel's HELLO after its reader resolved the
226    /// channel and before the blocking HELLO handler starts.
227    #[cfg(test)]
228    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
229    /// Holds an agent command declaration at a numbered point in its handler.
230    #[cfg(test)]
231    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
232    claims: Arc<claims::Claims>,
233    registry: Arc<Registry>,
234    control_usage: Arc<Mutex<usage::ControlUsage>>,
235    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
236    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
237    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
238    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
239    config_review_admission_is_default: bool,
240    activity: Option<crate::activity::ActivityLedger>,
241    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
242    activity_reservations: activity_reservations::ActivityReservations,
243    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
244    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
245    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
246    forwarding: Arc<ForwardingTable>,
247    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
248    supervisor: SupervisorHandle,
249    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
250    agent_declarations: agent_commands::Queues,
251    list_admission: Arc<tokio::sync::Semaphore>,
252    subc_capabilities: Arc<[String]>,
253    /// Daemon-wide route.bind relay budget. Used as the fallback when the
254    /// target module has no per-module override in
255    /// `route_bind_relay_timeouts`.
256    route_bind_relay_timeout: Duration,
257    /// Per-module route.bind relay budget overrides, keyed by module id. When
258    /// `handle_route_open` resolves the deadline for a target module, a
259    /// per-module entry wins over the daemon-wide value above.
260    route_bind_relay_timeouts: BTreeMap<String, Duration>,
261    /// Per-target-module bind-relay breaker state. Shared with the forwarding
262    /// table, which is where a new module connection resets it.
263    route_bind_breakers: RouteBindBreakers,
264    /// Live relay admissions keyed by target module. Shared through the
265    /// forwarding table so cloned or separately built handlers enforce one cap.
266    route_bind_concurrency: RouteBindConcurrency,
267    /// Start and end of each module's not-serving period as seen by
268    /// `route.open`, so an outage gets one line at each edge instead of only
269    /// the per-refusal INFO lines. Taken from the forwarding table, so every
270    /// handler built over one table shares it.
271    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
272    route_refusal_log: route_open_refusal_log::RefusalLog,
273    /// Consecutive relay timeouts that open a module's breaker.
274    route_bind_breaker_threshold: u32,
275    /// How long a breaker stays open before one probe is admitted.
276    route_bind_breaker_cooldown: Duration,
277    health_probe_timeout: Duration,
278    /// Central storage policy. When set, each registering module receives its
279    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
280    storage_config: Option<crate::daemon_config::StorageConfig>,
281    /// The machine id established at boot, served on every HELLO_ACK and on
282    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
283    /// changes the file, never this value. `None` serves no id.
284    machine_id: Option<crate::machine_id::MachineId>,
285    admission_facts_carrier_module_id: Option<String>,
286    admission_facts_targets: Option<Vec<String>>,
287    /// Scope records with their sync authorities and tombstones; see
288    /// `crate::scopes`. Shared by clones of this handler, so every connection
289    /// reads and writes one table.
290    scopes: Arc<RwLock<ScopeTable>>,
291    /// Wakes the expiry loop when an accepted scope change may have added a
292    /// deadline, so the loop can wait without ticking while no live scope has
293    /// one. A permit is stored when nothing waits, so no wake is lost.
294    scope_deadline_added: Arc<tokio::sync::Notify>,
295    /// The configured `scope_authority_owners`, kept so a rescan can report a
296    /// changed value as needing a daemon restart; rescan never applies it.
297    scope_authority_owners: Vec<String>,
298    federated_scope_owner: String,
299    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
300    privileged_operator_prompt: PrivilegedOperatorPrompt,
301    /// The local and peer address of each accepted TCP client connection, read
302    /// from the daemon's own socket, so a privileged request can name its caller.
303    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
304    route_openers: Arc<Mutex<HashMap<ConnectionId, RouteOpenerConnection>>>,
305    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
306    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
307    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
308    config_desktop_stamps:
309        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
310    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
311    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
312    pub(crate) operator_apps:
313        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
314    /// One launch entry per app, behind a leaf lock: no other lock is taken
315    /// while it is held. Entries are memory-only, so a daemon or
316    /// installed-service restart drops them and a relaunched daemon never
317    /// mistakes an older process for its own launch.
318    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
319    /// Serializes `app.open` launches: the liveness check in the decision and
320    /// the later publish must not interleave across concurrent calls, or two
321    /// calls could both launch and the second publish would orphan the first
322    /// process. Refusals and `already_running` answers share the same lock;
323    /// `app.open` is rare, so the cost is negligible.
324    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
325    // Portable wire samples exercise dispatch without starting an OS process.
326    #[cfg(test)]
327    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
328    #[cfg(test)]
329    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
330    #[cfg(test)]
331    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
332    #[cfg(test)]
333    pub(crate) config_review_test_replies:
334        std::collections::BTreeMap<String, subc_protocol::config::ConfigReviewReply>,
335    #[cfg(test)]
336    pub(crate) config_review_test_seen: Option<tokio::sync::mpsc::UnboundedSender<String>>,
337    #[cfg(test)]
338    pub(crate) config_review_test_refuse: Arc<std::sync::Mutex<std::collections::BTreeSet<String>>>,
339    #[cfg(test)]
340    pub(crate) config_review_test_fail_once: Arc<std::sync::atomic::AtomicBool>,
341    #[cfg(test)]
342    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
343    #[cfg(test)]
344    recovery_exit_test_completed: Option<fn(u64)>,
345    #[cfg(test)]
346    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
347    #[cfg(test)]
348    recovery_exit_test_quiet_retry: bool,
349    #[cfg(test)]
350    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
351    #[cfg(test)]
352    config_delivery_test_wakes:
353        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
354    #[cfg(all(test, unix))]
355    config_delivery_test_idle:
356        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
357    #[cfg(all(test, unix))]
358    settings_poll_test_idle:
359        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
360    /// Test-only Windows signature and flash hooks. Production builds carry
361    /// neither: with the publisher unset, the production table never reaches
362    /// verification, and the default attention hook only logs.
363    #[allow(dead_code)]
364    #[cfg(windows)]
365    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
366    #[allow(dead_code)]
367    #[cfg(windows)]
368    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
369    /// Test-only tracking fault hook: makes opening the tracking handle on
370    /// the launched pid fail, so a test can prove an untrackable launch is
371    /// stopped rather than left running.
372    #[allow(dead_code)]
373    #[cfg(windows)]
374    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
375    /// Test-only count of Windows spawn attempts, so a test can prove a
376    /// refused launch started no process. Unit tests only.
377    #[cfg(all(test, windows))]
378    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
379    #[cfg(test)]
380    caller_lookup: Option<TestCallerLookup>,
381    /// The launch nonce each module connection presented at HELLO, which is how
382    /// a `scope.sync` is matched to the owner's current launch.
383    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
384    rescan: Option<SupervisorRescanContext>,
385    connected_clients: ConnectedClients,
386    counters: DaemonCounters,
387    /// Why this daemon serves no local endpoint, when binding one failed. `None`
388    /// when the endpoint is served, and also on a handler that was never told.
389    local_endpoint_unavailable: Option<String>,
390    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
391    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
392    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
393    /// their usual severity (see [`log_requirement_events`]). A handler built
394    /// without one has a flag that is never set.
395    daemon_shutdown: DaemonShutdownFlag,
396    #[cfg(any(target_os = "linux", target_os = "macos"))]
397    pub(crate) upgrade: Option<Arc<upgrade_in_place::Runtime>>,
398    daemon_provenance: DaemonProvenanceFacts,
399    #[cfg(test)]
400    control_dispatch_delay: Option<Duration>,
401    #[cfg(test)]
402    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
403    /// Holds `route.open` after the route.bind is queued to the module and
404    /// before it is marked enqueued, so a test can make the module's reply (or
405    /// a client teardown) land exactly inside that window.
406    #[cfg(test)]
407    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
408    /// Holds a HELLO after its registry entry is reserved and before its
409    /// forwarding endpoint is installed, so a test can read the catalog and
410    /// open routes while the module is registered but not yet routable. A
411    /// blocking barrier because the HELLO handler is synchronous; the test
412    /// runs the HELLO on its own thread.
413    #[cfg(test)]
414    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
415    #[cfg(test)]
416    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
417    #[cfg(test)]
418    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
419    #[cfg(test)]
420    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
421    #[cfg(test)]
422    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
423}
424
425impl fmt::Debug for ControlHandler {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        f.debug_struct("ControlHandler")
428            .field("registry", &self.registry)
429            .field("forwarding", &self.forwarding)
430            .field("process_liveness", &self.process_liveness.is_some())
431            .field("supervisor", &self.supervisor)
432            .field("subc_capabilities", &self.subc_capabilities)
433            .finish()
434    }
435}
436
437impl ControlHandler {
438    pub(crate) fn install_registration_service(
439        &self,
440        router: std::sync::Weak<crate::Router>,
441        auth: crate::server::ServerAuth,
442    ) {
443        self.supervisor.install_registration_service(router, auth);
444    }
445    pub fn new(registry: Arc<Registry>) -> Self {
446        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
447    }
448
449    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
450        let counters = forwarding.counters();
451        // Taken from the forwarding table rather than created here, so that the
452        // breaker a `route.open` consults is the same one a module's
453        // registration resets, however many handlers are built over one table.
454        let route_bind_breakers = forwarding.route_bind_breakers();
455        let route_bind_concurrency = forwarding.route_bind_concurrency();
456        let route_outages = forwarding.route_outages();
457        Self {
458            registry,
459            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
460            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
461            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
462            #[cfg(test)]
463            activity_request_pause: Arc::new(Mutex::new(None)),
464            #[cfg(test)]
465            cleanup_pause: Arc::new(Mutex::new(None)),
466            #[cfg(test)]
467            after_nonce_attestation: Arc::new(Mutex::new(None)),
468            #[cfg(test)]
469            hello_ingress_pause: Arc::new(Mutex::new(None)),
470            #[cfg(test)]
471            agent_commands_pause: Arc::new(Mutex::new(None)),
472            claims: Arc::new(claims::Claims::default()),
473            config_runtime: None,
474            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
475            config_review_admission_is_default: true,
476            activity: None,
477            activity_streams: Arc::new(Mutex::new(HashMap::new())),
478            activity_reservations: Default::default(),
479            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
480            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
481            scope_streams: Arc::new(Mutex::new(HashMap::new())),
482            forwarding,
483            process_liveness: None,
484            supervisor: SupervisorHandle::new(),
485            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
486                env!("CARGO_PKG_VERSION").to_owned(),
487            )),
488            agent_declarations: agent_commands::Queues::default(),
489            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
490            subc_capabilities: Arc::from([
491                CAP_MANIFEST_REGISTRATION.to_string(),
492                CAP_CHANNEL_LIFECYCLE.to_string(),
493                CAP_PING_PONG.to_string(),
494                CAP_SESSION_ATTACH.to_string(),
495                CAP_ADMISSION_FACTS_RELAY.to_string(),
496                CAP_SCOPES_V1.to_string(),
497                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
498                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
499                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
500                PEER_BUILD_CAPABILITY.to_string(),
501                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
502                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
503                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
504                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
505                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
506                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
507                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
508                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
509                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
510                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
511                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
512                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
513                subc_protocol::session::ACCEPTING_DRAIN_CAPABILITY.to_string(),
514            ]),
515            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
516            route_bind_relay_timeouts: BTreeMap::new(),
517            route_bind_breakers,
518            route_bind_concurrency,
519            route_outages,
520            route_refusal_log: Default::default(),
521            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
522            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
523            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
524            storage_config: None,
525            machine_id: None,
526            admission_facts_carrier_module_id: None,
527            admission_facts_targets: None,
528            scopes: Arc::new(RwLock::new(ScopeTable::new(
529                crate::daemon_config::default_scope_authority_owners(),
530            ))),
531            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
532            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
533            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
534            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
535            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
536            route_openers: Arc::new(Mutex::new(HashMap::new())),
537            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
538            observed_peers: Arc::new(Mutex::new(HashMap::new())),
539            captured_peers: Arc::new(Mutex::new(HashMap::new())),
540            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
541            local_connections: Arc::new(Mutex::new(HashSet::new())),
542            operator_app_policy: Default::default(),
543            operator_apps: Arc::new(Mutex::new(HashMap::new())),
544            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
545            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
546            #[cfg(test)]
547            app_open_test_platform: None,
548            #[cfg(test)]
549            app_open_test_launch: None,
550            #[cfg(test)]
551            config_review_test_reply: None,
552            #[cfg(test)]
553            config_review_test_replies: Default::default(),
554            #[cfg(test)]
555            config_review_test_seen: None,
556            #[cfg(test)]
557            config_review_test_refuse: Default::default(),
558            #[cfg(test)]
559            config_review_test_fail_once: Default::default(),
560            #[cfg(test)]
561            recovery_exit_test_after_step: None,
562            #[cfg(test)]
563            recovery_exit_test_completed: None,
564            #[cfg(test)]
565            apply_reconcile_pause: Arc::new(Mutex::new(None)),
566            #[cfg(test)]
567            recovery_exit_test_quiet_retry: false,
568            #[cfg(test)]
569            recovery_exit_test_retry_pause: None,
570            #[cfg(test)]
571            config_delivery_test_wakes: None,
572            #[cfg(all(test, unix))]
573            config_delivery_test_idle: None,
574            #[cfg(all(test, unix))]
575            settings_poll_test_idle: None,
576            #[cfg(windows)]
577            windows_verify: None,
578            #[cfg(windows)]
579            windows_flash: None,
580            #[cfg(windows)]
581            windows_track: None,
582            #[cfg(all(test, windows))]
583            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
584            #[cfg(test)]
585            caller_lookup: None,
586            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
587            rescan: None,
588            connected_clients: ConnectedClients::new(),
589            local_endpoint_unavailable: None,
590            counters,
591            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
592            daemon_shutdown: DaemonShutdownFlag::default(),
593            #[cfg(any(target_os = "linux", target_os = "macos"))]
594            upgrade: None,
595            daemon_provenance: DaemonProvenanceFacts::default(),
596            #[cfg(test)]
597            control_dispatch_delay: None,
598            #[cfg(test)]
599            provenance_probe_override: None,
600            #[cfg(test)]
601            route_bind_relay_sent_hold: None,
602            #[cfg(test)]
603            hello_registry_to_forwarding_hold: None,
604            #[cfg(test)]
605            hello_ack_to_publication_hold: None,
606            #[cfg(test)]
607            hello_before_publication_hold: None,
608            #[cfg(test)]
609            hello_after_launch_check_hold: None,
610            #[cfg(test)]
611            hello_inside_publication_hold: None,
612        }
613    }
614
615    /// Set the central storage policy: registering modules then receive their
616    /// resolved storage descriptor in HELLO_ACK.
617    pub fn with_storage_config(
618        mut self,
619        storage_config: Option<crate::daemon_config::StorageConfig>,
620    ) -> Self {
621        self.storage_config = storage_config;
622        self
623    }
624
625    /// Set the machine id served to every registering module (HELLO_ACK) and on
626    /// `server.describe`.
627    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
628        self.machine_id = machine_id;
629        self
630    }
631
632    /// Configure the exact reserved module and target ids permitted to relay
633    /// opaque admission facts. Config-file loading validates this authority;
634    /// this builder keeps the same policy available to embedded test daemons.
635    pub fn with_admission_facts_config(
636        mut self,
637        carrier_module_id: Option<String>,
638        targets: Option<Vec<String>>,
639    ) -> Self {
640        self.admission_facts_carrier_module_id = carrier_module_id;
641        self.admission_facts_targets = targets;
642        self
643    }
644
645    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
646    /// Replaces the scope table with an empty one under the new list, so call it
647    /// while building the handler, before any module can sync.
648    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
649        self.scopes = Arc::new(RwLock::new(
650            ScopeTable::new(owners.iter().cloned())
651                .with_federated_owner(self.federated_scope_owner.clone()),
652        ));
653        self.scope_authority_owners = owners;
654        self
655    }
656
657    /// Set the exclusive federated owner while building the handler, before syncs.
658    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
659        self.scopes = Arc::new(RwLock::new(
660            ScopeTable::new(self.scope_authority_owners.iter().cloned())
661                .with_federated_owner(owner.clone()),
662        ));
663        self.federated_scope_owner = owner;
664        self
665    }
666
667    /// Set the startup policy before installing the rescan context or serving requests.
668    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
669        self.privileged_operator_prompt = mode;
670        self
671    }
672
673    #[cfg(test)]
674    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
675        self.control_dispatch_delay = Some(delay);
676        self
677    }
678
679    pub fn with_process_liveness(
680        mut self,
681        process_liveness: Arc<dyn ModuleProcessLiveness>,
682    ) -> Self {
683        self.process_liveness = Some(process_liveness);
684        self
685    }
686
687    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
688        self.supervisor = supervisor;
689        if let Some(owner) = &self.config_runtime {
690            self.supervisor.install_binding_retirement(owner);
691        }
692        self.supervisor.set_activity(self.activity.clone());
693        self
694    }
695
696    /// Install the configured module set and its reserved capability bindings.
697    /// Bindings are configuration-scoped and may point at a provider that has not
698    /// been installed yet, so this does not require the bound module to exist.
699    pub fn with_capability_config(
700        self,
701        modules: impl IntoIterator<Item = (String, bool)>,
702        reserved_capabilities: BTreeMap<String, String>,
703    ) -> Self {
704        self.capability_evaluator
705            .configure(modules, reserved_capabilities);
706        self
707    }
708
709    /// Share the supervisor's daemon-shutdown flag with this handler, so
710    /// requirement changes after the daemon has begun its announced shutdown
711    /// are not reported as faults.
712    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
713        self.daemon_shutdown = flag;
714        self
715    }
716
717    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
718        self.connected_clients = connected_clients;
719        self
720    }
721
722    /// Report why this daemon serves no local endpoint, in `server.describe`, so
723    /// an operator can see a bind failure without reading the daemon log.
724    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
725        self.local_endpoint_unavailable = reason;
726        self
727    }
728
729    pub fn forwarding(&self) -> Arc<ForwardingTable> {
730        Arc::clone(&self.forwarding)
731    }
732
733    pub(crate) fn counters(&self) -> DaemonCounters {
734        self.counters.clone()
735    }
736
737    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
738    /// registration-release watch. The signal is what the supervisor waits on
739    /// before spawning a replacement, so it must only fire once forwarding
740    /// teardown is also done (see [`Self::cleanup_connection`] /
741    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
742    /// registry-only path below because publication already owns the spawn lock.
743    fn deregister_connection(
744        &self,
745        connection_id: ConnectionId,
746        reason: RegistrationEndReason,
747    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
748        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
749            spawn.end_primary_registration();
750        }
751        self.registry
752            .deregister_connection_with_reason(connection_id, reason)
753    }
754
755    fn request_refusal_close(
756        &self,
757        connection: ConnectionId,
758        sink: Option<&crate::FrameSink>,
759        reason: CloseReason,
760    ) {
761        if let Some(sink) = sink {
762            sink.terminate_ingress();
763        }
764        if self.claims.close_notifications_enabled() {
765            self.forwarding.request_connection_close(connection, reason);
766        }
767    }
768
769    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
770    ///
771    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
772    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
773    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
774    #[cfg(test)]
775    pub fn handle_control(
776        &self,
777        connection_id: ConnectionId,
778        frame: Frame,
779    ) -> Result<Vec<Frame>, RouterError> {
780        match frame.header.ty {
781            FrameType::Ping => Ok(vec![pong(&frame)?]),
782            FrameType::Hello => self.handle_hello(connection_id, None, frame),
783            FrameType::Goodbye => self.handle_goodbye(connection_id),
784            ty => Ok(vec![control_error_frame(
785                &frame,
786                "unsupported_control_frame",
787                format!("unsupported channel-0 frame {ty:?}"),
788            )?]),
789        }
790    }
791
792    pub async fn handle_control_frame(
793        &self,
794        ctx: &RouteCtx,
795        frame: Frame,
796    ) -> Result<Vec<Frame>, RouterError> {
797        self.handle_control_frame_timed(ctx, frame, None).await
798    }
799
800    #[cfg(any(test, feature = "test-support"))]
801    pub fn with_test_operator_app_policy(
802        mut self,
803        policy: crate::operator_apps::TestOperatorAppPolicy,
804    ) -> Self {
805        self.operator_app_policy = policy.into();
806        self
807    }
808
809    /// Inject the Windows signature check for tests. The injected check
810    /// answers the verified version string or the rejection reason; the
811    /// daemon enforces the floor itself on the returned version.
812    #[cfg(all(windows, any(test, feature = "test-support")))]
813    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
814        self.windows_verify = Some(verify);
815        self
816    }
817
818    /// Record which pids the daemon would flash for `already_running`.
819    #[cfg(all(windows, any(test, feature = "test-support")))]
820    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
821        self.windows_flash = Some(flash);
822        self
823    }
824
825    /// Inject a tracking failure for tests: makes `track_launched_process`
826    /// fail so a test can prove a launch that cannot be tracked is stopped,
827    /// never left running.
828    #[cfg(all(windows, any(test, feature = "test-support")))]
829    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
830        self.windows_track = Some(track);
831        self
832    }
833
834    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
835        self.local_connections
836            .lock()
837            .unwrap_or_else(|p| p.into_inner())
838            .insert(connection);
839    }
840
841    pub(crate) fn record_route_opener(
842        &self,
843        connection: ConnectionId,
844        opener: RouteOpenerConnection,
845    ) {
846        self.route_openers
847            .lock()
848            .unwrap_or_else(|p| p.into_inner())
849            .insert(connection, opener);
850    }
851
852    // Keep the connection-level delivery decision shared with route.bind. The
853    // target's capability opt-in is separate from recognition of the caller.
854    fn connection_operator_app(
855        &self,
856        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
857    ) -> Option<subc_protocol::peer::OperatorApp> {
858        stamp
859            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
860            .map(|stamp| stamp.app.clone())
861    }
862
863    pub(crate) fn record_observed_peer(
864        &self,
865        connection: ConnectionId,
866        peer: subc_os::local_peer::ObservedPeer,
867    ) {
868        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
869        let peer = match peer {
870            OsPeer::Unobserved => ObservedPeer::unobserved(),
871            OsPeer::Observed(peer) => {
872                let observed = match peer.user {
873                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
874                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
875                };
876                observed
877                    .with_exe(
878                        peer.exe
879                            .and_then(|path| path.into_os_string().into_string().ok()),
880                    )
881                    .with_signing_id(peer.signing_id)
882            }
883        };
884        self.observed_peers
885            .lock()
886            .unwrap_or_else(|p| p.into_inner())
887            .insert(connection, peer);
888    }
889
890    pub(crate) fn record_caller_endpoints(
891        &self,
892        connection: ConnectionId,
893        endpoints: Option<(SocketAddr, SocketAddr)>,
894    ) {
895        let mut callers = self
896            .caller_endpoints
897            .lock()
898            .unwrap_or_else(|p| p.into_inner());
899        callers.remove(&connection);
900        if let Some(endpoints) = endpoints {
901            callers.insert(connection, endpoints);
902        }
903    }
904
905    #[cfg(test)]
906    pub(crate) fn with_caller_lookup_for_test(
907        mut self,
908        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
909    ) -> Self {
910        self.caller_lookup = Some(Arc::new(lookup));
911        self
912    }
913
914    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
915        let endpoints = self
916            .caller_endpoints
917            .lock()
918            .unwrap_or_else(|p| p.into_inner())
919            .get(&connection)
920            .copied();
921        #[cfg(test)]
922        let lookup = self.caller_lookup.clone();
923        tokio::task::spawn_blocking(move || {
924            #[cfg(test)]
925            if let Some(lookup) = lookup {
926                return lookup(endpoints);
927            }
928            endpoints
929                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
930                .unwrap_or_default()
931        })
932        .await
933        .unwrap_or_default()
934    }
935
936    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
937        frame.header.channel == 0
938            && frame.header.ty == FrameType::Request
939            && self
940                .forwarding
941                .module_endpoint_for_connection(ctx.connection_id)
942                .is_ok_and(|endpoint| endpoint.is_none())
943            && parse_client_control_request(&frame.body)
944                .ok()
945                .is_some_and(|request| privileged_operation(&request).is_some())
946    }
947
948    pub(crate) async fn handle_control_frame_timed(
949        &self,
950        ctx: &RouteCtx,
951        frame: Frame,
952        dispatch_started_at: Option<StdInstant>,
953    ) -> Result<Vec<Frame>, RouterError> {
954        let first = ctx.egress.first_ingress_frame();
955        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
956            .await
957    }
958
959    pub(crate) async fn handle_control_frame_ingress(
960        &self,
961        ctx: &RouteCtx,
962        frame: Frame,
963        dispatch_started_at: Option<StdInstant>,
964        first: bool,
965    ) -> Result<Vec<Frame>, RouterError> {
966        if ctx.egress.ingress_terminal() {
967            return Ok(Vec::new());
968        }
969        #[cfg(test)]
970        self.claims.record_dispatch(frame.header.corr);
971        let claim_binding = self.claims.binding(ctx.connection_id);
972        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
973            && claim_binding
974                .as_ref()
975                .is_some_and(|binding| binding.prefix_module_id().is_some()))
976        .then(|| self.prefix_hello_attempt(ctx));
977        if claim_binding
978            .as_ref()
979            .is_some_and(|binding| binding.prefix_module_id().is_some())
980        {
981            let registered = self
982                .forwarding
983                .module_endpoint_for_connection(ctx.connection_id)
984                .map_err(RouterError::Forwarding)?
985                .is_some();
986            if !registered && frame.header.ty != FrameType::Hello {
987                return self
988                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
989                    .await;
990            }
991            if registered && frame.header.ty == FrameType::Goodbye {
992                ctx.egress.terminate_ingress();
993                let result = self.handle_goodbye(ctx.connection_id);
994                self.claims.connection_closed(ctx.connection_id);
995                self.request_refusal_close(
996                    ctx.connection_id,
997                    Some(&ctx.egress),
998                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
999                );
1000                return result;
1001            }
1002            if registered && frame.header.ty == FrameType::Request {
1003                let allowed =
1004                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
1005                        matches!(
1006                            probe.op.as_str(),
1007                            "catalog.update"
1008                                | "catalog.update_role_declarations"
1009                                | "scope.describe"
1010                                | "scope.watch"
1011                                | "supervisor.live_roots"
1012                                | subc_protocol::policy_root::GET_OP
1013                                | "activity.record"
1014                        )
1015                    });
1016                if !allowed {
1017                    return Ok(vec![control_error_frame(
1018                        &frame,
1019                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1020                        "prefix registrations have only brokered module operations",
1021                    )?]);
1022                }
1023            }
1024            if registered
1025                && frame.header.ty == FrameType::Push
1026                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
1027                    .is_ok_and(|probe| probe.op == "route.status")
1028            {
1029                return Ok(vec![control_error_frame(
1030                    &frame,
1031                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1032                    "prefix registrations may push only route.status for routes they serve",
1033                )?]);
1034            }
1035        }
1036        match frame.header.ty {
1037            FrameType::Ping => Ok(vec![pong(&frame)?]),
1038            FrameType::Hello => {
1039                if claim_binding
1040                    .as_ref()
1041                    .is_some_and(|binding| binding.prefix_module_id().is_none())
1042                {
1043                    return self
1044                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
1045                        .await;
1046                }
1047                // Resolve before the blocking HELLO can outlive channel cleanup.
1048                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
1049                if let Some(spawn) = &channel_spawn {
1050                    spawn.wait_launch().await;
1051                    // Refused launches close the channel. Leave their pending
1052                    // HELLO unanswered instead of racing a reply against shutdown.
1053                    if !spawn.launch_ready() {
1054                        ctx.egress.terminate_ingress();
1055                        return Ok(Vec::new());
1056                    }
1057                    #[cfg(test)]
1058                    self.pause_hello_ingress_for_test().await;
1059                } else if claim_binding.is_none() {
1060                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
1061                        if crate::supervise::resume_hello::has_resume_token(&hello) {
1062                            self.wait_for_resume_preparation(ctx.connection_id, &hello)
1063                                .await;
1064                        } else if let (Some(module), Some(nonce)) = (
1065                            hello
1066                                .get("manifest")
1067                                .and_then(|value| value.get("module_id"))
1068                                .and_then(|value| value.as_str()),
1069                            hello.get("launch_nonce").and_then(|value| value.as_str()),
1070                        ) {
1071                            if !self
1072                                .config_runtime
1073                                .as_ref()
1074                                .is_some_and(|owner| owner.module_is_gated(module))
1075                                && !self.supervisor.wait_program_binding(module, nonce).await
1076                            {
1077                                self.request_refusal_close(
1078                                    ctx.connection_id,
1079                                    Some(&ctx.egress),
1080                                    CloseReason::new(
1081                                        "program_refused",
1082                                        "the spawned program binding failed",
1083                                    ),
1084                                );
1085                                return Ok(vec![control_error_frame(
1086                                    &frame,
1087                                    if self
1088                                        .config_runtime
1089                                        .as_ref()
1090                                        .is_some_and(|owner| owner.is_recovering())
1091                                    {
1092                                        "config_gated"
1093                                    } else {
1094                                        "program_refused"
1095                                    },
1096                                    "the spawned program binding failed",
1097                                )?]);
1098                            }
1099                            if let Some(spawn) = self.supervisor.nonce_hello_spawn(module, nonce) {
1100                                // The child can dial before the supervisor has
1101                                // installed its durable roster entry.
1102                                spawn.wait_launch().await;
1103                            }
1104                        }
1105                    }
1106                }
1107                let handler = self.clone();
1108                let connection = ctx.connection_id;
1109                let egress = ctx.egress.clone();
1110                let correlation = frame.header.corr;
1111                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
1112                let span = tracing::Span::current();
1113                let hello_binding = claim_binding.clone();
1114                let replies = tokio::task::spawn_blocking(move || {
1115                    tracing::dispatcher::with_default(&dispatcher, || {
1116                        span.in_scope(|| {
1117                            handler.handle_hello_checked(
1118                                connection,
1119                                Some(egress),
1120                                frame,
1121                                true,
1122                                hello_binding,
1123                                channel_spawn,
1124                            )
1125                        })
1126                    })
1127                })
1128                .await
1129                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
1130                #[cfg(test)]
1131                if prefix_attempt.is_some() {
1132                    self.claims.pause_prefix_commit_for_test(false).await;
1133                }
1134                if let Some(attempt) = &mut prefix_attempt {
1135                    let accepted = !replies
1136                        .iter()
1137                        .any(|reply| reply.header.ty == FrameType::Error)
1138                        && self
1139                            .registry
1140                            .get_module_by_connection(ctx.connection_id)
1141                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
1142                            .is_some();
1143                    if accepted {
1144                        attempt.accepted = true;
1145                    } else {
1146                        ctx.egress.terminate_ingress();
1147                        for reply in replies {
1148                            ctx.egress.send_flushed(reply).await?;
1149                        }
1150                        return Ok(Vec::new());
1151                    }
1152                }
1153                Ok(replies)
1154            }
1155            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
1156            FrameType::Cancel => {
1157                // Channel-0 cancellation withdraws approvals and subscriptions
1158                // and fences pending agent declarations;
1159                // successful cancellation has no ordinary reply.
1160                // A config Apply may also own an OS prompt. Cancel that prompt
1161                // before config cancellation can report the request handled.
1162                if self
1163                    .agent_declarations
1164                    .cancel(ctx.connection_id, frame.header.corr)
1165                    || self
1166                        .forwarding
1167                        .operator_confirms()
1168                        .cancel(ctx.connection_id, frame.header.corr)
1169                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
1170                    || self
1171                        .supervisor
1172                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
1173                    || self.cancel_activity_subscription(ctx, &frame)?
1174                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
1175                    || self
1176                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
1177                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
1178                {
1179                    Ok(Vec::new())
1180                } else {
1181                    Ok(vec![control_error_frame(
1182                        &frame,
1183                        "unknown_subscription",
1184                        "no subscription has this correlation id",
1185                    )?])
1186                }
1187            }
1188            FrameType::Request => {
1189                // This additive operation is not part of the existing exhaustive
1190                // module-control enum. Probe the op before decoding that enum.
1191                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
1192                if let Some(probe) = &op {
1193                    self.record_control_usage(ctx.connection_id, &probe.op);
1194                }
1195                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
1196                if let Some(refusal) = self.recovery_request_refusal(
1197                    ctx,
1198                    &frame,
1199                    op.as_ref().map(|probe| probe.op.as_str()),
1200                )? {
1201                    if claim_present {
1202                        self.reclaim_presented_expiry(&frame);
1203                        return self
1204                            .refuse_claim_connection(ctx, &frame, "config_gated")
1205                            .await;
1206                    }
1207                    return Ok(vec![refusal]);
1208                }
1209                if claim_present {
1210                    return self.handle_claim_present(ctx, &frame, first).await;
1211                }
1212                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
1213                    return self.handle_claim_mint(ctx, &frame).await;
1214                }
1215                if let Some(refusal) = self.registration_operation_refusal(
1216                    ctx,
1217                    &frame,
1218                    op.as_ref().map(|probe| probe.op.as_str()),
1219                )? {
1220                    return Ok(vec![refusal]);
1221                }
1222                if let Some(probe) = op.as_ref().filter(|probe| policy_root::is_op(&probe.op)) {
1223                    return self.handle_policy_root(ctx, frame, &probe.op).await;
1224                }
1225                if op
1226                    .as_ref()
1227                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
1228                {
1229                    return self.handle_catalog_watch(ctx, frame);
1230                }
1231                if op
1232                    .as_ref()
1233                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
1234                {
1235                    return self.handle_scope_watch(ctx, frame);
1236                }
1237                if op
1238                    .as_ref()
1239                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
1240                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
1241                        .unwrap_or(false)
1242                {
1243                    return Ok(vec![control_error_frame(
1244                        &frame,
1245                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
1246                        "provider_declarations are fixed at HELLO; restart the module to change them",
1247                    )?]);
1248                }
1249                if let Some(probe) = op
1250                    .as_ref()
1251                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
1252                {
1253                    return self
1254                        .handle_module_config_request(ctx, frame, &probe.op)
1255                        .await;
1256                }
1257                if let Some(probe) = op
1258                    .as_ref()
1259                    .filter(|probe| config_gate::is_config_op(&probe.op))
1260                {
1261                    return self.handle_config_gate_request(ctx, frame, &probe.op).await;
1262                }
1263                if op
1264                    .as_ref()
1265                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
1266                {
1267                    return self.handle_activity_record(ctx, frame).await;
1268                }
1269                if op.as_ref().is_some_and(|probe| {
1270                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
1271                }) {
1272                    // A refusal and a CANCEL that won must not both end the stream.
1273                    let key = (ctx.connection_id, frame.header.corr);
1274                    let replies = self.handle_activity_read(ctx, frame).await?;
1275                    return Ok(self.activity_reservations.settle(key, replies));
1276                }
1277                if op
1278                    .as_ref()
1279                    .is_some_and(|probe| probe.op == "operator.confirm")
1280                {
1281                    return self.handle_operator_confirm(ctx, frame).await;
1282                }
1283                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
1284                    return self
1285                        .observe_control_wait(
1286                            ctx,
1287                            None,
1288                            ops::APP_OPEN,
1289                            self.handle_app_open(ctx, frame),
1290                        )
1291                        .await;
1292                }
1293                if op
1294                    .as_ref()
1295                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
1296                {
1297                    return self.handle_connection_describe(ctx, frame).await;
1298                }
1299                if op
1300                    .as_ref()
1301                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
1302                {
1303                    return self.handle_scope_served_by(ctx.connection_id, frame);
1304                }
1305                if self
1306                    .forwarding
1307                    .module_endpoint_for_connection(ctx.connection_id)
1308                    .map_err(RouterError::Forwarding)?
1309                    .is_some()
1310                {
1311                    if !is_known_module_request_op(&frame.body) {
1312                        return Ok(vec![control_error_frame(
1313                            &frame,
1314                            "unsupported_control_frame",
1315                            "module-originated channel-0 REQUEST is not supported",
1316                        )?]);
1317                    }
1318                    if op.as_ref().is_some_and(|probe| {
1319                        probe.op == subc_protocol::session::MODULE_DRAIN_READY_OP
1320                    }) {
1321                        return self.handle_module_drain_ready(ctx.connection_id, frame);
1322                    }
1323                    let request = match parse_module_control_request_from_module(&frame.body) {
1324                        Ok(request) => request,
1325                        Err((err, ControlRequestBodyError::UnknownOp)) => {
1326                            return Ok(vec![control_error_frame(
1327                                &frame,
1328                                "unsupported_control_frame",
1329                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
1330                            )?])
1331                        }
1332                        Err((err, ControlRequestBodyError::InvalidBody)) => {
1333                            return Ok(vec![control_error_frame(
1334                                &frame,
1335                                "invalid_control_body",
1336                                format!("malformed module control body: {err}"),
1337                            )?])
1338                        }
1339                    };
1340                    let op = module_control_request_op(&request);
1341                    let corr = frame.header.corr;
1342                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
1343                    if let ModuleControlRequestFromModule::AgentCommands {
1344                        started,
1345                        finished,
1346                        known,
1347                    } = request
1348                    {
1349                        return self
1350                            .agent_declarations
1351                            .enqueue(
1352                                self,
1353                                ctx,
1354                                frame,
1355                                crate::resource_totals::Declaration {
1356                                    started,
1357                                    finished,
1358                                    known,
1359                                },
1360                            )
1361                            .await;
1362                    }
1363                    let result =
1364                        self.handle_module_control_request(ctx.connection_id, frame, request);
1365                    log_slow_control_dispatch(
1366                        dispatch_started_at,
1367                        op,
1368                        ctx.connection_id,
1369                        corr,
1370                        None,
1371                    );
1372                    return result;
1373                }
1374
1375                if is_known_module_request_op(&frame.body) {
1376                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
1377                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
1378                    let code = if is_agents {
1379                        "not_supervised"
1380                    } else if op
1381                        .as_ref()
1382                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
1383                    {
1384                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
1385                    } else {
1386                        "not_registered"
1387                    };
1388                    return Ok(vec![control_error_frame(
1389                        &frame,
1390                        code,
1391                        "module-originated control requests require the module's own registered connection",
1392                    )?]);
1393                }
1394
1395                let request = match parse_client_control_request(&frame.body) {
1396                    Ok(request) => request,
1397                    Err((err, ControlRequestBodyError::UnknownOp)) => {
1398                        return Ok(vec![control_error_frame(
1399                            &frame,
1400                            "unknown_control_op",
1401                            format!("unknown client control op: {err}"),
1402                        )?])
1403                    }
1404                    Err((err, ControlRequestBodyError::InvalidBody)) => {
1405                        return Ok(vec![control_error_frame(
1406                            &frame,
1407                            "invalid_control_body",
1408                            format!("malformed client control body: {err}"),
1409                        )?])
1410                    }
1411                };
1412                let op = client_control_request_op(&request);
1413                let corr = frame.header.corr;
1414                log_control_dispatch_arrival(op, ctx.connection_id, corr);
1415                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
1416                #[cfg(test)]
1417                if let Some(delay) = self.control_dispatch_delay {
1418                    tokio::time::sleep(delay).await;
1419                }
1420                let result = self
1421                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
1422                    .await;
1423                if let Some(timings) = route_open_timings.as_mut() {
1424                    timings.finish();
1425                }
1426                log_slow_control_dispatch(
1427                    dispatch_started_at,
1428                    op,
1429                    ctx.connection_id,
1430                    corr,
1431                    route_open_timings.as_ref(),
1432                );
1433                result
1434            }
1435            FrameType::Push => {
1436                let Some(endpoint) = self
1437                    .forwarding
1438                    .module_endpoint_for_connection(ctx.connection_id)
1439                    .map_err(RouterError::Forwarding)?
1440                else {
1441                    return Ok(vec![control_error_frame(
1442                        &frame,
1443                        "unsupported_control_frame",
1444                        "client-originated channel-0 PUSH is not supported",
1445                    )?]);
1446                };
1447                self.handle_status_update(endpoint, frame)
1448            }
1449            FrameType::Response | FrameType::Error
1450                if self
1451                    .forwarding
1452                    .module_endpoint_for_connection(ctx.connection_id)
1453                    .map_err(RouterError::Forwarding)?
1454                    .is_some() =>
1455            {
1456                self.handle_module_relay_response(ctx.connection_id, frame)
1457            }
1458            ty => Ok(vec![control_error_frame(
1459                &frame,
1460                "unsupported_control_frame",
1461                format!("unsupported channel-0 frame {ty:?}"),
1462            )?]),
1463        }
1464    }
1465
1466    #[cfg(test)]
1467    fn pause_cleanup_for_test(&self, stage: u8) {
1468        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
1469        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
1470            let (_, (reached, release)) = slot.take().unwrap();
1471            drop(slot);
1472            let _ = reached.send(());
1473            let _ = release.recv_timeout(Duration::from_secs(5));
1474        }
1475    }
1476
1477    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
1478    /// right after the nonce is resolved.
1479    #[cfg(all(test, unix, feature = "test-support"))]
1480    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
1481        *self
1482            .after_nonce_attestation
1483            .lock()
1484            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
1485    }
1486
1487    #[cfg(test)]
1488    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
1489        let hook = self
1490            .after_nonce_attestation
1491            .lock()
1492            .unwrap_or_else(|p| p.into_inner())
1493            .take();
1494        if let Some(hook) = hook {
1495            hook();
1496        }
1497    }
1498
1499    pub fn cleanup_connection(
1500        &self,
1501        connection_id: ConnectionId,
1502    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1503        // The server loop joins its offloaded request tasks (route opens,
1504        // privileged requests and activity reads) before this cleanup runs, and
1505        // inline dispatch has ended. Two kinds of work are not joined. Agent
1506        // command declarations run on their queue's detached worker, so the
1507        // queue is closed first: every declaration still queued or validating
1508        // has its commit fence cancelled before anything below can change how
1509        // the connection resolves. A HELLO whose reader was dropped keeps
1510        // running on its blocking thread. It carries the channel spawn its
1511        // reader resolved at ingress instead of re-reading the index forgotten
1512        // below, so it is still judged as that channel's HELLO: the retired
1513        // spawn refuses it before it records anything, and a channel HELLO
1514        // never records a launch nonce, so it cannot leave this connection any
1515        // nonce authority.
1516        self.agent_declarations.close(connection_id);
1517        self.close_catalog_subscriptions(connection_id);
1518        self.close_config_settings_subscriptions(connection_id);
1519        self.close_scope_subscriptions(connection_id);
1520        #[cfg(test)]
1521        self.pause_cleanup_for_test(0);
1522        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1523            spawn.retire_registration_channel();
1524        }
1525        self.supervisor
1526            .forget_registration_connection(connection_id);
1527        #[cfg(test)]
1528        self.pause_cleanup_for_test(1);
1529        self.local_connections
1530            .lock()
1531            .unwrap_or_else(|p| p.into_inner())
1532            .remove(&connection_id);
1533        self.caller_endpoints
1534            .lock()
1535            .unwrap_or_else(|p| p.into_inner())
1536            .remove(&connection_id);
1537        self.route_openers
1538            .lock()
1539            .unwrap_or_else(|p| p.into_inner())
1540            .remove(&connection_id);
1541        self.build_class_warned
1542            .lock()
1543            .unwrap_or_else(|p| p.into_inner())
1544            .remove(&connection_id);
1545        // Retire the capture before its published facts so an in-flight
1546        // verification cannot recreate them after cleanup.
1547        self.captured_peers
1548            .lock()
1549            .unwrap_or_else(|p| p.into_inner())
1550            .remove(&connection_id);
1551        self.observed_peers
1552            .lock()
1553            .unwrap_or_else(|p| p.into_inner())
1554            .remove(&connection_id);
1555        self.config_desktop_stamps
1556            .lock()
1557            .unwrap_or_else(|p| p.into_inner())
1558            .remove(&connection_id);
1559        self.operator_apps
1560            .lock()
1561            .unwrap_or_else(|p| p.into_inner())
1562            .remove(&connection_id);
1563        self.forwarding
1564            .operator_confirms()
1565            .connection_closed(connection_id);
1566        let cleanup = self.cleanup_connection_with_end_reason(
1567            connection_id,
1568            RegistrationEndReason::ConnectionClosed,
1569        );
1570        // A draining writer can still be reached by a route until forwarding
1571        // cleanup finishes. Keep its claim sink visible to launch retirement.
1572        self.claims.connection_closed(connection_id);
1573        cleanup
1574    }
1575
1576    fn cleanup_connection_with_end_reason(
1577        &self,
1578        connection_id: ConnectionId,
1579        requested_reason: RegistrationEndReason,
1580    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1581        #[cfg(test)]
1582        if let Some(pause) = self
1583            .activity_request_pause
1584            .lock()
1585            .unwrap()
1586            .as_ref()
1587            .filter(|pause| pause.connection == connection_id)
1588        {
1589            pause
1590                .cleanup_started
1591                .store(true, std::sync::atomic::Ordering::Release);
1592        }
1593        if let Some(runtime) = &self.config_runtime {
1594            runtime.disconnected(connection_id);
1595        }
1596        self.agent_declarations.close(connection_id);
1597        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
1598            self.registry
1599                .get_module_by_connection(connection_id)?
1600                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
1601                .and_then(|module| module.registration_end_reason().ok().flatten())
1602                .unwrap_or(requested_reason)
1603        } else {
1604            requested_reason
1605        };
1606        let crash_closed = self
1607            .registry
1608            .get_module_by_connection(connection_id)?
1609            .and_then(|registration| {
1610                self.forwarding
1611                    .module_endpoint_for_connection(connection_id)
1612                    .ok()
1613                    .flatten()
1614                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
1615                    .map(|routes| (registration.manifest.module_id, routes))
1616            });
1617        let crash_closed = crash_closed.map(|(module_id, routes)| {
1618            let terminal = match self.supervisor.get(&module_id) {
1619                None => false,
1620                Some(module) => match module.will_recover_after_connection_loss() {
1621                    Ok(will_recover) => !will_recover,
1622                    Err(err) => {
1623                        warn!(
1624                            %module_id,
1625                            error = %err,
1626                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
1627                        );
1628                        false
1629                    }
1630                },
1631            };
1632            // The forwarding table gates all providers at the start of daemon
1633            // shutdown, before their connections are closed. An ordinary
1634            // module disconnect still reports crash if that gate is not set.
1635            let (reason, drained) = match self
1636                .forwarding
1637                .daemon_drain_result_for_connection(connection_id)
1638            {
1639                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
1640                Ok(None) => (RouteCloseReason::Crash, false),
1641                Err(err) => {
1642                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
1643                    (RouteCloseReason::Crash, false)
1644                }
1645            };
1646            (module_id, routes, reason, drained, terminal)
1647        });
1648        let registrations = self.deregister_connection(connection_id, end_reason);
1649        // Read before teardown: the spawn whose registration this connection
1650        // was. Its registration ending is an authority change for it.
1651        let ended_authority = self
1652            .forwarding
1653            .target_authority_for_connection(connection_id)
1654            .ok()
1655            .flatten();
1656        let cleanup = if crash_closed.is_some() {
1657            self.forwarding.cleanup_connection_counted(connection_id)
1658        } else {
1659            // A module connection's teardown needs the count of abandoned
1660            // route.bind relays for its route.closed notice below. Any other
1661            // connection, such as a client's, sends no such notice and needs
1662            // only its routes released, so it uses the route-only wrapper and
1663            // reports zero.
1664            self.forwarding
1665                .cleanup_connection(connection_id)
1666                .map(|released| crate::forwarding::ConnectionCleanup {
1667                    released,
1668                    abandoned_relays: 0,
1669                })
1670        };
1671        // The route.closed push waits for forwarding teardown because only
1672        // teardown knows how many pending route.bind relays it aborted. It still
1673        // goes out before the GOODBYEs for the released routes, and its targets
1674        // were captured above, before teardown removed those routes.
1675        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
1676            let abandoned = cleanup
1677                .as_ref()
1678                .map_or(0, |cleanup| cleanup.abandoned_relays);
1679            send_route_control_pushes(
1680                &self.forwarding,
1681                routes,
1682                ClientControlPush::RouteClosed {
1683                    module_id,
1684                    channels: Vec::new(),
1685                    reason,
1686                    drained,
1687                    abandoned,
1688                    excluded_subscriptions: 0,
1689                    terminal: Some(terminal),
1690                },
1691            );
1692        }
1693        if let Ok(cleanup) = cleanup {
1694            self.emit_route_goodbyes(cleanup.released);
1695        }
1696        if let Some(record) = ended_authority {
1697            self.change_spawn_authority(&record);
1698        }
1699        // Signal the registration-release watch only now that BOTH registry and
1700        // forwarding teardown are done, so a supervisor waiting to spawn a
1701        // replacement never observes release while old routes still exist.
1702        if matches!(&registrations, Ok(r) if !r.is_empty()) {
1703            crate::supervise::notify_registration_release();
1704            self.capability_evaluator.wake_deadline_loop();
1705            self.refresh_capability_requirements();
1706        }
1707        self.supervisor.remove_spawn_subscribers(connection_id);
1708        self.activity_streams
1709            .lock()
1710            .unwrap_or_else(|p| p.into_inner())
1711            .retain(|(id, _), task| {
1712                if *id == connection_id {
1713                    task.abort();
1714                    false
1715                } else {
1716                    true
1717                }
1718            });
1719        // Sync authority dies with its connection, so the owner's next
1720        // connection can take it; the owner's scopes stay as they are.
1721        self.hello_launch_nonces
1722            .lock()
1723            .unwrap_or_else(|poisoned| poisoned.into_inner())
1724            .forget(connection_id);
1725        self.scopes
1726            .write()
1727            .unwrap_or_else(|poisoned| poisoned.into_inner())
1728            .release_connection(connection_id);
1729        registrations
1730    }
1731
1732    pub(crate) fn handle_route_goodbye(
1733        &self,
1734        connection_id: ConnectionId,
1735        route_channel: u16,
1736        route_epoch: u32,
1737    ) -> Result<bool, RouterError> {
1738        debug!(
1739            connection_id = connection_id.get(),
1740            route_channel, route_epoch, "handling route GOODBYE"
1741        );
1742        let RouteRelease::Removed(released_route) = self
1743            .forwarding
1744            .release_client_route(connection_id, route_channel, route_epoch)
1745            .map_err(RouterError::Forwarding)?
1746        else {
1747            return Ok(false);
1748        };
1749        self.emit_route_goodbyes(vec![released_route]);
1750        Ok(true)
1751    }
1752
1753    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
1754        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
1755    }
1756
1757    async fn handle_client_control_request(
1758        &self,
1759        ctx: &RouteCtx,
1760        frame: Frame,
1761        request: ClientControlRequest,
1762        route_open_timings: &mut Option<RouteOpenTimings>,
1763    ) -> Result<Vec<Frame>, RouterError> {
1764        if let Some(owner) = &self.config_runtime {
1765            let module = match &request {
1766                ClientControlRequest::SupervisorRestart { module_id, .. }
1767                | ClientControlRequest::SupervisorReload { module_id }
1768                | ClientControlRequest::SupervisorSwap { module_id, .. }
1769                | ClientControlRequest::SupervisorSetEnabled {
1770                    module_id,
1771                    enabled: true,
1772                } => Some(module_id.as_str()),
1773                _ => None,
1774            };
1775            let rescan = matches!(
1776                &request,
1777                ClientControlRequest::SupervisorRescan { preview: false }
1778                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
1779            );
1780            let held = if module.is_some() || rescan {
1781                let module = module.map(str::to_owned);
1782                owner
1783                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
1784                    .await
1785            } else {
1786                Ok(())
1787            };
1788            if let Err(error) = held {
1789                if error.code != "config_delivery_deferred" {
1790                    let code = if error.code == "store_tampered" {
1791                        "store_tampered"
1792                    } else {
1793                        "config_gated"
1794                    };
1795                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
1796                }
1797            }
1798        }
1799        if let Some(operation) = privileged_operation(&request) {
1800            #[cfg(any(target_os = "macos", target_os = "linux"))]
1801            if operation == PrivilegedOperation::UpgradeInPlace {
1802                if let Some(upgrade) = &self.upgrade {
1803                    if !upgrade.wait_for_identity().await {
1804                        return Ok(vec![control_error_frame(
1805                            &frame,
1806                            subc_control::upgrade_in_place::UPGRADE_IN_PLACE_UNSUPPORTED,
1807                            "running executable identity is unavailable",
1808                        )?]);
1809                    }
1810                }
1811            }
1812            let caller = self.resolve_caller(ctx.connection_id).await;
1813            let op = client_control_request_op(&request);
1814            let text = prompt_text(operation, &caller);
1815            match if operation == PrivilegedOperation::UpgradeInPlace {
1816                PrivilegedOperatorPrompt::Enforce
1817            } else {
1818                self.privileged_operator_prompt
1819            } {
1820                PrivilegedOperatorPrompt::Log => {
1821                    info!(target: "subc_daemon::privileged_prompt", operation = op,
1822                        target = ?operation, caller = %caller.description(), summary = %text,
1823                        "privileged request would prompt the operator");
1824                }
1825                PrivilegedOperatorPrompt::Enforce => {
1826                    let key =
1827                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1828                    let shortcut = if operation == PrivilegedOperation::UpgradeInPlace {
1829                        None
1830                    } else {
1831                        self.operator_shortcut_stamp(ctx.connection_id)
1832                            .await
1833                            .map(|stamp| {
1834                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
1835                            })
1836                    };
1837                    let outcome = self
1838                        .forwarding
1839                        .operator_confirms()
1840                        .approve_privileged_with_shortcut(
1841                            ctx,
1842                            &frame,
1843                            op,
1844                            text,
1845                            caller.description(),
1846                            key,
1847                            shortcut,
1848                        )
1849                        .await;
1850                    if outcome.code != "confirmed" {
1851                        return Ok(vec![outcome.frame(&frame)]);
1852                    }
1853                }
1854            }
1855        }
1856        match request {
1857            ClientControlRequest::DaemonUpgradeInPlace { executable_sha256 } => {
1858                self.upgrade_in_place(ctx, frame, executable_sha256)
1859            }
1860            ClientControlRequest::DaemonShutdownIntent { intent } => {
1861                self.daemon_restart_intent(frame, intent).await
1862            }
1863            // Clients probe capabilities here before opening routes. A cold
1864            // boot hash is optional metadata, not a prerequisite to serving.
1865            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
1866            ClientControlRequest::PolicyRoot(_)
1867            | ClientControlRequest::PolicyRootSet(_)
1868            | ClientControlRequest::PolicyRootRecover(_) => {
1869                unreachable!("policy root ops dispatch before the client-only path")
1870            }
1871            ClientControlRequest::CatalogList { module_id } => {
1872                self.handle_catalog_list(frame, module_id)
1873            }
1874            ClientControlRequest::RouteOpen {
1875                target,
1876                identity,
1877                consumer_identity,
1878                consumer_capabilities,
1879                role_versions,
1880                busy_refusals,
1881                admission_facts,
1882                scope,
1883                ..
1884            } => {
1885                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
1886                    &frame.body,
1887                ) {
1888                    Ok(extensions) => extensions,
1889                    Err(err) => {
1890                        return Ok(vec![control_error_frame(
1891                            &frame,
1892                            "invalid_control_body",
1893                            format!("malformed route.open extensions: {err}"),
1894                        )?]);
1895                    }
1896                };
1897                self.handle_route_open(
1898                    ctx,
1899                    frame,
1900                    RouteOpenRequest {
1901                        target,
1902                        identity,
1903                        consumer_identity,
1904                        consumer_capabilities,
1905                        role_versions,
1906                        busy_refusals,
1907                        admission_facts,
1908                        scope,
1909                        accepts_close_reasons: extensions.accepts_close_reasons,
1910                    },
1911                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
1912                )
1913                .await
1914            }
1915            ClientControlRequest::RoutePoll {
1916                route_channel,
1917                route_epoch,
1918                kind,
1919            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
1920            ClientControlRequest::SupervisorList {} => {
1921                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
1922                    self.agent_declarations.refuse(
1923                        self,
1924                        ctx,
1925                        control_error_frame(
1926                            &frame,
1927                            "busy",
1928                            "supervisor list work is at capacity; retry",
1929                        )?,
1930                    );
1931                    return Ok(Vec::new());
1932                };
1933                // Filesystem-backed diagnostics must not hold up this connection's reader.
1934                let handler = self.clone();
1935                let sink = ctx.egress.clone();
1936                tokio::spawn(
1937                    async move {
1938                        let _permit = permit;
1939                        let result = handler.handle_supervisor_list(frame.clone()).await;
1940                        let replies = match result {
1941                            Ok(replies) => replies,
1942                            Err(error) => {
1943                                control_error_frame(&frame, "backend_error", error.to_string())
1944                                    .into_iter()
1945                                    .collect()
1946                            }
1947                        };
1948                        for reply in replies {
1949                            if !matches!(
1950                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
1951                                    .await,
1952                                Ok(Ok(()))
1953                            ) {
1954                                break;
1955                            }
1956                        }
1957                    }
1958                    .with_current_subscriber(),
1959                );
1960                Ok(Vec::new())
1961            }
1962            ClientControlRequest::SupervisorSpawnSnapshot {} => {
1963                self.handle_supervisor_spawn_snapshot(frame)
1964            }
1965            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
1966                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
1967            }
1968            ClientControlRequest::SupervisorRestart {
1969                module_id,
1970                drain_timeout_ms,
1971            } => {
1972                self.log_supervisor_request_received(
1973                    ctx,
1974                    frame.header.corr,
1975                    ops::SUPERVISOR_RESTART,
1976                    Some(&module_id),
1977                    None,
1978                )?;
1979                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1980                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
1981                    .await
1982            }
1983            ClientControlRequest::SupervisorSwap {
1984                module_id,
1985                ready_timeout_ms,
1986            } => {
1987                self.log_supervisor_request_received(
1988                    ctx,
1989                    frame.header.corr,
1990                    ops::SUPERVISOR_SWAP,
1991                    Some(&module_id),
1992                    None,
1993                )?;
1994                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1995                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
1996                    .await
1997            }
1998            ClientControlRequest::SupervisorReload { module_id } => {
1999                self.log_supervisor_request_received(
2000                    ctx,
2001                    frame.header.corr,
2002                    ops::SUPERVISOR_RELOAD,
2003                    Some(&module_id),
2004                    None,
2005                )?;
2006                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2007                self.handle_supervisor_reload(frame, module_id, requester)
2008                    .await
2009            }
2010            ClientControlRequest::SupervisorRescan { preview } => {
2011                if !preview {
2012                    self.log_supervisor_request_received(
2013                        ctx,
2014                        frame.header.corr,
2015                        ops::SUPERVISOR_RESCAN,
2016                        None,
2017                        None,
2018                    )?;
2019                }
2020                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2021                let operation = self.handle_supervisor_rescan(
2022                    frame,
2023                    if preview {
2024                        RescanMode::Preview
2025                    } else {
2026                        RescanMode::Execute
2027                    },
2028                    requester,
2029                );
2030                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
2031                    .await
2032            }
2033            ClientControlRequest::SupervisorRescanChecked {
2034                preview,
2035                candidate,
2036                expect,
2037            } => {
2038                self.observe_control_wait(
2039                    ctx,
2040                    None,
2041                    ops::SUPERVISOR_RESCAN,
2042                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
2043                )
2044                .await
2045            }
2046            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2047                self.log_supervisor_request_received(
2048                    ctx,
2049                    frame.header.corr,
2050                    ops::SUPERVISOR_RELEASE_RESERVED,
2051                    Some(&module_id),
2052                    None,
2053                )?;
2054                self.handle_supervisor_release_reserved(frame, module_id)
2055                    .await
2056            }
2057            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2058                self.log_supervisor_request_received(
2059                    ctx,
2060                    frame.header.corr,
2061                    ops::SUPERVISOR_SET_ENABLED,
2062                    Some(&module_id),
2063                    Some(enabled),
2064                )?;
2065                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2066                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
2067                    .await
2068            }
2069            ClientControlRequest::SupervisorHealthProbe { module_id } => {
2070                self.handle_supervisor_health_probe(ctx, frame, module_id)
2071                    .await
2072            }
2073            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
2074            ClientControlRequest::SupervisorRoutes { module_id } => {
2075                self.handle_supervisor_routes(frame, module_id)
2076            }
2077            ClientControlRequest::SupervisorProvenance { module_id } => {
2078                self.handle_supervisor_provenance(ctx, frame, module_id)
2079                    .await
2080            }
2081            ClientControlRequest::SupervisorStderrTail {
2082                module_id,
2083                max_lines,
2084                max_bytes,
2085            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
2086            ClientControlRequest::SupervisorTerminals { module_id } => {
2087                self.handle_supervisor_terminals(ctx, frame, module_id)
2088                    .await
2089            }
2090        }
2091    }
2092
2093    /// Explicit test-only phone policy; daemon configuration cannot select it.
2094    #[cfg(any(test, feature = "test-support"))]
2095    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
2096        self.operator_app_policy.phone_enabled = enabled;
2097        self
2098    }
2099
2100    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
2101        debug!(connection_id = connection_id.get(), "handling GOODBYE");
2102        // GOODBYE ends the connection's logical session even when its socket
2103        // stays open. Use disconnect teardown so verdicts, client notices and
2104        // scope authority are released at the same lifecycle boundary.
2105        self.cleanup_connection_with_end_reason(
2106            connection_id,
2107            RegistrationEndReason::ExplicitGoodbye,
2108        )
2109        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
2110        Ok(Vec::new())
2111    }
2112}
2113
2114impl Default for ControlHandler {
2115    fn default() -> Self {
2116        Self::new(Arc::new(Registry::default()))
2117    }
2118}
2119
2120impl crate::supervise::SwapPromotionObserver for ControlHandler {
2121    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2122        self.apply_registration_capabilities(registration);
2123    }
2124}
2125
2126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2127enum ControlRequestBodyError {
2128    UnknownOp,
2129    InvalidBody,
2130}
2131
2132#[derive(Debug, Deserialize)]
2133struct ControlOpProbe {
2134    op: String,
2135}
2136
2137fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
2138    debug!(
2139        op = %op,
2140        connection_id = connection_id.get(),
2141        corr,
2142        "control dispatch"
2143    );
2144}
2145
2146fn log_slow_control_dispatch(
2147    dispatch_started_at: Option<StdInstant>,
2148    op: &'static str,
2149    connection_id: ConnectionId,
2150    corr: u64,
2151    route_open_timings: Option<&RouteOpenTimings>,
2152) {
2153    let Some(dispatch_started_at) = dispatch_started_at else {
2154        return;
2155    };
2156    // Use the same monotonic clock as the phase timers and relay deadline.
2157    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
2158    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
2159        if let Some(timings) = route_open_timings {
2160            warn!(
2161                op = %op,
2162                connection_id = connection_id.get(),
2163                corr,
2164                elapsed_ms = elapsed.as_millis() as u64,
2165                module_id = ?timings.module_id,
2166                principal = %timings.principal,
2167                admission_ms = timings.admission.as_millis() as u64,
2168                project_root_ms = timings.project_root.as_millis() as u64,
2169                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
2170                bind_send_ms = timings.bind_send.as_millis() as u64,
2171                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
2172                "slow control dispatch"
2173            );
2174            return;
2175        }
2176        warn!(
2177            op = %op,
2178            connection_id = connection_id.get(),
2179            corr,
2180            elapsed_ms = elapsed.as_millis() as u64,
2181            "slow control dispatch"
2182        );
2183    }
2184}
2185
2186/// A test stand-in for the OS caller lookup, given the recorded endpoints.
2187#[cfg(test)]
2188type TestCallerLookup =
2189    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
2190
2191/// Every new client operation needs an explicit privilege decision here.
2192fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
2193    request.privileged_operation()
2194}
2195
2196trait PrivilegedRequest {
2197    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
2198}
2199
2200impl PrivilegedRequest for ClientControlRequest {
2201    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
2202        let request = self;
2203        match request {
2204        ClientControlRequest::SupervisorRestart { module_id, .. } => {
2205            Some(PrivilegedOperation::Restart { module_id })
2206        }
2207        ClientControlRequest::DaemonUpgradeInPlace { .. } => Some(PrivilegedOperation::UpgradeInPlace),
2208        ClientControlRequest::SupervisorSwap { module_id, .. } => {
2209            Some(PrivilegedOperation::Swap { module_id })
2210        }
2211        ClientControlRequest::SupervisorReload { module_id } => {
2212            Some(PrivilegedOperation::Reload { module_id })
2213        }
2214        ClientControlRequest::SupervisorRescan { preview } => {
2215            if *preview {
2216                None
2217            } else {
2218                Some(PrivilegedOperation::Rescan)
2219            }
2220        }
2221        // Only the well-formed apply can change state, so only it needs approval.
2222        ClientControlRequest::SupervisorRescanChecked {
2223            preview,
2224            candidate,
2225            expect,
2226        } => (!*preview && candidate.is_none() && expect.is_some())
2227            .then_some(PrivilegedOperation::Rescan),
2228        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2229            Some(PrivilegedOperation::SetEnabled {
2230                module_id,
2231                enabled: *enabled,
2232            })
2233        }
2234        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2235            Some(PrivilegedOperation::ReleaseReserved { module_id })
2236        }
2237        ClientControlRequest::ServerDescribe {}
2238        | ClientControlRequest::PolicyRoot(_)
2239        | ClientControlRequest::PolicyRootSet(_)
2240        | ClientControlRequest::PolicyRootRecover(_)
2241        // A restart announcement cannot stop anything and requires no prompt.
2242        | ClientControlRequest::DaemonShutdownIntent { .. }
2243        | ClientControlRequest::CatalogList { .. }
2244        | ClientControlRequest::RouteOpen { .. }
2245        | ClientControlRequest::RoutePoll { .. }
2246        | ClientControlRequest::SupervisorList {}
2247        | ClientControlRequest::SupervisorHealth {}
2248        | ClientControlRequest::SupervisorHealthProbe { .. }
2249        | ClientControlRequest::SupervisorRoutes { .. }
2250        | ClientControlRequest::SupervisorProvenance { .. }
2251        | ClientControlRequest::SupervisorStderrTail { .. }
2252        | ClientControlRequest::SupervisorTerminals { .. }
2253        | ClientControlRequest::SupervisorSpawnSnapshot {}
2254        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
2255    }
2256    }
2257}
2258
2259fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
2260    match request {
2261        ClientControlRequest::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
2262        ClientControlRequest::PolicyRootSet(_) => subc_control::policy_root::SET_OP,
2263        ClientControlRequest::PolicyRootRecover(_) => subc_control::policy_root::RECOVER_OP,
2264        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
2265        ClientControlRequest::DaemonUpgradeInPlace { .. } => ops::DAEMON_UPGRADE_IN_PLACE,
2266        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
2267        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
2268        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
2269        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
2270        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
2271        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
2272        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
2273        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
2274        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
2275        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
2276        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
2277        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
2278        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
2279        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
2280        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
2281        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
2282        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
2283        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
2284        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
2285        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
2286    }
2287}
2288
2289fn parse_client_control_request(
2290    body: &[u8],
2291) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
2292    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
2293        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
2294            Ok(probe)
2295                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
2296                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
2297            {
2298                ControlRequestBodyError::InvalidBody
2299            }
2300            Ok(_) => ControlRequestBodyError::UnknownOp,
2301            Err(_) => ControlRequestBodyError::InvalidBody,
2302        };
2303        (err, classification)
2304    })
2305}
2306
2307fn pong(frame: &Frame) -> Result<Frame, RouterError> {
2308    Frame::build_with_version(
2309        response_version(frame),
2310        FrameType::Pong,
2311        frame.header.flags,
2312        0,
2313        0,
2314        frame.header.corr,
2315        Vec::new(),
2316    )
2317    .map_err(RouterError::FrameBuild)
2318}
2319
2320pub(crate) fn control_error_frame(
2321    frame: &Frame,
2322    code: &'static str,
2323    message: impl Into<String>,
2324) -> Result<Frame, RouterError> {
2325    control_error_body_frame(
2326        frame,
2327        ErrorBody {
2328            code: code.to_string(),
2329            message: message.into(),
2330            detail: None,
2331        },
2332    )
2333}
2334
2335/// A channel-0 ERROR for a refusal the daemon decided itself: every
2336/// route.open refusal, the drain `module_reloading` and scope-change/end
2337/// bodies, spawn-subscription and supervisor refusals. Carries the
2338/// daemon-origin bit, which is what lets a client treat `module_reloading`
2339/// as proof that its request never reached a module. Response, push,
2340/// goodbye and relay-request frames keep the plain control flags in their
2341/// own builders.
2342pub(crate) fn control_error_body_frame(
2343    frame: &Frame,
2344    error: ErrorBody,
2345) -> Result<Frame, RouterError> {
2346    control_error_frame_with_flags(frame, error, daemon_error_flags())
2347}
2348
2349/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
2350/// refused route.bind answered as a route.open refusal, or a refused
2351/// module-control RPC. Plain control flags — the code and message are
2352/// module-chosen, so the frame must not claim daemon authorship, even when
2353/// the module picks a daemon code like `module_reloading`.
2354fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
2355    control_error_frame_with_flags(frame, error, control_flags())
2356}
2357
2358fn control_error_frame_with_flags(
2359    frame: &Frame,
2360    error: ErrorBody,
2361    flags: Flags,
2362) -> Result<Frame, RouterError> {
2363    let body = serde_json::to_vec(&error).map_err(|err| {
2364        RouterError::backend(
2365            0,
2366            frame.header.corr,
2367            format!("failed to encode control ERROR: {err}"),
2368        )
2369    })?;
2370
2371    Frame::build_with_version(
2372        response_version(frame),
2373        FrameType::Error,
2374        flags,
2375        0,
2376        0,
2377        frame.header.corr,
2378        body,
2379    )
2380    .map_err(RouterError::FrameBuild)
2381}
2382
2383pub(crate) fn control_response_body_frame<T: Serialize>(
2384    frame: &Frame,
2385    reply: &T,
2386    label: &'static str,
2387) -> Result<Frame, RouterError> {
2388    let body = serde_json::to_vec(reply).map_err(|err| {
2389        RouterError::backend(
2390            0,
2391            frame.header.corr,
2392            format!("failed to encode {label}: {err}"),
2393        )
2394    })?;
2395
2396    Frame::build_with_version(
2397        response_version(frame),
2398        FrameType::Response,
2399        control_flags(),
2400        0,
2401        0,
2402        frame.header.corr,
2403        body,
2404    )
2405    .map_err(RouterError::FrameBuild)
2406}
2407
2408fn forwarding_error_code(err: &ForwardingError) -> &'static str {
2409    match err {
2410        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
2411        ForwardingError::NoModuleConnection => "target_unavailable",
2412        ForwardingError::ModuleReloading { .. } => "module_reloading",
2413        ForwardingError::ClientRouteChannelExhausted { .. }
2414        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
2415        ForwardingError::StaleModuleEndpoint
2416        | ForwardingError::UnknownReservation { .. }
2417        | ForwardingError::ConnectionClosing { .. }
2418        | ForwardingError::ClientEgressClosed { .. }
2419        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
2420        // Only a swap candidate's registration can produce this, and it means
2421        // exactly what a second active HELLO for a live id means.
2422        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
2423        ForwardingError::HelloRegistrationRefused(code) => code,
2424        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
2425        ForwardingError::RelayDeadlineElapsed => "module_timeout",
2426        ForwardingError::RelayCorrelationExhausted
2427        | ForwardingError::RouteOpenBuild(_)
2428        | ForwardingError::Poisoned => "forwarding_error",
2429    }
2430}
2431
2432fn response_version(frame: &Frame) -> u8 {
2433    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
2434        frame.header.ver
2435    } else {
2436        PROTOCOL_VERSION
2437    }
2438}
2439
2440pub(crate) fn control_flags() -> Flags {
2441    Flags::new(false, Priority::Passive, false)
2442}
2443
2444/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
2445/// channel. The target is the module (a client never saw the route), so this
2446/// takes the module path: delivered late rather than dropped when the module's
2447/// queue is momentarily full, and never closing its connection.
2448fn send_goodbye_target_best_effort(
2449    counters: &DaemonCounters,
2450    target: &GoodbyeTarget,
2451    context: &'static str,
2452) {
2453    let Ok(frame) = Frame::build_with_version(
2454        target.negotiated_ver,
2455        FrameType::Goodbye,
2456        control_flags(),
2457        target.channel,
2458        target.epoch,
2459        0,
2460        Vec::new(),
2461    ) else {
2462        return;
2463    };
2464    crate::forwarding::send_module_route_goodbye(
2465        counters,
2466        &target.sink,
2467        frame,
2468        target.module_id.as_deref(),
2469        context,
2470    );
2471}
2472
2473fn route_close_reason_for_opener(
2474    reason: RouteCloseReason,
2475    accepts_close_reasons: Option<&[String]>,
2476) -> RouteCloseReason {
2477    if reason == RouteCloseReason::AuthorityChanged
2478        && !accepts_close_reasons
2479            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
2480    {
2481        // Older readers forbid reopening for unknown reasons. Reload already
2482        // permits reopening and, like an authority change, requires a new bind.
2483        RouteCloseReason::Reload
2484    } else {
2485        reason
2486    }
2487}
2488
2489pub(crate) fn send_route_control_pushes(
2490    forwarding: &ForwardingTable,
2491    routes: Vec<EndpointRoute>,
2492    push: ClientControlPush,
2493) {
2494    let reason = match &push {
2495        ClientControlPush::RouteClosing { reason, .. }
2496        | ClientControlPush::RouteClosed { reason, .. } => *reason,
2497    };
2498    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
2499    for route in routes {
2500        let recipient_reason =
2501            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
2502        let target = route.goodbye_target;
2503        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
2504            existing.connection_id == target.connection_id && *reason == recipient_reason
2505        }) {
2506            debug_assert_eq!(
2507                existing.negotiated_ver, target.negotiated_ver,
2508                "one connection cannot negotiate multiple frame versions"
2509            );
2510            if !channels.contains(&target.channel) {
2511                channels.push(target.channel);
2512            }
2513            continue;
2514        }
2515        let channel = target.channel;
2516        targets.push((target, recipient_reason, vec![channel]));
2517    }
2518    for (target, recipient_reason, mut channels) in targets {
2519        channels.sort_unstable();
2520        let mut push = push.clone();
2521        match &mut push {
2522            ClientControlPush::RouteClosing {
2523                channels: covered,
2524                reason,
2525                ..
2526            }
2527            | ClientControlPush::RouteClosed {
2528                channels: covered,
2529                reason,
2530                ..
2531            } => {
2532                *covered = channels;
2533                *reason = recipient_reason;
2534            }
2535        }
2536        let body = match serde_json::to_vec(&push) {
2537            Ok(body) => body,
2538            Err(err) => {
2539                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
2540                continue;
2541            }
2542        };
2543        let frame = match Frame::build_with_version(
2544            target.negotiated_ver,
2545            FrameType::Push,
2546            control_flags(),
2547            0,
2548            0,
2549            0,
2550            body.clone(),
2551        ) {
2552            Ok(frame) => frame,
2553            Err(err) => {
2554                warn!(
2555                    route_channel = target.channel,
2556                    error = %err,
2557                    "failed to build route lifecycle control PUSH frame"
2558                );
2559                continue;
2560            }
2561        };
2562        if let Err(err) = target.sink.try_send(frame) {
2563            if target.close_on_delivery_failure() {
2564                warn!(
2565                    target_connection_id = target.connection_id.get(),
2566                    route_channel = target.channel,
2567                    error = %err,
2568                    "route lifecycle control PUSH was not delivered to client; closing target connection"
2569                );
2570                let _ = forwarding.escalate_client_delivery_failure(
2571                    target.connection_id,
2572                    target.channel,
2573                    target.epoch,
2574                    CloseReason::new(
2575                        "route_lifecycle_push_delivery_failed",
2576                        format!(
2577                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
2578                            target.channel
2579                        ),
2580                    ),
2581                    crate::forwarding::UndeliveredFrame {
2582                        module_id: target.module_id.as_deref(),
2583                        sink: &target.sink,
2584                    },
2585                );
2586            }
2587        }
2588    }
2589}
2590
2591#[cfg(test)]
2592#[path = "control/scope_outcome_count_tests.rs"]
2593mod scope_outcome_count_tests;
2594
2595#[cfg(test)]
2596#[path = "control/control_tests.rs"]
2597mod tests;
2598
2599#[cfg(test)]
2600#[path = "control/concurrency_default_exposure_tests.rs"]
2601mod concurrency_default_exposure_tests;