Skip to main content

subc_daemon/bootstrap/
resume.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    fs::{self, File},
4    io::{self, Read},
5    os::{
6        fd::{AsFd, RawFd},
7        unix::fs::MetadataExt,
8    },
9    time::{Duration, Instant, SystemTime},
10};
11
12use rustix::{
13    fs::{self as rfs, FileType, Mode, OFlags},
14    io::{fcntl_setfd, FdFlags},
15};
16use sha2::{Digest, Sha256};
17use subc_os::child_spawn::{monotonic_ns, InheritedDescriptors};
18
19use crate::{
20    config_store::{StoreRoot, StoreWriterLock},
21    live_children::{self, AdoptedPids},
22    run_dir_lock::{RunDirLock, RUN_DIR_LOCK_FILE_NAME},
23    supervise::{
24        handover::{
25            self, Cohort, Handover, HexBytes, LockPaths, LockRole, StreamWitness, VerifiedImage,
26        },
27        live_upgrade::{
28            reconcile_child_with_container, reconcile_child_with_unrecorded_fence,
29            InheritedStreams, ReconciledChild,
30        },
31        resume_hello::Preparation,
32        RegisteredConfiguredModule,
33    },
34};
35
36use super::{
37    start_lock_path, BootstrapConfig, BootstrapError, Path, PathBuf, StartLock, Supervisor,
38    SupervisorHandle,
39};
40
41/// Formats that the daemon binary can resume on this platform.
42pub const HANDOVER_VERSIONS: &[u32] = handover::HANDOVER_VERSIONS;
43
44/// A startup request whose handover has been checked before daemon startup.
45pub struct ResumeBootstrap {
46    config: BootstrapConfig,
47    inherited: Result<Inherited, io::Error>,
48}
49
50impl ResumeBootstrap {
51    /// Validate the handover using only read-only boot configuration and the
52    /// descriptor snapshot taken at process entry. A different running image
53    /// is allowed to boot cold, but a malformed handover refuses startup.
54    pub fn validate(
55        config: BootstrapConfig,
56        path: &Path,
57        key_fd: RawFd,
58        inherited: InheritedDescriptors,
59    ) -> Result<Self, BootstrapError> {
60        let inherited = validate(&config, path, key_fd, inherited)?;
61        Ok(Self { config, inherited })
62    }
63
64    pub async fn run(self) -> Result<(), BootstrapError> {
65        let inherited = match self.inherited {
66            Ok(inherited) => Some(inherited),
67            Err(error) => {
68                tracing::warn!(%error, "running image did not match the upgrade target; starting cold");
69                eprintln!("ck-subc: running image did not match the upgrade target; starting cold: {error}");
70                None
71            }
72        };
73        super::run_with_config_inner(self.config, inherited).await
74    }
75}
76
77pub(super) struct Inherited {
78    pub(super) start: StartLock,
79    pub(super) run: RunDirLock,
80    pub(super) store: Option<(StoreRoot, StoreWriterLock)>,
81    pub(super) resume: Resume,
82}
83
84pub(super) struct Resume {
85    handover: Handover,
86    streams: BTreeMap<RawFd, std::os::fd::OwnedFd>,
87    deadline: Instant,
88    #[cfg(feature = "test-support")]
89    pause_install: Option<(String, PathBuf)>,
90}
91
92fn refused(error: impl std::fmt::Display) -> BootstrapError {
93    BootstrapError::Resume(io::Error::other(error.to_string()))
94}
95
96fn validate(
97    config: &BootstrapConfig,
98    path: &Path,
99    key_fd: RawFd,
100    mut inherited: InheritedDescriptors,
101) -> Result<Result<Inherited, io::Error>, BootstrapError> {
102    let record = config
103        .live_children_path
104        .as_ref()
105        .ok_or_else(|| refused("no live-children record configured"))?;
106    let expected = record.with_file_name(handover::HANDOVER_FILE_NAME);
107    if path.as_os_str() != expected.as_os_str() {
108        return Err(refused(
109            "handover path does not match the configured run directory",
110        ));
111    }
112    let file = File::from(
113        rfs::open(
114            path,
115            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
116            Mode::empty(),
117        )
118        .map_err(refused)?,
119    );
120    let stat = file.metadata().map_err(refused)?;
121    if !stat.is_file() || stat.uid() != subc_os::effective_uid() || stat.mode() & 0o7777 != 0o600 {
122        return Err(refused(
123            "handover must be a regular file owned by this user with mode 0600",
124        ));
125    }
126    let key =
127        read_key(File::from(inherited.take_key(key_fd).map_err(refused)?)).map_err(refused)?;
128    let mut bytes = Vec::new();
129    (&file).read_to_end(&mut bytes).map_err(refused)?;
130    let mut handover = handover::decode(&bytes, &key).map_err(refused)?;
131    validate_cohort(&handover)?;
132    let now_ms = crate::stderr_tail::unix_ms(SystemTime::now());
133    let deadline = Instant::now()
134        .checked_add(Duration::from_millis(
135            handover.reconnect_by_ms.saturating_sub(now_ms),
136        ))
137        .ok_or_else(|| refused("handover reconnect deadline is out of range"))?;
138
139    let run = record.with_file_name(RUN_DIR_LOCK_FILE_NAME);
140    let publication = start_lock_path(&config.connection_file_path);
141    let store = config
142        .config_store_root()
143        .map(StoreWriterLock::inherited_layout)
144        .transpose()
145        .map_err(refused)?;
146    let paths = LockPaths {
147        run_dir: &run,
148        publication: &publication,
149        store_writer: store.as_ref().map(|(_, lock)| lock.as_path()),
150    };
151    let expected_fds = handover
152        .locks
153        .iter()
154        .map(|lock| lock.fd)
155        .chain(
156            handover
157                .children
158                .iter()
159                .flat_map(|child| [&child.stdout, &child.stderr])
160                .filter_map(|stream| match stream {
161                    StreamWitness::Open { fd, .. } => Some(*fd),
162                    StreamWitness::Ended {} => None,
163                }),
164        )
165        .collect();
166    let mut descriptors = inherited.into_named(&expected_fds).map_err(refused)?;
167    handover::validate_inherited_fds(&handover, config, &paths, |fd| {
168        descriptors.get(&fd).map(AsFd::as_fd)
169    })
170    .map_err(refused)?;
171
172    if let Err(error) = verify_running_image(config, &handover.verified_image) {
173        // Close the inherited descriptors without adopting their locks. The
174        // cold boot removes the handover once it owns the run directory.
175        return Ok(Err(error));
176    }
177
178    let current = fs::symlink_metadata(path).map_err(refused)?;
179    if current.dev() != stat.dev() || current.ino() != stat.ino() {
180        return Err(refused("handover file changed during validation"));
181    }
182    fs::remove_file(path).map_err(refused)?;
183    for fd in descriptors.values() {
184        fcntl_setfd(fd, FdFlags::CLOEXEC).map_err(refused)?;
185    }
186
187    let mut locks: BTreeMap<_, _> = handover
188        .locks
189        .drain(..)
190        .map(|lock| {
191            (
192                lock.role,
193                File::from(
194                    descriptors
195                        .remove(&lock.fd)
196                        .expect("validated lock descriptor"),
197                ),
198            )
199        })
200        .collect();
201    let start = StartLock {
202        _file: locks
203            .remove(&LockRole::Publication)
204            .expect("validated publication lock"),
205    };
206    let run = RunDirLock::from_inherited(
207        record.clone(),
208        locks.remove(&LockRole::RunDir).expect("validated run lock"),
209    );
210    let store = store.map(|(root, _)| {
211        (
212            root,
213            StoreWriterLock::from_inherited(
214                locks
215                    .remove(&LockRole::StoreWriter)
216                    .expect("validated store lock"),
217            ),
218        )
219    });
220    Ok(Ok(Inherited {
221        start,
222        run,
223        store,
224        resume: Resume {
225            handover,
226            streams: descriptors,
227            deadline,
228            #[cfg(feature = "test-support")]
229            pause_install: config
230                .upgrade_binary
231                .as_ref()
232                .filter(|binary| binary.test_hooks)
233                .and_then(|_| std::env::var("SUBC_TEST_RESUME_PAUSE_MODULE").ok())
234                // No longer than `subc.sock`, so it fits the Unix socket path
235                // limit wherever the daemon's own socket does.
236                .map(|module| (module, record.with_file_name("rp.sock"))),
237        },
238    }))
239}
240
241fn read_key(mut pipe: File) -> io::Result<[u8; 32]> {
242    let flags = rfs::fcntl_getfl(&pipe)?;
243    if FileType::from_raw_mode(rfs::fstat(&pipe)?.st_mode) != FileType::Fifo
244        || flags.intersects(OFlags::WRONLY | OFlags::RDWR)
245    {
246        return Err(io::Error::other(
247            "handover key descriptor must be a pipe read end",
248        ));
249    }
250    // The old image closes its writer before exec. Never block if a malformed
251    // invocation presents a pipe whose writer is still open.
252    rfs::fcntl_setfl(&pipe, flags | OFlags::NONBLOCK)?;
253    let mut key = [0; 32];
254    pipe.read_exact(&mut key)?;
255    if pipe.read(&mut [0])? != 0 {
256        return Err(io::Error::other("handover key must be exactly 32 bytes"));
257    }
258    Ok(key)
259}
260
261fn validate_cohort(handover: &Handover) -> Result<(), BootstrapError> {
262    let cohort = &handover.cohort;
263    let mut modules = BTreeSet::new();
264    let carried: BTreeSet<_> = cohort.carried.iter().collect();
265    let mut children = BTreeSet::new();
266    let mut pids = BTreeSet::new();
267    if !cohort
268        .carried
269        .iter()
270        .chain(&cohort.restarting)
271        .chain(&cohort.stopped)
272        .all(|id| modules.insert(id))
273        || !handover
274            .children
275            .iter()
276            .all(|child| children.insert(&child.module_id) && pids.insert(child.pid))
277        || carried != children
278    {
279        return Err(refused("handover children and cohort disagree"));
280    }
281    let mut streams = BTreeSet::new();
282    for stream in handover
283        .children
284        .iter()
285        .flat_map(|child| [&child.stdout, &child.stderr])
286    {
287        if let StreamWitness::Open { fd, .. } = stream {
288            if !streams.insert(*fd) {
289                return Err(refused(format!(
290                    "duplicate handover stream descriptor {fd}"
291                )));
292            }
293        }
294    }
295    Ok(())
296}
297
298fn verify_running_image(_config: &BootstrapConfig, expected: &VerifiedImage) -> io::Result<()> {
299    #[cfg(target_os = "linux")]
300    let (path, cdhash_matches) = (PathBuf::from("/proc/self/exe"), expected.cdhash.is_none());
301    #[cfg(target_os = "macos")]
302    let (path, cdhash_matches) = {
303        use subc_os::code_signature::{self, SignatureError};
304        let cdhash_matches = match (expected.cdhash, code_signature::self_cdhash()) {
305            (Some(expected), Ok(actual)) => expected.0 == actual.0,
306            #[cfg(feature = "test-support")]
307            (None, Err(SignatureError::NotSigned)) => _config
308                .upgrade_binary
309                .as_ref()
310                .is_some_and(|binary| binary.test_hooks),
311            (_, Err(SignatureError::NotSigned)) | (None, Ok(_)) => false,
312            (_, Err(error)) => return Err(io::Error::other(error)),
313        };
314        (std::env::current_exe()?, cdhash_matches)
315    };
316    let mut digest = Sha256::new();
317    io::copy(&mut File::open(path)?, &mut digest)?;
318    if !cdhash_matches || HexBytes(digest.finalize().into()) != expected.sha256 {
319        return Err(io::Error::other(
320            "running executable digest or code signature differs from the verified target",
321        ));
322    }
323    Ok(())
324}
325
326/// Cold cleanup is only callable with ownership of the same run directory.
327pub(super) fn discard_leftover(owner: &RunDirLock) {
328    let path = owner
329        .live_children_record()
330        .with_file_name(handover::HANDOVER_FILE_NAME);
331    if let Err(error) = fs::remove_file(&path) {
332        if error.kind() != io::ErrorKind::NotFound {
333            tracing::warn!(path = %path.display(), %error, "could not remove a leftover daemon handover");
334        }
335    }
336}
337
338pub(super) struct AdoptionPlan {
339    pub(super) protected: AdoptedPids,
340    pub(super) monotonic_ns: u64,
341    cohort: Cohort,
342    children: BTreeMap<String, (ReconciledChild, InheritedStreams)>,
343    unrecorded_fences: BTreeMap<String, live_children::RecordedChild>,
344    attempt: HexBytes<16>,
345    started_at_ms: u64,
346    deadline: Instant,
347    #[cfg(feature = "test-support")]
348    pause_install: Option<(String, PathBuf)>,
349}
350
351impl Resume {
352    pub(super) fn verified_digest(&self) -> HexBytes<32> {
353        self.handover.verified_image.sha256
354    }
355
356    pub(super) fn reconcile(mut self, owner: &RunDirLock) -> Result<AdoptionPlan, BootstrapError> {
357        let path = owner.live_children_record();
358        let (records, reasons) = match live_children::read_record_entries(path) {
359            Ok(record) => (record.0, Some(record.1)),
360            Err(error) => {
361                // Missing identity makes the supervisor hold, never signal, a
362                // listed child. The normal sweep quarantines the unusable file.
363                tracing::warn!(%error, "could not read the carried children's durable identities");
364                (Vec::new(), None)
365            }
366        };
367        // A carried process-group container is recorded in its own row under
368        // the group's first module process. That pid can also be the module
369        // process's own row, so container rows are looked up by group id.
370        let (containers, processes): (Vec<_>, Vec<_>) = records
371            .iter()
372            .partition(|record| record.child.is_group_container());
373        let by_pid: BTreeMap<_, _> = processes
374            .into_iter()
375            .map(|record| (record.child.pid, record))
376            .collect();
377        let containers: BTreeMap<_, _> = containers
378            .into_iter()
379            .map(|record| (record.child.pid, record))
380            .collect();
381        let unrecorded_fences =
382            fence_unrecorded_containers(path, &records, reasons, &self.handover.children);
383        let mut adopted = Vec::new();
384        let mut held = Vec::new();
385        let mut children = BTreeMap::new();
386        for mut child in self.handover.children {
387            let streams = [&mut child.stdout, &mut child.stderr].map(|stream| {
388                match std::mem::replace(stream, StreamWitness::Ended {}) {
389                    StreamWitness::Open { fd, tail } => Some((
390                        self.streams
391                            .remove(&fd)
392                            .expect("validated stream descriptor"),
393                        tail,
394                    )),
395                    StreamWitness::Ended {} => None,
396                }
397            });
398            let pid = child.pid;
399            let module = child.module_id.clone();
400            let carried_pgid = child.carried_container.as_ref().map(|carried| carried.pgid);
401            let container = carried_pgid.and_then(|pgid| containers.get(&pgid).copied());
402            let process = by_pid.get(&pid).copied();
403            let reconciled = if unrecorded_fences.contains_key(&module) {
404                reconcile_child_with_unrecorded_fence(child, process)
405            } else {
406                reconcile_child_with_container(child, process, container)
407            }
408            .map_err(refused)?;
409            match &reconciled {
410                ReconciledChild::Adopt(child) => {
411                    adopted.push(pid);
412                    adopted.extend(child.carried_pgid());
413                }
414                ReconciledChild::Held(_) => held.push(pid),
415                ReconciledChild::Exited => {}
416            }
417            // A container that is not taken over keeps its row as a held
418            // fence: the sweep leaves it, the record keeps it across a
419            // restart, and only the settlement of that container removes it.
420            if let Some(pgid) = carried_pgid {
421                if !matches!(&reconciled, ReconciledChild::Adopt(child) if child.carried_pgid().is_some())
422                {
423                    held.push(pgid);
424                }
425            }
426            children.insert(module, (reconciled, streams));
427        }
428        Ok(AdoptionPlan {
429            protected: AdoptedPids::from_classes(adopted, held),
430            monotonic_ns: self.handover.monotonic_ns,
431            cohort: self.handover.cohort,
432            children,
433            unrecorded_fences,
434            attempt: self.handover.attempt_id,
435            started_at_ms: self.handover.started_at_ms,
436            deadline: self.deadline,
437            #[cfg(feature = "test-support")]
438            pause_install: self.pause_install,
439        })
440    }
441}
442
443/// Record a carried container that the signed handover names but the durable
444/// record lacks. Missing evidence does not prove that the container is empty,
445/// so its row is written from the handover's own facts before the orphan sweep
446/// or a shutdown could lose them. The resume holds that row like any other
447/// container row, a cold start sweeps it, and only the container's settlement
448/// removes it.
449pub(super) fn fence_unrecorded_containers(
450    path: &Path,
451    records: &[live_children::RecordedChild],
452    reasons: Option<BTreeMap<u32, live_children::RetainedReason>>,
453    children: &[handover::ChildWitness],
454) -> BTreeMap<String, live_children::RecordedChild> {
455    let recorded = |pgid: u32| {
456        records
457            .iter()
458            .any(|record| record.child.is_group_container() && record.child.pid == pgid)
459    };
460    let missing: Vec<_> = children
461        .iter()
462        .filter_map(|child| {
463            let carried = child.carried_container.as_ref()?;
464            (!recorded(carried.pgid)).then(|| live_children::RecordedChild {
465                child: live_children::LiveChild {
466                    module_id: child.module_id.clone(),
467                    pid: carried.pgid,
468                    protocol: records
469                        .iter()
470                        .find(|record| record.child.module_id == child.module_id)
471                        .map_or(subc_control::ModuleProtocol::Subc, |record| {
472                            record.child.protocol
473                        }),
474                    start_time: Some(carried.created_start_time),
475                    executable: None,
476                    cgroup_name: None,
477                    container: Some(live_children::ContainerIdentity {
478                        pgid: Some(carried.pgid),
479                        created_start_time: Some(carried.created_start_time),
480                        boot_id: Some(carried.boot_id.clone()),
481                        session_id: Some(carried.session_id),
482                        cgroup_path: None,
483                    }),
484                },
485                resume_token_sha256: None,
486            })
487        })
488        .collect();
489    if missing.is_empty() {
490        return BTreeMap::new();
491    }
492    for row in &missing {
493        tracing::warn!(module_id = %row.child.module_id, pgid = row.child.pid,
494            "the handover names a carried container the record lacks; recording it as a fence");
495    }
496    // Leave an unreadable record to the orphan sweep's quarantine. Retry
497    // against the running roster, not against this stale bootstrap snapshot.
498    let result = reasons.map_or_else(
499        || {
500            Err(std::io::Error::other(
501                "the existing recovery record is unreadable",
502            ))
503        },
504        |reasons| {
505            let rows: Vec<_> = records.iter().chain(&missing).cloned().collect();
506            live_children::write_record_with_reasons(path, &rows, reasons)
507        },
508    );
509    match result {
510        Ok(()) => BTreeMap::new(),
511        Err(error) => {
512            for row in &missing {
513                tracing::error!(module_id = %row.child.module_id, pgid = row.child.pid, %error,
514                    "could not record the carried container fence; holding the module and retrying");
515            }
516            missing
517                .into_iter()
518                .map(|row| (row.child.module_id.clone(), row))
519                .collect()
520        }
521    }
522}
523
524type RegisteredCohort = BTreeMap<String, (RegisteredConfiguredModule, bool)>;
525pub(super) type PlannedStarts = Vec<(String, Option<RegisteredConfiguredModule>, bool)>;
526type Preparations = BTreeMap<String, Preparation>;
527
528impl AdoptionPlan {
529    fn modules(&self) -> impl Iterator<Item = &String> {
530        self.cohort
531            .carried
532            .iter()
533            .chain(&self.cohort.restarting)
534            .chain(&self.cohort.stopped)
535    }
536
537    pub(super) fn begin_report(&self, supervisor: &SupervisorHandle) {
538        supervisor.begin_resume_report(
539            self.attempt.to_string(),
540            self.started_at_ms,
541            self.modules().cloned(),
542        );
543    }
544
545    pub(super) fn enabled(&self, module: &str, configured: bool) -> Option<bool> {
546        self.modules()
547            .any(|id| id == module)
548            .then(|| self.cohort.allow_start(module, Some(configured)))
549    }
550
551    pub(super) fn stage_preparations(
552        &self,
553        handle: &SupervisorHandle,
554        registered: &RegisteredCohort,
555    ) -> Result<Preparations, BootstrapError> {
556        self.children
557            .iter()
558            .filter_map(|(module, (child, _))| {
559                let ReconciledChild::Adopt(child) = child else {
560                    return None;
561                };
562                registered.get(module).filter(|(_, enabled)| *enabled)?;
563                Some(
564                    child
565                        .begin_preparation(handle, self.deadline.into())
566                        .map(|guard| (module.clone(), guard))
567                        .map_err(refused),
568                )
569            })
570            .collect()
571    }
572
573    pub(super) async fn install(
574        mut self,
575        supervisor: &Supervisor,
576        mut registered: RegisteredCohort,
577        mut preparations: Preparations,
578    ) -> Result<PlannedStarts, BootstrapError> {
579        let mut planned = Vec::new();
580        let mut installing = tokio::task::JoinSet::new();
581        let attempt = self.attempt.0;
582        let deadline = self.deadline.into();
583        for module in self
584            .cohort
585            .carried
586            .into_iter()
587            .chain(self.cohort.restarting)
588            .chain(self.cohort.stopped)
589        {
590            let (registered, enabled) = match registered.remove(&module) {
591                Some((registered, enabled)) => (Some(registered), enabled),
592                None => (None, false),
593            };
594            match self.children.remove(&module) {
595                Some((ReconciledChild::Adopt(child), streams)) => {
596                    if let Some(registered) = registered {
597                        let supervisor = supervisor.clone();
598                        let preparation = preparations.remove(&module);
599                        #[cfg(feature = "test-support")]
600                        let pause = self
601                            .pause_install
602                            .as_ref()
603                            .filter(|(id, _)| *id == module)
604                            .map(|(_, path)| path.clone());
605                        installing.spawn(async move {
606                            let _preparation = preparation;
607                            #[cfg(feature = "test-support")]
608                            if let Some(path) = pause {
609                                let _ = tokio::time::timeout_at(
610                                    deadline,
611                                    crate::control::upgrade_in_place::wait_at_gate(&path, 1),
612                                )
613                                .await;
614                            }
615                            supervisor
616                                .start_adopted_after_upgrade(
617                                    registered, *child, streams, attempt, deadline, enabled,
618                                )
619                                .await
620                        });
621                    } else {
622                        supervisor.stop_unconfigured_after_upgrade(*child);
623                    }
624                }
625                Some((ReconciledChild::Held(child), _)) => {
626                    supervisor.watch_unresolved_with_fence(
627                        *child,
628                        registered,
629                        enabled,
630                        self.unrecorded_fences.remove(&module),
631                    );
632                }
633                Some((ReconciledChild::Exited, _)) | None => {
634                    planned.push((module, registered, enabled))
635                }
636            }
637        }
638        while let Some(result) = installing.join_next().await {
639            result.map_err(refused)?.map_err(refused)?;
640        }
641        Ok(planned)
642    }
643}
644
645pub(super) fn log_accept(sample: u64) {
646    match monotonic_ns() {
647        Ok(now) => tracing::info!(
648            resume_accept_ms = now.saturating_sub(sample) / 1_000_000,
649            "local listener accepting daemon upgrade reconnects"
650        ),
651        Err(error) => {
652            tracing::warn!(%error, "could not measure when the local listener started accepting")
653        }
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660    use std::io::Write;
661
662    /// A signed handover names a carried container the record lacks, and a
663    /// helper survives in it. The fence must outlive this daemon: after a
664    /// shutdown, a cold start still has the group identity and holds the module.
665    #[test]
666    fn an_unrecorded_carried_container_stays_fenced_across_a_cold_start() {
667        use std::os::unix::process::CommandExt;
668        struct Owned(std::process::Child);
669        impl Drop for Owned {
670            fn drop(&mut self) {
671                let _ = self.0.kill();
672                let _ = self.0.wait();
673            }
674        }
675        let scratch = cortexkit_test_support::ScratchDir::new("resume-unrecorded-container");
676        let sleep = |group: i32| {
677            Owned(
678                std::process::Command::new("/bin/sleep")
679                    .arg("60")
680                    .process_group(group)
681                    .spawn()
682                    .unwrap(),
683            )
684        };
685        let pin = sleep(0);
686        let pgid = pin.0.id();
687        let _helper = sleep(i32::try_from(pgid).unwrap());
688        let created = subc_os::process_group::inspect(pgid)
689            .unwrap()
690            .unwrap()
691            .start_time;
692        let mut handover = handover::decode(
693            include_bytes!("../../tests/fixtures/handover-format-2.txt"),
694            b"0123456789abcdef0123456789abcdef",
695        )
696        .unwrap();
697        let child = &mut handover.children[0];
698        child.module_id = "carrier".into();
699        child.pid = pgid;
700        child.start_time = created;
701        child.carried_container = Some(handover::CarriedContainerWitness {
702            pgid,
703            pin_pid: pgid,
704            created_start_time: created,
705            boot_id: subc_os::boot_id::current().unwrap(),
706            session_id: subc_os::process_group::session_id(std::process::id())
707                .unwrap()
708                .unwrap(),
709        });
710        let module_row = live_children::RecordedChild {
711            child: live_children::LiveChild {
712                module_id: "carrier".into(),
713                pid: pgid,
714                protocol: subc_control::ModuleProtocol::Subc,
715                start_time: Some(created),
716                executable: None,
717                cgroup_name: None,
718                container: None,
719            },
720            resume_token_sha256: None,
721        };
722        let path = scratch.join("live-children.json");
723        let blocked_path = scratch.join("blocked-record");
724        std::fs::create_dir(&blocked_path).unwrap();
725        let pending = fence_unrecorded_containers(
726            &blocked_path,
727            std::slice::from_ref(&module_row),
728            Some(BTreeMap::new()),
729            &handover.children[..1],
730        );
731        assert!(pending["carrier"].child.is_group_container());
732        assert_eq!(pending["carrier"].child.pid, pgid);
733        live_children::write_record_with_reasons(
734            &path,
735            std::slice::from_ref(&module_row),
736            BTreeMap::new(),
737        )
738        .unwrap();
739
740        assert!(fence_unrecorded_containers(
741            &path,
742            std::slice::from_ref(&module_row),
743            Some(BTreeMap::new()),
744            &handover.children[..1],
745        )
746        .is_empty());
747        // The resumed daemon holds the row; then it shuts down.
748        let resumed = crate::child_roster::ChildRoster::default();
749        resumed.record_to_with_adopted(path.clone(), &AdoptedPids::from_classes([], [pgid]));
750        assert!(resumed.previous_instance("carrier").is_some());
751        drop(resumed);
752        assert!(live_children::read_record_entries(&path)
753            .unwrap()
754            .0
755            .iter()
756            .any(|row| row.child.is_group_container() && row.child.pid == pgid));
757
758        // A cold start finds the fence and holds the module until the group
759        // is settled under the recorded group's own proof.
760        let cold = crate::child_roster::ChildRoster::default();
761        cold.record_to_with_adopted(path.clone(), &AdoptedPids::none());
762        assert!(
763            cold.previous_instance("carrier").is_some(),
764            "a cold start must not start the module beside the container's helper"
765        );
766    }
767
768    #[test]
769    fn duplicate_stream_descriptor_is_refused_before_adoption() {
770        let mut handover = handover::decode(
771            include_bytes!("../../tests/fixtures/handover-format-2.txt"),
772            b"0123456789abcdef0123456789abcdef",
773        )
774        .unwrap();
775        validate_cohort(&handover).unwrap();
776        let StreamWitness::Open { fd, .. } = handover.children[0].stdout else {
777            panic!("golden handover must have an open stdout");
778        };
779        handover.children[1].stderr = StreamWitness::Open { fd, tail: vec![] };
780        assert!(validate_cohort(&handover)
781            .unwrap_err()
782            .to_string()
783            .contains("duplicate handover stream descriptor"));
784    }
785
786    #[test]
787    fn handover_key_requires_exactly_32_bytes_and_a_closed_writer() {
788        for key in [&[7; 31][..], &[7; 32], &[7; 33]] {
789            let (reader, mut writer) = io::pipe().unwrap();
790            writer.write_all(key).unwrap();
791            drop(writer);
792            let result = read_key(File::from(std::os::fd::OwnedFd::from(reader)));
793            if key.len() == 32 {
794                assert_eq!(result.unwrap(), [7; 32]);
795            } else {
796                assert!(result.is_err());
797            }
798        }
799        let (reader, mut writer) = io::pipe().unwrap();
800        writer.write_all(&[7; 32]).unwrap();
801        let error = read_key(File::from(std::os::fd::OwnedFd::from(reader))).unwrap_err();
802        assert_eq!(error.kind(), io::ErrorKind::WouldBlock);
803        drop(writer);
804    }
805}