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