Skip to main content

subc_daemon/
bootstrap.rs

1use std::{
2    collections::BTreeMap,
3    env,
4    error::Error,
5    ffi::OsString,
6    fmt, fs, io,
7    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
8    path::{Path, PathBuf},
9    process,
10    time::Duration,
11};
12
13use fs4::{FileExt, TryLockError};
14use subc_protocol::PROTOCOL_VERSION;
15pub use subc_transport::user_connection_token;
16use subc_transport::{
17    authenticate_client, connection_file, generate_daemon_id, generate_key, write_atomic,
18    AuthError, ConnectionFileError, ConnectionInfo, Endpoint, SCHEMA_VERSION,
19};
20use tokio::{
21    net::{TcpListener, TcpStream},
22    task::{JoinError, JoinHandle},
23    time::{sleep, timeout},
24};
25use tracing::{error, info, warn};
26
27use crate::{
28    daemon_config::{self, ConfiguredModule, DaemonConfigError},
29    server::{serve_listeners, ServerAuth, ServerError},
30    supervise::HealthConfig,
31    ConnectedClients, ControlHandler, DaemonSelfWatchdog, DaemonSelfWatchdogConfig,
32    ForwardingTable, Registry, RestartPolicy, Router, Supervisor, SupervisorHandle,
33    SupervisorProcessLiveness,
34};
35use std::sync::Arc;
36
37pub const DEFAULT_SUBC_PORT: u16 = 8757;
38pub const SUBC_PORT_ENV: &str = "SUBC_PORT";
39use subc_transport::CONNECTION_FILE_NAME;
40const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");
41const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
42const PROBE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
43const START_LOCK_RETRIES: usize = 40;
44const START_LOCK_RETRY_DELAY: Duration = Duration::from_millis(25);
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ConnectionFileSource {
48    XdgRuntimeDir,
49    TempDirFallback,
50    Explicit,
51}
52
53impl ConnectionFileSource {
54    fn reason(self) -> &'static str {
55        match self {
56            Self::XdgRuntimeDir => "XDG_RUNTIME_DIR set and non-empty",
57            Self::TempDirFallback => "XDG_RUNTIME_DIR unset or empty",
58            Self::Explicit => "configured path",
59        }
60    }
61}
62
63impl fmt::Display for ConnectionFileSource {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter.write_str(match self {
66            Self::XdgRuntimeDir => "xdg_runtime_dir",
67            Self::TempDirFallback => "temp_dir_fallback",
68            Self::Explicit => "explicit",
69        })
70    }
71}
72
73/// Runtime bootstrap configuration. Production uses the default fixed port and
74/// optional daemon-config override; tests pass port 0 to let the OS assign a free
75/// loopback port and discover it from the connection file.
76#[derive(Debug, Clone, Default)]
77struct AdmissionFactsConfig {
78    carrier_module_id: Option<String>,
79    targets: Option<Vec<String>>,
80}
81
82/// Controls where module cgroups are prepared.
83///
84/// In-process daemons default to [`Self::Disabled`] so they never derive a
85/// production location from the host process. The shipped daemon explicitly uses
86/// [`Self::Current`]. The `ck-subc` binary accepts
87/// `SUBC_CGROUP_PLACEMENT=disabled` for isolated test processes; an unset
88/// variable retains `Current`, and every other value is rejected at startup.
89/// Tests that exercise placement can own a [`Self::Root`].
90#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub enum CgroupPlacementConfig {
92    #[default]
93    Disabled,
94    Current,
95    Root(PathBuf),
96}
97
98#[derive(Debug, Clone)]
99pub struct BootstrapConfig {
100    pub operator_queue_wait: Duration,
101    pub operator_timeout: Duration,
102    pub operator_stuck_grace: Duration,
103    #[cfg(feature = "test-support")]
104    pub operator_script: Option<PathBuf>,
105    #[cfg(feature = "test-support")]
106    pub operator_events: Option<PathBuf>,
107    pub connection_file_path: PathBuf,
108    pub port: u16,
109    pub daemon_ver: String,
110    configured_modules: Vec<ConfiguredModule>,
111    storage_config: Option<daemon_config::StorageConfig>,
112    admission_facts: AdmissionFactsConfig,
113    /// Module ids whose scopes may carry the attributes that grant authority.
114    scope_authority_owners: Vec<String>,
115    privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
116    activity_config: daemon_config::ActivityConfig,
117    daemon_config_path: Option<PathBuf>,
118    configured_port: Option<u16>,
119    /// Daemon-wide route.bind relay budget in milliseconds (the fallback for
120    /// any module without a per-module override). `None` = built-in default
121    /// (12s — see `control::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`).
122    route_bind_relay_default_ms: Option<u64>,
123    reserved_capabilities: BTreeMap<String, String>,
124    watchdog_config: DaemonSelfWatchdogConfig,
125    connection_file_source: ConnectionFileSource,
126    /// Where module cgroups are prepared. Disabled unless a caller explicitly
127    /// opts in, because `Current` derives a host location from `/proc/self/cgroup`.
128    cgroup_placement: CgroupPlacementConfig,
129    /// Directory the supervisor writes per-module stdout/stderr capture files
130    /// into. `None` disables capture; the shipped binary supplies its real run
131    /// directory explicitly.
132    capture_logs_dir: Option<PathBuf>,
133    /// File the supervisor appends every module's terminal exits to, so exit
134    /// history survives a daemon restart. `None` keeps terminal history in
135    /// memory only (each module's ring). Absent by default for the same reason
136    /// as `capture_logs_dir`: an in-process daemon booted by a test must not
137    /// append its exits to the operator's real `terminals.jsonl`, where they
138    /// would show up in `ck module terminals`. The shipped binary supplies
139    /// `<run dir>/terminals.jsonl` explicitly.
140    terminal_journal_path: Option<PathBuf>,
141    /// Where the machine id is read from, or minted into when absent. `None`
142    /// serves no machine id. Absent by default for the same reason as
143    /// `capture_logs_dir`: an in-process daemon booted by a test must never
144    /// derive the operator's real data home and mint into it. The shipped binary
145    /// supplies `<data home>/cortexkit/machine-id` explicitly.
146    machine_id_path: Option<PathBuf>,
147    /// The live-children record: every supervised process this daemon has
148    /// running, kept so the next daemon can end the ones a crash left behind.
149    /// At startup, before any module is spawned, the previous daemon's record
150    /// here is swept. `None` keeps no record and sweeps nothing, for the same
151    /// reason as `capture_logs_dir`: an in-process daemon booted by a test
152    /// must never signal processes listed in the operator's real run
153    /// directory. The shipped binary supplies `<run dir>/live-children.json`.
154    live_children_path: Option<PathBuf>,
155    privacy_trampoline: Option<PathBuf>,
156}
157
158impl BootstrapConfig {
159    pub fn new(connection_file_path: impl Into<PathBuf>, port: u16) -> Self {
160        Self {
161            connection_file_path: connection_file_path.into(),
162            operator_queue_wait: Duration::from_secs(150),
163            operator_timeout: Duration::from_secs(120),
164            operator_stuck_grace: Duration::from_secs(10),
165            #[cfg(feature = "test-support")]
166            operator_script: None,
167            #[cfg(feature = "test-support")]
168            operator_events: None,
169            port,
170            daemon_ver: DAEMON_VERSION.to_owned(),
171            configured_modules: Vec::new(),
172            storage_config: None,
173            admission_facts: AdmissionFactsConfig::default(),
174            scope_authority_owners: daemon_config::default_scope_authority_owners(),
175            privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt::default(),
176            activity_config: daemon_config::ActivityConfig::default(),
177            daemon_config_path: None,
178            configured_port: None,
179            route_bind_relay_default_ms: None,
180            reserved_capabilities: BTreeMap::new(),
181            watchdog_config: DaemonSelfWatchdogConfig::default(),
182            connection_file_source: ConnectionFileSource::Explicit,
183            cgroup_placement: CgroupPlacementConfig::default(),
184            capture_logs_dir: None,
185            terminal_journal_path: None,
186            machine_id_path: None,
187            live_children_path: None,
188            privacy_trampoline: None,
189        }
190    }
191
192    /// Keep the live-children record at `path`, and at startup end the
193    /// processes a previous daemon recorded there that are still running.
194    /// Embedding daemons and tests pass a path inside their own fixture tree.
195    pub fn with_live_children_record(mut self, path: impl Into<PathBuf>) -> Self {
196        self.live_children_path = Some(path.into());
197        self
198    }
199
200    /// macOS module launches require an explicit executable implementing the
201    /// subc-os trampoline entry point. Other systems ignore this setting.
202    pub fn with_privacy_trampoline(mut self, path: impl Into<PathBuf>) -> Self {
203        self.privacy_trampoline = Some(path.into());
204        self
205    }
206
207    /// Serve the machine id stored at `path`, minting it there at startup when
208    /// the file is absent. Embedding daemons and tests pass a path inside their
209    /// own fixture tree.
210    pub fn with_machine_id_path(mut self, path: impl Into<PathBuf>) -> Self {
211        self.machine_id_path = Some(path.into());
212        self
213    }
214
215    /// Selects module cgroup placement. The default is disabled.
216    pub fn with_cgroup_placement(mut self, placement: CgroupPlacementConfig) -> Self {
217        self.cgroup_placement = placement;
218        self
219    }
220
221    /// Redirects per-module stdout/stderr capture files out of the real run
222    /// directory. Tests that start an in-process daemon must call this with a
223    /// path inside their fixture tree.
224    pub fn with_capture_logs_dir(mut self, dir: impl Into<PathBuf>) -> Self {
225        self.capture_logs_dir = Some(dir.into());
226        self
227    }
228
229    /// Redirects the daemon-private journal, allowing embedded daemons and tests
230    /// to keep their observations out of the operator's live run directory.
231    pub fn with_terminal_journal_path(mut self, path: impl Into<PathBuf>) -> Self {
232        self.terminal_journal_path = Some(path.into());
233        self
234    }
235
236    pub fn from_env() -> Result<Self, BootstrapError> {
237        Self::from_env_with_daemon_config_path(daemon_config::default_config_path())
238    }
239
240    /// The SHIPPED BINARY's config, which is the only caller that should capture
241    /// child output into the operator's real run directory.
242    ///
243    /// Kept separate from `from_env` deliberately: see `capture_logs_dir` and
244    /// `terminal_journal_path` on this struct for why an absent value must mean
245    /// NO CAPTURE and NO JOURNAL rather than the operator's real run directory.
246    /// A run directory that cannot be resolved (a relative data home) refuses
247    /// startup instead of landing under the working directory.
248    pub fn from_env_for_daemon_binary() -> Result<Self, BootstrapError> {
249        let run_dir = daemon_config::daemon_run_dir().map_err(BootstrapError::RunDir)?;
250        let machine_id_path =
251            crate::machine_id::default_machine_id_path().map_err(BootstrapError::MachineId)?;
252        let config = Self::from_env()?
253            .with_capture_logs_dir(run_dir.join("logs"))
254            .with_terminal_journal_path(run_dir.join("terminals.jsonl"))
255            .with_live_children_record(crate::live_children::record_path(&run_dir))
256            .with_machine_id_path(machine_id_path);
257        #[cfg(feature = "test-support")]
258        let config = {
259            let mut config = config;
260            config.operator_script =
261                std::env::var_os("SUBC_TEST_OPERATOR_SCRIPT").map(PathBuf::from);
262            config.operator_events =
263                std::env::var_os("SUBC_TEST_OPERATOR_EVENTS").map(PathBuf::from);
264            for (name, value) in [
265                (
266                    "SUBC_TEST_OPERATOR_QUEUE_WAIT_MS",
267                    &mut config.operator_queue_wait,
268                ),
269                (
270                    "SUBC_TEST_OPERATOR_TIMEOUT_MS",
271                    &mut config.operator_timeout,
272                ),
273                (
274                    "SUBC_TEST_OPERATOR_STUCK_MS",
275                    &mut config.operator_stuck_grace,
276                ),
277            ] {
278                if let Ok(ms) = std::env::var(name) {
279                    if let Ok(ms) = ms.parse::<u64>() {
280                        *value = Duration::from_millis(ms);
281                    }
282                }
283            }
284            config
285        };
286        Ok(config)
287    }
288
289    pub fn from_env_with_daemon_config_path(
290        daemon_config_path: impl AsRef<Path>,
291    ) -> Result<Self, BootstrapError> {
292        let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
293        let (daemon_config, activity_config) =
294            daemon_config::load_with_activity(&daemon_config_path)
295                .map_err(BootstrapError::DaemonConfig)?
296                .map(|(config, activity)| (Some(config), activity))
297                .unwrap_or_default();
298        let config_port = daemon_config.as_ref().and_then(|config| config.port);
299        let storage_config = daemon_config
300            .as_ref()
301            .and_then(|config| config.storage.clone());
302        let admission_facts_carrier_module_id = daemon_config
303            .as_ref()
304            .and_then(|config| config.admission_facts_carrier_module_id.clone());
305        let admission_facts_targets = daemon_config
306            .as_ref()
307            .and_then(|config| config.admission_facts_targets.clone());
308        let scope_authority_owners = daemon_config
309            .as_ref()
310            .map(|config| config.scope_authority_owners.clone())
311            .unwrap_or_else(daemon_config::default_scope_authority_owners);
312        let privileged_operator_prompt = daemon_config
313            .as_ref()
314            .map(|config| config.privileged_operator_prompt)
315            .unwrap_or_default();
316        let route_bind_relay_default_ms = daemon_config
317            .as_ref()
318            .and_then(|config| config.route_bind_relay_timeout_ms);
319        let reserved_capabilities = daemon_config
320            .as_ref()
321            .map(|config| config.reserved_capabilities.clone())
322            .unwrap_or_default();
323        let configured_modules = daemon_config
324            .map(|config| config.modules)
325            .unwrap_or_default();
326
327        let port = match env::var(SUBC_PORT_ENV) {
328            Ok(raw) if !raw.trim().is_empty() => {
329                let port = raw
330                    .parse::<u16>()
331                    .map_err(|source| BootstrapError::InvalidPort { raw, source })?;
332                if let Some(config_port) = config_port {
333                    info!(
334                        env = SUBC_PORT_ENV,
335                        env_port = port,
336                        config_port,
337                        "SUBC_PORT overrides daemon config port"
338                    );
339                }
340                port
341            }
342            Ok(_) | Err(_) => config_port.unwrap_or(DEFAULT_SUBC_PORT),
343        };
344
345        let (connection_file_path, connection_file_source) =
346            connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR"));
347        Ok(Self::new(connection_file_path, port)
348            .with_configured_modules(configured_modules)
349            .with_storage_config(storage_config)
350            .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
351            .with_scope_authority_owners(scope_authority_owners)
352            .with_privileged_operator_prompt(privileged_operator_prompt)
353            .with_activity_config(activity_config)
354            .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
355            .with_reserved_capabilities(reserved_capabilities)
356            .with_daemon_config_source(daemon_config_path, config_port)
357            .with_connection_file_source(connection_file_source))
358    }
359
360    pub fn with_daemon_config_path(
361        self,
362        daemon_config_path: impl AsRef<Path>,
363    ) -> Result<Self, BootstrapError> {
364        let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
365        let (daemon_config, activity_config) =
366            daemon_config::load_with_activity(&daemon_config_path)
367                .map_err(BootstrapError::DaemonConfig)?
368                .map(|(config, activity)| (Some(config), activity))
369                .unwrap_or_default();
370        let configured_port = daemon_config.as_ref().and_then(|config| config.port);
371        let storage_config = daemon_config
372            .as_ref()
373            .and_then(|config| config.storage.clone());
374        let admission_facts_carrier_module_id = daemon_config
375            .as_ref()
376            .and_then(|config| config.admission_facts_carrier_module_id.clone());
377        let admission_facts_targets = daemon_config
378            .as_ref()
379            .and_then(|config| config.admission_facts_targets.clone());
380        let scope_authority_owners = daemon_config
381            .as_ref()
382            .map(|config| config.scope_authority_owners.clone())
383            .unwrap_or_else(daemon_config::default_scope_authority_owners);
384        let privileged_operator_prompt = daemon_config
385            .as_ref()
386            .map(|config| config.privileged_operator_prompt)
387            .unwrap_or_default();
388        let route_bind_relay_default_ms = daemon_config
389            .as_ref()
390            .and_then(|config| config.route_bind_relay_timeout_ms);
391        let reserved_capabilities = daemon_config
392            .as_ref()
393            .map(|config| config.reserved_capabilities.clone())
394            .unwrap_or_default();
395        let configured_modules = daemon_config
396            .map(|config| config.modules)
397            .unwrap_or_default();
398        Ok(self
399            .with_configured_modules(configured_modules)
400            .with_storage_config(storage_config)
401            .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
402            .with_scope_authority_owners(scope_authority_owners)
403            .with_privileged_operator_prompt(privileged_operator_prompt)
404            .with_activity_config(activity_config)
405            .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
406            .with_reserved_capabilities(reserved_capabilities)
407            .with_daemon_config_source(daemon_config_path, configured_port))
408    }
409
410    pub fn with_configured_modules(
411        mut self,
412        modules: impl IntoIterator<Item = ConfiguredModule>,
413    ) -> Self {
414        self.configured_modules = modules.into_iter().collect();
415        self.configured_modules
416            .sort_by(|left, right| left.module_id.cmp(&right.module_id));
417        self
418    }
419
420    pub fn with_storage_config(
421        mut self,
422        storage_config: Option<daemon_config::StorageConfig>,
423    ) -> Self {
424        self.storage_config = storage_config;
425        self
426    }
427
428    pub fn with_admission_facts_config(
429        mut self,
430        carrier_module_id: Option<String>,
431        targets: Option<Vec<String>>,
432    ) -> Self {
433        self.admission_facts = AdmissionFactsConfig {
434            carrier_module_id,
435            targets,
436        };
437        self
438    }
439
440    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
441    /// Absent from a config, this is `daemon_config::default_scope_authority_owners`.
442    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
443        self.scope_authority_owners = owners;
444        self
445    }
446
447    /// Choose the privileged-operation policy for the daemon's entire lifetime.
448    pub fn with_privileged_operator_prompt(
449        mut self,
450        mode: daemon_config::PrivilegedOperatorPrompt,
451    ) -> Self {
452        self.privileged_operator_prompt = mode;
453        self
454    }
455
456    pub fn with_activity_config(mut self, config: daemon_config::ActivityConfig) -> Self {
457        self.activity_config = config;
458        self
459    }
460
461    /// Set the daemon-wide route.bind relay default (the fallback for any
462    /// module without a per-module override). `None` preserves the built-in
463    /// default (12s). `serve_bound_daemon` reads this at startup and threads
464    /// it into the control handler's daemon-wide field.
465    pub fn with_route_bind_relay_default_ms(mut self, ms: Option<u64>) -> Self {
466        self.route_bind_relay_default_ms = ms;
467        self
468    }
469
470    pub fn with_reserved_capabilities(
471        mut self,
472        reserved_capabilities: BTreeMap<String, String>,
473    ) -> Self {
474        self.reserved_capabilities = reserved_capabilities;
475        self
476    }
477
478    fn with_daemon_config_source(
479        mut self,
480        daemon_config_path: PathBuf,
481        configured_port: Option<u16>,
482    ) -> Self {
483        self.daemon_config_path = Some(daemon_config_path);
484        self.configured_port = configured_port;
485        self
486    }
487
488    fn with_connection_file_source(mut self, source: ConnectionFileSource) -> Self {
489        self.connection_file_source = source;
490        self
491    }
492
493    pub fn with_watchdog_config(mut self, watchdog_config: DaemonSelfWatchdogConfig) -> Self {
494        self.watchdog_config = watchdog_config;
495        self
496    }
497}
498
499/// Result of singleton discovery.
500// Built once per daemon start and immediately matched, so the size gap between
501// the variants costs nothing worth a box on the public shape.
502#[allow(clippy::large_enum_variant)]
503#[derive(Debug)]
504pub enum Outcome {
505    /// A live daemon authenticated from the connection file; this invocation should exit 0.
506    AlreadyRunning,
507    /// This process won the singleton race, owns bound loopback listener(s), and
508    /// has published a fresh connection file.
509    Bound(BoundDaemon),
510}
511
512#[derive(Debug)]
513pub struct BoundDaemon {
514    pub listeners: Vec<TcpListener>,
515    pub connection_info: ConnectionInfo,
516    pub connection_file_path: PathBuf,
517    pub connection_file_source: ConnectionFileSource,
518    /// The machine id this daemon serves, established before any connection is
519    /// accepted. `None` when the config named no machine id path.
520    pub machine_id: Option<crate::machine_id::MachineId>,
521    /// Ownership of the run directory, held until the daemon exits so no other
522    /// daemon sweeps or writes this one's run state. `None` when the config
523    /// keeps no live-children record, and so has no run directory to own.
524    run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
525    /// The singleton start lock, kept when binding deferred publishing the
526    /// connection file. It stays held until the daemon has verified it is serving
527    /// and written the connection file, so a second daemon starting meanwhile
528    /// cannot claim the singleton too. `None` when the connection
529    /// file was already written at bind time.
530    publication_lock: Option<StartLock>,
531}
532
533/// Resolve subc's per-user TCP connection-file path.
534///
535/// `$XDG_RUNTIME_DIR/subc-connection.json` is preferred because the runtime
536/// directory is already per-user on Unix desktops. Without it, subc falls back
537/// to the system temp dir with a per-user token in the filename so different OS
538/// users do not collide on shared temp directories.
539pub fn connection_file_path() -> PathBuf {
540    connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR")).0
541}
542
543fn connection_file_path_with_source(
544    runtime_dir: Option<OsString>,
545) -> (PathBuf, ConnectionFileSource) {
546    if let Some(runtime_dir) = runtime_dir.filter(|value| !value.is_empty()) {
547        return (
548            PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
549            ConnectionFileSource::XdgRuntimeDir,
550        );
551    }
552
553    (
554        env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token())),
555        ConnectionFileSource::TempDirFallback,
556    )
557}
558
559/// Resolve, claim, and serve the per-user daemon singleton.
560///
561/// A second invocation is successful: if a live daemon authenticates from the
562/// existing connection file, this returns `Ok(())` after logging and the caller
563/// exits with status 0.
564pub async fn run() -> Result<(), BootstrapError> {
565    // `run` is a binary entry point, so it opts into the production cgroup and
566    // child-log locations. In-process callers keep both features disabled by default.
567    run_with_config(
568        BootstrapConfig::from_env_for_daemon_binary()?
569            .with_cgroup_placement(CgroupPlacementConfig::Current),
570    )
571    .await
572}
573
574/// Serve a daemon from an explicit config. This is the entry point the twelve
575/// sibling repos use to boot an in-process daemon in their integration tests.
576///
577/// # THIS INSTALLS NO TRACING SUBSCRIBER, SO THE DAEMON IS SILENT BY DEFAULT
578///
579/// The daemon's own diagnostics go through `tracing`, and `tracing` DISCARDS
580/// every event when no subscriber is installed. The shipped binary installs one
581/// in `main` (`init_tracing`); this function deliberately does not, because a
582/// library that installs a global subscriber fights with whatever the host
583/// process already set up.
584///
585/// The consequence for a test harness is not "less verbose": it is that the
586/// daemon has NOTHING TO SAY about any failure, and a missing instrument reads
587/// exactly like a clean one. PLEX found this on 2026-09-18 while trying to
588/// capture daemon logs beside an intermittent bind failure, and discovered the
589/// daemon had been silent in every conformance run that repo had ever done --
590/// so the one client-side error string was all the evidence that could exist,
591/// and they had spent a real investigation on a failure whose second source was
592/// never being recorded.
593///
594/// Install one in the harness before calling this, and assert it did something
595/// (they measured 236 daemon lines with the subscriber installed, 0 with the
596/// call commented out) -- otherwise the fix is itself unverified.
597pub async fn run_with_config(config: BootstrapConfig) -> Result<(), BootstrapError> {
598    let forwarding = Arc::new(ForwardingTable::default());
599    forwarding.operator_confirms().configure_bootstrap(&config);
600    let configured_modules = config.configured_modules.clone();
601    let storage_config = config.storage_config.clone();
602    let admission_facts = config.admission_facts.clone();
603    let scope_authority_owners = config.scope_authority_owners.clone();
604    let privileged_operator_prompt = config.privileged_operator_prompt;
605    let activity_config = config.activity_config;
606    let daemon_config_path = config.daemon_config_path.clone();
607    let configured_port = config.configured_port;
608    let route_bind_relay_default_ms = config.route_bind_relay_default_ms;
609    let reserved_capabilities = config.reserved_capabilities.clone();
610    let watchdog_config = config.watchdog_config.clone();
611    let cgroup_placement_config = config.cgroup_placement.clone();
612    let capture_logs_dir = config.capture_logs_dir.clone();
613    let terminal_journal_path = config.terminal_journal_path.clone();
614    let live_children_path = config.live_children_path.clone();
615    let privacy_trampoline = config.privacy_trampoline.clone();
616    match ensure_singleton_inner(config, false).await? {
617        Outcome::AlreadyRunning => {
618            info!("subc daemon already running");
619            Ok(())
620        }
621        Outcome::Bound(bound) => {
622            #[cfg(target_os = "linux")]
623            let cgroup_placement = prepare_cgroup_placement(&cgroup_placement_config);
624            #[cfg(not(target_os = "linux"))]
625            let _ = cgroup_placement_config;
626            serve_bound_daemon(
627                bound,
628                forwarding,
629                configured_modules,
630                storage_config,
631                admission_facts,
632                scope_authority_owners,
633                privileged_operator_prompt,
634                activity_config,
635                daemon_config_path,
636                configured_port,
637                route_bind_relay_default_ms,
638                reserved_capabilities,
639                watchdog_config,
640                capture_logs_dir,
641                terminal_journal_path,
642                live_children_path,
643                privacy_trampoline,
644                #[cfg(target_os = "linux")]
645                cgroup_placement,
646            )
647            .await
648        }
649    }
650}
651
652#[cfg(target_os = "linux")]
653fn prepare_cgroup_placement(config: &CgroupPlacementConfig) -> Option<subc_cgroup::Placement> {
654    let result = match config {
655        CgroupPlacementConfig::Disabled => return None,
656        CgroupPlacementConfig::Current => subc_cgroup::prepare_current(),
657        CgroupPlacementConfig::Root(root) => subc_cgroup::prepare_at(root),
658    };
659
660    match result {
661        Ok(Some(placement)) => Some(placement),
662        Ok(None) => {
663            warn!(
664                placement = ?config,
665                "module cgroup placement is disabled: configured cgroup root is not delegated"
666            );
667            None
668        }
669        Err(error) => {
670            warn!(
671                placement = ?config,
672                error = %error,
673                "module cgroup placement is disabled by an unexpected cgroup probe error"
674            );
675            None
676        }
677    }
678}
679
680/// Target soft limit for open file descriptors, applied to the daemon before any
681/// module is spawned so children inherit it. Multi-root modules (one process
682/// aggregating every project root's sqlite stores, index caches, watchers, and
683/// LSP pipes) trivially exceed the macOS default soft limit of 256; a launchd
684/// user agent does not pass login-shell ulimits through, so the raise must
685/// happen in-process.
686#[cfg(unix)]
687const NOFILE_TARGET: u64 = 65536;
688
689/// Raise RLIMIT_NOFILE to `NOFILE_TARGET` (clamped to the hard limit).
690/// Best-effort: failure is logged and never fatal, since the daemon can run
691/// under the inherited limit — modules with few roots just have less headroom.
692#[cfg(unix)]
693fn raise_nofile_limit() {
694    #[cfg(target_os = "macos")]
695    let ceiling = std::process::Command::new("/usr/sbin/sysctl")
696        .args(["-n", "kern.maxfilesperproc"])
697        .output()
698        .ok()
699        .filter(|output| output.status.success())
700        .and_then(|output| String::from_utf8(output.stdout).ok())
701        .and_then(|value| value.trim().parse::<u64>().ok())
702        .filter(|value| *value > 0);
703    #[cfg(not(target_os = "macos"))]
704    let ceiling = None;
705    raise_nofile_limit_with_ceiling(ceiling);
706}
707
708#[cfg(unix)]
709fn raise_nofile_limit_with_ceiling(kernel_ceiling: Option<u64>) {
710    match rlimit::Resource::NOFILE.get() {
711        Ok((soft, hard)) => {
712            // On XNU an infinite hard limit does not remove the separate
713            // per-process kernel ceiling. Exceeding it makes setrlimit fail
714            // without raising the inherited (often 256) soft limit at all.
715            let target = NOFILE_TARGET
716                .min(hard)
717                .min(kernel_ceiling.unwrap_or(u64::MAX));
718            if soft >= target {
719                return;
720            }
721            match rlimit::Resource::NOFILE.set(target, hard) {
722                Ok(()) => info!(
723                    previous_soft = soft,
724                    new_soft = target,
725                    hard,
726                    "raised open-file soft limit for daemon and module children"
727                ),
728                Err(err) => warn!(
729                    soft,
730                    hard,
731                    error = %err,
732                    "could not raise open-file soft limit; multi-root modules may exhaust descriptors"
733                ),
734            }
735        }
736        Err(err) => warn!(error = %err, "could not read open-file limit"),
737    }
738}
739
740/// CRT stdio-stream target on Windows (the `_setmaxstdio` maximum). Win32
741/// HANDLEs — what Rust `File`, tokio sockets, and SQLite's Win32 VFS actually
742/// consume — have a per-process quota in the millions and need no raise; the
743/// C-runtime stream table (default 512) is the only low ceiling, and it is
744/// per-process rather than inherited, so supervised modules linking the CRT
745/// must raise their own. Raising it here covers the daemon itself.
746#[cfg(windows)]
747fn raise_nofile_limit() {
748    const MAXSTDIO_TARGET: u32 = 8192;
749    let current = rlimit::getmaxstdio();
750    if current >= MAXSTDIO_TARGET {
751        return;
752    }
753    match rlimit::setmaxstdio(MAXSTDIO_TARGET) {
754        Ok(new_max) => info!(
755            previous = current,
756            new_max, "raised CRT stdio-stream limit for daemon"
757        ),
758        Err(err) => warn!(
759            current,
760            error = %err,
761            "could not raise CRT stdio-stream limit"
762        ),
763    }
764}
765
766#[cfg(not(any(unix, windows)))]
767fn raise_nofile_limit() {}
768
769pub async fn run_with_daemon_config_path(
770    config: BootstrapConfig,
771    daemon_config_path: impl AsRef<Path>,
772) -> Result<(), BootstrapError> {
773    run_with_config(config.with_daemon_config_path(daemon_config_path)?).await
774}
775
776#[allow(clippy::too_many_arguments)]
777async fn serve_bound_daemon(
778    bound: BoundDaemon,
779    forwarding: Arc<ForwardingTable>,
780    configured_modules: Vec<ConfiguredModule>,
781    storage_config: Option<daemon_config::StorageConfig>,
782    admission_facts: AdmissionFactsConfig,
783    scope_authority_owners: Vec<String>,
784    privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
785    activity_config: daemon_config::ActivityConfig,
786    daemon_config_path: Option<PathBuf>,
787    configured_port: Option<u16>,
788    route_bind_relay_default_ms: Option<u64>,
789    reserved_capabilities: BTreeMap<String, String>,
790    watchdog_config: DaemonSelfWatchdogConfig,
791    capture_logs_dir: Option<PathBuf>,
792    terminal_journal_path: Option<PathBuf>,
793    live_children_path: Option<PathBuf>,
794    privacy_trampoline: Option<PathBuf>,
795    #[cfg(target_os = "linux")] cgroup_placement: Option<subc_cgroup::Placement>,
796) -> Result<(), BootstrapError> {
797    #[cfg(unix)]
798    let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
799        .map_err(BootstrapError::Signal)?;
800    // Windows has no SIGTERM. Ctrl-C is a different event, not an equivalent
801    // service-stop contract, so this shutdown handler is intentionally Unix-only.
802    raise_nofile_limit();
803    #[cfg(windows)]
804    if let Err(error) = subc_jobobject::ensure_root_job() {
805        // Keep the control plane available. The root-job API caches setup
806        // failures, so later module spawns refuse instead of running unprotected.
807        warn!(%error, "module launches disabled: Windows root job setup failed");
808    }
809
810    info!(
811        connection_file = %bound.connection_file_path.display(),
812        connection_file_source = %bound.connection_file_source,
813        connection_file_source_reason = bound.connection_file_source.reason(),
814        endpoints = ?bound.connection_info.endpoints,
815        configured_modules = configured_modules.len(),
816        machine_id = bound.machine_id.as_ref().map(|id| id.as_str()).unwrap_or("none"),
817        "subc daemon starting"
818    );
819
820    // Before anything can spawn a module (the configured modules below, or a
821    // client's start request once the listeners are served): a previous daemon
822    // that died without its shutdown stop may have left children running, and
823    // a fresh copy beside one would fight it for its port and stores. The
824    // record is not a running daemon's because this daemon holds the lock on
825    // the run directory the record lives in, and a running daemon holds that
826    // lock for its whole life. (Claiming the singleton is not enough: it is
827    // keyed on the connection file, which can live in a different runtime
828    // directory from the run directory.) The lock stays held until this
829    // function returns, which is when the daemon exits.
830    let run_dir_lock = bound.run_dir_lock;
831    let publication_lock = bound.publication_lock;
832    if let Some(owner) = &run_dir_lock {
833        crate::live_children::sweep_orphans(
834            owner,
835            &crate::live_children::AdoptedPids::none(),
836            crate::live_children::SweepBounds::default(),
837        )
838        .await;
839    }
840
841    let registry = Arc::new(Registry::default());
842    let process_liveness = Arc::new(SupervisorProcessLiveness::new());
843    let supervisor_handle = SupervisorHandle::new();
844    let connected_clients = ConnectedClients::new();
845    let daemon_incarnation = format!(
846        "{:032x}",
847        u128::from_be_bytes(bound.connection_info.daemon_id)
848    );
849    let supervisor = Supervisor::new(Arc::clone(&registry), RestartPolicy::default())
850        .with_process_liveness(process_liveness.clone())
851        .with_forwarding(Arc::clone(&forwarding))
852        .with_handle(supervisor_handle.clone())
853        .with_connection_file_path(bound.connection_file_path.clone())
854        .with_daemon_incarnation(daemon_incarnation.clone());
855    let supervisor = match privacy_trampoline {
856        Some(path) => supervisor.with_privacy_trampoline(path),
857        None => supervisor,
858    };
859    // ABSENT MEANS NO CAPTURE AND NO JOURNAL, NOT "THE REAL RUN DIRECTORY", and
860    // the difference is a production-corruption hazard rather than a preference.
861    // Both fields below follow the same rule: `None` for `capture_logs_dir`
862    // means supervised output is not captured, and `None` for
863    // `terminal_journal_path` means terminal history lives only in each
864    // module's in-memory ring (`supervisor.terminals` still answers, with the
865    // journal counters at zero).
866    //
867    // The terminal journal used to fall back to
868    // `daemon_run_dir().join("terminals.jsonl")`, so an in-process test daemon
869    // appended its fixture exits to the operator's journal, where they then
870    // appeared in `ck module terminals`.
871    //
872    // The capture line used to be `unwrap_or_else(|| daemon_run_dir().join("logs"))`,
873    // so ANY caller that did not set the field captured supervised children into
874    // the operator's live `~/.local/share/cortexkit/run/logs/`. That is twelve
875    // sibling repos whose integration tests boot an in-process daemon through
876    // `run_with_config` -- none of which asked for it, and none of which can see
877    // it from their side.
878    //
879    // Harmless while fixture module ids are fixture-shaped: this host carries 20
880    // zero-byte files from subc's own tests (good-aft, missing-aft,
881    // preview-consumer...). THE HAZARD IS A COLLISION. A fixture named "broca"
882    // or "aft" appends to a PRODUCTION capture file that operators read
883    // forensically and that placement gates count lines in -- with no residue to
884    // notice, because the file legitimately exists and legitimately grows.
885    //
886    // Found by BROCA (2026-09-19) from the other side: their rigs spawn the
887    // SHIPPED ck-subc and set XDG_CONFIG_HOME + XDG_RUNTIME_DIR but not
888    // XDG_DATA_HOME, so every local rig run supervised a module named "broca"
889    // and captured it into production's broca.stderr.log -- the same file I
890    // count seal lines in before and after placing their binaries.
891    //
892    // The supervisor already treats `None` as no-capture and no-journal, so
893    // this only removes invented defaults. The binary keeps capturing and
894    // journaling via `BootstrapConfig::from_env_for_daemon_binary`.
895
896    // Keep both ledgers in the explicitly selected run directory. An embedded
897    // daemon without a journal path must not write to the operator's live ledger.
898    let activity_run_dir = terminal_journal_path
899        .as_ref()
900        .and_then(|path| path.parent())
901        .map(Path::to_path_buf);
902    let supervisor = match terminal_journal_path {
903        Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation.clone()),
904        None => supervisor,
905    };
906    let supervisor = match capture_logs_dir {
907        Some(dir) => supervisor.with_capture_logs_dir(dir),
908        None => supervisor,
909    };
910    let supervisor = match live_children_path {
911        Some(path) => supervisor.with_live_children_record(path),
912        None => supervisor,
913    };
914    #[cfg(target_os = "linux")]
915    let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
916    // Collect per-module route.bind relay overrides BEFORE handing the
917    // `configured_modules` vector to the supervisor (which only needs each
918    // module's `drain_timeout_ms`). Each entry was filled in by parse-time
919    // resolution (per-module > daemon-wide > absent), so modules with no
920    // override are absent from this map and the daemon-wide default applies.
921    let route_bind_relay_timeouts = configured_modules
922        .iter()
923        .filter_map(|module| {
924            module
925                .route_bind_relay_timeout_ms
926                .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
927        })
928        .collect::<std::collections::BTreeMap<_, _>>();
929    let control_start_clock = crate::clock::StartClock::capture();
930    let mut control = ControlHandler::with_forwarding(Arc::clone(&registry), forwarding)
931        .with_process_liveness(process_liveness)
932        .with_supervisor(supervisor_handle)
933        // The same flag `begin_daemon_shutdown` sets below, so requirement
934        // changes while modules exit during the shutdown log at INFO.
935        .with_daemon_shutdown_flag(supervisor.daemon_shutdown_flag())
936        .with_connected_clients(connected_clients.clone())
937        .with_storage_config(storage_config)
938        .with_machine_id(bound.machine_id.clone())
939        .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
940        .with_scope_authority_owners(scope_authority_owners)
941        .with_privileged_operator_prompt(privileged_operator_prompt)
942        .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
943        .with_daemon_provenance(
944            bound.connection_info.pid,
945            control_start_clock.started_at_ms(),
946            std::env::current_exe().ok(),
947            normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
948            normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
949        )
950        .with_daemon_start_clock(control_start_clock)
951        .with_capability_config(
952            configured_modules
953                .iter()
954                .map(|module| (module.module_id.clone(), module.enabled)),
955            reserved_capabilities,
956        );
957    if let Some(run_dir) = activity_run_dir {
958        control =
959            control.with_activity_ledger_config(&run_dir, daemon_incarnation, activity_config);
960    }
961    if let Some(ms) = route_bind_relay_default_ms {
962        // A daemon-wide config value overrides the built-in default; a
963        // `None` here leaves the ControlHandler's 12s default in place.
964        control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
965    }
966    if let Some(config_path) = daemon_config_path {
967        control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
968    }
969    let control = Arc::new(control);
970    let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
971    let auth = ServerAuth::new(
972        bound.connection_info.key.clone(),
973        bound.connection_info.daemon_id,
974        bound.connection_info.daemon_ver.clone(),
975    )
976    .with_connected_clients(connected_clients);
977
978    // Discovery must expose every accepted configured module, including disabled
979    // ones. Registration creates status handles but neither starts monitors
980    // nor launches processes: children need the published file for `--subc`.
981    let mut registered_modules = Vec::with_capacity(configured_modules.len());
982    for configured in configured_modules {
983        let enabled = configured.enabled;
984        let health = configured.health.clone();
985        let module_id = configured.module_id.clone();
986        let registered = match supervisor.register_configured_with_health(
987            configured.module_spec(),
988            enabled,
989            health.clone(),
990            configured.drain_timeout_ms,
991            configured.restart,
992        ) {
993            Ok(registered) => registered,
994            Err(err) => {
995                error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
996                continue;
997            }
998        };
999        registered_modules.push(registered);
1000        // A relaxed threshold can silently outlive the temporary allowance
1001        // that required it, so report the extra tolerance on every boot.
1002        let default_threshold = HealthConfig::default().failure_threshold;
1003        if enabled && health.failure_threshold > default_threshold {
1004            warn!(
1005                module_id = %module_id,
1006                failure_threshold = health.failure_threshold,
1007                default_threshold,
1008                tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
1009                "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
1010            );
1011        }
1012        info!(module_id = %module_id, enabled, "configured module registered");
1013    }
1014    control.refresh_capability_requirements();
1015
1016    let mut serve_task =
1017        AbortOnDrop::new(tokio::spawn(serve_listeners(bound.listeners, router, auth)));
1018    verify_serving(&bound.connection_info).await?;
1019    // A published endpoint promises that authentication can complete now.
1020    // Orphan cleanup and control-plane construction can take longer than an
1021    // existing-daemon probe's deadline, so finish both before discovery.
1022    // The write fsyncs, so it runs on tokio's blocking pool (see
1023    // `publish_connection_file`). The singleton lock travels with it and comes
1024    // back only once the file is in place.
1025    let (published, publication_lock) = publish_connection_file(
1026        &bound.connection_file_path,
1027        &bound.connection_info,
1028        publication_lock,
1029    )
1030    .await;
1031    published?;
1032    #[cfg(test)]
1033    startup_publication_hook::run(&bound.connection_file_path).await;
1034    drop(publication_lock);
1035    let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
1036    // Off the startup path: it runs `systemctl`, and only ever logs.
1037    #[cfg(target_os = "linux")]
1038    let _kill_mode_check = AbortOnDrop::new(tokio::spawn(
1039        crate::systemd_kill_mode::warn_if_kill_mode_defeats_ordered_shutdown(),
1040    ));
1041    let _watchdog_task = AbortOnDrop::new(
1042        DaemonSelfWatchdog::new(
1043            bound.connection_info.clone(),
1044            bound.connection_file_path.clone(),
1045        )
1046        .with_config(watchdog_config)
1047        .spawn(),
1048    );
1049
1050    for registered in registered_modules {
1051        match supervisor.start_registered_configured(registered, None) {
1052            Ok(module) => {
1053                info!(module_id = %module.module_id(), "configured module supervised");
1054            }
1055            Err(err) => {
1056                error!(error = %err, "failed to start configured module; continuing daemon startup");
1057            }
1058        }
1059    }
1060
1061    control.refresh_capability_requirements();
1062    Arc::clone(&control).spawn_capability_deadline_loop();
1063    Arc::clone(&control).spawn_scope_expiry_loop();
1064
1065    #[cfg(unix)]
1066    {
1067        tokio::select! {
1068            result = serve_task.join() => {
1069                return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
1070            }
1071            _ = terminate.recv() => {}
1072        }
1073        // First, before the notice, the drain, or any connection close: from
1074        // here on a module exit is recorded as `daemon_shutdown` and never
1075        // respawned. Also before allowing a second signal to cut the bounded
1076        // wait short, so the journal marker is always written.
1077        supervisor.begin_daemon_shutdown();
1078        // Stop the self-watchdog before closing the listener. Its next tick would
1079        // connect to that listener, fail, and log an ERROR indistinguishable from
1080        // a wedged daemon, once for every interval a planned stop lasts.
1081        drop(_watchdog_task);
1082        // Dropping the listener stops new accepts, not established connections:
1083        // their detached tasks must remain live throughout notice and drain.
1084        drop(serve_task);
1085        let escalated = tokio::select! {
1086            biased;
1087            _ = terminate.recv() => {
1088                info!("second SIGTERM: abandoning daemon shutdown wait");
1089                true
1090            }
1091            result = supervisor.drain_for_daemon_shutdown() => {
1092                if let Err(error) = result {
1093                    warn!(%error, "daemon shutdown drain failed; exiting anyway");
1094                }
1095                false
1096            }
1097        };
1098        // Supervised modules lead their own process groups, so a service
1099        // manager's kill of this process's group does not reach them. (A
1100        // systemd unit with KillMode=control-group kills by cgroup instead and
1101        // does reach them; see `systemd_kill_mode`.) The daemon ends them
1102        // itself: EOF (or SIGTERM for a protocol none child) first, then
1103        // signals at each child's own drain deadline.
1104        supervisor
1105            .end_children_for_daemon_shutdown(escalated, async {
1106                terminate.recv().await;
1107            })
1108            .await;
1109        info!("daemon exiting: SIGTERM shutdown complete");
1110        Ok(())
1111    }
1112    #[cfg(not(unix))]
1113    serve_task
1114        .join()
1115        .await
1116        .map_err(BootstrapError::ServeJoin)?
1117        .map_err(BootstrapError::Serve)
1118}
1119
1120fn normalized_build_provenance(value: &str) -> Option<String> {
1121    match value.trim() {
1122        "" | "unavailable" => None,
1123        value => Some(value.to_string()),
1124    }
1125}
1126
1127/// Find an existing daemon or atomically bind loopback TCP for this daemon.
1128///
1129/// The algorithm is intentionally connect-first: an endpoint from the connection
1130/// file is treated as live only after the TCP+key server-proof authenticates for
1131/// that file's key and daemon_id. Stale or foreign connection files are reclaimed
1132/// only while holding the per-user start lock; the TCP port is never the
1133/// singleton primitive.
1134pub async fn ensure_singleton(
1135    connection_file_path: impl AsRef<Path>,
1136    port: u16,
1137) -> Result<Outcome, BootstrapError> {
1138    ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
1139}
1140
1141pub async fn ensure_singleton_with_config(
1142    config: BootstrapConfig,
1143) -> Result<Outcome, BootstrapError> {
1144    ensure_singleton_inner(config, true).await
1145}
1146
1147async fn ensure_singleton_inner(
1148    config: BootstrapConfig,
1149    publish: bool,
1150) -> Result<Outcome, BootstrapError> {
1151    let path = config.connection_file_path;
1152
1153    if stable_peer(&path).await? {
1154        return Ok(Outcome::AlreadyRunning);
1155    }
1156
1157    let lock = StartLock::acquire(&path).await?;
1158
1159    // Re-probe after acquiring the start lock so a peer that won the race between
1160    // our first failed probe and the lock acquisition is observed instead of
1161    // overwritten.
1162    if stable_peer(&path).await? {
1163        return Ok(Outcome::AlreadyRunning);
1164    }
1165
1166    // The start lock and the probe above only rule out a daemon using this
1167    // connection file. A daemon started with another runtime directory but
1168    // the same data home shares the run directory while passing both, so the
1169    // run directory needs its own owner: refuse at once if a live daemon holds
1170    // it, before anything below reads or writes run or data-home state.
1171    let run_dir_lock = config
1172        .live_children_path
1173        .as_deref()
1174        .map(crate::run_dir_lock::RunDirLock::acquire)
1175        .transpose()?;
1176
1177    remove_stale_connection_file_if_present(&path)?;
1178
1179    // Established under the start lock, and under the run-directory lock when
1180    // there is one, and before binding: a corrupt file stops boot before
1181    // anything is published, and two daemons racing to start cannot both mint.
1182    //
1183    // Minting a new machine id fsyncs its file, so loading or minting runs on
1184    // tokio's blocking pool. Both locks travel with that work, so neither is
1185    // released while a mint is in flight.
1186    let (machine_id, lock, run_dir_lock) = match config.machine_id_path {
1187        None => (None, lock, run_dir_lock),
1188        Some(machine_id_path) => {
1189            let task_path = machine_id_path.clone();
1190            match run_blocking_holding((lock, run_dir_lock), move || {
1191                crate::machine_id::load_or_mint(&task_path)
1192            })
1193            .await
1194            {
1195                Ok((Ok(id), (lock, run_dir_lock))) => (Some(id), lock, run_dir_lock),
1196                Ok((Err(error), _locks)) => return Err(BootstrapError::MachineId(error)),
1197                Err(join_error) => {
1198                    return Err(BootstrapError::MachineId(
1199                        crate::machine_id::MachineIdFileError::Write {
1200                            path: machine_id_path,
1201                            source: io::Error::other(describe_blocking_task_failure(
1202                                "loading or minting the machine id",
1203                                &join_error,
1204                            )),
1205                        },
1206                    ))
1207                }
1208            }
1209        }
1210    };
1211
1212    let (listeners, endpoints) = bind_loopback(config.port).await?;
1213    let connection_info = ConnectionInfo {
1214        schema: SCHEMA_VERSION,
1215        wire_version: Some(PROTOCOL_VERSION),
1216        endpoints,
1217        key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
1218        daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
1219        pid: process::id(),
1220        daemon_ver: config.daemon_ver,
1221    };
1222
1223    // The low-level binding API historically publishes for callers that serve
1224    // these listeners themselves. The daemon entry point defers publication
1225    // until its own authentication server is running.
1226    let publication_lock = if publish {
1227        let (published, lock) = publish_connection_file(&path, &connection_info, lock).await;
1228        if let Err(error) = published {
1229            drop(listeners);
1230            return Err(error);
1231        }
1232        drop(lock);
1233        None
1234    } else {
1235        Some(lock)
1236    };
1237
1238    Ok(Outcome::Bound(BoundDaemon {
1239        listeners,
1240        connection_info,
1241        connection_file_path: path,
1242        connection_file_source: config.connection_file_source,
1243        machine_id,
1244        run_dir_lock,
1245        publication_lock,
1246    }))
1247}
1248
1249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1250enum Probe {
1251    Live,
1252    StaleOrAbsent,
1253}
1254
1255async fn stable_peer(path: &Path) -> Result<bool, BootstrapError> {
1256    if !matches!(probe_existing(path).await?, Probe::Live) {
1257        return Ok(false);
1258    }
1259    // A terminating peer can still authenticate while its listeners drain.
1260    // Require another proof after a short settling interval before reporting
1261    // a successful duplicate start. If the peer left, proceed with startup;
1262    // any remaining bind/ownership conflict is an error, not exit 0 (which
1263    // would suppress launchd's restart-on-failure policy).
1264    tokio::time::sleep(Duration::from_millis(1500)).await;
1265    Ok(matches!(probe_existing(path).await?, Probe::Live))
1266}
1267
1268async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
1269    let info = match connection_file::read(path) {
1270        Ok(info) => info,
1271        Err(source) if is_absent_or_stale_connection_file(&source) => {
1272            return Ok(Probe::StaleOrAbsent)
1273        }
1274        Err(source) => {
1275            return Err(BootstrapError::ConnectionFileRead {
1276                path: path.to_path_buf(),
1277                source,
1278            })
1279        }
1280    };
1281
1282    for endpoint in &info.endpoints {
1283        if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
1284            return Ok(Probe::Live);
1285        }
1286    }
1287
1288    Ok(Probe::StaleOrAbsent)
1289}
1290
1291async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
1292    let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
1293        return Probe::StaleOrAbsent;
1294    };
1295    if !ip.is_loopback() {
1296        return Probe::StaleOrAbsent;
1297    }
1298    let addr = SocketAddr::new(ip, endpoint.port);
1299
1300    let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
1301        Ok(Ok(stream)) => stream,
1302        Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
1303    };
1304
1305    match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
1306        Ok(()) => Probe::Live,
1307        Err(AuthError::DaemonIdMismatch)
1308        | Err(AuthError::InvalidServerProof)
1309        | Err(AuthError::UnexpectedEof { .. })
1310        | Err(AuthError::Timeout { .. })
1311        | Err(AuthError::JsonEncode { .. })
1312        | Err(AuthError::JsonDecode { .. })
1313        | Err(AuthError::Io { .. })
1314        | Err(AuthError::MessageTooLarge { .. })
1315        | Err(AuthError::KeyTooShort { .. })
1316        | Err(AuthError::Random(_))
1317        | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
1318    }
1319}
1320
1321async fn verify_serving(info: &ConnectionInfo) -> Result<(), BootstrapError> {
1322    // Scheduling a server task is not a readiness barrier. Authenticate once
1323    // against the mandatory IPv4 listener before exposing discovery to peers.
1324    // This uses the normal probe deadline, with no retries or widened budget.
1325    if let Some(endpoint) = info.endpoints.first() {
1326        if matches!(probe_endpoint(info, endpoint).await, Probe::Live) {
1327            return Ok(());
1328        }
1329    }
1330    Err(BootstrapError::StartupNotServing)
1331}
1332
1333/// Run blocking filesystem work (an fsync, a rename) on tokio's blocking-thread
1334/// pool rather than on the async worker thread that awaits it. On a slow or
1335/// busy disk an fsync can take seconds, and a runtime has few worker threads
1336/// (an in-process test daemon may share two with everything else), so doing it
1337/// inline stalls unrelated tasks for that long.
1338///
1339/// `guards` (lock handles) move into the blocking task and are handed back
1340/// with the work's result. If the awaiting future is dropped first, the work
1341/// still runs to completion on its thread and the guards are released only
1342/// after it ends, so a lock is never given up while the work it protects is
1343/// still writing.
1344///
1345/// `Err` means the task panicked, or was cancelled before it started because
1346/// the runtime is shutting down; the guards have then been released already.
1347async fn run_blocking_holding<G, T>(
1348    guards: G,
1349    work: impl FnOnce() -> T + Send + 'static,
1350) -> Result<(T, G), JoinError>
1351where
1352    G: Send + 'static,
1353    T: Send + 'static,
1354{
1355    tokio::task::spawn_blocking(move || {
1356        let output = work();
1357        (output, guards)
1358    })
1359    .await
1360}
1361
1362/// Explain, for a startup error, why blocking work produced no result.
1363fn describe_blocking_task_failure(work: &str, join_error: &JoinError) -> String {
1364    if join_error.is_panic() {
1365        format!("the background thread {work} panicked before finishing: {join_error}")
1366    } else {
1367        format!(
1368            "the background thread {work} was cancelled before finishing, because the async runtime is shutting down: {join_error}"
1369        )
1370    }
1371}
1372
1373/// Publish the connection file: owner-only permissions, written to a temporary
1374/// file, fsynced and renamed over `path` (all done by `write_atomic`). The
1375/// write runs on tokio's blocking pool through [`run_blocking_holding`], so the
1376/// fsync never holds an async worker thread.
1377///
1378/// `guard` is the singleton start lock (or whatever the caller must keep held
1379/// across publication); it is returned with the result. It comes back `None`
1380/// only when the write task panicked or was cancelled, in which case the
1381/// result is an error and the file must be treated as not published.
1382async fn publish_connection_file<G: Send + 'static>(
1383    path: &Path,
1384    info: &ConnectionInfo,
1385    guard: G,
1386) -> (Result<(), BootstrapError>, Option<G>) {
1387    let task_path = path.to_path_buf();
1388    let task_info = info.clone();
1389    let outcome =
1390        run_blocking_holding(guard, move || write_connection_file(&task_path, &task_info)).await;
1391    match outcome {
1392        Ok((Ok(()), guard)) => (Ok(()), Some(guard)),
1393        Ok((Err(source), guard)) => (
1394            Err(BootstrapError::ConnectionFileWrite {
1395                path: path.to_path_buf(),
1396                source,
1397            }),
1398            Some(guard),
1399        ),
1400        Err(join_error) => (
1401            Err(BootstrapError::ConnectionFileWrite {
1402                path: path.to_path_buf(),
1403                source: ConnectionFileError::Io {
1404                    op: "write",
1405                    path: path.to_path_buf(),
1406                    source: io::Error::other(describe_blocking_task_failure(
1407                        "writing the connection file",
1408                        &join_error,
1409                    )),
1410                },
1411            }),
1412            None,
1413        ),
1414    }
1415}
1416
1417/// The synchronous connection-file write, including its fsync. Call it only
1418/// through [`publish_connection_file`], which keeps it off the async workers.
1419fn write_connection_file(path: &Path, info: &ConnectionInfo) -> Result<(), ConnectionFileError> {
1420    #[cfg(test)]
1421    connection_file_write_hook::run(path);
1422    write_atomic(path, info)
1423}
1424
1425/// Lets a test run code inside the connection-file write, on whichever thread
1426/// performs it, for example to block there and check what else can still run.
1427#[cfg(test)]
1428mod connection_file_write_hook {
1429    use std::{
1430        path::{Path, PathBuf},
1431        sync::{Mutex, PoisonError},
1432    };
1433
1434    type Hook = Box<dyn FnOnce() + Send>;
1435
1436    /// Keyed by connection-file path, so a hook fires only for the test that
1437    /// installed it while other tests publish their own files in parallel.
1438    static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
1439
1440    /// Run `hook` once, at the start of the next write of `path`.
1441    pub(super) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) {
1442        HOOKS
1443            .lock()
1444            .unwrap_or_else(PoisonError::into_inner)
1445            .push((path.to_path_buf(), Box::new(hook)));
1446    }
1447
1448    pub(super) fn run(path: &Path) {
1449        let hook = {
1450            let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
1451            hooks
1452                .iter()
1453                .position(|(hooked, _)| hooked == path)
1454                .map(|index| hooks.swap_remove(index).1)
1455        };
1456        if let Some(hook) = hook {
1457            hook();
1458        }
1459    }
1460}
1461
1462/// A path-scoped barrier after publication and before any configured activation.
1463/// The async wait leaves the listeners free to answer discovery-time requests.
1464#[cfg(test)]
1465mod startup_publication_hook {
1466    use std::{
1467        path::{Path, PathBuf},
1468        sync::{Mutex, PoisonError},
1469    };
1470    use tokio::sync::oneshot;
1471
1472    type Barrier = (oneshot::Sender<()>, oneshot::Receiver<()>);
1473    static BARRIERS: Mutex<Vec<(PathBuf, Barrier)>> = Mutex::new(Vec::new());
1474
1475    pub(super) fn install(path: &Path) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
1476        let (entered_tx, entered_rx) = oneshot::channel();
1477        let (release_tx, release_rx) = oneshot::channel();
1478        BARRIERS
1479            .lock()
1480            .unwrap_or_else(PoisonError::into_inner)
1481            .push((path.to_path_buf(), (entered_tx, release_rx)));
1482        (entered_rx, release_tx)
1483    }
1484
1485    pub(super) async fn run(path: &Path) {
1486        let barrier = {
1487            let mut barriers = BARRIERS.lock().unwrap_or_else(PoisonError::into_inner);
1488            barriers
1489                .iter()
1490                .position(|(hooked, _)| hooked == path)
1491                .map(|index| barriers.swap_remove(index).1)
1492        };
1493        if let Some((entered, release)) = barrier {
1494            let _ = entered.send(());
1495            let _ = release.await;
1496        }
1497    }
1498}
1499
1500fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
1501    match err {
1502        ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
1503        ConnectionFileError::JsonRead { .. }
1504        | ConnectionFileError::UnsupportedSchema { .. }
1505        | ConnectionFileError::Invalid { .. }
1506        | ConnectionFileError::KeyTooShort { .. }
1507        // A live daemon always publishes the file owner-only (0600), so a file
1508        // with insecure permissions is never a daemon we should defer to: treat it
1509        // as stale and take over (which republishes a correct 0600 file).
1510        | ConnectionFileError::InsecurePermissions { .. } => true,
1511        ConnectionFileError::MissingParent { .. }
1512        | ConnectionFileError::MissingFileName { .. }
1513        // A writable ancestor is an operator misconfiguration, never evidence
1514        // about whether a daemon is live. Reclaiming the file would republish key
1515        // material into the same directory the refusal is about.
1516        | ConnectionFileError::InsecureParentDirectory { .. }
1517        | ConnectionFileError::Io { .. }
1518        | ConnectionFileError::JsonWrite { .. }
1519        | ConnectionFileError::Random(_)
1520        // A wire mismatch may identify a newer live daemon, so never reclaim its
1521        // connection file merely because this binary cannot speak its envelope.
1522        | ConnectionFileError::WireVersionMismatch { .. } => false,
1523    }
1524}
1525
1526fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
1527    match fs::remove_file(path) {
1528        Ok(()) => Ok(()),
1529        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
1530        Err(source) => Err(BootstrapError::RemoveStale {
1531            path: path.to_path_buf(),
1532            source,
1533        }),
1534    }
1535}
1536
1537async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
1538    bind_loopback_with(port, |port| TcpListener::bind((Ipv6Addr::LOCALHOST, port))).await
1539}
1540
1541async fn bind_loopback_with<F, Fut>(
1542    port: u16,
1543    mut bind_v6: F,
1544) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError>
1545where
1546    F: FnMut(u16) -> Fut,
1547    Fut: std::future::Future<Output = io::Result<TcpListener>>,
1548{
1549    let v4_host = Ipv4Addr::LOCALHOST;
1550    let v4 = TcpListener::bind((v4_host, port))
1551        .await
1552        .map_err(|source| BootstrapError::Bind {
1553            host: v4_host.to_string(),
1554            port,
1555            source,
1556        })?;
1557    let actual_port = v4
1558        .local_addr()
1559        .map_err(|source| BootstrapError::LocalAddr {
1560            host: v4_host.to_string(),
1561            source,
1562        })?
1563        .port();
1564
1565    let mut listeners = vec![v4];
1566    let mut endpoints = vec![Endpoint {
1567        host: v4_host.to_string(),
1568        port: actual_port,
1569    }];
1570
1571    let v6_host = Ipv6Addr::LOCALHOST;
1572    match bind_v6(actual_port).await {
1573        Ok(v6) => {
1574            listeners.push(v6);
1575            endpoints.push(Endpoint {
1576                host: v6_host.to_string(),
1577                port: actual_port,
1578            });
1579        }
1580        Err(err)
1581            if ipv6_loopback_unavailable(&err)
1582                || (port == 0 && err.kind() == io::ErrorKind::AddrInUse) =>
1583        {
1584            warn!(
1585                port = actual_port,
1586                error = %err,
1587                "IPv6 loopback unavailable; serving only IPv4 loopback"
1588            );
1589        }
1590        Err(source) => {
1591            drop(listeners);
1592            return Err(BootstrapError::Bind {
1593                host: v6_host.to_string(),
1594                port: actual_port,
1595                source,
1596            });
1597        }
1598    }
1599
1600    Ok((listeners, endpoints))
1601}
1602
1603fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
1604    matches!(
1605        err.kind(),
1606        io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
1607    ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
1608}
1609
1610struct AbortOnDrop<T> {
1611    handle: JoinHandle<T>,
1612}
1613
1614impl<T> AbortOnDrop<T> {
1615    fn new(handle: JoinHandle<T>) -> Self {
1616        Self { handle }
1617    }
1618
1619    async fn join(&mut self) -> Result<T, JoinError> {
1620        (&mut self.handle).await
1621    }
1622}
1623
1624impl<T> Drop for AbortOnDrop<T> {
1625    fn drop(&mut self) {
1626        if !self.handle.is_finished() {
1627            self.handle.abort();
1628        }
1629    }
1630}
1631
1632#[derive(Debug)]
1633struct StartLock {
1634    // Keep the locked file handle alive for the duration of bootstrap.
1635    _file: fs::File,
1636}
1637
1638impl Drop for StartLock {
1639    fn drop(&mut self) {
1640        // Closing alone leaves the lock held if a concurrent fork inherited
1641        // the open file description and has not exec'd yet. Unlock explicitly
1642        // so a restart can reclaim the singleton as soon as bootstrap ends.
1643        if let Err(error) = FileExt::unlock(&self._file) {
1644            tracing::warn!(%error, "failed to release the singleton start lock");
1645        }
1646    }
1647}
1648
1649impl StartLock {
1650    async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
1651        let path = start_lock_path(connection_file_path);
1652        for _ in 0..START_LOCK_RETRIES {
1653            let file = match open_owner_only_lock(&path) {
1654                Ok(file) => file,
1655                Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
1656            };
1657            match FileExt::try_lock(&file) {
1658                Ok(()) => return Ok(Self { _file: file }),
1659                Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
1660                Err(TryLockError::Error(source)) => {
1661                    return Err(BootstrapError::StartLockCreate { path, source });
1662                }
1663            }
1664        }
1665
1666        Err(BootstrapError::StartLockBusy {
1667            path,
1668            attempts: START_LOCK_RETRIES,
1669        })
1670    }
1671}
1672
1673pub(crate) fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
1674    let mut options = fs::OpenOptions::new();
1675    options.read(true).write(true).create(true);
1676    #[cfg(unix)]
1677    {
1678        use std::os::unix::fs::OpenOptionsExt;
1679        options.mode(0o600);
1680    }
1681    options.open(path)
1682}
1683
1684fn start_lock_path(connection_file_path: &Path) -> PathBuf {
1685    let file_name = connection_file_path
1686        .file_name()
1687        .map(|name| name.to_string_lossy())
1688        .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
1689    let lock_name = format!("{file_name}.start-lock");
1690    connection_file_path
1691        .parent()
1692        .filter(|parent| !parent.as_os_str().is_empty())
1693        .unwrap_or_else(|| Path::new("."))
1694        .join(lock_name)
1695}
1696
1697fn non_empty_os_var(key: &str) -> Option<OsString> {
1698    let value = env::var_os(key)?;
1699    if value.is_empty() {
1700        None
1701    } else {
1702        Some(value)
1703    }
1704}
1705
1706/// Bootstrap-layer errors are deliberately typed so startup never panics for
1707/// ordinary daemon-discovery races or stale filesystem state.
1708#[derive(Debug)]
1709pub enum BootstrapError {
1710    /// The bound server could not authenticate its own readiness probe.
1711    StartupNotServing,
1712    #[cfg(unix)]
1713    Signal(io::Error),
1714    InvalidPort {
1715        raw: String,
1716        source: std::num::ParseIntError,
1717    },
1718    ConnectionFileRead {
1719        path: PathBuf,
1720        source: ConnectionFileError,
1721    },
1722    ConnectionFileWrite {
1723        path: PathBuf,
1724        source: ConnectionFileError,
1725    },
1726    GenerateConnectionFile(ConnectionFileError),
1727    StartLockCreate {
1728        path: PathBuf,
1729        source: io::Error,
1730    },
1731    StartLockBusy {
1732        path: PathBuf,
1733        attempts: usize,
1734    },
1735    /// The run-directory lock file could not be created, opened or locked.
1736    RunDirLockCreate {
1737        path: PathBuf,
1738        source: io::Error,
1739    },
1740    /// Another live process, almost certainly a daemon started with a
1741    /// different runtime directory over the same data home, owns the run
1742    /// directory. The daemon does not start. `holder_pid` is read from the
1743    /// lock file when possible and is informational only.
1744    RunDirBusy {
1745        path: PathBuf,
1746        holder_pid: Option<u32>,
1747    },
1748    RemoveStale {
1749        path: PathBuf,
1750        source: io::Error,
1751    },
1752    Bind {
1753        host: String,
1754        port: u16,
1755        source: io::Error,
1756    },
1757    LocalAddr {
1758        host: String,
1759        source: io::Error,
1760    },
1761    DaemonConfig(DaemonConfigError),
1762    /// The machine id could not be established: its file is corrupt, unreadable
1763    /// or unwritable, or the data home is relative. The daemon does not start.
1764    MachineId(crate::machine_id::MachineIdFileError),
1765    /// The daemon run directory could not be resolved because the data home is
1766    /// relative. The daemon does not start.
1767    RunDir(daemon_config::DaemonRunDirError),
1768    Serve(ServerError),
1769    ServeJoin(tokio::task::JoinError),
1770}
1771
1772impl fmt::Display for BootstrapError {
1773    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774        match self {
1775            Self::StartupNotServing => write!(f, "bound daemon did not authenticate its readiness probe; connection file was not published"),
1776            #[cfg(unix)]
1777            Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
1778            Self::InvalidPort { raw, source } => {
1779                write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
1780            }
1781            Self::ConnectionFileRead { path, source } => write!(
1782                f,
1783                "failed to read connection file {}: {source}",
1784                path.display()
1785            ),
1786            Self::ConnectionFileWrite { path, source } => write!(
1787                f,
1788                "failed to publish connection file {}: {source}",
1789                path.display()
1790            ),
1791            Self::GenerateConnectionFile(err) => {
1792                write!(f, "failed to generate connection-file auth material: {err}")
1793            }
1794            Self::StartLockCreate { path, source } => {
1795                write!(
1796                    f,
1797                    "failed to create start lock {}: {source}",
1798                    path.display()
1799                )
1800            }
1801            Self::StartLockBusy { path, attempts } => write!(
1802                f,
1803                "start lock {} remained busy after {attempts} attempts",
1804                path.display()
1805            ),
1806            Self::RunDirLockCreate { path, source } => write!(
1807                f,
1808                "refusing to start: failed to lock run directory via {}: {source}",
1809                path.display()
1810            ),
1811            Self::RunDirBusy { path, holder_pid } => {
1812                write!(
1813                    f,
1814                    "refusing to start: run directory lock {} is held by another daemon",
1815                    path.display()
1816                )?;
1817                if let Some(pid) = holder_pid {
1818                    write!(f, " (pid {pid})")?;
1819                }
1820                write!(
1821                    f,
1822                    "; a live daemon owns this data home's run state (typically one started with a different XDG_RUNTIME_DIR)"
1823                )
1824            }
1825            Self::RemoveStale { path, source } => write!(
1826                f,
1827                "failed to remove stale connection file {}: {source}",
1828                path.display()
1829            ),
1830            Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
1831                write!(
1832                    f,
1833                    "port {port} in use on loopback {host}: {source}; set the port in config"
1834                )
1835            }
1836            Self::Bind { host, port, source } => {
1837                write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
1838            }
1839            Self::LocalAddr { host, source } => {
1840                write!(f, "failed to read local address for {host}: {source}")
1841            }
1842            Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
1843            Self::MachineId(err) => write!(f, "refusing to start: {err}"),
1844            Self::RunDir(err) => write!(f, "refusing to start: {err}"),
1845            Self::Serve(err) => write!(f, "daemon server failed: {err}"),
1846            Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
1847        }
1848    }
1849}
1850
1851impl Error for BootstrapError {
1852    fn source(&self) -> Option<&(dyn Error + 'static)> {
1853        match self {
1854            Self::StartupNotServing => None,
1855            #[cfg(unix)]
1856            Self::Signal(source) => Some(source),
1857            Self::InvalidPort { source, .. } => Some(source),
1858            Self::ConnectionFileRead { source, .. }
1859            | Self::ConnectionFileWrite { source, .. }
1860            | Self::GenerateConnectionFile(source) => Some(source),
1861            Self::StartLockCreate { source, .. }
1862            | Self::RunDirLockCreate { source, .. }
1863            | Self::RemoveStale { source, .. }
1864            | Self::Bind { source, .. }
1865            | Self::LocalAddr { source, .. } => Some(source),
1866            Self::DaemonConfig(err) => Some(err),
1867            Self::MachineId(err) => Some(err),
1868            Self::RunDir(err) => Some(err),
1869            Self::Serve(err) => Some(err),
1870            Self::ServeJoin(err) => Some(err),
1871            Self::StartLockBusy { .. } | Self::RunDirBusy { .. } => None,
1872        }
1873    }
1874}
1875
1876#[cfg(test)]
1877mod tests {
1878    mod activity {
1879        include!("activity_bootstrap_tests.rs");
1880    }
1881    mod startup_order {
1882        include!("startup_order_tests.rs");
1883    }
1884    use super::*;
1885    use crate::server::ServerAuth;
1886    use cortexkit_test_support::ScratchDir;
1887    #[cfg(target_os = "linux")]
1888    use std::collections::BTreeSet;
1889    use std::sync::Mutex;
1890    #[cfg(target_os = "linux")]
1891    use subc_control::ModuleProtocol;
1892    use subc_transport::MIN_KEY_LEN;
1893    use tokio::io::AsyncReadExt;
1894    use tokio::task::JoinHandle;
1895
1896    #[cfg(unix)]
1897    use std::os::unix::fs::PermissionsExt;
1898
1899    static ENV_LOCK: Mutex<()> = Mutex::new(());
1900
1901    #[test]
1902    fn normalized_build_provenance_preserves_real_values() {
1903        assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
1904    }
1905
1906    #[test]
1907    fn normalized_build_provenance_omits_unavailable_and_empty_values() {
1908        assert_eq!(normalized_build_provenance("unavailable"), None);
1909        assert_eq!(normalized_build_provenance(""), None);
1910    }
1911
1912    #[cfg(target_os = "linux")]
1913    fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
1914        let cgroups = fs::read_to_string("/proc/self/cgroup")?;
1915        let relative = cgroups
1916            .lines()
1917            .find_map(|line| line.strip_prefix("0::"))
1918            .ok_or_else(|| {
1919                io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
1920            })?;
1921        Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
1922    }
1923
1924    #[cfg(target_os = "linux")]
1925    fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
1926        let modules = current_cgroup_path_for_test()?.join("subc-modules");
1927        let entries = match fs::read_dir(modules) {
1928            Ok(entries) => entries,
1929            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
1930            Err(error) => return Err(error),
1931        };
1932        let mut directories = BTreeSet::new();
1933        for entry in entries {
1934            let entry = entry?;
1935            if entry.file_type()?.is_dir() {
1936                directories.insert(entry.file_name());
1937            }
1938        }
1939        Ok(directories)
1940    }
1941
1942    #[cfg(target_os = "linux")]
1943    async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
1944        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1945        while !path.exists() && tokio::time::Instant::now() < deadline {
1946            assert!(
1947                !task.is_finished(),
1948                "daemon exited before creating {}",
1949                path.display()
1950            );
1951            sleep(Duration::from_millis(10)).await;
1952        }
1953        assert!(path.exists(), "daemon did not create {}", path.display());
1954    }
1955
1956    /// An in-process daemon with the default (disabled) cgroup placement must
1957    /// leave the host's live module cgroup tree exactly as it found it.
1958    /// Red-checking this test (making it fail) creates a
1959    /// `cgroup-isolation-probe-*` directory in the live cgroup tree, which must be removed by hand.
1960    #[cfg(target_os = "linux")]
1961    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1962    async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
1963        let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
1964        let module_id = format!("cgroup-isolation-probe-{}", process::id());
1965        let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
1966        assert!(
1967            !before.contains(&OsString::from(&module_id)),
1968            "isolation probe cgroup already exists before this daemon starts"
1969        );
1970        let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
1971        let module = ConfiguredModule {
1972            module_id,
1973            program: PathBuf::from("sh"),
1974            args: vec!["-c".to_string(), "sleep 30".to_string()],
1975            env: Vec::new(),
1976            log: None,
1977            enabled: true,
1978            reserved: false,
1979            reserved_prefixes: Vec::new(),
1980            protocol: ModuleProtocol::None,
1981            overlap: Default::default(),
1982            health: HealthConfig::default(),
1983            drain_timeout_ms: None,
1984            route_bind_relay_timeout_ms: None,
1985            restart: RestartPolicy::default(),
1986        };
1987        let config = BootstrapConfig::new(temp.join("connection.json"), 0)
1988            .with_configured_modules([module])
1989            .with_capture_logs_dir(temp.join("logs"))
1990            .with_terminal_journal_path(temp.join("terminals.jsonl"));
1991        let task = tokio::spawn(run_with_config(config));
1992
1993        wait_for_path(&capture, &task).await;
1994        let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
1995
1996        task.abort();
1997        assert!(task
1998            .await
1999            .expect_err("aborted daemon task must cancel")
2000            .is_cancelled());
2001        assert_eq!(
2002            before, after,
2003            "an in-process daemon must not create or reconcile ambient module cgroups"
2004        );
2005    }
2006
2007    #[cfg(target_os = "linux")]
2008    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2009    async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
2010        let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
2011        let cgroup_root = temp.join("cgroup");
2012        fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
2013        fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
2014        let modules = cgroup_root.join("subc-modules");
2015        let config = BootstrapConfig::new(temp.join("connection.json"), 0)
2016            .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
2017            .with_terminal_journal_path(temp.join("terminals.jsonl"));
2018        let task = tokio::spawn(run_with_config(config));
2019
2020        wait_for_path(&modules, &task).await;
2021
2022        task.abort();
2023        assert!(task
2024            .await
2025            .expect_err("aborted daemon task must cancel")
2026            .is_cancelled());
2027        assert!(
2028            fs::read_dir(&modules)
2029                .expect("read prepared modules directory")
2030                .next()
2031                .is_none(),
2032            "the delegation probe must clean up after itself"
2033        );
2034    }
2035
2036    struct EnvGuard {
2037        key: &'static str,
2038        previous: Option<OsString>,
2039    }
2040
2041    impl EnvGuard {
2042        fn set(key: &'static str, value: &Path) -> Self {
2043            let previous = env::var_os(key);
2044            env::set_var(key, value);
2045            Self { key, previous }
2046        }
2047
2048        fn set_str(key: &'static str, value: &str) -> Self {
2049            let previous = env::var_os(key);
2050            env::set_var(key, value);
2051            Self { key, previous }
2052        }
2053
2054        fn unset(key: &'static str) -> Self {
2055            let previous = env::var_os(key);
2056            env::remove_var(key);
2057            Self { key, previous }
2058        }
2059    }
2060
2061    impl Drop for EnvGuard {
2062        fn drop(&mut self) {
2063            match &self.previous {
2064                Some(value) => env::set_var(self.key, value),
2065                None => env::remove_var(self.key),
2066            }
2067        }
2068    }
2069
2070    fn unique_temp_dir(name: &str) -> ScratchDir {
2071        ScratchDir::new(name)
2072    }
2073
2074    fn temp_connection_file_path(name: &str) -> (ScratchDir, PathBuf) {
2075        let dir = unique_temp_dir(name);
2076        let path = dir.join("conn.json");
2077        (dir, path)
2078    }
2079
2080    fn auth_for(info: &ConnectionInfo) -> ServerAuth {
2081        ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
2082    }
2083
2084    fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
2085        let auth = auth_for(&bound.connection_info);
2086        tokio::spawn(serve_listeners(
2087            bound.listeners,
2088            Arc::new(Router::with_default_self_handler()),
2089            auth,
2090        ))
2091    }
2092
2093    fn expect_bound(outcome: Outcome) -> BoundDaemon {
2094        match outcome {
2095            Outcome::Bound(bound) => bound,
2096            Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
2097        }
2098    }
2099
2100    async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
2101        let endpoint = conn
2102            .endpoints
2103            .first()
2104            .expect("test connection file should have an endpoint");
2105        let ip: IpAddr = endpoint.host.parse().unwrap();
2106        TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
2107    }
2108
2109    fn make_connection_info(port: u16) -> ConnectionInfo {
2110        ConnectionInfo {
2111            schema: SCHEMA_VERSION,
2112            wire_version: Some(PROTOCOL_VERSION),
2113            endpoints: vec![Endpoint {
2114                host: "127.0.0.1".to_owned(),
2115                port,
2116            }],
2117            key: generate_key().unwrap(),
2118            daemon_id: generate_daemon_id().unwrap(),
2119            pid: process::id(),
2120            daemon_ver: "test-subc".to_owned(),
2121        }
2122    }
2123
2124    fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
2125        fs::write(path, contents).unwrap();
2126        #[cfg(unix)]
2127        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
2128    }
2129
2130    fn assert_owner_only_connection_file(path: &Path) {
2131        // `path` is only inspected on Unix (mode bits); on Windows the owner-only
2132        // guarantee comes from the inherited %TEMP% ACL, nothing to assert here.
2133        #[cfg(unix)]
2134        {
2135            let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
2136            assert_eq!(mode, 0o600);
2137        }
2138        #[cfg(not(unix))]
2139        let _ = path;
2140    }
2141
2142    #[test]
2143    fn connection_file_path_uses_xdg_runtime_dir_when_set() {
2144        let _env_lock = ENV_LOCK.lock().unwrap();
2145        let runtime_dir = unique_temp_dir("xdg-runtime");
2146        let _xdg = EnvGuard::set("XDG_RUNTIME_DIR", runtime_dir.path());
2147
2148        assert_eq!(
2149            connection_file_path(),
2150            runtime_dir.join(CONNECTION_FILE_NAME)
2151        );
2152    }
2153
2154    #[test]
2155    fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
2156        let runtime_dir = OsString::from("/run/user/1000");
2157
2158        let (path, source) = connection_file_path_with_source(Some(runtime_dir));
2159
2160        assert_eq!(
2161            path,
2162            PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
2163        );
2164        assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
2165    }
2166
2167    #[test]
2168    fn connection_file_path_falls_back_to_temp_dir_with_user_token_when_xdg_unset() {
2169        let _env_lock = ENV_LOCK.lock().unwrap();
2170        let _xdg = EnvGuard::unset("XDG_RUNTIME_DIR");
2171
2172        assert_eq!(
2173            connection_file_path(),
2174            env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2175        );
2176    }
2177
2178    #[test]
2179    fn connection_file_path_source_is_temp_dir_when_xdg_unset() {
2180        let (path, source) = connection_file_path_with_source(None);
2181
2182        assert_eq!(
2183            path,
2184            env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2185        );
2186        assert_eq!(source, ConnectionFileSource::TempDirFallback);
2187    }
2188
2189    /// Concurrent callers must derive one token. The former temp-file uid probe
2190    /// could fail transiently (same-tick name collision, fd exhaustion) and send
2191    /// the loser down the env-derived fallback with a different identity for the
2192    /// same user; this fence keeps identity independent of filesystem luck.
2193    #[test]
2194    fn user_connection_token_is_stable_under_concurrent_callers() {
2195        let expected = user_connection_token();
2196        let workers: Vec<_> = (0..32)
2197            .map(|_| {
2198                std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
2199            })
2200            .collect();
2201        for worker in workers {
2202            for token in worker.join().expect("probe thread") {
2203                assert_eq!(token, expected, "token diverged under concurrent probes");
2204            }
2205        }
2206    }
2207
2208    #[test]
2209    fn connection_file_path_source_is_temp_dir_when_xdg_empty() {
2210        let (path, source) = connection_file_path_with_source(Some(OsString::new()));
2211
2212        assert_eq!(
2213            path,
2214            env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2215        );
2216        assert_eq!(source, ConnectionFileSource::TempDirFallback);
2217    }
2218
2219    /// The shipped binary is the only caller that journals terminal exits into
2220    /// the real run directory, so its constructor must supply that path itself;
2221    /// the in-process default leaves it unset.
2222    #[test]
2223    fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
2224        let _env_lock = ENV_LOCK.lock().unwrap();
2225        let root = unique_temp_dir("daemon-binary-config");
2226        let data_home = root.join("data");
2227        let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
2228        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
2229        let _port = EnvGuard::unset(SUBC_PORT_ENV);
2230
2231        let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
2232
2233        let run_dir = data_home.join("cortexkit").join("run");
2234        assert_eq!(
2235            config.terminal_journal_path,
2236            Some(run_dir.join("terminals.jsonl"))
2237        );
2238        assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
2239        assert_eq!(
2240            BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
2241            None,
2242            "an in-process config must not journal anywhere unless asked to"
2243        );
2244    }
2245
2246    #[test]
2247    fn daemon_binary_config_refuses_a_relative_data_home() {
2248        let _env_lock = ENV_LOCK.lock().unwrap();
2249        let root = unique_temp_dir("daemon-binary-relative-data");
2250        let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
2251        let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
2252        let _port = EnvGuard::unset(SUBC_PORT_ENV);
2253
2254        let error = BootstrapConfig::from_env_for_daemon_binary()
2255            .expect_err("a relative data home must refuse the daemon binary's config");
2256        assert!(
2257            matches!(error, BootstrapError::RunDir(_)),
2258            "expected a run-directory refusal, got {error}"
2259        );
2260        assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
2261    }
2262
2263    #[test]
2264    fn privileged_operator_prompt_is_loaded_by_both_bootstrap_config_paths() {
2265        let _env_lock = ENV_LOCK.lock().unwrap();
2266        let _port = EnvGuard::unset(SUBC_PORT_ENV);
2267        let (_dir, conn_path) = temp_connection_file_path("privileged-operator-prompt");
2268        let config_path = conn_path.with_file_name("subc.jsonc");
2269        for (doc, expected) in [
2270            (None, daemon_config::PrivilegedOperatorPrompt::Log),
2271            (
2272                Some(r#"{"version":1}"#),
2273                daemon_config::PrivilegedOperatorPrompt::Log,
2274            ),
2275            (
2276                Some(r#"{"version":1,"privileged_operator_prompt":"log"}"#),
2277                daemon_config::PrivilegedOperatorPrompt::Log,
2278            ),
2279            (
2280                Some(r#"{"version":1,"privileged_operator_prompt":"enforce"}"#),
2281                daemon_config::PrivilegedOperatorPrompt::Enforce,
2282            ),
2283        ] {
2284            if let Some(doc) = doc {
2285                fs::write(&config_path, doc).unwrap();
2286            }
2287            assert_eq!(
2288                BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2289                    .unwrap()
2290                    .privileged_operator_prompt,
2291                expected
2292            );
2293            assert_eq!(
2294                BootstrapConfig::new(&conn_path, 0)
2295                    .with_daemon_config_path(&config_path)
2296                    .unwrap()
2297                    .privileged_operator_prompt,
2298                expected
2299            );
2300        }
2301    }
2302
2303    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2304    async fn privileged_operator_prompt_is_snapshotted_by_running_daemon() {
2305        let dir = unique_temp_dir("privileged-operator-prompt-bootstrap");
2306        let connection_path = dir.join("connection.json");
2307        let config_path = dir.join("subc.jsonc");
2308        fs::write(
2309            &config_path,
2310            r#"{"version":1,"privileged_operator_prompt":"enforce"}"#,
2311        )
2312        .unwrap();
2313        let config = BootstrapConfig::new(&connection_path, 0)
2314            .with_daemon_config_path(&config_path)
2315            .unwrap();
2316        let daemon = AbortOnDrop::new(tokio::spawn(run_with_config(config)));
2317        tokio::time::timeout(Duration::from_secs(5), async {
2318            while !connection_path.exists() {
2319                assert!(
2320                    !daemon.handle.is_finished(),
2321                    "daemon exited before publishing"
2322                );
2323                tokio::task::yield_now().await;
2324            }
2325        })
2326        .await
2327        .unwrap();
2328        let info = connection_file::read(&connection_path).unwrap();
2329        let mut client = connect_from_info(&info).await.unwrap();
2330        authenticate_client(&mut client, &info, Duration::from_secs(5))
2331            .await
2332            .unwrap();
2333        for (correlation, mode, expected) in [
2334            (1, "enforce", Vec::new()),
2335            (2, "log", vec!["privileged_operator_prompt"]),
2336            (3, "log", vec!["privileged_operator_prompt"]),
2337        ] {
2338            fs::write(
2339                &config_path,
2340                serde_json::json!({"version":1,"privileged_operator_prompt":mode}).to_string(),
2341            )
2342            .unwrap();
2343            let frame = crate::Frame::build(
2344                subc_protocol::FrameType::Request,
2345                subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
2346                0,
2347                0,
2348                correlation,
2349                serde_json::to_vec(&subc_control::ClientControlRequest::SupervisorRescan {
2350                    preview: true,
2351                })
2352                .unwrap(),
2353            )
2354            .unwrap();
2355            crate::write_frame(&mut client, &frame).await.unwrap();
2356            let reply =
2357                tokio::time::timeout(Duration::from_secs(5), crate::read_frame(&mut client))
2358                    .await
2359                    .unwrap()
2360                    .unwrap()
2361                    .unwrap();
2362            assert_eq!(reply.header.ty, subc_protocol::FrameType::Response);
2363            assert_eq!(reply.header.corr, correlation);
2364            let subc_control::ClientControlResponse::SupervisorRescan { result } =
2365                serde_json::from_slice(&reply.body).unwrap()
2366            else {
2367                panic!("expected a rescan response");
2368            };
2369            assert_eq!(result.restart_required, expected);
2370        }
2371    }
2372
2373    #[test]
2374    fn configured_port_uses_default_config_and_env_override() {
2375        let _env_lock = ENV_LOCK.lock().unwrap();
2376        let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
2377        let config_path = conn_path.with_file_name("subc.jsonc");
2378
2379        let _port = EnvGuard::unset(SUBC_PORT_ENV);
2380        assert_eq!(
2381            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2382                .unwrap()
2383                .port,
2384            DEFAULT_SUBC_PORT
2385        );
2386
2387        fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
2388        assert_eq!(
2389            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2390                .unwrap()
2391                .port,
2392            8123
2393        );
2394
2395        let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
2396        assert_eq!(
2397            BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2398                .unwrap()
2399                .port,
2400            9012
2401        );
2402    }
2403
2404    #[tokio::test]
2405    async fn singleton_does_not_accept_a_peer_that_answers_once_then_exits() {
2406        let (_dir, path) = temp_connection_file_path("departing-peer");
2407        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2408        let info = make_connection_info(listener.local_addr().unwrap().port());
2409        write_connection_file(&path, &info).unwrap();
2410        let peer = tokio::spawn(async move {
2411            let (mut stream, _) = listener.accept().await.unwrap();
2412            subc_transport::authenticate_server(
2413                &mut stream,
2414                &info.key,
2415                &info.daemon_id,
2416                &info.daemon_ver,
2417                PROBE_AUTH_DEADLINE,
2418            )
2419            .await
2420            .unwrap();
2421        });
2422        let outcome = ensure_singleton(&path, 0).await.unwrap();
2423        peer.await.unwrap();
2424        assert!(
2425            matches!(outcome, Outcome::Bound(_)),
2426            "a departing peer is not AlreadyRunning"
2427        );
2428    }
2429
2430    #[tokio::test]
2431    async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
2432        let (_dir, path) = temp_connection_file_path("already-running");
2433
2434        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2435        let server = start_server(bound);
2436
2437        let second = ensure_singleton(&path, 0).await.unwrap();
2438        assert!(matches!(second, Outcome::AlreadyRunning));
2439
2440        server.abort();
2441        let _ = server.await;
2442    }
2443
2444    #[tokio::test]
2445    async fn daemon_connection_file_publishes_protocol_wire_version() {
2446        let (_dir, path) = temp_connection_file_path("wire-version");
2447        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2448        assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
2449        assert_eq!(
2450            connection_file::read(&path).unwrap().wire_version,
2451            Some(PROTOCOL_VERSION)
2452        );
2453
2454        drop(bound.listeners);
2455    }
2456
2457    #[tokio::test]
2458    async fn stale_unbound_connection_file_is_reclaimed() {
2459        let (_dir, path) = temp_connection_file_path("stale-reclaim");
2460        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2461        let stale_port = stale.local_addr().unwrap().port();
2462        drop(stale);
2463        let stale_info = make_connection_info(stale_port);
2464        write_atomic(&path, &stale_info).unwrap();
2465
2466        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2467        assert_ne!(bound.connection_info.key, stale_info.key);
2468        drop(bound.listeners);
2469    }
2470
2471    #[cfg(unix)]
2472    #[tokio::test]
2473    async fn ensure_singleton_reclaims_insecure_connection_file() {
2474        let (_dir, path) = temp_connection_file_path("insecure-reclaim");
2475        let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2476        let stale_port = stale.local_addr().unwrap().port();
2477        drop(stale);
2478        let stale_info = make_connection_info(stale_port);
2479        write_atomic(&path, &stale_info).unwrap();
2480        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
2481
2482        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2483        assert_ne!(bound.connection_info.key, stale_info.key);
2484        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
2485        assert_owner_only_connection_file(&path);
2486
2487        drop(bound.listeners);
2488    }
2489
2490    #[tokio::test]
2491    async fn ensure_singleton_reclaims_non_loopback_connection_file() {
2492        let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
2493        let mut stale_info = make_connection_info(8757);
2494        stale_info.endpoints = vec![Endpoint {
2495            host: "192.0.2.10".to_owned(),
2496            port: 8757,
2497        }];
2498        write_atomic(&path, &stale_info).unwrap();
2499
2500        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2501        assert_ne!(bound.connection_info.key, stale_info.key);
2502        assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
2503        assert!(bound
2504            .connection_info
2505            .endpoints
2506            .iter()
2507            .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
2508        assert_owner_only_connection_file(&path);
2509
2510        drop(bound.listeners);
2511    }
2512
2513    #[tokio::test]
2514    async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
2515        let mut unsupported_schema = make_connection_info(8757);
2516        unsupported_schema.schema = SCHEMA_VERSION + 1;
2517
2518        let mut empty_endpoints = make_connection_info(8757);
2519        empty_endpoints.endpoints.clear();
2520
2521        let mut short_key = make_connection_info(8757);
2522        short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
2523
2524        let cases = vec![
2525            (
2526                "unsupported-schema",
2527                serde_json::to_vec(&unsupported_schema).unwrap(),
2528                Some(unsupported_schema),
2529            ),
2530            (
2531                "empty-endpoints",
2532                serde_json::to_vec(&empty_endpoints).unwrap(),
2533                Some(empty_endpoints),
2534            ),
2535            (
2536                "short-key",
2537                serde_json::to_vec(&short_key).unwrap(),
2538                Some(short_key),
2539            ),
2540            ("invalid-json", b"{not valid connection json".to_vec(), None),
2541        ];
2542
2543        for (label, contents, old_info) in cases {
2544            let (_dir, path) = temp_connection_file_path(label);
2545            write_raw_owner_only_connection_file(&path, &contents);
2546
2547            let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2548            if let Some(old_info) = old_info {
2549                assert_ne!(bound.connection_info.key, old_info.key, "{label}");
2550                assert_ne!(
2551                    bound.connection_info.daemon_id, old_info.daemon_id,
2552                    "{label}"
2553                );
2554            }
2555            assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
2556            assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
2557            assert_owner_only_connection_file(&path);
2558
2559            drop(bound.listeners);
2560        }
2561    }
2562
2563    #[tokio::test]
2564    async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
2565        let (_dir, path) = temp_connection_file_path("foreign-reclaim");
2566        let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2567        let foreign_port = foreign.local_addr().unwrap().port();
2568        write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
2569        let foreign_task = tokio::spawn(async move {
2570            if let Ok((mut stream, _)) = foreign.accept().await {
2571                let mut buf = [0u8; 64];
2572                let _ = stream.read(&mut buf).await;
2573            }
2574        });
2575
2576        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2577        assert!(bound
2578            .connection_info
2579            .endpoints
2580            .iter()
2581            .all(|endpoint| endpoint.port != foreign_port));
2582
2583        drop(bound.listeners);
2584        let _ = foreign_task.await;
2585    }
2586
2587    #[tokio::test]
2588    async fn stale_start_lock_file_is_reclaimable() {
2589        let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
2590        let lock_path = start_lock_path(&path);
2591        drop(open_owner_only_lock(&lock_path).unwrap());
2592        assert!(lock_path.is_file());
2593
2594        let lock = StartLock::acquire(&path).await.unwrap();
2595        assert!(lock_path.is_file());
2596
2597        drop(lock);
2598        assert!(lock_path.is_file());
2599    }
2600
2601    #[tokio::test]
2602    async fn held_start_lock_blocks_second_acquire_until_release() {
2603        let (_dir, path) = temp_connection_file_path("start-lock-held");
2604        let lock_path = start_lock_path(&path);
2605        let first = StartLock::acquire(&path).await.unwrap();
2606
2607        let err = match StartLock::acquire(&path).await {
2608            Ok(_) => panic!("second acquire while held must stay busy"),
2609            Err(err) => err,
2610        };
2611        assert!(matches!(
2612            err,
2613            BootstrapError::StartLockBusy {
2614                ref path,
2615                attempts: START_LOCK_RETRIES,
2616            } if path == &lock_path
2617        ));
2618
2619        drop(first);
2620
2621        let second = StartLock::acquire(&path)
2622            .await
2623            .expect("released advisory lock should be reclaimable");
2624        drop(second);
2625    }
2626
2627    #[tokio::test]
2628    async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
2629        let (_dir, path) = temp_connection_file_path("bind-conflict");
2630        let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2631        let occupied_port = occupied.local_addr().unwrap().port();
2632
2633        let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
2634        assert!(matches!(
2635            err,
2636            BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
2637        ));
2638        assert!(err.to_string().contains("set the port in config"));
2639
2640        drop(occupied);
2641    }
2642
2643    #[tokio::test]
2644    async fn ephemeral_ipv6_collision_still_serves_ipv4() {
2645        let (listeners, endpoints) = bind_loopback_with(0, |port| async move {
2646            let occupied = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await?;
2647            let result = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await;
2648            drop(occupied);
2649            result
2650        })
2651        .await
2652        .expect("an incidental IPv6 collision must not prevent an ephemeral daemon from starting");
2653        assert_eq!(endpoints.len(), 1);
2654        assert_eq!(endpoints[0].host, "127.0.0.1");
2655        TcpStream::connect((Ipv4Addr::LOCALHOST, endpoints[0].port))
2656            .await
2657            .unwrap();
2658        drop(listeners);
2659    }
2660
2661    #[tokio::test]
2662    async fn unpublished_boot_holds_singleton_lock_until_publication() {
2663        let dir = ScratchDir::new("unpublished-singleton-lock");
2664        let path = dir.join("connection.json");
2665        let bound = expect_bound(
2666            ensure_singleton_inner(BootstrapConfig::new(&path, 0), false)
2667                .await
2668                .unwrap(),
2669        );
2670        assert!(!path.exists());
2671        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
2672        assert!(
2673            matches!(FileExt::try_lock(&contender), Err(TryLockError::WouldBlock)),
2674            "an unpublished boot must keep its singleton claim"
2675        );
2676        drop(bound);
2677        FileExt::try_lock(&contender).unwrap();
2678    }
2679
2680    #[tokio::test]
2681    async fn start_lock_drop_releases_claim_with_a_shared_file_description() {
2682        let dir = ScratchDir::new("shared-singleton-lock");
2683        let path = dir.join("connection.json");
2684        let bound = expect_bound(
2685            ensure_singleton_inner(BootstrapConfig::new(&path, 0), false)
2686                .await
2687                .unwrap(),
2688        );
2689        // try_clone shares the open file description just as fork does,
2690        // without relying on the timing of another test's child spawn.
2691        let inherited = bound
2692            .publication_lock
2693            .as_ref()
2694            .unwrap()
2695            ._file
2696            .try_clone()
2697            .unwrap();
2698        let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
2699        assert!(matches!(
2700            FileExt::try_lock(&contender),
2701            Err(TryLockError::WouldBlock)
2702        ));
2703        drop(bound);
2704        FileExt::try_lock(&contender).expect("dropping bootstrap releases even an inherited lock");
2705        drop(inherited);
2706    }
2707
2708    #[tokio::test]
2709    async fn readiness_probe_requires_an_authenticating_server() {
2710        let dir = ScratchDir::new("unserved-readiness");
2711        let bound = expect_bound(
2712            ensure_singleton_inner(BootstrapConfig::new(dir.join("connection.json"), 0), false)
2713                .await
2714                .unwrap(),
2715        );
2716        assert!(matches!(
2717            verify_serving(&bound.connection_info).await,
2718            Err(BootstrapError::StartupNotServing)
2719        ));
2720    }
2721
2722    #[cfg(unix)]
2723    #[tokio::test]
2724    async fn orphan_sweep_finishes_before_connection_file_publication() {
2725        use crate::live_children::{ExecutableIdentity, LiveChild};
2726        let dir = ScratchDir::new("publish-after-sweep");
2727        let path = dir.join("connection.json");
2728        let record = dir.join("live-children.json");
2729        let ready = dir.join("ready");
2730        let mut child = std::process::Command::new("/bin/sh")
2731            .args([
2732                "-c",
2733                "trap '' TERM; : > \"$0\"; read -r _",
2734                ready.to_str().unwrap(),
2735            ])
2736            .stdin(std::process::Stdio::piped())
2737            .env("XDG_DATA_HOME", dir.path())
2738            .env("XDG_RUNTIME_DIR", dir.path())
2739            .env("XDG_CONFIG_HOME", dir.path())
2740            .spawn()
2741            .unwrap();
2742        timeout(Duration::from_secs(5), async {
2743            while !ready.exists() {
2744                sleep(Duration::from_millis(5)).await;
2745            }
2746        })
2747        .await
2748        .unwrap();
2749        let observed = subc_os::Process::open(child.id())
2750            .unwrap()
2751            .unwrap()
2752            .observe()
2753            .unwrap();
2754        crate::live_children::write_record(
2755            &record,
2756            &[LiveChild {
2757                module_id: "old-sleep".into(),
2758                pid: child.id(),
2759                protocol: subc_control::ModuleProtocol::None,
2760                start_time: Some(observed.start_time),
2761                executable: observed.executable.map(ExecutableIdentity::from),
2762                cgroup_name: None,
2763            }],
2764        )
2765        .unwrap();
2766        let config = BootstrapConfig::new(&path, 0).with_live_children_record(&record);
2767        let daemon = tokio::spawn(run_with_config(config));
2768        timeout(Duration::from_secs(5), async {
2769            while !path.exists() {
2770                sleep(Duration::from_millis(5)).await;
2771            }
2772        })
2773        .await
2774        .unwrap();
2775        assert!(path.exists());
2776        let ended = child.try_wait().unwrap().is_some();
2777        if !ended {
2778            child.kill().unwrap();
2779        }
2780        child.wait().unwrap();
2781        if ended {
2782            assert!(matches!(probe_existing(&path).await.unwrap(), Probe::Live));
2783        }
2784        daemon.abort();
2785        let _ = daemon.await;
2786        assert!(
2787            ended,
2788            "the published daemon must not still owe its orphan sweep"
2789        );
2790    }
2791
2792    /// Publishing the connection file fsyncs, which can take seconds on a busy
2793    /// disk, so the daemon must do it off the async worker thread. The hook
2794    /// blocks inside the write until another task on the same single-threaded
2795    /// runtime has run. Writing on the worker thread would starve that task: the
2796    /// hook then gives up after its deadline and the test fails, as it does if
2797    /// startup publishes without going through the hooked write at all.
2798    #[tokio::test(flavor = "current_thread")]
2799    async fn connection_file_publication_leaves_the_async_runtime_free() {
2800        use std::sync::atomic::{AtomicBool, Ordering};
2801
2802        let (_dir, path) = temp_connection_file_path("publish-off-runtime");
2803        let write_started = Arc::new(AtomicBool::new(false));
2804        let (progress_tx, progress_rx) = std::sync::mpsc::channel::<()>();
2805        let (verdict_tx, verdict_rx) = std::sync::mpsc::channel::<bool>();
2806        let hook_started = Arc::clone(&write_started);
2807        connection_file_write_hook::install(&path, move || {
2808            hook_started.store(true, Ordering::SeqCst);
2809            let progressed = progress_rx.recv_timeout(Duration::from_secs(5)).is_ok();
2810            let _ = verdict_tx.send(progressed);
2811        });
2812        // Signals only after the write has started, so a message can only come
2813        // from this task running while the write is still blocked.
2814        let ticker = tokio::spawn(async move {
2815            loop {
2816                if write_started.load(Ordering::SeqCst) {
2817                    let _ = progress_tx.send(());
2818                    return;
2819                }
2820                sleep(Duration::from_millis(5)).await;
2821            }
2822        });
2823
2824        let daemon = tokio::spawn(run_with_config(BootstrapConfig::new(&path, 0)));
2825        let published = timeout(Duration::from_secs(15), async {
2826            while !path.exists() && !daemon.is_finished() {
2827                sleep(Duration::from_millis(5)).await;
2828            }
2829        })
2830        .await;
2831        let daemon_exited = daemon.is_finished();
2832        daemon.abort();
2833        let daemon_result = daemon.await;
2834        ticker.abort();
2835
2836        assert!(
2837            published.is_ok() && !daemon_exited,
2838            "the daemon must start and publish its connection file: {daemon_result:?}"
2839        );
2840        match verdict_rx.try_recv() {
2841            Ok(true) => {}
2842            Ok(false) => panic!(
2843                "no other task on the runtime ran while the connection file was being written: the write is blocking the async worker thread"
2844            ),
2845            Err(_) => panic!("startup published the connection file without the hooked write"),
2846        }
2847    }
2848
2849    /// A write that never reports back must stop startup with an error naming
2850    /// the connection file, never be taken as published.
2851    #[tokio::test]
2852    async fn a_panicking_connection_file_write_fails_startup() {
2853        let (_dir, path) = temp_connection_file_path("publish-panics");
2854        connection_file_write_hook::install(&path, || {
2855            panic!("deliberate panic inside the connection-file write")
2856        });
2857
2858        let error = timeout(
2859            Duration::from_secs(15),
2860            run_with_config(BootstrapConfig::new(&path, 0)),
2861        )
2862        .await
2863        .expect("startup must end once the write task fails")
2864        .expect_err("startup must fail when the connection-file write panics");
2865
2866        assert!(
2867            matches!(&error, BootstrapError::ConnectionFileWrite { path: failed, .. } if failed == &path),
2868            "expected a connection-file write error, got {error:?}"
2869        );
2870        let message = error.to_string();
2871        assert!(message.contains(&path.display().to_string()), "{message}");
2872        assert!(message.contains("panicked"), "{message}");
2873        assert!(!path.exists(), "no connection file may be published");
2874    }
2875
2876    #[cfg(target_os = "macos")]
2877    #[test]
2878    fn nofile_raise_worker() {
2879        let Some(path) = std::env::var_os("SUBC_NOFILE_TEST_FILE") else {
2880            return;
2881        };
2882        let (_, hard) = rlimit::Resource::NOFILE.get().unwrap();
2883        rlimit::Resource::NOFILE.set(256, hard).unwrap();
2884        raise_nofile_limit_with_ceiling(Some(10240));
2885        std::fs::write(path, rlimit::Resource::NOFILE.get().unwrap().0.to_string()).unwrap();
2886    }
2887
2888    #[cfg(target_os = "macos")]
2889    #[test]
2890    fn macos_nofile_raise_clamps_to_kernel_ceiling() {
2891        let dir = ScratchDir::new("nofile-ceiling");
2892        let result = dir.join("soft");
2893        let status = std::process::Command::new(std::env::current_exe().unwrap())
2894            .args(["--exact", "bootstrap::tests::nofile_raise_worker"])
2895            .env("SUBC_NOFILE_TEST_FILE", &result)
2896            .env("XDG_DATA_HOME", dir.path())
2897            .env("XDG_RUNTIME_DIR", dir.path())
2898            .env("XDG_CONFIG_HOME", dir.path())
2899            .status()
2900            .unwrap();
2901        assert!(status.success());
2902        let soft: u64 = std::fs::read_to_string(result).unwrap().parse().unwrap();
2903        assert!(
2904            soft > 256 && soft <= 10240,
2905            "the inherited limit must be raised within the kernel ceiling; got {soft}"
2906        );
2907    }
2908
2909    #[tokio::test]
2910    async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
2911        let (_dir, path) = temp_connection_file_path("key-rotation");
2912        let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2913        let old_info = first.connection_info.clone();
2914        let fixed_port = old_info.endpoints[0].port;
2915        drop(first.listeners);
2916
2917        let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
2918        let new_info = second.connection_info.clone();
2919        assert_ne!(old_info.key, new_info.key);
2920        assert_ne!(old_info.daemon_id, new_info.daemon_id);
2921        let server = start_server(second);
2922
2923        let mut old_stream = connect_from_info(&old_info).await.unwrap();
2924        let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
2925        assert!(
2926            old_auth.is_err(),
2927            "old key must not authenticate after restart"
2928        );
2929
2930        let reread = connection_file::read(&path).unwrap();
2931        let mut new_stream = connect_from_info(&reread).await.unwrap();
2932        authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
2933            .await
2934            .unwrap();
2935
2936        server.abort();
2937        let _ = server.await;
2938    }
2939
2940    #[cfg(unix)]
2941    #[tokio::test]
2942    async fn published_connection_file_permissions_are_owner_only() {
2943        let (_dir, path) = temp_connection_file_path("permissions");
2944        let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2945
2946        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2947        assert_eq!(mode, 0o600);
2948
2949        drop(bound.listeners);
2950    }
2951}