1#[cfg(all(test, target_os = "linux"))]
6#[path = "supervise/audit_identity_tests.rs"]
7mod audit_identity_tests;
8mod resource_launch;
9pub(crate) use resource_launch::{ResourceCommitError, ResourceLaunch};
10
11use std::{
12 collections::{HashMap, HashSet, VecDeque},
13 error::Error,
14 fmt, io,
15 path::PathBuf,
16 process::{ExitStatus, Stdio},
17 sync::{Arc, Mutex, OnceLock},
18 time::{Duration, SystemTime, UNIX_EPOCH},
19};
20
21use cortexkit_log::Retention;
22use serde_json::Value;
23use sha2::{Digest, Sha256};
24use subc_control::{
25 ClientControlPush, LiveSpawn, ModuleProtocol, RouteCloseReason, SpawnCursor, SpawnEvent,
26 SpawnEventKind, SpawnSnapshot, SupervisorHealthStatus, TerminalDisposition, TerminalExitKind,
27};
28use subc_protocol::{
29 manifest::{SelfSignalKind, SignalAnchor},
30 session::{
31 HealthReport, HealthStatus, ModuleControlCommand, ModuleControlRequest,
32 MODULE_CONTROL_OP_HEALTH_CHECK,
33 },
34 Flags, FrameType, Principal, Priority, SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV,
35};
36use tokio::{
37 process::{Child, Command},
38 sync::{mpsc, oneshot, watch, Mutex as AsyncMutex},
39 task::JoinHandle,
40 time::{sleep, sleep_until, timeout, timeout_at, Instant},
41};
42use tracing::{debug, error, info, warn};
43
44use crate::{
45 child_output::StderrPump,
46 child_roster::ChildRoster,
47 daemon_config::{
48 CAPTURE_KEEP_ENV, CAPTURE_MAX_AGE_DAYS_ENV, CAPTURE_MAX_FILE_MB_ENV, CK_LOG_ENV,
49 },
50 forwarding::{
51 CloseReason, ForwardingError, ForwardingTable, GoodbyeTarget, ModuleControlRpcOutcome,
52 ModuleDrainTarget, PendingModuleControlRpc,
53 },
54 provenance::{ExecutableIdentityProbe, SpawnedFileIdentity},
55 registry::{ConnectionId, RegistrationEndReason, RegistryError},
56 stderr_tail::{ChildOutputSink, StderrRing, StderrTailConfig, StderrTailSnapshot},
57 terminal_ring::{TerminalHistorySnapshot, TerminalRecord, TerminalRing, TerminalRingConfig},
58 Frame, FrameSink, Registry,
59};
60
61#[cfg(not(windows))]
62use crate::provenance::spawned_file_identity;
63
64#[path = "supervise_swap.rs"]
65mod swap;
66
67#[path = "supervise_activity.rs"]
68mod activity;
69
70#[cfg(unix)]
71#[path = "supervise/admission.rs"]
72mod admission;
73mod admission_exit;
74#[cfg(all(test, target_os = "linux"))]
75mod async_spawn_tests;
76#[cfg(all(test, windows))]
77mod carried_job_tests;
78mod config_delivery;
79mod content_binding;
80mod program_binding;
81mod registration;
82pub(crate) mod script;
83type NonceLaunches = HashMap<String, (String, std::sync::Weak<RegistrationSpawn>)>;
85pub(crate) use registration::NonceAttestation;
86#[cfg(all(test, unix))]
87pub(crate) use registration::RegistrationProof;
88pub(crate) use registration::RegistrationSpawn;
89pub(crate) use registration::REGISTRATION_CHANNEL_CLOSED;
90#[cfg(all(test, unix))]
91pub(crate) mod unix_channel_placement_tests;
92use program_binding::ProgramBindingPublication;
93mod config_exit_failure;
94#[cfg(all(test, any(target_os = "linux", windows)))]
95mod missing_path_tests;
96#[cfg(all(test, unix))]
97mod program_binding_tests;
98#[cfg(all(test, windows))]
99mod program_binding_windows_tests;
100#[cfg(all(test, windows))]
101mod windows_channel_tests;
102pub use config_exit_failure::ModuleStopReason;
103mod unregistered_stop;
104use unregistered_stop::stop_unregistered_child;
105#[cfg(target_os = "linux")]
106#[path = "supervise/cgroup_label.rs"]
107mod cgroup_label;
108#[cfg(all(test, unix))]
109mod config_exit_hold_tests;
110pub(crate) mod containment;
111#[cfg(all(test, unix))]
112mod containment_tests;
113#[cfg(target_os = "linux")]
114mod ordinary_cgroup;
115#[cfg(unix)]
116pub(crate) mod plain_group;
117#[cfg(all(test, target_os = "linux"))]
118mod plain_group_regression;
119mod slow_retry;
120use slow_retry::{FailedRetry, FailureContext};
121mod host_health;
122use host_health::HostHealth;
123
124#[cfg(test)]
125mod crash_admission_tests;
126mod crash_budget;
127#[cfg(all(test, unix))]
128mod mark_readiness_tests;
129#[cfg(all(test, unix))]
130mod slow_retry_tests;
131use crash_budget::{admit_running_child_async, spawn_and_mark_running_async};
132
133pub const SUBC_ARG: &str = "--subc";
139
140const DEFAULT_MAX_RESTARTS: u32 = 3;
141const DEFAULT_BACKOFF: Duration = Duration::from_millis(100);
142const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
143const DEFAULT_RESTART_WINDOW: Duration = Duration::from_secs(600);
147pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
158#[cfg(any(unix, feature = "test-support"))]
161const ADMISSION_TIMEOUT: Duration = Duration::from_secs(30);
162
163#[cfg(feature = "test-support")]
165pub const CHILD_ADMISSION_TIMEOUT: Duration = ADMISSION_TIMEOUT;
166
167pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
168const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
169const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
170const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
182const STDERR_PUMP_DRAIN_TIMEOUT: Duration = Duration::from_millis(250);
190pub const SPAWN_EVENT_RING_CAPACITY: usize = 4096;
192const SPAWN_SUBSCRIBER_BUFFER: usize = SPAWN_EVENT_RING_CAPACITY + 1;
193pub(crate) const SPAWN_SUBSCRIBER_LAGGED_CODE: &str = "spawn_subscriber_lagged";
198
199#[cfg(target_os = "macos")]
200struct PrivacyExec {
201 content_check: Option<tokio::task::JoinHandle<Result<(), crate::config_gate::GateError>>>,
202 gated: bool,
203 admission_binding: Option<ProgramBindingPublication>,
204 reader: tokio::io::unix::AsyncFd<std::io::PipeReader>,
205 deadline: tokio::time::Instant,
206 expected: Option<subc_os::FileIdentity>,
207 trampoline: Option<subc_os::FileIdentity>,
208 signature: Option<Arc<subc_os::privacy_identity::SuspendedSignature>>,
209 module_id: String,
210 #[cfg(test)]
211 confirmation_pause: Option<(String, Option<tokio::net::TcpStream>)>,
212 #[cfg(test)]
213 image_probe: Option<fn(u32) -> Option<subc_os::Observation>>,
214 #[cfg(test)]
215 image_read_delay: Option<Duration>,
216}
217
218#[cfg(all(test, target_os = "macos"))]
219pub(crate) fn test_privacy_trampoline() -> PathBuf {
220 let path = cortexkit_test_support::cargo_profile_bin("privacy-trampoline-fixture");
223 assert!(
227 path.exists(),
228 "privacy-trampoline-fixture not built at {}: run `cargo build -p subc-daemon \
229 --bins --features test-support` or `cargo test -p subc-daemon` first",
230 path.display()
231 );
232 path
233}
234
235#[cfg(target_os = "macos")]
236fn probe_privacy_trampoline(path: &std::path::Path) -> Result<(), String> {
237 use std::io::Read;
238 let mut probe = subc_os::child_spawn::spawn(
239 std::process::Command::new(path)
240 .args(["__disclaim-exec", "--probe-suspended"])
241 .stdin(Stdio::null())
242 .stdout(Stdio::piped())
243 .stderr(Stdio::piped()),
244 )
245 .map_err(|error| {
246 format!(
247 "privacy trampoline probe failed for {}: {error}",
248 path.display()
249 )
250 })?;
251 let deadline = std::time::Instant::now() + Duration::from_secs(5);
252 let status = loop {
253 match probe.try_wait() {
254 Ok(Some(status)) => break status,
255 Ok(None) if std::time::Instant::now() < deadline => {
256 std::thread::sleep(Duration::from_millis(5))
257 }
258 result => {
259 let _ = probe.kill();
260 let _ = probe.wait();
261 return Err(format!(
262 "privacy trampoline probe failed or timed out for {}: {result:?}",
263 path.display()
264 ));
265 }
266 }
267 };
268 let mut answer = String::new();
269 if let Some(stdout) = probe.stdout.take() {
270 let _ = stdout.take(256).read_to_string(&mut answer);
271 }
272 if status.success() && answer.trim() == subc_os::privacy_identity::SUSPENDED_TRAMPOLINE_PROBE {
273 return Ok(());
274 }
275 let mut diagnostic = String::new();
276 if let Some(stderr) = probe.stderr.take() {
277 let _ = stderr.take(1024).read_to_string(&mut diagnostic);
278 }
279 let cause = diagnostic
280 .trim()
281 .strip_prefix("ck-subc: own privacy identity refused: ")
282 .unwrap_or("binary does not implement the privacy trampoline protocol");
283 Err(format!(
284 "{cause}: probe of {} exited {status}",
285 path.display()
286 ))
287}
288
289#[cfg(target_os = "macos")]
290fn privacy_command(
291 spec: &ModuleSpec,
292 binding: &SpawnProgramBinding,
293 roster: &ChildRoster,
294 gated: bool,
295) -> Result<
296 (
297 Command,
298 Option<PrivacyExec>,
299 subc_os::privacy_identity::ExecAcknowledgement,
300 ),
301 SuperviseError,
302> {
303 let failure = |cause: String| {
304 warn!(module_id = %spec.module_id, %cause, "privacy identity trampoline refused module spawn");
305 SuperviseError::Spawn {
306 program: spec.program.clone(),
307 source: io::Error::other(cause),
308 cgroup_path: None,
309 }
310 };
311 let trampoline = roster.privacy_trampoline().map_err(failure)?;
312 let expected = Some(binding.identity);
313 let trampoline_image = subc_os::file_identity(&trampoline);
314 let signature = gated
315 .then(|| {
316 subc_os::privacy_identity::SuspendedSignature::capture(&binding._file, &binding.path)
317 .map(Arc::new)
318 })
319 .transpose()
320 .map_err(|error| failure(error.to_string()))?;
321 if expected == trampoline_image {
322 return Err(failure(
323 "privacy identity module executable is missing or is the trampoline itself".to_string(),
324 ));
325 }
326 let (reader, ack) = subc_os::privacy_identity::ExecAcknowledgement::pipe()
327 .map_err(|error| failure(error.to_string()))?;
328 let reader =
329 tokio::io::unix::AsyncFd::new(reader).map_err(|error| failure(error.to_string()))?;
330 let mut command = Command::new(&trampoline);
331 command
332 .arg(if gated {
333 "__disclaim-exec-suspended"
334 } else {
335 "__disclaim-exec"
336 })
337 .arg(ack.fd().to_string())
338 .arg(&binding.path);
339 Ok((
340 command,
341 Some(PrivacyExec {
342 gated,
343 admission_binding: None,
344 content_check: None,
345 reader,
346 deadline: tokio::time::Instant::now() + Duration::from_secs(5),
347 expected,
348 trampoline: trampoline_image,
349 signature,
350 module_id: spec.module_id.clone(),
351 #[cfg(test)]
352 image_probe: None,
353 #[cfg(test)]
354 image_read_delay: spec
355 .env
356 .iter()
357 .find(|(key, _)| key == "SUBC_TEST_PRIVACY_IMAGE_DELAY_MS")
358 .map(|(_, millis)| Duration::from_millis(millis.parse().unwrap())),
359 #[cfg(test)]
360 confirmation_pause: spec
361 .env
362 .iter()
363 .find(|(key, _)| key == "SUBC_TEST_BEFORE_EXEC_CONFIRM")
364 .map(|(_, address)| (address.clone(), None)),
365 }),
366 ack,
367 ))
368}
369
370#[cfg(unix)]
371type SpawnRegistrationChannel = std::os::unix::net::UnixStream;
372#[cfg(windows)]
373type SpawnRegistrationChannel = subc_os::registration_channel::RegistrationPipe;
374#[cfg(test)]
375type CapturedRegistrationChannels =
376 Arc<Mutex<Option<Vec<(Arc<RegistrationSpawn>, CapturedRegistrationEndpoint)>>>>;
377#[cfg(test)]
378struct CapturedRegistrationEndpoint {
379 _channel: SpawnRegistrationChannel,
380}
381#[cfg(test)]
382impl fmt::Debug for CapturedRegistrationEndpoint {
383 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
384 f.write_str("CapturedRegistrationEndpoint")
385 }
386}
387
388struct SupervisedChild {
389 registration_spawn: Option<Arc<RegistrationSpawn>>,
390 #[cfg(any(unix, windows))]
392 registration_channel: Option<SpawnRegistrationChannel>,
393 live_program_binding: Option<Arc<content_binding::LiveProgramBinding>>,
394 registered_config_connection: Option<ConnectionId>,
395 admission_base: Option<subc_config::Digest>,
396 registration_declaration: Option<String>,
397 _program_binding: Option<ProgramBindingPublication>,
398 subtree_target: crate::subtree_resources::Target,
399 child: containment::ProcessChild,
400 exec: crate::activity::ExecOwner,
401 #[cfg(windows)]
402 nonce_delivery: Option<subc_os::LaunchNoncePipeDelivery>,
403 #[cfg(target_os = "macos")]
404 privacy_exec: Option<PrivacyExec>,
405 #[cfg(target_os = "macos")]
412 report_ready: Arc<OnceLock<()>>,
413 spawn_failure: Option<String>,
416 admission_kill_sent: bool,
419 protocol: ModuleProtocol,
424 #[cfg(target_os = "linux")]
431 module_id: String,
432 #[cfg(target_os = "linux")]
433 cgroup_placement: Option<subc_cgroup::Placement>,
434 #[cfg(target_os = "linux")]
435 unresolved_cgroup: Option<ordinary_cgroup::Unresolved>,
436 #[cfg(windows)]
459 job: Option<Arc<Mutex<subc_jobobject::JobObject>>>,
460 stdout_pump: Option<tokio::sync::oneshot::Receiver<()>>,
461 stderr_pump: Option<StderrPump>,
462 #[cfg(unix)]
463 capture_stop: Option<crate::child_output::StopReaders>,
464 #[cfg(unix)]
465 late_output_lost: bool,
466 stderr_ring: Arc<Mutex<StderrRing>>,
467 spawned_at: Instant,
470 config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
471 registration_deadline: Option<Instant>,
474 registration_watch: Option<RegistrationWatch>,
475 spawned_at_ms: u64,
476 spawned_from: PathBuf,
477 launch_spec_digest: LaunchSpecDigest,
478 spawned_file_identity: Option<SpawnedFileIdentity>,
479 process_start_time: Option<u64>,
480 process_identity: Option<ProcessIdentity>,
481 pid: u32,
482 roster_guard: Option<crate::child_roster::RosterGuard>,
485}
486
487impl SupervisedChild {
488 fn retire_registration(&self) {
489 if let Some(spawn) = &self.registration_spawn {
494 spawn.retire();
495 } else if let Some(binding) = &self._program_binding {
496 binding.retire();
497 }
498 #[cfg(unix)]
499 if let Some(channel) = &self.registration_channel {
500 let _ = channel.shutdown(std::net::Shutdown::Both);
501 }
502 #[cfg(windows)]
503 if let Some(channel) = &self.registration_channel {
504 if let Ok(shutdown) = channel.shutdown_handle() {
505 shutdown.shutdown();
506 }
507 }
508 }
509 fn registered_since_spawn(&self) -> bool {
510 self.registration_watch
511 .as_ref()
512 .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
513 }
514
515 fn awaiting_registration(&self) -> bool {
516 let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
520 !admission_failed && !self.registered_since_spawn()
521 }
522
523 fn id(&self) -> Option<u32> {
524 Some(self.pid)
525 }
526
527 fn process_identity(&self) -> Option<ProcessIdentity> {
528 self.process_identity
529 }
530
531 fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
532 let result = self.child.try_wait();
533 if !matches!(result, Ok(None)) {
534 self.retire_registration();
535 #[cfg(any(unix, windows))]
536 self.registration_channel.take();
537 if let Some(binding) = &self._program_binding {
538 binding.retire();
539 }
540 }
541 result
542 }
543
544 async fn wait(&mut self) -> io::Result<ExitStatus> {
545 #[cfg(target_os = "macos")]
546 self.confirm_privacy_exec().await;
547 let result = self.child.wait().await;
555 self.retire_registration();
556 #[cfg(any(unix, windows))]
557 self.registration_channel.take();
558 if let Some(binding) = &self._program_binding {
561 binding.retire();
562 }
563 #[cfg(all(test, target_os = "linux"))]
564 if let Some(binding) = &self._program_binding {
565 binding.pause_after_wait_for_test().await;
566 }
567 result
568 }
569
570 async fn finish_exit(&mut self, carry: bool) -> io::Result<()> {
571 self.retire_registration();
572 if let Some(binding) = self._program_binding.take() {
574 binding.retire();
575 }
576 if !carry && self.child.container().is_some() {
577 self.child.terminate_container().await;
578 }
579 self.child.reap().await?;
580 #[cfg(target_os = "linux")]
581 self.cleanup_ordinary_cgroup().await;
582 self.release_roster();
583 Ok(())
584 }
585
586 #[cfg(target_os = "macos")]
587 async fn confirm_privacy_exec(&mut self) {
588 if self
589 .privacy_exec
590 .as_ref()
591 .is_some_and(|pending| pending.content_check.is_some())
592 {
593 self.finish_privacy_content_check().await;
594 return;
595 }
596 let Some(pending) = &mut self.privacy_exec else {
597 return;
598 };
599 let result = tokio::time::timeout_at(pending.deadline, async {
600 let mut record = Vec::new();
601 loop {
602 let mut ready = pending.reader.readable().await?;
603 let read = ready.try_io(|reader| {
604 use std::io::Read;
605 let mut reader = reader.get_ref();
606 let mut buffer = [0u8; 256];
607 reader.read(&mut buffer).map(|count| (count, buffer))
608 });
609 match read {
610 Ok(Ok((0, _))) => return Ok::<_, io::Error>(record),
611 Ok(Ok((count, buffer))) => {
612 if record.len() + count > 1024 {
613 return Err(io::Error::other(
614 "privacy exec refusal record is too long",
615 ));
616 }
617 record.extend_from_slice(&buffer[..count]);
618 }
619 Ok(Err(error)) => return Err(error),
620 Err(_) => continue,
621 }
622 }
623 })
624 .await;
625 #[cfg(test)]
626 let result = if let Some((address, stream)) = &mut pending.confirmation_pause {
627 use tokio::io::{AsyncReadExt, AsyncWriteExt};
628 if stream.is_none() {
629 *stream = Some(
630 tokio::net::TcpStream::connect(address.as_str())
631 .await
632 .unwrap(),
633 );
634 stream.as_mut().unwrap().write_all(b"R").await.unwrap();
635 stream
636 .as_mut()
637 .unwrap()
638 .write_all(&self.pid.to_ne_bytes())
639 .await
640 .unwrap();
641 }
642 let mut reply = [0];
643 stream
644 .as_mut()
645 .unwrap()
646 .read_exact(&mut reply)
647 .await
648 .unwrap();
649 pending.confirmation_pause = None;
650 if &reply == b"F" {
651 Ok(Err(io::Error::other("injected late exec refusal")))
652 } else {
653 assert_eq!(&reply, b"X");
654 result
655 }
656 } else {
657 result
658 };
659 let waited = if matches!(&result, Ok(Ok(record)) if record.is_empty()) {
664 Some(self.try_wait())
665 } else {
666 None
667 };
668 let pending = self.privacy_exec.as_ref().expect("pending exec");
669 let cause = match result {
670 Err(_) => Some("privacy identity trampoline did not exec within 5s".to_string()),
671 Ok(Err(error)) => Some(format!(
672 "privacy identity exec acknowledgement failed: {error}"
673 )),
674 Ok(Ok(record)) if !record.is_empty() => Some(
675 std::str::from_utf8(&record)
676 .ok()
677 .and_then(|record| {
678 record
679 .trim()
680 .strip_prefix(subc_os::privacy_identity::EXEC_REFUSAL_TAG)
681 })
682 .filter(|cause| !cause.is_empty())
683 .unwrap_or("invalid privacy exec refusal record")
684 .to_string(),
685 ),
686 Ok(Ok(_)) if !pending.gated => match waited.expect("exec EOF checked child") {
687 Ok(Some(_)) => None,
688 Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
689 Ok(None) => {
690 #[cfg(test)]
691 if let Some(delay) = pending.image_read_delay {
692 tokio::time::sleep(delay).await;
693 }
694 let image = observe_spawned_image(self.pid);
695 #[cfg(test)]
696 let image = pending.image_probe.map_or(image, |probe| probe(self.pid));
697 if let Some(image) = image.filter(|image| {
701 image.executable.is_some() && image.executable != pending.trampoline
702 }) {
703 match self
704 .roster_guard
705 .as_ref()
706 .map(|guard| guard.confirm_executable(image))
707 .transpose()
708 {
709 Err(error) => Some(format!(
710 "could not durably record confirmed module image: {error}"
711 )),
712 Ok(_) => {
713 let _ = self.report_ready.set(());
714 None
715 }
716 }
717 } else if image.is_none()
718 || image.is_some_and(|image| image.executable.is_none())
719 {
720 match tokio::time::timeout_at(pending.deadline, self.child.wait()).await {
723 Ok(result) => {
724 self.retire_registration();
725 self.registration_channel.take();
726 if let Some(binding) = &self._program_binding {
727 binding.retire();
728 }
729 result.err().map(|error| format!("privacy identity trampoline wait failed: {error}"))
730 }
731 Err(_) => Some("privacy identity module executable remained unreadable until the 5s exec deadline".to_string()),
732 }
733 } else {
734 Some("privacy identity trampoline did not exec the module".to_string())
735 }
736 }
737 },
738 Ok(Ok(_)) => match waited.expect("exec EOF checked child") {
739 Ok(Some(_)) => {
740 Some("privacy identity target exited before suspended admission".to_string())
741 }
742 Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
743 Ok(None) => {
744 let stopped = tokio::time::timeout_at(pending.deadline, async {
747 loop {
748 if subc_os::privacy_identity::SuspendedSignature::is_suspended(
749 self.pid,
750 )? {
751 return Ok::<_, io::Error>(());
752 }
753 tokio::time::sleep(Duration::from_millis(1)).await;
754 }
755 })
756 .await;
757 match stopped {
758 Err(_) => {
759 Some("privacy identity target was not suspended within 5s".to_string())
760 }
761 Ok(Err(error)) => Some(format!(
762 "privacy identity suspended target unavailable: {error}"
763 )),
764 Ok(Ok(())) => {
765 let image = observe_spawned_image(self.pid);
766 if image.is_some_and(|image| {
767 image.executable.is_some()
768 && image.executable != pending.trampoline
769 && image.executable == pending.expected
770 }) {
771 None
772 } else {
773 Some("privacy identity trampoline executable mismatch: expected the suspended module program".to_string())
774 }
775 }
776 }
777 }
778 },
779 };
780 #[cfg(test)]
781 if let Some(binding) = &self._program_binding {
782 binding.pause_after_wait_for_test().await;
783 }
784 if cause.is_none() && pending.gated {
785 let publication = pending.admission_binding.clone();
786 let live = self.live_program_binding.clone();
787 let signature = Arc::clone(pending.signature.as_ref().expect("gated signature"));
788 let pid = self.pid;
789 let gated = pending.gated;
790 self.privacy_exec
791 .as_mut()
792 .expect("pending exec")
793 .content_check = Some(tokio::task::spawn_blocking(move || {
794 signature.verify(pid).map_err(|error| {
795 crate::config_gate::GateError::new("program_refused", error)
796 })?;
797 if !gated {
798 return Ok(());
799 }
800 match (publication, live) {
801 (Some(publication), _) => publication.verify(),
802 (None, Some(live)) => live.check(),
803 _ => Err(crate::config_gate::GateError::new(
804 "config_delivery_deferred",
805 "live program witness is unavailable",
806 )),
807 }
808 }));
809 self.finish_privacy_content_check().await;
810 } else {
811 self.finish_privacy_exec(cause);
812 }
813 }
814
815 #[cfg(target_os = "macos")]
816 async fn finish_privacy_content_check(&mut self) {
817 let result = self
818 .privacy_exec
819 .as_mut()
820 .expect("pending exec")
821 .content_check
822 .as_mut()
823 .expect("pending content check")
824 .await;
825 let cause = match result {
826 Ok(Ok(())) => None,
827 Ok(Err(error)) => Some(format!("{}: {}", error.code, error.detail)),
828 Err(error) => Some(format!(
829 "config_delivery_deferred: content check stopped: {error}"
830 )),
831 };
832 self.finish_privacy_exec(cause);
833 }
834
835 #[cfg(target_os = "macos")]
836 fn finish_privacy_exec(&mut self, mut cause: Option<String>) {
837 let mut pending = self.privacy_exec.take().expect("pending exec");
838 if cause.is_none() && pending.gated {
839 let admission = (|| -> io::Result<()> {
840 let image = observe_spawned_image(self.pid)
841 .filter(|image| image.executable == pending.expected)
842 .ok_or_else(|| io::Error::other("suspended executable mismatch"))?;
843 if let Some(guard) = &self.roster_guard {
844 guard.confirm_executable(image)?;
845 }
846 pending
847 .signature
848 .as_ref()
849 .expect("gated signature")
850 .resume(self.pid)?;
851 let _ = self.report_ready.set(());
852 info!(module_id = %pending.module_id, pid = self.pid,
853 "verified suspended module resumed with own privacy identity");
854 Ok(())
855 })();
856 if let Err(error) = admission {
857 cause = Some(format!("program_refused: {error}"));
858 }
859 }
860 if cause.is_some() {
861 if let Some(spawn) = &self.registration_spawn {
862 spawn.refuse();
863 }
864 if let Some(binding) = &mut pending.admission_binding {
865 binding.reject();
866 }
867 } else if let Some(spawn) = &self.registration_spawn {
868 spawn.ready();
869 }
870 self.exec.0.finish(if cause.is_some() {
873 crate::activity::ExecState::Refused
874 } else {
875 crate::activity::ExecState::CommittedExec
876 });
877 if let Some(cause) = cause {
878 warn!(module_id = %pending.module_id, pid = self.pid, %cause, "privacy identity trampoline refused module spawn");
879 self.spawn_failure = Some(
880 if pending.gated
881 && (cause.contains("executable mismatch")
882 || cause.starts_with("program_refused:"))
883 {
884 format!("program_refused: {cause}")
885 } else if pending.gated {
886 format!("config_delivery_deferred: {cause}")
887 } else {
888 cause
889 },
890 );
891 let _ = self.start_admission_kill();
894 }
895 }
896
897 fn release_roster(&mut self) {
901 let _guard = self.roster_guard.take();
902 #[cfg(target_os = "linux")]
903 if let (Some(unresolved), Some(guard)) = (self.unresolved_cgroup.take(), _guard) {
904 unresolved.retain(guard);
905 }
906 }
907
908 fn exit_cleanup_detail(&self, detail: Option<String>) -> Option<String> {
909 #[cfg(unix)]
910 let detail = if self.late_output_lost {
911 Some(match detail {
912 Some(detail) => {
913 format!("{detail}; late child output lost: capture pipes did not close")
914 }
915 None => "late child output lost: capture pipes did not close".into(),
916 })
917 } else {
918 detail
919 };
920 #[cfg(target_os = "linux")]
921 if let Some(unresolved) = &self.unresolved_cgroup {
922 return Some(match detail {
923 Some(detail) => format!("{detail}; {}", unresolved.detail()),
924 None => unresolved.detail(),
925 });
926 }
927 detail
928 }
929
930 fn group_drain_budget(&self, budget: Duration, _notice: StopNotice) -> Duration {
931 #[cfg(unix)]
932 if self.child.plain_group.is_some() && _notice != StopNotice::SentOverConnection {
933 return budget.min(plain_group::TERM_GRACE);
934 }
935 budget
936 }
937
938 fn start_kill(&mut self) -> io::Result<()> {
951 self.retire_registration();
952 if let Some(container) = self.child.container() {
953 container.hard_kill();
954 return self.kill_leader();
955 }
956 #[cfg(windows)]
957 if let Some(job) = &self.job {
958 if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
959 debug!(
960 error = %error,
961 "job termination failed; the direct-child kill still owns the outcome"
962 );
963 }
964 }
965 #[cfg(target_os = "linux")]
966 kill_module_cgroup(self.cgroup_placement.as_ref(), &self.module_id);
967 self.child.start_kill()
968 }
969
970 fn kill_leader(&mut self) -> io::Result<()> {
971 self.retire_registration();
972 self.child.start_kill()
973 }
974
975 fn start_admission_kill(&mut self) -> io::Result<()> {
976 self.retire_registration();
977 #[cfg(windows)]
978 let result = {
979 let result = self
982 .spawned_file_identity
983 .as_ref()
984 .and_then(|identity| identity.windows_image.as_ref())
985 .ok_or_else(|| io::Error::other("admission child handle unavailable"))
986 .and_then(|image| {
987 image.process().terminate_with_exit_code(
988 admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE as u32,
989 )
990 });
991 if let Some(container) = self.child.container() {
992 container.hard_kill();
993 } else if let Some(job) = &self.job {
994 if let Err(error) = job.lock().unwrap_or_else(|p| p.into_inner()).terminate() {
995 debug!(%error, "job termination failed after admission leader termination");
996 }
997 }
998 result
999 };
1000 #[cfg(not(windows))]
1001 let result = self.start_kill().map(|()| true);
1002 self.admission_kill_sent |= result?;
1003 Ok(())
1004 }
1005
1006 async fn drain_stderr(&mut self, module_id: &str) {
1007 #[cfg(unix)]
1008 if self.child.plain_group.is_some() {
1009 self.drain_plain_capture(module_id).await;
1010 return;
1011 }
1012 #[cfg(target_os = "linux")]
1013 self.cleanup_ordinary_cgroup().await;
1014 if let Some(pump) = self.stdout_pump.take() {
1015 settle_stdout_pump(module_id, pump, STDERR_PUMP_DRAIN_TIMEOUT).await;
1016 }
1017
1018 let Some(pump) = self.stderr_pump.take() else {
1019 return;
1020 };
1021 settle_stderr_pump(
1022 module_id,
1023 &self.stderr_ring,
1024 pump,
1025 STDERR_PUMP_DRAIN_TIMEOUT,
1026 )
1027 .await;
1028 }
1029}
1030
1031async fn settle_stdout_pump<E: std::fmt::Display>(
1034 module_id: &str,
1035 pump: impl std::future::Future<Output = Result<(), E>>,
1036 bound: Duration,
1037) {
1038 match timeout(bound, pump).await {
1039 Ok(Ok(())) => {}
1040 Ok(Err(error)) => {
1041 warn!(module_id, error = %error, "stdout pump ended unexpectedly");
1042 }
1043 Err(_) => {
1044 warn!(
1045 module_id,
1046 waited = ?bound,
1047 "stdout of the exited process has not finished capture; the reader and writer continue without delaying restart"
1048 );
1049 }
1050 }
1051}
1052
1053async fn settle_stderr_pump<E: std::fmt::Display>(
1057 module_id: &str,
1058 ring: &Arc<Mutex<StderrRing>>,
1059 pump: StderrPump<impl std::future::Future<Output = Result<(), E>>>,
1060 bound: Duration,
1061) {
1062 let lock = || ring.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1063 let StderrPump { task, generation } = pump;
1064 lock().retire_pump(generation);
1065 match timeout(bound, task).await {
1066 Ok(Ok(())) => {}
1067 Ok(Err(err)) => {
1068 let mut ring = lock();
1069 ring.mark_incomplete_from(generation, format!("stderr pump ended unexpectedly: {err}"));
1070 ring.finish_pump(generation);
1071 warn!(module_id, error = %err, "stderr pump ended before clean EOF");
1072 }
1073 Err(_) => {
1074 lock().mark_pump_late(
1075 generation,
1076 format!(
1077 "stderr of the exited process had not reached EOF or finished queued capture \
1078 {bound:?} after it was retired; retained lines go in that process's section"
1079 ),
1080 );
1081 warn!(
1082 module_id,
1083 waited = ?bound,
1084 "stderr of the exited process has not finished capture; the reader and writer continue without delaying restart"
1085 );
1086 }
1087 }
1088}
1089
1090fn registration_release_events() -> &'static watch::Sender<u64> {
1091 static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1092 EVENTS.get_or_init(|| {
1093 let (sender, _receiver) = watch::channel(0);
1094 sender
1095 })
1096}
1097
1098pub(crate) fn notify_registration_release() {
1099 let events = registration_release_events();
1100 let next_generation = (*events.borrow()).wrapping_add(1);
1101 events.send_replace(next_generation);
1102}
1103
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1106#[non_exhaustive]
1107pub enum ScriptRuntime {
1108 Bun,
1109 Python,
1110}
1111
1112impl ScriptRuntime {
1113 pub const fn as_str(self) -> &'static str {
1114 match self {
1115 Self::Bun => "bun",
1116 Self::Python => "python",
1117 }
1118 }
1119}
1120
1121#[derive(Debug, Clone, PartialEq, Eq)]
1123#[non_exhaustive]
1124pub struct ScriptEntry {
1125 pub runtime: ScriptRuntime,
1126 pub path: PathBuf,
1127}
1128
1129impl ScriptEntry {
1130 pub fn new(runtime: ScriptRuntime, path: PathBuf) -> Self {
1131 Self { runtime, path }
1132 }
1133}
1134
1135#[derive(Debug, Clone, PartialEq, Eq)]
1137pub struct ModuleSpec {
1138 pub module_id: String,
1139 pub program: PathBuf,
1140 pub script: Option<ScriptEntry>,
1142 pub args: Vec<String>,
1143 pub env: Vec<(String, String)>,
1144 pub reserved: bool,
1149 pub reserved_prefixes: Vec<String>,
1154 pub protocol: ModuleProtocol,
1173 pub overlap: ModuleOverlap,
1178 pub carry_containment: bool,
1182}
1183
1184#[derive(Clone, PartialEq, Eq)]
1187pub(crate) struct LaunchSpecDigest([u8; 32]);
1188
1189impl fmt::Debug for LaunchSpecDigest {
1190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191 f.write_str("LaunchSpecDigest([redacted])")
1192 }
1193}
1194
1195impl LaunchSpecDigest {
1196 pub(crate) fn from_spec(spec: &ModuleSpec) -> Self {
1197 fn field(hash: &mut Sha256, bytes: &[u8]) {
1198 hash.update((bytes.len() as u64).to_le_bytes());
1199 hash.update(bytes);
1200 }
1201 let mut hash = Sha256::new();
1202 if let Some(script) = &spec.script {
1203 field(
1204 &mut hash,
1205 match script.runtime {
1206 ScriptRuntime::Bun => b"bun-script",
1207 ScriptRuntime::Python => b"python-script",
1208 },
1209 );
1210 field(&mut hash, script.path.as_os_str().as_encoded_bytes());
1211 }
1212 if let Some(program) = spec.program.to_str() {
1213 field(&mut hash, b"utf8-program");
1214 field(&mut hash, program.as_bytes());
1215 } else {
1216 #[cfg(unix)]
1219 {
1220 use std::os::unix::ffi::OsStrExt;
1221 field(&mut hash, b"unix-program");
1222 field(&mut hash, spec.program.as_os_str().as_bytes());
1223 }
1224 #[cfg(windows)]
1225 {
1226 use std::os::windows::ffi::OsStrExt;
1227 field(&mut hash, b"windows-program");
1228 let bytes = spec
1229 .program
1230 .as_os_str()
1231 .encode_wide()
1232 .flat_map(u16::to_le_bytes)
1233 .collect::<Vec<_>>();
1234 field(&mut hash, &bytes);
1235 }
1236 #[cfg(not(any(unix, windows)))]
1237 field(&mut hash, spec.program.to_string_lossy().as_bytes());
1238 }
1239 hash.update((spec.args.len() as u64).to_le_bytes());
1240 for arg in &spec.args {
1241 field(&mut hash, arg.as_bytes());
1242 }
1243 let mut env = spec.env.iter().collect::<Vec<_>>();
1244 env.sort_unstable();
1245 hash.update((env.len() as u64).to_le_bytes());
1246 for (key, value) in env {
1247 field(&mut hash, key.as_bytes());
1248 field(&mut hash, value.as_bytes());
1249 }
1250 field(
1251 &mut hash,
1252 match spec.protocol {
1253 ModuleProtocol::Subc => b"subc",
1254 ModuleProtocol::None => b"none",
1255 },
1256 );
1257 Self(hash.finalize().into())
1258 }
1259}
1260
1261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1268pub enum ModuleOverlap {
1269 #[default]
1271 Exclusive,
1272 Safe,
1284}
1285
1286impl ModuleOverlap {
1287 pub fn as_str(self) -> &'static str {
1288 match self {
1289 Self::Exclusive => "exclusive",
1290 Self::Safe => "safe",
1291 }
1292 }
1293}
1294
1295pub const SUBC_SPAWN_ROLE_ENV: &str = "SUBC_SPAWN_ROLE";
1305pub const SPAWN_ROLE_SWAP_CANDIDATE: &str = "swap_candidate";
1307pub const DEFAULT_SWAP_READY_TIMEOUT: Duration = Duration::from_secs(100);
1312
1313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1331pub struct RestartPolicy {
1332 pub max_restarts: u32,
1333 pub backoff: Duration,
1336 pub max_backoff: Duration,
1338 pub window: Duration,
1342}
1343
1344impl RestartPolicy {
1345 pub fn new(max_restarts: u32, backoff: Duration) -> Self {
1349 Self {
1350 max_restarts,
1351 backoff,
1352 max_backoff: DEFAULT_MAX_BACKOFF,
1353 window: DEFAULT_RESTART_WINDOW,
1354 }
1355 }
1356
1357 pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
1358 self.max_backoff = max_backoff;
1359 self
1360 }
1361
1362 pub fn with_window(mut self, window: Duration) -> Self {
1363 self.window = window;
1364 self
1365 }
1366
1367 fn delay_for_restart(&self, restart_in_window: u32) -> Duration {
1372 if self.backoff.is_zero() || self.max_backoff.is_zero() {
1373 return Duration::ZERO;
1374 }
1375
1376 let mut delay = self.backoff;
1377 for _ in 0..restart_in_window {
1378 if delay >= self.max_backoff {
1379 return self.max_backoff;
1380 }
1381 delay = delay
1382 .checked_mul(10)
1383 .unwrap_or(self.max_backoff)
1384 .min(self.max_backoff);
1385 }
1386 delay.min(self.max_backoff)
1387 }
1388
1389 fn budget_exhausted_detail(&self) -> String {
1394 format!(
1395 "crash budget exhausted: max_restarts={} within window_secs={}",
1396 self.max_restarts,
1397 self.window.as_secs()
1398 )
1399 }
1400}
1401
1402impl Default for RestartPolicy {
1403 fn default() -> Self {
1404 Self {
1405 max_restarts: DEFAULT_MAX_RESTARTS,
1406 backoff: DEFAULT_BACKOFF,
1407 max_backoff: DEFAULT_MAX_BACKOFF,
1408 window: DEFAULT_RESTART_WINDOW,
1409 }
1410 }
1411}
1412
1413#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1414struct CrashRestartSchedule {
1415 restart_in_window: u32,
1416 delay: Duration,
1417}
1418
1419fn daemon_will_restart(
1426 state: &mut SupervisorSnapshot,
1427 policy: &RestartPolicy,
1428 now: Instant,
1429) -> bool {
1430 state.enabled && state.crash_restarts_in_window(policy.window, now) < policy.max_restarts
1431}
1432
1433const DEFAULT_HEALTH_CADENCE: Duration = Duration::from_secs(30);
1434const DEFAULT_HEALTH_DEADLINE: Duration = Duration::from_secs(5);
1435const DEFAULT_HEALTH_FAILURE_THRESHOLD: u32 = 3;
1436const MAX_HEALTH_METRICS_BYTES: usize = 16 * 1024;
1437
1438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1439pub enum HealthAction {
1440 Report,
1441 Restart,
1442 Alert,
1443}
1444
1445impl fmt::Display for HealthAction {
1446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1447 f.write_str(match self {
1448 Self::Report => "report",
1449 Self::Restart => "restart",
1450 Self::Alert => "alert",
1451 })
1452 }
1453}
1454
1455#[derive(Debug, Clone, PartialEq, Eq)]
1456pub struct HealthConfig {
1457 pub http: Option<String>,
1461 pub cadence: Duration,
1462 pub deadline: Duration,
1463 pub failure_threshold: u32,
1464 pub on_degraded: HealthAction,
1465 pub on_failing: HealthAction,
1466 pub critical: bool,
1467}
1468
1469impl Default for HealthConfig {
1470 fn default() -> Self {
1471 Self {
1472 http: None,
1473 cadence: DEFAULT_HEALTH_CADENCE,
1474 deadline: DEFAULT_HEALTH_DEADLINE,
1475 failure_threshold: DEFAULT_HEALTH_FAILURE_THRESHOLD,
1476 on_degraded: HealthAction::Report,
1477 on_failing: HealthAction::Report,
1478 critical: false,
1479 }
1480 }
1481}
1482
1483#[derive(Debug, Clone, PartialEq)]
1501pub struct ModuleHealthStatus {
1502 pub status: SupervisorHealthStatus,
1503 pub last_probe_ms: Option<u64>,
1504 pub detail: Option<String>,
1505 pub metrics: Option<Value>,
1506 pub consecutive_failures: u32,
1507 pub late_answer_count: u64,
1510 pub last_late_answer_latency_ms: Option<u64>,
1512 pub last_action: Option<String>,
1513 pub last_action_ms: Option<u64>,
1517}
1518
1519impl Default for ModuleHealthStatus {
1520 fn default() -> Self {
1521 Self {
1522 status: SupervisorHealthStatus::Unknown,
1523 last_probe_ms: None,
1524 detail: None,
1525 metrics: None,
1526 consecutive_failures: 0,
1527 late_answer_count: 0,
1528 last_late_answer_latency_ms: None,
1529 last_action: None,
1530 last_action_ms: None,
1531 }
1532 }
1533}
1534
1535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1537pub enum ModuleState {
1538 Starting,
1539 Running,
1540 Unresponsive,
1541 Restarting,
1542 Draining,
1543 Stopped,
1544 Failed,
1545 Disabled,
1546}
1547
1548impl fmt::Display for ModuleState {
1549 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1550 f.write_str(match self {
1551 Self::Starting => "starting",
1552 Self::Running => "running",
1553 Self::Unresponsive => "unresponsive",
1554 Self::Restarting => "restarting",
1555 Self::Draining => "draining",
1556 Self::Stopped => "stopped",
1557 Self::Failed => "failed",
1558 Self::Disabled => "disabled",
1559 })
1560 }
1561}
1562
1563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1565pub enum ExitKind {
1566 Clean,
1567 Crash,
1568 DeliberateSeverance,
1569}
1570
1571impl From<ExitKind> for TerminalExitKind {
1572 fn from(kind: ExitKind) -> Self {
1573 match kind {
1574 ExitKind::Clean => Self::Clean,
1575 ExitKind::Crash => Self::Crash,
1576 ExitKind::DeliberateSeverance => Self::DeliberateSeverance,
1577 }
1578 }
1579}
1580
1581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1584pub(crate) struct ProcessIdentity {
1585 pub(crate) pid: u32,
1586 pub(crate) start_time: u64,
1587}
1588
1589#[derive(Debug, Clone, PartialEq, Eq)]
1591pub struct ExitReport {
1592 pub kind: ExitKind,
1593 pub code: Option<i32>,
1594 pub signal: Option<i32>,
1595 pub at_ms: u64,
1596}
1597
1598#[derive(Debug, Clone, PartialEq)]
1601pub struct ModuleStatus {
1602 pub(crate) admission_refused: Option<String>,
1603 pub(crate) legacy_registration_spawn: bool,
1604 pub(crate) registration_declaration: Option<String>,
1605 pub module_id: String,
1606 pub stop_reason: Option<ModuleStopReason>,
1609 pub waiting_for_previous_pid: Option<u32>,
1611 pub waiting_for_previous_detail: Option<String>,
1613 pub launch_nonce_source: Option<String>,
1618 pub state: ModuleState,
1619 pub enabled: bool,
1620 pub process_alive: bool,
1621 pub registration_active: bool,
1622 pub protocol: ModuleProtocol,
1627 pub live: bool,
1638 pub restart_count: u32,
1642 pub lifetime_restarts: u32,
1646 pub spawn_generation: u64,
1647 pub swap_outcome: Option<SwapOutcome>,
1649 pub max_restarts: u32,
1654 pub restart_window: Duration,
1658 pub drain_timeout: Duration,
1662 pub restart_backoff: Duration,
1663 pub restart_max_backoff: Duration,
1664 pub pid: Option<u32>,
1669 pub spawned_at_ms: Option<u64>,
1670 pub spawned_from: Option<PathBuf>,
1671 pub(crate) launch_spec_digest: Option<LaunchSpecDigest>,
1672 pub process_start_time: Option<u64>,
1673 pub last_exit: Option<ExitReport>,
1674 pub health: ModuleHealthStatus,
1675}
1676
1677#[cfg(test)]
1678#[derive(Debug, Clone, Copy, PartialEq)]
1679struct ActorSelectCheckpoint {
1680 generation: u64,
1681 turn: u64,
1682 registered_connection: Option<ConnectionId>,
1683 next_probe_at: Option<Instant>,
1684 wake_after: Option<Duration>,
1685}
1686
1687#[derive(Debug, Clone, PartialEq)]
1688struct SupervisorSnapshot {
1689 admission_refused: Option<String>,
1690 config_hold_parked: bool,
1692 config_hold_daemon_initiated: bool,
1695 config_hold_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1697 approved_start_failure: Option<(crate::config_gate::runtime::ApprovalIdentity, String)>,
1699 legacy_registration_spawn: bool,
1700 registration_declaration: Option<String>,
1701 stop_reason: Option<ModuleStopReason>,
1702 config_exit_failed_approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
1703 subtree_target: crate::subtree_resources::Target,
1704 failed_retry: FailedRetry,
1705 exec_outcome: Option<Arc<crate::activity::ExecOutcome>>,
1706 #[cfg(windows)]
1707 pipe_consumed: Option<Arc<OnceLock<()>>>,
1708 #[cfg(test)]
1710 actor_turns: u64,
1711 #[cfg(test)]
1714 actor_select: Option<ActorSelectCheckpoint>,
1715 state: ModuleState,
1716 enabled: bool,
1717 process_alive: bool,
1718 spawned_protocol: Option<ModuleProtocol>,
1719 spawn_failure: Option<String>,
1720 waiting_for_previous_pid: Option<u32>,
1721 waiting_for_previous_detail: Option<String>,
1722 crash_restarts: VecDeque<Instant>,
1728 lifetime_restarts: u32,
1729 spawn_generation: u64,
1738 swap_outcome: Option<SwapOutcome>,
1739 pid: Option<u32>,
1740 #[cfg(target_os = "macos")]
1741 report_ready: Option<Arc<OnceLock<()>>>,
1742 reaped_pid: Option<u32>,
1744 respawn_pending: bool,
1746 coalesced_restart_pending: bool,
1748 spawned_at_ms: Option<u64>,
1749 spawned_from: Option<PathBuf>,
1750 launch_spec_digest: Option<LaunchSpecDigest>,
1751 spawned_file_identity: Option<SpawnedFileIdentity>,
1752 process_start_time: Option<u64>,
1753 deliberate_severance: Option<ProcessIdentity>,
1754 last_exit: Option<ExitReport>,
1755 drain_disposition_detail: Option<String>,
1757 health: ModuleHealthStatus,
1758 last_probe_evidence: Option<HealthProbeEvidence>,
1759 in_alternate_slot: bool,
1764 draining_to_replace: bool,
1771 configuration_updated_since_spawn: bool,
1777}
1778
1779impl SupervisorSnapshot {
1780 fn reported_pid(&self) -> Option<u32> {
1785 #[cfg(target_os = "macos")]
1786 if self
1787 .report_ready
1788 .as_ref()
1789 .is_some_and(|ready| ready.get().is_none())
1790 {
1791 return None;
1792 }
1793 self.pid
1794 }
1795
1796 fn starting() -> Self {
1797 Self::new(ModuleState::Starting, true)
1798 }
1799
1800 fn disabled() -> Self {
1801 Self::new(ModuleState::Disabled, false)
1802 }
1803
1804 fn clear_crash_restarts(&mut self) {
1809 self.crash_restarts.clear();
1810 }
1811
1812 fn new(state: ModuleState, enabled: bool) -> Self {
1813 Self {
1814 admission_refused: None,
1815 config_hold_parked: false,
1816 config_hold_daemon_initiated: false,
1817 config_hold_approval: None,
1818 approved_start_failure: None,
1819 legacy_registration_spawn: false,
1820 registration_declaration: None,
1821 stop_reason: None,
1822 config_exit_failed_approval: None,
1823 subtree_target: crate::subtree_resources::Target::Unavailable("not_running"),
1824 failed_retry: FailedRetry::default(),
1825 exec_outcome: None,
1826 #[cfg(test)]
1827 actor_turns: 0,
1828 #[cfg(test)]
1829 actor_select: None,
1830 state,
1831 enabled,
1832 process_alive: false,
1833 #[cfg(windows)]
1834 pipe_consumed: None,
1835 spawned_protocol: None,
1836 spawn_failure: None,
1837 waiting_for_previous_pid: None,
1838 waiting_for_previous_detail: None,
1839 crash_restarts: VecDeque::new(),
1840 lifetime_restarts: 0,
1841 spawn_generation: 0,
1842 swap_outcome: None,
1843 pid: None,
1844 #[cfg(target_os = "macos")]
1845 report_ready: None,
1846 reaped_pid: None,
1847 respawn_pending: false,
1848 coalesced_restart_pending: false,
1849 spawned_at_ms: None,
1850 spawned_from: None,
1851 launch_spec_digest: None,
1852 spawned_file_identity: None,
1853 process_start_time: None,
1854 deliberate_severance: None,
1855 last_exit: None,
1856 drain_disposition_detail: None,
1857 health: ModuleHealthStatus::default(),
1858 last_probe_evidence: None,
1859 in_alternate_slot: false,
1860 draining_to_replace: false,
1861 configuration_updated_since_spawn: false,
1862 }
1863 }
1864}
1865
1866type SharedSnapshot = Arc<Mutex<SupervisorSnapshot>>;
1867
1868type SpawnSubscriberKey = (ConnectionId, u64);
1869
1870#[derive(Debug)]
1871struct SpawnSubscriber {
1872 version: u8,
1873 frames: mpsc::Sender<Frame>,
1874 lagged: Option<oneshot::Sender<SpawnCursor>>,
1878}
1879
1880#[derive(Debug)]
1881struct SpawnEventState {
1882 daemon_incarnation: String,
1883 seq: u64,
1884 capacity: usize,
1885 live: HashMap<String, LiveSpawn>,
1886 generations: HashMap<String, u64>,
1887 events: VecDeque<SpawnEvent>,
1888 subscribers: HashMap<SpawnSubscriberKey, SpawnSubscriber>,
1889 process_changes: HashMap<String, tokio::sync::watch::Sender<u64>>,
1890}
1891
1892impl Default for SpawnEventState {
1893 fn default() -> Self {
1894 Self {
1895 daemon_incarnation: "unconfigured".to_string(),
1896 seq: 0,
1897 capacity: SPAWN_EVENT_RING_CAPACITY,
1898 live: HashMap::new(),
1899 generations: HashMap::new(),
1900 events: VecDeque::new(),
1901 subscribers: HashMap::new(),
1902 process_changes: HashMap::new(),
1903 }
1904 }
1905}
1906
1907#[derive(Debug, Clone, Default)]
1908struct SpawnEventFeed(
1909 Arc<Mutex<SpawnEventState>>,
1910 #[cfg(test)] Arc<Mutex<Option<std::net::TcpStream>>>,
1911);
1912
1913#[derive(Debug, Clone, PartialEq, Eq)]
1914pub(crate) enum SpawnSubscribeRefusal {
1915 ForeignIncarnation { current: String },
1916 TooOld { oldest: SpawnCursor },
1917 Frame(String),
1918}
1919
1920impl SpawnEventFeed {
1921 fn configure_incarnation(&self, daemon_incarnation: String) {
1922 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1923 state.daemon_incarnation = daemon_incarnation;
1924 state.seq = 0;
1925 state.live.clear();
1926 state.generations.clear();
1927 state.events.clear();
1928 state.subscribers.clear();
1929 for changed in state.process_changes.values() {
1930 changed.send_replace(0);
1931 }
1932 }
1933
1934 fn cursor(state: &SpawnEventState) -> SpawnCursor {
1935 SpawnCursor {
1936 daemon_incarnation: state.daemon_incarnation.clone(),
1937 seq: state.seq,
1938 }
1939 }
1940
1941 fn snapshot(&self) -> SpawnSnapshot {
1942 let state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1943 let mut live = state.live.values().cloned().collect::<Vec<_>>();
1944 live.sort_by(|left, right| left.module_id.cmp(&right.module_id));
1945 SpawnSnapshot {
1946 cursor: Self::cursor(&state),
1947 ring_bound: state.capacity as u64,
1948 live,
1949 }
1950 }
1951
1952 fn allocate_generation_locked(state: &mut SpawnEventState, module_id: &str) -> u64 {
1953 let generation = state
1954 .generations
1955 .get(module_id)
1956 .copied()
1957 .unwrap_or(0)
1958 .checked_add(1)
1959 .expect("spawn generation exhausted");
1960 state.generations.insert(module_id.to_string(), generation);
1961 generation
1962 }
1963
1964 fn allocate_generation(&self, module_id: &str) -> (String, u64) {
1969 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1970 let generation = Self::allocate_generation_locked(&mut state, module_id);
1971 (state.daemon_incarnation.clone(), generation)
1972 }
1973
1974 fn emit_spawned(
1978 &self,
1979 module_id: &str,
1980 allocated: Option<u64>,
1981 pid: u32,
1982 spawned_at_ms: u64,
1983 ) -> u64 {
1984 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
1985 let generation = match allocated {
1986 Some(generation) => generation,
1987 None => Self::allocate_generation_locked(&mut state, module_id),
1988 };
1989 let live = LiveSpawn {
1990 module_id: module_id.to_string(),
1991 spawn_generation: generation,
1992 pid,
1993 spawned_at_ms,
1994 };
1995 state.live.insert(module_id.to_string(), live);
1996 Self::emit_locked(
1997 &mut state,
1998 SpawnEventKind::Spawned,
1999 module_id.to_string(),
2000 generation,
2001 pid,
2002 None,
2003 None,
2004 );
2005 generation
2006 }
2007
2008 fn emit_exited(&self, module_id: &str, exit_code: Option<i32>, exit_signal: Option<i32>) {
2009 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2010 let Some(live) = state.live.remove(module_id) else {
2011 warn!(
2012 module_id,
2013 "terminal record had no live spawn event identity"
2014 );
2015 return;
2016 };
2017 Self::emit_locked(
2018 &mut state,
2019 SpawnEventKind::Exited,
2020 module_id.to_string(),
2021 live.spawn_generation,
2022 live.pid,
2023 exit_code,
2024 exit_signal,
2025 );
2026 }
2027
2028 fn emit_superseded_exited(
2035 &self,
2036 module_id: &str,
2037 spawn_generation: u64,
2038 pid: u32,
2039 exit_code: Option<i32>,
2040 exit_signal: Option<i32>,
2041 ) {
2042 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2043 if state
2044 .live
2045 .get(module_id)
2046 .is_some_and(|live| live.spawn_generation == spawn_generation)
2047 {
2048 state.live.remove(module_id);
2049 }
2050 Self::emit_locked(
2051 &mut state,
2052 SpawnEventKind::Exited,
2053 module_id.to_string(),
2054 spawn_generation,
2055 pid,
2056 exit_code,
2057 exit_signal,
2058 );
2059 }
2060
2061 #[allow(clippy::too_many_arguments)]
2062 fn emit_locked(
2063 state: &mut SpawnEventState,
2064 kind: SpawnEventKind,
2065 module_id: String,
2066 spawn_generation: u64,
2067 pid: u32,
2068 exit_code: Option<i32>,
2069 exit_signal: Option<i32>,
2070 ) {
2071 state.seq = state
2072 .seq
2073 .checked_add(1)
2074 .expect("spawn event sequence exhausted");
2075 let event = SpawnEvent {
2076 cursor: Self::cursor(state),
2077 kind,
2078 module_id,
2079 spawn_generation,
2080 pid,
2081 exit_code,
2082 exit_signal,
2083 };
2084 state
2085 .process_changes
2086 .retain(|_, changed| changed.receiver_count() > 0);
2087 if let Some(changed) = state.process_changes.get(&event.module_id) {
2088 changed.send_replace(state.seq);
2089 }
2090 state.events.push_back(event.clone());
2091 while state.events.len() > state.capacity {
2092 state.events.pop_front();
2093 }
2094 let body = match serde_json::to_vec(&event) {
2095 Ok(body) => body,
2096 Err(error) => {
2097 error!(%error, "failed to serialize supervisor spawn event");
2098 return;
2099 }
2100 };
2101 state.subscribers.retain(|(connection_id, corr), subscriber| {
2102 let frame = Frame::build_with_version(
2103 subscriber.version,
2104 FrameType::StreamData,
2105 control_flags(),
2106 0,
2107 0,
2108 *corr,
2109 body.clone(),
2110 );
2111 match frame {
2112 Ok(frame) => {
2113 if subscriber.frames.try_send(frame).is_ok() {
2114 true
2115 } else {
2116 warn!(connection_id = connection_id.get(), corr, "dropping lagged supervisor spawn subscriber");
2117 if let Some(lagged) = subscriber.lagged.take() {
2118 let _ = lagged.send(event.cursor.clone());
2119 }
2120 false
2121 }
2122 }
2123 Err(error) => {
2124 warn!(connection_id = connection_id.get(), corr, %error, "dropping supervisor spawn subscriber after frame build failure");
2125 false
2126 }
2127 }
2128 });
2129 }
2130
2131 fn subscribe(
2132 &self,
2133 connection_id: ConnectionId,
2134 corr: u64,
2135 version: u8,
2136 since: Option<SpawnCursor>,
2137 sink: FrameSink,
2138 ) -> Result<(), SpawnSubscribeRefusal> {
2139 let (frames, mut receiver) = mpsc::channel(SPAWN_SUBSCRIBER_BUFFER);
2140 let (lagged, mut lagged_rx) = oneshot::channel::<SpawnCursor>();
2141 {
2142 let mut state = self.0.lock().unwrap_or_else(|p| p.into_inner());
2143 let replay = if let Some(since) = since {
2144 if since.daemon_incarnation != state.daemon_incarnation {
2145 return Err(SpawnSubscribeRefusal::ForeignIncarnation {
2146 current: state.daemon_incarnation.clone(),
2147 });
2148 }
2149 if let Some(oldest) = state.events.front().map(|event| event.cursor.clone()) {
2150 if since.seq < oldest.seq.saturating_sub(1) {
2151 return Err(SpawnSubscribeRefusal::TooOld { oldest });
2152 }
2153 }
2154 state
2155 .events
2156 .iter()
2157 .filter(|event| event.cursor.seq > since.seq)
2158 .cloned()
2159 .collect::<Vec<_>>()
2160 } else {
2161 Vec::new()
2162 };
2163 for event in replay {
2164 let body = serde_json::to_vec(&event)
2165 .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2166 let frame = Frame::build_with_version(
2167 version,
2168 FrameType::StreamData,
2169 control_flags(),
2170 0,
2171 0,
2172 corr,
2173 body,
2174 )
2175 .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2176 frames
2177 .try_send(frame)
2178 .map_err(|error| SpawnSubscribeRefusal::Frame(error.to_string()))?;
2179 }
2180 state.subscribers.insert(
2181 (connection_id, corr),
2182 SpawnSubscriber {
2183 version,
2184 frames,
2185 lagged: Some(lagged),
2186 },
2187 );
2188 }
2189 tokio::spawn(async move {
2200 while let Some(frame) = receiver.recv().await {
2201 if sink.send(frame).await.is_err() {
2202 return;
2203 }
2204 }
2205 let Ok(first_undelivered) = lagged_rx.try_recv() else {
2206 return;
2207 };
2208 match spawn_subscriber_lagged_frame(version, corr, first_undelivered) {
2209 Ok(frame) => {
2210 let _ = sink.send(frame).await;
2211 }
2212 Err(error) => {
2213 error!(%error, corr, "failed to build lagged spawn subscriber terminal frame");
2214 }
2215 }
2216 });
2217 Ok(())
2218 }
2219
2220 fn cancel(&self, connection_id: ConnectionId, corr: u64) -> bool {
2221 let Some(subscriber) = self
2222 .0
2223 .lock()
2224 .unwrap_or_else(|p| p.into_inner())
2225 .subscribers
2226 .remove(&(connection_id, corr))
2227 else {
2228 return false;
2229 };
2230 if let Ok(frame) = Frame::build_with_version(
2231 subscriber.version,
2232 FrameType::StreamEnd,
2233 control_flags(),
2234 0,
2235 0,
2236 corr,
2237 Vec::new(),
2238 ) {
2239 tokio::spawn(async move {
2240 let _ = subscriber.frames.send(frame).await;
2241 });
2242 }
2243 true
2244 }
2245
2246 fn remove_connection(&self, connection_id: ConnectionId) {
2247 self.0
2248 .lock()
2249 .unwrap_or_else(|p| p.into_inner())
2250 .subscribers
2251 .retain(|(subscriber_connection, _), _| *subscriber_connection != connection_id);
2252 }
2253
2254 #[cfg(any(test, feature = "test-support"))]
2255 fn set_capacity(&self, capacity: usize) {
2256 self.0.lock().unwrap_or_else(|p| p.into_inner()).capacity = capacity;
2257 }
2258
2259 #[cfg(any(test, feature = "test-support"))]
2260 fn subscriber_count(&self) -> usize {
2261 self.0
2262 .lock()
2263 .unwrap_or_else(|p| p.into_inner())
2264 .subscribers
2265 .len()
2266 }
2267}
2268
2269fn spawn_subscriber_lagged_frame(
2272 version: u8,
2273 corr: u64,
2274 first_undelivered: SpawnCursor,
2275) -> Result<Frame, String> {
2276 let body = serde_json::to_vec(&subc_protocol::ErrorBody {
2278 code: SPAWN_SUBSCRIBER_LAGGED_CODE.to_string(),
2279 message: "spawn subscriber fell behind and was dropped; resubscribe from the last cursor received"
2280 .to_string(),
2281 detail: Some(serde_json::json!({
2282 "first_undelivered_cursor": first_undelivered
2283 })),
2284 })
2285 .map_err(|error| error.to_string())?;
2286 Frame::build_with_version(
2287 version,
2288 FrameType::Error,
2289 crate::router::daemon_error_flags(),
2290 0,
2291 0,
2292 corr,
2293 body,
2294 )
2295 .map_err(|error| error.to_string())
2296}
2297
2298pub trait ModuleProcessLiveness: Send + Sync {
2299 fn process_live(&self, module_id: &str) -> Option<bool>;
2300
2301 fn process_replacing(&self, _module_id: &str) -> bool {
2307 false
2308 }
2309}
2310
2311#[derive(Debug, Clone, Default)]
2313pub struct SupervisorProcessLiveness {
2314 snapshots: Arc<Mutex<HashMap<String, SharedSnapshot>>>,
2315}
2316
2317impl SupervisorProcessLiveness {
2318 pub fn new() -> Self {
2319 Self::default()
2320 }
2321
2322 fn track(&self, module_id: String, snapshot: SharedSnapshot) {
2323 let mut snapshots = self
2324 .snapshots
2325 .lock()
2326 .unwrap_or_else(|poisoned| poisoned.into_inner());
2327 snapshots.insert(module_id, snapshot);
2328 }
2329
2330 fn untrack_if_current(&self, module_id: &str, snapshot: &SharedSnapshot) {
2331 let mut snapshots = self
2332 .snapshots
2333 .lock()
2334 .unwrap_or_else(|poisoned| poisoned.into_inner());
2335 let is_current = snapshots
2336 .get(module_id)
2337 .map(|tracked| Arc::ptr_eq(tracked, snapshot))
2338 .unwrap_or(false);
2339 if is_current {
2340 snapshots.remove(module_id);
2341 }
2342 }
2343}
2344
2345impl ModuleProcessLiveness for SupervisorProcessLiveness {
2346 fn process_live(&self, module_id: &str) -> Option<bool> {
2347 let snapshot = {
2348 let snapshots = self
2349 .snapshots
2350 .lock()
2351 .unwrap_or_else(|poisoned| poisoned.into_inner());
2352 snapshots.get(module_id).cloned()
2353 }?;
2354 let snapshot = snapshot
2355 .lock()
2356 .unwrap_or_else(|poisoned| poisoned.into_inner());
2357 Some(snapshot.state == ModuleState::Running && snapshot.process_alive)
2358 }
2359
2360 fn process_replacing(&self, module_id: &str) -> bool {
2361 let Some(snapshot) = self
2362 .snapshots
2363 .lock()
2364 .unwrap_or_else(|poisoned| poisoned.into_inner())
2365 .get(module_id)
2366 .cloned()
2367 else {
2368 return false;
2369 };
2370 let snapshot = snapshot
2371 .lock()
2372 .unwrap_or_else(|poisoned| poisoned.into_inner());
2373 snapshot.enabled
2374 && match snapshot.state {
2375 ModuleState::Restarting => true,
2376 ModuleState::Draining => snapshot.draining_to_replace,
2377 ModuleState::Starting
2378 | ModuleState::Running
2379 | ModuleState::Unresponsive
2380 | ModuleState::Stopped
2381 | ModuleState::Failed
2382 | ModuleState::Disabled => false,
2383 }
2384 }
2385}
2386
2387#[cfg(test)]
2388#[derive(Debug, Default)]
2389struct ReloadExitRecordGate {
2390 reached: tokio::sync::Notify,
2391 resume: tokio::sync::Notify,
2392}
2393
2394#[derive(Debug, Clone, Copy)]
2395enum RespawnKind {
2396 Spawn,
2397 CrashRestart,
2398 Reload,
2399}
2400
2401#[derive(Debug, Clone)]
2402struct PendingRespawn {
2403 deadline: Instant,
2404 kind: RespawnKind,
2405 daemon_initiated: bool,
2406 approval: Option<crate::config_gate::runtime::ApprovalIdentity>,
2407}
2408
2409impl PendingRespawn {
2410 fn failure_context(&self, runtime: &SupervisorRuntimeConfig) -> FailureContext {
2411 FailureContext {
2412 approval: self.approval.clone(),
2413 ..runtime.failure_context(self.daemon_initiated)
2414 }
2415 }
2416}
2417
2418type ReloadReply = oneshot::Sender<Result<(), SuperviseError>>;
2419
2420#[derive(Debug, Clone)]
2421struct SupervisorRuntimeConfig {
2422 registry: Arc<Registry>,
2423 config_delivery: Option<config_delivery::ConfigDelivery>,
2424 recovery_is_daemon: bool,
2426 start_requester: Option<Principal>,
2427 pending_activity_restart: bool,
2428 provenance_probe: ExecutableIdentityProbe,
2429 scheduled_respawn: Arc<Mutex<Option<PendingRespawn>>>,
2431 deferred_reload_reply: Arc<Mutex<Option<ReloadReply>>>,
2433 restart_policy: RestartPolicy,
2434 register_timeout: Duration,
2435 drain_timeout: Duration,
2438 effective_drain_timeout: Arc<Mutex<Duration>>,
2441 default_drain_timeout: Duration,
2444 health: HealthConfig,
2445 host_health: HostHealth,
2446 connection_file_path: Option<PathBuf>,
2447 capture_logs_dir: Option<PathBuf>,
2448 forwarding: Option<Arc<ForwardingTable>>,
2449 supervisor_handle: Option<SupervisorHandle>,
2452 stderr_ring: Arc<Mutex<StderrRing>>,
2459 terminal_ring: Arc<Mutex<TerminalRing>>,
2460 spawn_events: SpawnEventFeed,
2461 child_roster: ChildRoster,
2462 #[cfg(target_os = "linux")]
2463 cgroup_placement: Option<subc_cgroup::Placement>,
2464 #[cfg(test)]
2465 test_seed_stale_facts_before_enable_spawn: bool,
2466 #[cfg(test)]
2467 test_reload_exit_record_gate: Option<Arc<ReloadExitRecordGate>>,
2468}
2469
2470impl SupervisorRuntimeConfig {
2471 fn failure_context(&self, daemon_initiated: bool) -> FailureContext {
2472 FailureContext {
2473 daemon_initiated,
2474 approval: None,
2475 shutdown: self.child_roster.shutdown_flag(),
2476 }
2477 }
2478}
2479
2480#[derive(Debug, Clone, PartialEq, Eq)]
2481struct SupervisedConfiguration {
2482 spec: ModuleSpec,
2483 enabled: bool,
2484 health: HealthConfig,
2485 register_timeout: Duration,
2486 restart_policy: RestartPolicy,
2487}
2488
2489#[derive(Debug, Clone, Default)]
2495pub struct SupervisorHandle {
2496 #[cfg(test)]
2497 resource_commit_pause: Arc<Mutex<Option<resource_launch::ResourceCommitPause>>>,
2498 #[cfg(test)]
2499 registration_test_channels: CapturedRegistrationChannels,
2500 registration_service: Arc<Mutex<Option<registration::RegistrationService>>>,
2501 registration_connections: Arc<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
2502 registration_launches: Arc<Mutex<Vec<std::sync::Weak<RegistrationSpawn>>>>,
2503 gate_runtime: Arc<Mutex<Option<std::sync::Weak<crate::config_gate::runtime::RuntimeOwner>>>>,
2504 program_bindings: program_binding::ProgramBindings,
2505 #[cfg(test)]
2506 identity_sample_pause: Arc<Mutex<Option<IdentitySamplePause>>>,
2507 #[cfg(all(test, unix))]
2508 plain_identity_policy_pause: Arc<Mutex<Option<(String, IdentitySamplePause)>>>,
2509 host_health: HostHealth,
2510 restart_intent: Arc<Mutex<DaemonRestartIntent>>,
2511 activity: Arc<Mutex<Option<crate::activity::ActivityLedger>>>,
2512 activity_images: Arc<Mutex<HashMap<String, activity::ActivityImage>>>,
2513 modules: Arc<Mutex<HashMap<String, SupervisedModule>>>,
2514 configured_ids: Arc<Mutex<HashSet<String>>>,
2526 spawn_events: SpawnEventFeed,
2527 reserved_nonces: Arc<Mutex<HashMap<String, Option<String>>>>,
2538 implicit_protocol_none: Arc<Mutex<HashSet<String>>>,
2542 removal_tombstones: Arc<Mutex<HashMap<String, u64>>>,
2548 spawn_nonces: Arc<Mutex<HashMap<String, String>>>,
2552 nonce_launches: Arc<Mutex<NonceLaunches>>,
2558 reserved_prefix_owners: Arc<Mutex<HashMap<String, String>>>,
2566 swaps: Arc<Mutex<HashMap<String, OpenSwap>>>,
2572 promotion_observer: PromotionObserverSlot,
2574 operation_lock: Arc<AsyncMutex<()>>,
2578}
2579
2580#[cfg(test)]
2581#[derive(Debug)]
2582struct IdentitySamplePause {
2583 reached: std::sync::mpsc::Sender<()>,
2584 release: std::sync::mpsc::Receiver<()>,
2585}
2586
2587pub(crate) trait SwapPromotionObserver: Send + Sync {
2596 fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration);
2597}
2598
2599#[derive(Clone, Default)]
2603struct PromotionObserverSlot(Arc<Mutex<Option<std::sync::Weak<dyn SwapPromotionObserver>>>>);
2604
2605impl fmt::Debug for PromotionObserverSlot {
2606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2607 f.write_str("PromotionObserverSlot")
2608 }
2609}
2610
2611#[derive(Debug, Clone)]
2613struct OpenSwap {
2614 candidate_nonce: String,
2617 incumbent_nonce: Option<String>,
2620 candidate_admitted: bool,
2624}
2625
2626#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2629pub(crate) enum SwapHelloAdmission {
2630 NotSwapping,
2633 Candidate,
2635 Refused,
2638 ProtocolNone,
2641 ChannelRequired,
2644}
2645
2646#[derive(Debug, Clone, PartialEq, Eq)]
2647pub(crate) enum ReservedHelloRejection {
2648 Exact {
2649 module_id: String,
2650 },
2651 Prefix {
2652 prefix: String,
2653 owner_module_id: String,
2654 },
2655}
2656
2657#[derive(Debug, Default)]
2659pub(crate) struct ReservedHelloVerification {
2660 pub(crate) nonce_verified: bool,
2661 pub(crate) prefix_owner: Option<String>,
2662}
2663
2664#[derive(Debug)]
2665struct DaemonRestartIntent {
2666 expires: Option<Duration>,
2667 window: Duration,
2668}
2669
2670impl Default for DaemonRestartIntent {
2671 fn default() -> Self {
2672 Self {
2673 expires: None,
2674 window: Duration::from_secs(120),
2675 }
2676 }
2677}
2678
2679impl SupervisorHandle {
2680 pub(crate) fn module_is_gated(&self, module: &str) -> bool {
2681 let runtime = {
2682 let Ok(runtime) = self.gate_runtime.lock() else {
2683 return true;
2684 };
2685 runtime.clone()
2686 };
2687 runtime.is_some_and(|runtime| {
2688 runtime
2689 .upgrade()
2690 .is_none_or(|owner| owner.module_is_gated(module))
2691 })
2692 }
2693 pub(crate) fn announce_daemon_restart(&self) -> u64 {
2694 let mut intent = self
2695 .restart_intent
2696 .lock()
2697 .unwrap_or_else(|p| p.into_inner());
2698 intent.expires = Some(subc_uptime::suspend_inclusive_now() + intent.window);
2699 unix_ms_now().saturating_add(intent.window.as_millis() as u64)
2700 }
2701
2702 #[cfg(feature = "test-support")]
2703 pub(crate) fn set_shutdown_intent_window(&self, window: Duration) {
2704 self.restart_intent
2705 .lock()
2706 .unwrap_or_else(|p| p.into_inner())
2707 .window = window;
2708 }
2709
2710 #[cfg(unix)]
2711 fn take_daemon_shutdown_reason(&self) -> RouteCloseReason {
2712 let expiry = self
2713 .restart_intent
2714 .lock()
2715 .unwrap_or_else(|p| p.into_inner())
2716 .expires
2717 .take();
2718 if expiry.is_some_and(|expiry| subc_uptime::suspend_inclusive_now() < expiry) {
2719 RouteCloseReason::Restart
2720 } else {
2721 RouteCloseReason::Disable
2722 }
2723 }
2724
2725 pub fn new() -> Self {
2726 Self::default()
2727 }
2728
2729 pub(crate) fn spawn_snapshot(&self) -> SpawnSnapshot {
2730 self.spawn_events.snapshot()
2731 }
2732
2733 pub(crate) fn subscribe_process_changes(
2736 &self,
2737 module: &str,
2738 ) -> tokio::sync::watch::Receiver<u64> {
2739 let mut state = self
2740 .spawn_events
2741 .0
2742 .lock()
2743 .unwrap_or_else(|p| p.into_inner());
2744 state
2745 .process_changes
2746 .retain(|_, changed| changed.receiver_count() > 0);
2747 let seq = state.seq;
2748 state
2749 .process_changes
2750 .entry(module.into())
2751 .or_insert_with(|| tokio::sync::watch::channel(seq).0)
2752 .subscribe()
2753 }
2754
2755 pub(crate) fn current_spawn(&self, module: &str) -> Option<LiveSpawn> {
2756 self.spawn_events
2757 .0
2758 .lock()
2759 .unwrap_or_else(|p| p.into_inner())
2760 .live
2761 .get(module)
2762 .cloned()
2763 }
2764
2765 pub(crate) fn subscribe_spawns(
2766 &self,
2767 connection_id: ConnectionId,
2768 corr: u64,
2769 version: u8,
2770 since: Option<SpawnCursor>,
2771 sink: FrameSink,
2772 ) -> Result<(), SpawnSubscribeRefusal> {
2773 self.spawn_events
2774 .subscribe(connection_id, corr, version, since, sink)
2775 }
2776
2777 pub(crate) fn cancel_spawn_subscription(&self, connection_id: ConnectionId, corr: u64) -> bool {
2778 self.spawn_events.cancel(connection_id, corr)
2779 }
2780
2781 pub(crate) fn remove_spawn_subscribers(&self, connection_id: ConnectionId) {
2782 self.spawn_events.remove_connection(connection_id);
2783 }
2784
2785 #[cfg(any(test, feature = "test-support"))]
2786 pub fn set_spawn_event_capacity_for_test(&self, capacity: usize) {
2787 assert!(capacity > 0, "spawn event capacity must be non-zero");
2788 self.spawn_events.set_capacity(capacity);
2789 }
2790
2791 #[cfg(any(test, feature = "test-support"))]
2792 pub fn spawn_subscriber_count_for_test(&self) -> usize {
2793 self.spawn_events.subscriber_count()
2794 }
2795
2796 pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
2799 self.spawn_nonces
2800 .lock()
2801 .unwrap_or_else(|poisoned| poisoned.into_inner())
2802 .insert(module_id.to_string(), nonce);
2803 self.refresh_program_binding_nonces(module_id);
2804 }
2805
2806 pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
2809 {
2810 let mut reserved = self
2811 .reserved_nonces
2812 .lock()
2813 .unwrap_or_else(|p| p.into_inner());
2814 self.implicit_protocol_none
2815 .lock()
2816 .unwrap_or_else(|p| p.into_inner())
2817 .remove(module_id);
2818 reserved.insert(module_id.to_string(), Some(nonce));
2819 }
2820 self.refresh_program_binding_nonces(module_id);
2821 }
2822
2823 pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
2825 let mut owners = self
2826 .reserved_prefix_owners
2827 .lock()
2828 .unwrap_or_else(|poisoned| poisoned.into_inner());
2829 owners.retain(|_, owner| owner != owner_module_id);
2830 for prefix in prefixes {
2831 owners.insert(prefix.clone(), owner_module_id.to_string());
2832 }
2833 }
2834
2835 pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
2837 if self.module_is_gated(module_id) {
2838 return None;
2839 }
2840 self.spawn_nonces
2841 .lock()
2842 .unwrap_or_else(|poisoned| poisoned.into_inner())
2843 .get(module_id)
2844 .cloned()
2845 }
2846
2847 #[cfg(all(test, unix))]
2848 pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
2849 self.spawn_nonces.lock().unwrap().contains_key(module)
2850 }
2851
2852 pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
2853 self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
2856 let protocol = self
2857 .get(&spec.module_id)
2858 .and_then(|module| {
2859 let snapshot = module.inner.snapshot.lock().ok()?;
2860 snapshot
2861 .process_alive
2862 .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
2863 })
2864 .unwrap_or(spec.protocol);
2865 self.apply_identity_policy(spec, protocol);
2866 }
2867
2868 #[cfg(all(test, unix))]
2869 pub(crate) fn pause_plain_identity_policy_for_test(
2870 &self,
2871 module: &str,
2872 ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
2873 let (reached, waiting) = std::sync::mpsc::channel();
2874 let (release, paused) = std::sync::mpsc::channel();
2875 *self.plain_identity_policy_pause.lock().unwrap() = Some((
2876 module.to_owned(),
2877 IdentitySamplePause {
2878 reached,
2879 release: paused,
2880 },
2881 ));
2882 (waiting, release)
2883 }
2884
2885 fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
2886 let channel_only = self.module_is_gated(&spec.module_id);
2887 let mut current_nonces = self
2888 .spawn_nonces
2889 .lock()
2890 .unwrap_or_else(|poisoned| poisoned.into_inner());
2891 if protocol == ModuleProtocol::None || channel_only {
2892 current_nonces.remove(&spec.module_id);
2893 }
2894 let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
2895 #[cfg(test)]
2896 if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
2897 pause.reached.send(()).unwrap();
2898 pause.release.recv().unwrap();
2899 }
2900 let mut reserved_nonces = self
2901 .reserved_nonces
2902 .lock()
2903 .unwrap_or_else(|poisoned| poisoned.into_inner());
2904 let mut implicit = self
2905 .implicit_protocol_none
2906 .lock()
2907 .unwrap_or_else(|p| p.into_inner());
2908 if spec.reserved {
2909 implicit.remove(&spec.module_id);
2910 } else if protocol == ModuleProtocol::None {
2911 if !reserved_nonces.contains_key(&spec.module_id) {
2912 implicit.insert(spec.module_id.clone());
2913 }
2914 } else if implicit.remove(&spec.module_id) {
2915 reserved_nonces.remove(&spec.module_id);
2916 }
2917 if spec.reserved || protocol == ModuleProtocol::None {
2918 reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
2923 }
2924 drop(implicit);
2925 drop(reserved_nonces);
2926 drop(current_nonces);
2927 self.refresh_program_binding_nonces(&spec.module_id);
2928 self.removal_tombstones
2932 .lock()
2933 .unwrap_or_else(|poisoned| poisoned.into_inner())
2934 .remove(&spec.module_id);
2935 }
2936
2937 pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
2942 self.reserved_hello_verification(module_id, presented)
2943 .is_ok()
2944 }
2945
2946 pub(crate) fn reserved_hello_verification(
2949 &self,
2950 module_id: &str,
2951 presented: Option<&str>,
2952 ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2953 if self.module_is_gated(module_id) {
2954 return Err(ReservedHelloRejection::Exact {
2955 module_id: module_id.into(),
2956 });
2957 }
2958 self.hello_verification(module_id, presented, false)
2959 }
2960
2961 pub(crate) fn channel_hello_verification(
2962 &self,
2963 module_id: &str,
2964 ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
2965 if self
2966 .get(module_id)
2967 .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
2968 {
2969 return Err(ReservedHelloRejection::Exact {
2970 module_id: module_id.into(),
2971 });
2972 }
2973 let mut verification = self.hello_verification(module_id, None, true)?;
2974 verification.nonce_verified = true;
2975 Ok(verification)
2976 }
2977
2978 pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
2979 self.prefix_claim_publication(owner, module_id).is_some()
2980 }
2981
2982 #[cfg(all(test, unix))]
2983 pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
2984 matches!(
2985 self.reserved_prefix_owners.try_lock(),
2986 Err(std::sync::TryLockError::WouldBlock)
2987 )
2988 }
2989
2990 pub(crate) fn prefix_claim_publication(
2994 &self,
2995 owner: &str,
2996 module_id: &str,
2997 ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
2998 if subc_protocol::manifest::validate_module_id(module_id).is_err()
2999 || self.module_is_gated(module_id)
3000 || self
3001 .reserved_nonces
3002 .lock()
3003 .unwrap_or_else(|p| p.into_inner())
3004 .contains_key(module_id)
3005 {
3006 return None;
3007 }
3008 let owners = self
3009 .reserved_prefix_owners
3010 .lock()
3011 .unwrap_or_else(|p| p.into_inner());
3012 let authorized = owners
3013 .iter()
3014 .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3015 .max_by_key(|(prefix, _)| prefix.len())
3016 .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
3017 authorized.then_some(owners)
3018 }
3019
3020 fn hello_verification(
3021 &self,
3022 module_id: &str,
3023 presented: Option<&str>,
3024 channel: bool,
3025 ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
3026 let nonces = self
3027 .reserved_nonces
3028 .lock()
3029 .unwrap_or_else(|poisoned| poisoned.into_inner());
3030 if let Some(expected) = nonces.get(module_id) {
3031 let authorized = channel
3035 || match expected {
3036 Some(expected) => presented.is_some_and(|p| {
3037 !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
3038 }),
3039 None => false,
3040 };
3041 if authorized {
3042 return Ok(ReservedHelloVerification {
3043 nonce_verified: true,
3044 prefix_owner: None,
3045 });
3046 }
3047 return Err(ReservedHelloRejection::Exact {
3048 module_id: module_id.to_string(),
3049 });
3050 }
3051 drop(nonces);
3052
3053 let matched_prefix = self
3054 .reserved_prefix_owners
3055 .lock()
3056 .unwrap_or_else(|poisoned| poisoned.into_inner())
3057 .iter()
3058 .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
3059 .max_by_key(|(prefix, _)| prefix.len())
3060 .map(|(prefix, owner)| (prefix.clone(), owner.clone()));
3061 let Some((prefix, owner_module_id)) = matched_prefix else {
3062 return Ok(ReservedHelloVerification::default());
3063 };
3064
3065 if module_id.len() == prefix.len()
3066 || (!channel
3067 && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
3068 {
3069 return Err(ReservedHelloRejection::Prefix {
3070 prefix,
3071 owner_module_id,
3072 });
3073 }
3074
3075 let authorized = if channel {
3076 owner_module_id == module_id
3077 } else {
3078 presented.is_some_and(|presented| {
3079 self.spawn_nonces
3080 .lock()
3081 .unwrap_or_else(|poisoned| poisoned.into_inner())
3082 .get(&owner_module_id)
3083 .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
3084 || self.swap_nonce_matches(&owner_module_id, presented)
3087 })
3088 };
3089 if authorized {
3090 Ok(ReservedHelloVerification {
3091 nonce_verified: true,
3092 prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
3093 })
3094 } else {
3095 Err(ReservedHelloRejection::Prefix {
3096 prefix,
3097 owner_module_id,
3098 })
3099 }
3100 }
3101
3102 pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
3107 if self.module_is_gated(module_id) || self.protocol_none(module_id) {
3108 return false;
3109 }
3110 let nonces = self
3111 .spawn_nonces
3112 .lock()
3113 .unwrap_or_else(|poisoned| poisoned.into_inner());
3114 let current = nonces.get(module_id).is_some_and(|expected| {
3115 !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
3116 });
3117 drop(nonces);
3118 current || self.swap_nonce_matches(module_id, presented)
3121 }
3122
3123 fn swap_nonce_matches(&self, module_id: &str, presented: &str) -> bool {
3125 if self.module_is_gated(module_id) || self.protocol_none(module_id) || presented.is_empty()
3126 {
3127 return false;
3128 }
3129 let swaps = self
3130 .swaps
3131 .lock()
3132 .unwrap_or_else(|poisoned| poisoned.into_inner());
3133 swaps.get(module_id).is_some_and(|swap| {
3134 constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes())
3135 || swap.incumbent_nonce.as_deref().is_some_and(|incumbent| {
3136 constant_time_eq(incumbent.as_bytes(), presented.as_bytes())
3137 })
3138 })
3139 }
3140
3141 pub(crate) fn open_swap(&self, module_id: &str, candidate_nonce: String) {
3144 let incumbent_nonce = self
3145 .spawn_nonces
3146 .lock()
3147 .unwrap_or_else(|poisoned| poisoned.into_inner())
3148 .get(module_id)
3149 .cloned();
3150 self.swaps
3151 .lock()
3152 .unwrap_or_else(|poisoned| poisoned.into_inner())
3153 .insert(
3154 module_id.to_string(),
3155 OpenSwap {
3156 candidate_nonce,
3157 incumbent_nonce,
3158 candidate_admitted: false,
3159 },
3160 );
3161 self.refresh_program_binding_nonces(module_id);
3162 }
3163
3164 pub(crate) fn close_swap(&self, module_id: &str) {
3167 self.swaps
3168 .lock()
3169 .unwrap_or_else(|poisoned| poisoned.into_inner())
3170 .remove(module_id);
3171 self.refresh_program_binding_nonces(module_id);
3172 }
3173
3174 pub(crate) fn set_swap_promotion_observer(
3177 &self,
3178 observer: std::sync::Weak<dyn SwapPromotionObserver>,
3179 ) {
3180 *self
3181 .promotion_observer
3182 .0
3183 .lock()
3184 .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(observer);
3185 }
3186
3187 fn notify_swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
3190 let observer = self
3191 .promotion_observer
3192 .0
3193 .lock()
3194 .unwrap_or_else(|poisoned| poisoned.into_inner())
3195 .as_ref()
3196 .and_then(std::sync::Weak::upgrade);
3197 if let Some(observer) = observer {
3198 observer.swap_promoted(registration);
3199 }
3200 }
3201
3202 pub(crate) fn swap_open(&self, module_id: &str) -> bool {
3204 self.swaps
3205 .lock()
3206 .unwrap_or_else(|poisoned| poisoned.into_inner())
3207 .contains_key(module_id)
3208 }
3209
3210 fn promote_swap_nonce(&self, module_id: &str, reserved: bool) {
3215 let candidate_nonce = self
3216 .swaps
3217 .lock()
3218 .unwrap_or_else(|poisoned| poisoned.into_inner())
3219 .get_mut(module_id)
3220 .map(|swap| {
3221 swap.incumbent_nonce = None;
3222 swap.candidate_nonce.clone()
3223 });
3224 self.spawn_nonces
3225 .lock()
3226 .unwrap_or_else(|p| p.into_inner())
3227 .remove(module_id);
3228 {
3229 let mut nonces = self
3230 .reserved_nonces
3231 .lock()
3232 .unwrap_or_else(|p| p.into_inner());
3233 if reserved || nonces.contains_key(module_id) {
3234 nonces.insert(module_id.into(), None);
3235 }
3236 }
3237 if self.module_is_gated(module_id) {
3238 return;
3239 }
3240 let Some(nonce) = candidate_nonce.filter(|nonce| !nonce.is_empty()) else {
3241 return;
3242 };
3243 self.set_spawn_nonce(module_id, nonce.clone());
3244 if reserved {
3245 self.set_reserved_nonce(module_id, nonce);
3246 }
3247 }
3248
3249 pub(crate) fn swap_hello_admission(
3264 &self,
3265 module_id: &str,
3266 presented: Option<&str>,
3267 ) -> SwapHelloAdmission {
3268 if self.protocol_none(module_id) {
3269 return SwapHelloAdmission::ProtocolNone;
3270 }
3271 if self.module_is_gated(module_id) {
3272 return SwapHelloAdmission::ChannelRequired;
3273 }
3274 let swaps = self
3275 .swaps
3276 .lock()
3277 .unwrap_or_else(|poisoned| poisoned.into_inner());
3278 let Some(swap) = swaps.get(module_id) else {
3279 return SwapHelloAdmission::NotSwapping;
3280 };
3281 let Some(presented) = presented.filter(|nonce| !nonce.is_empty()) else {
3282 return SwapHelloAdmission::Refused;
3283 };
3284 if constant_time_eq(swap.candidate_nonce.as_bytes(), presented.as_bytes()) {
3285 return if swap.candidate_admitted {
3286 SwapHelloAdmission::Refused
3287 } else {
3288 SwapHelloAdmission::Candidate
3289 };
3290 }
3291 if swap
3292 .incumbent_nonce
3293 .as_deref()
3294 .is_some_and(|incumbent| constant_time_eq(incumbent.as_bytes(), presented.as_bytes()))
3295 {
3296 return SwapHelloAdmission::NotSwapping;
3297 }
3298 SwapHelloAdmission::Refused
3299 }
3300
3301 fn protocol_none(&self, module: &str) -> bool {
3302 self.get(module)
3303 .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
3304 }
3305
3306 pub(crate) fn with_swap_candidate_admission<T>(
3308 &self,
3309 module_id: &str,
3310 publish: impl FnOnce() -> (T, bool),
3311 ) -> Option<T> {
3312 let mut swaps = self.swaps.lock().unwrap_or_else(|p| p.into_inner());
3313 let swap = swaps
3314 .get_mut(module_id)
3315 .filter(|swap| !swap.candidate_admitted)?;
3316 let (result, admitted) = publish();
3317 swap.candidate_admitted = admitted;
3318 Some(result)
3319 }
3320
3321 pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3323 self.spawn_nonce(module_id)
3324 }
3325
3326 pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
3328 if self.module_is_gated(module_id) {
3329 return None;
3330 }
3331 self.reserved_nonces
3332 .lock()
3333 .unwrap_or_else(|poisoned| poisoned.into_inner())
3334 .get(module_id)
3335 .cloned()
3336 .flatten()
3337 }
3338
3339 pub fn insert(&self, module: SupervisedModule) -> Option<SupervisedModule> {
3340 self.mark_configured(module.module_id());
3344 let mut modules = self
3345 .modules
3346 .lock()
3347 .unwrap_or_else(|poisoned| poisoned.into_inner());
3348 modules.insert(module.module_id().to_string(), module)
3349 }
3350
3351 fn mark_configured(&self, module_id: &str) {
3355 self.update_configured_ids(|ids| {
3356 ids.insert(module_id.to_string());
3357 });
3358 }
3359
3360 fn publish_configured_ids(&self, ids: Option<&HashSet<String>>) {
3361 let owner = self
3362 .gate_runtime
3363 .lock()
3364 .unwrap_or_else(|p| p.into_inner())
3365 .clone()
3366 .and_then(|owner| owner.upgrade());
3367 if let Some(owner) = owner {
3368 owner.observe_supervisor_configured_ids(ids, Arc::downgrade(&self.configured_ids));
3369 }
3370 }
3371
3372 fn update_configured_ids(&self, update: impl FnOnce(&mut HashSet<String>)) {
3373 match self.configured_ids.lock() {
3374 Ok(mut ids) => {
3375 update(&mut ids);
3376 self.publish_configured_ids(Some(&ids));
3379 }
3380 Err(poisoned) => {
3381 update(&mut poisoned.into_inner());
3382 self.publish_configured_ids(None);
3383 }
3384 }
3385 }
3386
3387 fn unmark_configured_unless_rostered(&self, module_id: &str) {
3391 let modules = self
3392 .modules
3393 .lock()
3394 .unwrap_or_else(|poisoned| poisoned.into_inner());
3395 if !modules.contains_key(module_id) {
3396 self.update_configured_ids(|ids| {
3397 ids.remove(module_id);
3398 });
3399 }
3400 }
3401
3402 pub(crate) fn is_configured(&self, module_id: &str) -> bool {
3410 self.configured_ids
3411 .lock()
3412 .unwrap_or_else(|poisoned| poisoned.into_inner())
3413 .contains(module_id)
3414 }
3415
3416 pub fn get(&self, module_id: &str) -> Option<SupervisedModule> {
3417 let modules = self
3418 .modules
3419 .lock()
3420 .unwrap_or_else(|poisoned| poisoned.into_inner());
3421 modules.get(module_id).cloned()
3422 }
3423
3424 pub(crate) fn record_late_health_answer(
3425 &self,
3426 module_id: &str,
3427 latency_ms: u64,
3428 ) -> Result<bool, SuperviseError> {
3429 let Some(module) = self.get(module_id) else {
3430 return Ok(false);
3431 };
3432 self.host_health.record_late_module(module_id);
3433 update_snapshot(&module.inner.snapshot, Some(module_id), |state| {
3434 state.health.late_answer_count = state.health.late_answer_count.saturating_add(1);
3435 state.health.last_late_answer_latency_ms = Some(latency_ms);
3436 state.health.consecutive_failures = 0;
3444 })?;
3445 Ok(true)
3446 }
3447
3448 pub(crate) fn spawn_host_health_monitor(&self) -> JoinHandle<()> {
3449 self.host_health.spawn_monitor()
3450 }
3451
3452 pub fn record_deliberate_severance(&self, module_id: &str) -> Result<bool, SuperviseError> {
3458 let Some(module) = self.get(module_id) else {
3459 return Ok(false);
3460 };
3461 let snapshot = lock_snapshot(&module.inner.snapshot)?;
3462 let Some((pid, start_time)) = snapshot.pid.zip(snapshot.process_start_time) else {
3463 return Ok(false);
3464 };
3465 drop(snapshot);
3466 module.record_deliberate_severance(ProcessIdentity { pid, start_time })
3467 }
3468
3469 pub fn list(&self) -> Vec<SupervisedModule> {
3470 let modules = self
3471 .modules
3472 .lock()
3473 .unwrap_or_else(|poisoned| poisoned.into_inner());
3474 let mut modules = modules.values().cloned().collect::<Vec<_>>();
3475 modules.sort_by(|left, right| left.module_id().cmp(right.module_id()));
3476 modules
3477 }
3478
3479 pub(crate) fn retire(&self, module_id: &str) -> Option<SupervisedModule> {
3480 self.activity_images
3481 .lock()
3482 .unwrap_or_else(|p| p.into_inner())
3483 .remove(module_id);
3484 self.spawn_nonces
3485 .lock()
3486 .unwrap_or_else(|poisoned| poisoned.into_inner())
3487 .remove(module_id);
3488 self.close_swap(module_id);
3489 let mut reserved_nonces = self
3490 .reserved_nonces
3491 .lock()
3492 .unwrap_or_else(|poisoned| poisoned.into_inner());
3493 if reserved_nonces.contains_key(module_id) {
3494 reserved_nonces.insert(module_id.to_string(), None);
3497 }
3498 drop(reserved_nonces);
3499 self.reserved_prefix_owners
3500 .lock()
3501 .unwrap_or_else(|poisoned| poisoned.into_inner())
3502 .retain(|_, owner| owner != module_id);
3503 let removed = self
3504 .modules
3505 .lock()
3506 .unwrap_or_else(|poisoned| poisoned.into_inner())
3507 .remove(module_id);
3508 self.update_configured_ids(|ids| {
3509 ids.remove(module_id);
3510 });
3511 self.remove_program_binding_records(module_id);
3512 removed
3513 }
3514
3515 pub(crate) fn record_rescan_removal(&self, module_id: &str) {
3518 self.removal_tombstones
3519 .lock()
3520 .unwrap_or_else(|poisoned| poisoned.into_inner())
3521 .insert(module_id.to_string(), unix_ms_now());
3522 }
3523
3524 pub(crate) fn removal_tombstone_age_ms(&self, module_id: &str) -> Option<u64> {
3526 self.removal_tombstones
3527 .lock()
3528 .unwrap_or_else(|poisoned| poisoned.into_inner())
3529 .get(module_id)
3530 .copied()
3531 .map(|removed_at_ms| unix_ms_now().saturating_sub(removed_at_ms))
3532 }
3533
3534 pub(crate) fn release_retained_reserved_gate(&self, module_id: &str) -> bool {
3539 if self.get(module_id).is_some() {
3540 return false;
3541 }
3542 let mut reserved_nonces = self
3543 .reserved_nonces
3544 .lock()
3545 .unwrap_or_else(|poisoned| poisoned.into_inner());
3546 if !matches!(reserved_nonces.get(module_id), Some(None)) {
3547 return false;
3548 }
3549 reserved_nonces.remove(module_id);
3550 self.implicit_protocol_none
3551 .lock()
3552 .unwrap_or_else(|p| p.into_inner())
3553 .remove(module_id);
3554 true
3555 }
3556
3557 pub(crate) fn operation_lock(&self) -> Arc<AsyncMutex<()>> {
3558 Arc::clone(&self.operation_lock)
3559 }
3560}
3561
3562#[derive(Debug, Clone)]
3564pub struct Supervisor {
3565 registry: Arc<Registry>,
3566 config_delivery: Option<config_delivery::ConfigDelivery>,
3567 restart_policy: RestartPolicy,
3568 drain_timeout: Duration,
3569 connection_file_path: Option<PathBuf>,
3570 capture_logs_dir: Option<PathBuf>,
3571 forwarding: Option<Arc<ForwardingTable>>,
3572 process_liveness: Arc<SupervisorProcessLiveness>,
3573 supervisor_handle: Option<SupervisorHandle>,
3574 health: HealthConfig,
3575 host_health: HostHealth,
3576 daemon_start_clock: crate::clock::StartClock,
3577 terminal_journal: Option<Arc<crate::terminal_journal::TerminalJournal>>,
3578 spawn_events: SpawnEventFeed,
3579 provenance_probe: ExecutableIdentityProbe,
3580 child_roster: ChildRoster,
3583 #[cfg(target_os = "linux")]
3584 cgroup_placement: Option<subc_cgroup::Placement>,
3585 #[cfg(test)]
3586 test_after_first_spawn: AfterFirstSpawnHook,
3587}
3588
3589pub(crate) struct RegisteredConfiguredModule {
3593 spec: ModuleSpec,
3594 runtime: SupervisorRuntimeConfig,
3595 module: SupervisedModule,
3596 commands: mpsc::Receiver<SupervisorCommand>,
3597}
3598
3599#[cfg(test)]
3605#[derive(Clone, Default)]
3606struct AfterFirstSpawnHook(Option<AfterFirstSpawnFn>);
3607
3608#[cfg(test)]
3609type AfterFirstSpawnFn = Arc<dyn Fn(&str) + Send + Sync>;
3610
3611#[cfg(test)]
3612impl fmt::Debug for AfterFirstSpawnHook {
3613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3614 f.write_str("AfterFirstSpawnHook")
3615 }
3616}
3617
3618#[cfg(test)]
3619impl AfterFirstSpawnHook {
3620 fn run(&self, module_id: &str) {
3621 if let Some(hook) = &self.0 {
3622 hook(module_id);
3623 }
3624 }
3625}
3626
3627impl Supervisor {
3628 #[cfg(all(test, target_os = "linux"))]
3629 pub(crate) fn set_admission_hook_for_test(
3630 &self,
3631 hook: impl Fn(&str, &'static str, Option<u32>) -> bool + Send + Sync + 'static,
3632 ) {
3633 self.child_roster.set_admission_hook_for_test(hook);
3634 }
3635
3636 #[cfg(test)]
3637 pub(crate) fn new_for_test(registry: Arc<Registry>, policy: RestartPolicy) -> Self {
3638 let supervisor = Self::new(registry, policy);
3639 #[cfg(target_os = "macos")]
3640 let supervisor = supervisor.with_privacy_trampoline(test_privacy_trampoline());
3641 supervisor
3642 }
3643 pub fn with_privacy_trampoline(self, path: impl Into<PathBuf>) -> Self {
3648 let path = path.into();
3649 #[cfg(target_os = "macos")]
3650 {
3651 let result = probe_privacy_trampoline(&path).map(|()| path);
3652 if let Err(cause) = &result {
3653 error!(%cause, "macOS privacy identity unavailable; supervised launches will refuse");
3654 }
3655 self.child_roster.set_privacy_trampoline(result);
3656 }
3657 #[cfg(not(target_os = "macos"))]
3658 let _ = path;
3659 self
3660 }
3661 pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
3664 self.child_roster.shutdown_flag()
3665 }
3666
3667 #[cfg(unix)]
3677 pub(crate) fn begin_daemon_shutdown(&self) {
3678 self.child_roster.close();
3679 if let Some(journal) = &self.terminal_journal {
3680 journal.stamp_shutdown();
3681 }
3682 }
3683
3684 #[cfg(unix)]
3689 pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
3690 const NOTICE_BUDGET: Duration = Duration::from_millis(500);
3691 const DRAIN_BUDGET: Duration = Duration::from_secs(2);
3692 let Some(forwarding) = &self.forwarding else {
3693 return Ok(());
3694 };
3695 let notice_started = Instant::now();
3696 let modules = forwarding
3697 .begin_daemon_drain()
3698 .map_err(SuperviseError::Forwarding)?;
3699 let deadline_ms =
3700 unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
3701 let shutdown_reason = self
3702 .supervisor_handle
3703 .as_ref()
3704 .map(SupervisorHandle::take_daemon_shutdown_reason)
3705 .unwrap_or(RouteCloseReason::Disable);
3706 let mut modules_told = 0;
3707 let mut notices = tokio::task::JoinSet::new();
3708 let mut drains = Vec::new();
3709 for connection in forwarding
3710 .module_connections()
3711 .map_err(SuperviseError::Forwarding)?
3712 {
3713 let target = ModuleDrainTarget {
3714 endpoint: connection.endpoint,
3715 sink: connection.sink,
3716 negotiated_ver: connection.negotiated_ver,
3717 abandoned_bindings: Vec::new(),
3718 excluded_subscriptions: 0,
3719 };
3720 notices.spawn(async move {
3721 (
3722 true,
3723 send_module_draining(
3724 &connection.module_id,
3725 shutdown_reason,
3726 deadline_ms,
3727 &target,
3728 true,
3729 )
3730 .await,
3731 )
3732 });
3733 }
3734 for (module_id, endpoint) in modules {
3735 let Some(target) = forwarding
3736 .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
3737 .map_err(SuperviseError::Forwarding)?
3738 else {
3739 continue;
3740 };
3741 let routes = forwarding
3742 .endpoint_routes(target.endpoint)
3743 .map_err(SuperviseError::Forwarding)?;
3744 let mut recipients = Vec::new();
3747 let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
3748 for route in routes {
3749 let client = route.goodbye_target;
3750 if let Some((_, channels)) = clients
3751 .iter_mut()
3752 .find(|(existing, _)| existing.connection_id == client.connection_id)
3753 {
3754 channels.push(client.channel);
3755 } else {
3756 let channel = client.channel;
3757 clients.push((client, vec![channel]));
3758 }
3759 }
3760 for (client, mut channels) in clients {
3761 channels.sort_unstable();
3762 channels.dedup();
3763 let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
3764 module_id: module_id.clone(),
3765 channels,
3766 reason: RouteCloseReason::Restart,
3767 })
3768 .expect("route closing serializes");
3769 recipients.push((client.sink, client.negotiated_ver, closing));
3770 }
3771 for (sink, version, body) in recipients {
3772 notices.spawn(async move {
3773 let frame = Frame::build_with_version(
3774 version,
3775 FrameType::Push,
3776 control_flags(),
3777 0,
3778 0,
3779 0,
3780 body,
3781 )
3782 .expect("bounded lifecycle notice frame builds");
3783 (false, sink.send_flushed(frame).await.is_ok())
3784 });
3785 }
3786 let gauges = declared_busy_gauges(&self.registry, &module_id)?;
3787 drains.push((module_id, target.endpoint, gauges));
3788 }
3789 let notice_deadline = Instant::now() + NOTICE_BUDGET;
3792 while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
3793 match result {
3794 Ok((true, true)) => modules_told += 1,
3795 Ok((false, true)) => {}
3796 result => warn!(?result, "daemon shutdown notice delivery failed"),
3797 }
3798 }
3799 notices.abort_all();
3800 info!(
3801 ?shutdown_reason,
3802 modules_told, "daemon shutdown module notices delivered"
3803 );
3804 let notice_elapsed = notice_started.elapsed();
3805 let drain_started = Instant::now();
3806 let deadline = drain_started + DRAIN_BUDGET;
3807 let mut waits = tokio::task::JoinSet::new();
3808 for (module_id, endpoint, gauges) in drains {
3809 let forwarding = Arc::clone(forwarding);
3810 let mut runtime = self.runtime_config();
3811 runtime.health.cadence = Duration::from_millis(100);
3812 waits.spawn(async move {
3813 let wait_result = wait_for_forwarding_quiescence(
3814 &forwarding,
3815 &module_id,
3816 &runtime,
3817 endpoint,
3818 deadline,
3819 &gauges,
3820 DrainScope::Endpoint(endpoint),
3821 &mut DrainGaugeTrace::new(&gauges),
3822 )
3823 .await;
3824 forwarding
3828 .record_daemon_drain_result(
3829 endpoint,
3830 drained_after_quiescence_wait(&wait_result),
3831 )
3832 .map_err(SuperviseError::Forwarding)?;
3833 wait_result
3834 });
3835 }
3836 while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
3837 if !matches!(result, Ok(Ok(true))) {
3838 warn!(?result, "daemon shutdown drain did not reach quiescence");
3839 }
3840 }
3841 info!(
3844 notice_elapsed_ms = notice_elapsed.as_millis() as u64,
3845 drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
3846 "daemon shutdown forwarding drain complete"
3847 );
3848 Ok(())
3849 }
3850
3851 #[cfg(unix)]
3863 pub(crate) async fn end_children_for_daemon_shutdown(
3864 &self,
3865 already_escalated: bool,
3866 escalate: impl std::future::Future<Output = ()>,
3867 ) {
3868 tokio::pin!(escalate);
3869 let mut escalated = already_escalated;
3870 if let Some(forwarding) = &self.forwarding {
3871 let reason = CloseReason::new(
3872 "daemon_shutdown",
3873 "the daemon is exiting after its shutdown notice and drain",
3874 );
3875 if escalated {
3876 send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
3879 } else {
3880 tokio::select! {
3881 biased;
3882 _ = escalate.as_mut() => {
3883 info!("second SIGTERM: abandoning module GOODBYE delivery");
3884 escalated = true;
3885 }
3886 _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
3887 }
3888 }
3889 let closed = forwarding.close_all_connections(&reason);
3890 debug!(closed, "closed established connections for daemon shutdown");
3891 }
3892 let escalated_here = escalated && !already_escalated;
3896 let remaining_escalate = async move {
3897 if escalated_here {
3898 std::future::pending::<()>().await;
3899 } else {
3900 escalate.await;
3901 }
3902 };
3903 crate::child_roster::end_children_for_daemon_shutdown(
3904 &self.child_roster,
3905 escalated,
3906 remaining_escalate,
3907 )
3908 .await;
3909 if let Some(journal) = &self.terminal_journal {
3910 journal.flush_shutdown().await;
3911 }
3912 }
3913
3914 pub fn new(registry: Arc<Registry>, restart_policy: RestartPolicy) -> Self {
3915 Self {
3916 registry,
3917 config_delivery: None,
3918 restart_policy,
3919 drain_timeout: DEFAULT_DRAIN_TIMEOUT,
3920 connection_file_path: None,
3921 capture_logs_dir: None,
3922 forwarding: None,
3923 process_liveness: Arc::new(SupervisorProcessLiveness::default()),
3924 supervisor_handle: None,
3925 health: HealthConfig::default(),
3926 host_health: HostHealth::default(),
3927 daemon_start_clock: crate::clock::StartClock::capture(),
3928 terminal_journal: None,
3929 spawn_events: SpawnEventFeed::default(),
3930 provenance_probe: ExecutableIdentityProbe::default(),
3931 child_roster: ChildRoster::default(),
3932 #[cfg(target_os = "linux")]
3933 cgroup_placement: None,
3934 #[cfg(test)]
3935 test_after_first_spawn: AfterFirstSpawnHook::default(),
3936 }
3937 }
3938
3939 pub fn with_drain_timeout(mut self, drain_timeout: Duration) -> Self {
3940 self.drain_timeout = drain_timeout;
3941 self
3942 }
3943
3944 pub(crate) fn default_drain_timeout(&self) -> Duration {
3946 self.drain_timeout
3947 }
3948
3949 pub fn with_process_liveness(
3950 mut self,
3951 process_liveness: Arc<SupervisorProcessLiveness>,
3952 ) -> Self {
3953 self.process_liveness = process_liveness;
3954 self
3955 }
3956
3957 pub fn with_config_runtime(
3959 mut self,
3960 owner: Arc<crate::config_gate::runtime::RuntimeOwner>,
3961 ) -> Self {
3962 if let Some(handle) = &self.supervisor_handle {
3963 handle.install_binding_retirement(&owner);
3964 }
3965 self.config_delivery = Some(config_delivery::ConfigDelivery(owner));
3966 self
3967 }
3968
3969 pub fn with_connection_file_path(mut self, connection_file_path: impl Into<PathBuf>) -> Self {
3970 self.connection_file_path = Some(connection_file_path.into());
3971 self
3972 }
3973
3974 pub fn with_capture_logs_dir(mut self, logs_dir: impl Into<PathBuf>) -> Self {
3976 self.capture_logs_dir = Some(logs_dir.into());
3977 self
3978 }
3979
3980 pub fn with_daemon_incarnation(self, daemon_incarnation: String) -> Self {
3983 self.spawn_events.configure_incarnation(daemon_incarnation);
3987 self
3988 }
3989
3990 pub fn with_terminal_journal(self, path: PathBuf, daemon_incarnation: String) -> Self {
3993 let mut this = self.with_daemon_incarnation(daemon_incarnation.clone());
3994 this.terminal_journal = Some(Arc::new(crate::terminal_journal::TerminalJournal::open(
3995 path,
3996 daemon_incarnation,
3997 )));
3998 this
3999 }
4000
4001 pub fn with_forwarding(mut self, forwarding: Arc<ForwardingTable>) -> Self {
4002 self.child_roster.counters = forwarding.counters();
4003 self.forwarding = Some(forwarding);
4004 self
4005 }
4006
4007 pub fn with_handle(mut self, supervisor_handle: SupervisorHandle) -> Self {
4008 if let Some(delivery) = &self.config_delivery {
4009 supervisor_handle.install_binding_retirement(&delivery.0);
4010 }
4011 self.host_health = supervisor_handle.host_health.clone();
4012 self.spawn_events = supervisor_handle.spawn_events.clone();
4013 self.supervisor_handle = Some(supervisor_handle);
4014 self
4015 }
4016
4017 pub fn with_health_config(mut self, health: HealthConfig) -> Self {
4018 self.health = health;
4019 self
4020 }
4021
4022 pub fn with_live_children_record(self, path: impl Into<PathBuf>) -> Self {
4026 self.child_roster.record_to(path.into());
4027 self
4028 }
4029
4030 #[cfg(target_os = "linux")]
4031 pub fn with_cgroup_placement(
4032 mut self,
4033 cgroup_placement: Option<subc_cgroup::Placement>,
4034 ) -> Self {
4035 self.child_roster
4036 .set_cgroup_placement(cgroup_placement.clone());
4037 self.cgroup_placement = cgroup_placement;
4038 self
4039 }
4040
4041 pub fn spawn(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4050 validate_spec(&spec)?;
4051 self.establish_identity(&spec);
4052
4053 let runtime = self.runtime_config();
4054 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4055 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4056 let registration_watch = watch_registration(&self.registry, &spec);
4057 let spawned = spawn_child(
4058 &spec,
4059 runtime.connection_file_path.as_deref(),
4060 self.supervisor_handle.as_ref(),
4061 &runtime.stderr_ring,
4062 runtime.capture_logs_dir.as_deref(),
4063 &runtime.child_roster,
4064 runtime.spawn_delivery(),
4065 #[cfg(target_os = "linux")]
4066 runtime.cgroup_placement.as_ref(),
4067 runtime.register_timeout,
4068 );
4069 #[cfg(test)]
4070 self.test_after_first_spawn.run(&spec.module_id);
4071 let mut child = match spawned {
4072 Ok(child) => child,
4073 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4074 defer_config_spawn(
4075 &spec,
4076 &runtime,
4077 &snapshot,
4078 RespawnKind::Spawn,
4079 &runtime.failure_context(runtime.recovery_is_daemon),
4080 )?;
4081 return Ok(self.supervised_module(spec, runtime, snapshot, None));
4082 }
4083 Err(SuperviseError::ConfigHeld { .. }) => {
4084 hold_config_spawn(
4085 &spec,
4086 &runtime,
4087 &snapshot,
4088 &runtime.failure_context(runtime.recovery_is_daemon),
4089 )?;
4090 return Ok(self.supervised_module(spec, runtime, snapshot, None));
4091 }
4092 Err(err) => {
4093 self.abandon_unrostered(&spec.module_id);
4096 return Err(err);
4097 }
4098 };
4099 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4100 self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4101 if let Some(spawn) = activity_spawn {
4102 spawn.complete(&snapshot);
4103 }
4104
4105 Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4106 }
4107
4108 pub async fn spawn_async(&self, spec: ModuleSpec) -> Result<SupervisedModule, SuperviseError> {
4111 validate_spec(&spec)?;
4112 self.establish_identity(&spec);
4113 let mut identity = AsyncInitialIdentity {
4114 supervisor: self,
4115 module: spec.module_id.clone(),
4116 committed: false,
4117 };
4118 let runtime = self.runtime_config();
4119 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
4120 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4121 let registration_watch = watch_registration(&self.registry, &spec);
4122 let spawned = spawn_child_async(&spec, &runtime).await;
4123 #[cfg(test)]
4124 self.test_after_first_spawn.run(&spec.module_id);
4125 let mut child = match spawned {
4126 Ok(child) => child,
4127 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4128 defer_config_spawn(
4129 &spec,
4130 &runtime,
4131 &snapshot,
4132 RespawnKind::Spawn,
4133 &runtime.failure_context(runtime.recovery_is_daemon),
4134 )?;
4135 identity.committed = true;
4136 return Ok(self.supervised_module(spec, runtime, snapshot, None));
4137 }
4138 Err(SuperviseError::ConfigHeld { .. }) => {
4139 hold_config_spawn(
4140 &spec,
4141 &runtime,
4142 &snapshot,
4143 &runtime.failure_context(runtime.recovery_is_daemon),
4144 )?;
4145 identity.committed = true;
4146 return Ok(self.supervised_module(spec, runtime, snapshot, None));
4147 }
4148 Err(err) => {
4149 self.abandon_unrostered(&spec.module_id);
4150 return Err(err);
4151 }
4152 };
4153 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
4154 self.mark_first_process_running(&spec, &runtime, &snapshot, &mut child)?;
4155 if let Some(spawn) = activity_spawn {
4156 spawn.complete(&snapshot);
4157 }
4158 identity.committed = true;
4159 Ok(self.supervised_module(spec, runtime, snapshot, Some(child)))
4160 }
4161
4162 fn establish_identity(&self, spec: &ModuleSpec) {
4175 if let Some(supervisor_handle) = &self.supervisor_handle {
4176 supervisor_handle.apply_identity_configuration(spec);
4177 supervisor_handle.mark_configured(&spec.module_id);
4178 }
4179 }
4180
4181 fn abandon_unrostered(&self, module_id: &str) {
4184 if let Some(supervisor_handle) = &self.supervisor_handle {
4185 supervisor_handle.unmark_configured_unless_rostered(module_id);
4186 }
4187 }
4188
4189 fn mark_first_process_running(
4192 &self,
4193 spec: &ModuleSpec,
4194 runtime: &SupervisorRuntimeConfig,
4195 snapshot: &SharedSnapshot,
4196 child: &mut SupervisedChild,
4197 ) -> Result<(), SuperviseError> {
4198 if let Err(err) = set_running(snapshot, child, &spec.module_id, &runtime.spawn_events) {
4199 containment::terminate_blocking(&runtime.child_roster.containment);
4200 self.abandon_unrostered(&spec.module_id);
4201 return Err(err);
4202 }
4203 self.process_liveness
4204 .track(spec.module_id.clone(), Arc::clone(snapshot));
4205 Ok(())
4206 }
4207
4208 pub fn supervise_configured(
4214 &self,
4215 spec: ModuleSpec,
4216 enabled: bool,
4217 ) -> Result<SupervisedModule, SuperviseError> {
4218 self.supervise_configured_requested(
4219 spec,
4220 enabled,
4221 self.health.clone(),
4222 None,
4223 self.restart_policy,
4224 DEFAULT_REGISTER_TIMEOUT,
4225 None,
4226 )
4227 }
4228
4229 pub fn supervise_configured_with_health(
4235 &self,
4236 spec: ModuleSpec,
4237 enabled: bool,
4238 health: HealthConfig,
4239 drain_timeout_ms: Option<u64>,
4240 restart_policy: RestartPolicy,
4241 ) -> Result<SupervisedModule, SuperviseError> {
4242 self.supervise_configured_requested(
4243 spec,
4244 enabled,
4245 health,
4246 drain_timeout_ms,
4247 restart_policy,
4248 DEFAULT_REGISTER_TIMEOUT,
4249 None,
4250 )
4251 }
4252
4253 #[allow(clippy::too_many_arguments)]
4254 pub(crate) fn supervise_configured_requested(
4255 &self,
4256 spec: ModuleSpec,
4257 enabled: bool,
4258 health: HealthConfig,
4259 drain_timeout_ms: Option<u64>,
4260 restart_policy: RestartPolicy,
4261 register_timeout: Duration,
4262 requester: Option<Principal>,
4263 ) -> Result<SupervisedModule, SuperviseError> {
4264 let registered = self.register_configured_with_health(
4265 spec,
4266 enabled,
4267 health,
4268 drain_timeout_ms,
4269 restart_policy,
4270 register_timeout,
4271 )?;
4272 let daemon_initiated = requester.is_none();
4273 self.start_registered_configured(registered, requester, daemon_initiated)
4274 }
4275
4276 #[allow(clippy::too_many_arguments)]
4277 pub(crate) async fn supervise_configured_requested_async(
4278 &self,
4279 spec: ModuleSpec,
4280 enabled: bool,
4281 health: HealthConfig,
4282 drain_timeout_ms: Option<u64>,
4283 restart_policy: RestartPolicy,
4284 register_timeout: Duration,
4285 requester: Option<Principal>,
4286 ) -> Result<SupervisedModule, SuperviseError> {
4287 let registered = self.register_configured_with_health(
4288 spec,
4289 enabled,
4290 health,
4291 drain_timeout_ms,
4292 restart_policy,
4293 register_timeout,
4294 )?;
4295 let daemon_initiated = requester.is_none();
4296 self.start_registered_configured_async(registered, requester, daemon_initiated)
4297 .await
4298 }
4299
4300 pub(crate) fn register_configured_with_health(
4305 &self,
4306 spec: ModuleSpec,
4307 enabled: bool,
4308 health: HealthConfig,
4309 drain_timeout_ms: Option<u64>,
4310 restart_policy: RestartPolicy,
4311 register_timeout: Duration,
4312 ) -> Result<RegisteredConfiguredModule, SuperviseError> {
4313 validate_spec(&spec)?;
4314 self.establish_identity(&spec);
4315
4316 let mut runtime = self.runtime_config();
4317 runtime.health = health;
4318 runtime.restart_policy = restart_policy;
4319 runtime.register_timeout = register_timeout;
4320 if let Some(ms) = drain_timeout_ms {
4321 runtime.drain_timeout = Duration::from_millis(ms);
4322 *runtime
4323 .effective_drain_timeout
4324 .lock()
4325 .unwrap_or_else(|poisoned| poisoned.into_inner()) = runtime.drain_timeout;
4326 }
4327 let snapshot = if enabled {
4328 SupervisorSnapshot::starting()
4329 } else {
4330 SupervisorSnapshot::disabled()
4331 };
4332 let snapshot = {
4333 let mut snapshot = snapshot;
4334 if enabled {
4335 if let Some((pid, reason)) = runtime.child_roster.previous_instance(&spec.module_id)
4336 {
4337 snapshot.waiting_for_previous_pid = Some(pid);
4338 snapshot.waiting_for_previous_detail = Some(reason.waiting_message(pid));
4339 }
4340 }
4341 snapshot
4342 };
4343 let (module, commands) =
4344 self.register_module(&spec, &runtime, Arc::new(Mutex::new(snapshot)));
4345 Ok(RegisteredConfiguredModule {
4346 spec,
4347 runtime,
4348 module,
4349 commands,
4350 })
4351 }
4352
4353 pub(crate) fn start_registered_configured(
4356 &self,
4357 registered: RegisteredConfiguredModule,
4358 requester: Option<Principal>,
4359 daemon_initiated: bool,
4360 ) -> Result<SupervisedModule, SuperviseError> {
4361 let RegisteredConfiguredModule {
4362 spec,
4363 mut runtime,
4364 module,
4365 commands,
4366 } = registered;
4367 runtime.start_requester = requester;
4368 runtime.recovery_is_daemon = daemon_initiated;
4369 let snapshot = &module.inner.snapshot;
4370 let should_spawn = {
4371 let state = lock_snapshot(snapshot)?;
4372 state.enabled && state.waiting_for_previous_pid.is_none()
4373 };
4374 let child = if should_spawn {
4375 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4376 let registration_watch = watch_registration(&self.registry, &spec);
4377 let spawned = spawn_child(
4378 &spec,
4379 runtime.connection_file_path.as_deref(),
4380 self.supervisor_handle.as_ref(),
4381 &runtime.stderr_ring,
4382 runtime.capture_logs_dir.as_deref(),
4383 &runtime.child_roster,
4384 runtime.spawn_delivery(),
4385 #[cfg(target_os = "linux")]
4386 runtime.cgroup_placement.as_ref(),
4387 runtime.register_timeout,
4388 );
4389 #[cfg(test)]
4390 self.test_after_first_spawn.run(&spec.module_id);
4391 match spawned {
4392 Ok(mut child) => {
4393 arm_registration_deadline(
4394 &mut child,
4395 runtime.register_timeout,
4396 registration_watch,
4397 );
4398 self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4399 if let Some(spawn) = activity_spawn {
4400 spawn.complete(snapshot);
4401 }
4402 Some(child)
4403 }
4404 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4405 defer_config_spawn(
4406 &spec,
4407 &runtime,
4408 snapshot,
4409 RespawnKind::Spawn,
4410 &runtime.failure_context(daemon_initiated),
4411 )?;
4412 None
4413 }
4414 Err(mut err) => {
4415 if matches!(err, SuperviseError::ConfigHeld { .. }) {
4416 match hold_config_spawn(
4417 &spec,
4418 &runtime,
4419 snapshot,
4420 &runtime.failure_context(daemon_initiated),
4421 ) {
4422 Ok(()) => {
4423 self.start_monitor(spec, runtime, &module, None, commands);
4424 return Ok(module);
4425 }
4426 Err(parking_error) => err = parking_error,
4427 }
4428 }
4429 if runtime.health.critical {
4430 error!(
4431 module_id = %spec.module_id,
4432 program = %spec.program.display(),
4433 error = %err,
4434 "critical configured module failed to spawn; marking failed and alerting"
4435 );
4436 } else {
4437 error!(
4438 module_id = %spec.module_id,
4439 program = %spec.program.display(),
4440 error = %err,
4441 "configured module failed to spawn; marking failed and continuing"
4442 );
4443 }
4444 fail_snapshot(
4445 snapshot,
4446 Some(&spec.module_id),
4447 None,
4448 &runtime.failure_context(daemon_initiated),
4449 );
4450 None
4451 }
4452 }
4453 } else {
4454 None
4455 };
4456 self.start_monitor(spec, runtime, &module, child, commands);
4457 Ok(module)
4458 }
4459
4460 pub(crate) async fn start_registered_configured_async(
4461 &self,
4462 registered: RegisteredConfiguredModule,
4463 requester: Option<Principal>,
4464 daemon_initiated: bool,
4465 ) -> Result<SupervisedModule, SuperviseError> {
4466 self.start_registered_with_failure_policy(registered, requester, daemon_initiated, None)
4467 .await
4468 }
4469
4470 pub(crate) async fn start_registered_approved_async(
4471 &self,
4472 registered: RegisteredConfiguredModule,
4473 requester: Principal,
4474 generation: crate::config_gate::runtime::ApprovalIdentity,
4475 ) -> Result<SupervisedModule, SuperviseError> {
4476 self.start_registered_with_failure_policy(
4477 registered,
4478 Some(requester),
4479 false,
4480 Some(generation),
4481 )
4482 .await
4483 }
4484
4485 async fn start_registered_with_failure_policy(
4486 &self,
4487 registered: RegisteredConfiguredModule,
4488 requester: Option<Principal>,
4489 daemon_initiated: bool,
4490 approved_generation: Option<crate::config_gate::runtime::ApprovalIdentity>,
4491 ) -> Result<SupervisedModule, SuperviseError> {
4492 let RegisteredConfiguredModule {
4493 spec,
4494 mut runtime,
4495 module,
4496 commands,
4497 } = registered;
4498 runtime.start_requester = requester;
4499 runtime.recovery_is_daemon = daemon_initiated;
4500 let snapshot = &module.inner.snapshot;
4501 let mut startup_error = None;
4502 let failure = FailureContext {
4503 approval: approved_generation.clone(),
4504 ..runtime.failure_context(daemon_initiated)
4505 };
4506 let should_spawn = {
4507 let state = lock_snapshot(snapshot)?;
4508 state.enabled && state.waiting_for_previous_pid.is_none()
4509 };
4510 let child = if should_spawn {
4511 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
4512 let registration_watch = watch_registration(&self.registry, &spec);
4513 let spawned = spawn_child_async(&spec, &runtime).await;
4514 #[cfg(test)]
4515 self.test_after_first_spawn.run(&spec.module_id);
4516 match spawned {
4517 Ok(mut child) => {
4518 arm_registration_deadline(
4519 &mut child,
4520 runtime.register_timeout,
4521 registration_watch,
4522 );
4523 self.mark_first_process_running(&spec, &runtime, snapshot, &mut child)?;
4524 if let Some(spawn) = activity_spawn {
4525 spawn.complete(snapshot);
4526 }
4527 Some(child)
4528 }
4529 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
4530 defer_config_spawn(&spec, &runtime, snapshot, RespawnKind::Spawn, &failure)?;
4531 None
4532 }
4533 Err(mut err) => {
4534 if matches!(err, SuperviseError::ConfigHeld { .. }) {
4535 match hold_config_spawn(&spec, &runtime, snapshot, &failure) {
4536 Ok(()) => {
4537 self.start_monitor(spec, runtime, &module, None, commands);
4538 return Ok(module);
4539 }
4540 Err(parking_error) => err = parking_error,
4541 }
4542 }
4543 if runtime.health.critical {
4544 error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4545 "critical configured module failed to spawn; marking failed and alerting");
4546 } else {
4547 error!(module_id = %spec.module_id, program = %spec.program.display(), error = %err,
4548 "configured module failed to spawn; marking failed and continuing");
4549 }
4550 fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
4551 if let Some(generation) = approved_generation {
4552 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
4553 state.approved_start_failure = Some((generation, err.to_string()));
4554 });
4555 startup_error = Some(err);
4556 }
4557 None
4558 }
4559 }
4560 } else {
4561 None
4562 };
4563 self.start_monitor(spec, runtime, &module, child, commands);
4564 startup_error.map_or(Ok(module), Err)
4568 }
4569
4570 fn runtime_config(&self) -> SupervisorRuntimeConfig {
4571 let effective_drain_timeout = Arc::new(Mutex::new(self.drain_timeout));
4572 SupervisorRuntimeConfig {
4573 registry: self.registry.clone(),
4574 config_delivery: self.config_delivery.clone(),
4575 recovery_is_daemon: true,
4576 start_requester: None,
4577 pending_activity_restart: false,
4578 provenance_probe: self.provenance_probe.clone(),
4579 scheduled_respawn: Arc::default(),
4580 deferred_reload_reply: Arc::default(),
4581 restart_policy: self.restart_policy,
4582 register_timeout: DEFAULT_REGISTER_TIMEOUT,
4583 drain_timeout: self.drain_timeout,
4584 child_roster: self
4587 .child_roster
4588 .for_module(Arc::clone(&effective_drain_timeout)),
4589 effective_drain_timeout,
4590 default_drain_timeout: self.drain_timeout,
4591 health: self.health.clone(),
4592 host_health: self.host_health.clone(),
4593 connection_file_path: self.connection_file_path.clone(),
4594 capture_logs_dir: self.capture_logs_dir.clone(),
4595 forwarding: self.forwarding.clone(),
4596 supervisor_handle: self.supervisor_handle.clone(),
4597 stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
4598 terminal_ring: Arc::new(Mutex::new(
4599 TerminalRing::new(
4600 TerminalRingConfig::default(),
4601 self.daemon_start_clock.started_at_ms(),
4602 )
4603 .with_start_clock(self.daemon_start_clock)
4604 .with_journal(self.terminal_journal.clone())
4605 .with_daemon_shutdown(self.child_roster.shutdown_flag()),
4606 )),
4607 spawn_events: self.spawn_events.clone(),
4608 #[cfg(target_os = "linux")]
4609 cgroup_placement: self.cgroup_placement.clone(),
4610 #[cfg(test)]
4611 test_seed_stale_facts_before_enable_spawn: false,
4612 #[cfg(test)]
4613 test_reload_exit_record_gate: None,
4614 }
4615 }
4616
4617 fn supervised_module(
4618 &self,
4619 spec: ModuleSpec,
4620 runtime: SupervisorRuntimeConfig,
4621 snapshot: SharedSnapshot,
4622 child: Option<SupervisedChild>,
4623 ) -> SupervisedModule {
4624 let (module, commands) = self.register_module(&spec, &runtime, snapshot);
4625 self.start_monitor(spec, runtime, &module, child, commands);
4626 module
4627 }
4628
4629 fn register_module(
4630 &self,
4631 spec: &ModuleSpec,
4632 runtime: &SupervisorRuntimeConfig,
4633 snapshot: SharedSnapshot,
4634 ) -> (SupervisedModule, mpsc::Receiver<SupervisorCommand>) {
4635 runtime.host_health.track(spec, &snapshot);
4636 let configuration = Arc::new(Mutex::new(SupervisedConfiguration {
4637 spec: spec.clone(),
4638 enabled: snapshot.lock().unwrap_or_else(|p| p.into_inner()).enabled,
4639 health: runtime.health.clone(),
4640 register_timeout: runtime.register_timeout,
4641 restart_policy: runtime.restart_policy,
4642 }));
4643 let stderr_ring = Arc::clone(&runtime.stderr_ring);
4644 let terminal_ring = Arc::clone(&runtime.terminal_ring);
4645 let effective_drain_timeout = Arc::clone(&runtime.effective_drain_timeout);
4646 let (tx, rx) = mpsc::channel(4);
4647 let module_id = spec.module_id.clone();
4648 let module = SupervisedModule {
4649 inner: Arc::new(SupervisedModuleInner {
4650 module_id: module_id.clone(),
4651 registry: Arc::clone(&self.registry),
4652 snapshot,
4653 configuration,
4654 stderr_ring,
4655 terminal_ring,
4656 commands: tx,
4657 monitor: Mutex::new(None),
4658 effective_drain_timeout,
4659 provenance_probe: self.provenance_probe.clone(),
4660 retained: runtime.child_roster.retained_view(),
4661 }),
4662 };
4663 if let Some(supervisor_handle) = &self.supervisor_handle {
4666 supervisor_handle.insert(module.clone());
4667 }
4668 (module, rx)
4669 }
4670
4671 fn start_monitor(
4672 &self,
4673 spec: ModuleSpec,
4674 runtime: SupervisorRuntimeConfig,
4675 module: &SupervisedModule,
4676 child: Option<SupervisedChild>,
4677 commands: mpsc::Receiver<SupervisorCommand>,
4678 ) {
4679 let monitor = tokio::spawn(supervise_loop(
4680 spec,
4681 runtime,
4682 Arc::clone(&self.registry),
4683 Arc::clone(&self.process_liveness),
4684 Arc::clone(&module.inner.snapshot),
4685 child,
4686 commands,
4687 ));
4688 *module
4689 .inner
4690 .monitor
4691 .lock()
4692 .unwrap_or_else(|p| p.into_inner()) = Some(monitor);
4693 }
4694}
4695
4696impl Default for Supervisor {
4697 fn default() -> Self {
4698 Self::new(Arc::new(Registry::default()), RestartPolicy::default())
4699 }
4700}
4701
4702#[derive(Clone)]
4704pub struct SupervisedModule {
4705 inner: Arc<SupervisedModuleInner>,
4706}
4707
4708struct SupervisedModuleInner {
4709 retained: crate::child_roster::RetainedView,
4710 module_id: String,
4711 registry: Arc<Registry>,
4712 snapshot: SharedSnapshot,
4713 configuration: Arc<Mutex<SupervisedConfiguration>>,
4714 stderr_ring: Arc<Mutex<StderrRing>>,
4715 terminal_ring: Arc<Mutex<TerminalRing>>,
4716 commands: mpsc::Sender<SupervisorCommand>,
4717 monitor: Mutex<Option<JoinHandle<()>>>,
4718 effective_drain_timeout: Arc<Mutex<Duration>>,
4719 provenance_probe: ExecutableIdentityProbe,
4720}
4721
4722impl fmt::Debug for SupervisedModule {
4723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4724 f.debug_struct("SupervisedModule")
4725 .field("module_id", &self.inner.module_id)
4726 .field("status", &self.status())
4727 .finish_non_exhaustive()
4728 }
4729}
4730
4731impl SupervisedModule {
4732 pub(crate) fn check_approved_start_failure(
4733 &self,
4734 generation: &crate::config_gate::runtime::ApprovalIdentity,
4735 ) -> Result<bool, SuperviseError> {
4736 let state = lock_snapshot(&self.inner.snapshot)?;
4737 if let Some((failed_generation, detail)) = &state.approved_start_failure {
4738 if failed_generation == generation {
4739 return Err(SuperviseError::ReloadFailed {
4740 module_id: self.inner.module_id.clone(),
4741 reason: detail.clone(),
4742 });
4743 }
4744 }
4745 Ok(state.approved_start_failure.is_some())
4746 }
4747
4748 pub(crate) fn has_approved_start_failure(
4749 &self,
4750 identity: &crate::config_gate::runtime::ApprovalIdentity,
4751 ) -> bool {
4752 lock_snapshot(&self.inner.snapshot).is_ok_and(|state| {
4753 state
4754 .approved_start_failure
4755 .as_ref()
4756 .is_some_and(|(failed, _)| failed == identity)
4757 })
4758 }
4759
4760 pub(crate) fn needs_approved_gate_restart(
4761 &self,
4762 approval: &crate::config_gate::runtime::ApprovalIdentity,
4763 ) -> bool {
4764 lock_snapshot(&self.inner.snapshot)
4765 .is_ok_and(|state| state.needs_approved_gate_restart(approval))
4766 }
4767
4768 #[cfg(all(test, unix))]
4769 pub(crate) fn config_hold_origin_for_test(
4770 &self,
4771 ) -> (bool, Option<crate::config_gate::runtime::ApprovalIdentity>) {
4772 let state = lock_snapshot(&self.inner.snapshot).unwrap();
4773 (
4774 state.config_hold_daemon_initiated,
4775 state.config_hold_approval.clone(),
4776 )
4777 }
4778
4779 pub(crate) async fn config_policy_probe(
4780 &self,
4781 connection: crate::ConnectionId,
4782 generation: u64,
4783 attempt: u64,
4784 ) -> Result<(), SuperviseError> {
4785 self.inner
4786 .commands
4787 .send(SupervisorCommand::ConfigPolicyProbe {
4788 connection,
4789 generation,
4790 attempt,
4791 })
4792 .await
4793 .map_err(|_| SuperviseError::CommandClosed {
4794 module_id: self.inner.module_id.clone(),
4795 })
4796 }
4797 pub(crate) async fn config_exit_hold(&self) -> Result<(), SuperviseError> {
4798 let (reply, result) = oneshot::channel();
4799 self.inner
4800 .commands
4801 .send(SupervisorCommand::ConfigExitHold { reply })
4802 .await
4803 .map_err(|_| SuperviseError::CommandClosed {
4804 module_id: self.module_id().to_string(),
4805 })?;
4806 result.await.map_err(|_| SuperviseError::CommandClosed {
4807 module_id: self.module_id().to_string(),
4808 })?
4809 }
4810 pub(crate) async fn config_delivery_failed(
4811 &self,
4812 connection: crate::ConnectionId,
4813 hold: bool,
4814 ) -> Result<(), SuperviseError> {
4815 self.inner
4816 .commands
4817 .send(SupervisorCommand::ConfigDeliveryFailed { connection, hold })
4818 .await
4819 .map_err(|_| SuperviseError::CommandClosed {
4820 module_id: self.module_id().to_string(),
4821 })
4822 }
4823
4824 pub(crate) async fn config_apply_restart(&self, generation: u64) -> Result<(), SuperviseError> {
4825 self.inner
4826 .commands
4827 .send(SupervisorCommand::ConfigApplyRestart {
4828 generation,
4829 supersedes_swap: false,
4830 })
4831 .await
4832 .map_err(|_| SuperviseError::CommandClosed {
4833 module_id: self.inner.module_id.clone(),
4834 })
4835 }
4836 pub fn module_id(&self) -> &str {
4837 &self.inner.module_id
4838 }
4839
4840 #[cfg(test)]
4844 pub(crate) fn record_health_probe_failure_for_test(
4845 &self,
4846 detail: &str,
4847 ) -> Result<(), SuperviseError> {
4848 update_snapshot(&self.inner.snapshot, Some(&self.inner.module_id), |state| {
4849 state.health.consecutive_failures = state.health.consecutive_failures.saturating_add(1);
4850 state.health.detail = Some(detail.to_string());
4851 })
4852 }
4853
4854 pub fn state(&self) -> Result<ModuleState, SuperviseError> {
4855 Ok(lock_snapshot(&self.inner.snapshot)?.state)
4856 }
4857
4858 pub(crate) fn registration_end_reason(
4859 &self,
4860 ) -> Result<Option<RegistrationEndReason>, SuperviseError> {
4861 let snapshot = lock_snapshot(&self.inner.snapshot)?;
4862 Ok(match snapshot.state {
4863 ModuleState::Draining if snapshot.draining_to_replace => {
4864 Some(RegistrationEndReason::SupervisorRestart)
4865 }
4866 ModuleState::Draining => Some(RegistrationEndReason::SupervisorStop),
4867 ModuleState::Restarting if snapshot.draining_to_replace => {
4868 Some(RegistrationEndReason::SupervisorRestart)
4869 }
4870 _ => None,
4871 })
4872 }
4873
4874 pub fn stderr_tail(
4881 &self,
4882 max_lines: Option<usize>,
4883 max_bytes: Option<usize>,
4884 ) -> StderrTailSnapshot {
4885 self.inner
4886 .stderr_ring
4887 .lock()
4888 .unwrap_or_else(|poisoned| poisoned.into_inner())
4889 .snapshot(max_lines, max_bytes)
4890 }
4891
4892 pub fn terminal_history(&self) -> TerminalHistorySnapshot {
4897 self.inner
4898 .terminal_ring
4899 .lock()
4900 .unwrap_or_else(|poisoned| poisoned.into_inner())
4901 .snapshot()
4902 }
4903
4904 pub fn durable_terminal_history(&self) -> subc_control::TerminalHistory {
4909 durable_terminal_history_of(&self.inner.terminal_ring, &self.inner.module_id)
4910 }
4911
4912 pub(crate) async fn read_durable_terminal_history(
4917 &self,
4918 ) -> Result<subc_control::TerminalHistory, tokio::task::JoinError> {
4919 let terminal_ring = Arc::clone(&self.inner.terminal_ring);
4920 let module_id = self.inner.module_id.clone();
4921 tokio::task::spawn_blocking(move || durable_terminal_history_of(&terminal_ring, &module_id))
4922 .await
4923 }
4924
4925 pub fn status(&self) -> Result<ModuleStatus, SuperviseError> {
4926 self.status_with_snapshot_lock(&self.inner.snapshot, None)
4927 .map(|(status, _)| status)
4928 }
4929
4930 pub(crate) fn next_retry_at_ms(&self) -> Result<Option<u64>, SuperviseError> {
4931 let state = lock_snapshot(&self.inner.snapshot)?;
4932 Ok(state
4933 .failed_retry
4934 .pending
4935 .filter(|_| state.state == ModuleState::Failed && state.enabled)
4936 .map(|retry| {
4937 unix_ms_now().saturating_add(
4938 u64::try_from(
4939 retry
4940 .deadline
4941 .saturating_duration_since(Instant::now())
4942 .as_millis(),
4943 )
4944 .unwrap_or(u64::MAX),
4945 )
4946 }))
4947 }
4948
4949 #[cfg(all(test, unix))]
4950 pub(crate) fn retry_deadline_for_test(&self) -> Option<Instant> {
4951 lock_snapshot(&self.inner.snapshot)
4952 .unwrap()
4953 .failed_retry
4954 .pending
4955 .map(|retry| retry.deadline)
4956 }
4957
4958 pub(crate) fn record_deliberate_severance(
4959 &self,
4960 identity: ProcessIdentity,
4961 ) -> Result<bool, SuperviseError> {
4962 let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
4963 if snapshot.pid != Some(identity.pid)
4964 || snapshot.process_start_time != Some(identity.start_time)
4965 {
4966 return Ok(false);
4967 }
4968 snapshot.deliberate_severance = Some(identity);
4969 Ok(true)
4970 }
4971
4972 pub(crate) fn status_for_control(
4977 &self,
4978 caller: &'static str,
4979 ) -> Result<ModuleStatus, SuperviseError> {
4980 self.status_with_snapshot_lock(&self.inner.snapshot, Some(caller))
4981 .map(|(status, _)| status)
4982 }
4983
4984 fn status_with_snapshot_lock(
4985 &self,
4986 snapshot: &SharedSnapshot,
4987 caller: Option<&'static str>,
4988 ) -> Result<(ModuleStatus, Option<SpawnedFileIdentity>), SuperviseError> {
4989 let restart_policy = self
4990 .inner
4991 .configuration
4992 .lock()
4993 .map_err(|_| SuperviseError::StatePoisoned {
4994 module_id: Some(self.inner.module_id.clone()),
4995 })?
4996 .restart_policy;
4997 let mut guard = match caller {
4998 Some(caller) => lock_snapshot_for_control(snapshot, &self.inner.module_id, caller)?,
4999 None => lock_snapshot(snapshot)?,
5000 };
5001 let restart_count = guard.crash_restarts_in_window(restart_policy.window, Instant::now());
5004 let snapshot = guard.clone();
5005 drop(guard);
5006 let drain_timeout = *self.inner.effective_drain_timeout.lock().map_err(|_| {
5007 SuperviseError::StatePoisoned {
5008 module_id: Some(self.inner.module_id.clone()),
5009 }
5010 })?;
5011 let registration_active = self
5012 .inner
5013 .registry
5014 .get_module(&self.inner.module_id)
5015 .map_err(SuperviseError::Registry)?
5016 .is_some();
5017 let protocol = snapshot
5018 .spawned_protocol
5019 .unwrap_or(self.declared_protocol()?);
5020 let running_process =
5021 snapshot.enabled && snapshot.state == ModuleState::Running && snapshot.process_alive;
5022 let live = match protocol {
5028 ModuleProtocol::Subc => running_process && registration_active,
5029 ModuleProtocol::None => running_process,
5030 };
5031 let retained = self.inner.retained.waiting_detail(&self.inner.module_id);
5034 let carry_configured = self
5035 .inner
5036 .configuration
5037 .lock()
5038 .map_err(|_| SuperviseError::StatePoisoned {
5039 module_id: Some(self.inner.module_id.clone()),
5040 })?
5041 .spec
5042 .carry_containment;
5043 let recovery_block = carries_containment(
5044 carry_configured,
5045 self.inner
5046 .retained
5047 .has_carried_container(&self.inner.module_id),
5048 )
5049 .then(|| self.inner.retained.recovery_block())
5050 .flatten();
5051 let launch_nonce_source = observed_launch_nonce_source(&snapshot);
5052 let pid = snapshot.reported_pid();
5053 let mut health = snapshot.health;
5054 if let Some(detail) = recovery_block
5055 .as_ref()
5056 .or_else(|| retained.as_ref().map(|(_, detail)| detail))
5057 {
5058 health.detail = Some(match health.detail {
5059 Some(previous) => format!("{previous}; {detail}"),
5060 None => detail.clone(),
5061 });
5062 }
5063
5064 Ok((
5065 ModuleStatus {
5066 admission_refused: snapshot.admission_refused,
5067 legacy_registration_spawn: snapshot.legacy_registration_spawn,
5068 registration_declaration: snapshot.registration_declaration.clone(),
5069 stop_reason: snapshot.stop_reason,
5070 waiting_for_previous_pid: retained
5071 .as_ref()
5072 .map(|(pid, _)| *pid)
5073 .filter(|pid| *pid > 0)
5074 .or(snapshot.waiting_for_previous_pid),
5075 waiting_for_previous_detail: recovery_block
5076 .or_else(|| retained.map(|(_, detail)| detail))
5077 .or(snapshot.waiting_for_previous_detail),
5078 module_id: self.inner.module_id.clone(),
5079 launch_nonce_source,
5080 state: snapshot.state,
5081 enabled: snapshot.enabled,
5082 process_alive: snapshot.process_alive,
5083 registration_active,
5084 protocol,
5085 live,
5086 restart_count,
5087 lifetime_restarts: snapshot.lifetime_restarts,
5088 spawn_generation: snapshot.spawn_generation,
5089 swap_outcome: snapshot.swap_outcome,
5090 max_restarts: restart_policy.max_restarts,
5091 restart_window: restart_policy.window,
5092 drain_timeout,
5093 restart_backoff: restart_policy.backoff,
5094 restart_max_backoff: restart_policy.max_backoff,
5095 pid,
5096 spawned_at_ms: snapshot.spawned_at_ms,
5097 spawned_from: snapshot.spawned_from,
5098 launch_spec_digest: snapshot.launch_spec_digest,
5099 process_start_time: snapshot.process_start_time,
5100 last_exit: snapshot.last_exit,
5101 health,
5102 },
5103 snapshot.spawned_file_identity.clone(),
5104 ))
5105 }
5106
5107 #[cfg(test)]
5108 pub(crate) fn hold_snapshot_for_test(
5109 &self,
5110 acquired: std::sync::mpsc::Sender<()>,
5111 hold: Duration,
5112 ) -> std::thread::JoinHandle<()> {
5113 let snapshot = Arc::clone(&self.inner.snapshot);
5114 std::thread::spawn(move || {
5115 let _guard = snapshot.lock().expect("test snapshot lock is not poisoned");
5116 acquired
5117 .send(())
5118 .expect("test receiver waits for snapshot lock");
5119 std::thread::sleep(hold);
5120 })
5121 }
5122
5123 pub(crate) async fn status_and_running_image_agreement(
5129 &self,
5130 ) -> Result<(ModuleStatus, subc_control::RunningImageAgreement), SuperviseError> {
5131 let (status, identity) = self.status_with_snapshot_lock(&self.inner.snapshot, None)?;
5132 let image = self
5133 .inner
5134 .provenance_probe
5135 .observe(
5136 status.pid,
5137 status.spawned_from.as_deref(),
5138 identity,
5139 status.process_start_time,
5140 )
5141 .await;
5142 Ok((status, image))
5143 }
5144
5145 pub(crate) async fn running_image_agreement(&self) -> subc_control::RunningImageAgreement {
5146 let snapshot = match lock_snapshot(&self.inner.snapshot) {
5147 Ok(snapshot) => snapshot.clone(),
5148 Err(_) => {
5149 return subc_control::RunningImageAgreement::Unavailable {
5150 reason: subc_control::RunningImageUnavailableReason::NotRunning,
5151 };
5152 }
5153 };
5154 self.inner
5155 .provenance_probe
5156 .observe(
5157 snapshot.reported_pid(),
5158 snapshot.spawned_from.as_deref(),
5159 snapshot.spawned_file_identity.clone(),
5160 snapshot.process_start_time,
5161 )
5162 .await
5163 }
5164
5165 pub(crate) fn child_resource_usage(&self) -> subc_control::ChildResourceUsage {
5168 #[cfg(windows)]
5169 {
5170 let image = lock_snapshot(&self.inner.snapshot)
5171 .ok()
5172 .and_then(|snapshot| {
5173 snapshot
5174 .spawned_file_identity
5175 .as_ref()
5176 .and_then(|identity| identity.windows_image.clone())
5177 });
5178 match image {
5179 Some(image) => {
5180 crate::child_resources::read_windows_handle(image.process(), image.start_time())
5181 }
5182 None => subc_control::ChildResourceUsage::Unavailable {
5183 reason: subc_control::ChildResourceUnavailableReason::NotRunning,
5184 },
5185 }
5186 }
5187 #[cfg(not(windows))]
5188 {
5189 let (pid, start_time) = match lock_snapshot(&self.inner.snapshot) {
5190 Ok(snapshot) => (snapshot.reported_pid(), snapshot.process_start_time),
5191 Err(_) => {
5192 return subc_control::ChildResourceUsage::Unavailable {
5193 reason: subc_control::ChildResourceUnavailableReason::Unreadable,
5194 }
5195 }
5196 };
5197 crate::child_resources::read(pid, start_time)
5198 }
5199 }
5200
5201 #[cfg(all(test, any(target_os = "linux", windows)))]
5202 pub(crate) fn subtree_target(&self) -> crate::subtree_resources::Target {
5203 self.inner
5204 .snapshot
5205 .try_lock()
5206 .map(|snapshot| snapshot.subtree_target.clone())
5207 .unwrap_or(crate::subtree_resources::Target::Unavailable("read_failed"))
5208 }
5209
5210 #[cfg(test)]
5211 pub(crate) fn set_subtree_target_for_test(&self, target: crate::subtree_resources::Target) {
5212 self.inner.snapshot.lock().unwrap().subtree_target = target;
5213 }
5214
5215 pub(crate) fn will_recover_after_connection_loss(&self) -> Result<bool, SuperviseError> {
5216 let mut snapshot = lock_snapshot(&self.inner.snapshot)?;
5217 Ok(match snapshot.state {
5218 ModuleState::Restarting => true,
5219 ModuleState::Failed | ModuleState::Disabled => false,
5220 _ if snapshot.enabled && snapshot.respawn_pending => true,
5221 _ => daemon_will_restart(
5222 &mut snapshot,
5223 &self
5224 .inner
5225 .configuration
5226 .lock()
5227 .map_err(|_| SuperviseError::StatePoisoned {
5228 module_id: Some(self.inner.module_id.clone()),
5229 })?
5230 .restart_policy,
5231 Instant::now(),
5232 ),
5233 })
5234 }
5235
5236 #[cfg(test)]
5237 pub(crate) fn is_warming(&self) -> Result<bool, SuperviseError> {
5238 self.is_warming_with_snapshot_lock(None)
5239 }
5240
5241 pub(crate) fn is_warming_for_control(
5242 &self,
5243 caller: &'static str,
5244 ) -> Result<bool, SuperviseError> {
5245 self.is_warming_with_snapshot_lock(Some(caller))
5246 }
5247
5248 fn is_warming_with_snapshot_lock(
5249 &self,
5250 caller: Option<&'static str>,
5251 ) -> Result<bool, SuperviseError> {
5252 let snapshot = match caller {
5253 Some(caller) => {
5254 lock_snapshot_for_control(&self.inner.snapshot, &self.inner.module_id, caller)?
5255 }
5256 None => lock_snapshot(&self.inner.snapshot)?,
5257 }
5258 .clone();
5259 Ok(matches!(
5260 snapshot.state,
5261 ModuleState::Starting | ModuleState::Running | ModuleState::Restarting
5262 ))
5263 }
5264
5265 pub async fn drain(&self) -> Result<(), SuperviseError> {
5267 self.stop().await
5268 }
5269
5270 pub(crate) async fn retire_requested(
5271 &self,
5272 requester: Option<Principal>,
5273 ) -> Result<(), SuperviseError> {
5274 match self.state()? {
5275 ModuleState::Stopped => return Ok(()),
5276 ModuleState::Failed
5277 if lock_snapshot(&self.inner.snapshot)?
5278 .failed_retry
5279 .pending
5280 .is_none() =>
5281 {
5282 return Ok(())
5283 }
5284 ModuleState::Failed
5285 | ModuleState::Starting
5286 | ModuleState::Running
5287 | ModuleState::Unresponsive
5288 | ModuleState::Restarting
5289 | ModuleState::Draining
5290 | ModuleState::Disabled => {}
5291 }
5292
5293 let (reply_tx, reply_rx) = oneshot::channel();
5294 self.inner
5295 .commands
5296 .send(SupervisorCommand::Retire {
5297 requester,
5298 reply: reply_tx,
5299 })
5300 .await
5301 .map_err(|_| SuperviseError::CommandClosed {
5302 module_id: self.inner.module_id.clone(),
5303 })?;
5304 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5305 module_id: self.inner.module_id.clone(),
5306 })?
5307 }
5308
5309 pub async fn stop(&self) -> Result<(), SuperviseError> {
5310 self.stop_requested(None).await
5311 }
5312
5313 pub(crate) async fn stop_requested(
5314 &self,
5315 requester: Option<Principal>,
5316 ) -> Result<(), SuperviseError> {
5317 match self.state()? {
5318 ModuleState::Stopped => return Ok(()),
5319 ModuleState::Failed
5320 if lock_snapshot(&self.inner.snapshot)?
5321 .failed_retry
5322 .pending
5323 .is_none() =>
5324 {
5325 return Ok(())
5326 }
5327 ModuleState::Failed
5328 | ModuleState::Starting
5329 | ModuleState::Running
5330 | ModuleState::Unresponsive
5331 | ModuleState::Restarting
5332 | ModuleState::Draining
5333 | ModuleState::Disabled => {}
5334 }
5335
5336 let (reply_tx, reply_rx) = oneshot::channel();
5337 self.inner
5338 .commands
5339 .send(SupervisorCommand::Drain {
5340 requester,
5341 reply: reply_tx,
5342 })
5343 .await
5344 .map_err(|_| SuperviseError::CommandClosed {
5345 module_id: self.inner.module_id.clone(),
5346 })?;
5347 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5348 module_id: self.inner.module_id.clone(),
5349 })?
5350 }
5351
5352 pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
5353 self.restart_requested(drain_timeout_ms, None).await
5354 }
5355
5356 pub(crate) async fn restart_requested(
5357 &self,
5358 drain_timeout_ms: Option<u64>,
5359 requester: Option<Principal>,
5360 ) -> Result<(), SuperviseError> {
5361 let queued_at = Instant::now();
5362 let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
5363 let (reply_tx, reply_rx) = oneshot::channel();
5364 self.inner
5365 .commands
5366 .send(SupervisorCommand::Restart {
5367 requester,
5368 drain_timeout_ms,
5369 received_at_generation,
5370 queued_at,
5371 reply: reply_tx,
5372 })
5373 .await
5374 .map_err(|_| SuperviseError::CommandClosed {
5375 module_id: self.inner.module_id.clone(),
5376 })?;
5377 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5378 module_id: self.inner.module_id.clone(),
5379 })?
5380 }
5381
5382 pub async fn swap(
5388 &self,
5389 ready_timeout: Option<Duration>,
5390 ) -> Result<SwapOutcome, SuperviseError> {
5391 self.swap_requested(ready_timeout, None).await
5392 }
5393
5394 pub(crate) async fn swap_requested(
5395 &self,
5396 ready_timeout: Option<Duration>,
5397 requester: Option<Principal>,
5398 ) -> Result<SwapOutcome, SuperviseError> {
5399 let (reply_tx, reply_rx) = oneshot::channel();
5400 self.inner
5401 .commands
5402 .send(SupervisorCommand::Swap {
5403 requester,
5404 ready_timeout,
5405 reply: reply_tx,
5406 })
5407 .await
5408 .map_err(|_| SuperviseError::CommandClosed {
5409 module_id: self.inner.module_id.clone(),
5410 })?;
5411 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5412 module_id: self.inner.module_id.clone(),
5413 })?
5414 }
5415
5416 pub async fn reload(&self) -> Result<(), SuperviseError> {
5417 self.reload_requested(None).await
5418 }
5419
5420 pub(crate) async fn reload_requested(
5421 &self,
5422 requester: Option<Principal>,
5423 ) -> Result<(), SuperviseError> {
5424 let (reply_tx, reply_rx) = oneshot::channel();
5425 self.inner
5426 .commands
5427 .send(SupervisorCommand::Reload {
5428 requester,
5429 reply: reply_tx,
5430 })
5431 .await
5432 .map_err(|_| SuperviseError::CommandClosed {
5433 module_id: self.inner.module_id.clone(),
5434 })?;
5435 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5436 module_id: self.inner.module_id.clone(),
5437 })?
5438 }
5439
5440 pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
5441 self.set_enabled_requested(enabled, None).await
5442 }
5443
5444 pub(crate) async fn set_enabled_requested(
5445 &self,
5446 enabled: bool,
5447 requester: Option<Principal>,
5448 ) -> Result<bool, SuperviseError> {
5449 self.set_enabled_with_budget_policy(enabled, requester, true)
5450 .await
5451 }
5452
5453 pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
5454 self.set_enabled_with_budget_policy(true, None, false).await
5455 }
5456
5457 #[cfg(all(test, unix))]
5458 pub(crate) fn seed_crash_budget_for_test(&self, count: u32) {
5459 let policy = self.inner.configuration.lock().unwrap().restart_policy;
5460 let mut state = self.inner.snapshot.lock().unwrap();
5461 for _ in 0..count {
5462 state.record_crash_restart(&policy, Instant::now());
5463 }
5464 }
5465
5466 async fn set_enabled_with_budget_policy(
5467 &self,
5468 enabled: bool,
5469 requester: Option<Principal>,
5470 reset_budget: bool,
5471 ) -> Result<bool, SuperviseError> {
5472 let (reply_tx, reply_rx) = oneshot::channel();
5473 self.inner
5474 .commands
5475 .send(SupervisorCommand::SetEnabled {
5476 requester,
5477 enabled,
5478 reset_budget,
5479 reply: reply_tx,
5480 })
5481 .await
5482 .map_err(|_| SuperviseError::CommandClosed {
5483 module_id: self.inner.module_id.clone(),
5484 })?;
5485 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5486 module_id: self.inner.module_id.clone(),
5487 })?
5488 }
5489
5490 pub(crate) fn declared_protocol(&self) -> Result<ModuleProtocol, SuperviseError> {
5494 let configured = self
5495 .inner
5496 .configuration
5497 .lock()
5498 .map_err(|_| SuperviseError::StatePoisoned {
5499 module_id: Some(self.inner.module_id.clone()),
5500 })?
5501 .spec
5502 .protocol;
5503 let state = lock_snapshot(&self.inner.snapshot)?;
5504 Ok(state.spawned_protocol.unwrap_or(configured))
5505 }
5506
5507 pub(crate) fn configuration(&self) -> Result<(ModuleSpec, HealthConfig), SuperviseError> {
5508 let configuration =
5509 self.inner
5510 .configuration
5511 .lock()
5512 .map_err(|_| SuperviseError::StatePoisoned {
5513 module_id: Some(self.inner.module_id.clone()),
5514 })?;
5515 Ok((configuration.spec.clone(), configuration.health.clone()))
5516 }
5517
5518 pub(crate) fn configured_register_timeout(&self) -> Result<Duration, SuperviseError> {
5519 self.inner
5520 .configuration
5521 .lock()
5522 .map(|configuration| configuration.register_timeout)
5523 .map_err(|_| SuperviseError::StatePoisoned {
5524 module_id: Some(self.inner.module_id.clone()),
5525 })
5526 }
5527
5528 pub(crate) fn configured_enabled(&self) -> Result<bool, SuperviseError> {
5529 self.inner
5530 .configuration
5531 .lock()
5532 .map(|configuration| configuration.enabled)
5533 .map_err(|_| SuperviseError::StatePoisoned {
5534 module_id: Some(self.inner.module_id.clone()),
5535 })
5536 }
5537
5538 #[cfg(any(test, feature = "test-support"))]
5542 pub async fn update_spec_for_test(&self, spec: ModuleSpec) -> Result<(), SuperviseError> {
5543 let (_, health) = self.configuration()?;
5544 let drain_timeout_ms = u64::try_from(
5545 self.inner
5546 .effective_drain_timeout
5547 .lock()
5548 .unwrap_or_else(|poisoned| poisoned.into_inner())
5549 .as_millis(),
5550 )
5551 .ok();
5552 self.update_configuration(spec, health, drain_timeout_ms)
5553 .await
5554 }
5555
5556 pub(crate) async fn reconcile_approved_configuration(
5557 &self,
5558 approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5559 ) -> Result<(), SuperviseError> {
5560 let entry = approved
5561 .module_entry(&self.inner.module_id)
5562 .map_err(|error| SuperviseError::InvalidSpec {
5563 reason: error.to_string(),
5564 })?;
5565 validate_spec(&entry.module_spec())?;
5566 let (reply, received) = oneshot::channel();
5567 self.inner
5568 .commands
5569 .send(SupervisorCommand::ApprovedConfiguration { approved, reply })
5570 .await
5571 .map_err(|_| SuperviseError::CommandClosed {
5572 module_id: self.inner.module_id.clone(),
5573 })?;
5574 received.await.map_err(|_| SuperviseError::CommandClosed {
5575 module_id: self.inner.module_id.clone(),
5576 })??;
5577 let mut configuration =
5578 self.inner
5579 .configuration
5580 .lock()
5581 .map_err(|_| SuperviseError::StatePoisoned {
5582 module_id: Some(self.inner.module_id.clone()),
5583 })?;
5584 configuration.spec = entry.module_spec();
5585 configuration.enabled = entry.enabled;
5586 configuration.health = entry.health;
5587 configuration.register_timeout = entry.register_timeout;
5588 configuration.restart_policy = entry.restart;
5589 Ok(())
5590 }
5591
5592 pub(crate) async fn update_configuration(
5593 &self,
5594 spec: ModuleSpec,
5595 health: HealthConfig,
5596 drain_timeout_ms: Option<u64>,
5597 ) -> Result<(), SuperviseError> {
5598 if spec.module_id != self.inner.module_id {
5599 return Err(SuperviseError::InvalidSpec {
5600 reason: "a supervised module's module_id cannot be changed".to_string(),
5601 });
5602 }
5603 validate_spec(&spec)?;
5604 let (reply_tx, reply_rx) = oneshot::channel();
5605 self.inner
5606 .commands
5607 .send(SupervisorCommand::UpdateConfiguration {
5608 spec: spec.clone(),
5609 health: health.clone(),
5610 drain_timeout_ms,
5611 reply: reply_tx,
5612 })
5613 .await
5614 .map_err(|_| SuperviseError::CommandClosed {
5615 module_id: self.inner.module_id.clone(),
5616 })?;
5617 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
5618 module_id: self.inner.module_id.clone(),
5619 })??;
5620 let mut configuration =
5621 self.inner
5622 .configuration
5623 .lock()
5624 .map_err(|_| SuperviseError::StatePoisoned {
5625 module_id: Some(self.inner.module_id.clone()),
5626 })?;
5627 configuration.spec = spec;
5628 configuration.health = health;
5629 Ok(())
5630 }
5631}
5632
5633impl Drop for SupervisedModuleInner {
5634 fn drop(&mut self) {
5635 let Ok(mut monitor) = self.monitor.lock() else {
5636 return;
5637 };
5638 if let Some(monitor) = monitor.as_ref().filter(|monitor| !monitor.is_finished()) {
5639 let _ = update_snapshot(&self.snapshot, Some(&self.module_id), |state| {
5640 state.state = ModuleState::Stopped;
5641 clear_current_process_facts(state);
5642 });
5643 monitor.abort();
5644 }
5645 let _ = monitor.take();
5646 }
5647}
5648
5649#[derive(Debug)]
5650enum SupervisorCommand {
5651 ApprovedConfiguration {
5652 approved: crate::config_gate::runtime::ApprovedDaemonConfiguration,
5653 reply: oneshot::Sender<Result<(), SuperviseError>>,
5654 },
5655 ConfigPolicyProbe {
5656 connection: crate::ConnectionId,
5657 generation: u64,
5658 attempt: u64,
5659 },
5660 ConfigApplyRestart {
5661 generation: u64,
5662 supersedes_swap: bool,
5663 },
5664 ConfigExitHold {
5665 reply: oneshot::Sender<Result<(), SuperviseError>>,
5666 },
5667 ConfigDeliveryFailed {
5668 connection: crate::ConnectionId,
5669 hold: bool,
5670 },
5671 Drain {
5672 requester: Option<Principal>,
5673 reply: oneshot::Sender<Result<(), SuperviseError>>,
5674 },
5675 Retire {
5676 requester: Option<Principal>,
5677 reply: oneshot::Sender<Result<(), SuperviseError>>,
5678 },
5679 Restart {
5680 requester: Option<Principal>,
5681 drain_timeout_ms: Option<u64>,
5686 received_at_generation: u64,
5690 queued_at: Instant,
5693 reply: oneshot::Sender<Result<(), SuperviseError>>,
5694 },
5695 Reload {
5696 requester: Option<Principal>,
5697 reply: oneshot::Sender<Result<(), SuperviseError>>,
5698 },
5699 SetEnabled {
5700 reset_budget: bool,
5701 requester: Option<Principal>,
5702 enabled: bool,
5703 reply: oneshot::Sender<Result<bool, SuperviseError>>,
5704 },
5705 UpdateConfiguration {
5706 spec: ModuleSpec,
5707 health: HealthConfig,
5708 drain_timeout_ms: Option<u64>,
5711 reply: oneshot::Sender<Result<(), SuperviseError>>,
5712 },
5713 Swap {
5714 requester: Option<Principal>,
5715 ready_timeout: Option<Duration>,
5718 reply: oneshot::Sender<Result<SwapOutcome, SuperviseError>>,
5720 },
5721}
5722
5723#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5727pub enum SwapOutcome {
5728 Cutover,
5729 SupersededByConfigRestart,
5730}
5731
5732impl SwapOutcome {
5733 pub fn as_str(self) -> &'static str {
5734 match self {
5735 Self::Cutover => "cutover",
5736 Self::SupersededByConfigRestart => "superseded_by_config_restart",
5737 }
5738 }
5739}
5740
5741#[derive(Debug)]
5742pub enum SuperviseError {
5743 ConfigHeld {
5744 module_id: String,
5745 code: String,
5746 detail: String,
5747 },
5748 ConfigDeliveryDeferred {
5749 module_id: String,
5750 },
5751 InvalidSpec {
5752 reason: String,
5753 },
5754 Spawn {
5755 program: PathBuf,
5756 source: io::Error,
5757 cgroup_path: Option<PathBuf>,
5758 },
5759 Cgroup {
5760 module_id: String,
5761 source: io::Error,
5762 },
5763 LaunchNonce {
5766 reason: String,
5767 },
5768 Wait {
5769 module_id: String,
5770 source: io::Error,
5771 },
5772 Kill {
5773 module_id: String,
5774 source: io::Error,
5775 },
5776 Forwarding(ForwardingError),
5777 Registry(RegistryError),
5778 ReloadUnavailable {
5779 module_id: String,
5780 reason: String,
5781 },
5782 Disabled {
5787 module_id: String,
5788 },
5789 ReloadFailed {
5790 module_id: String,
5791 reason: String,
5792 },
5793 RegistrationStillActive {
5794 module_id: String,
5795 waited: Duration,
5796 },
5797 StatePoisoned {
5798 module_id: Option<String>,
5799 },
5800 CommandClosed {
5801 module_id: String,
5802 },
5803 SwapInProgress {
5807 module_id: String,
5808 },
5809 SwapRefused {
5811 module_id: String,
5812 reason: SwapRefusal,
5813 },
5814 SwapFailed {
5818 module_id: String,
5819 arm: SwapFailureArm,
5820 detail: String,
5821 candidate_exit: Option<ExitReport>,
5824 },
5825}
5826
5827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5829pub enum SwapRefusal {
5830 OverlapExclusive,
5832 NotRegistered,
5835 ProtocolNone,
5838 NotConfigured,
5841 AlreadySwapping,
5843}
5844
5845impl SwapRefusal {
5846 pub fn as_str(self) -> &'static str {
5847 match self {
5848 Self::OverlapExclusive => "overlap_exclusive",
5849 Self::NotRegistered => "not_registered",
5850 Self::ProtocolNone => "protocol_none",
5851 Self::NotConfigured => "not_configured",
5852 Self::AlreadySwapping => "already_swapping",
5853 }
5854 }
5855}
5856
5857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5860pub enum SwapFailureArm {
5861 SpawnFailed,
5863 NeverRegistered,
5865 NeverReady,
5867 CandidateExited,
5869 CandidateUnhealthy,
5871 Interrupted,
5875 CutoverLost,
5880}
5881
5882impl SwapFailureArm {
5883 pub fn as_str(self) -> &'static str {
5884 match self {
5885 Self::SpawnFailed => "spawn_failed",
5886 Self::NeverRegistered => "never_registered",
5887 Self::NeverReady => "never_ready",
5888 Self::CandidateExited => "candidate_exited",
5889 Self::CandidateUnhealthy => "candidate_unhealthy",
5890 Self::Interrupted => "interrupted",
5891 Self::CutoverLost => "cutover_lost",
5892 }
5893 }
5894}
5895
5896impl SuperviseError {
5897 pub(crate) fn is_config_gate_error(&self) -> bool {
5898 match self {
5899 Self::ConfigHeld { .. } => true,
5900 Self::Spawn { source, .. } => source
5901 .get_ref()
5902 .is_some_and(|cause| cause.is::<crate::config_gate::GateError>()),
5903 _ => false,
5904 }
5905 }
5906}
5907
5908impl fmt::Display for SuperviseError {
5909 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5910 match self {
5911 Self::ConfigHeld { module_id, code, detail } => write!(f, "{code}: module '{module_id}' held: {detail}"),
5912 Self::ConfigDeliveryDeferred { module_id } => write!(f, "config_gated: module '{module_id}' is waiting for its exited delivery target's failure record"),
5913 Self::InvalidSpec { reason } => write!(f, "invalid module spec: {reason}"),
5914 Self::Spawn {
5915 program,
5916 source,
5917 cgroup_path: Some(cgroup_path),
5918 } => write!(
5919 f,
5920 "failed to place module in cgroup '{}' while spawning '{}': {source}",
5921 cgroup_path.display(),
5922 program.display()
5923 ),
5924 Self::Spawn {
5925 program,
5926 source,
5927 cgroup_path: None,
5928 } => write!(
5929 f,
5930 "failed to spawn module '{}': {source}",
5931 program.display()
5932 ),
5933 Self::Cgroup { module_id, source } => {
5934 write!(
5935 f,
5936 "failed to prepare cgroup for module '{module_id}': {source}"
5937 )
5938 }
5939 Self::LaunchNonce { reason } => {
5940 write!(
5941 f,
5942 "failed to generate reserved-module launch nonce: {reason}"
5943 )
5944 }
5945 Self::Wait { module_id, source } => {
5946 write!(f, "failed to wait for module '{module_id}': {source}")
5947 }
5948 Self::Kill { module_id, source } => {
5949 write!(f, "failed to kill module '{module_id}': {source}")
5950 }
5951 Self::Forwarding(err) => write!(f, "forwarding error: {err}"),
5952 Self::Registry(err) => write!(f, "registry error: {err}"),
5953 Self::ReloadUnavailable { module_id, reason } => {
5954 write!(f, "reload unavailable for module '{module_id}': {reason}")
5955 }
5956 Self::Disabled { module_id } => {
5957 write!(
5958 f,
5959 "module '{module_id}' is disabled; enable it before restart or reload"
5960 )
5961 }
5962 Self::ReloadFailed { module_id, reason } => {
5963 write!(f, "reload failed for module '{module_id}': {reason}")
5964 }
5965 Self::RegistrationStillActive { module_id, waited } => write!(
5966 f,
5967 "module '{module_id}' registration remained active after waiting {waited:?}"
5968 ),
5969 Self::StatePoisoned { module_id } => match module_id {
5970 Some(module_id) => {
5971 write!(f, "supervisor state for module '{module_id}' was poisoned")
5972 }
5973 None => write!(f, "supervisor state was poisoned"),
5974 },
5975 Self::CommandClosed { module_id } => {
5976 write!(
5977 f,
5978 "supervisor command channel for module '{module_id}' is closed"
5979 )
5980 }
5981 Self::SwapInProgress { module_id } => write!(
5982 f,
5983 "module '{module_id}' is being swapped; retry once the swap has cut over or failed, or stop the module to abort the swap"
5984 ),
5985 Self::SwapRefused { module_id, reason } => match reason {
5986 SwapRefusal::OverlapExclusive => write!(
5987 f,
5988 "module '{module_id}' is declared overlap: \"exclusive\" (the default): two processes of it must not run at once, so it cannot be swapped; use a plain restart, or declare overlap: \"safe\" in its config if it really tolerates a second process"
5989 ),
5990 SwapRefusal::NotRegistered => write!(
5991 f,
5992 "module '{module_id}' is not registered, so there is no serving process to keep while a replacement warms; use a plain restart"
5993 ),
5994 SwapRefusal::ProtocolNone => write!(
5995 f,
5996 "module '{module_id}' is protocol: \"none\" and never registers, so a swap could never see its replacement become ready; use a plain restart"
5997 ),
5998 SwapRefusal::NotConfigured => write!(
5999 f,
6000 "module '{module_id}' cannot be swapped: the supervisor was built without the forwarding table or shared handle a swap needs"
6001 ),
6002 SwapRefusal::AlreadySwapping => {
6003 write!(f, "module '{module_id}' is already being swapped")
6004 }
6005 },
6006 Self::SwapFailed {
6007 module_id,
6008 arm,
6009 detail,
6010 ..
6011 } => write!(
6012 f,
6013 "swap of module '{module_id}' failed ({}): {detail}; the running process was left serving",
6014 arm.as_str()
6015 ),
6016 }
6017 }
6018}
6019
6020impl Error for SuperviseError {
6021 fn source(&self) -> Option<&(dyn Error + 'static)> {
6022 match self {
6023 Self::Spawn { source, .. }
6024 | Self::Cgroup { source, .. }
6025 | Self::Wait { source, .. }
6026 | Self::Kill { source, .. } => Some(source),
6027 Self::Forwarding(err) => Some(err),
6028 Self::Registry(err) => Some(err),
6029 Self::LaunchNonce { .. }
6030 | Self::ConfigDeliveryDeferred { .. }
6031 | Self::ConfigHeld { .. }
6032 | Self::InvalidSpec { .. }
6033 | Self::ReloadUnavailable { .. }
6034 | Self::Disabled { .. }
6035 | Self::ReloadFailed { .. }
6036 | Self::RegistrationStillActive { .. }
6037 | Self::StatePoisoned { .. }
6038 | Self::CommandClosed { .. }
6039 | Self::SwapInProgress { .. }
6040 | Self::SwapRefused { .. }
6041 | Self::SwapFailed { .. } => None,
6042 }
6043 }
6044}
6045
6046pub(crate) fn validate_spec(spec: &ModuleSpec) -> Result<(), SuperviseError> {
6047 if spec.carry_containment && spec.overlap == ModuleOverlap::Safe {
6048 return Err(SuperviseError::InvalidSpec {
6049 reason: "carry_containment cannot be combined with overlap: safe".to_owned(),
6050 });
6051 }
6052 if spec.module_id.trim().is_empty() {
6053 return Err(SuperviseError::InvalidSpec {
6054 reason: "module_id must not be empty".to_string(),
6055 });
6056 }
6057
6058 Ok(())
6059}
6060
6061#[derive(Debug, Default)]
6062struct HealthProbeRuntime {
6063 spawn_generation: Option<u64>,
6064 configured_health: Option<HealthConfig>,
6065 registered_connection: Option<crate::ConnectionId>,
6066 advertised: bool,
6067 next_probe_at: Option<Instant>,
6068 probe_index: u64,
6069}
6070
6071fn running_protocol(spec: &ModuleSpec, snapshot: &SharedSnapshot) -> ModuleProtocol {
6072 lock_snapshot(snapshot)
6073 .ok()
6074 .and_then(|state| state.spawned_protocol)
6075 .unwrap_or(spec.protocol)
6076}
6077
6078impl HealthProbeRuntime {
6079 fn refresh_registration(
6080 &mut self,
6081 spec: &ModuleSpec,
6082 runtime: &SupervisorRuntimeConfig,
6083 registry: &Registry,
6084 snapshot: &SharedSnapshot,
6085 ) {
6086 let generation = lock_snapshot(snapshot)
6087 .ok()
6088 .map(|state| state.spawn_generation);
6089 if self.spawn_generation != generation {
6090 *self = Self {
6094 spawn_generation: generation,
6095 ..Self::default()
6096 };
6097 }
6098 if self.configured_health.as_ref() != Some(&runtime.health) {
6099 self.configured_health = Some(runtime.health.clone());
6100 self.next_probe_at = None;
6101 self.registered_connection = None;
6102 self.probe_index = 0;
6103 }
6104 if running_protocol(spec, snapshot) == ModuleProtocol::None {
6108 self.registered_connection = None;
6109 self.advertised = runtime.health.http.is_some();
6110 if !self.advertised {
6111 self.next_probe_at = None;
6112 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6113 let unknown = ModuleHealthStatus::default();
6114 if state.health != unknown {
6115 state.health = unknown;
6116 state.last_probe_evidence = None;
6117 }
6118 });
6119 } else if self.next_probe_at.is_none() {
6120 self.next_probe_at = Some(
6121 Instant::now()
6122 + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6123 );
6124 }
6125 return;
6126 }
6127
6128 let registration = match registry.get_module(&spec.module_id) {
6129 Ok(registration) => registration,
6130 Err(err) => {
6131 warn!(module_id = %spec.module_id, error = %err, "health prober could not read registry");
6132 self.advertised = false;
6133 self.next_probe_at = None;
6134 return;
6135 }
6136 };
6137
6138 let Some(registration) = registration else {
6139 self.registered_connection = None;
6140 self.advertised = false;
6141 self.next_probe_at = None;
6142 return;
6143 };
6144
6145 let advertised = registration
6146 .control_ops
6147 .iter()
6148 .any(|op| op == MODULE_CONTROL_OP_HEALTH_CHECK);
6149 if !advertised {
6150 self.registered_connection = Some(registration.connection_id);
6151 self.advertised = false;
6152 self.next_probe_at = None;
6153 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6154 if state.health.status != SupervisorHealthStatus::Unknown
6155 || state.health.consecutive_failures != 0
6156 || state.health.last_probe_ms.is_some()
6157 || state.health.detail.is_some()
6158 || state.health.metrics.is_some()
6159 {
6160 state.health.status = SupervisorHealthStatus::Unknown;
6161 state.last_probe_evidence = None;
6162 state.health.consecutive_failures = 0;
6163 state.health.last_probe_ms = None;
6164 state.health.detail = None;
6165 state.health.metrics = None;
6166 }
6167 });
6168 return;
6169 }
6170
6171 let reregistered = self.registered_connection != Some(registration.connection_id);
6172 self.registered_connection = Some(registration.connection_id);
6173 self.advertised = true;
6174 if reregistered || self.next_probe_at.is_none() {
6175 self.probe_index = 0;
6176 self.next_probe_at = Some(
6177 Instant::now() + jittered_health_delay(&spec.module_id, 0, runtime.health.cadence),
6178 );
6179 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6180 state.health.status = SupervisorHealthStatus::Unknown;
6181 state.last_probe_evidence = None;
6182 state.health.consecutive_failures = 0;
6183 state.health.detail = None;
6184 state.health.metrics = None;
6185 });
6186 }
6187 }
6188
6189 fn wake_at(&self) -> Option<Instant> {
6190 if !self.advertised {
6191 return None;
6192 }
6193 self.next_probe_at
6194 }
6195
6196 fn due(&self) -> bool {
6197 self.advertised
6198 && self
6199 .next_probe_at
6200 .is_some_and(|next| Instant::now() >= next)
6201 }
6202
6203 fn schedule_next(&mut self, spec: &ModuleSpec, cadence: Duration) {
6204 self.probe_index = self.probe_index.wrapping_add(1);
6205 self.next_probe_at = Some(
6206 Instant::now() + jittered_health_delay(&spec.module_id, self.probe_index, cadence),
6207 );
6208 }
6209}
6210
6211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6215enum HealthProbeEvidence {
6216 LaneDead,
6218 NoAnswer,
6220 BadAnswer,
6222 Misconfigured,
6224}
6225
6226#[derive(Debug)]
6227struct HealthProbeError {
6228 evidence: HealthProbeEvidence,
6229 message: String,
6230}
6231
6232impl HealthProbeError {
6233 fn lane_dead(message: impl Into<String>) -> Self {
6234 Self::with(HealthProbeEvidence::LaneDead, message)
6235 }
6236
6237 fn no_answer(message: impl Into<String>) -> Self {
6238 Self::with(HealthProbeEvidence::NoAnswer, message)
6239 }
6240
6241 fn bad_answer(message: impl Into<String>) -> Self {
6242 Self::with(HealthProbeEvidence::BadAnswer, message)
6243 }
6244
6245 fn misconfigured(message: impl Into<String>) -> Self {
6246 Self::with(HealthProbeEvidence::Misconfigured, message)
6247 }
6248
6249 fn with(evidence: HealthProbeEvidence, message: impl Into<String>) -> Self {
6250 Self {
6251 evidence,
6252 message: message.into(),
6253 }
6254 }
6255
6256 #[allow(dead_code)]
6265 fn is_proof_of_death(&self) -> bool {
6266 matches!(self.evidence, HealthProbeEvidence::LaneDead)
6267 }
6268
6269 fn label(&self) -> &'static str {
6277 match self.evidence {
6278 HealthProbeEvidence::LaneDead => "lane-dead",
6279 HealthProbeEvidence::NoAnswer => "no-answer",
6280 HealthProbeEvidence::BadAnswer => "bad-answer",
6281 HealthProbeEvidence::Misconfigured => "daemon-misconfigured",
6282 }
6283 }
6284}
6285
6286impl fmt::Display for HealthProbeError {
6287 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6288 f.write_str(&self.message)
6289 }
6290}
6291
6292async fn run_health_probe_cycle(
6293 spec: &ModuleSpec,
6294 runtime: &SupervisorRuntimeConfig,
6295 registry: &Registry,
6296 process_liveness: &SupervisorProcessLiveness,
6297 snapshot: &SharedSnapshot,
6298 child: &mut Option<SupervisedChild>,
6299) {
6300 let now_ms = unix_ms_now();
6301 let delivery_probe = match &runtime.config_delivery {
6302 Some(delivery) => {
6303 delivery
6304 .health_probe(&spec.module_id, runtime.forwarding.as_deref(), registry)
6305 .await
6306 }
6307 None => None,
6308 };
6309 let http = (running_protocol(spec, snapshot) == ModuleProtocol::None)
6310 .then_some(runtime.health.http.as_deref())
6311 .flatten();
6312 let result = match http {
6313 Some(url) => probe_http_health(url, runtime.health.deadline)
6314 .await
6315 .map(|report| (report, None)),
6316 None => probe_module_health_from(&spec.module_id, runtime, None)
6317 .await
6318 .map(|(report, probed)| (report, Some(probed))),
6319 };
6320 match result {
6321 Ok((report, probed)) => {
6322 handle_health_report(
6323 spec,
6324 runtime,
6325 registry,
6326 process_liveness,
6327 snapshot,
6328 child,
6329 report,
6330 now_ms,
6331 delivery_probe,
6332 probed,
6333 )
6334 .await;
6335 }
6336 Err(err) => {
6337 if http.is_some() {
6338 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6339 state.health.status = SupervisorHealthStatus::Failing;
6340 });
6341 }
6342 handle_health_probe_failure(
6343 spec,
6344 runtime,
6345 registry,
6346 process_liveness,
6347 snapshot,
6348 child,
6349 err,
6350 now_ms,
6351 delivery_probe,
6352 )
6353 .await;
6354 }
6355 }
6356}
6357
6358pub(crate) struct HttpProbeTarget<'a> {
6359 address: std::net::SocketAddr,
6360 localhost: bool,
6361 authority: &'a str,
6362 path: String,
6363}
6364
6365pub(crate) fn parse_http_probe_url(url: &str) -> Result<HttpProbeTarget<'_>, String> {
6368 if url.bytes().any(|b| b <= b' ' || b == 127) || url.contains('#') {
6369 return Err("must not contain whitespace, controls, or a fragment".into());
6370 }
6371 let rest = url
6372 .strip_prefix("http://")
6373 .ok_or("must use plain http://")?;
6374 let split = rest.find(['/', '?']).unwrap_or(rest.len());
6375 let (authority, suffix) = rest.split_at(split);
6376 let (host, port) = if let Some(rest) = authority.strip_prefix("[::1]") {
6377 ("::1", rest)
6378 } else {
6379 let split = authority.find(':').unwrap_or(authority.len());
6380 authority.split_at(split)
6381 };
6382 let ip: std::net::IpAddr = match host {
6383 "127.0.0.1" | "localhost" => std::net::Ipv4Addr::LOCALHOST.into(),
6384 "::1" => std::net::Ipv6Addr::LOCALHOST.into(),
6385 _ => return Err("host must be 127.0.0.1, [::1], or localhost".into()),
6386 };
6387 let port = if port.is_empty() {
6388 80
6389 } else {
6390 port.strip_prefix(':')
6391 .and_then(|p| p.parse::<u16>().ok())
6392 .filter(|p| *p > 0)
6393 .ok_or("must have a valid nonzero TCP port")?
6394 };
6395 let path = if suffix.is_empty() {
6396 "/".into()
6397 } else if suffix.starts_with('?') {
6398 format!("/{suffix}")
6399 } else {
6400 suffix.into()
6401 };
6402 Ok(HttpProbeTarget {
6403 address: std::net::SocketAddr::new(ip, port),
6404 localhost: host == "localhost",
6405 authority,
6406 path,
6407 })
6408}
6409
6410async fn probe_http_health(
6411 url: &str,
6412 deadline: Duration,
6413) -> Result<HealthReport, HealthProbeError> {
6414 use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
6415 let target = parse_http_probe_url(url).map_err(HealthProbeError::misconfigured)?;
6416 let mut response_status = String::new();
6419 let mut body = Vec::new();
6420 let probe = async {
6421 let connection = match tokio::net::TcpStream::connect(target.address).await {
6424 Err(_) if target.localhost => {
6425 tokio::net::TcpStream::connect((
6426 std::net::Ipv6Addr::LOCALHOST,
6427 target.address.port(),
6428 ))
6429 .await
6430 }
6431 result => result,
6432 };
6433 let mut stream = connection.map_err(|error| {
6434 HealthProbeError::no_answer(format!("HTTP connect failed: {error}"))
6435 })?;
6436 stream.write_all(format!("GET {} HTTP/1.1\r\nHost: {}\r\nAccept-Encoding: identity\r\nConnection: close\r\n\r\n", target.path, target.authority).as_bytes()).await
6437 .map_err(|error| HealthProbeError::no_answer(format!("HTTP write failed: {error}")))?;
6438 let mut reader = BufReader::new(stream);
6439 let mut budget = 16 * 1024;
6440 let status = http_line(&mut reader, &mut budget).await?;
6441 let mut words = status.split_ascii_whitespace();
6442 let version = words.next();
6443 let code = words
6444 .next()
6445 .filter(|word| word.len() == 3)
6446 .and_then(|word| word.parse::<u16>().ok());
6447 if !matches!(version, Some("HTTP/1.1" | "HTTP/1.0"))
6448 || !code.is_some_and(|code| (100..600).contains(&code))
6449 {
6450 return Err(HealthProbeError::bad_answer(format!(
6451 "invalid HTTP status: {status}"
6452 )));
6453 }
6454 let code = code.expect("validated status code");
6455 response_status = status.clone();
6456 let mut length = None;
6457 let mut chunked = false;
6458 loop {
6459 let line = http_line(&mut reader, &mut budget).await?;
6460 if line.is_empty() {
6461 break;
6462 }
6463 if let Some((name, value)) = line.split_once(':') {
6464 if name.eq_ignore_ascii_case("content-length") {
6465 length = Some(value.trim().parse::<u64>().map_err(|_| {
6466 HealthProbeError::bad_answer("invalid HTTP Content-Length")
6467 })?);
6468 } else if name.eq_ignore_ascii_case("transfer-encoding") {
6469 chunked = value.trim().eq_ignore_ascii_case("chunked");
6470 }
6471 }
6472 }
6473 if chunked {
6474 while body.len() < 200 {
6475 let line = http_line(&mut reader, &mut budget).await?;
6476 let size = u64::from_str_radix(line.split(';').next().unwrap_or("").trim(), 16)
6477 .map_err(|_| HealthProbeError::bad_answer("invalid HTTP chunk size"))?;
6478 if size == 0 {
6479 break;
6480 }
6481 let count = size.min((200 - body.len()) as u64) as usize;
6482 let start = body.len();
6483 (&mut reader)
6484 .take(count as u64)
6485 .read_to_end(&mut body)
6486 .await
6487 .map_err(|error| {
6488 HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6489 })?;
6490 if body.len() - start != count {
6491 return Err(HealthProbeError::bad_answer("truncated HTTP chunk"));
6492 }
6493 if size > count as u64 || body.len() == 200 {
6494 break;
6495 }
6496 if !http_line(&mut reader, &mut budget).await?.is_empty() {
6497 return Err(HealthProbeError::bad_answer("invalid HTTP chunk delimiter"));
6498 }
6499 }
6500 } else {
6501 reader
6502 .take(length.unwrap_or(200).min(200))
6503 .read_to_end(&mut body)
6504 .await
6505 .map_err(|error| {
6506 HealthProbeError::no_answer(format!("HTTP body read failed: {error}"))
6507 })?;
6508 }
6509 if (200..300).contains(&code) {
6510 Ok(HealthReport::ok())
6511 } else {
6512 Err(HealthProbeError::bad_answer(
6513 "HTTP health endpoint returned non-2xx",
6514 ))
6515 }
6516 };
6517 let mut result = timeout(deadline, probe).await.unwrap_or_else(|_| {
6518 Err(HealthProbeError::no_answer(format!(
6519 "HTTP probe timed out after {deadline:?}"
6520 )))
6521 });
6522 if let Err(error) = &mut result {
6523 if !response_status.is_empty() {
6524 error.message = format!(
6525 "{}; {response_status}: {}",
6526 error.message,
6527 String::from_utf8_lossy(&body)
6528 );
6529 }
6530 }
6531 result
6532}
6533
6534async fn http_line(
6535 reader: &mut tokio::io::BufReader<tokio::net::TcpStream>,
6536 remaining: &mut usize,
6537) -> Result<String, HealthProbeError> {
6538 use tokio::io::{AsyncBufReadExt, AsyncReadExt};
6539 let mut line = Vec::new();
6540 (&mut *reader)
6541 .take(*remaining as u64)
6542 .read_until(b'\n', &mut line)
6543 .await
6544 .map_err(|error| {
6545 HealthProbeError::no_answer(format!("HTTP header read failed: {error}"))
6546 })?;
6547 *remaining -= line.len();
6548 if !line.ends_with(b"\r\n") {
6549 return Err(HealthProbeError::bad_answer(
6550 "HTTP headers are incomplete or exceed 16 KiB",
6551 ));
6552 }
6553 line.truncate(line.len() - 2);
6554 String::from_utf8(line).map_err(|_| HealthProbeError::bad_answer("HTTP header is not UTF-8"))
6555}
6556
6557async fn probe_module_health(
6558 module_id: &str,
6559 runtime: &SupervisorRuntimeConfig,
6560 drain_deadline: Option<Instant>,
6561) -> Result<HealthReport, HealthProbeError> {
6562 probe_module_health_from(module_id, runtime, drain_deadline)
6563 .await
6564 .map(|(report, _)| report)
6565}
6566
6567async fn probe_module_health_from(
6570 module_id: &str,
6571 runtime: &SupervisorRuntimeConfig,
6572 drain_deadline: Option<Instant>,
6573) -> Result<(HealthReport, ConnectionId), HealthProbeError> {
6574 let Some(forwarding) = runtime.forwarding.as_ref() else {
6575 return Err(HealthProbeError::misconfigured(
6576 "supervisor was not configured with a forwarding table",
6577 ));
6578 };
6579 let probe_started_at = Instant::now();
6580 let mut deadline = probe_started_at + runtime.health.deadline;
6581 if let Some(drain_deadline) = drain_deadline {
6582 deadline = deadline.min(drain_deadline);
6583 }
6584 let pending = if drain_deadline.is_some() {
6585 forwarding.begin_drain_health_probe_rpc_for(
6586 module_id,
6587 MODULE_CONTROL_OP_HEALTH_CHECK,
6588 probe_started_at,
6589 deadline,
6590 )
6591 } else {
6592 forwarding.begin_health_probe_rpc_for(
6593 module_id,
6594 MODULE_CONTROL_OP_HEALTH_CHECK,
6595 probe_started_at,
6596 deadline,
6597 )
6598 }
6599 .map_err(|err| {
6600 HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6603 })?;
6604 let probed = pending.endpoint.connection_id;
6605 await_health_probe(forwarding, pending, deadline, runtime.health.deadline)
6606 .await
6607 .map(|report| (report, probed))
6608}
6609
6610async fn probe_endpoint_health(
6617 endpoint: crate::ModuleEndpointId,
6618 runtime: &SupervisorRuntimeConfig,
6619 deadline_cap: Option<Instant>,
6620) -> Result<HealthReport, HealthProbeError> {
6621 let Some(forwarding) = runtime.forwarding.as_ref() else {
6622 return Err(HealthProbeError::misconfigured(
6623 "supervisor was not configured with a forwarding table",
6624 ));
6625 };
6626 let probe_started_at = Instant::now();
6627 let mut deadline = probe_started_at + runtime.health.deadline;
6628 if let Some(cap) = deadline_cap {
6629 deadline = deadline.min(cap);
6630 }
6631 let pending = forwarding
6632 .begin_endpoint_health_probe_rpc_for(
6633 endpoint,
6634 MODULE_CONTROL_OP_HEALTH_CHECK,
6635 probe_started_at,
6636 deadline,
6637 )
6638 .map_err(|err| {
6639 HealthProbeError::lane_dead(format!("failed to begin health.check RPC: {err}"))
6640 })?;
6641 await_health_probe(forwarding, pending, deadline, runtime.health.deadline).await
6642}
6643
6644async fn await_health_probe(
6646 forwarding: &ForwardingTable,
6647 pending: PendingModuleControlRpc,
6648 deadline: Instant,
6649 probe_budget: Duration,
6650) -> Result<HealthReport, HealthProbeError> {
6651 let PendingModuleControlRpc {
6652 endpoint,
6653 module_sink,
6654 negotiated_ver,
6655 corr,
6656 receiver,
6657 } = pending;
6658 let body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
6659 HealthProbeError::misconfigured(format!("failed to encode health.check: {err}"))
6660 })?;
6661 let frame = Frame::build_with_version(
6662 negotiated_ver,
6663 FrameType::Request,
6664 control_flags(),
6665 0,
6666 0,
6667 corr,
6668 body,
6669 )
6670 .map_err(|err| {
6671 HealthProbeError::misconfigured(format!("failed to build health.check frame: {err}"))
6672 })?;
6673
6674 match timeout_at(deadline, module_sink.send(frame)).await {
6680 Ok(Ok(())) => {}
6681 Ok(Err(err)) => {
6682 let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6683 return Err(HealthProbeError::lane_dead(format!(
6686 "failed to send health.check: {err}"
6687 )));
6688 }
6689 Err(_elapsed) => {
6690 let _ = forwarding.cancel_module_control_rpc(endpoint, corr);
6691 return Err(HealthProbeError::no_answer(
6695 "health.check send timed out before enqueue (module egress full)",
6696 ));
6697 }
6698 }
6699
6700 match timeout_at(deadline, receiver).await {
6701 Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => Err(HealthProbeError::bad_answer(
6702 "health.check returned an unexpected config response",
6703 )),
6704 Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
6708 response.health_report().ok_or_else(|| {
6709 HealthProbeError::bad_answer("health.check RPC returned a non-health response")
6710 })
6711 }
6712 Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => Err(HealthProbeError::bad_answer(
6713 format!("health.check rejected: {}", body.message),
6714 )),
6715 Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
6716 Err(HealthProbeError::lane_dead(message))
6717 }
6718 Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
6719 Err(HealthProbeError::bad_answer(message))
6720 }
6721 Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
6722 Err(HealthProbeError::bad_answer(format!(
6723 "expected module-control op '{expected}', got '{actual}'"
6724 )))
6725 }
6726 Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => Err(HealthProbeError::bad_answer(
6730 "module answered health.check after its daemon deadline",
6731 )),
6732 Ok(Err(_)) => Err(HealthProbeError::misconfigured(
6733 "health.check waiter was canceled before the module responded",
6734 )),
6735 Err(_) => {
6736 let _ = forwarding.tombstone_health_probe_rpc(endpoint, corr);
6737 Err(HealthProbeError::no_answer(format!(
6738 "module did not answer health.check within {probe_budget:?}"
6739 )))
6740 }
6741 }
6742}
6743
6744#[allow(clippy::too_many_arguments)]
6748async fn handle_health_report(
6749 spec: &ModuleSpec,
6750 runtime: &SupervisorRuntimeConfig,
6751 registry: &Registry,
6752 process_liveness: &SupervisorProcessLiveness,
6753 snapshot: &SharedSnapshot,
6754 child: &mut Option<SupervisedChild>,
6755 report: HealthReport,
6756 now_ms: u64,
6757 delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6758 probed: Option<ConnectionId>,
6759) {
6760 let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6761 (Some(delivery), Some(probe)) => {
6762 delivery
6763 .health_result(
6764 &spec.module_id,
6765 runtime.forwarding.as_deref(),
6766 registry,
6767 probe,
6768 report.status == HealthStatus::Ok,
6769 )
6770 .await
6771 }
6772 _ => false,
6773 };
6774 if let (Some(delivery), Some(spawn)) = (
6775 &runtime.config_delivery,
6776 child
6777 .as_ref()
6778 .and_then(|child| child.config_delivery.as_ref()),
6779 ) {
6780 delivery
6781 .mark_readiness(
6782 &spec.module_id,
6783 runtime.forwarding.as_deref(),
6784 probed,
6785 spawn,
6786 report.status == HealthStatus::Ok,
6787 )
6788 .await;
6789 }
6790 let status = supervisor_health_status(report.status);
6791 let detail = report.detail.clone();
6792 let metrics = truncate_health_metrics(report.metrics);
6793 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6794 state.health.status = status;
6795 state.last_probe_evidence = None;
6796 state.health.last_probe_ms = Some(now_ms);
6797 state.health.detail = detail.clone();
6798 state.health.metrics = metrics.clone();
6799 state.health.consecutive_failures = 0;
6800 state.failed_retry.observe_health(
6801 report.status == HealthStatus::Ok,
6802 runtime.restart_policy.window,
6803 );
6804 });
6805
6806 if delivery_failed {
6807 return;
6808 }
6809 let action = match report.status {
6810 HealthStatus::Ok => return,
6811 HealthStatus::Degraded => runtime.health.on_degraded,
6812 HealthStatus::Failing => runtime.health.on_failing,
6813 };
6814 apply_l3_health_action(
6815 spec,
6816 runtime,
6817 registry,
6818 process_liveness,
6819 snapshot,
6820 child,
6821 status,
6822 detail.as_deref(),
6823 action,
6824 now_ms,
6825 )
6826 .await;
6827}
6828
6829#[allow(clippy::too_many_arguments)]
6830async fn handle_health_probe_failure(
6831 spec: &ModuleSpec,
6832 runtime: &SupervisorRuntimeConfig,
6833 registry: &Registry,
6834 process_liveness: &SupervisorProcessLiveness,
6835 snapshot: &SharedSnapshot,
6836 child: &mut Option<SupervisedChild>,
6837 err: HealthProbeError,
6838 now_ms: u64,
6839 delivery_probe: Option<crate::config_gate::runtime::DeliveryProbe>,
6840) {
6841 let delivery_failed = match (&runtime.config_delivery, delivery_probe) {
6842 (Some(delivery), Some(probe)) => {
6843 delivery
6844 .health_result(
6845 &spec.module_id,
6846 runtime.forwarding.as_deref(),
6847 registry,
6848 probe,
6849 false,
6850 )
6851 .await
6852 }
6853 _ => false,
6854 };
6855 let threshold = runtime.health.failure_threshold.max(1);
6856 let held = if err.evidence == HealthProbeEvidence::NoAnswer {
6857 runtime.host_health.record_late_module(&spec.module_id)
6858 } else {
6859 false
6860 };
6861 let mut failures = 0;
6862 let detail = if held {
6867 format!("[{}] {err}; host overloaded", err.label())
6868 } else {
6869 format!("[{}] {err}", err.label())
6870 };
6871 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6872 state.last_probe_evidence = Some(err.evidence);
6873 state
6874 .failed_retry
6875 .observe_health(false, runtime.restart_policy.window);
6876 if held {
6879 state.health.status = SupervisorHealthStatus::Degraded;
6880 } else if state.spawned_protocol.unwrap_or(spec.protocol) == ModuleProtocol::Subc {
6881 state.health.status = SupervisorHealthStatus::Unknown;
6882 }
6883 state.health.last_probe_ms = Some(now_ms);
6884 state.health.consecutive_failures = if held {
6887 0
6888 } else {
6889 state.health.consecutive_failures.saturating_add(1)
6890 };
6891 state.health.detail = Some(detail.clone());
6892 state.health.metrics = None;
6893 failures = state.health.consecutive_failures;
6894 });
6895
6896 if delivery_failed {
6897 return;
6898 }
6899 if held || failures < threshold {
6900 warn!(
6901 module_id = %spec.module_id,
6902 consecutive_failures = failures,
6903 threshold,
6904 evidence = err.label(),
6905 detail = %detail,
6906 "health.check probe failed"
6907 );
6908 return;
6909 }
6910
6911 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
6912 state.state = ModuleState::Unresponsive;
6913 state.health.status = SupervisorHealthStatus::Unresponsive;
6914 });
6915 if runtime.health.critical {
6919 error!(
6920 module_id = %spec.module_id,
6921 status = "unresponsive",
6922 evidence = err.label(),
6923 detail = %detail,
6924 "critical module health alert"
6925 );
6926 } else {
6927 warn!(
6928 module_id = %spec.module_id,
6929 status = "unresponsive",
6930 evidence = err.label(),
6931 detail = %detail,
6932 "module health threshold breached"
6933 );
6934 }
6935 if let Err(err) = health_restart_child(
6936 spec,
6937 runtime,
6938 registry,
6939 process_liveness,
6940 snapshot,
6941 child,
6942 SupervisorHealthStatus::Unresponsive,
6943 Some(&detail),
6944 now_ms,
6945 )
6946 .await
6947 {
6948 error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6949 }
6950}
6951
6952#[allow(clippy::too_many_arguments)]
6953async fn apply_l3_health_action(
6954 spec: &ModuleSpec,
6955 runtime: &SupervisorRuntimeConfig,
6956 registry: &Registry,
6957 process_liveness: &SupervisorProcessLiveness,
6958 snapshot: &SharedSnapshot,
6959 child: &mut Option<SupervisedChild>,
6960 status: SupervisorHealthStatus,
6961 detail: Option<&str>,
6962 action: HealthAction,
6963 now_ms: u64,
6964) {
6965 record_health_action(snapshot, &spec.module_id, action.to_string(), now_ms);
6966 match action {
6967 HealthAction::Report => {
6968 info!(
6969 module_id = %spec.module_id,
6970 status = ?status,
6971 detail,
6972 "module reported non-ok health"
6973 );
6974 }
6975 HealthAction::Alert => {
6976 error!(
6977 module_id = %spec.module_id,
6978 status = ?status,
6979 detail,
6980 "module health alert"
6981 );
6982 }
6983 HealthAction::Restart => {
6984 if let Err(err) = health_restart_child(
6985 spec,
6986 runtime,
6987 registry,
6988 process_liveness,
6989 snapshot,
6990 child,
6991 status,
6992 detail,
6993 now_ms,
6994 )
6995 .await
6996 {
6997 error!(module_id = %spec.module_id, error = %err, "health-triggered restart failed");
6998 }
6999 }
7000 }
7001}
7002
7003#[allow(clippy::too_many_arguments)]
7004async fn health_restart_child(
7005 spec: &ModuleSpec,
7006 runtime: &SupervisorRuntimeConfig,
7007 registry: &Registry,
7008 process_liveness: &SupervisorProcessLiveness,
7009 snapshot: &SharedSnapshot,
7010 child: &mut Option<SupervisedChild>,
7011 status: SupervisorHealthStatus,
7012 detail: Option<&str>,
7013 now_ms: u64,
7014) -> Result<(), SuperviseError> {
7015 budgeted_restart_child(
7016 spec,
7017 runtime,
7018 registry,
7019 process_liveness,
7020 snapshot,
7021 child,
7022 status,
7023 detail,
7024 now_ms,
7025 true,
7026 )
7027 .await
7028}
7029
7030#[allow(clippy::too_many_arguments)]
7031async fn budgeted_restart_child(
7032 spec: &ModuleSpec,
7033 runtime: &SupervisorRuntimeConfig,
7034 registry: &Registry,
7035 process_liveness: &SupervisorProcessLiveness,
7036 snapshot: &SharedSnapshot,
7037 child: &mut Option<SupervisedChild>,
7038 status: SupervisorHealthStatus,
7039 detail: Option<&str>,
7040 now_ms: u64,
7041 health_failure: bool,
7042) -> Result<(), SuperviseError> {
7043 if let Some(error) = runtime
7044 .config_delivery
7045 .as_ref()
7046 .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
7047 .filter(|error| error.code != "config_delivery_deferred")
7048 {
7049 return Err(config_delivery::gate_hold_error(
7050 spec,
7051 error,
7052 runtime.config_delivery.as_ref(),
7053 ));
7054 }
7055 let recovery_reason = if health_failure {
7056 "health_check"
7057 } else {
7058 "configuration_delivery"
7059 };
7060 let (enabled, schedule) = {
7061 let mut state = lock_snapshot(snapshot)?;
7062 let enabled = state.enabled;
7063 let schedule = if enabled {
7064 state.next_crash_restart(&runtime.restart_policy, Instant::now())
7065 } else {
7066 None
7067 };
7068 (enabled, schedule)
7069 };
7070
7071 if !enabled {
7072 return Err(SuperviseError::Disabled {
7073 module_id: spec.module_id.clone(),
7074 });
7075 }
7076
7077 if schedule.is_none() {
7078 if health_failure {
7079 record_health_action(snapshot, &spec.module_id, "failed".to_string(), now_ms);
7080 }
7081 error!(
7082 module_id = %spec.module_id,
7083 status = ?status,
7084 detail,
7085 max_restarts = runtime.restart_policy.max_restarts,
7086 window_secs = runtime.restart_policy.window.as_secs(),
7087 reason = %runtime.restart_policy.budget_exhausted_detail(),
7088 recovery_reason,
7089 "automatic restart budget exhausted; marking module failed"
7090 );
7091 let stop_notice = begin_forwarding_drain_if_configured(
7092 spec,
7093 runtime,
7094 registry,
7095 snapshot,
7096 Some(true),
7097 RouteCloseReason::Disable,
7098 )
7099 .await?;
7100 update_snapshot(snapshot, Some(&spec.module_id), |state| {
7101 state.drain_disposition_detail = Some(runtime.restart_policy.budget_exhausted_detail());
7102 })?;
7103 let result = drain_optional_child(
7104 &spec.module_id,
7105 spec.protocol,
7106 stop_notice,
7107 registry,
7108 runtime.forwarding.as_deref(),
7109 snapshot,
7110 &runtime.terminal_ring,
7111 &runtime.spawn_events,
7112 child,
7113 runtime.drain_timeout,
7114 ModuleState::Failed,
7115 Some(true),
7116 &runtime.failure_context(true),
7117 )
7118 .await;
7119 update_snapshot(snapshot, Some(&spec.module_id), |state| {
7120 if state.state == ModuleState::Failed && !runtime.child_roster.is_closed() {
7121 state.failed_retry.schedule(&spec.module_id);
7122 }
7123 })?;
7124 result?;
7125 process_liveness.untrack_if_current(&spec.module_id, snapshot);
7126 return Ok(());
7127 }
7128
7129 let schedule = schedule.expect("a health restart must have a crash-restart schedule");
7130 let mut restart_count = 0;
7131 update_snapshot(snapshot, Some(&spec.module_id), |state| {
7132 restart_count = state.crash_restarts.len();
7133 state.state = ModuleState::Unresponsive;
7134 if health_failure {
7135 state.health.status = status;
7136 state.health.last_action = Some(HealthAction::Restart.to_string());
7137 state.health.last_action_ms = Some(now_ms);
7138 }
7139 })?;
7140 warn!(
7141 module_id = %spec.module_id,
7142 status = ?status,
7143 detail,
7144 restart_count,
7145 restart_in_window = schedule.restart_in_window,
7146 delay_ms = schedule.delay.as_millis() as u64,
7147 recovery_reason,
7148 "automatic module restart"
7149 );
7150
7151 let stop_notice = begin_forwarding_drain_if_configured(
7152 spec,
7153 runtime,
7154 registry,
7155 snapshot,
7156 Some(true),
7157 RouteCloseReason::Restart,
7158 )
7159 .await?;
7160 drain_optional_child(
7161 &spec.module_id,
7162 spec.protocol,
7163 stop_notice,
7164 registry,
7165 runtime.forwarding.as_deref(),
7166 snapshot,
7167 &runtime.terminal_ring,
7168 &runtime.spawn_events,
7169 child,
7170 runtime.drain_timeout,
7171 ModuleState::Restarting,
7172 Some(true),
7173 &runtime.failure_context(true),
7174 )
7175 .await?;
7176 schedule_respawn(
7177 runtime,
7178 snapshot,
7179 &spec.module_id,
7180 schedule.delay,
7181 RespawnKind::CrashRestart,
7182 true,
7183 )
7184}
7185
7186fn cancel_deferred_reload(runtime: &SupervisorRuntimeConfig, module_id: &str, reason: &str) {
7187 if let Some(reply) = runtime
7188 .deferred_reload_reply
7189 .lock()
7190 .unwrap_or_else(|p| p.into_inner())
7191 .take()
7192 {
7193 let _ = reply.send(Err(SuperviseError::ReloadFailed {
7194 module_id: module_id.to_string(),
7195 reason: reason.to_string(),
7196 }));
7197 }
7198}
7199
7200fn park_config_spawn(
7201 spec: &ModuleSpec,
7202 runtime: &SupervisorRuntimeConfig,
7203 snapshot: &SharedSnapshot,
7204 failure: &FailureContext,
7205 admission_refused: Option<String>,
7206) -> Result<(), SuperviseError> {
7207 *runtime
7208 .scheduled_respawn
7209 .lock()
7210 .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
7211 if let Some(reply) = runtime
7212 .deferred_reload_reply
7213 .lock()
7214 .unwrap_or_else(|poisoned| poisoned.into_inner())
7215 .take()
7216 {
7217 let _ = reply.send(Err(SuperviseError::ConfigHeld {
7218 module_id: spec.module_id.clone(),
7219 code: "config_gated".into(),
7220 detail: "module is held by configuration admission".into(),
7221 }));
7222 }
7223 update_snapshot(snapshot, Some(&spec.module_id), |state| {
7224 state.admission_refused = admission_refused;
7225 state.config_hold_daemon_initiated = failure.daemon_initiated;
7226 state.config_hold_approval = failure.approval.clone();
7227 state.config_hold_parked = true;
7228 state.state = ModuleState::Stopped;
7229 state.respawn_pending = false;
7230 state.failed_retry.pending = None;
7231 state.failed_retry.failed_at = None;
7234 clear_current_process_facts(state);
7235 })
7236}
7237
7238fn try_park_config_attempt(
7239 spec: &ModuleSpec,
7240 runtime: &SupervisorRuntimeConfig,
7241 snapshot: &SharedSnapshot,
7242 failure: &FailureContext,
7243 program_base: Option<&subc_config::Digest>,
7244) -> Result<bool, SuperviseError> {
7245 let result = (|| {
7246 if !lock_snapshot(snapshot)?.enabled {
7247 return Ok(false);
7248 }
7249 #[cfg(test)]
7250 if let Some(delivery) = &runtime.config_delivery {
7251 delivery.0.pause_before_config_park_for_test();
7252 }
7253 let Some(delivery) = &runtime.config_delivery else {
7254 return Ok(false);
7255 };
7256 let parked = delivery
7257 .0
7258 .with_recorded_admission_hold(&spec.module_id, program_base, |refusal| {
7259 park_config_spawn(spec, runtime, snapshot, failure, refusal)
7260 })
7261 .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(delivery)))?;
7262 if let Some(result) = parked {
7263 result?;
7264 Ok(true)
7265 } else {
7266 Ok(false)
7267 }
7268 })();
7269 if let Err(error) = &result {
7270 fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
7274 record_approved_attempt_failure(spec, snapshot, failure, error);
7275 }
7276 result
7277}
7278
7279fn record_approved_attempt_failure(
7280 spec: &ModuleSpec,
7281 snapshot: &SharedSnapshot,
7282 failure: &FailureContext,
7283 error: &SuperviseError,
7284) {
7285 let Some(approval) = &failure.approval else {
7286 return;
7287 };
7288 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
7289 if state.enabled
7290 && state.state == ModuleState::Failed
7291 && state
7292 .approved_start_failure
7293 .as_ref()
7294 .is_none_or(|(identity, _)| identity != approval)
7295 {
7296 state.approved_start_failure = Some((approval.clone(), error.to_string()));
7297 }
7298 });
7299}
7300
7301fn hold_config_spawn(
7302 spec: &ModuleSpec,
7303 runtime: &SupervisorRuntimeConfig,
7304 snapshot: &SharedSnapshot,
7305 failure: &FailureContext,
7306) -> Result<(), SuperviseError> {
7307 hold_config_respawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)
7308}
7309
7310fn hold_config_respawn(
7311 spec: &ModuleSpec,
7312 runtime: &SupervisorRuntimeConfig,
7313 snapshot: &SharedSnapshot,
7314 kind: RespawnKind,
7315 failure: &FailureContext,
7316) -> Result<(), SuperviseError> {
7317 if !lock_snapshot(snapshot)?.enabled {
7318 return Ok(());
7319 }
7320 if !try_park_config_attempt(spec, runtime, snapshot, failure, None)? {
7321 defer_config_spawn(spec, runtime, snapshot, kind, failure)?;
7324 }
7325 Ok(())
7326}
7327
7328fn schedule_respawn(
7329 runtime: &SupervisorRuntimeConfig,
7330 snapshot: &SharedSnapshot,
7331 module_id: &str,
7332 delay: Duration,
7333 kind: RespawnKind,
7334 daemon_initiated: bool,
7335) -> Result<(), SuperviseError> {
7336 cancel_deferred_reload(runtime, module_id, "respawn superseded by another restart");
7337 update_snapshot(snapshot, Some(module_id), |state| {
7338 state.respawn_pending = true
7339 })?;
7340 *runtime
7341 .scheduled_respawn
7342 .lock()
7343 .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7344 deadline: Instant::now() + delay,
7345 kind,
7346 daemon_initiated,
7347 approval: None,
7348 });
7349 Ok(())
7350}
7351
7352const CONFIG_ADMISSION_RETRY_DELAY: Duration = Duration::from_millis(100);
7353
7354fn defer_config_spawn(
7355 spec: &ModuleSpec,
7356 runtime: &SupervisorRuntimeConfig,
7357 snapshot: &SharedSnapshot,
7358 kind: RespawnKind,
7359 failure: &FailureContext,
7360) -> Result<(), SuperviseError> {
7361 update_snapshot(snapshot, Some(&spec.module_id), |state| {
7362 state.state = ModuleState::Restarting;
7363 state.respawn_pending = true;
7364 clear_current_process_facts(state);
7365 })?;
7366 *runtime
7367 .scheduled_respawn
7368 .lock()
7369 .unwrap_or_else(|p| p.into_inner()) = Some(PendingRespawn {
7370 deadline: Instant::now() + CONFIG_ADMISSION_RETRY_DELAY,
7371 kind,
7372 daemon_initiated: failure.daemon_initiated,
7373 approval: failure.approval.clone(),
7374 });
7375 Ok(())
7376}
7377
7378fn record_health_action(snapshot: &SharedSnapshot, module_id: &str, action: String, now_ms: u64) {
7379 let _ = update_snapshot(snapshot, Some(module_id), |state| {
7380 state.health.last_action = Some(action);
7381 state.health.last_action_ms = Some(now_ms);
7382 });
7383}
7384
7385fn supervisor_health_status(status: HealthStatus) -> SupervisorHealthStatus {
7386 match status {
7387 HealthStatus::Ok => SupervisorHealthStatus::Ok,
7388 HealthStatus::Degraded => SupervisorHealthStatus::Degraded,
7389 HealthStatus::Failing => SupervisorHealthStatus::Failing,
7390 }
7391}
7392
7393fn truncate_health_metrics(metrics: Option<Value>) -> Option<Value> {
7405 let metrics = metrics?;
7406 match serde_json::to_vec(&metrics) {
7407 Ok(encoded) if encoded.len() > MAX_HEALTH_METRICS_BYTES => Some(serde_json::json!({
7408 "truncated": true,
7409 "original_bytes": encoded.len(),
7410 })),
7411 Ok(_) | Err(_) => Some(metrics),
7412 }
7413}
7414
7415fn jittered_health_delay(module_id: &str, probe_index: u64, cadence: Duration) -> Duration {
7421 if cadence.is_zero() {
7422 return Duration::ZERO;
7423 }
7424 let cadence_ms = cadence.as_millis() as u64;
7425 if cadence_ms == 0 {
7441 return cadence;
7442 }
7443 let jitter_span = (cadence_ms / 10).max(1);
7458 let hash = module_id.as_bytes().iter().fold(
7459 probe_index.wrapping_mul(0x9E37_79B9_7F4A_7C15),
7460 |acc, byte| {
7461 acc.wrapping_mul(1099511628211)
7462 .wrapping_add(u64::from(*byte))
7463 },
7464 );
7465 cadence + Duration::from_millis(hash % jitter_span)
7466}
7467
7468#[cfg(test)]
7469mod tests {
7470 use super::*;
7471
7472 #[test]
7473 fn registration_retirement_self_prefixed_owner_is_not_a_prefix_submodule() {
7474 let handle = SupervisorHandle::new();
7475 handle.set_spawn_nonce("prefix:owner", "owner-nonce".into());
7476 handle.set_reserved_prefixes("prefix:owner", &["prefix:".into()]);
7477 let owner = handle
7478 .reserved_hello_verification("prefix:owner", Some("owner-nonce"))
7479 .unwrap();
7480 assert!(owner.nonce_verified);
7481 assert!(
7482 owner.prefix_owner.is_none(),
7483 "an unreserved programmatic owner is not its own prefix child"
7484 );
7485 let child = handle
7486 .reserved_hello_verification("prefix:child", Some("owner-nonce"))
7487 .unwrap();
7488 assert!(child.nonce_verified);
7489 assert_eq!(child.prefix_owner.as_deref(), Some("prefix:owner"));
7490 }
7491
7492 #[test]
7493 fn readding_a_module_clears_its_rescan_removal_tombstone() {
7494 let handle = SupervisorHandle::new();
7495 let module_id = "readded-tombstone";
7496 handle.record_rescan_removal(module_id);
7497 assert!(handle.removal_tombstone_age_ms(module_id).is_some());
7498
7499 handle.apply_identity_configuration(&ModuleSpec {
7500 script: None,
7501 module_id: module_id.to_string(),
7502 program: PathBuf::from("/test/module"),
7503 args: Vec::new(),
7504 env: Vec::new(),
7505 reserved: false,
7506 reserved_prefixes: Vec::new(),
7507 protocol: ModuleProtocol::Subc,
7508 overlap: Default::default(),
7509 carry_containment: false,
7510 });
7511
7512 assert!(
7513 handle.removal_tombstone_age_ms(module_id).is_none(),
7514 "a re-added module must not retain a stale removal tombstone"
7515 );
7516 }
7517
7518 #[derive(Debug, PartialEq, Eq)]
7521 struct OwnerInSpawnWindow {
7522 module_id: String,
7523 configured: bool,
7524 on_roster: bool,
7525 admission_refusal: Option<&'static str>,
7526 }
7527
7528 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7539 async fn a_new_module_is_configured_before_its_first_process_can_register() {
7540 use crate::scopes::ScopeTable;
7541 use subc_protocol::{error_codes, scope::ScopeSelector, Principal};
7542
7543 let dir = cortexkit_test_support::ScratchDir::new("configured-before-spawn");
7544 let stub = |module_id: &str, program: PathBuf| ModuleSpec {
7545 script: None,
7546 module_id: module_id.to_string(),
7547 program,
7548 args: Vec::new(),
7549 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7550 .into_iter()
7551 .map(|key| (key.to_string(), dir.path().display().to_string()))
7552 .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7553 .collect(),
7554 reserved: false,
7555 reserved_prefixes: Vec::new(),
7556 protocol: ModuleProtocol::Subc,
7557 overlap: Default::default(),
7558 carry_containment: false,
7559 };
7560 let live = super::terminal_history_tests::fake_aft_stub_path();
7561 let missing = dir.path().join("definitely-missing-module");
7562
7563 let handle = SupervisorHandle::new();
7564 let mut supervisor =
7565 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7566 .with_handle(handle.clone());
7567 let observed = Arc::new(Mutex::new(Vec::<OwnerInSpawnWindow>::new()));
7568 let hook_handle = handle.clone();
7569 let hook_observed = Arc::clone(&observed);
7570 supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7571 let configured = hook_handle.is_configured(module_id);
7574 let selector = ScopeSelector::new(
7575 Principal::Reserved {
7576 module_id: module_id.to_string(),
7577 },
7578 "s".to_string(),
7579 Some(1),
7580 );
7581 let carrier = Principal::Reserved {
7582 module_id: "carrier".to_string(),
7583 };
7584 let admission_refusal = match ScopeTable::new(Vec::<String>::new())
7585 .admit(&carrier, module_id, &selector, configured)
7586 {
7587 Ok(_) => None,
7588 Err(refusal) => Some(refusal.code),
7589 };
7590 hook_observed.lock().unwrap().push(OwnerInSpawnWindow {
7591 module_id: module_id.to_string(),
7592 configured,
7593 on_roster: hook_handle.get(module_id).is_some(),
7594 admission_refusal,
7595 });
7596 })));
7597
7598 let plain = supervisor.spawn(stub("plain", live.clone())).unwrap();
7599 let configured = supervisor
7600 .supervise_configured(stub("configured", live.clone()), true)
7601 .unwrap();
7602 let with_health = supervisor
7603 .supervise_configured_with_health(
7604 stub("with-health", live.clone()),
7605 true,
7606 HealthConfig::default(),
7607 None,
7608 RestartPolicy::default(),
7609 )
7610 .unwrap();
7611 let failed = supervisor
7614 .supervise_configured_with_health(
7615 stub("failed-spawn", missing.clone()),
7616 true,
7617 HealthConfig::default(),
7618 None,
7619 RestartPolicy::default(),
7620 )
7621 .unwrap();
7622 assert!(supervisor.spawn(stub("spawn-error", missing)).is_err());
7625
7626 let expected = [
7627 "plain",
7628 "configured",
7629 "with-health",
7630 "failed-spawn",
7631 "spawn-error",
7632 ]
7633 .into_iter()
7634 .map(|module_id| OwnerInSpawnWindow {
7635 module_id: module_id.to_string(),
7636 configured: true,
7637 on_roster: !matches!(module_id, "plain" | "spawn-error"),
7638 admission_refusal: Some(error_codes::SCOPE_NOT_SYNCED),
7639 })
7640 .collect::<Vec<_>>();
7641 assert_eq!(*observed.lock().unwrap(), expected);
7642
7643 for module_id in ["plain", "configured", "with-health", "failed-spawn"] {
7644 assert!(
7645 handle.get(module_id).is_some(),
7646 "{module_id} is on the roster"
7647 );
7648 assert!(
7649 handle.is_configured(module_id),
7650 "{module_id} stays configured"
7651 );
7652 }
7653 assert!(handle.get("spawn-error").is_none());
7654 assert!(
7655 !handle.is_configured("spawn-error"),
7656 "a plain spawn that failed must not leave its module marked configured"
7657 );
7658
7659 handle.retire("failed-spawn");
7661 assert!(!handle.is_configured("failed-spawn"));
7662
7663 for module in [plain, configured, with_health] {
7664 module.stop().await.unwrap();
7665 }
7666 drop(failed);
7667 }
7668
7669 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7676 async fn a_configured_module_reads_starting_while_its_first_process_already_runs() {
7677 let dir = cortexkit_test_support::ScratchDir::new("starting-while-spawned");
7678 let spec = ModuleSpec {
7679 script: None,
7680 module_id: "spawned-not-admitted".to_string(),
7681 program: super::terminal_history_tests::fake_aft_stub_path(),
7682 args: Vec::new(),
7683 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7684 .into_iter()
7685 .map(|key| (key.to_string(), dir.path().display().to_string()))
7686 .chain([("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())])
7687 .collect(),
7688 reserved: false,
7689 reserved_prefixes: Vec::new(),
7690 protocol: ModuleProtocol::Subc,
7691 overlap: Default::default(),
7692 carry_containment: false,
7693 };
7694 let handle = SupervisorHandle::new();
7695 let mut supervisor =
7696 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7697 .with_handle(handle.clone());
7698 let observed = Arc::new(Mutex::new(None));
7699 let hook_handle = handle.clone();
7700 let hook_observed = Arc::clone(&observed);
7701 supervisor.test_after_first_spawn = AfterFirstSpawnHook(Some(Arc::new(move |module_id| {
7702 let state = hook_handle
7703 .get(module_id)
7704 .expect("a configured module is on the roster before it is spawned")
7705 .state()
7706 .unwrap();
7707 *hook_observed.lock().unwrap() = Some(state);
7708 })));
7709
7710 let module = supervisor.supervise_configured(spec, true).unwrap();
7711 assert_eq!(
7712 *observed.lock().unwrap(),
7713 Some(ModuleState::Starting),
7714 "between the spawn and its admission the supervisor still reports starting"
7715 );
7716 assert_eq!(module.state().unwrap(), ModuleState::Running);
7717 module.stop().await.unwrap();
7718 }
7719
7720 fn stale_process_snapshot(state: ModuleState, enabled: bool) -> SharedSnapshot {
7721 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(state, enabled)));
7722 update_snapshot(&snapshot, Some("stale-process-facts"), |snapshot| {
7723 snapshot.process_alive = true;
7724 snapshot.pid = Some(41);
7725 snapshot.spawned_at_ms = Some(42);
7726 snapshot.spawned_from = Some(PathBuf::from("/spawned/module"));
7727 snapshot.launch_spec_digest = Some(LaunchSpecDigest([0xA5; 32]));
7728 snapshot.spawned_file_identity = Some(SpawnedFileIdentity {
7729 device: 43,
7730 inode: 44,
7731 #[cfg(windows)]
7732 windows_image: None,
7733 });
7734 })
7735 .unwrap();
7736 snapshot
7737 }
7738
7739 fn assert_snapshot_process_facts_cleared(snapshot: &SharedSnapshot) {
7740 let snapshot = lock_snapshot(snapshot).unwrap();
7741 assert!(!snapshot.process_alive);
7742 assert_eq!(snapshot.pid, None);
7743 assert_eq!(snapshot.spawned_at_ms, None);
7744 assert_eq!(snapshot.spawned_from, None);
7745 assert_eq!(snapshot.launch_spec_digest, None);
7746 assert_eq!(snapshot.spawned_file_identity, None);
7747 }
7748
7749 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7750 async fn failed_enable_spawn_clears_preexisting_current_process_facts() {
7751 let supervisor =
7752 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7753 let mut runtime = supervisor.runtime_config();
7754 runtime.test_seed_stale_facts_before_enable_spawn = true;
7755 let snapshot = stale_process_snapshot(ModuleState::Disabled, false);
7756 let mut child = None;
7757 let spec = ModuleSpec {
7758 script: None,
7759 module_id: "failed-enable-clears-facts".to_string(),
7760 program: PathBuf::from("/definitely/missing/failed-enable-module"),
7761 args: Vec::new(),
7762 env: Vec::new(),
7763 reserved: false,
7764 reserved_prefixes: Vec::new(),
7765 protocol: ModuleProtocol::Subc,
7766 overlap: Default::default(),
7767 carry_containment: false,
7768 };
7769
7770 let result = set_child_enabled(
7771 &spec,
7772 &runtime,
7773 &supervisor.registry,
7774 &supervisor.process_liveness,
7775 &snapshot,
7776 &mut child,
7777 true,
7778 &runtime.failure_context(false),
7779 )
7780 .await;
7781
7782 assert!(matches!(result, Err(SuperviseError::Spawn { .. })));
7783 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7784 assert_snapshot_process_facts_cleared(&snapshot);
7785 }
7786
7787 #[tokio::test]
7788 async fn start_revives_stranded_restarting_but_not_pending_backoff() {
7789 let supervisor =
7790 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7791 let runtime = supervisor.runtime_config();
7792 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
7793 ModuleState::Restarting,
7794 true,
7795 )));
7796 let spec = ModuleSpec {
7797 script: None,
7798 module_id: "start-stranded-restarting".to_string(),
7799 program: super::terminal_history_tests::fake_aft_stub_path(),
7800 args: Vec::new(),
7801 env: vec![("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string())],
7802 reserved: false,
7803 reserved_prefixes: Vec::new(),
7804 protocol: ModuleProtocol::None,
7805 overlap: Default::default(),
7806 carry_containment: false,
7807 };
7808 let mut child = None;
7809 lock_snapshot(&snapshot).unwrap().respawn_pending = true;
7810 assert!(!super::set_child_enabled(
7811 &spec,
7812 &runtime,
7813 &Registry::default(),
7814 &supervisor.process_liveness,
7815 &snapshot,
7816 &mut child,
7817 true,
7818 &runtime.failure_context(false),
7819 )
7820 .await
7821 .unwrap());
7822 assert!(child.is_none());
7823 lock_snapshot(&snapshot).unwrap().respawn_pending = false;
7824 assert!(super::set_child_enabled(
7825 &spec,
7826 &runtime,
7827 &Registry::default(),
7828 &supervisor.process_liveness,
7829 &snapshot,
7830 &mut child,
7831 true,
7832 &runtime.failure_context(false),
7833 )
7834 .await
7835 .unwrap());
7836 assert_eq!(
7837 lock_snapshot(&snapshot).unwrap().state,
7838 ModuleState::Running
7839 );
7840 let mut child = child.unwrap();
7841 child.start_kill().unwrap();
7842 child.wait().await.unwrap();
7843 }
7844
7845 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7846 async fn failed_reload_spawn_clears_current_process_facts() {
7847 let supervisor =
7848 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7849 let mut runtime = supervisor.runtime_config();
7850 runtime.restart_policy = RestartPolicy::new(0, Duration::ZERO);
7851 let snapshot = stale_process_snapshot(ModuleState::Running, true);
7852 let mut child = None;
7853 let spec = ModuleSpec {
7854 script: None,
7855 module_id: "failed-reload-clears-facts".to_string(),
7856 program: PathBuf::from("/unused/failed-reload-module"),
7857 args: Vec::new(),
7858 env: Vec::new(),
7859 reserved: false,
7860 reserved_prefixes: Vec::new(),
7861 protocol: ModuleProtocol::Subc,
7862 overlap: Default::default(),
7863 carry_containment: false,
7864 };
7865
7866 let result = handle_reload_spawn_failure(
7867 &spec,
7868 &runtime,
7869 &supervisor.process_liveness,
7870 &snapshot,
7871 &mut child,
7872 "forced reload spawn failure".to_string(),
7873 )
7874 .await;
7875
7876 assert!(matches!(result, Err(SuperviseError::ReloadFailed { .. })));
7877 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
7878 assert_snapshot_process_facts_cleared(&snapshot);
7879 }
7880
7881 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
7882 async fn dropping_a_module_with_an_active_monitor_clears_current_process_facts() {
7883 let supervisor =
7884 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7885 let snapshot = stale_process_snapshot(ModuleState::Running, true);
7886 let module = supervisor.supervised_module(
7887 ModuleSpec {
7888 script: None,
7889 module_id: "drop-clears-facts".to_string(),
7890 program: PathBuf::from("/unused/drop-module"),
7891 args: Vec::new(),
7892 env: Vec::new(),
7893 reserved: false,
7894 reserved_prefixes: Vec::new(),
7895 protocol: ModuleProtocol::Subc,
7896 overlap: Default::default(),
7897 carry_containment: false,
7898 },
7899 supervisor.runtime_config(),
7900 Arc::clone(&snapshot),
7901 None,
7902 );
7903 assert!(!module
7904 .inner
7905 .monitor
7906 .lock()
7907 .unwrap()
7908 .as_ref()
7909 .unwrap()
7910 .is_finished());
7911
7912 drop(module);
7913
7914 assert_eq!(
7915 lock_snapshot(&snapshot).unwrap().state,
7916 ModuleState::Stopped
7917 );
7918 assert_snapshot_process_facts_cleared(&snapshot);
7919 }
7920
7921 #[cfg(unix)]
7922 #[tokio::test]
7923 async fn rescan_preserves_running_protocol_until_respawn() {
7924 let dir = cortexkit_test_support::ScratchDir::new("rescan-protocol");
7925 let initial = ModuleSpec {
7926 script: None,
7927 module_id: "rescan-protocol".into(),
7928 program: PathBuf::from("/bin/sleep"),
7929 args: vec!["60".into()],
7930 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
7931 .into_iter()
7932 .map(|key| (key.into(), dir.path().to_string_lossy().into_owned()))
7933 .collect(),
7934 reserved: false,
7935 reserved_prefixes: vec![],
7936 protocol: ModuleProtocol::None,
7937 overlap: Default::default(),
7938 carry_containment: false,
7939 };
7940 let supervisor =
7941 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
7942 let module = supervisor.spawn(initial.clone()).unwrap();
7943 assert!(module.status().unwrap().live);
7944 let mut next = initial;
7945 next.protocol = ModuleProtocol::Subc;
7946 module
7947 .update_configuration(next.clone(), HealthConfig::default(), None)
7948 .await
7949 .unwrap();
7950 assert!(
7951 module.status().unwrap().live,
7952 "rescan must not require HELLO from the old non-wire process"
7953 );
7954 let runtime = supervisor.runtime_config();
7955 let action = on_child_exit(
7956 &next,
7957 RestartPolicy::default(),
7958 &supervisor.registry,
7959 &module.inner.snapshot,
7960 &runtime.terminal_ring,
7961 &runtime.spawn_events,
7962 &runtime.child_roster,
7963 ExitReport {
7964 kind: ExitKind::Clean,
7965 code: Some(0),
7966 signal: None,
7967 at_ms: unix_ms_now(),
7968 },
7969 true,
7970 )
7971 .await;
7972 assert!(
7973 matches!(action, NextAction::Restart { .. }),
7974 "the old non-wire process's clean exit must restart"
7975 );
7976 module.drain().await.unwrap();
7977 }
7978
7979 #[cfg(unix)]
7980 #[tokio::test]
7981 async fn orphan_identity_matches_path_names_and_shebang_interpreters() {
7982 use std::os::unix::fs::PermissionsExt;
7983 let dir = cortexkit_test_support::ScratchDir::new("spawn-image-identity");
7984 let script = dir.join("module.sh");
7985 std::fs::write(&script, "#!/bin/sh\nwhile :; do sleep 0.1; done\n").unwrap();
7986 std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap();
7987 let record_path = dir.join("live-children.json");
7988 let supervisor =
7989 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
7990 .with_live_children_record(&record_path);
7991 for (program, args) in [
7992 (PathBuf::from("sleep"), vec!["60".into()]),
7993 (script, vec![]),
7994 ] {
7995 let spec = ModuleSpec {
7996 script: None,
7997 module_id: "image-identity".into(),
7998 program: program.clone(),
7999 args,
8000 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
8001 .into_iter()
8002 .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
8003 .collect(),
8004 reserved: false,
8005 reserved_prefixes: vec![],
8006 protocol: ModuleProtocol::None,
8007 overlap: Default::default(),
8008 carry_containment: false,
8009 };
8010 let module = supervisor.spawn(spec).unwrap();
8011 #[cfg(target_os = "macos")]
8012 {
8013 let deadline = Instant::now() + Duration::from_secs(5);
8016 while crate::live_children::read_record(&record_path)
8017 .unwrap()
8018 .iter()
8019 .all(|entry| entry.executable.is_none())
8020 {
8021 assert!(Instant::now() < deadline, "module image was not confirmed");
8022 tokio::time::sleep(Duration::from_millis(5)).await;
8023 }
8024 }
8025 let entry = crate::live_children::read_record(&record_path)
8026 .unwrap()
8027 .pop()
8028 .unwrap();
8029 let observed = subc_os::Process::open(entry.pid)
8030 .unwrap()
8031 .unwrap()
8032 .observe()
8033 .unwrap();
8034 let verdict = crate::live_children::identity_verdict(&entry, entry.pid, &observed);
8035 module.drain().await.unwrap();
8036 assert_eq!(
8037 verdict,
8038 crate::live_children::IdentityVerdict::Matches,
8039 "program {program:?}: recorded {entry:?}, observed {observed:?}"
8040 );
8041 }
8042 }
8043
8044 #[cfg(unix)]
8045 fn http_fixture(
8046 dir: &std::path::Path,
8047 url: &str,
8048 threshold: u32,
8049 ) -> crate::daemon_config::ConfiguredModule {
8050 let path = dir.join("subc.jsonc");
8051 std::fs::write(&path, serde_json::json!({"version": 1, "modules": {"http-process": {
8052 "program": "/bin/sleep", "args": ["60"], "protocol": "none",
8053 "env": {"XDG_DATA_HOME":dir,"XDG_RUNTIME_DIR":dir,"XDG_CONFIG_HOME":dir},
8054 "health": {"http":url,"cadence_ms":20,"deadline_ms":200,"failure_threshold":threshold},
8055 "restart": {"backoff_ms":1,"max_backoff_ms":1}, "drain_timeout_ms":10
8056 }}}).to_string()).unwrap();
8057 crate::daemon_config::load(&path)
8058 .unwrap()
8059 .unwrap()
8060 .modules
8061 .pop()
8062 .unwrap()
8063 }
8064
8065 #[cfg(unix)]
8066 async fn wait_http_health(module: &SupervisedModule, status: SupervisorHealthStatus) {
8067 timeout(Duration::from_secs(5), async {
8068 loop {
8069 if module.status().unwrap().health.status == status {
8070 break;
8071 }
8072 sleep(Duration::from_millis(5)).await;
8073 }
8074 })
8075 .await
8076 .unwrap_or_else(|_| {
8077 panic!(
8078 "expected {status:?}, got {:?}",
8079 module.status().unwrap().health
8080 )
8081 });
8082 }
8083
8084 #[cfg(unix)]
8085 #[tokio::test]
8086 async fn http_health_status_flips_ok_failing_ok() {
8087 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8088 let dir = cortexkit_test_support::ScratchDir::new("http-status-flips");
8089 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8090 let status = Arc::new(std::sync::atomic::AtomicU16::new(200));
8091 let serving_status = status.clone();
8092 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8093 let server = tokio::spawn(async move {
8094 loop {
8095 let (mut stream, _) = listener.accept().await.unwrap();
8096 let mut request = [0u8; 2048];
8097 let count = stream.read(&mut request).await.unwrap();
8098 assert!(count > 0, "a probe must send an HTTP request");
8099 let code = serving_status.load(std::sync::atomic::Ordering::SeqCst);
8100 let body = if code == 200 {
8101 "ready"
8102 } else {
8103 "{\"status\":\"unavailable\",\"error\":\"scratch failure\"}"
8104 };
8105 let response = format!("HTTP/1.1 {code} scratch\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
8106 let _ = stream.write_all(response.as_bytes()).await;
8107 }
8108 });
8109 let configured = http_fixture(&dir, &url, 1000);
8110 let module =
8111 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8112 .supervise_configured_with_health(
8113 configured.module_spec(),
8114 true,
8115 configured.health,
8116 configured.drain_timeout_ms,
8117 configured.restart,
8118 )
8119 .unwrap();
8120 wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8121 status.store(503, std::sync::atomic::Ordering::SeqCst);
8122 wait_http_health(&module, SupervisorHealthStatus::Failing).await;
8123 assert!(module
8124 .status()
8125 .unwrap()
8126 .health
8127 .detail
8128 .unwrap()
8129 .contains("scratch failure"));
8130 status.store(200, std::sync::atomic::Ordering::SeqCst);
8131 wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8132 assert_eq!(module.status().unwrap().health.consecutive_failures, 0);
8133 let before = module.status().unwrap();
8134 let (spec, mut health) = module.configuration().unwrap();
8135 health.http = None;
8136 module
8137 .update_configuration(spec.clone(), health.clone(), Some(10))
8138 .await
8139 .unwrap();
8140 wait_http_health(&module, SupervisorHealthStatus::Unknown).await;
8141 health.http = Some(url);
8142 module
8143 .update_configuration(spec, health, Some(10))
8144 .await
8145 .unwrap();
8146 wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8147 assert_eq!(
8148 module.status().unwrap().pid,
8149 before.pid,
8150 "changing a probe must apply live, not restart its process"
8151 );
8152 let (spec, mut health) = module.configuration().unwrap();
8153 health.failure_threshold = 2;
8154 module
8155 .update_configuration(spec, health, Some(10))
8156 .await
8157 .unwrap();
8158 status.store(503, std::sync::atomic::Ordering::SeqCst);
8159 timeout(Duration::from_secs(5), async {
8160 while module.status().unwrap().spawn_generation == before.spawn_generation {
8161 sleep(Duration::from_millis(5)).await;
8162 }
8163 })
8164 .await
8165 .expect("sustained HTTP 503 responses must trigger the health restart policy");
8166 module.drain().await.unwrap();
8167 server.abort();
8168 }
8169
8170 #[cfg(unix)]
8171 #[tokio::test]
8172 async fn http_health_replacement_recovers_after_one_restart() {
8173 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8174 let dir = cortexkit_test_support::ScratchDir::new("http-replacement-recovers");
8175 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8176 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8177 let mut configured = http_fixture(&dir, &url, 2);
8178 configured.restart.max_restarts = 2;
8179 let module =
8180 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8181 .supervise_configured_with_health(
8182 configured.module_spec(),
8183 true,
8184 configured.health,
8185 configured.drain_timeout_ms,
8186 configured.restart,
8187 )
8188 .unwrap();
8189 let first_generation = module.status().unwrap().spawn_generation;
8190 let observed = module.clone();
8191 let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
8192 let server = tokio::spawn(async move {
8193 let mut generation = first_generation;
8194 let mut probes = 0;
8195 loop {
8196 let (mut stream, _) = listener.accept().await.unwrap();
8197 let mut request = [0; 2048];
8198 assert!(stream.read(&mut request).await.unwrap() > 0);
8199 let current = observed.status().unwrap().spawn_generation;
8200 if current != generation {
8201 generation = current;
8202 probes = 0;
8203 }
8204 probes += 1;
8205 let healthy = generation != first_generation && probes > 1;
8208 let code = if healthy { 200 } else { 503 };
8209 let response = format!(
8210 "HTTP/1.1 {code} scratch\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
8211 );
8212 let _ = stream.write_all(response.as_bytes()).await;
8213 if healthy {
8214 healthy_tx.send(()).await.unwrap();
8215 }
8216 }
8217 });
8218 timeout(Duration::from_secs(5), async {
8219 let mut healthy_probes = 0;
8220 loop {
8221 if module.state().unwrap() == ModuleState::Failed {
8222 break;
8223 }
8224 while healthy_rx.try_recv().is_ok() {
8225 healthy_probes += 1;
8226 }
8227 if healthy_probes >= 3
8228 && module.status().unwrap().health.status == SupervisorHealthStatus::Ok
8229 {
8230 break;
8231 }
8232 sleep(Duration::from_millis(5)).await;
8233 }
8234 })
8235 .await
8236 .expect("the replacement must settle healthy without exhausting its restart budget");
8237 let status = module.status().unwrap();
8238 module.drain().await.unwrap();
8239 server.abort();
8240 assert_eq!(status.state, ModuleState::Running);
8241 assert_eq!(status.health.status, SupervisorHealthStatus::Ok);
8242 assert_eq!(status.health.consecutive_failures, 0);
8243 assert_eq!(status.lifetime_restarts, 1);
8244 assert_eq!(status.restart_count, 1);
8245 }
8246
8247 #[cfg(unix)]
8248 #[tokio::test]
8249 async fn http_health_sustained_failure_exhausts_restart_budget() {
8250 use std::collections::BTreeMap;
8251 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8252 let dir = cortexkit_test_support::ScratchDir::new("http-health-budget");
8253 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8254 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8255 let mut configured = http_fixture(&dir, &url, 2);
8256 configured.restart.max_restarts = 2;
8257 let module =
8258 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8259 .supervise_configured_with_health(
8260 configured.module_spec(),
8261 true,
8262 configured.health,
8263 configured.drain_timeout_ms,
8264 configured.restart,
8265 )
8266 .unwrap();
8267 let observed = module.clone();
8268 let probes = Arc::new(Mutex::new(BTreeMap::<u64, u32>::new()));
8269 let served = probes.clone();
8270 let server = tokio::spawn(async move {
8271 loop {
8272 let (mut stream, _) = listener.accept().await.unwrap();
8273 let mut request = [0; 2048];
8274 assert!(stream.read(&mut request).await.unwrap() > 0);
8275 *served
8276 .lock()
8277 .unwrap()
8278 .entry(observed.status().unwrap().spawn_generation)
8279 .or_default() += 1;
8280 let _ = stream
8281 .write_all(b"HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
8282 .await;
8283 }
8284 });
8285 timeout(Duration::from_secs(5), async {
8286 while module.state().unwrap() != ModuleState::Failed {
8287 sleep(Duration::from_millis(5)).await;
8288 }
8289 })
8290 .await
8291 .expect("sustained failures must still exhaust the health restart budget");
8292 let status = module.status().unwrap();
8293 server.abort();
8294 assert_eq!(status.restart_count, 2);
8295 assert_eq!(status.lifetime_restarts, 2);
8296 assert!(!status.process_alive);
8297 assert_eq!(
8298 probes.lock().unwrap().values().copied().collect::<Vec<_>>(),
8299 vec![2, 2, 2]
8300 );
8301 }
8302
8303 #[cfg(unix)]
8304 #[tokio::test]
8305 async fn spawn_clears_the_previous_process_health() {
8306 let dir = cortexkit_test_support::ScratchDir::new("spawn-fresh-health");
8307 let mut configured = http_fixture(&dir, "http://127.0.0.1:1/healthz", 2);
8308 configured.health.cadence = Duration::from_secs(3600);
8309 let module =
8310 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8311 .supervise_configured_with_health(
8312 configured.module_spec(),
8313 false,
8314 configured.health,
8315 configured.drain_timeout_ms,
8316 configured.restart,
8317 )
8318 .unwrap();
8319 update_snapshot(&module.inner.snapshot, Some(module.module_id()), |state| {
8320 state.health.status = SupervisorHealthStatus::Unresponsive;
8321 state.health.consecutive_failures = 3;
8322 state.health.detail = Some("old process refused connections".into());
8323 state.health.metrics = Some(serde_json::json!({"old": true}));
8324 state.health.last_probe_ms = Some(123);
8325 state.health.last_action = Some("restart".into());
8326 state.health.last_action_ms = Some(124);
8327 })
8328 .unwrap();
8329 module.set_enabled(true).await.unwrap();
8330 let health = module.status().unwrap().health;
8331 module.drain().await.unwrap();
8332 assert_eq!(health.consecutive_failures, 0);
8333 assert_eq!(health.status, SupervisorHealthStatus::Unknown);
8334 assert_eq!(health.detail, None);
8335 assert_eq!(health.metrics, None);
8336 assert_eq!(health.last_probe_ms, None);
8337 assert_eq!(health.last_action.as_deref(), Some("restart"));
8338 assert_eq!(health.last_action_ms, Some(124));
8339 }
8340
8341 #[cfg(unix)]
8342 #[tokio::test]
8343 async fn http_health_no_listener_restarts_after_consecutive_failures() {
8344 let dir = cortexkit_test_support::ScratchDir::new("http-refused");
8345 let unused = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8346 let url = format!("http://{}/healthz", unused.local_addr().unwrap());
8347 drop(unused);
8348 let configured = http_fixture(&dir, &url, 2);
8349 let module =
8350 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8351 .supervise_configured_with_health(
8352 configured.module_spec(),
8353 true,
8354 configured.health,
8355 configured.drain_timeout_ms,
8356 configured.restart,
8357 )
8358 .unwrap();
8359 let before = module.status().unwrap().spawn_generation;
8360 timeout(Duration::from_secs(5), async {
8361 loop {
8362 let status = module.status().unwrap();
8363 if status.spawn_generation > before {
8364 assert!(status.lifetime_restarts > 0);
8365 break;
8366 }
8367 sleep(Duration::from_millis(5)).await;
8368 }
8369 })
8370 .await
8371 .expect("sustained HTTP refusal must trigger the health restart policy");
8372 module.drain().await.unwrap();
8373 }
8374
8375 #[cfg(unix)]
8376 #[tokio::test]
8377 async fn http_health_timeout_honours_deadline() {
8378 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8379 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8380 let server = tokio::spawn(async move {
8381 let _held = listener.accept().await.unwrap();
8382 std::future::pending::<()>().await;
8383 });
8384 let error = timeout(
8385 Duration::from_secs(1),
8386 probe_http_health(&url, Duration::from_millis(10)),
8387 )
8388 .await
8389 .expect("the probe must enforce its own deadline")
8390 .unwrap_err();
8391 server.abort();
8392 assert!(error.to_string().contains("timed out"));
8393 }
8394
8395 #[cfg(unix)]
8396 #[tokio::test]
8397 async fn http_health_localhost_reaches_an_ipv6_only_listener() {
8398 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8399 let listener = tokio::net::TcpListener::bind("[::1]:0").await.unwrap();
8400 let url = format!(
8401 "http://localhost:{}/healthz",
8402 listener.local_addr().unwrap().port()
8403 );
8404 let server = tokio::spawn(async move {
8405 let (mut stream, _) = listener.accept().await.unwrap();
8406 let mut request = [0u8; 2048];
8407 assert!(stream.read(&mut request).await.unwrap() > 0);
8408 stream
8409 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
8410 .await
8411 .unwrap();
8412 });
8413 assert_eq!(
8418 probe_http_health(&url, Duration::from_secs(10))
8419 .await
8420 .unwrap()
8421 .status,
8422 HealthStatus::Ok
8423 );
8424 server.await.unwrap();
8425 }
8426
8427 #[cfg(unix)]
8428 #[tokio::test]
8429 async fn http_health_timeout_keeps_partial_status_and_body() {
8430 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8431 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8432 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8433 let server = tokio::spawn(async move {
8434 let (mut stream, _) = listener.accept().await.unwrap();
8435 let mut request = [0u8; 2048];
8436 assert!(stream.read(&mut request).await.unwrap() > 0);
8437 stream
8438 .write_all(
8439 b"HTTP/1.1 503 Unavailable\r\nContent-Length: 100\r\n\r\npartial diagnostic",
8440 )
8441 .await
8442 .unwrap();
8443 std::future::pending::<()>().await;
8444 });
8445 let error = probe_http_health(&url, Duration::from_secs(1))
8446 .await
8447 .unwrap_err()
8448 .to_string();
8449 server.abort();
8450 assert!(
8451 error.contains("timed out")
8452 && error.contains("503 Unavailable")
8453 && error.contains("partial diagnostic"),
8454 "{error}"
8455 );
8456 }
8457
8458 #[cfg(unix)]
8459 #[tokio::test]
8460 async fn http_health_diagnostic_body_is_bounded_to_200_bytes() {
8461 use tokio::io::{AsyncReadExt, AsyncWriteExt};
8462 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8463 let url = format!("http://{}/healthz", listener.local_addr().unwrap());
8464 let server = tokio::spawn(async move {
8465 let (mut stream, _) = listener.accept().await.unwrap();
8466 let mut request = [0u8; 2048];
8467 assert!(stream.read(&mut request).await.unwrap() > 0);
8468 let body = format!("{}not-in-diagnostic", "x".repeat(400));
8469 let response = format!(
8470 "HTTP/1.1 503 Unavailable\r\nContent-Length: {}\r\n\r\n{body}",
8471 body.len()
8472 );
8473 stream.write_all(response.as_bytes()).await.unwrap();
8474 });
8475 let error = probe_http_health(&url, Duration::from_secs(1))
8476 .await
8477 .unwrap_err()
8478 .to_string();
8479 server.await.unwrap();
8480 assert!(error.ends_with(&"x".repeat(200)), "{error}");
8481 assert_eq!(error.split(": ").last().unwrap().len(), 200);
8482 assert!(!error.contains("not-in-diagnostic"));
8483 }
8484
8485 #[cfg(unix)]
8486 #[tokio::test]
8487 async fn http_health_real_nats_server_monitoring() {
8488 if std::process::Command::new("nats-server")
8489 .arg("--version")
8490 .env("XDG_DATA_HOME", std::env::temp_dir())
8491 .env("XDG_RUNTIME_DIR", std::env::temp_dir())
8492 .env("XDG_CONFIG_HOME", std::env::temp_dir())
8493 .output()
8494 .is_err()
8495 {
8496 eprintln!(
8497 "skipped: http_health_real_nats_server_monitoring (nats-server is not on PATH)"
8498 );
8499 return;
8500 }
8501 let dir = cortexkit_test_support::ScratchDir::new("nats-http-monitoring");
8502 let monitor = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8503 let port = monitor.local_addr().unwrap().port();
8504 let client = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
8505 let client_port = client.local_addr().unwrap().port();
8506 let config = dir.join("server.conf");
8507 std::fs::write(&config, format!("listen: 127.0.0.1:{client_port}\nhttp: 127.0.0.1:{port}\njetstream {{ store_dir: \"{}\" }}\n", dir.join("jetstream").display())).unwrap();
8508 let mut configured = http_fixture(&dir, &format!("http://127.0.0.1:{port}/healthz"), 1000);
8509 configured.program = PathBuf::from("nats-server");
8510 configured.args = vec!["-c".into(), config.to_string_lossy().into_owned()];
8511 drop(monitor);
8512 drop(client);
8513 let module =
8514 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
8515 .supervise_configured_with_health(
8516 configured.module_spec(),
8517 true,
8518 configured.health,
8519 configured.drain_timeout_ms,
8520 configured.restart,
8521 )
8522 .unwrap();
8523 wait_http_health(&module, SupervisorHealthStatus::Ok).await;
8524 module.drain().await.unwrap();
8525 }
8526
8527 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8528 async fn configuration_update_does_not_replace_captured_running_process_facts() {
8529 let supervisor =
8530 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
8531 let snapshot = stale_process_snapshot(ModuleState::Running, true);
8532 let initial = ModuleSpec {
8533 script: None,
8534 module_id: "rescan-preserves-spawn-facts".to_string(),
8535 program: PathBuf::from("/spawned/module"),
8536 args: Vec::new(),
8537 env: Vec::new(),
8538 reserved: false,
8539 reserved_prefixes: Vec::new(),
8540 protocol: ModuleProtocol::Subc,
8541 overlap: Default::default(),
8542 carry_containment: false,
8543 };
8544 let module = supervisor.supervised_module(
8545 initial.clone(),
8546 supervisor.runtime_config(),
8547 snapshot,
8548 None,
8549 );
8550 let before = module.status().unwrap();
8551 let mut replacement = initial;
8552 replacement.program = PathBuf::from("/rescanned/replacement-module");
8553
8554 module
8555 .update_configuration(replacement, HealthConfig::default(), None)
8556 .await
8557 .unwrap();
8558
8559 let after = module.status().unwrap();
8560 assert_eq!(after.pid, before.pid);
8561 assert_eq!(after.spawned_at_ms, before.spawned_at_ms);
8562 assert_eq!(after.spawned_from, before.spawned_from);
8563 drop(module);
8564 }
8565}
8566
8567fn unix_ms_now() -> u64 {
8568 SystemTime::now()
8569 .duration_since(UNIX_EPOCH)
8570 .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
8571 .unwrap_or(0)
8572}
8573
8574async fn supervise_loop(
8575 mut spec: ModuleSpec,
8576 mut runtime: SupervisorRuntimeConfig,
8577 registry: Arc<Registry>,
8578 process_liveness: Arc<SupervisorProcessLiveness>,
8579 snapshot: SharedSnapshot,
8580 mut child: Option<SupervisedChild>,
8581 mut commands: mpsc::Receiver<SupervisorCommand>,
8582) {
8583 let mut health_probe = HealthProbeRuntime::default();
8584 let mut registration_changes = match registry.subscribe_module_changes(&spec.module_id) {
8588 Ok(changes) => Some(changes),
8589 Err(err) => {
8590 warn!(module_id = %spec.module_id, error = %err, "health prober could not subscribe to registry");
8593 None
8594 }
8595 };
8596 let mut pending_respawn: Option<PendingRespawn> = None;
8600 let mut requeued: VecDeque<SupervisorCommand> = VecDeque::new();
8603 let mut previous_instance_recheck = tokio::time::interval_at(
8604 Instant::now() + Duration::from_secs(5),
8605 Duration::from_secs(5),
8606 );
8607 previous_instance_recheck.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
8608 'supervision: loop {
8609 #[cfg(test)]
8610 {
8611 lock_snapshot(&snapshot).unwrap().actor_select = None;
8612 }
8613 #[cfg(target_os = "macos")]
8614 if let Some(active) = child.as_mut() {
8615 active.confirm_privacy_exec().await;
8616 }
8617 if let Some(scheduled) = runtime
8618 .scheduled_respawn
8619 .lock()
8620 .unwrap_or_else(|p| p.into_inner())
8621 .take()
8622 {
8623 runtime.recovery_is_daemon = scheduled.daemon_initiated;
8624 pending_respawn = Some(scheduled);
8625 }
8626 if pending_respawn.is_some() && (child.is_some() || !respawn_still_pending(&snapshot)) {
8627 pending_respawn = None;
8628 cancel_deferred_reload(
8629 &runtime,
8630 &spec.module_id,
8631 "respawn cancelled by a supervisor command",
8632 );
8633 }
8634 if child.is_none()
8635 && pending_respawn.is_none()
8636 && lock_snapshot(&snapshot).is_ok_and(|state| state.waiting_for_previous_pid.is_none())
8637 {
8638 cancel_deferred_reload(
8639 &runtime,
8640 &spec.module_id,
8641 "respawn cancelled before a replacement was spawned",
8642 );
8643 let mut stranded = false;
8644 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8645 state.respawn_pending = false;
8646 state.coalesced_restart_pending = false;
8647 if matches!(
8648 state.state,
8649 ModuleState::Restarting
8650 | ModuleState::Starting
8651 | ModuleState::Draining
8652 | ModuleState::Unresponsive
8653 ) {
8654 error!(module_id = %spec.module_id, state = ?state.state,
8655 "supervision operation ended without a child or pending respawn; marking failed so start can retry");
8656 stranded = true;
8657 }
8658 });
8659 if stranded {
8660 fail_snapshot(
8661 &snapshot,
8662 Some(&spec.module_id),
8663 None,
8664 &runtime.failure_context(runtime.recovery_is_daemon),
8665 );
8666 }
8667 }
8668 if child.is_none()
8669 && (runtime.child_roster.is_closed()
8670 || pending_respawn.is_none()
8671 || !lock_snapshot(&snapshot)
8672 .is_ok_and(|state| state.enabled && state.state == ModuleState::Restarting))
8673 {
8674 containment::terminate(&runtime.child_roster.containment).await;
8675 }
8676 if let Some(command) = requeued.pop_front() {
8677 if !handle_supervisor_command(
8678 command,
8679 &mut spec,
8680 &mut runtime,
8681 ®istry,
8682 &process_liveness,
8683 &snapshot,
8684 &mut child,
8685 &mut commands,
8686 &mut requeued,
8687 )
8688 .await
8689 {
8690 containment::terminate(&runtime.child_roster.containment).await;
8691 return;
8692 }
8693 if child.is_some() || !respawn_still_pending(&snapshot) {
8694 pending_respawn = None;
8695 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
8696 state.respawn_pending = false
8697 });
8698 }
8699 continue;
8700 }
8701 if child.is_some() {
8702 runtime.recovery_is_daemon = true;
8703 #[cfg(test)]
8704 {
8705 lock_snapshot(&snapshot).unwrap().actor_turns += 1;
8706 }
8707 health_probe.refresh_registration(&spec, &runtime, ®istry, &snapshot);
8708 let active = child.as_mut().expect("child checked above");
8709 if active.registered_since_spawn() {
8710 if let Some(delivery) = &runtime.config_delivery {
8711 delivery.queue_registered(
8712 &spec.module_id,
8713 runtime.forwarding.as_ref(),
8714 ®istry,
8715 active,
8716 );
8717 }
8718 }
8719 if runtime.child_roster.is_closed() || !active.awaiting_registration() {
8720 active.registration_deadline = None;
8721 }
8722 let registration_deadline = active.registration_deadline;
8723 let no_checks = runtime.health.http.is_none()
8724 && (running_protocol(&spec, &snapshot) == ModuleProtocol::None
8725 || (health_probe.registered_connection.is_some() && !health_probe.advertised));
8726 let uptime_reset = lock_snapshot(&snapshot).ok().and_then(|mut state| {
8727 state
8728 .failed_retry
8729 .uptime_reset_at(no_checks, runtime.restart_policy.window)
8730 });
8731 let wake_at = match (health_probe.wake_at(), uptime_reset) {
8732 (probe, Some(reset)) => Some(probe.map_or(reset, |probe| probe.min(reset))),
8733 (probe, None) => probe,
8734 };
8735 let wake_at = match (wake_at, registration_deadline) {
8736 (Some(wake), Some(register)) => Some(wake.min(register)),
8737 (wake, register) => wake.or(register),
8738 };
8739 #[cfg(test)]
8740 let wake_after = wake_at.map(|at| at.saturating_duration_since(Instant::now()));
8741 let probe_sleep = supervisor_sleep(wake_at);
8742 tokio::pin!(probe_sleep);
8743 let wire_child = running_protocol(&spec, &snapshot) == ModuleProtocol::Subc;
8748 #[cfg(test)]
8749 {
8750 let registration_pending = wire_child
8751 && registration_changes
8752 .as_ref()
8753 .is_some_and(|changes| changes.has_changed().unwrap());
8754 let mut state = lock_snapshot(&snapshot).unwrap();
8755 state.actor_select = (!registration_pending).then_some(ActorSelectCheckpoint {
8756 generation: state.spawn_generation,
8757 turn: state.actor_turns,
8758 registered_connection: health_probe.registered_connection,
8759 next_probe_at: health_probe.next_probe_at,
8760 wake_after,
8761 });
8762 }
8763 let registration = active
8764 .awaiting_registration()
8765 .then(|| active.registration_spawn.clone())
8766 .flatten();
8767 #[cfg(all(test, target_os = "linux"))]
8768 let registration_before_exit = !runtime.child_roster.admission_event_for_test(
8769 &spec.module_id,
8770 "observe_registration_before_exit",
8771 Some(active.pid),
8772 ) && registration.is_some();
8773 #[cfg(not(all(test, target_os = "linux")))]
8774 let registration_before_exit = false;
8775 #[cfg(all(test, target_os = "linux"))]
8776 let registration_child_is_running = |child: &mut SupervisedChild| {
8777 registration_before_exit || registration_child_is_running(child)
8780 };
8781 let registration_failed = async {
8782 match ®istration {
8783 Some(spawn) => spawn.wait_registration_failure().await,
8784 None => std::future::pending().await,
8785 }
8786 };
8787 let active_child = child.as_mut().expect("child checked above");
8788 tokio::select! {
8789 _ = registration_failed => {
8790 if !active_child.registered_since_spawn() && registration_child_is_running(active_child) {
8791 active_child.registration_deadline = None;
8792 active_child.spawn_failure = Some("registration_channel_closed".into());
8793 if let Err(error) = stop_unregistered_child(active_child).await {
8794 fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8795 &runtime.spawn_events, format!("registration_channel_closed: {error}"),
8796 &runtime.failure_context(true));
8797 child = None;
8798 }
8799 }
8800 continue;
8801 }
8802 wait_result = active_child.wait(), if !registration_before_exit => {
8803 if let Ok(mut state) = lock_snapshot(&snapshot) {
8804 state.failed_retry.uptime_reset_at(no_checks, runtime.restart_policy.window);
8805 }
8806 #[cfg(test)]
8807 { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8808 let exit_report = match wait_result {
8817 Ok(status) => classify_reaped_child_exit(&snapshot, active_child, &status),
8818 Err(err) => {
8819 active_child.drain_stderr(&spec.module_id).await;
8820 fail_after_wait_error(
8821 &spec.module_id,
8822 &snapshot,
8823 &runtime.terminal_ring,
8824 &runtime.spawn_events,
8825 format!("failed to wait for supervised module: {err}"),
8826 &runtime.failure_context(true),
8827 );
8828 untrack_if_registration_released(
8829 &process_liveness,
8830 ®istry,
8831 &spec.module_id,
8832 &snapshot,
8833 );
8834 error!(module_id = %spec.module_id, error = %err, "failed to wait for supervised module");
8835 child = None;
8836 continue;
8837 }
8838 };
8839 active_child.drain_stderr(&spec.module_id).await;
8840
8841 let delivery=runtime.config_delivery.clone();
8842 let exited_spawn=active_child.spawned_at;
8843 let spawn=active_child.config_delivery.clone();
8844 let refusal=active_child.spawn_failure.as_deref().filter(|detail|detail.starts_with("program_refused:") && !active_child.live_program_binding.as_ref().is_some_and(|binding|binding.is_refused())).zip(active_child.admission_base.clone()).map(|(detail,base)|(base,subc_config::raw_digest(detail.as_bytes())));
8845 let module_id=spec.module_id.clone();
8846 let observed=async move {
8850 if let Some(delivery)=delivery {
8851 delivery.0.on_blocking(move |owner| {
8852 if let Some(spawn)=spawn { owner.delivery_child_exited(&spawn)?; }
8853 if let Some((base,identity))=refusal {owner.record_program_refusal(&module_id,&base,identity)?;}
8854 Ok(())
8855 }).await
8856 } else {Ok(())}
8857 };
8858 tokio::pin!(observed);
8859 loop {
8860 tokio::select! {
8861 result=&mut observed=>{
8862 if let Err(error)=result {warn!(module_id=%spec.module_id,%error,"configuration exit observation failed");}
8863 break;
8864 }
8865 command=commands.recv()=>{
8866 let Some(command)=command else {containment::terminate(&runtime.child_roster.containment).await;return;};
8867 let deferred=||SuperviseError::ConfigDeliveryDeferred {module_id:spec.module_id.clone()};
8868 let command=match command {
8869 SupervisorCommand::Restart {reply,..}|SupervisorCommand::Reload {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8870 SupervisorCommand::Swap {reply,..}=>{let _=reply.send(Err(deferred()));continue;}
8871 command @ (SupervisorCommand::ConfigApplyRestart {..}|SupervisorCommand::ConfigPolicyProbe {..}|SupervisorCommand::ConfigDeliveryFailed {..})=>{requeued.push_back(command);continue;}
8872 command=>command,
8873 };
8874 if !handle_supervisor_command(command,&mut spec,&mut runtime,®istry,&process_liveness,&snapshot,&mut child,&mut commands,&mut requeued).await {
8875 containment::terminate(&runtime.child_roster.containment).await;return;
8876 }
8877 if child.as_ref().is_none_or(|current|current.spawned_at!=exited_spawn) {continue 'supervision;}
8878 }
8879 }
8880 }
8881 let active_child=child.as_mut().expect("exit observation retained its child");
8882 let admission_kill = admission_exit::is_admission_kill(active_child.admission_kill_sent, &exit_report);
8886 let deferred_spawn=admission_kill && active_child.spawn_failure.as_deref().is_some_and(|detail|detail.starts_with("config_delivery_deferred:"));
8887 let refused_program = active_child.live_program_binding.as_ref().is_some_and(|binding| binding.is_refused());
8888 let exit_held = !deferred_spawn && (refused_program || runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.exit_is_held(&spec.module_id)));
8889 let parked = exit_held && (!refused_program || active_child.admission_base.is_some())
8890 && try_park_config_attempt(&spec, &runtime, &snapshot, &runtime.failure_context(true),
8891 if refused_program { active_child.admission_base.as_ref() } else { None })
8892 .unwrap_or_else(|error| { warn!(module_id=%spec.module_id, %error, "exit hold could not be recorded; using ordinary exit accounting"); false });
8893 let next = if deferred_spawn {
8894 record_terminal_with_detail(&spec.module_id,&runtime.terminal_ring,&runtime.spawn_events,&exit_report,TerminalDisposition::Restarting,active_child.exit_cleanup_detail(active_child.spawn_failure.clone()));
8895 let _=update_snapshot(&snapshot,Some(&spec.module_id),|state| {
8896 state.state=ModuleState::Restarting;
8897 clear_current_process_facts(state);
8898 state.last_exit=Some(exit_report.clone());
8899 });
8900 NextAction::Restart {schedule:None}
8901 } else if parked {
8902 record_terminal_with_detail(&spec.module_id, &runtime.terminal_ring, &runtime.spawn_events, &exit_report, TerminalDisposition::Stopped, active_child.exit_cleanup_detail(active_child.spawn_failure.clone().or_else(|| Some("config_gated".into()))));
8903 NextAction::Stop { registration_released: registry.get_module(&spec.module_id).ok().flatten().is_none() }
8904 } else { on_child_exit_with_detail(
8905 &spec,
8906 runtime.restart_policy,
8907 ®istry,
8908 &snapshot,
8909 &runtime.terminal_ring,
8910 &runtime.spawn_events,
8911 &runtime.child_roster,
8912 exit_report,
8913 true,
8914 active_child.exit_cleanup_detail(None),
8915 ).await };
8916 runtime.start_requester = None;
8917 runtime.pending_activity_restart = false;
8918 let carry = matches!(next, NextAction::Restart { .. })
8921 && active_child.spawn_failure.is_none()
8922 && !runtime.child_roster.is_closed();
8923 if let Err(error) = active_child.finish_exit(carry).await {
8924 containment::terminate(&runtime.child_roster.containment).await;
8925 fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
8926 &runtime.spawn_events, format!("failed to reap classified exit: {error}"),
8927 &runtime.failure_context(true));
8928 child = None;
8929 continue;
8930 }
8931 match next {
8932 NextAction::Stop { registration_released } => {
8933 if registration_released {
8934 process_liveness.untrack_if_current(&spec.module_id, &snapshot);
8935 }
8936 child = None;
8937 }
8938 NextAction::Restart { schedule } => {
8939 let delay = if deferred_spawn {CONFIG_ADMISSION_RETRY_DELAY} else {schedule.map_or(
8940 runtime.restart_policy.delay_for_restart(0),
8941 |schedule| schedule.delay,
8942 )};
8943 if let Some(schedule) = schedule {
8944 log_crash_respawn(&spec.module_id, schedule);
8945 }
8946 child = None;
8954 pending_respawn = Some(PendingRespawn { deadline: Instant::now() + delay, kind: RespawnKind::after_exit(schedule), daemon_initiated: true, approval: None });
8955 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
8956 }
8957 }
8958 }
8959 command = commands.recv() => {
8960 #[cfg(test)]
8961 { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8962 let Some(command) = command else {
8963 containment::terminate(&runtime.child_roster.containment).await;
8964 return;
8965 };
8966 if !handle_supervisor_command(
8967 command,
8968 &mut spec,
8969 &mut runtime,
8970 ®istry,
8971 &process_liveness,
8972 &snapshot,
8973 &mut child,
8974 &mut commands,
8975 &mut requeued,
8976 ).await {
8977 containment::terminate(&runtime.child_roster.containment).await;
8978 return;
8979 }
8980 }
8981 _ = async {
8982 match registration_changes.as_mut() {
8983 Some(changes) => { let _ = changes.changed().await; }
8984 None => std::future::pending().await,
8985 }
8986 }, if wire_child => {
8987 #[cfg(test)]
8988 { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8989 }
8990 _ = &mut probe_sleep => {
8991 #[cfg(test)]
8992 { lock_snapshot(&snapshot).unwrap().actor_select = None; }
8993 if registration_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
8994 active_child.registration_deadline = None;
8997 if !runtime.child_roster.is_closed()
8998 && !active_child.registered_since_spawn()
8999 && registration_child_is_running(active_child)
9000 {
9001 warn!(module_id = %spec.module_id, pid = active_child.pid,
9002 wait_secs = runtime.register_timeout.as_secs(),
9003 "supervised module registration_timeout: first HELLO deadline expired; stopping child");
9004 active_child.spawn_failure = Some("registration_timeout".into());
9005 if let Err(error) = stop_unregistered_child(active_child).await {
9006 error!(module_id = %spec.module_id, %error, "failed to stop unregistered child");
9007 fail_after_wait_error(&spec.module_id, &snapshot, &runtime.terminal_ring,
9008 &runtime.spawn_events, format!("registration_timeout: {error}"),
9009 &runtime.failure_context(true));
9010 child = None;
9011 }
9012 continue;
9015 }
9016 }
9017 if health_probe.due() {
9018 run_health_probe_cycle(
9019 &spec,
9020 &runtime,
9021 ®istry,
9022 &process_liveness,
9023 &snapshot,
9024 &mut child,
9025 ).await;
9026 if child.is_none() {
9027 runtime.start_requester = None;
9028 runtime.pending_activity_restart = false;
9029 }
9030 if child.is_some() {
9031 health_probe.schedule_next(&spec, runtime.health.cadence);
9032 }
9033 }
9034 }
9035 }
9036 } else if let Some(pending) = pending_respawn.clone() {
9037 tokio::select! {
9038 _ = runtime.child_roster.closed() => {
9039 pending_respawn = None;
9040 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9041 state.state = ModuleState::Stopped;
9042 state.respawn_pending = false;
9043 });
9044 containment::terminate(&runtime.child_roster.containment).await;
9045 }
9046 _ = async {
9047 sleep_until(pending.deadline).await;
9048 #[cfg(target_os = "linux")]
9049 ordinary_cgroup::await_clear(&runtime.child_roster, &spec.module_id).await;
9050 if let Some(delivery) = &runtime.config_delivery {
9051 delivery.unfenced(&spec.module_id).await;
9052 }
9053 } => {
9054 pending_respawn = None;
9055 let failure = pending.failure_context(&runtime);
9056 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9057 if !respawn_still_pending(&snapshot) {
9061 continue;
9062 }
9063 if runtime.child_roster.is_closed() {
9068 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9069 state.state = ModuleState::Stopped;
9070 });
9071 debug!(module_id = %spec.module_id, "crash respawn cancelled by daemon shutdown");
9072 continue;
9073 }
9074 if let Err(err) = release_dead_registration(
9075 ®istry,
9076 runtime.forwarding.as_deref(),
9077 &snapshot,
9078 &spec.module_id,
9079 &failure,
9080 ).await {
9081 record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9082 error!(module_id = %spec.module_id, error = %err, "registration did not release before restart");
9083 continue;
9084 }
9085
9086 if matches!(pending.kind, RespawnKind::Reload) {
9087 let reply = runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()).take();
9088 let result = finish_reload_child(&spec, &runtime, ®istry, &process_liveness, &snapshot, &mut child).await;
9089 if matches!(result, Err(SuperviseError::ConfigDeliveryDeferred { .. })) {
9090 *runtime.deferred_reload_reply.lock().unwrap_or_else(|p| p.into_inner()) = reply;
9091 continue;
9092 }
9093 if result.is_ok() && runtime.pending_activity_restart {
9094 runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9095 }
9096 runtime.pending_activity_restart = false;
9097 if let Some(reply) = reply { let _ = reply.send(result); }
9098 continue;
9099 }
9100 process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9101 match admit_running_child_async(&spec, &runtime, &snapshot, pending.kind).await {
9102 Ok(next_child) => {
9103 child = Some(next_child);
9104 if runtime.pending_activity_restart {
9105 runtime.record_activity_transition("subc.module_restarted", &spec.module_id, runtime.start_requester.clone());
9106 runtime.pending_activity_restart = false;
9107 }
9108 debug!(module_id = %spec.module_id, "supervised module restarted after crash");
9109 }
9110 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9111 pending_respawn = Some(PendingRespawn { deadline:Instant::now()+CONFIG_ADMISSION_RETRY_DELAY, ..pending });
9112 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = true);
9113 }
9114 Err(SuperviseError::ConfigHeld { .. }) => {
9115 let _ = hold_config_respawn(&spec, &runtime, &snapshot, pending.kind, &failure);
9116 runtime.pending_activity_restart = false;
9117 process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9118 }
9119 Err(err) => {
9120 fail_snapshot(&snapshot, Some(&spec.module_id), None, &failure);
9121 record_approved_attempt_failure(&spec, &snapshot, &failure, &err);
9122 process_liveness.untrack_if_current(&spec.module_id, &snapshot);
9123 error!(module_id = %spec.module_id, error = %err, "failed to restart supervised module");
9124 }
9125 }
9126 }
9127 command = commands.recv() => {
9128 let Some(command) = command else {
9129 containment::terminate(&runtime.child_roster.containment).await;
9130 return;
9131 };
9132 if !handle_supervisor_command(
9133 command,
9134 &mut spec,
9135 &mut runtime,
9136 ®istry,
9137 &process_liveness,
9138 &snapshot,
9139 &mut child,
9140 &mut commands,
9141 &mut requeued,
9142 ).await {
9143 containment::terminate(&runtime.child_roster.containment).await;
9144 return;
9145 }
9146 if child.is_some() || !respawn_still_pending(&snapshot) {
9151 pending_respawn = None;
9152 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| state.respawn_pending = false);
9153 }
9154 }
9155 }
9156 } else {
9157 let slow_retry = lock_snapshot(&snapshot).ok().and_then(|state| {
9158 (state.enabled && state.state == ModuleState::Failed)
9159 .then_some(state.failed_retry.pending)
9160 .flatten()
9161 });
9162 let command = if lock_snapshot(&snapshot)
9163 .is_ok_and(|state| state.waiting_for_previous_pid.is_some())
9164 {
9165 tokio::select! {
9166 command = commands.recv() => command,
9167 _ = previous_instance_recheck.tick() => {
9168 if runtime.child_roster.previous_instance_pid(&spec.module_id).is_none() {
9169 let enabled = lock_snapshot(&snapshot).is_ok_and(|state| state.enabled);
9170 if enabled && !runtime.child_roster.is_closed() {
9171 process_liveness.track(spec.module_id.clone(), Arc::clone(&snapshot));
9172 match spawn_and_mark_running_async(&spec, &runtime, &snapshot).await {
9173 Ok(next_child) => child = Some(next_child),
9174 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9175 let _ = defer_config_spawn(&spec, &runtime, &snapshot, RespawnKind::Spawn, &runtime.failure_context(true));
9176 }
9177 Err(SuperviseError::ConfigHeld { .. }) => {
9178 let _ = hold_config_spawn(&spec, &runtime, &snapshot, &runtime.failure_context(true));
9179 }
9180 Err(error) => {
9181 fail_snapshot(&snapshot, Some(&spec.module_id), None, &runtime.failure_context(true));
9182 error!(module_id = %spec.module_id, %error, "failed to start module after its previous instance exited");
9183 }
9184 }
9185 } else {
9186 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9187 state.waiting_for_previous_pid = None;
9188 state.waiting_for_previous_detail = None;
9189 });
9190 }
9191 }
9192 continue;
9193 }
9194 }
9195 } else {
9196 tokio::select! {
9197 biased;
9198 command = commands.recv() => command,
9199 _ = async {
9200 match slow_retry {
9201 Some(retry) => sleep_until(retry.deadline).await,
9202 None => std::future::pending().await,
9203 }
9204 } => {
9205 let retry = slow_retry.expect("only a scheduled slow retry can wake");
9206 let _ = update_snapshot(&snapshot, Some(&spec.module_id), |state| {
9207 state.failed_retry.pending = None;
9208 });
9209 if runtime.child_roster.is_closed() {
9210 continue;
9211 }
9212 info!(module_id = %spec.module_id, attempt = retry.attempt,
9213 delay_secs = retry.delay.as_secs(), "starting failed module retry");
9214 if let Err(error) = set_child_enabled(
9215 &spec, &runtime, ®istry, &process_liveness, &snapshot, &mut child, true,
9216 &runtime.failure_context(true),
9217 ).await {
9218 error!(module_id = %spec.module_id, %error, "failed module retry could not start");
9219 }
9220 continue;
9221 }
9222 }
9223 };
9224 let Some(command) = command else {
9225 containment::terminate(&runtime.child_roster.containment).await;
9226 return;
9227 };
9228 if !handle_supervisor_command(
9229 command,
9230 &mut spec,
9231 &mut runtime,
9232 ®istry,
9233 &process_liveness,
9234 &snapshot,
9235 &mut child,
9236 &mut commands,
9237 &mut requeued,
9238 )
9239 .await
9240 {
9241 containment::terminate(&runtime.child_roster.containment).await;
9242 return;
9243 }
9244 }
9245 }
9246}
9247
9248async fn supervisor_sleep(wake_at: Option<Instant>) {
9251 match wake_at {
9252 Some(deadline) => sleep_until(deadline).await,
9253 None => std::future::pending().await,
9254 }
9255}
9256
9257fn log_crash_respawn(module_id: &str, schedule: CrashRestartSchedule) {
9258 info!(
9259 module_id,
9260 restart_in_window = schedule.restart_in_window,
9261 delay_ms = schedule.delay.as_millis() as u64,
9262 "respawning after crash"
9263 );
9264}
9265
9266fn respawn_still_pending(snapshot: &SharedSnapshot) -> bool {
9272 matches!(
9273 lock_snapshot(snapshot),
9274 Ok(state) if state.enabled && state.state == ModuleState::Restarting
9275 )
9276}
9277
9278enum NextAction {
9279 Stop {
9280 registration_released: bool,
9281 },
9282 Restart {
9283 schedule: Option<CrashRestartSchedule>,
9284 },
9285}
9286
9287#[allow(clippy::too_many_arguments)]
9288async fn handle_supervisor_command(
9289 command: SupervisorCommand,
9290 spec: &mut ModuleSpec,
9291 runtime: &mut SupervisorRuntimeConfig,
9292 registry: &Arc<Registry>,
9293 process_liveness: &SupervisorProcessLiveness,
9294 snapshot: &SharedSnapshot,
9295 child: &mut Option<SupervisedChild>,
9296 commands: &mut mpsc::Receiver<SupervisorCommand>,
9297 requeued: &mut VecDeque<SupervisorCommand>,
9298) -> bool {
9299 if let SupervisorCommand::SetEnabled {
9300 enabled: true,
9301 reset_budget: false,
9302 reply,
9303 ..
9304 } = command
9305 {
9306 let parked = lock_snapshot(snapshot).ok().and_then(|state| {
9307 (state.config_hold_parked
9308 && state.enabled
9309 && !state.process_alive
9310 && child.is_none()
9311 && state.state == ModuleState::Stopped)
9312 .then(|| {
9313 (
9314 state.config_hold_daemon_initiated,
9315 state.config_hold_approval.clone(),
9316 )
9317 })
9318 });
9319 let result = if let Some((daemon_initiated, approval)) = parked {
9323 runtime.recovery_is_daemon = daemon_initiated;
9324 let failure = FailureContext {
9325 approval,
9326 ..runtime.failure_context(daemon_initiated)
9327 };
9328 let result = set_child_enabled_with_budget_policy(
9329 spec,
9330 runtime,
9331 registry,
9332 process_liveness,
9333 snapshot,
9334 child,
9335 true,
9336 &failure,
9337 false,
9338 )
9339 .await;
9340 if let Err(error) = &result {
9341 record_approved_attempt_failure(spec, snapshot, &failure, error);
9342 }
9343 result
9344 } else {
9345 Ok(false)
9346 };
9347 let _ = reply.send(result);
9348 return true;
9349 }
9350 let blocked = runtime
9351 .config_delivery
9352 .as_ref()
9353 .and_then(|delivery| delivery.0.check_module_hold(&spec.module_id).err())
9354 .filter(|error| error.code != "config_delivery_deferred")
9355 .map(|error| {
9356 config_delivery::gate_hold_error(spec, error, runtime.config_delivery.as_ref())
9357 })
9358 .or_else(|| recovery_block_error(spec, &runtime.child_roster))
9359 .or_else(|| {
9360 runtime
9361 .child_roster
9362 .previous_instance(&spec.module_id)
9363 .map(|(pid, reason)| previous_instance_error(spec, pid, reason))
9364 });
9365 let command = if let Some(error) = blocked {
9366 match command {
9367 SupervisorCommand::Restart { reply, .. } | SupervisorCommand::Reload { reply, .. } => {
9368 let _ = reply.send(Err(error));
9369 return true;
9370 }
9371 SupervisorCommand::Swap { reply, .. } => {
9372 let _ = reply.send(Err(error));
9373 return true;
9374 }
9375 SupervisorCommand::ConfigApplyRestart { .. } => return true,
9376 SupervisorCommand::SetEnabled {
9377 enabled: true,
9378 requester,
9379 reply,
9380 ..
9381 } => {
9382 if matches!(error, SuperviseError::ConfigHeld { .. })
9383 && lock_snapshot(snapshot).is_ok_and(|state| !state.enabled)
9384 && runtime
9385 .config_delivery
9386 .as_ref()
9387 .is_some_and(|delivery| delivery.0.can_stage_unstamp_enable())
9388 {
9389 let mut changed = false;
9393 let result = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9394 changed = !state.enabled;
9395 state.enabled = true;
9396 if child.is_none() && state.waiting_for_previous_pid.is_none() {
9397 state.state = ModuleState::Starting;
9398 state.failed_retry.cancel();
9399 }
9400 })
9401 .and_then(|_| {
9402 if child.is_none()
9403 && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none()
9404 {
9405 hold_config_spawn(
9406 spec,
9407 runtime,
9408 snapshot,
9409 &runtime.failure_context(false),
9410 )?;
9411 }
9412 Ok(changed)
9413 });
9414 if result.is_ok() && changed {
9415 runtime.start_requester = requester;
9416 }
9417 let _ = reply.send(result);
9418 return true;
9419 }
9420 let _ = reply.send(Err(error));
9421 return true;
9422 }
9423 other => other,
9424 }
9425 } else {
9426 command
9427 };
9428 if matches!(
9431 command,
9432 SupervisorCommand::Drain { .. }
9433 | SupervisorCommand::Retire { .. }
9434 | SupervisorCommand::SetEnabled { .. }
9435 | SupervisorCommand::Restart { .. }
9436 ) {
9437 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9438 state.failed_retry.cancel();
9439 });
9440 }
9441 match command {
9442 SupervisorCommand::ApprovedConfiguration { approved, reply } => {
9443 let result = async {
9444 let next = approved.module_entry(&spec.module_id).map_err(|error| {
9445 SuperviseError::InvalidSpec { reason: error.to_string() }
9446 })?;
9447 let retry_approved_failure = {
9448 let mut state = lock_snapshot(snapshot)?;
9449 if let Some((generation, detail)) = &state.approved_start_failure {
9450 if *generation == approved.identity() && next.enabled {
9451 return Err(SuperviseError::Spawn {
9452 program: spec.program.clone(),
9453 source: std::io::Error::other(detail.clone()),
9454 cgroup_path: None,
9455 });
9456 }
9457 }
9458 let retry = state.approved_start_failure.is_some();
9459 state.approved_start_failure = None;
9460 retry
9461 };
9462 stage_supervisor_configuration(
9463 spec, runtime, snapshot, next.module_spec(), next.health,
9464 next.drain_timeout_ms,
9465 );
9466 runtime.restart_policy = next.restart;
9467 runtime.register_timeout = next.register_timeout;
9468 if let Some(active) = child.as_mut()
9469 .filter(|child| child.registration_deadline.is_some())
9470 {
9471 active.registration_deadline = Some(active.spawned_at + next.register_timeout);
9472 }
9473 let enabled = lock_snapshot(snapshot)?.enabled;
9474 let retry_gate_stopped = lock_snapshot(snapshot)?
9481 .needs_approved_gate_restart(&approved.identity());
9482 let retry_failed = enabled && child.is_none()
9483 && ((lock_snapshot(snapshot)?.state == ModuleState::Failed
9484 && (retry_approved_failure || approved.changes_entry(&spec.module_id)))
9485 || retry_gate_stopped);
9486 if retry_failed {
9487 update_snapshot(snapshot, Some(&spec.module_id), |state| {
9490 state.failed_retry.cancel();
9491 if retry_gate_stopped {
9492 state.stop_reason = None;
9493 state.config_exit_failed_approval = None;
9494 }
9495 })?;
9496 }
9497 if enabled != next.enabled || retry_failed {
9498 let failure = FailureContext {
9499 approval: next.enabled.then(|| approved.identity()),
9500 ..runtime.failure_context(false)
9501 };
9502 let held = next.enabled && runtime.config_delivery.as_ref()
9503 .is_some_and(|delivery| delivery.0.has_recorded_admission_hold(&spec.module_id)
9504 || delivery.0.check_module_hold(&spec.module_id).is_err_and(|error| error.code == "config_delivery_deferred"));
9505 if held {
9506 reset_restart_count(snapshot, &spec.module_id)?;
9509 update_snapshot(snapshot, Some(&spec.module_id), |state| {
9510 state.enabled = true;
9511 if child.is_none() && state.waiting_for_previous_pid.is_none() {
9512 state.state = ModuleState::Starting;
9513 }
9514 })?;
9515 if child.is_none() && lock_snapshot(snapshot)?.waiting_for_previous_pid.is_none() {
9516 hold_config_spawn(spec, runtime, snapshot, &failure)?;
9517 }
9518 } else {
9519 match set_child_enabled_with_budget_policy(
9520 spec, runtime, registry, process_liveness, snapshot, child,
9521 next.enabled, &failure, true,
9522 ).await {
9523 Ok(_) => {},
9524 Err(SuperviseError::ConfigHeld { .. }) if next.enabled => {},
9525 Err(error) => return Err(error),
9526 }
9527 if !next.enabled {
9528 containment::terminate(&runtime.child_roster.containment).await;
9529 }
9530 }
9531 }
9532 if (child.as_ref().is_some_and(|child| child.registration_spawn.is_some() && child.admission_base.is_none())
9533 || (child.is_none() && lock_snapshot(snapshot)?.state == ModuleState::Restarting
9534 && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.stamp_channel_cutover_pending())))
9535 && runtime.config_delivery.as_ref().is_some_and(|delivery| delivery.0.module_is_gated(&spec.module_id))
9536 {
9537 let failure = FailureContext {
9538 approval: Some(approved.identity()),
9539 ..runtime.failure_context(false)
9540 };
9541 if child.is_some() {
9545 restart_child_with_budget_policy(spec, runtime, registry,
9546 process_liveness, snapshot, child, runtime.drain_timeout, false).await?;
9547 }
9548 update_snapshot(snapshot, Some(&spec.module_id), |state| state.respawn_pending = false)?;
9551 match spawn_and_mark_running_async(spec, runtime, snapshot).await {
9552 Ok(replacement) => *child = Some(replacement),
9553 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
9554 defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, &failure)?;
9555 }
9556 Err(SuperviseError::ConfigHeld { .. }) => hold_config_spawn(spec, runtime, snapshot, &failure)?,
9557 Err(error) => {
9558 fail_snapshot(snapshot, Some(&spec.module_id), None, &failure);
9559 return Err(error);
9560 }
9561 }
9562 }
9563 info!(module_id=%spec.module_id, config_generation=approved.generation(), "approved daemon entry reconciled");
9564 Ok(())
9565 }
9566 .await;
9567 if let Err(error) = &result {
9568 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9569 if state.enabled
9570 && state.state == ModuleState::Failed
9571 && state
9572 .approved_start_failure
9573 .as_ref()
9574 .is_none_or(|(generation, _)| *generation != approved.identity())
9575 {
9576 state.approved_start_failure =
9577 Some((approved.identity(), error.to_string()));
9578 }
9579 });
9580 }
9581 let _ = reply.send(result);
9582 true
9583 }
9584 SupervisorCommand::ConfigPolicyProbe {
9585 connection,
9586 generation,
9587 attempt,
9588 } => {
9589 let Some(delivery) = &runtime.config_delivery else {
9590 return true;
9591 };
9592 let Ok(gate) = delivery.0.module_gate(&spec.module_id) else {
9593 return true;
9594 };
9595 let guard = gate.lock().await;
9596 let pending = delivery
9597 .0
9598 .on_blocking(move |owner| {
9599 owner.policy_probe_pending(connection, generation, attempt)
9600 })
9601 .await
9602 .unwrap_or(false)
9603 && child.is_some()
9604 && registry
9605 .get_module(&spec.module_id)
9606 .ok()
9607 .flatten()
9608 .is_some_and(|registration| registration.connection_id == connection);
9609 drop(guard);
9610 if pending {
9611 run_health_probe_cycle(spec, runtime, registry, process_liveness, snapshot, child)
9612 .await;
9613 }
9614 true
9615 }
9616 SupervisorCommand::ConfigApplyRestart {
9617 generation,
9618 supersedes_swap,
9619 } => {
9620 let Some(owner) = runtime
9621 .config_delivery
9622 .as_ref()
9623 .map(|delivery| delivery.0.clone())
9624 else {
9625 return true;
9626 };
9627 let Ok(gate) = owner.module_gate(&spec.module_id) else {
9628 return true;
9629 };
9630 let _guard = gate.lock().await;
9631 let spawn = child
9632 .as_ref()
9633 .and_then(|child| child.config_delivery.clone());
9634 let module = spec.module_id.clone();
9635 let current = owner
9636 .on_blocking(move |owner| {
9637 Ok((supersedes_swap
9638 || owner
9639 .pending_config_restarts()?
9640 .contains(&(module.clone(), generation)))
9641 && owner.requires_fresher_spawn(&module, spawn.as_ref())?
9642 == Some(generation))
9643 })
9644 .await
9645 .unwrap_or(false);
9646 if !current
9647 || !lock_snapshot(snapshot).is_ok_and(|state| {
9648 state.enabled && !state.respawn_pending && state.process_alive
9649 })
9650 {
9651 return true;
9652 }
9653 drop(_guard);
9654 info!(module_id=%spec.module_id, config_generation=generation, "approved configuration restart preserves the crash budget");
9655 if let Err(error) = restart_child_with_budget_policy(
9656 spec,
9657 runtime,
9658 registry,
9659 process_liveness,
9660 snapshot,
9661 child,
9662 runtime.drain_timeout,
9663 false,
9664 )
9665 .await
9666 {
9667 warn!(module_id=%spec.module_id, %error, "approved configuration restart could not be scheduled");
9668 }
9669 true
9670 }
9671 SupervisorCommand::ConfigExitHold { reply } => {
9672 let idle_start = child.is_none()
9676 && lock_snapshot(snapshot).is_ok_and(|state| {
9677 state.enabled
9678 && state.state == ModuleState::Starting
9679 && !state.process_alive
9680 && !state.respawn_pending
9681 && state.waiting_for_previous_pid.is_none()
9682 && state.waiting_for_previous_detail.is_none()
9683 && state.failed_retry.pending.is_none()
9684 })
9685 && runtime
9686 .scheduled_respawn
9687 .lock()
9688 .unwrap_or_else(|p| p.into_inner())
9689 .is_none()
9690 && runtime
9691 .deferred_reload_reply
9692 .lock()
9693 .unwrap_or_else(|p| p.into_inner())
9694 .is_none();
9695 let result = if idle_start {
9696 try_park_config_attempt(
9697 spec,
9698 runtime,
9699 snapshot,
9700 &runtime.failure_context(runtime.recovery_is_daemon),
9701 None,
9702 )
9703 .map(|_| ())
9704 } else {
9705 Ok(())
9706 };
9707 let _ = reply.send(result);
9708 true
9709 }
9710 SupervisorCommand::ConfigDeliveryFailed { connection, hold } => {
9711 if registry
9712 .get_module(&spec.module_id)
9713 .ok()
9714 .flatten()
9715 .is_none_or(|registration| registration.connection_id != connection)
9716 {
9717 return true;
9718 }
9719 runtime.recovery_is_daemon = true;
9720 if hold {
9724 let notice = begin_forwarding_drain_if_configured(
9725 spec,
9726 runtime,
9727 registry,
9728 snapshot,
9729 Some(true),
9730 RouteCloseReason::Disable,
9731 )
9732 .await;
9733 if let Ok(notice) = notice {
9734 let drained = drain_optional_child(
9735 &spec.module_id,
9736 spec.protocol,
9737 notice,
9738 registry,
9739 runtime.forwarding.as_deref(),
9740 snapshot,
9741 &runtime.terminal_ring,
9742 &runtime.spawn_events,
9743 child,
9744 runtime.drain_timeout,
9745 ModuleState::Failed,
9746 Some(true),
9747 &runtime.failure_context(true),
9748 )
9749 .await;
9750 if drained.is_ok() {
9751 match try_park_config_attempt(
9752 spec,
9753 runtime,
9754 snapshot,
9755 &runtime.failure_context(true),
9756 None,
9757 ) {
9758 Ok(true) => {}
9759 Ok(false) => {
9760 if let Err(error) = budgeted_restart_child(
9761 spec,
9762 runtime,
9763 registry,
9764 process_liveness,
9765 snapshot,
9766 child,
9767 SupervisorHealthStatus::Unknown,
9768 Some("configuration delivery failed after its hold ended"),
9769 unix_ms_now(),
9770 false,
9771 )
9772 .await
9773 {
9774 warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9775 }
9776 }
9777 Err(error) => {
9778 warn!(module_id=%spec.module_id, %error, "configuration failure could not be parked")
9779 }
9780 }
9781 }
9782 }
9783 } else if let Err(error) = budgeted_restart_child(
9784 spec,
9785 runtime,
9786 registry,
9787 process_liveness,
9788 snapshot,
9789 child,
9790 SupervisorHealthStatus::Unknown,
9791 Some("configuration delivery failed"),
9792 unix_ms_now(),
9793 false,
9794 )
9795 .await
9796 {
9797 warn!(module_id=%spec.module_id, %error, "configuration failure restart could not be scheduled");
9798 }
9799 true
9800 }
9801 SupervisorCommand::Drain { requester, reply } => {
9802 let result = drain_optional_child(
9805 &spec.module_id,
9806 spec.protocol,
9807 StopNotice::NotSent,
9808 registry,
9809 runtime.forwarding.as_deref(),
9810 snapshot,
9811 &runtime.terminal_ring,
9812 &runtime.spawn_events,
9813 child,
9814 runtime.drain_timeout,
9815 ModuleState::Stopped,
9816 None,
9817 &FailureContext::operator(),
9818 )
9819 .await;
9820 containment::terminate(&runtime.child_roster.containment).await;
9821 let registration_released = result.is_ok();
9822 if registration_released {
9823 runtime.record_activity_transition(
9824 "subc.module_stopped",
9825 &spec.module_id,
9826 requester,
9827 );
9828 }
9829 let _ = reply.send(result);
9830 if registration_released {
9831 process_liveness.untrack_if_current(&spec.module_id, snapshot);
9832 }
9833 false
9834 }
9835 SupervisorCommand::Retire { requester, reply } => {
9836 let result = async {
9837 let stop_notice = begin_forwarding_drain_if_configured(
9838 spec,
9839 runtime,
9840 registry,
9841 snapshot,
9842 None,
9843 RouteCloseReason::Disable,
9844 )
9845 .await?;
9846 drain_optional_child(
9847 &spec.module_id,
9848 spec.protocol,
9849 stop_notice,
9850 registry,
9851 runtime.forwarding.as_deref(),
9852 snapshot,
9853 &runtime.terminal_ring,
9854 &runtime.spawn_events,
9855 child,
9856 runtime.drain_timeout,
9857 ModuleState::Stopped,
9858 None,
9859 &FailureContext::operator(),
9860 )
9861 .await
9862 }
9863 .await;
9864 containment::terminate(&runtime.child_roster.containment).await;
9865 let registration_released = result.is_ok();
9866 if registration_released {
9867 runtime.record_activity_transition(
9868 "subc.module_stopped",
9869 &spec.module_id,
9870 requester,
9871 );
9872 }
9873 let _ = reply.send(result);
9874 if registration_released {
9875 process_liveness.untrack_if_current(&spec.module_id, snapshot);
9876 }
9877 false
9878 }
9879 SupervisorCommand::Restart {
9880 requester,
9881 drain_timeout_ms,
9882 received_at_generation,
9883 queued_at,
9884 reply,
9885 } => {
9886 info!(
9890 module_id = %spec.module_id,
9891 queued_ms = u64::try_from(queued_at.elapsed().as_millis()).unwrap_or(u64::MAX),
9892 "restart command dequeued"
9893 );
9894 let validation = match lock_snapshot(snapshot) {
9906 Ok(state) if !state.enabled => Err(SuperviseError::Disabled {
9907 module_id: spec.module_id.clone(),
9908 }),
9909 Ok(_) => Ok(()),
9910 Err(err) => Err(err),
9911 };
9912 let initiated = validation.is_ok();
9913 let _ = reply.send(validation);
9914 let satisfied_by_generation = if initiated
9928 && child
9929 .as_ref()
9930 .is_some_and(|child| child.spawned_at > queued_at)
9931 {
9932 lock_snapshot(snapshot).ok().and_then(|state| {
9933 (!state.configuration_updated_since_spawn).then_some(state.spawn_generation)
9934 })
9935 } else {
9936 None
9937 };
9938 let satisfied_by_pending = initiated
9939 && child.is_none()
9940 && lock_snapshot(snapshot).ok().is_some_and(|mut state| {
9941 let pending = state.respawn_pending && !state.configuration_updated_since_spawn;
9945 if pending {
9946 state.coalesced_restart_pending = true;
9947 }
9948 pending
9949 });
9950 if satisfied_by_pending {
9951 debug!(module_id = %spec.module_id, "restart coalesced into the pending replacement");
9952 } else if let Some(generation) = satisfied_by_generation {
9953 info!(
9954 module_id = %spec.module_id,
9955 received_at_generation,
9956 "restart already satisfied by generation {generation}; not restarting again"
9957 );
9958 } else if initiated {
9959 let drain_timeout = drain_timeout_ms
9962 .map(Duration::from_millis)
9963 .unwrap_or(runtime.drain_timeout);
9964 if let Err(err) = restart_child(
9965 spec,
9966 runtime,
9967 registry,
9968 process_liveness,
9969 snapshot,
9970 child,
9971 drain_timeout,
9972 )
9973 .await
9974 {
9975 warn!(
9976 module_id = %spec.module_id,
9977 error = %err,
9978 "operator restart failed after initiation ack; module state carries the outcome"
9979 );
9980 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
9981 state.state = ModuleState::Failed;
9982 clear_current_process_facts(state);
9983 });
9984 } else {
9985 runtime.start_requester = requester;
9986 runtime.pending_activity_restart = true;
9987 }
9988 }
9989 true
9990 }
9991 SupervisorCommand::Reload { requester, reply } => {
9992 let result =
9993 reload_child(spec, runtime, registry, process_liveness, snapshot, child).await;
9994 if result.is_ok() {
9995 runtime.start_requester = requester;
9996 runtime.pending_activity_restart = true;
9997 }
9998 if result.is_ok()
9999 && runtime
10000 .scheduled_respawn
10001 .lock()
10002 .unwrap_or_else(|p| p.into_inner())
10003 .as_ref()
10004 .is_some_and(|pending| matches!(pending.kind, RespawnKind::Reload))
10005 {
10006 *runtime
10007 .deferred_reload_reply
10008 .lock()
10009 .unwrap_or_else(|p| p.into_inner()) = Some(reply);
10010 } else {
10011 let _ = reply.send(result);
10012 }
10013 true
10014 }
10015 SupervisorCommand::SetEnabled {
10016 enabled,
10017 requester,
10018 reply,
10019 reset_budget,
10020 } => {
10021 let previous_requester = runtime.start_requester.clone();
10022 if enabled {
10023 runtime.start_requester = requester.clone();
10024 }
10025 let result = set_child_enabled_with_budget_policy(
10026 spec,
10027 runtime,
10028 registry,
10029 process_liveness,
10030 snapshot,
10031 child,
10032 enabled,
10033 &runtime.failure_context(false),
10034 reset_budget,
10035 )
10036 .await;
10037 if !enabled {
10038 containment::terminate(&runtime.child_roster.containment).await;
10039 }
10040 if matches!(result, Ok(true)) {
10041 runtime.pending_activity_restart = false;
10042 if enabled {
10043 runtime.start_requester = requester;
10044 } else {
10045 runtime.start_requester = None;
10046 runtime.record_activity_transition(
10047 "subc.module_disabled",
10048 &spec.module_id,
10049 requester,
10050 );
10051 }
10052 } else {
10053 runtime.start_requester = previous_requester;
10054 }
10055 let _ = reply.send(result);
10056 true
10057 }
10058 SupervisorCommand::UpdateConfiguration {
10059 spec: next_spec,
10060 health,
10061 drain_timeout_ms,
10062 reply,
10063 } => {
10064 if runtime
10065 .config_delivery
10066 .as_ref()
10067 .is_some_and(|delivery| delivery.0.file_configuration_is_gated(&spec.module_id))
10068 {
10069 let _ = reply.send(Err(SuperviseError::ConfigHeld {
10070 module_id: spec.module_id.clone(),
10071 code: "config_gated".into(),
10072 detail: "live file reconfiguration cannot replace stamped authority".into(),
10073 }));
10074 return true;
10075 }
10076 stage_supervisor_configuration(
10077 spec,
10078 runtime,
10079 snapshot,
10080 next_spec,
10081 health,
10082 drain_timeout_ms,
10083 );
10084 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10085 state.configuration_updated_since_spawn = true;
10086 });
10087 let _ = reply.send(Ok(()));
10088 true
10089 }
10090 SupervisorCommand::Swap {
10091 requester,
10092 ready_timeout,
10093 reply,
10094 } => {
10095 if spec.carry_containment
10096 || containment::current(&runtime.child_roster.containment).is_some()
10097 {
10098 let _ = reply.send(Err(SuperviseError::InvalidSpec {
10099 reason: "a carried container cannot overlap a swap candidate".to_owned(),
10100 }));
10101 return true;
10102 }
10103 let mut swap_runtime = runtime.clone();
10104 swap_runtime.start_requester = requester;
10105 let before = lock_snapshot(snapshot)
10106 .ok()
10107 .map(|state| state.spawn_generation);
10108 let end = swap::run_swap(
10109 spec,
10110 &swap_runtime,
10111 registry,
10112 process_liveness,
10113 snapshot,
10114 child,
10115 commands,
10116 ready_timeout.unwrap_or(DEFAULT_SWAP_READY_TIMEOUT),
10117 reply,
10118 )
10119 .await;
10120 if before
10121 != lock_snapshot(snapshot)
10122 .ok()
10123 .map(|state| state.spawn_generation)
10124 {
10125 runtime.start_requester = swap_runtime.start_requester;
10126 }
10127 requeued.extend(end.requeue);
10128 true
10129 }
10130 }
10131}
10132
10133fn stage_supervisor_configuration(
10134 spec: &mut ModuleSpec,
10135 runtime: &mut SupervisorRuntimeConfig,
10136 snapshot: &SharedSnapshot,
10137 next_spec: ModuleSpec,
10138 health: HealthConfig,
10139 drain_timeout_ms: Option<u64>,
10140) {
10141 if let Some(handle) = &runtime.supervisor_handle {
10142 handle.apply_identity_configuration(&next_spec);
10143 }
10144 let launch_changed = *spec != next_spec;
10145 *spec = next_spec;
10146 if launch_changed {
10147 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10148 state.configuration_updated_since_spawn = true
10149 });
10150 }
10151 let health_changed = runtime.health != health;
10152 runtime.health = health;
10153 if health_changed {
10156 let _ = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10157 state.health = ModuleHealthStatus::default();
10158 state.last_probe_evidence = None;
10159 });
10160 }
10161 runtime.drain_timeout = drain_timeout_ms
10162 .map(Duration::from_millis)
10163 .unwrap_or(runtime.default_drain_timeout);
10164 *runtime
10165 .effective_drain_timeout
10166 .lock()
10167 .unwrap_or_else(|p| p.into_inner()) = runtime.drain_timeout;
10168}
10169
10170async fn restart_child(
10171 spec: &ModuleSpec,
10172 runtime: &SupervisorRuntimeConfig,
10173 registry: &Registry,
10174 process_liveness: &SupervisorProcessLiveness,
10175 snapshot: &SharedSnapshot,
10176 child: &mut Option<SupervisedChild>,
10177 drain_timeout: Duration,
10178) -> Result<(), SuperviseError> {
10179 restart_child_with_budget_policy(
10180 spec,
10181 runtime,
10182 registry,
10183 process_liveness,
10184 snapshot,
10185 child,
10186 drain_timeout,
10187 true,
10188 )
10189 .await
10190}
10191
10192#[allow(clippy::too_many_arguments)]
10193async fn restart_child_with_budget_policy(
10194 spec: &ModuleSpec,
10195 runtime: &SupervisorRuntimeConfig,
10196 registry: &Registry,
10197 process_liveness: &SupervisorProcessLiveness,
10198 snapshot: &SharedSnapshot,
10199 child: &mut Option<SupervisedChild>,
10200 drain_timeout: Duration,
10201 reset_budget: bool,
10202) -> Result<(), SuperviseError> {
10203 if !lock_snapshot(snapshot)?.enabled {
10205 return Err(SuperviseError::Disabled {
10206 module_id: spec.module_id.clone(),
10207 });
10208 }
10209 let stop_notice = begin_forwarding_drain_with_timeout(
10210 spec,
10211 runtime,
10212 registry,
10213 snapshot,
10214 None,
10215 RouteCloseReason::Restart,
10216 drain_timeout,
10217 )
10218 .await?;
10219
10220 if child.is_some() {
10221 drain_optional_child(
10222 &spec.module_id,
10223 spec.protocol,
10224 stop_notice,
10225 registry,
10226 runtime.forwarding.as_deref(),
10227 snapshot,
10228 &runtime.terminal_ring,
10229 &runtime.spawn_events,
10230 child,
10231 drain_timeout,
10232 ModuleState::Restarting,
10233 Some(true),
10234 &FailureContext::operator(),
10235 )
10236 .await?;
10237 } else {
10238 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10239 state.enabled = true;
10240 state.state = ModuleState::Restarting;
10241 clear_current_process_facts(state);
10242 })?;
10243 release_dead_registration(
10244 registry,
10245 runtime.forwarding.as_deref(),
10246 snapshot,
10247 &spec.module_id,
10248 &runtime.failure_context(false),
10249 )
10250 .await?;
10251 }
10252
10253 if reset_budget {
10254 reset_restart_count(snapshot, &spec.module_id)?;
10255 }
10256 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10257 schedule_respawn(
10258 runtime,
10259 snapshot,
10260 &spec.module_id,
10261 runtime.restart_policy.backoff,
10262 RespawnKind::Spawn,
10263 false,
10264 )
10265}
10266
10267async fn reload_child(
10268 spec: &ModuleSpec,
10269 runtime: &SupervisorRuntimeConfig,
10270 registry: &Registry,
10271 process_liveness: &SupervisorProcessLiveness,
10272 snapshot: &SharedSnapshot,
10273 child: &mut Option<SupervisedChild>,
10274) -> Result<(), SuperviseError> {
10275 if !lock_snapshot(snapshot)?.enabled {
10277 return Err(SuperviseError::Disabled {
10278 module_id: spec.module_id.clone(),
10279 });
10280 }
10281 let stop_notice = begin_forwarding_drain(
10282 spec,
10283 runtime,
10284 registry,
10285 snapshot,
10286 Some(true),
10287 RouteCloseReason::Reload,
10288 )
10289 .await?;
10290
10291 if child.is_some() {
10292 drain_optional_child(
10293 &spec.module_id,
10294 spec.protocol,
10295 stop_notice,
10296 registry,
10297 runtime.forwarding.as_deref(),
10298 snapshot,
10299 &runtime.terminal_ring,
10300 &runtime.spawn_events,
10301 child,
10302 runtime.drain_timeout,
10303 ModuleState::Restarting,
10304 Some(true),
10305 &FailureContext::operator(),
10306 )
10307 .await?;
10308 } else {
10309 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10310 state.enabled = true;
10311 state.state = ModuleState::Restarting;
10312 clear_current_process_facts(state);
10313 })?;
10314 release_dead_registration(
10315 registry,
10316 runtime.forwarding.as_deref(),
10317 snapshot,
10318 &spec.module_id,
10319 &runtime.failure_context(false),
10320 )
10321 .await?;
10322 }
10323
10324 reset_restart_count(snapshot, &spec.module_id)?;
10325 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10326 schedule_respawn(
10327 runtime,
10328 snapshot,
10329 &spec.module_id,
10330 runtime.restart_policy.backoff,
10331 RespawnKind::Reload,
10332 false,
10333 )
10334}
10335
10336async fn finish_reload_child(
10337 spec: &ModuleSpec,
10338 runtime: &SupervisorRuntimeConfig,
10339 registry: &Registry,
10340 process_liveness: &SupervisorProcessLiveness,
10341 snapshot: &SharedSnapshot,
10342 child: &mut Option<SupervisedChild>,
10343) -> Result<(), SuperviseError> {
10344 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10345 let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10346 Ok(next_child) => next_child,
10347 Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
10348 defer_config_spawn(
10349 spec,
10350 runtime,
10351 snapshot,
10352 RespawnKind::Reload,
10353 &runtime.failure_context(runtime.recovery_is_daemon),
10354 )?;
10355 return Err(error);
10356 }
10357 Err(error @ SuperviseError::ConfigHeld { .. }) => {
10358 let failure = runtime.failure_context(runtime.recovery_is_daemon);
10359 if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
10360 return Err(error);
10361 }
10362 defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
10363 return Err(SuperviseError::ConfigDeliveryDeferred {
10364 module_id: spec.module_id.clone(),
10365 });
10366 }
10367 Err(err) => {
10368 return handle_reload_spawn_failure(
10369 spec,
10370 runtime,
10371 process_liveness,
10372 snapshot,
10373 child,
10374 format!("new child failed to spawn: {err}"),
10375 )
10376 .await;
10377 }
10378 };
10379 *child = Some(next_child);
10380
10381 let wait_outcome = {
10382 let active_child = child.as_mut().expect("new reload child was just stored");
10383 wait_for_registration_after_reload(
10384 registry,
10385 &spec.module_id,
10386 snapshot,
10387 active_child,
10388 REGISTRY_RELEASE_TIMEOUT,
10389 )
10390 .await?
10391 };
10392
10393 match wait_outcome {
10394 RegistrationWaitOutcome::Registered => {
10395 child
10396 .as_mut()
10397 .expect("registered reload child")
10398 .registration_deadline = None;
10399 debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
10400 Ok(())
10401 }
10402 RegistrationWaitOutcome::Exited(exit_report) => {
10403 if let Some(active_child) = child.as_mut() {
10404 active_child.drain_stderr(&spec.module_id).await;
10405 }
10406 let mut exited_child = child.take().expect("exited reload child is still stored");
10409 #[cfg(test)]
10410 if let Some(gate) = &runtime.test_reload_exit_record_gate {
10411 gate.reached.notify_one();
10412 gate.resume.notified().await;
10413 }
10414 let result = handle_reload_child_registration_failure(
10415 spec,
10416 runtime,
10417 registry,
10418 process_liveness,
10419 snapshot,
10420 child,
10421 ReloadRegistrationFailure {
10422 exit_report: registration_failure_exit_report(exit_report),
10423 cleanup_detail: exited_child.exit_cleanup_detail(None),
10424 reason: exited_child
10425 .spawn_failure
10426 .clone()
10427 .unwrap_or_else(|| "new child exited before registering".to_string()),
10428 },
10429 )
10430 .await;
10431 exited_child
10432 .finish_exit(false)
10433 .await
10434 .map_err(|source| SuperviseError::Wait {
10435 module_id: spec.module_id.clone(),
10436 source,
10437 })?;
10438 result
10439 }
10440 RegistrationWaitOutcome::TimedOut => {
10441 let mut timed_out_child = child
10442 .take()
10443 .expect("timed-out reload child is still running");
10444 timed_out_child
10445 .start_kill()
10446 .map_err(|source| SuperviseError::Kill {
10447 module_id: spec.module_id.clone(),
10448 source,
10449 })?;
10450 let status = timed_out_child
10451 .wait()
10452 .await
10453 .map_err(|source| SuperviseError::Wait {
10454 module_id: spec.module_id.clone(),
10455 source,
10456 })?;
10457 timed_out_child.drain_stderr(&spec.module_id).await;
10458 let result = handle_reload_child_registration_failure(
10459 spec,
10460 runtime,
10461 registry,
10462 process_liveness,
10463 snapshot,
10464 child,
10465 ReloadRegistrationFailure {
10466 exit_report: registration_failure_exit_report(classify_reaped_child_exit(
10467 snapshot,
10468 &timed_out_child,
10469 &status,
10470 )),
10471 cleanup_detail: timed_out_child.exit_cleanup_detail(None),
10472 reason: format!(
10473 "new child did not register within {:?}",
10474 REGISTRY_RELEASE_TIMEOUT
10475 ),
10476 },
10477 )
10478 .await;
10479 timed_out_child
10480 .finish_exit(false)
10481 .await
10482 .map_err(|source| SuperviseError::Wait {
10483 module_id: spec.module_id.clone(),
10484 source,
10485 })?;
10486 result
10487 }
10488 }
10489}
10490
10491#[allow(clippy::too_many_arguments)]
10492async fn set_child_enabled(
10493 spec: &ModuleSpec,
10494 runtime: &SupervisorRuntimeConfig,
10495 registry: &Registry,
10496 process_liveness: &SupervisorProcessLiveness,
10497 snapshot: &SharedSnapshot,
10498 child: &mut Option<SupervisedChild>,
10499 enabled: bool,
10500 failure: &FailureContext,
10501) -> Result<bool, SuperviseError> {
10502 set_child_enabled_with_budget_policy(
10503 spec,
10504 runtime,
10505 registry,
10506 process_liveness,
10507 snapshot,
10508 child,
10509 enabled,
10510 failure,
10511 true,
10512 )
10513 .await
10514}
10515
10516#[allow(clippy::too_many_arguments)]
10517async fn set_child_enabled_with_budget_policy(
10518 spec: &ModuleSpec,
10519 runtime: &SupervisorRuntimeConfig,
10520 registry: &Registry,
10521 process_liveness: &SupervisorProcessLiveness,
10522 snapshot: &SharedSnapshot,
10523 child: &mut Option<SupervisedChild>,
10524 enabled: bool,
10525 failure: &FailureContext,
10526 reset_budget: bool,
10527) -> Result<bool, SuperviseError> {
10528 let (current_enabled, current_state, respawn_pending) = {
10529 let state = lock_snapshot(snapshot)?;
10530 (state.enabled, state.state, state.respawn_pending)
10531 };
10532 let revive_terminal = enabled
10540 && current_enabled
10541 && child.is_none()
10542 && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
10543 || (current_state == ModuleState::Restarting && !respawn_pending));
10544 if current_enabled == enabled && !revive_terminal {
10545 return Ok(false);
10546 }
10547
10548 if enabled {
10549 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10550 state.enabled = true;
10551 state.state = ModuleState::Starting;
10552 clear_current_process_facts(state);
10553 })?;
10554 #[cfg(test)]
10555 if runtime.test_seed_stale_facts_before_enable_spawn {
10556 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10557 state.process_alive = true;
10558 state.pid = Some(41);
10559 state.spawned_at_ms = Some(42);
10560 state.spawned_from = Some(PathBuf::from("/spawned/module"));
10561 state.spawned_file_identity = Some(SpawnedFileIdentity {
10562 device: 43,
10563 inode: 44,
10564 #[cfg(windows)]
10565 windows_image: None,
10566 });
10567 })?;
10568 }
10569 release_dead_registration(
10570 registry,
10571 runtime.forwarding.as_deref(),
10572 snapshot,
10573 &spec.module_id,
10574 failure,
10575 )
10576 .await?;
10577 if reset_budget {
10578 reset_restart_count(snapshot, &spec.module_id)?;
10579 }
10580 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
10581 let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
10582 Ok(next_child) => next_child,
10583 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
10584 defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
10585 return Ok(true);
10586 }
10587 Err(error @ SuperviseError::ConfigHeld { .. }) => {
10588 if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
10589 process_liveness.untrack_if_current(&spec.module_id, snapshot);
10590 return Err(parking_error);
10591 }
10592 return Err(error);
10593 }
10594 Err(err) => {
10595 fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
10596 process_liveness.untrack_if_current(&spec.module_id, snapshot);
10597 return Err(err);
10598 }
10599 };
10600 *child = Some(next_child);
10601 debug!(module_id = %spec.module_id, "supervised module enabled");
10602 Ok(true)
10603 } else {
10604 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10605 state.config_hold_parked = false;
10606 state.config_hold_daemon_initiated = false;
10607 state.config_hold_approval = None;
10608 })?;
10609 let stop_notice = begin_forwarding_drain_if_configured(
10610 spec,
10611 runtime,
10612 registry,
10613 snapshot,
10614 Some(false),
10615 RouteCloseReason::Disable,
10616 )
10617 .await?;
10618 drain_optional_child(
10619 &spec.module_id,
10620 spec.protocol,
10621 stop_notice,
10622 registry,
10623 runtime.forwarding.as_deref(),
10624 snapshot,
10625 &runtime.terminal_ring,
10626 &runtime.spawn_events,
10627 child,
10628 runtime.drain_timeout,
10629 ModuleState::Disabled,
10630 Some(false),
10631 failure,
10632 )
10633 .await?;
10634 debug!(module_id = %spec.module_id, "supervised module disabled");
10635 Ok(true)
10636 }
10637}
10638
10639#[allow(clippy::too_many_arguments)]
10640#[cfg(test)]
10641async fn on_child_exit(
10642 spec: &ModuleSpec,
10643 policy: RestartPolicy,
10644 registry: &Registry,
10645 snapshot: &SharedSnapshot,
10646 terminal_ring: &Arc<Mutex<TerminalRing>>,
10647 spawn_events: &SpawnEventFeed,
10648 roster: &ChildRoster,
10649 exit_report: ExitReport,
10650 daemon_initiated: bool,
10651) -> NextAction {
10652 on_child_exit_with_detail(
10653 spec,
10654 policy,
10655 registry,
10656 snapshot,
10657 terminal_ring,
10658 spawn_events,
10659 roster,
10660 exit_report,
10661 daemon_initiated,
10662 None,
10663 )
10664 .await
10665}
10666
10667#[allow(clippy::too_many_arguments)]
10668async fn on_child_exit_with_detail(
10669 spec: &ModuleSpec,
10670 policy: RestartPolicy,
10671 registry: &Registry,
10672 snapshot: &SharedSnapshot,
10673 terminal_ring: &Arc<Mutex<TerminalRing>>,
10674 spawn_events: &SpawnEventFeed,
10675 roster: &ChildRoster,
10676 exit_report: ExitReport,
10677 daemon_initiated: bool,
10678 detail: Option<String>,
10679) -> NextAction {
10680 if roster.is_closed() {
10686 return on_child_exit_during_daemon_shutdown(
10687 spec,
10688 registry,
10689 snapshot,
10690 terminal_ring,
10691 spawn_events,
10692 exit_report,
10693 detail,
10694 )
10695 .await;
10696 }
10697 let unrequested_clean_exit_of_protocol_none = exit_report.kind == ExitKind::Clean
10713 && running_protocol(spec, snapshot) == ModuleProtocol::None;
10714 match exit_report.kind {
10715 ExitKind::Clean if !unrequested_clean_exit_of_protocol_none => {
10716 info!(
10717 module_id = %spec.module_id,
10718 exit_code = ?exit_report.code,
10719 exit_signal = ?exit_report.signal,
10720 "supervised module exited cleanly"
10721 );
10722 if let Err(err) = publish_after_terminal_record(
10723 &spec.module_id,
10724 || {
10725 record_terminal_with_detail(
10726 &spec.module_id,
10727 terminal_ring,
10728 spawn_events,
10729 &exit_report,
10730 TerminalDisposition::Stopped,
10731 detail,
10732 )
10733 },
10734 || {
10735 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10736 state.state = ModuleState::Stopped;
10737 clear_current_process_facts(state);
10738 state.last_exit = Some(exit_report.clone());
10739 })
10740 },
10741 ) {
10742 error!(module_id = %spec.module_id, error = %err, "failed to publish clean module exit");
10743 }
10744 let registration_released = match wait_for_registration_release(
10745 registry,
10746 &spec.module_id,
10747 REGISTRY_RELEASE_TIMEOUT,
10748 )
10749 .await
10750 {
10751 Ok(()) => true,
10752 Err(err) => {
10753 warn!(module_id = %spec.module_id, error = %err, "registration still active after clean exit");
10754 false
10755 }
10756 };
10757 NextAction::Stop {
10758 registration_released,
10759 }
10760 }
10761 ExitKind::Clean | ExitKind::Crash => {
10762 if unrequested_clean_exit_of_protocol_none {
10763 warn!(
10764 module_id = %spec.module_id,
10765 exit_code = ?exit_report.code,
10766 exit_signal = ?exit_report.signal,
10767 "protocol-none module exited cleanly without a stop request; handling it as a crash"
10768 );
10769 } else {
10770 warn!(
10771 module_id = %spec.module_id,
10772 exit_code = ?exit_report.code,
10773 exit_signal = ?exit_report.signal,
10774 "supervised module exited abnormally (crash)"
10775 );
10776 }
10777 let mut restart_schedule = None;
10778 let mut disposition = TerminalDisposition::Disabled;
10779 let mut final_state = ModuleState::Disabled;
10780 let mut disposition_detail = lock_snapshot(snapshot)
10784 .ok()
10785 .and_then(|mut state| state.spawn_failure.take());
10786 if let Some(detail) = detail {
10787 disposition_detail = Some(
10788 disposition_detail
10789 .map_or_else(|| detail.clone(), |cause| format!("{cause}; {detail}")),
10790 );
10791 }
10792 let now = Instant::now();
10793 if let Err(err) = update_snapshot(snapshot, Some(&spec.module_id), |state| {
10794 if state.enabled {
10795 if let Some(schedule) = state.next_crash_restart(&policy, now) {
10796 state.respawn_pending = true;
10799 final_state = ModuleState::Restarting;
10800 restart_schedule = Some(schedule);
10801 disposition = TerminalDisposition::Restarting;
10802 } else {
10803 final_state = ModuleState::Failed;
10804 disposition = TerminalDisposition::Failed;
10805 let budget = policy.budget_exhausted_detail();
10806 disposition_detail =
10807 Some(disposition_detail.take().map_or_else(
10808 || budget.clone(),
10809 |cause| format!("{cause}; {budget}"),
10810 ));
10811 }
10812 } else {
10813 disposition = TerminalDisposition::Disabled;
10814 }
10815 }) {
10816 error!(module_id = %spec.module_id, error = %err, "failed to record crashed module exit");
10817 return NextAction::Stop {
10818 registration_released: false,
10819 };
10820 }
10821 if disposition == TerminalDisposition::Failed {
10822 error!(
10827 module_id = %spec.module_id,
10828 max_restarts = policy.max_restarts,
10829 window_secs = policy.window.as_secs(),
10830 "module stopped: {}",
10831 policy.budget_exhausted_detail()
10832 );
10833 }
10834 if let Err(err) = publish_after_terminal_record(
10835 &spec.module_id,
10836 || {
10837 record_terminal_with_detail(
10838 &spec.module_id,
10839 terminal_ring,
10840 spawn_events,
10841 &exit_report,
10842 disposition,
10843 disposition_detail,
10844 )
10845 },
10846 || {
10847 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10848 state.state = final_state;
10849 clear_current_process_facts(state);
10850 if final_state == ModuleState::Failed
10851 && daemon_initiated
10852 && !roster.is_closed()
10853 {
10854 state.failed_retry.schedule(&spec.module_id);
10855 }
10856 state.last_exit = Some(exit_report.clone());
10857 })
10858 },
10859 ) {
10860 error!(module_id = %spec.module_id, error = %err, "failed to publish crashed module exit");
10861 }
10862
10863 if let Some(schedule) = restart_schedule {
10864 NextAction::Restart {
10865 schedule: Some(schedule),
10866 }
10867 } else {
10868 let registration_released = match wait_for_registration_release(
10869 registry,
10870 &spec.module_id,
10871 REGISTRY_RELEASE_TIMEOUT,
10872 )
10873 .await
10874 {
10875 Ok(()) => true,
10876 Err(err) => {
10877 warn!(module_id = %spec.module_id, error = %err, "registration still active after failed module");
10878 false
10879 }
10880 };
10881 NextAction::Stop {
10882 registration_released,
10883 }
10884 }
10885 }
10886 ExitKind::DeliberateSeverance => {
10887 warn!(
10888 module_id = %spec.module_id,
10889 exit_code = ?exit_report.code,
10890 exit_signal = ?exit_report.signal,
10891 "supervised module exited after deliberate connection severance"
10892 );
10893 let should_restart = match lock_snapshot(snapshot) {
10894 Ok(state) => state.enabled,
10895 Err(err) => {
10896 error!(module_id = %spec.module_id, error = %err, "failed to read deliberately severed module state");
10897 return NextAction::Stop {
10898 registration_released: false,
10899 };
10900 }
10901 };
10902 let final_state = if should_restart {
10903 ModuleState::Restarting
10904 } else {
10905 ModuleState::Disabled
10906 };
10907 if let Err(err) = publish_after_terminal_record(
10908 &spec.module_id,
10909 || {
10910 record_terminal_with_detail(
10911 &spec.module_id,
10912 terminal_ring,
10913 spawn_events,
10914 &exit_report,
10915 terminal_disposition(final_state),
10916 detail,
10917 )
10918 },
10919 || {
10920 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10921 state.state = final_state;
10922 clear_current_process_facts(state);
10923 state.last_exit = Some(exit_report.clone());
10924 state.lifetime_restarts += 1;
10925 })
10926 },
10927 ) {
10928 error!(module_id = %spec.module_id, error = %err, "failed to publish deliberately severed module exit");
10929 return NextAction::Stop {
10930 registration_released: false,
10931 };
10932 }
10933
10934 if should_restart {
10935 NextAction::Restart { schedule: None }
10936 } else {
10937 let registration_released = match wait_for_registration_release(
10938 registry,
10939 &spec.module_id,
10940 REGISTRY_RELEASE_TIMEOUT,
10941 )
10942 .await
10943 {
10944 Ok(()) => true,
10945 Err(err) => {
10946 warn!(module_id = %spec.module_id, error = %err, "registration still active after deliberately severed module exit");
10947 false
10948 }
10949 };
10950 NextAction::Stop {
10951 registration_released,
10952 }
10953 }
10954 }
10955 }
10956}
10957
10958async fn on_child_exit_during_daemon_shutdown(
10959 spec: &ModuleSpec,
10960 registry: &Registry,
10961 snapshot: &SharedSnapshot,
10962 terminal_ring: &Arc<Mutex<TerminalRing>>,
10963 spawn_events: &SpawnEventFeed,
10964 exit_report: ExitReport,
10965 detail: Option<String>,
10966) -> NextAction {
10967 info!(
10968 module_id = %spec.module_id,
10969 exit_code = ?exit_report.code,
10970 exit_signal = ?exit_report.signal,
10971 exit_kind = ?exit_report.kind,
10972 "supervised module exited during daemon shutdown; not restarting it"
10973 );
10974 if let Err(err) = publish_after_terminal_record(
10975 &spec.module_id,
10976 || {
10977 record_terminal_with_detail(
10978 &spec.module_id,
10979 terminal_ring,
10980 spawn_events,
10981 &exit_report,
10982 TerminalDisposition::DaemonShutdown,
10983 detail,
10984 )
10985 },
10986 || {
10987 update_snapshot(snapshot, Some(&spec.module_id), |state| {
10988 state.state = ModuleState::Stopped;
10989 clear_current_process_facts(state);
10990 state.last_exit = Some(exit_report.clone());
10991 })
10992 },
10993 ) {
10994 error!(module_id = %spec.module_id, error = %err, "failed to publish module exit during daemon shutdown");
10995 }
10996 let registration_released =
10997 wait_for_registration_release(registry, &spec.module_id, REGISTRY_RELEASE_TIMEOUT)
10998 .await
10999 .is_ok();
11000 NextAction::Stop {
11001 registration_released,
11002 }
11003}
11004
11005fn publish_after_terminal_record<T>(
11010 module_id: &str,
11011 record: impl FnOnce(),
11012 publish: impl FnOnce() -> T,
11013) -> T {
11014 let recorded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(record));
11015 let published = publish();
11016 if let Err(panic) = recorded {
11017 error!(
11018 module_id,
11019 "terminal recording panicked; published final state before resuming unwind"
11020 );
11021 std::panic::resume_unwind(panic);
11022 }
11023 published
11024}
11025
11026fn fail_after_wait_error(
11027 module_id: &str,
11028 snapshot: &SharedSnapshot,
11029 terminal_ring: &Arc<Mutex<TerminalRing>>,
11030 spawn_events: &SpawnEventFeed,
11031 detail: String,
11032 failure: &FailureContext,
11033) {
11034 let report = wait_error_exit_report();
11035 publish_after_terminal_record(
11036 module_id,
11037 || {
11038 record_terminal_with_detail(
11039 module_id,
11040 terminal_ring,
11041 spawn_events,
11042 &report,
11043 TerminalDisposition::Failed,
11044 Some(detail),
11045 )
11046 },
11047 || fail_snapshot(snapshot, Some(module_id), Some(report.clone()), failure),
11048 );
11049}
11050
11051#[cfg(test)]
11052fn record_wait_error_terminal(
11053 module_id: &str,
11054 terminal_ring: &Arc<Mutex<TerminalRing>>,
11055 spawn_events: &SpawnEventFeed,
11056) {
11057 record_terminal(
11058 module_id,
11059 terminal_ring,
11060 spawn_events,
11061 &wait_error_exit_report(),
11062 TerminalDisposition::Failed,
11063 );
11064}
11065
11066#[cfg(test)]
11067fn record_terminal(
11068 module_id: &str,
11069 terminal_ring: &Arc<Mutex<TerminalRing>>,
11070 spawn_events: &SpawnEventFeed,
11071 exit_report: &ExitReport,
11072 disposition: TerminalDisposition,
11073) {
11074 record_terminal_with_detail(
11075 module_id,
11076 terminal_ring,
11077 spawn_events,
11078 exit_report,
11079 disposition,
11080 None,
11081 );
11082}
11083
11084fn durable_terminal_history_of(
11086 terminal_ring: &Mutex<TerminalRing>,
11087 module_id: &str,
11088) -> subc_control::TerminalHistory {
11089 let read = terminal_ring
11090 .lock()
11091 .unwrap_or_else(|p| p.into_inner())
11092 .capture_durable_history();
11093 read.read(module_id)
11094}
11095
11096fn record_terminal_with_detail(
11097 module_id: &str,
11098 terminal_ring: &Arc<Mutex<TerminalRing>>,
11099 spawn_events: &SpawnEventFeed,
11100 exit_report: &ExitReport,
11101 disposition: TerminalDisposition,
11102 disposition_detail: Option<String>,
11103) {
11104 #[cfg(test)]
11105 terminal_history_tests::before_terminal_record(spawn_events);
11106 spawn_events.emit_exited(module_id, exit_report.code, exit_report.signal);
11107 let record = TerminalRecord {
11108 exit_code: exit_report.code,
11109 exit_signal: exit_report.signal,
11110 at_ms: exit_report.at_ms,
11111 disposition,
11112 exit_kind: exit_report.kind.into(),
11113 disposition_detail,
11114 };
11115 terminal_ring
11116 .lock()
11117 .unwrap_or_else(|poisoned| poisoned.into_inner())
11118 .record_exit(module_id, record);
11119}
11120
11121fn untrack_if_registration_released(
11122 process_liveness: &SupervisorProcessLiveness,
11123 registry: &Registry,
11124 module_id: &str,
11125 snapshot: &SharedSnapshot,
11126) {
11127 match registry.get_module(module_id) {
11128 Ok(None) => process_liveness.untrack_if_current(module_id, snapshot),
11129 Ok(Some(_)) => {}
11130 Err(err) => {
11131 warn!(module_id, error = %err, "could not determine whether supervisor liveness can be untracked");
11132 }
11133 }
11134}
11135
11136#[cfg(test)]
11150fn apply_wire_spawn_args(
11151 command: &mut Command,
11152 spec: &ModuleSpec,
11153 connection_file_path: Option<&std::path::Path>,
11154 handle: Option<&SupervisorHandle>,
11155) -> Result<Option<NonceHandoff>, SuperviseError> {
11156 apply_wire_spawn_args_for_role(
11157 command,
11158 spec,
11159 connection_file_path,
11160 handle,
11161 SpawnRole::Plain,
11162 )
11163}
11164
11165#[cfg(unix)]
11170type NonceHandoff = subc_os::LaunchNonceHandoff;
11171#[cfg(windows)]
11172type NonceHandoff = subc_os::LaunchNoncePipeHandoff;
11173#[cfg(not(any(unix, windows)))]
11174type NonceHandoff = std::convert::Infallible;
11175
11176#[cfg(test)]
11194fn apply_wire_spawn_args_for_role(
11195 command: &mut Command,
11196 spec: &ModuleSpec,
11197 connection_file_path: Option<&std::path::Path>,
11198 handle: Option<&SupervisorHandle>,
11199 role: SpawnRole,
11200) -> Result<Option<NonceHandoff>, SuperviseError> {
11201 apply_wire_spawn_args_for_admission(command, spec, connection_file_path, handle, role, None)
11202}
11203
11204fn apply_wire_spawn_args_for_admission(
11205 command: &mut Command,
11206 spec: &ModuleSpec,
11207 connection_file_path: Option<&std::path::Path>,
11208 handle: Option<&SupervisorHandle>,
11209 role: SpawnRole,
11210 admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11211) -> Result<Option<NonceHandoff>, SuperviseError> {
11212 command.env(SUBC_MODULE_ID_ENV, &spec.module_id);
11213 command.env_remove(subc_os::LAUNCH_NONCE_FD_ENV);
11218 #[cfg(windows)]
11219 {
11220 command.env_remove(subc_os::LAUNCH_NONCE_PIPE_ENV);
11221 command.env_remove(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV);
11222 }
11223 command.env_remove(SUBC_LAUNCH_NONCE_ENV);
11225 command.env_remove(subc_os::registration_channel::REGISTRATION_FD_ENV);
11226 command.env_remove(subc_os::registration_channel::REGISTRATION_PIPE_ENV);
11227 command.env_remove(subc_os::registration_channel::DAEMON_PID_ENV);
11228 if role == SpawnRole::Plain {
11229 if let Some(handle) = handle {
11230 #[cfg(all(test, unix))]
11231 {
11232 let pause = {
11233 let mut slot = handle.plain_identity_policy_pause.lock().unwrap();
11234 if slot
11235 .as_ref()
11236 .is_some_and(|(module, _)| module == &spec.module_id)
11237 {
11238 slot.take().map(|(_, pause)| pause)
11239 } else {
11240 None
11241 }
11242 };
11243 if let Some(pause) = pause {
11244 pause.reached.send(()).unwrap();
11245 pause.release.recv().unwrap();
11246 }
11247 }
11248 handle.apply_identity_policy(spec, spec.protocol);
11252 }
11253 }
11254 if spec.protocol == ModuleProtocol::None {
11255 return Ok(None);
11256 }
11257 if let Some(connection_file_path) = connection_file_path {
11258 command.arg(SUBC_ARG).arg(connection_file_path);
11259 }
11260
11261 if admission.is_some_and(|admission| admission.launch.is_some()) {
11262 if let Some(handle) = handle {
11263 match role {
11264 SpawnRole::Plain => {
11265 handle
11266 .spawn_nonces
11267 .lock()
11268 .unwrap_or_else(|p| p.into_inner())
11269 .remove(&spec.module_id);
11270 if spec.reserved {
11271 handle
11272 .reserved_nonces
11273 .lock()
11274 .unwrap_or_else(|p| p.into_inner())
11275 .insert(spec.module_id.clone(), None);
11276 }
11277 }
11278 SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, String::new()),
11281 }
11282 }
11283 return Ok(None);
11284 }
11285 let nonce = generate_launch_nonce()?;
11289 if let Some(handle) = handle {
11290 match role {
11291 SpawnRole::Plain => {
11292 handle.set_spawn_nonce(&spec.module_id, nonce.clone());
11293 if spec.reserved {
11294 handle.set_reserved_nonce(&spec.module_id, nonce.clone());
11295 }
11296 }
11297 SpawnRole::SwapCandidate => handle.open_swap(&spec.module_id, nonce.clone()),
11298 }
11299 }
11300 #[cfg(unix)]
11301 let handoff = {
11302 let handoff =
11303 subc_os::LaunchNonceHandoff::new(&nonce).map_err(|source| SuperviseError::Spawn {
11304 program: spec.program.clone(),
11305 source,
11306 cgroup_path: None,
11307 })?;
11308 command.env(subc_os::LAUNCH_NONCE_FD_ENV, handoff.fd_env_value());
11309 Some(handoff)
11310 };
11311 #[cfg(windows)]
11312 let handoff = prepare_windows_nonce_pipe(command, spec, &nonce);
11313 #[cfg(not(any(unix, windows)))]
11314 let handoff = None;
11315 #[cfg(not(unix))]
11319 command.env(SUBC_LAUNCH_NONCE_ENV, nonce);
11320 Ok(handoff)
11321}
11322
11323pub(crate) fn apply_child_env(command: &mut Command, spec: &ModuleSpec) {
11324 command.env_remove(CK_LOG_ENV);
11325 command.env_remove(SUBC_SPAWN_ROLE_ENV);
11332 for (key, value) in &spec.env {
11333 if matches!(
11337 key.as_str(),
11338 CAPTURE_MAX_FILE_MB_ENV | CAPTURE_KEEP_ENV | CAPTURE_MAX_AGE_DAYS_ENV
11339 ) || key == SUBC_SPAWN_ROLE_ENV
11340 {
11341 continue;
11342 }
11343 command.env(key, value);
11344 }
11345}
11346
11347#[cfg(windows)]
11348fn prepare_windows_registration_pipe(
11349 command: &mut Command,
11350 spec: &ModuleSpec,
11351) -> Result<Option<SpawnRegistrationChannel>, SuperviseError> {
11352 if spec.protocol == ModuleProtocol::None {
11353 return Ok(None);
11354 }
11355 let pipe = subc_os::registration_channel::RegistrationPipe::new().map_err(|source| {
11356 SuperviseError::Spawn {
11357 program: spec.program.clone(),
11358 source,
11359 cgroup_path: None,
11360 }
11361 })?;
11362 command
11363 .env(
11364 subc_os::registration_channel::REGISTRATION_PIPE_ENV,
11365 pipe.name(),
11366 )
11367 .env(
11368 subc_os::registration_channel::DAEMON_PID_ENV,
11369 std::process::id().to_string(),
11370 );
11371 Ok(Some(pipe))
11372}
11373
11374#[cfg(windows)]
11375fn prepare_windows_nonce_pipe(
11376 command: &mut Command,
11377 spec: &ModuleSpec,
11378 nonce: &str,
11379) -> Option<NonceHandoff> {
11380 match subc_os::LaunchNoncePipeHandoff::new(nonce) {
11381 Ok(handoff) => {
11382 command.env(subc_os::LAUNCH_NONCE_PIPE_ENV, handoff.name());
11383 command.env(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env");
11388 Some(handoff)
11389 }
11390 Err(error) => {
11391 warn!(module_id = %spec.module_id, %error, "could not prepare launch nonce pipe; retaining the environment handoff");
11392 None
11393 }
11394 }
11395}
11396
11397#[cfg(windows)]
11398fn start_windows_nonce_pipe(
11399 handoff: Option<NonceHandoff>,
11400 pid: u32,
11401 spec: &ModuleSpec,
11402) -> Option<subc_os::LaunchNoncePipeDelivery> {
11403 handoff.and_then(|handoff| match handoff.serve(pid, REGISTRY_RELEASE_TIMEOUT) {
11407 Ok(delivery) => Some(delivery),
11408 Err(error) => {
11409 warn!(module_id = %spec.module_id, %error, "could not serve launch nonce pipe; retaining the environment handoff");
11410 None
11411 }
11412 })
11413}
11414
11415fn observed_launch_nonce_source(snapshot: &SupervisorSnapshot) -> Option<String> {
11416 #[cfg(windows)]
11417 if snapshot.process_alive && snapshot.spawned_protocol == Some(ModuleProtocol::Subc) {
11418 return Some(
11419 if snapshot
11420 .pipe_consumed
11421 .as_ref()
11422 .is_some_and(|consumed| consumed.get().is_some())
11423 {
11424 "pipe"
11425 } else {
11426 "env"
11427 }
11428 .to_owned(),
11429 );
11430 }
11431 let _ = snapshot;
11432 None
11433}
11434
11435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11438enum SpawnRole {
11439 Plain,
11440 SwapCandidate,
11441}
11442
11443fn apply_spawn_role(command: &mut Command, role: SpawnRole) {
11446 if role == SpawnRole::SwapCandidate {
11447 command.env(SUBC_SPAWN_ROLE_ENV, SPAWN_ROLE_SWAP_CANDIDATE);
11448 }
11449}
11450
11451fn previous_instance_error(
11452 spec: &ModuleSpec,
11453 pid: u32,
11454 reason: crate::live_children::RetainedReason,
11455) -> SuperviseError {
11456 SuperviseError::Spawn {
11457 program: spec.program.clone(),
11458 source: io::Error::new(io::ErrorKind::WouldBlock, reason.waiting_message(pid)),
11459 cgroup_path: None,
11460 }
11461}
11462
11463fn carries_containment(configured: bool, has_container: bool) -> bool {
11464 configured || has_container
11465}
11466
11467fn recovery_block_error(spec: &ModuleSpec, roster: &ChildRoster) -> Option<SuperviseError> {
11468 if !carries_containment(
11469 spec.carry_containment,
11470 containment::current(&roster.containment).is_some(),
11471 ) {
11472 return None;
11473 }
11474 Some(SuperviseError::Spawn {
11475 program: spec.program.clone(),
11476 source: io::Error::new(io::ErrorKind::WouldBlock, roster.recovery_block()?),
11477 cgroup_path: None,
11478 })
11479}
11480
11481#[allow(clippy::too_many_arguments)]
11482fn spawn_child(
11483 spec: &ModuleSpec,
11484 connection_file_path: Option<&std::path::Path>,
11485 handle: Option<&SupervisorHandle>,
11486 ring: &Arc<Mutex<StderrRing>>,
11487 capture_logs_dir: Option<&std::path::Path>,
11488 roster: &ChildRoster,
11489 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11490 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11491 register_timeout: Duration,
11492) -> Result<SupervisedChild, SuperviseError> {
11493 #[cfg(all(test, unix))]
11494 if let Some(source) = containment_tests::join_failure(spec, roster) {
11495 containment::terminate_blocking(&roster.containment);
11496 return Err(SuperviseError::Spawn {
11497 program: spec.program.clone(),
11498 source,
11499 cgroup_path: None,
11500 });
11501 }
11502 let result = spawn_child_in_slot(
11503 spec,
11504 connection_file_path,
11505 handle,
11506 ring,
11507 capture_logs_dir,
11508 roster,
11509 config_delivery,
11510 #[cfg(target_os = "linux")]
11511 cgroup_placement,
11512 SpawnRole::Plain,
11513 false,
11514 register_timeout,
11515 );
11516 if result
11517 .as_ref()
11518 .is_err_and(|error| !is_launch_deferral(error))
11519 {
11520 if roster.admission_pending(&spec.module_id) {
11521 containment::terminate_deferred(&roster.containment);
11522 } else {
11523 containment::terminate_blocking(&roster.containment);
11524 }
11525 }
11526 result
11527}
11528
11529fn is_launch_deferral(error: &SuperviseError) -> bool {
11535 matches!(error, SuperviseError::ConfigDeliveryDeferred { .. })
11536}
11537
11538#[allow(clippy::too_many_arguments)]
11551fn spawn_child_in_slot(
11552 spec: &ModuleSpec,
11553 connection_file_path: Option<&std::path::Path>,
11554 handle: Option<&SupervisorHandle>,
11555 ring: &Arc<Mutex<StderrRing>>,
11556 capture_logs_dir: Option<&std::path::Path>,
11557 roster: &ChildRoster,
11558 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11559 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
11560 role: SpawnRole,
11561 alternate_slot: bool,
11562 register_timeout: Duration,
11563) -> Result<SupervisedChild, SuperviseError> {
11564 let prepared = prepare_child_in_slot(
11565 spec,
11566 connection_file_path,
11567 handle,
11568 capture_logs_dir,
11569 roster,
11570 config_delivery,
11571 #[cfg(target_os = "linux")]
11572 cgroup_placement,
11573 role,
11574 alternate_slot,
11575 false,
11576 )?;
11577 let gate = config_delivery
11578 .map(|delivery| delivery.module_gate(spec))
11579 .transpose()?;
11580 let _gate = gate
11581 .as_ref()
11582 .map(|gate| {
11583 gate.try_lock()
11584 .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11585 module_id: spec.module_id.clone(),
11586 })
11587 })
11588 .transpose()?;
11589 if let (Some(delivery), Some(admission)) = (config_delivery, &prepared.spawn_admission) {
11590 delivery.check(spec, admission)?;
11591 }
11592 let checked_base = prepared
11593 .spawn_admission
11594 .as_ref()
11595 .and_then(|admission| admission.approved_base())
11596 .cloned();
11597 let mut result = launch_child_in_slot(spec, ring, roster, prepared, register_timeout);
11598 drop(_gate);
11599 if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11600 (config_delivery, &result)
11601 {
11602 if let Some(base) = checked_base.as_ref().filter(|_| code == "program_refused") {
11603 if !delivery.record_refusal(spec, base, detail)? {
11604 result = Err(spawn_plan_stale(spec));
11605 }
11606 }
11607 }
11608 result
11609}
11610
11611struct AsyncInitialIdentity<'a> {
11612 supervisor: &'a Supervisor,
11613 module: String,
11614 committed: bool,
11615}
11616impl Drop for AsyncInitialIdentity<'_> {
11617 fn drop(&mut self) {
11618 if !self.committed {
11619 self.supervisor.abandon_unrostered(&self.module);
11620 }
11621 }
11622}
11623
11624struct PreparedChild {
11628 script_delivery: Option<script::Delivery>,
11629 registration_spawn: Option<Arc<RegistrationSpawn>>,
11630 registration_handle: Option<SupervisorHandle>,
11631 #[cfg(any(unix, windows))]
11632 registration_channel: Option<SpawnRegistrationChannel>,
11633 config_context: Option<config_delivery::ConfigDelivery>,
11634 binding_publication: Option<ProgramBindingPublication>,
11635 launch_spec: ModuleSpec,
11636 spawn_admission: Option<crate::config_gate::runtime::SpawnAdmission>,
11637 command: Command,
11638 carrying: bool,
11639 carried: Option<Arc<containment::CarriedContainment>>,
11640 #[cfg(unix)]
11641 launch_identity: Option<containment::LaunchIdentity>,
11642 #[cfg(unix)]
11643 group_target: containment::GroupTarget,
11644 #[cfg(target_os = "linux")]
11645 cgroup_placement: Option<subc_cgroup::Placement>,
11646 #[cfg(target_os = "linux")]
11647 cgroup_name: String,
11648 #[cfg(target_os = "linux")]
11649 cgroup_cleanup: PreparedCgroup,
11650 cgroup_path: Option<PathBuf>,
11651 #[cfg(unix)]
11652 admission_gate: Option<admission::Gate>,
11653 output_sink: ChildOutputSink,
11654 #[cfg(target_os = "macos")]
11655 privacy_exec: Option<PrivacyExec>,
11656 #[cfg(windows)]
11657 image_capture: subc_os::ExecutableCapture,
11658 #[cfg(windows)]
11659 nonce_handoff: Option<NonceHandoff>,
11660 spawned_at: Instant,
11661 config_delivery: Option<crate::config_gate::runtime::DeliverySpawn>,
11662 delivery_registration: Option<config_delivery::RegistrationGuard>,
11663 program_binding: Option<SpawnProgramBinding>,
11664}
11665
11666#[cfg(target_os = "linux")]
11667struct PreparedCgroup(Option<(subc_cgroup::Placement, String)>);
11668#[cfg(target_os = "linux")]
11669impl Drop for PreparedCgroup {
11670 fn drop(&mut self) {
11671 if let Some((placement, name)) = &self.0 {
11672 remove_module_cgroup(placement, name);
11673 }
11674 }
11675}
11676
11677pub(crate) struct SpawnProgramBinding {
11678 pub(crate) path: PathBuf,
11679 _file: std::fs::File,
11682 pub(crate) identity: subc_os::RetainedFileIdentity,
11683}
11684
11685impl SpawnProgramBinding {
11686 pub(crate) fn capture(spec: &ModuleSpec) -> Result<Self, SuperviseError> {
11687 Self::capture_after_resolution(spec, |_| {})
11688 }
11689
11690 fn capture_after_resolution(
11691 spec: &ModuleSpec,
11692 before_open: impl FnOnce(&std::path::Path),
11693 ) -> Result<Self, SuperviseError> {
11694 require_program_search_path(spec)?;
11695 #[cfg(windows)]
11696 let windows_capture =
11697 windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
11698 program: spec.program.clone(),
11699 source,
11700 cgroup_path: None,
11701 })?;
11702 #[cfg(windows)]
11703 let path = windows_capture.path().to_path_buf();
11704 #[cfg(not(windows))]
11705 let path = if spec.program.is_absolute() || spec.program.components().count() > 1 {
11706 spec.program.clone()
11707 } else {
11708 let path = spec
11709 .env
11710 .iter()
11711 .rev()
11712 .find(|(key, _)| key == "PATH")
11713 .map(|(_, path)| std::ffi::OsString::from(path))
11714 .or_else(|| std::env::var_os("PATH"))
11715 .unwrap_or_else(|| {
11716 if cfg!(target_os = "macos") {
11717 "/usr/bin:/bin".into()
11720 } else {
11721 Default::default()
11722 }
11723 });
11724 std::env::split_paths(&path)
11725 .map(|dir| dir.join(&spec.program))
11726 .find(|path| {
11727 if !path.is_file() {
11728 return false;
11729 }
11730 #[cfg(unix)]
11731 {
11732 rustix::fs::accessat(
11733 rustix::fs::CWD,
11734 path,
11735 rustix::fs::Access::EXEC_OK,
11736 rustix::fs::AtFlags::EACCESS,
11737 )
11738 .is_ok()
11739 }
11740 #[cfg(not(unix))]
11741 {
11742 true
11743 }
11744 })
11745 .ok_or_else(|| SuperviseError::Spawn {
11746 program: spec.program.clone(),
11747 source: io::Error::new(io::ErrorKind::NotFound, "executable not found in PATH"),
11748 cgroup_path: None,
11749 })?
11750 };
11751 let resolved = std::fs::canonicalize(&path).map_err(|source| SuperviseError::Spawn {
11752 program: spec.program.clone(),
11753 source,
11754 cgroup_path: None,
11755 })?;
11756 before_open(&resolved);
11757 let file =
11760 subc_os::open_regular_nofollow(&resolved).map_err(|source| SuperviseError::Spawn {
11761 program: spec.program.clone(),
11762 source: io::Error::other(source),
11763 cgroup_path: None,
11764 })?;
11765 let identity =
11766 subc_os::retained_file_identity(&file).map_err(|source| SuperviseError::Spawn {
11767 program: spec.program.clone(),
11768 source,
11769 cgroup_path: None,
11770 })?;
11771 Ok(Self {
11772 path,
11773 _file: file,
11774 identity,
11775 })
11776 }
11777 fn current(&self) -> bool {
11778 #[cfg(unix)]
11779 {
11780 subc_os::file_identity(&self.path) == Some(self.identity)
11781 }
11782 #[cfg(windows)]
11783 {
11784 std::fs::canonicalize(&self.path)
11785 .ok()
11786 .and_then(|path| subc_os::open_regular_nofollow(&path).ok())
11787 .and_then(|file| subc_os::retained_file_identity(&file).ok())
11788 == Some(self.identity)
11789 }
11790 }
11791}
11792
11793fn spawn_plan_stale(spec: &ModuleSpec) -> SuperviseError {
11794 SuperviseError::ConfigDeliveryDeferred {
11795 module_id: spec.module_id.clone(),
11796 }
11797}
11798
11799fn require_program_search_path(spec: &ModuleSpec) -> Result<(), SuperviseError> {
11800 if !cfg!(target_os = "macos")
11801 && !spec.program.is_absolute()
11802 && spec.program.components().count() == 1
11803 && !spec.env.iter().any(|(key, _)| {
11804 if cfg!(windows) {
11805 key.eq_ignore_ascii_case("PATH")
11806 } else {
11807 key == "PATH"
11808 }
11809 })
11810 && std::env::var_os("PATH").is_none()
11811 {
11812 return Err(SuperviseError::Spawn {
11815 program: spec.program.clone(),
11816 source: io::Error::new(io::ErrorKind::InvalidInput, "bare program requires PATH"),
11817 cgroup_path: None,
11818 });
11819 }
11820 Ok(())
11821}
11822
11823async fn spawn_child_async(
11824 spec: &ModuleSpec,
11825 runtime: &SupervisorRuntimeConfig,
11826) -> Result<SupervisedChild, SuperviseError> {
11827 #[cfg(all(test, unix))]
11828 if let Some(source) = containment_tests::join_failure(spec, &runtime.child_roster) {
11829 containment::terminate_blocking(&runtime.child_roster.containment);
11830 return Err(SuperviseError::Spawn {
11831 program: spec.program.clone(),
11832 source,
11833 cgroup_path: None,
11834 });
11835 }
11836 let result = spawn_child_in_slot_async(spec, runtime, SpawnRole::Plain, false).await;
11837 if result
11838 .as_ref()
11839 .is_err_and(|error| !is_launch_deferral(error))
11840 {
11841 if runtime.child_roster.admission_pending(&spec.module_id) {
11842 containment::terminate_deferred(&runtime.child_roster.containment);
11843 } else {
11844 containment::terminate_blocking(&runtime.child_roster.containment);
11845 }
11846 }
11847 result
11848}
11849
11850async fn spawn_child_in_slot_async(
11851 spec: &ModuleSpec,
11852 runtime: &SupervisorRuntimeConfig,
11853 role: SpawnRole,
11854 alternate_slot: bool,
11855) -> Result<SupervisedChild, SuperviseError> {
11856 let gate = runtime
11857 .config_delivery
11858 .as_ref()
11859 .map(|delivery| delivery.0.module_gate(&spec.module_id))
11860 .transpose()
11861 .map_err(|error| SuperviseError::InvalidSpec {
11862 reason: error.to_string(),
11863 })?;
11864 if gate.as_ref().is_some_and(|gate| gate.try_lock().is_err()) {
11865 return Err(SuperviseError::ConfigDeliveryDeferred {
11866 module_id: spec.module_id.clone(),
11867 });
11868 }
11869 let prepared_spec = spec.clone();
11870 let prepared_runtime = runtime.clone();
11871 let prepared = tokio::task::spawn_blocking(move || {
11872 let prepared = prepare_child_in_slot(
11873 &prepared_spec,
11874 prepared_runtime.connection_file_path.as_deref(),
11875 prepared_runtime.supervisor_handle.as_ref(),
11876 prepared_runtime.capture_logs_dir.as_deref(),
11877 &prepared_runtime.child_roster,
11878 prepared_runtime.spawn_delivery(),
11879 #[cfg(target_os = "linux")]
11880 prepared_runtime.cgroup_placement.as_ref(),
11881 role,
11882 alternate_slot,
11883 true,
11884 );
11885 prepared
11886 })
11887 .await
11888 .map_err(|_| SuperviseError::InvalidSpec {
11889 reason: "configuration launch preparation stopped".into(),
11890 })??;
11891 if let Some(registration) = &prepared.delivery_registration {
11892 if !registration.launch_current()? {
11893 return Err(spawn_plan_stale(spec));
11894 }
11895 }
11896 let _gate = match gate {
11897 Some(gate) => {
11898 Some(
11899 gate.try_lock_owned()
11900 .map_err(|_| SuperviseError::ConfigDeliveryDeferred {
11901 module_id: spec.module_id.clone(),
11902 })?,
11903 )
11904 }
11905 None => None,
11906 };
11907 if let (Some(delivery), Some(admission)) = (runtime.spawn_delivery(), &prepared.spawn_admission)
11908 {
11909 delivery.check(spec, admission)?;
11910 }
11911 if prepared
11912 .spawn_admission
11913 .as_ref()
11914 .is_none_or(|admission| admission.launch.is_none())
11915 && prepared
11916 .program_binding
11917 .as_ref()
11918 .is_some_and(|binding| !binding.current())
11919 {
11920 return Err(spawn_plan_stale(spec));
11921 }
11922 let checked_base = prepared
11924 .spawn_admission
11925 .as_ref()
11926 .and_then(|admission| admission.approved_base())
11927 .cloned();
11928 let mut result = launch_child_in_slot(
11929 spec,
11930 &runtime.stderr_ring,
11931 &runtime.child_roster,
11932 prepared,
11933 runtime.register_timeout,
11934 );
11935 drop(_gate);
11936 if let (Some(delivery), Err(SuperviseError::ConfigHeld { code, detail, .. })) =
11937 (runtime.config_delivery.as_ref(), &result)
11938 {
11939 if let Some(base) = checked_base.filter(|_| code == "program_refused") {
11940 let module = spec.module_id.clone();
11941 let identity = subc_config::raw_digest(detail.as_bytes());
11942 let recorded = delivery
11943 .0
11944 .on_blocking(move |owner| owner.record_program_refusal(&module, &base, identity))
11945 .await;
11946 match recorded {
11947 Ok(true) => {}
11948 Ok(false) => result = Err(spawn_plan_stale(spec)),
11949 Err(error) => {
11950 result = Err(config_delivery::gate_hold_error(
11951 spec,
11952 error,
11953 Some(delivery),
11954 ))
11955 }
11956 }
11957 }
11958 }
11959 result
11960}
11961
11962fn validate_spawn_program(
11963 spec: &ModuleSpec,
11964 admission: Option<&crate::config_gate::runtime::SpawnAdmission>,
11965 delivery: Option<config_delivery::SpawnDelivery<'_>>,
11966) -> Result<(), SuperviseError> {
11967 if let Some(admission) = admission {
11968 if let Some(program) = &admission.launch {
11969 if let Err(error) = program.validate_for_spawn() {
11970 if let (Some(context), Some(base)) = (delivery, admission.approved_base()) {
11974 if error.code == "program_refused"
11975 && !context.record_refusal(spec, base, &error.detail)?
11976 {
11977 return Err(spawn_plan_stale(spec));
11978 }
11979 }
11980 return Err(config_delivery::gate_hold_error(
11981 spec,
11982 error,
11983 delivery.map(|context| context.runtime()).as_ref(),
11984 ));
11985 }
11986 }
11987 }
11988 Ok(())
11989}
11990
11991#[allow(clippy::too_many_arguments)]
11992fn prepare_child_in_slot(
11993 spec: &ModuleSpec,
11994 connection_file_path: Option<&std::path::Path>,
11995 handle: Option<&SupervisorHandle>,
11996 capture_logs_dir: Option<&std::path::Path>,
11997 roster: &ChildRoster,
11998 config_delivery: Option<config_delivery::SpawnDelivery<'_>>,
11999 #[cfg(target_os = "linux")] cgroup_placement: Option<&subc_cgroup::Placement>,
12000 role: SpawnRole,
12001 alternate_slot: bool,
12002 asynchronous: bool,
12003) -> Result<PreparedChild, SuperviseError> {
12004 require_program_search_path(spec)?;
12005 let spawn_admission = config_delivery
12006 .map(|delivery| delivery.prepare(spec))
12007 .transpose()?;
12008 #[cfg(target_os = "macos")]
12009 let gated = spawn_admission
12010 .as_ref()
12011 .is_some_and(|admission| admission.approved_base().is_some());
12012 let mut launch_spec = spawn_admission
12013 .as_ref()
12014 .and_then(|admission| admission.launch.as_ref())
12015 .map(|launch| launch.spec.clone())
12016 .unwrap_or_else(|| spec.clone());
12017 if let Some(script) = &launch_spec.script {
12018 launch_spec.program =
12019 script::runner_path(script.runtime).map_err(|source| SuperviseError::Spawn {
12020 program: launch_spec.program.clone(),
12021 source,
12022 cgroup_path: None,
12023 })?;
12024 }
12025 let script_content = if let Some(entry) = &launch_spec.script {
12026 Some(
12027 spawn_admission
12028 .as_ref()
12029 .and_then(|admission| admission.launch.as_ref())
12030 .and_then(|launch| launch.script.clone())
12031 .map_or_else(|| script::ScriptBytes::read(&entry.path), Ok)
12032 .map_err(|error| config_delivery::gate_hold_error(&launch_spec, error, None))?,
12033 )
12034 } else {
12035 None
12036 };
12037 let spec = &launch_spec;
12038 if let Some(error) = recovery_block_error(spec, roster) {
12039 return Err(error);
12040 }
12041 if let Some((pid, reason)) = roster.previous_instance(&spec.module_id) {
12042 return Err(previous_instance_error(spec, pid, reason));
12043 }
12044 if roster.is_closed() {
12045 return Err(SuperviseError::Spawn {
12046 program: spec.program.clone(),
12047 source: io::Error::other("the daemon is shutting down; not starting a new process"),
12048 cgroup_path: None,
12049 });
12050 }
12051 let carried = containment::current(&roster.containment);
12052 let carrying = carries_containment(spec.carry_containment, carried.is_some());
12053 if role != SpawnRole::Plain && carrying {
12054 return Err(SuperviseError::InvalidSpec {
12055 reason: "a carried container cannot overlap a swap candidate".to_owned(),
12056 });
12057 }
12058 #[cfg(unix)]
12059 let launch_identity = if carrying && carried.is_none() {
12060 Some(
12061 containment::LaunchIdentity::capture().map_err(|source| SuperviseError::Spawn {
12062 program: spec.program.clone(),
12063 source,
12064 cgroup_path: None,
12065 })?,
12066 )
12067 } else {
12068 None
12069 };
12070 #[cfg(target_os = "linux")]
12071 let cgroup_placement = match &carried {
12072 Some(container) => container.cgroup().map(|(placement, _)| placement),
12073 None => cgroup_placement,
12074 };
12075 #[cfg(unix)]
12076 let group_target = if let Some(container) = carried
12077 .as_ref()
12078 .filter(|container| container.group().is_some())
12079 {
12080 containment::GroupTarget::Pinned(Arc::clone(container))
12081 } else {
12082 #[cfg(target_os = "linux")]
12083 let cgroup_container = carrying && cgroup_placement.is_some();
12084 #[cfg(not(target_os = "linux"))]
12085 let cgroup_container = false;
12086 if cgroup_container {
12087 containment::GroupTarget::NoGroup
12088 } else {
12089 containment::GroupTarget::OwnLeader
12090 }
12091 };
12092 #[cfg(target_os = "linux")]
12093 let cgroup_name = {
12094 if let Some((_, name)) = carried.as_ref().and_then(|container| container.cgroup()) {
12099 name.to_owned()
12100 } else if cgroup_placement.is_none() {
12101 swap::cgroup_name(&spec.module_id, alternate_slot)
12102 } else {
12103 let nonce = generate_launch_nonce()?;
12104 let suffix = u128::from_str_radix(&nonce[..32], 16).expect("hex launch nonce");
12105 cgroup_label::generation_label(&spec.module_id, alternate_slot, suffix)
12106 }
12107 };
12108 #[cfg(not(target_os = "linux"))]
12109 let _ = alternate_slot;
12110 #[cfg(windows)]
12111 let image_capture = windows_spawn_capture(spec).map_err(|source| SuperviseError::Spawn {
12112 program: spec.program.clone(),
12113 source,
12114 cgroup_path: None,
12115 })?;
12116 #[cfg(windows)]
12117 let program_binding = if asynchronous {
12118 let mut resolved = spec.clone();
12119 resolved.program = image_capture.path().to_path_buf();
12120 Some(SpawnProgramBinding::capture(&resolved)?)
12121 } else {
12122 None
12123 };
12124 #[cfg(not(windows))]
12125 let program_binding = (asynchronous || cfg!(target_os = "macos"))
12126 .then(|| SpawnProgramBinding::capture(spec))
12127 .transpose()?;
12128 #[cfg(target_os = "macos")]
12129 validate_spawn_program(spec, spawn_admission.as_ref(), config_delivery)?;
12130 #[cfg(target_os = "macos")]
12131 let (mut command, privacy_exec, exec_ack) = privacy_command(
12132 spec,
12133 program_binding
12134 .as_ref()
12135 .expect("macOS captures every launch"),
12136 roster,
12137 gated,
12141 )?;
12142 #[cfg(windows)]
12143 let mut command = Command::new(image_capture.path());
12144 #[cfg(not(any(target_os = "macos", windows)))]
12145 let mut command = Command::new(
12146 program_binding
12147 .as_ref()
12148 .map_or(spec.program.as_path(), |binding| binding.path.as_path()),
12149 );
12150 command.args(&spec.args);
12151 apply_child_env(&mut command, spec);
12181 if spec.script.is_some() {
12182 script::remove_runtime_env(&mut command, spec);
12183 }
12184 let origin_witness = crate::program_origin::LaunchWitness::capture_command(spec, &command)
12185 .map_err(|source| SuperviseError::Spawn {
12186 program: spec.program.clone(),
12187 source,
12188 cgroup_path: None,
12189 })?;
12190 command.current_dir(&origin_witness.working_directory);
12191 apply_spawn_role(&mut command, role);
12192 let nonce_handoff = apply_wire_spawn_args_for_admission(
12193 &mut command,
12194 spec,
12195 connection_file_path,
12196 handle,
12197 role,
12198 spawn_admission.as_ref(),
12199 )?;
12200 #[cfg(unix)]
12201 let mut slots = subc_os::registration_channel::ChildDescriptorSlots::default();
12202 command.env_remove(subc_os::script_pipe::SCRIPT_FD_ENV);
12203 let script_delivery = script_content
12204 .map(|content| {
12205 script::Delivery::prepare(
12206 content,
12207 &mut command,
12208 #[cfg(unix)]
12209 &mut slots,
12210 )
12211 })
12212 .transpose()
12213 .map_err(|source| SuperviseError::Spawn {
12214 program: spec.program.clone(),
12215 source,
12216 cgroup_path: None,
12217 })?;
12218 #[cfg(unix)]
12219 let registration_channel = if spec.protocol == ModuleProtocol::Subc {
12220 let (parent, child, metadata) = subc_os::registration_channel::registration_socketpair()
12221 .map_err(|source| SuperviseError::Spawn {
12222 program: spec.program.clone(),
12223 source,
12224 cgroup_path: None,
12225 })?;
12226 slots
12227 .channel(child)
12228 .map_err(|source| SuperviseError::Spawn {
12229 program: spec.program.clone(),
12230 source,
12231 cgroup_path: None,
12232 })?;
12233 command
12234 .env(subc_os::registration_channel::REGISTRATION_FD_ENV, metadata)
12235 .env(
12236 subc_os::registration_channel::DAEMON_PID_ENV,
12237 std::process::id().to_string(),
12238 );
12239 Some(parent)
12240 } else {
12241 None
12242 };
12243 #[cfg(windows)]
12244 let registration_channel = prepare_windows_registration_pipe(&mut command, spec)?;
12245 let binding_publication = if spawn_admission
12246 .as_ref()
12247 .is_some_and(|admission| admission.launch.is_some())
12248 {
12249 handle.and_then(|handle| handle.begin_program_binding(&spec.module_id, role))
12250 } else {
12251 None
12252 };
12253 let registration_spawn = (spec.protocol == ModuleProtocol::Subc)
12254 .then(|| {
12255 handle.map(|handle| {
12256 let spawn = RegistrationSpawn::new_with_binding_requirement(
12257 handle,
12258 &spec.module_id,
12259 role,
12260 binding_publication.clone(),
12261 spawn_admission
12262 .as_ref()
12263 .is_some_and(|admission| admission.launch.is_some()),
12264 );
12265 if let Some(admission) = &spawn_admission {
12266 admission.initialize_origin(&spawn.authority, &origin_witness);
12267 }
12268 handle.record_nonce_launch(&spawn);
12269 spawn
12270 })
12271 })
12272 .flatten();
12273
12274 #[cfg(target_os = "linux")]
12275 let cgroup_path = cgroup_placement
12276 .map(|placement| {
12277 if let Some(container) = &carried {
12278 let path = container
12279 .cgroup_path()
12280 .ok_or_else(|| io::Error::other("carried container has no cgroup path"))?;
12281 placement.existing_module_path(path)?.ok_or_else(|| {
12282 io::Error::new(
12283 io::ErrorKind::NotFound,
12284 "carried cgroup disappeared before replacement",
12285 )
12286 })
12287 } else {
12288 if carrying {
12289 containment::prepare_cgroup_path(placement, &cgroup_name)
12290 } else {
12291 placement.module_path(&cgroup_name)
12292 }
12293 }
12294 })
12295 .transpose()
12296 .map_err(|source| SuperviseError::Cgroup {
12297 module_id: spec.module_id.clone(),
12298 source,
12299 })?;
12300 #[cfg(not(target_os = "linux"))]
12301 let cgroup_path: Option<PathBuf> = None;
12302 #[cfg(target_os = "linux")]
12305 let cgroup_cleanup = PreparedCgroup(
12306 cgroup_placement
12307 .filter(|_| carried.is_none())
12308 .map(|placement| (placement.clone(), cgroup_name.clone())),
12309 );
12310 #[cfg(unix)]
12311 let mut admission_gate = if carrying {
12312 Some(
12313 admission::Gate::install(&mut command, spec, roster).map_err(|source| {
12314 SuperviseError::Spawn {
12315 program: spec.program.clone(),
12316 source,
12317 cgroup_path: cgroup_path.clone(),
12318 }
12319 })?,
12320 )
12321 } else {
12322 None
12323 };
12324 #[cfg(target_os = "linux")]
12325 if let Some(path) = &cgroup_path {
12326 apply_cgroup_placement(&mut command, spec, path)?;
12327 }
12328
12329 let output_sink = if let Some(logs_dir) = capture_logs_dir {
12330 let path = logs_dir.join(format!("{}.stderr.log", spec.module_id));
12331 match ChildOutputSink::open(&path, capture_retention(spec)) {
12332 Ok(sink) => sink,
12333 Err(error) => {
12334 warn!(
12335 module_id = %spec.module_id,
12336 path = %path.display(),
12337 error = %error,
12338 "could not open child output capture file; forwarding to stderr"
12339 );
12340 ChildOutputSink::Stderr
12341 }
12342 }
12343 } else {
12344 ChildOutputSink::Stderr
12345 };
12346
12347 command.stdout(Stdio::piped());
12348 command.stderr(Stdio::piped());
12349 command.kill_on_drop(!carrying);
12350 #[cfg(unix)]
12367 command.process_group(
12368 carried
12369 .as_ref()
12370 .map(|container| container.verified_join_group())
12371 .transpose()
12372 .map_err(|source| SuperviseError::Spawn {
12373 program: spec.program.clone(),
12374 source,
12375 cgroup_path: cgroup_path.clone(),
12376 })?
12377 .flatten()
12378 .unwrap_or(0) as i32,
12379 );
12380 command.stdin(Stdio::null());
12381 #[cfg(unix)]
12382 if let Some(gate) = &mut admission_gate {
12383 gate.install_placement(&mut command);
12384 }
12385 #[cfg(unix)]
12388 {
12389 if let Some(handoff) = nonce_handoff {
12390 slots.nonce(handoff);
12391 }
12392 #[cfg(target_os = "macos")]
12393 slots
12394 .acknowledgement(exec_ack.into_descriptor())
12395 .map_err(|source| SuperviseError::Spawn {
12396 program: spec.program.clone(),
12397 source,
12398 cgroup_path: cgroup_path.clone(),
12399 })?;
12400 slots.install(command.as_std_mut());
12401 }
12402 #[cfg(not(any(unix, windows)))]
12403 let _ = nonce_handoff;
12404
12405 #[cfg(windows)]
12410 {
12411 subc_jobobject::ensure_root_job().map_err(|source| SuperviseError::Spawn {
12412 program: spec.program.clone(),
12413 source,
12414 cgroup_path: None,
12415 })?;
12416 subc_jobobject::suspend_on_create_async(&mut command);
12417 }
12418 let spawned_at = Instant::now();
12422 let delivery_context = config_delivery;
12423 let config_delivery = config_delivery
12424 .map(|delivery| {
12425 delivery.spawned(
12426 spec,
12427 spawn_admission
12428 .as_ref()
12429 .expect("delivery prepares spawn admission"),
12430 spawned_at,
12431 role,
12432 registration_spawn
12433 .as_ref()
12434 .map(|spawn| spawn.authority.clone()),
12435 )
12436 })
12437 .transpose()?
12438 .flatten();
12439 let mut delivery_registration =
12440 delivery_context.map(|context| context.registration_guard(config_delivery.as_ref(), role));
12441 if let Some(registration) = &mut delivery_registration {
12442 registration.defer_cleanup();
12443 }
12444 if asynchronous {
12445 #[cfg(test)]
12446 if let Some(context) = delivery_context {
12447 context.pause_preflight_for_test();
12448 }
12449 }
12450 validate_spawn_program(spec, spawn_admission.as_ref(), delivery_context)?;
12451 Ok(PreparedChild {
12452 script_delivery,
12453 registration_spawn,
12454 registration_handle: handle.cloned(),
12455 #[cfg(any(unix, windows))]
12456 registration_channel,
12457 config_context: delivery_context.map(|delivery| delivery.runtime()),
12458 binding_publication,
12459 launch_spec,
12460 spawn_admission,
12461 command,
12462 carrying,
12463 carried: carried.clone(),
12464 #[cfg(unix)]
12465 launch_identity,
12466 #[cfg(unix)]
12467 group_target,
12468 #[cfg(target_os = "linux")]
12469 cgroup_placement: cgroup_placement.cloned(),
12470 #[cfg(target_os = "linux")]
12471 cgroup_cleanup,
12472 #[cfg(target_os = "linux")]
12473 cgroup_name,
12474 cgroup_path,
12475 #[cfg(unix)]
12476 admission_gate,
12477 output_sink,
12478 #[cfg(target_os = "macos")]
12479 privacy_exec,
12480 #[cfg(windows)]
12481 image_capture,
12482 #[cfg(windows)]
12483 nonce_handoff,
12484 spawned_at,
12485 config_delivery,
12486 delivery_registration,
12487 program_binding,
12488 })
12489}
12490
12491fn launch_child_in_slot(
12492 _spec: &ModuleSpec,
12493 ring: &Arc<Mutex<StderrRing>>,
12494 roster: &ChildRoster,
12495 prepared: PreparedChild,
12496 register_timeout: Duration,
12497) -> Result<SupervisedChild, SuperviseError> {
12498 let launch_spec = prepared.launch_spec.clone();
12499 let registration_declaration = prepared
12500 .spawn_admission
12501 .as_ref()
12502 .and_then(|admission| admission.registration_declaration(&launch_spec.module_id));
12503 let admission_base = prepared
12504 .spawn_admission
12505 .as_ref()
12506 .and_then(|admission| admission.approved_base())
12507 .cloned();
12508 let spec = &launch_spec;
12509 let expected_image = prepared
12510 .spawn_admission
12511 .as_ref()
12512 .and_then(|admission| admission.launch.as_ref())
12513 .map(|launch| launch.image);
12514 let program_launch = prepared
12515 .spawn_admission
12516 .and_then(|admission| admission.launch);
12517 let config_owner = prepared
12518 .config_context
12519 .as_ref()
12520 .map(|context| context.0.clone());
12521 let binding_publication = prepared.binding_publication;
12522 #[cfg(test)]
12523 if let Some(context) = &prepared.config_context {
12524 context.0.before_spawn_exec_for_test();
12525 }
12526 #[cfg(feature = "test-support")]
12527 if let Some(context) = &prepared.config_context {
12528 context
12529 .0
12530 .pause_spawn_before_exec()
12531 .map_err(|error| config_delivery::gate_hold_error(spec, error, Some(context)))?;
12532 }
12533 let mut command = prepared.command;
12534 let carrying = prepared.carrying;
12535 let carried = prepared.carried;
12536 #[cfg(unix)]
12537 let launch_identity = prepared.launch_identity;
12538 #[cfg(unix)]
12539 let group_target = prepared.group_target;
12540 #[cfg(target_os = "linux")]
12541 let cgroup_placement = prepared.cgroup_placement.as_ref();
12542 #[cfg(target_os = "linux")]
12543 let cgroup_name = prepared.cgroup_name;
12544 #[cfg(target_os = "linux")]
12545 let mut cgroup_cleanup = prepared.cgroup_cleanup;
12546 #[cfg(target_os = "linux")]
12547 let _ = cgroup_cleanup.0.take();
12548 let cgroup_path = prepared.cgroup_path;
12549 #[cfg(unix)]
12550 let admission_gate = prepared.admission_gate;
12551 let output_sink = prepared.output_sink;
12552 #[cfg(target_os = "macos")]
12553 let mut privacy_exec = prepared.privacy_exec;
12554 #[cfg(target_os = "macos")]
12555 if let Some(pending) = &mut privacy_exec {
12556 pending.admission_binding = binding_publication.clone();
12557 if expected_image.is_some() {
12558 pending.expected = expected_image;
12559 }
12560 }
12561 #[cfg(any(unix, windows))]
12562 let registration_channel = prepared.registration_channel;
12563 let registration_spawn = prepared.registration_spawn;
12564 let registration_handle = prepared.registration_handle;
12565 #[cfg(windows)]
12566 let image_capture = prepared.image_capture;
12567 #[cfg(windows)]
12568 let nonce_handoff = prepared.nonce_handoff;
12569 let spawned_at = prepared.spawned_at;
12570 let config_delivery = prepared.config_delivery;
12571 let delivery_registration = prepared.delivery_registration;
12572 let _program_binding = prepared.program_binding;
12573 #[cfg(all(test, unix))]
12574 containment_tests::record_spawn_attempt(spec, &mut command);
12575 #[cfg(unix)]
12576 let spawned = match admission_gate {
12577 Some(gate) => gate
12578 .spawn(
12579 command,
12580 spec,
12581 roster,
12582 launch_identity,
12583 #[cfg(target_os = "linux")]
12584 cgroup_placement
12585 .zip(cgroup_path.as_ref())
12586 .map(|(placement, path)| {
12587 (placement.clone(), cgroup_name.clone(), path.clone())
12588 }),
12589 )
12590 .map(|(child, admitted)| (child, Some(admitted))),
12591 None => {
12592 let spawned =
12593 subc_os::child_spawn::tokio_spawn(&mut command).map(|child| (child, None));
12594 drop(command);
12597 spawned
12598 }
12599 };
12600 #[cfg(not(unix))]
12601 let spawned = subc_os::child_spawn::tokio_spawn(&mut command);
12602 let spawned = match spawned {
12603 Ok(child) => child,
12604 Err(source) => {
12605 if carried
12606 .as_ref()
12607 .and_then(|container| container.group())
12608 .is_some()
12609 {
12610 containment::terminate_blocking(&roster.containment);
12611 }
12612 #[cfg(target_os = "linux")]
12613 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12614 remove_module_cgroup(placement, &cgroup_name);
12615 }
12616 return Err(SuperviseError::Spawn {
12617 program: spec.program.clone(),
12618 source,
12619 cgroup_path,
12620 });
12621 }
12622 };
12623 #[cfg(unix)]
12624 let (mut child, mut admitted) = spawned;
12625 #[cfg(unix)]
12626 let group_target = admitted
12627 .as_ref()
12628 .map(|attempt| attempt.group_target())
12629 .unwrap_or(group_target);
12630 #[cfg(not(unix))]
12631 let mut child = spawned;
12632 if let Some(delivery) = prepared.script_delivery {
12633 delivery.start(child.id().expect("spawned child has a pid"));
12634 }
12635 #[cfg(test)]
12636 spawn_record_tests::after_create(&child, spec);
12637
12638 #[cfg(windows)]
12643 let windows_image = match image_capture.bind_tokio(&child) {
12644 Ok(image) => Arc::new(image),
12645 Err(source) => {
12646 kill_and_reap_rejected_child(&mut child);
12647 return Err(SuperviseError::Spawn {
12648 program: spec.program.clone(),
12649 source,
12650 cgroup_path: None,
12651 });
12652 }
12653 };
12654 #[cfg(windows)]
12657 let job = contain_spawned_child(&mut child, spec, carried.as_ref())?;
12658 let spawned_at_ms = unix_ms_now();
12659 #[cfg(not(windows))]
12660 let spawned_from = spec.program.clone();
12661 #[cfg(windows)]
12662 let spawned_from = windows_image.path().to_path_buf();
12663 #[cfg(not(windows))]
12664 let spawned_file_identity = spawned_file_identity(&spawned_from);
12665 #[cfg(windows)]
12666 let spawned_file_identity = Some(SpawnedFileIdentity {
12667 device: 0,
12668 inode: 0,
12669 windows_image: Some(Arc::clone(&windows_image)),
12670 });
12671 let pid = child.id().ok_or_else(|| SuperviseError::Spawn {
12672 program: spec.program.clone(),
12673 source: io::Error::other("spawned child exposed no live pid"),
12674 cgroup_path: cgroup_path.clone(),
12675 })?;
12676 #[cfg(unix)]
12677 let plain_group = (!carrying
12678 && cgroup_path.is_none()
12679 && matches!(group_target, containment::GroupTarget::OwnLeader))
12680 .then(|| plain_group::PlainGroup::from_spawn(pid).map(Arc::new))
12681 .flatten();
12682 #[cfg(windows)]
12683 let nonce_delivery = start_windows_nonce_pipe(nonce_handoff, pid, spec);
12684 #[cfg(not(windows))]
12685 let process_start_time = admitted
12686 .as_ref()
12687 .map(|admitted| admitted.birth)
12688 .or_else(|| crate::provenance::process_start_time(pid));
12689 #[cfg(windows)]
12690 let process_start_time = Some(windows_image.start_time());
12691 let process_identity = process_start_time.map(|start_time| ProcessIdentity { pid, start_time });
12692 #[cfg(all(test, target_os = "macos"))]
12693 privacy_exec_boundary_tests::before_image_sample(spec, pid);
12694 #[cfg(all(test, target_os = "linux"))]
12695 assert!(roster.admission_event_for_test(&spec.module_id, "before_image_binding", Some(pid)));
12696 #[cfg(not(windows))]
12701 let recorded_image = observe_spawned_image(pid);
12702 #[cfg(all(test, target_os = "linux"))]
12703 let recorded_image = if roster.admission_event_for_test(
12704 &spec.module_id,
12705 "after_spawn_image_sample",
12706 Some(pid),
12707 ) {
12708 recorded_image
12709 } else {
12710 None
12711 };
12712 #[cfg(target_os = "linux")]
12713 let exited_before_binding = expected_image.is_some()
12716 && recorded_image.and_then(|image| image.executable) != expected_image
12717 && subc_os::child_exit::observe(pid).ok().flatten().is_some();
12718 #[cfg(target_os = "linux")]
12719 let unavailable_initial_image = expected_image.is_some()
12720 && recorded_image.and_then(|image| image.executable).is_none()
12721 && !exited_before_binding;
12722 #[cfg(not(target_os = "linux"))]
12723 let unavailable_initial_image = false;
12724 #[cfg(target_os = "linux")]
12725 if expected_image
12726 .is_some_and(|expected| recorded_image.and_then(|image| image.executable) != Some(expected))
12727 && !exited_before_binding
12728 && !unavailable_initial_image
12729 {
12730 kill_module_cgroup(cgroup_placement, &cgroup_name);
12731 kill_and_reap_rejected_child(&mut child, group_target.clone());
12732 return Err(SuperviseError::ConfigHeld {
12733 module_id: spec.module_id.clone(),
12734 code: "program_refused".into(),
12735 detail: format!(
12736 "spawned executable {:?} does not match hashed program {:?}",
12737 recorded_image.and_then(|image| image.executable),
12738 expected_image
12739 ),
12740 });
12741 }
12742 #[cfg(not(target_os = "linux"))]
12743 let _ = expected_image;
12744 #[cfg(target_os = "macos")]
12745 let binding_ready = privacy_exec.is_none();
12746 #[cfg(target_os = "linux")]
12747 let binding_ready = !exited_before_binding;
12748 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
12749 let binding_ready = cfg!(windows);
12750 #[cfg(target_os = "macos")]
12754 let recorded_image = if privacy_exec.is_some() {
12755 None
12756 } else {
12757 recorded_image
12758 };
12759 #[cfg(target_os = "linux")]
12760 let recorded_cgroup_name = cgroup_path.as_ref().map(|_| cgroup_name.clone());
12761 #[cfg(not(target_os = "linux"))]
12762 let recorded_cgroup_name = None;
12763 #[cfg(unix)]
12764 let preadmitted = admitted
12765 .as_mut()
12766 .and_then(|admitted| admitted.leader.take());
12767 #[cfg(not(unix))]
12768 let preadmitted: Option<crate::child_roster::RosterGuard> = None;
12769 let roster_guard = if let Some(guard) = preadmitted {
12770 Ok(guard)
12771 } else {
12772 roster.admit(
12773 spec.module_id.clone(),
12774 pid,
12775 spec.protocol,
12776 process_start_time,
12777 crate::child_roster::RecordedIdentity {
12778 #[cfg(target_os = "linux")]
12779 container: cgroup_path
12780 .clone()
12781 .filter(|_| !carrying)
12782 .map(ordinary_cgroup::recorded_identity),
12783 #[cfg(not(target_os = "linux"))]
12784 container: None,
12785 #[cfg(unix)]
12786 carried: None,
12787 #[cfg(unix)]
12788 plain_group: plain_group.as_ref().map(Arc::downgrade),
12789 #[cfg(not(windows))]
12790 start_time: recorded_image.map(|image| image.start_time),
12791 #[cfg(windows)]
12792 start_time: process_start_time,
12793 #[cfg(not(windows))]
12794 executable: recorded_image
12795 .and_then(|image| image.executable)
12796 .map(crate::live_children::ExecutableIdentity::from),
12797 #[cfg(windows)]
12798 executable: Some(crate::live_children::ExecutableIdentity::from(
12799 windows_image.identity(),
12800 )),
12801 cgroup_name: recorded_cgroup_name,
12802 #[cfg(target_os = "linux")]
12803 cgroup_placement: cgroup_placement.cloned(),
12804 },
12805 )
12806 };
12807 let roster_guard = match roster_guard {
12808 Ok(guard) => guard,
12809 Err(failure) => {
12810 return failure.with_cleanup(|source| {
12811 #[cfg(windows)]
12812 if let Some(job) = &job {
12813 let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12814 }
12815 #[cfg(target_os = "linux")]
12816 kill_module_cgroup(cgroup_placement, &cgroup_name);
12817 #[cfg(unix)]
12818 let rejected_group = group_target.clone();
12819 kill_and_reap_rejected_child(
12820 &mut child,
12821 #[cfg(unix)]
12822 rejected_group,
12823 );
12824 #[cfg(target_os = "linux")]
12825 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12826 remove_module_cgroup(placement, &cgroup_name);
12827 }
12828 Err(SuperviseError::Spawn {
12829 program: spec.program.clone(),
12830 source: io::Error::other(format!(
12831 "could not durably record module child: {source}"
12832 )),
12833 cgroup_path,
12834 })
12835 });
12836 }
12837 };
12838 #[cfg(unix)]
12839 if admitted.is_some() {
12840 if let Some(image) = recorded_image {
12841 if let Err(source) = roster_guard.confirm_executable(image) {
12842 kill_and_reap_rejected_child(&mut child, group_target.clone());
12843 return Err(SuperviseError::Spawn {
12844 program: spec.program.clone(),
12845 source,
12846 cgroup_path,
12847 });
12848 }
12849 }
12850 }
12851 if roster.is_closed() {
12856 if carrying {
12857 #[cfg(unix)]
12858 let rejected_group = admitted
12859 .as_ref()
12860 .map(|admitted| admitted.rejection_target())
12861 .unwrap_or_else(|| group_target.clone());
12862 #[cfg(windows)]
12863 if let Some(job) = &job {
12864 let _ = job.lock().unwrap_or_else(|p| p.into_inner()).terminate();
12865 }
12866 kill_and_reap_rejected_child(
12867 &mut child,
12868 #[cfg(unix)]
12869 rejected_group,
12870 );
12871 #[cfg(all(test, unix))]
12872 let _ =
12873 roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
12874 drop(roster_guard);
12875 return Err(SuperviseError::Spawn {
12876 program: spec.program.clone(),
12877 source: io::Error::other(
12878 "the daemon began shutting down during carried admission; ended the container",
12879 ),
12880 cgroup_path,
12881 });
12882 }
12883 #[cfg(target_os = "linux")]
12885 kill_module_cgroup(cgroup_placement, &cgroup_name);
12886 if let Err(error) = child.start_kill() {
12887 debug!(module_id = %spec.module_id, pid, %error, "kill of a process spawned during daemon shutdown failed; it may already have exited");
12888 }
12889 #[cfg(target_os = "linux")]
12890 if let Some(placement) = cgroup_placement.filter(|_| carried.is_none()) {
12891 while matches!(child.try_wait(), Ok(None)) {
12895 std::thread::yield_now();
12896 }
12897 if matches!(
12898 subc_cgroup::kill_module(Some(placement), &cgroup_name),
12899 subc_cgroup::KillOutcome::Killed
12900 ) {
12901 if let Ok(path) = placement.module_path(&cgroup_name) {
12902 while std::fs::read_to_string(path.join("cgroup.events"))
12903 .ok()
12904 .is_some_and(|events| events.lines().any(|line| line == "populated 1"))
12905 {
12906 std::thread::yield_now();
12907 }
12908 }
12909 }
12910 remove_module_cgroup(placement, &cgroup_name);
12911 }
12912 drop(roster_guard);
12913 return Err(SuperviseError::Spawn {
12914 program: spec.program.clone(),
12915 source: io::Error::other(
12916 "the daemon began shutting down while this process was starting; ended it",
12917 ),
12918 cgroup_path,
12919 });
12920 }
12921
12922 let pumps = crate::child_output::start(
12923 &mut child,
12924 output_sink,
12925 ring,
12926 &spec.module_id,
12927 #[cfg(unix)]
12928 plain_group.is_some(),
12929 );
12930
12931 let exec = Arc::new(crate::activity::ExecOutcome::new());
12932 #[cfg(target_os = "macos")]
12933 let pending_exec = privacy_exec.is_some();
12934 #[cfg(not(target_os = "macos"))]
12935 let pending_exec = false;
12936 if !pending_exec {
12937 exec.finish(crate::activity::ExecState::CommittedExec);
12938 }
12939 #[cfg(windows)]
12940 let subtree_target = job
12941 .as_ref()
12942 .map(|job| crate::subtree_resources::Target::Job(Arc::downgrade(job)))
12943 .unwrap_or(crate::subtree_resources::Target::Unavailable("no_job"));
12944 #[cfg(target_os = "linux")]
12945 let subtree_target = cgroup_path
12946 .map(crate::subtree_resources::Target::Cgroup)
12947 .unwrap_or(crate::subtree_resources::Target::Unavailable("no_cgroup"));
12948 #[cfg(not(any(target_os = "linux", windows)))]
12949 let subtree_target = crate::subtree_resources::Target::Unavailable("unsupported_platform");
12950 let mut supervised = SupervisedChild {
12951 registration_spawn,
12952 #[cfg(any(unix, windows))]
12953 registration_channel,
12954 live_program_binding: None,
12955 registered_config_connection: None,
12956 admission_base,
12957 registration_declaration,
12958 _program_binding: binding_publication,
12959 subtree_target,
12960 child: containment::ProcessChild::plain(child, pid),
12961 exec: crate::activity::ExecOwner(exec),
12962 #[cfg(windows)]
12963 nonce_delivery,
12964 protocol: spec.protocol,
12965 #[cfg(target_os = "linux")]
12966 module_id: cgroup_name,
12967 #[cfg(target_os = "linux")]
12968 cgroup_placement: cgroup_placement.cloned(),
12969 #[cfg(target_os = "linux")]
12970 unresolved_cgroup: None,
12971 #[cfg(windows)]
12972 job,
12973 stdout_pump: pumps.stdout,
12974 stderr_pump: pumps.stderr,
12975 #[cfg(unix)]
12976 capture_stop: pumps.stop,
12977 #[cfg(unix)]
12978 late_output_lost: false,
12979 stderr_ring: Arc::clone(ring),
12980 spawned_at,
12981 config_delivery,
12982 registration_deadline: None,
12983 registration_watch: None,
12984 spawned_at_ms,
12985 spawned_from,
12986 launch_spec_digest: LaunchSpecDigest::from_spec(spec),
12987 spawned_file_identity,
12988 process_start_time,
12989 process_identity,
12990 pid,
12991 roster_guard: Some(roster_guard),
12992 #[cfg(target_os = "macos")]
12993 privacy_exec,
12994 #[cfg(target_os = "macos")]
12995 report_ready: Arc::new(OnceLock::new()),
12996 spawn_failure: None,
12997 admission_kill_sent: false,
12998 };
12999 #[cfg(unix)]
13000 {
13001 supervised.child.plain_group = plain_group;
13002 }
13003 if let Err(error) = containment::adopt(&mut supervised, spec, roster) {
13004 supervised.child.reject(
13005 #[cfg(unix)]
13006 group_target,
13007 );
13008 #[cfg(all(test, unix))]
13009 let _ = roster.admission_event_for_test(&spec.module_id, "after_rejected_child", Some(pid));
13010 return Err(error);
13011 }
13012 if let (Some(launch), Some(owner), Some(base)) = (
13013 program_launch,
13014 config_owner,
13015 supervised.admission_base.clone(),
13016 ) {
13017 supervised.live_program_binding =
13018 content_binding::LiveProgramBinding::new(launch, &supervised, owner, base);
13019 if let (Some(publication), Some(live)) = (
13020 &supervised._program_binding,
13021 &supervised.live_program_binding,
13022 ) {
13023 publication.attach(live);
13024 }
13025 }
13026 #[cfg(unix)]
13027 if let Some(admitted) = admitted.take() {
13028 admitted.disarm();
13029 }
13030 #[cfg(windows)]
13031 if let Err(error) = resume_suspended_child(pid, spec) {
13032 containment::terminate_blocking(&roster.containment);
13033 let _ = supervised.child.start_kill();
13034 return Err(error);
13035 }
13036 if binding_ready {
13037 let checked = if unavailable_initial_image {
13041 Err(crate::config_gate::GateError::new(
13042 "config_delivery_deferred",
13043 "initial process image is unavailable",
13044 ))
13045 } else {
13046 match (
13047 &supervised._program_binding,
13048 &supervised.live_program_binding,
13049 ) {
13050 (Some(binding), _) => binding.verify(),
13051 (None, Some(live)) => live.check(),
13052 _ if supervised.admission_base.is_some() => {
13053 Err(crate::config_gate::GateError::new(
13054 "config_delivery_deferred",
13055 "live program witness is unavailable",
13056 ))
13057 }
13058 _ => Ok(()),
13059 }
13060 };
13061 #[cfg(all(test, target_os = "linux"))]
13062 let checked = if roster.admission_event_for_test(
13063 &spec.module_id,
13064 "after_content_witness_check",
13065 Some(pid),
13066 ) {
13067 checked
13068 } else {
13069 Err(crate::config_gate::GateError::new(
13070 "config_delivery_deferred",
13071 "current process image is unavailable",
13072 ))
13073 };
13074 if let Err(error) = checked {
13075 if let Some(binding) = &mut supervised._program_binding {
13076 binding.reject();
13077 }
13078 if error.code == "program_refused" || supervised.try_wait().ok().flatten().is_none() {
13081 supervised.spawn_failure = Some(format!("{}: {}", error.code, error.detail));
13082 #[cfg(all(test, target_os = "linux"))]
13083 assert!(roster.admission_event_for_test(
13084 &spec.module_id,
13085 if unavailable_initial_image {
13086 "before_initial_image_kill"
13087 } else {
13088 "before_content_witness_kill"
13089 },
13090 Some(pid),
13091 ));
13092 let _ = supervised.start_admission_kill();
13093 #[cfg(all(test, target_os = "linux"))]
13094 if supervised.admission_kill_sent {
13095 assert!(roster.admission_event_for_test(
13096 &spec.module_id,
13097 "after_admission_kill_sent",
13098 Some(pid),
13099 ));
13100 }
13101 }
13102 }
13103 }
13104 if let Some(registration) = delivery_registration {
13105 registration.commit();
13106 }
13107 if let Some(spawn) = &supervised.registration_spawn {
13108 if let Some(identity) = supervised.process_identity {
13109 let _ = spawn.identity.set(identity);
13110 }
13111 if supervised.spawn_failure.is_some() {
13112 spawn.refuse();
13113 } else if binding_ready {
13114 spawn.ready();
13115 }
13116 #[cfg(any(unix, windows))]
13117 if let (Some(handle), Some(channel)) =
13118 (registration_handle, supervised.registration_channel.take())
13119 {
13120 handle.serve_registration(channel, spawn.clone(), pid, spawned_at + register_timeout);
13121 }
13122 }
13123 Ok(supervised)
13124}
13125
13126#[cfg(test)]
13127mod spawn_record_tests {
13128 use super::*;
13129
13130 thread_local! {
13131 static LAST_PID: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
13132 }
13133
13134 pub(super) fn after_create(child: &Child, _spec: &ModuleSpec) {
13135 LAST_PID.set(child.id());
13136 #[cfg(windows)]
13137 if let Some((_, address)) = _spec
13138 .env
13139 .iter()
13140 .find(|(key, _)| key == "SUBC_TEST_AFTER_CREATE")
13141 {
13142 use std::io::{Read, Write};
13143 let mut stream = std::net::TcpStream::connect(address).unwrap();
13144 stream
13145 .write_all(&child.id().unwrap().to_ne_bytes())
13146 .unwrap();
13147 let mut release = [0];
13148 stream.read_exact(&mut release).unwrap();
13149 }
13150 }
13151
13152 #[cfg(windows)]
13153 pub(super) fn assignment_failpoint(spec: &ModuleSpec) -> io::Result<()> {
13154 if spec
13155 .env
13156 .iter()
13157 .any(|(key, _)| key == "SUBC_TEST_ASSIGNMENT_FAILURE")
13158 {
13159 Err(io::Error::other("injected module job assignment failure"))
13160 } else {
13161 Ok(())
13162 }
13163 }
13164
13165 fn spec() -> ModuleSpec {
13166 ModuleSpec {
13167 script: None,
13168 module_id: "spawn-record-worker".into(),
13169 #[cfg(unix)]
13170 program: "/bin/sleep".into(),
13171 #[cfg(windows)]
13172 program: std::env::current_exe().unwrap(),
13173 #[cfg(unix)]
13174 args: vec!["60".into()],
13175 #[cfg(windows)]
13176 args: vec![
13177 "--exact".into(),
13178 "supervise::spawn_record_tests::windows_store_touch_fixture".into(),
13179 "--nocapture".into(),
13180 ],
13181 env: vec![],
13182 reserved: false,
13183 reserved_prefixes: vec![],
13184 protocol: ModuleProtocol::None,
13185 overlap: Default::default(),
13186 carry_containment: false,
13187 }
13188 }
13189
13190 #[tokio::test]
13191 async fn record_sync_failure_fails_spawn_and_reaps_child() {
13192 let home = cortexkit_test_support::ScratchDir::new("record-sync-failure");
13193 let supervisor =
13194 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
13195 .with_live_children_record(home.join("live-children.json"));
13196 crate::live_children::fail_next_file_sync();
13197 let result = supervisor.spawn(spec());
13198 let failed = result.is_err();
13199 if let Ok(module) = result {
13200 module.stop().await.unwrap();
13201 }
13202 assert!(failed, "record failure must fail spawn");
13203 let pid = LAST_PID.get().expect("the real OS child was created");
13204 assert!(
13205 subc_os::Process::open(pid).unwrap().is_none(),
13206 "child {pid} survived rejected admission or was not reaped"
13207 );
13208 }
13209
13210 #[cfg(target_os = "macos")]
13211 #[test]
13212 #[ignore = "manual on-device latency measurement"]
13213 fn durable_record_write_latency_50() {
13214 let home = cortexkit_test_support::ScratchDir::new("record-latency");
13215 let path = home.join("live-children.json");
13216 let children = vec![crate::live_children::LiveChild {
13217 module_id: "latency-worker".into(),
13218 pid: std::process::id(),
13219 protocol: ModuleProtocol::None,
13220 start_time: Some(1),
13221 executable: None,
13222 cgroup_name: None,
13223 container: None,
13224 }];
13225 let mut samples = Vec::new();
13226 for _ in 0..50 {
13227 let start = std::time::Instant::now();
13228 crate::live_children::write_record(&path, &children).unwrap();
13229 samples.push(start.elapsed());
13230 }
13231 samples.sort();
13232 eprintln!(
13233 "durable_record_write_latency_50: n=50 median={:?} p95={:?}",
13234 (samples[24] + samples[25]) / 2,
13235 samples[47]
13236 );
13237 }
13238
13239 #[cfg(windows)]
13240 #[test]
13241 fn windows_store_touch_fixture() {
13242 if let Some(path) = std::env::var_os("SUBC_TEST_STORE_TOUCH") {
13243 std::fs::write(path, b"module ran").unwrap();
13244 }
13245 }
13246
13247 #[cfg(windows)]
13248 #[tokio::test]
13249 async fn windows_daemon_fixture() {
13250 let Ok(address) = std::env::var("SUBC_TEST_DAEMON_BARRIER") else {
13251 return;
13252 };
13253 let mut spec = spec();
13254 spec.env.push(("SUBC_TEST_AFTER_CREATE".into(), address));
13255 let supervisor =
13256 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13257 let _module = supervisor.spawn(spec).unwrap();
13258 }
13259
13260 #[cfg(windows)]
13261 #[test]
13262 fn windows_daemon_death_before_module_job_assignment_leaves_no_child() {
13263 use std::io::Read;
13264 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
13265 let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13268 command
13269 .args([
13270 "--exact",
13271 "supervise::spawn_record_tests::windows_daemon_fixture",
13272 "--nocapture",
13273 ])
13274 .env(
13275 "SUBC_TEST_DAEMON_BARRIER",
13276 listener.local_addr().unwrap().to_string(),
13277 );
13278 let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13279 listener.set_nonblocking(true).unwrap();
13280 let deadline = std::time::Instant::now() + Duration::from_secs(30);
13281 let mut stream = loop {
13282 if let Ok((stream, _)) = listener.accept() {
13283 break stream;
13284 }
13285 assert!(
13286 daemon.child.try_wait().unwrap().is_none(),
13287 "daemon failed before rendezvous"
13288 );
13289 assert!(
13290 std::time::Instant::now() < deadline,
13291 "daemon did not reach CreateProcess failpoint"
13292 );
13293 std::thread::yield_now();
13294 };
13295 stream
13296 .set_read_timeout(Some(Duration::from_secs(30)))
13297 .unwrap();
13298 let mut pid = [0; 4];
13299 stream.read_exact(&mut pid).unwrap();
13300 let pid = u32::from_ne_bytes(pid);
13301 assert!(subc_jobobject::process_exists(pid));
13302 daemon.child.kill().unwrap();
13305 daemon.child.wait().unwrap();
13306 let exited = subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10));
13307 if !exited {
13308 daemon.job.terminate().unwrap();
13309 }
13310 assert!(exited, "suspended child {pid} outlived hard-killed daemon");
13311 }
13312
13313 #[cfg(windows)]
13314 #[tokio::test]
13315 async fn windows_containment_failure_never_resumes() {
13316 let home = cortexkit_test_support::ScratchDir::new("assignment-refusal");
13317 let sentinel = home.join("store-touched");
13318 let mut spec = spec();
13319 spec.env
13320 .push(("SUBC_TEST_ASSIGNMENT_FAILURE".into(), "1".into()));
13321 spec.env.push((
13322 "SUBC_TEST_STORE_TOUCH".into(),
13323 sentinel.display().to_string(),
13324 ));
13325 let supervisor =
13326 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13327 let result = supervisor.spawn(spec);
13328 if let Ok(module) = result {
13331 let _ = tokio::time::timeout(Duration::from_secs(10), async {
13332 while !sentinel.exists() && module.state().unwrap() == ModuleState::Running {
13333 tokio::task::yield_now().await;
13334 }
13335 })
13336 .await;
13337 let _ = module.stop().await;
13338 panic!(
13339 "assignment failure resumed a module; store touched={}",
13340 sentinel.exists()
13341 );
13342 }
13343 assert!(
13344 !sentinel.exists(),
13345 "refused module executed store-touch sentinel"
13346 );
13347 assert!(!subc_jobobject::process_exists(LAST_PID.get().unwrap()));
13348 }
13349
13350 #[cfg(windows)]
13351 #[tokio::test]
13352 async fn windows_nested_daemon_fixture() {
13353 let Some(sentinel) = std::env::var_os("SUBC_TEST_NESTED_STORE") else {
13354 return;
13355 };
13356 let mut spec = spec();
13357 spec.env.push((
13358 "SUBC_TEST_STORE_TOUCH".into(),
13359 sentinel.to_str().unwrap().into(),
13360 ));
13361 let supervisor =
13362 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
13363 let module = supervisor
13364 .spawn(spec)
13365 .expect("per-module job must nest below daemon and host jobs");
13366 tokio::time::timeout(Duration::from_secs(10), async {
13367 while !PathBuf::from(&sentinel).exists() {
13368 tokio::task::yield_now().await;
13369 }
13370 })
13371 .await
13372 .unwrap();
13373 module.stop().await.unwrap();
13374 }
13375
13376 #[cfg(windows)]
13377 #[test]
13378 fn windows_module_job_nests_under_host_job() {
13379 let home = cortexkit_test_support::ScratchDir::new("nested-jobs");
13380 let sentinel = home.join("nested-store-touched");
13381 let mut command = std::process::Command::new(std::env::current_exe().unwrap());
13382 command
13383 .args([
13384 "--exact",
13385 "supervise::spawn_record_tests::windows_nested_daemon_fixture",
13386 "--nocapture",
13387 ])
13388 .env("SUBC_TEST_NESTED_STORE", &sentinel);
13389 let mut daemon = subc_jobobject::spawn_contained(&mut command).unwrap();
13390 assert!(daemon.child.wait().unwrap().success());
13391 assert!(sentinel.exists(), "nested protocol:none module never ran");
13392 }
13393}
13394
13395#[cfg(target_os = "linux")]
13396pub(crate) fn kill_module_cgroup(placement: Option<&subc_cgroup::Placement>, module_id: &str) {
13397 use subc_cgroup::KillOutcome;
13398 match subc_cgroup::kill_module(placement, module_id) {
13399 KillOutcome::Killed => {}
13400 KillOutcome::NotPlaced | KillOutcome::Unsupported => {
13401 debug!(
13402 module_id,
13403 "cgroup tree kill unavailable; using direct-child kill"
13404 );
13405 }
13406 KillOutcome::IoError { path, error } => {
13407 warn!(module_id, path = %path.display(), %error, "cgroup tree kill failed; using direct-child kill");
13408 }
13409 }
13410}
13411
13412#[cfg(windows)]
13420fn contain_spawned_child(
13421 child: &mut Child,
13422 spec: &ModuleSpec,
13423 carried: Option<&Arc<containment::CarriedContainment>>,
13424) -> Result<Option<Arc<Mutex<subc_jobobject::JobObject>>>, SuperviseError> {
13425 let assignment = || {
13426 let job = match carried {
13427 Some(container) => container.job(),
13428 None => Arc::new(Mutex::new(subc_jobobject::JobObject::new()?)),
13429 };
13430 #[cfg(test)]
13431 spawn_record_tests::assignment_failpoint(spec)?;
13432 job.lock()
13433 .unwrap_or_else(|p| p.into_inner())
13434 .assign(child)?;
13435 Ok::<_, io::Error>(job)
13436 };
13437 match assignment() {
13438 Ok(job) => Ok(Some(job)),
13439 Err(source) => {
13440 kill_and_reap_rejected_child(child);
13441 Err(SuperviseError::Spawn {
13442 program: spec.program.clone(),
13443 source: io::Error::other(format!(
13444 "Windows module job containment failed: {source}"
13445 )),
13446 cgroup_path: None,
13447 })
13448 }
13449 }
13450}
13451
13452fn kill_and_reap_rejected_child(child: &mut Child, #[cfg(unix)] group: containment::GroupTarget) {
13455 #[cfg(unix)]
13456 group.signal_rejected(child);
13457 let _ = child.start_kill();
13458 while matches!(child.try_wait(), Ok(None)) {
13459 std::thread::yield_now();
13460 }
13461}
13462
13463#[cfg(windows)]
13468fn resume_suspended_child(pid: u32, spec: &ModuleSpec) -> Result<(), SuperviseError> {
13469 if let Err(source) = subc_jobobject::resume_main_thread(pid) {
13470 let _ = subc_os::child_spawn::status(
13474 std::process::Command::new("taskkill.exe")
13475 .args(["/PID", &pid.to_string(), "/T", "/F"])
13476 .stdin(Stdio::null())
13477 .stdout(Stdio::null())
13478 .stderr(Stdio::null()),
13479 );
13480 return Err(SuperviseError::Spawn {
13481 program: spec.program.clone(),
13482 source,
13483 cgroup_path: None,
13484 });
13485 }
13486 Ok(())
13487}
13488
13489#[cfg(target_os = "linux")]
13490fn remove_module_cgroup(placement: &subc_cgroup::Placement, module_id: &str) {
13491 match placement.remove_module(module_id) {
13492 Ok(()) => debug!(module_id, "removed module cgroup after process exit"),
13493 Err(error) => warn!(
13494 module_id,
13495 error = %error,
13496 "could not remove module cgroup after process exit; continuing teardown"
13497 ),
13498 }
13499}
13500
13501#[cfg(target_os = "linux")]
13502fn apply_cgroup_placement(
13503 command: &mut Command,
13504 spec: &ModuleSpec,
13505 path: &std::path::Path,
13506) -> Result<(), SuperviseError> {
13507 subc_cgroup::apply(command, path).map_err(|source| SuperviseError::Cgroup {
13508 module_id: spec.module_id.clone(),
13509 source,
13510 })
13511}
13512
13513fn capture_retention(spec: &ModuleSpec) -> Retention {
13514 let defaults = Retention::default();
13515 let value = |name: &str| {
13516 spec.env
13517 .iter()
13518 .rev()
13519 .find_map(|(key, value)| (key == name).then_some(value.as_str()))
13520 };
13521 Retention {
13522 max_file_mb: value(CAPTURE_MAX_FILE_MB_ENV)
13523 .and_then(|value| value.parse().ok())
13524 .unwrap_or(defaults.max_file_mb),
13525 keep: value(CAPTURE_KEEP_ENV)
13526 .and_then(|value| value.parse().ok())
13527 .unwrap_or(defaults.keep),
13528 max_age_days: value(CAPTURE_MAX_AGE_DAYS_ENV)
13529 .and_then(|value| value.parse().ok())
13530 .unwrap_or(defaults.max_age_days),
13531 }
13532}
13533
13534fn generate_launch_nonce() -> Result<String, SuperviseError> {
13537 let mut bytes = [0u8; 32];
13538 getrandom::getrandom(&mut bytes).map_err(|source| SuperviseError::LaunchNonce {
13539 reason: source.to_string(),
13540 })?;
13541 let mut hex = String::with_capacity(64);
13542 for b in bytes {
13543 use std::fmt::Write;
13544 let _ = write!(hex, "{b:02x}");
13545 }
13546 Ok(hex)
13547}
13548
13549fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
13552 if a.len() != b.len() {
13553 return false;
13554 }
13555 let mut diff = 0u8;
13556 for (x, y) in a.iter().zip(b.iter()) {
13557 diff |= x ^ y;
13558 }
13559 diff == 0
13560}
13561
13562#[cfg(not(windows))]
13566fn observe_spawned_image(pid: u32) -> Option<subc_os::Observation> {
13567 let process = subc_os::Process::open(pid).ok().flatten()?;
13568 #[cfg(target_os = "linux")]
13569 return sample_after_linux_exec(
13570 || {
13571 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
13572 let committed = linux_exec_committed(&stat);
13573 #[cfg(test)]
13574 spawn_image_tests::report_exec_state(committed);
13575 committed
13576 },
13577 || process.observe(),
13578 );
13579 #[cfg(not(target_os = "linux"))]
13580 process.observe()
13581}
13582
13583#[cfg(target_os = "linux")]
13587fn linux_exec_committed(stat: &str) -> Option<bool> {
13588 const PF_FORKNOEXEC: u64 = 0x40;
13589 let flags = stat.rsplit_once(')')?.1.split_whitespace().nth(6)?;
13590 Some(flags.parse::<u64>().ok()? & PF_FORKNOEXEC == 0)
13591}
13592
13593#[cfg(target_os = "linux")]
13594fn sample_after_linux_exec(
13595 mut exec_committed: impl FnMut() -> Option<bool>,
13596 observe: impl FnOnce() -> Option<subc_os::Observation>,
13597) -> Option<subc_os::Observation> {
13598 let deadline = std::time::Instant::now() + Duration::from_secs(1);
13599 while !exec_committed()? {
13600 if std::time::Instant::now() >= deadline {
13604 return None;
13605 }
13606 std::thread::sleep(Duration::from_micros(50));
13607 }
13608 observe()
13609}
13610
13611#[cfg(all(test, target_os = "linux"))]
13612mod spawn_image_tests {
13613 use super::*;
13614 use std::cell::{Cell, RefCell};
13615
13616 enum ExecEvent {
13617 Uncommitted,
13618 Image(Option<subc_os::Observation>),
13619 }
13620
13621 thread_local! {
13622 static EXEC_EVENTS: RefCell<Option<std::sync::mpsc::Sender<ExecEvent>>> = const { RefCell::new(None) };
13623 }
13624
13625 pub(super) fn report_exec_state(committed: Option<bool>) {
13626 if committed == Some(false) {
13627 EXEC_EVENTS.with(|events| {
13628 if let Some(events) = events.borrow_mut().take() {
13629 let _ = events.send(ExecEvent::Uncommitted);
13630 }
13631 });
13632 }
13633 }
13634
13635 #[test]
13636 fn linux_spawn_observation_waits_for_a_paused_fork_to_exec() {
13637 use std::io::{Read, Write};
13638 use std::os::fd::AsRawFd;
13639
13640 let descriptor = std::fs::File::open("/dev/null").unwrap();
13641 let mut command = std::process::Command::new("/bin/sleep");
13642 command.arg("30");
13643 let (mut ready, mut release) =
13644 subc_os::fork_exec_test::pause_before_exec(&mut command, descriptor.as_raw_fd())
13645 .unwrap();
13646 let spawn = std::thread::spawn(move || command.spawn());
13647 let mut message = [0u8; 8];
13648 ready.read_exact(&mut message).unwrap();
13649 let pid = i32::from_ne_bytes(message[..4].try_into().unwrap()) as u32;
13650 let before = std::fs::read_to_string(format!("/proc/{pid}/stat"));
13651 let inherited = subc_os::Process::open(pid).unwrap().unwrap().observe();
13652 let (events, received) = std::sync::mpsc::channel();
13653 let observer = std::thread::spawn(move || {
13654 EXEC_EVENTS.with(|slot| *slot.borrow_mut() = Some(events.clone()));
13655 let image = observe_spawned_image(pid);
13656 let _ = events.send(ExecEvent::Image(image));
13657 });
13658 let first = received.recv_timeout(Duration::from_secs(5));
13662 release.write_all(&[1]).unwrap();
13663 let mut child = spawn.join().unwrap().unwrap();
13664 let after = match first {
13665 Ok(ExecEvent::Uncommitted) => match received.recv_timeout(Duration::from_secs(5)) {
13666 Ok(ExecEvent::Image(image)) => image,
13667 _ => None,
13668 },
13669 Ok(ExecEvent::Image(image)) => image,
13670 Err(_) => None,
13671 };
13672 observer.join().unwrap();
13673 child.kill().unwrap();
13674 child.wait().unwrap();
13675
13676 assert_eq!(linux_exec_committed(&before.unwrap()), Some(false));
13677 assert_eq!(
13678 inherited.unwrap().executable,
13679 subc_os::file_identity(&std::env::current_exe().unwrap())
13680 );
13681 assert_eq!(
13682 after.unwrap().executable,
13683 subc_os::file_identity(std::path::Path::new("/bin/sleep"))
13684 );
13685 }
13686
13687 #[test]
13688 fn spawned_image_is_not_sampled_until_linux_exec_commits() {
13689 let committed = Cell::new(false);
13690 let inherited = subc_os::Observation {
13691 start_time: 23,
13692 executable: Some(subc_os::FileIdentity {
13693 device: 29,
13694 inode: 31,
13695 }),
13696 };
13697 let module = subc_os::Observation {
13698 start_time: 23,
13699 executable: Some(subc_os::FileIdentity {
13700 device: 29,
13701 inode: 37,
13702 }),
13703 };
13704 let polls = Cell::new(0);
13705 let image = sample_after_linux_exec(
13706 || {
13707 polls.set(polls.get() + 1);
13708 committed.set(polls.get() == 2);
13711 Some(committed.get())
13712 },
13713 || Some(if committed.get() { module } else { inherited }),
13714 );
13715 assert_eq!(image, Some(module));
13716 assert_eq!(polls.get(), 2);
13717 }
13718
13719 #[test]
13720 fn linux_exec_flag_is_read_from_flags_after_the_last_parenthesis() {
13721 assert_eq!(
13722 linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194368"),
13723 Some(false)
13724 );
13725 assert_eq!(
13726 linux_exec_committed("17 (a ) b) R 1 2 3 4 5 4194304"),
13727 Some(true)
13728 );
13729 assert_eq!(linux_exec_committed("17 (a) R 1 2 3 4 5 invalid"), None);
13730 assert_eq!(linux_exec_committed("17 (a) R"), None);
13731 }
13732
13733 #[test]
13734 fn unreadable_exec_state_never_samples_an_inherited_image() {
13735 assert_eq!(
13736 sample_after_linux_exec(
13737 || None,
13738 || panic!("must not sample before exec confirmation")
13739 ),
13740 None
13741 );
13742 }
13743
13744 #[test]
13745 fn uncommitted_exec_times_out_without_sampling_an_inherited_image() {
13746 assert_eq!(
13747 sample_after_linux_exec(
13748 || Some(false),
13749 || panic!("must not sample after an exec timeout")
13750 ),
13751 None
13752 );
13753 }
13754}
13755
13756#[cfg(windows)]
13759pub(crate) fn windows_spawn_capture(spec: &ModuleSpec) -> io::Result<subc_os::ExecutableCapture> {
13760 if let Err(error) = require_program_search_path(spec) {
13761 return Err(match error {
13762 SuperviseError::Spawn { source, .. } => source,
13763 error => io::Error::other(error),
13764 });
13765 }
13766 let mut program = spec.program.clone();
13767 if program.is_absolute() || program.components().count() > 1 {
13768 match subc_os::ExecutableCapture::open(&program) {
13771 Ok(capture) => return Ok(capture),
13772 Err(error)
13773 if error.kind() == io::ErrorKind::NotFound && program.extension().is_none() => {}
13774 Err(error) => return Err(error),
13775 }
13776 program.set_extension("exe");
13777 return subc_os::ExecutableCapture::open(&program);
13778 }
13779 if program.extension().is_none() {
13780 program.set_extension("exe");
13781 }
13782 let custom_path = spec
13783 .env
13784 .iter()
13785 .rev()
13786 .find(|(key, _)| key.eq_ignore_ascii_case("PATH"));
13787 let mut directories = Vec::new();
13788 if let Some(parent) = std::env::current_exe()?.parent() {
13791 directories.push(parent.to_path_buf());
13792 }
13793 directories.push(std::env::current_dir()?);
13794 if let Some(windows) = std::env::var_os("SystemRoot") {
13795 let windows = PathBuf::from(windows);
13796 directories.push(windows.join("System32"));
13797 directories.push(windows.clone());
13798 }
13799 let path = custom_path
13800 .map(|(_, value)| std::ffi::OsString::from(value))
13801 .or_else(|| std::env::var_os("PATH"));
13802 if let Some(path) = path {
13803 directories.extend(std::env::split_paths(&path));
13804 }
13805 for directory in directories {
13806 match subc_os::ExecutableCapture::open(&directory.join(&program)) {
13807 Ok(capture) => return Ok(capture),
13808 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
13809 Err(error) => return Err(error),
13810 }
13811 }
13812 Err(io::Error::new(
13813 io::ErrorKind::NotFound,
13814 "resolved executable not found",
13815 ))
13816}
13817
13818#[cfg(test)]
13819fn spawn_and_mark_running(
13820 spec: &ModuleSpec,
13821 runtime: &SupervisorRuntimeConfig,
13822 snapshot: &SharedSnapshot,
13823) -> Result<SupervisedChild, SuperviseError> {
13824 let activity_spawn = runtime.begin_activity_spawn(&spec.module_id);
13825 let registration_watch = watch_registration(&runtime.registry, spec);
13826 #[cfg(unix)]
13827 let joining_group = containment::current(&runtime.child_roster.containment)
13828 .is_some_and(|container| container.group().is_some());
13829 let spawn = || {
13830 spawn_child(
13831 spec,
13832 runtime.connection_file_path.as_deref(),
13833 runtime.supervisor_handle.as_ref(),
13834 &runtime.stderr_ring,
13835 runtime.capture_logs_dir.as_deref(),
13836 &runtime.child_roster,
13837 runtime.spawn_delivery(),
13838 #[cfg(target_os = "linux")]
13839 runtime.cgroup_placement.as_ref(),
13840 runtime.register_timeout,
13841 )
13842 };
13843 let result = spawn();
13844 #[cfg(unix)]
13845 let result = match result {
13846 Err(error)
13847 if joining_group
13848 && !is_launch_deferral(&error)
13849 && !runtime.child_roster.is_closed()
13850 && lock_snapshot(snapshot).is_ok_and(|state| state.enabled)
13851 && runtime
13852 .child_roster
13853 .previous_instance(&spec.module_id)
13854 .is_none() =>
13855 {
13856 warn!(module_id = %spec.module_id, %error, "carried process-group spawn failed; trying one fresh container");
13860 spawn()
13861 }
13862 other => other,
13863 };
13864 let child = result?;
13865 let mut child = child;
13866 arm_registration_deadline(&mut child, runtime.register_timeout, registration_watch);
13867 if let Err(error) = set_running(snapshot, &child, &spec.module_id, &runtime.spawn_events) {
13868 containment::terminate_blocking(&runtime.child_roster.containment);
13869 return Err(error);
13870 }
13871 if let Some(spawn) = activity_spawn {
13872 spawn.complete(snapshot);
13873 }
13874 Ok(child)
13875}
13876
13877struct RegistrationWatch {
13878 changes: watch::Receiver<u64>,
13879 baseline: u64,
13880}
13881
13882fn watch_registration(registry: &Registry, spec: &ModuleSpec) -> Option<RegistrationWatch> {
13886 if spec.protocol != ModuleProtocol::Subc {
13887 return None;
13888 }
13889 let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
13890 let baseline = *changes.borrow();
13891 Some(RegistrationWatch { changes, baseline })
13892}
13893
13894fn arm_registration_deadline(
13895 child: &mut SupervisedChild,
13896 budget: Duration,
13897 registration_watch: Option<RegistrationWatch>,
13898) {
13899 child.registration_watch = registration_watch;
13900 child.registration_deadline = (child.protocol == ModuleProtocol::Subc
13901 && child.awaiting_registration())
13902 .then_some(child.spawned_at + budget);
13903}
13904
13905enum RegistrationWaitOutcome {
13906 Registered,
13907 Exited(ExitReport),
13908 TimedOut,
13909}
13910
13911struct ReloadRegistrationFailure {
13912 cleanup_detail: Option<String>,
13913 exit_report: ExitReport,
13914 reason: String,
13915}
13916
13917#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13918enum BusyGaugeObservation {
13919 Quiescent,
13920 Busy,
13921 Omitted,
13922}
13923
13924#[derive(Debug, Clone, PartialEq, Eq)]
13926enum GaugeVerdict {
13927 Zero,
13929 NonZero(u64),
13931 NotACount(String),
13935 Missing,
13937 ProbeFailed(&'static str),
13940}
13941
13942impl GaugeVerdict {
13943 fn reads_quiet(&self) -> bool {
13944 matches!(self, Self::Zero)
13945 }
13946}
13947
13948impl fmt::Display for GaugeVerdict {
13949 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13950 match self {
13951 Self::Zero => f.write_str("zero"),
13952 Self::NonZero(value) => write!(f, "non_zero({value})"),
13953 Self::NotACount(value) => write!(f, "not_a_count({value})"),
13954 Self::Missing => f.write_str("missing_from_health_body"),
13955 Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
13956 }
13957 }
13958}
13959
13960const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
13963
13964fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
13966 let metrics = metrics.and_then(Value::as_object);
13967 gauges
13968 .iter()
13969 .map(
13970 |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
13971 None => GaugeVerdict::Missing,
13972 Some(value) => match value.as_u64() {
13973 Some(0) => GaugeVerdict::Zero,
13974 Some(count) => GaugeVerdict::NonZero(count),
13975 None => {
13976 let mut text = value.to_string();
13977 if text.len() > GAUGE_VALUE_TEXT_LIMIT {
13978 let mut end = GAUGE_VALUE_TEXT_LIMIT;
13979 while !text.is_char_boundary(end) {
13980 end -= 1;
13981 }
13982 text.truncate(end);
13983 text.push_str("...");
13984 }
13985 GaugeVerdict::NotACount(text)
13986 }
13987 },
13988 },
13989 )
13990 .collect()
13991}
13992
13993fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
13996 if verdicts
13997 .iter()
13998 .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
13999 {
14000 BusyGaugeObservation::Omitted
14001 } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
14002 BusyGaugeObservation::Quiescent
14003 } else {
14004 BusyGaugeObservation::Busy
14005 }
14006}
14007
14008#[derive(Debug, Clone, Default, PartialEq, Eq)]
14013struct GaugeTrace {
14014 latest: Option<(GaugeVerdict, Duration)>,
14015 last_value: Option<(GaugeVerdict, Duration)>,
14016}
14017
14018#[derive(Debug, Clone, Default, PartialEq, Eq)]
14024struct DrainGaugeTrace {
14025 probes: u32,
14027 gauges: Vec<(String, GaugeTrace)>,
14029}
14030
14031impl DrainGaugeTrace {
14032 fn new(gauges: &[String]) -> Self {
14033 Self {
14034 probes: 0,
14035 gauges: gauges
14036 .iter()
14037 .map(|gauge| (gauge.clone(), GaugeTrace::default()))
14038 .collect(),
14039 }
14040 }
14041
14042 fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
14044 self.probes = self.probes.saturating_add(1);
14045 for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
14046 trace.latest = Some((verdict.clone(), at));
14047 if matches!(
14048 verdict,
14049 GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
14050 ) {
14051 trace.last_value = Some((verdict.clone(), at));
14052 }
14053 }
14054 }
14055}
14056
14057impl fmt::Display for DrainGaugeTrace {
14062 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14063 if self.gauges.is_empty() {
14064 return f.write_str("none declared");
14065 }
14066 for (index, (name, trace)) in self.gauges.iter().enumerate() {
14067 if index > 0 {
14068 f.write_str(" | ")?;
14069 }
14070 write!(f, "{name}: ")?;
14071 match &trace.latest {
14072 Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
14073 None => f.write_str("never probed")?,
14074 }
14075 match &trace.last_value {
14076 Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
14077 None => f.write_str("; no value ever read")?,
14078 }
14079 }
14080 Ok(())
14081 }
14082}
14083
14084pub(crate) fn declared_busy_gauges(
14085 registry: &Registry,
14086 module_id: &str,
14087) -> Result<Vec<String>, SuperviseError> {
14088 busy_gauges_of(
14089 registry
14090 .get_module(module_id)
14091 .map_err(SuperviseError::Registry)?,
14092 )
14093}
14094
14095fn declared_busy_gauges_for_connection(
14099 registry: &Registry,
14100 connection_id: ConnectionId,
14101) -> Result<Vec<String>, SuperviseError> {
14102 busy_gauges_of(
14103 registry
14104 .get_module_by_connection(connection_id)
14105 .map_err(SuperviseError::Registry)?,
14106 )
14107}
14108
14109fn busy_gauges_of(
14110 registration: Option<crate::registry::ModuleRegistration>,
14111) -> Result<Vec<String>, SuperviseError> {
14112 let Some(registration) = registration else {
14113 return Ok(Vec::new());
14114 };
14115 let Some(self_signals) = registration.manifest.self_signals else {
14116 return Ok(Vec::new());
14117 };
14118
14119 let mut gauges = Vec::new();
14120 for declaration in self_signals {
14121 if declaration.kind != SelfSignalKind::Busy {
14122 continue;
14123 }
14124 match declaration.anchored_to {
14125 SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
14126 gauges.extend(declared)
14127 }
14128 _ => {
14129 gauges.push(String::new());
14132 }
14133 }
14134 }
14135 Ok(gauges)
14136}
14137
14138#[allow(clippy::too_many_arguments)]
14147async fn wait_for_forwarding_quiescence(
14148 forwarding: &ForwardingTable,
14149 module_id: &str,
14150 runtime: &SupervisorRuntimeConfig,
14151 endpoint: crate::ModuleEndpointId,
14152 deadline: Instant,
14153 busy_gauges: &[String],
14154 scope: DrainScope,
14155 trace: &mut DrainGaugeTrace,
14156) -> Result<bool, SuperviseError> {
14157 let wait_started = Instant::now();
14158 let mut gauges_quiescent = busy_gauges.is_empty();
14159 let mut next_probe_at = wait_started;
14160 let mut omission_reported = false;
14161
14162 loop {
14163 let now = Instant::now();
14164 if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
14165 let report = match scope {
14166 DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
14167 DrainScope::Endpoint(endpoint) => {
14168 probe_endpoint_health(endpoint, runtime, Some(deadline)).await
14169 }
14170 };
14171 let verdicts = match &report {
14172 Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
14173 Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
14174 };
14175 trace.record(&verdicts, wait_started.elapsed());
14176 gauges_quiescent = match report {
14177 Ok(_) => match busy_gauge_observation(&verdicts) {
14178 BusyGaugeObservation::Quiescent => true,
14179 BusyGaugeObservation::Busy => false,
14180 BusyGaugeObservation::Omitted => {
14181 if !omission_reported {
14184 forwarding
14185 .counters()
14186 .increment_drains_with_undeclared_gauge();
14187 let missing = busy_gauges
14188 .iter()
14189 .zip(&verdicts)
14190 .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
14191 .map(|(gauge, _)| gauge.as_str())
14192 .collect::<Vec<_>>()
14193 .join(",");
14194 warn!(
14195 module_id,
14196 missing_gauges = %missing,
14197 "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
14198 );
14199 omission_reported = true;
14200 }
14201 false
14202 }
14203 },
14204 Err(err) => {
14205 warn!(
14206 module_id,
14207 error = %err,
14208 "drain health.check did not produce declared busy gauges; treating module as busy"
14209 );
14210 false
14211 }
14212 };
14213 next_probe_at = Instant::now() + drain_busy_reprobe_interval();
14216 }
14217
14218 let in_flight = forwarding
14219 .endpoint_in_flight_count(endpoint)
14220 .map_err(SuperviseError::Forwarding)?;
14221 if in_flight == 0 && gauges_quiescent {
14222 return Ok(true);
14223 }
14224
14225 let now = Instant::now();
14226 if now >= deadline {
14227 return Ok(false);
14228 }
14229 let mut wait = deadline
14230 .saturating_duration_since(now)
14231 .min(REGISTRY_RELEASE_POLL);
14232 if !busy_gauges.is_empty() {
14233 wait = wait.min(next_probe_at.saturating_duration_since(now));
14234 }
14235 sleep(wait).await;
14236 }
14237}
14238
14239fn drain_busy_reprobe_interval() -> Duration {
14243 DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
14244}
14245
14246fn warn_drain_timed_out(
14261 module_id: &str,
14262 drain_timeout: Duration,
14263 reason: RouteCloseReason,
14264 holdouts: &crate::forwarding::DrainHoldouts,
14265 gauges: &DrainGaugeTrace,
14266) {
14267 warn!(
14268 module_id = %module_id,
14269 waited = ?drain_timeout,
14270 ?reason,
14271 held_requests = holdouts.requests,
14272 held_routes = holdouts.routes,
14273 total_routes = holdouts.total_routes,
14274 top_connections = ?holdouts.top_connections,
14275 held = %holdouts
14278 .held
14279 .iter()
14280 .map(|(channel, corr)| format!("{channel}:{corr}"))
14281 .collect::<Vec<_>>()
14282 .join(","),
14283 gauge_probes = gauges.probes,
14284 busy_gauges = %gauges,
14285 "route drain timed out before request quiescence; forcing teardown"
14286 );
14287}
14288
14289fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
14297 match wait_result {
14298 Ok(drained) => *drained,
14299 Err(_) => false,
14300 }
14301}
14302
14303fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
14304 for released in released_routes {
14305 let frame = match Frame::build_with_version(
14306 released.negotiated_ver,
14307 FrameType::Goodbye,
14308 control_flags(),
14309 released.channel,
14310 released.epoch,
14311 0,
14312 Vec::new(),
14313 ) {
14314 Ok(frame) => frame,
14315 Err(err) => {
14316 warn!(
14317 route_channel = released.channel,
14318 error = %err,
14319 "failed to build supervisor drain route GOODBYE frame"
14320 );
14321 continue;
14322 }
14323 };
14324 if !released.close_on_delivery_failure() {
14325 crate::forwarding::send_module_route_goodbye(
14326 &forwarding.counters(),
14327 &released.sink,
14328 frame,
14329 released.module_id.as_deref(),
14330 "supervisor drain",
14331 );
14332 continue;
14333 }
14334 if let Err(err) = released.sink.try_send(frame) {
14335 warn!(
14336 target_connection_id = released.connection_id.get(),
14337 route_channel = released.channel,
14338 error = %err,
14339 "supervisor drain route GOODBYE was not delivered to client; closing target connection"
14340 );
14341 let _ = forwarding.escalate_client_delivery_failure(
14342 released.connection_id,
14343 released.channel,
14344 released.epoch,
14345 CloseReason::new(
14346 "route_goodbye_delivery_failed",
14347 format!(
14348 "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
14349 released.channel
14350 ),
14351 ),
14352 crate::forwarding::UndeliveredFrame {
14353 module_id: released.module_id.as_deref(),
14354 sink: &released.sink,
14355 },
14356 );
14357 }
14358 }
14359}
14360
14361async fn send_module_draining(
14362 module_id: &str,
14363 reason: RouteCloseReason,
14364 deadline_ms: u64,
14365 target: &ModuleDrainTarget,
14366 _wait_for_flush: bool,
14367) -> bool {
14368 let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
14369 reason,
14370 deadline_ms,
14371 }) {
14372 Ok(body) => body,
14373 Err(err) => {
14374 warn!(
14375 module_id,
14376 error = %err,
14377 "failed to encode module draining command"
14378 );
14379 return false;
14380 }
14381 };
14382 let frame = match Frame::build_with_version(
14383 target.negotiated_ver,
14384 FrameType::Push,
14385 control_flags(),
14386 0,
14387 0,
14388 0,
14389 body,
14390 ) {
14391 Ok(frame) => frame,
14392 Err(err) => {
14393 warn!(
14394 module_id,
14395 error = %err,
14396 "failed to build module draining command frame"
14397 );
14398 return false;
14399 }
14400 };
14401 #[cfg(unix)]
14402 if _wait_for_flush {
14403 return target.sink.send_flushed(frame).await.is_ok();
14404 }
14405 if let Err(err) = target.sink.try_send(frame) {
14406 warn!(
14407 module_id,
14408 target_connection_id = target.endpoint.connection_id.get(),
14409 error = %err,
14410 "module draining command was not delivered to peer"
14411 );
14412 return false;
14413 }
14414 true
14415}
14416
14417fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
14419 match Frame::build_with_version(
14420 negotiated_ver,
14421 FrameType::Goodbye,
14422 control_flags(),
14423 0,
14424 0,
14425 0,
14426 Vec::new(),
14427 ) {
14428 Ok(frame) => Some(frame),
14429 Err(err) => {
14430 warn!(
14431 module_id,
14432 error = %err,
14433 "failed to build module GOODBYE frame"
14434 );
14435 None
14436 }
14437 }
14438}
14439
14440#[cfg(unix)]
14454async fn send_module_goodbyes_for_daemon_shutdown(
14455 forwarding: &Arc<ForwardingTable>,
14456 reason: &CloseReason,
14457 wait_for_flush: bool,
14458) {
14459 const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
14460 let targets = match forwarding.module_connections() {
14461 Ok(targets) => targets,
14462 Err(err) => {
14463 warn!(error = %err, "could not list module connections for shutdown GOODBYE");
14464 return;
14465 }
14466 };
14467 let deadline = Instant::now() + GOODBYE_BUDGET;
14468 let mut sends = tokio::task::JoinSet::new();
14469 for target in targets {
14470 let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
14471 continue;
14472 };
14473 if !wait_for_flush {
14474 if let Err(err) = target.sink.try_send(frame) {
14475 debug!(
14476 module_id = %target.module_id,
14477 error = %err,
14478 "shutdown module GOODBYE was not queued"
14479 );
14480 }
14481 continue;
14482 }
14483 let forwarding = Arc::clone(forwarding);
14484 let reason = reason.clone();
14485 sends.spawn(async move {
14486 match timeout_at(deadline, target.sink.send_flushed(frame)).await {
14487 Ok(Ok(())) => {}
14488 Ok(Err(err)) => debug!(
14489 module_id = %target.module_id,
14490 error = %err,
14491 "module connection closed before its shutdown GOODBYE was written"
14492 ),
14493 Err(_) => warn!(
14494 module_id = %target.module_id,
14495 budget = ?GOODBYE_BUDGET,
14496 "shutdown module GOODBYE was not written within its budget; closing anyway"
14497 ),
14498 }
14499 forwarding.request_connection_close(target.endpoint.connection_id, reason);
14500 });
14501 }
14502 while sends.join_next().await.is_some() {}
14504}
14505
14506async fn send_module_goodbye(
14507 module_id: &str,
14508 forwarding: &ForwardingTable,
14509 target: &ModuleDrainTarget,
14510 wait_for_flush: bool,
14511) {
14512 let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
14513 return;
14514 };
14515 let sent = if wait_for_flush {
14518 timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
14519 .await
14520 .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
14521 .and_then(|result| result.map_err(|err| err.to_string()))
14522 } else {
14523 target.sink.try_send(frame).map_err(|err| err.to_string())
14524 };
14525 if let Err(err) = sent {
14526 warn!(
14527 module_id,
14528 target_connection_id = target.endpoint.connection_id.get(),
14529 error = %err,
14530 "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
14531 );
14532 forwarding.request_connection_close(
14533 target.endpoint.connection_id,
14534 CloseReason::new(
14535 "module_goodbye_delivery_failed",
14536 format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
14537 ),
14538 );
14539 }
14540}
14541
14542#[derive(Clone, Copy)]
14543struct ForwardingDrainContext<'a> {
14544 spec: &'a ModuleSpec,
14545 runtime: &'a SupervisorRuntimeConfig,
14546 registry: &'a Registry,
14547 scope: DrainScope,
14548}
14549
14550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14552enum DrainScope {
14553 Active,
14556 Endpoint(crate::ModuleEndpointId),
14561}
14562
14563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14571enum StopNotice {
14572 SentOverConnection,
14575 NoConnection,
14579 NotSent,
14583}
14584
14585async fn begin_forwarding_drain(
14586 spec: &ModuleSpec,
14587 runtime: &SupervisorRuntimeConfig,
14588 registry: &Registry,
14589 snapshot: &SharedSnapshot,
14590 enabled: Option<bool>,
14591 reason: RouteCloseReason,
14592) -> Result<StopNotice, SuperviseError> {
14593 let Some(forwarding) = runtime.forwarding.as_ref() else {
14594 return Err(SuperviseError::ReloadUnavailable {
14595 module_id: spec.module_id.clone(),
14596 reason: "supervisor was not configured with a forwarding table".to_string(),
14597 });
14598 };
14599
14600 begin_forwarding_drain_with(
14601 forwarding,
14602 ForwardingDrainContext {
14603 spec,
14604 runtime,
14605 registry,
14606 scope: DrainScope::Active,
14607 },
14608 snapshot,
14609 enabled,
14610 reason,
14611 runtime.drain_timeout,
14612 )
14613 .await
14614}
14615
14616async fn begin_forwarding_drain_if_configured(
14617 spec: &ModuleSpec,
14618 runtime: &SupervisorRuntimeConfig,
14619 registry: &Registry,
14620 snapshot: &SharedSnapshot,
14621 enabled: Option<bool>,
14622 reason: RouteCloseReason,
14623) -> Result<StopNotice, SuperviseError> {
14624 begin_forwarding_drain_with_timeout(
14625 spec,
14626 runtime,
14627 registry,
14628 snapshot,
14629 enabled,
14630 reason,
14631 runtime.drain_timeout,
14632 )
14633 .await
14634}
14635
14636async fn begin_forwarding_drain_with_timeout(
14640 spec: &ModuleSpec,
14641 runtime: &SupervisorRuntimeConfig,
14642 registry: &Registry,
14643 snapshot: &SharedSnapshot,
14644 enabled: Option<bool>,
14645 reason: RouteCloseReason,
14646 drain_timeout: Duration,
14647) -> Result<StopNotice, SuperviseError> {
14648 let Some(forwarding) = runtime.forwarding.as_ref() else {
14649 return Ok(StopNotice::NotSent);
14650 };
14651
14652 begin_forwarding_drain_with(
14653 forwarding,
14654 ForwardingDrainContext {
14655 spec,
14656 runtime,
14657 registry,
14658 scope: DrainScope::Active,
14659 },
14660 snapshot,
14661 enabled,
14662 reason,
14663 drain_timeout,
14664 )
14665 .await
14666}
14667
14668async fn begin_forwarding_drain_with(
14669 forwarding: &ForwardingTable,
14670 context: ForwardingDrainContext<'_>,
14671 snapshot: &SharedSnapshot,
14672 enabled: Option<bool>,
14673 reason: RouteCloseReason,
14674 drain_timeout: Duration,
14675) -> Result<StopNotice, SuperviseError> {
14676 let ForwardingDrainContext {
14677 spec,
14678 runtime,
14679 registry,
14680 scope,
14681 } = context;
14682 debug_assert_ne!(reason, RouteCloseReason::Crash);
14683 let terminal = matches!(reason, RouteCloseReason::Disable);
14684 let drain_started_at = Instant::now();
14685 let drain_deadline = drain_started_at + drain_timeout;
14686 let deadline_ms =
14687 unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
14688 let busy_gauges = match scope {
14689 DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
14690 DrainScope::Endpoint(endpoint) => {
14691 declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
14692 }
14693 };
14694
14695 let gate_started = Instant::now();
14698 let drain_target = match scope {
14699 DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
14700 DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
14701 }
14702 .map_err(SuperviseError::Forwarding)?;
14703 info!(
14708 module_id = %spec.module_id,
14709 ?reason,
14710 gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
14711 connected = drain_target.is_some(),
14712 "module drain began; route admission closed"
14713 );
14714 if scope == DrainScope::Active {
14715 update_snapshot(snapshot, Some(&spec.module_id), |state| {
14716 state.state = ModuleState::Draining;
14717 state.draining_to_replace =
14718 matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
14719 if let Some(enabled) = enabled {
14720 state.enabled = enabled;
14721 }
14722 })?;
14723 }
14724
14725 let Some(target) = drain_target.as_ref() else {
14726 return Ok(StopNotice::NoConnection);
14730 };
14731 let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
14732 handle
14733 .registration_spawn(target.endpoint.connection_id)
14734 .is_some()
14735 });
14736 {
14737 send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
14738 #[cfg(feature = "test-support")]
14739 forwarding.wait_before_route_closing_for_test().await;
14740 let routes = forwarding
14741 .endpoint_routes(target.endpoint)
14742 .map_err(SuperviseError::Forwarding)?;
14743 let routes_notified = routes.len();
14744 crate::control::send_route_control_pushes(
14745 forwarding,
14746 routes.clone(),
14747 ClientControlPush::RouteClosing {
14748 module_id: spec.module_id.clone(),
14749 channels: Vec::new(),
14750 reason,
14751 },
14752 );
14753 send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
14754
14755 let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
14761 let wait_result = wait_for_forwarding_quiescence(
14762 forwarding,
14763 &spec.module_id,
14764 runtime,
14765 target.endpoint,
14766 drain_deadline,
14767 &busy_gauges,
14768 scope,
14769 &mut gauge_trace,
14770 )
14771 .await;
14772 let drained = drained_after_quiescence_wait(&wait_result);
14773 if let Err(err) = &wait_result {
14774 error!(
14775 module_id = %spec.module_id,
14776 ?reason,
14777 error = %err,
14778 "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
14779 );
14780 } else if !drained {
14781 let holdouts = forwarding
14783 .endpoint_drain_holdouts(target.endpoint)
14784 .unwrap_or_default();
14785 warn_drain_timed_out(
14786 &spec.module_id,
14787 drain_timeout,
14788 reason,
14789 &holdouts,
14790 &gauge_trace,
14791 );
14792 }
14793 crate::control::send_route_control_pushes(
14794 forwarding,
14795 routes,
14796 ClientControlPush::RouteClosed {
14797 module_id: spec.module_id.clone(),
14798 channels: Vec::new(),
14799 reason,
14800 drained,
14801 abandoned: target.abandoned_bindings.len() as u32,
14802 excluded_subscriptions: target.excluded_subscriptions,
14803 terminal: Some(terminal),
14804 },
14805 );
14806 wait_result?;
14807
14808 let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
14814 Ok(routes) => routes,
14815 Err(err) => {
14816 warn!(
14817 module_id = %spec.module_id,
14818 ?reason,
14819 error = %err,
14820 "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
14821 );
14822 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14823 return Err(SuperviseError::Forwarding(err));
14824 }
14825 };
14826 let route_goodbye_count = released_routes.len();
14827 send_route_goodbyes(forwarding, released_routes);
14828 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
14829
14830 info!(
14836 module_id = %spec.module_id,
14837 ?reason,
14838 routes_notified,
14839 route_goodbyes = route_goodbye_count,
14840 abandoned_reservations = target.abandoned_bindings.len(),
14841 excluded_subscriptions = target.excluded_subscriptions,
14842 drained,
14843 "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
14844 );
14845 }
14846
14847 Ok(StopNotice::SentOverConnection)
14848}
14849
14850async fn wait_for_registration_after_reload(
14853 registry: &Registry,
14854 module_id: &str,
14855 snapshot: &SharedSnapshot,
14856 child: &mut SupervisedChild,
14857 wait: Duration,
14858) -> Result<RegistrationWaitOutcome, SuperviseError> {
14859 wait_for_slot_registration(
14860 registry,
14861 crate::registry::RegistrationSlot::Active(module_id),
14862 module_id,
14863 snapshot,
14864 child,
14865 wait,
14866 )
14867 .await
14868}
14869
14870async fn wait_for_slot_registration(
14878 registry: &Registry,
14879 slot: crate::registry::RegistrationSlot<'_>,
14880 module_id: &str,
14881 snapshot: &SharedSnapshot,
14882 child: &mut SupervisedChild,
14883 wait: Duration,
14884) -> Result<RegistrationWaitOutcome, SuperviseError> {
14885 let deadline = Instant::now() + wait;
14886 loop {
14887 if registry
14888 .registration(slot)
14889 .map_err(SuperviseError::Registry)?
14890 .is_some()
14891 {
14892 return Ok(RegistrationWaitOutcome::Registered);
14893 }
14894
14895 let now = Instant::now();
14896 if now >= deadline {
14897 return Ok(RegistrationWaitOutcome::TimedOut);
14898 }
14899 let remaining = deadline.saturating_duration_since(now);
14900 let poll = remaining.min(REGISTRY_RELEASE_POLL);
14901
14902 tokio::select! {
14903 wait_result = child.wait() => {
14904 let status = wait_result.map_err(|source| SuperviseError::Wait {
14905 module_id: module_id.to_string(),
14906 source,
14907 })?;
14908 return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
14909 snapshot,
14910 child,
14911 &status,
14912 )));
14913 }
14914 _ = sleep(poll) => {}
14915 }
14916 }
14917}
14918
14919fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
14920 if exit_report.kind != ExitKind::DeliberateSeverance {
14924 exit_report.kind = ExitKind::Crash;
14925 }
14926 exit_report
14927}
14928
14929async fn handle_reload_child_registration_failure(
14930 spec: &ModuleSpec,
14931 runtime: &SupervisorRuntimeConfig,
14932 registry: &Registry,
14933 process_liveness: &SupervisorProcessLiveness,
14934 snapshot: &SharedSnapshot,
14935 _child: &mut Option<SupervisedChild>,
14936 failure: ReloadRegistrationFailure,
14937) -> Result<(), SuperviseError> {
14938 let ReloadRegistrationFailure {
14939 exit_report,
14940 reason,
14941 cleanup_detail,
14942 } = failure;
14943 match on_child_exit_with_detail(
14944 spec,
14945 runtime.restart_policy,
14946 registry,
14947 snapshot,
14948 &runtime.terminal_ring,
14949 &runtime.spawn_events,
14950 &runtime.child_roster,
14951 exit_report,
14952 runtime.recovery_is_daemon,
14953 cleanup_detail,
14954 )
14955 .await
14956 {
14957 NextAction::Stop {
14958 registration_released,
14959 } => {
14960 if registration_released {
14961 process_liveness.untrack_if_current(&spec.module_id, snapshot);
14962 }
14963 }
14964 NextAction::Restart { schedule } => {
14965 let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
14966 schedule.delay
14967 });
14968 if let Some(schedule) = schedule {
14969 log_crash_respawn(&spec.module_id, schedule);
14970 }
14971 schedule_respawn(
14972 runtime,
14973 snapshot,
14974 &spec.module_id,
14975 delay,
14976 RespawnKind::after_exit(schedule),
14977 true,
14978 )?;
14979 }
14980 }
14981 Err(SuperviseError::ReloadFailed {
14982 module_id: spec.module_id.clone(),
14983 reason,
14984 })
14985}
14986
14987async fn handle_reload_spawn_failure(
14988 spec: &ModuleSpec,
14989 runtime: &SupervisorRuntimeConfig,
14990 process_liveness: &SupervisorProcessLiveness,
14991 snapshot: &SharedSnapshot,
14992 _child: &mut Option<SupervisedChild>,
14993 reason: String,
14994) -> Result<(), SuperviseError> {
14995 let now = Instant::now();
14996 let mut schedule = None;
14997 update_snapshot(snapshot, Some(&spec.module_id), |state| {
14998 clear_current_process_facts(state);
14999 if state.enabled {
15000 schedule = state.next_crash_restart(&runtime.restart_policy, now);
15001 state.state = if schedule.is_some() {
15002 ModuleState::Restarting
15003 } else {
15004 if runtime
15005 .failure_context(runtime.recovery_is_daemon)
15006 .may_retry()
15007 {
15008 state.failed_retry.schedule(&spec.module_id);
15009 }
15010 ModuleState::Failed
15011 };
15012 } else {
15013 state.state = ModuleState::Disabled;
15014 }
15015 })?;
15016 if let Some(schedule) = schedule {
15017 schedule_respawn(
15018 runtime,
15019 snapshot,
15020 &spec.module_id,
15021 schedule.delay,
15022 RespawnKind::CrashRestart,
15023 true,
15024 )?;
15025 } else {
15026 process_liveness.untrack_if_current(&spec.module_id, snapshot);
15027 }
15028 Err(SuperviseError::ReloadFailed {
15029 module_id: spec.module_id.clone(),
15030 reason,
15031 })
15032}
15033
15034fn control_flags() -> Flags {
15035 Flags::new(false, Priority::Passive, false)
15036}
15037
15038#[allow(clippy::too_many_arguments)]
15039async fn drain_optional_child(
15040 module_id: &str,
15041 protocol: ModuleProtocol,
15042 stop_notice: StopNotice,
15043 registry: &Registry,
15044 forwarding: Option<&ForwardingTable>,
15045 snapshot: &SharedSnapshot,
15046 terminal_ring: &Arc<Mutex<TerminalRing>>,
15047 spawn_events: &SpawnEventFeed,
15048 child: &mut Option<SupervisedChild>,
15049 drain_timeout: Duration,
15050 final_state: ModuleState,
15051 enabled: Option<bool>,
15052 failure: &FailureContext,
15053) -> Result<(), SuperviseError> {
15054 if let Some(child) = child.take() {
15055 drain_child_to_state(
15056 module_id,
15057 protocol,
15058 stop_notice,
15059 registry,
15060 forwarding,
15061 snapshot,
15062 terminal_ring,
15063 spawn_events,
15064 child,
15065 drain_timeout,
15066 final_state,
15067 enabled,
15068 failure,
15069 )
15070 .await
15071 } else {
15072 update_snapshot(snapshot, Some(module_id), |state| {
15073 state.state = final_state;
15074 if final_state == ModuleState::Failed {
15075 state.failed_retry.failed_at = Some(Instant::now());
15076 }
15077 if let Some(enabled) = enabled {
15078 state.enabled = enabled;
15079 }
15080 clear_current_process_facts(state);
15081 })?;
15082 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
15083 }
15084}
15085
15086#[allow(clippy::too_many_arguments)]
15087async fn drain_child_to_state(
15088 module_id: &str,
15089 _protocol: ModuleProtocol,
15090 stop_notice: StopNotice,
15091 registry: &Registry,
15092 forwarding: Option<&ForwardingTable>,
15093 snapshot: &SharedSnapshot,
15094 terminal_ring: &Arc<Mutex<TerminalRing>>,
15095 spawn_events: &SpawnEventFeed,
15096 mut child: SupervisedChild,
15097 drain_timeout: Duration,
15098 final_state: ModuleState,
15099 enabled: Option<bool>,
15100 failure: &FailureContext,
15101) -> Result<(), SuperviseError> {
15102 let protocol = child.protocol;
15103 child.retire_registration();
15104 update_snapshot(snapshot, Some(module_id), |state| {
15105 state.state = ModuleState::Draining;
15106 state.draining_to_replace = final_state == ModuleState::Restarting;
15107 if let Some(enabled) = enabled {
15108 state.enabled = enabled;
15109 }
15110 })?;
15111
15112 if stop_notice != StopNotice::SentOverConnection {
15123 if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
15124 info!(
15125 module_id,
15126 pid = child.pid,
15127 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15128 "module has no connection yet; requesting stop by signal"
15129 );
15130 }
15131 request_graceful_stop(module_id, &child);
15132 }
15133
15134 let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
15135 let exit_report = match timeout(drain_timeout, child.wait()).await {
15136 Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
15137 Ok(Err(source)) => {
15138 fail_after_wait_error(
15139 module_id,
15140 snapshot,
15141 terminal_ring,
15142 spawn_events,
15143 format!("failed to wait during drain: {source}"),
15144 failure,
15145 );
15146 return Err(SuperviseError::Wait {
15147 module_id: module_id.to_string(),
15148 source,
15149 });
15150 }
15151 Err(_) => {
15152 warn!(
15165 module_id,
15166 pid = child.pid,
15167 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
15168 reason = ?final_state,
15169 ?stop_notice,
15170 "drain budget expired before the module exited; killing it"
15171 );
15172 let kill =
15173 if final_state == ModuleState::Restarting && child.child.container().is_some() {
15174 child.kill_leader()
15175 } else {
15176 child.start_kill()
15177 };
15178 kill.map_err(|source| {
15179 fail_after_wait_error(
15180 module_id,
15181 snapshot,
15182 terminal_ring,
15183 spawn_events,
15184 format!("failed to kill during drain: {source}"),
15185 failure,
15186 );
15187 SuperviseError::Kill {
15188 module_id: module_id.to_string(),
15189 source,
15190 }
15191 })?;
15192 let status = child.wait().await.map_err(|source| {
15193 fail_after_wait_error(
15194 module_id,
15195 snapshot,
15196 terminal_ring,
15197 spawn_events,
15198 format!("failed to wait after drain kill: {source}"),
15199 failure,
15200 );
15201 SuperviseError::Wait {
15202 module_id: module_id.to_string(),
15203 source,
15204 }
15205 })?;
15206 classify_reaped_child_exit(snapshot, &child, &status)
15207 }
15208 };
15209
15210 child.drain_stderr(module_id).await;
15211 let detail =
15212 child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
15213 publish_after_terminal_record(
15214 module_id,
15215 || {
15216 record_terminal_with_detail(
15217 module_id,
15218 terminal_ring,
15219 spawn_events,
15220 &exit_report,
15221 terminal_disposition(final_state),
15222 detail,
15223 )
15224 },
15225 || {
15226 update_snapshot(snapshot, Some(module_id), |state| {
15227 state.state = final_state;
15228 if final_state == ModuleState::Failed {
15229 state.failed_retry.failed_at = Some(Instant::now());
15230 }
15231 if let Some(enabled) = enabled {
15232 state.enabled = enabled;
15233 }
15234 clear_current_process_facts(state);
15235 state.last_exit = Some(exit_report.clone());
15236 if exit_report.kind == ExitKind::DeliberateSeverance {
15237 state.lifetime_restarts += 1;
15238 }
15239 })
15240 },
15241 )?;
15242 let released =
15243 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
15244 child
15245 .finish_exit(
15246 released.is_ok()
15247 && final_state == ModuleState::Restarting
15248 && child.spawn_failure.is_none(),
15249 )
15250 .await
15251 .map_err(|source| SuperviseError::Wait {
15252 module_id: module_id.to_owned(),
15253 source,
15254 })?;
15255 released
15256}
15257
15258#[cfg(unix)]
15278fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
15279 if let Some(group) = &child.child.plain_group {
15280 if let Err(error) = group.signal(rustix::process::Signal::TERM) {
15281 debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
15282 }
15283 return;
15284 }
15285 let Some(pid) = child
15286 .id()
15287 .and_then(|pid| i32::try_from(pid).ok())
15288 .filter(|pid| *pid > 1)
15289 .and_then(rustix::process::Pid::from_raw)
15290 else {
15291 debug!(
15292 module_id,
15293 "no pid to signal for teardown; falling through to the drain wait"
15294 );
15295 return;
15296 };
15297 match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
15298 Ok(()) => debug!(
15299 module_id,
15300 "sent SIGTERM to a module nothing else asked to stop"
15301 ),
15302 Err(err) => debug!(
15303 module_id,
15304 error = %err,
15305 "SIGTERM to module failed; the drain wait and kill still apply"
15306 ),
15307 }
15308}
15309
15310#[cfg(not(unix))]
15318fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
15319 debug!(
15320 module_id,
15321 "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
15322 );
15323}
15324
15325fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
15326 match final_state {
15327 ModuleState::Stopped => TerminalDisposition::Stopped,
15328 ModuleState::Disabled => TerminalDisposition::Disabled,
15329 ModuleState::Restarting => TerminalDisposition::Restarting,
15330 ModuleState::Failed => TerminalDisposition::Failed,
15331 ModuleState::Starting
15332 | ModuleState::Running
15333 | ModuleState::Unresponsive
15334 | ModuleState::Draining => {
15335 unreachable!("terminal exits only finish in terminal or restarting states")
15336 }
15337 }
15338}
15339
15340async fn release_dead_registration(
15348 registry: &Registry,
15349 forwarding: Option<&ForwardingTable>,
15350 snapshot: &SharedSnapshot,
15351 module_id: &str,
15352 failure: &FailureContext,
15353) -> Result<(), SuperviseError> {
15354 let result = async {
15355 let registration = registry
15356 .get_module(module_id)
15357 .map_err(SuperviseError::Registry)?;
15358 match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
15359 Ok(()) => return Ok(()),
15360 Err(SuperviseError::RegistrationStillActive { .. }) => {}
15361 Err(err) => return Err(err),
15362 }
15363 let pid = lock_snapshot(snapshot)?.reaped_pid;
15364 if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
15365 warn!(
15366 module_id,
15367 pid,
15368 connection_id = registration.connection_id.get(),
15369 "reaped module registration outlived release grace; closing dead connection"
15370 );
15371 forwarding.request_connection_close(
15372 registration.connection_id,
15373 CloseReason::new(
15374 "supervised_process_reaped",
15375 format!("module '{module_id}' pid {pid} exited"),
15376 ),
15377 );
15378 wait_for_slot_registration_release(
15379 registry,
15380 crate::registry::RegistrationSlot::Connection(registration.connection_id),
15381 REGISTRY_RELEASE_TIMEOUT,
15382 )
15383 .await?;
15384 }
15385 wait_for_registration_release(registry, module_id, Duration::ZERO).await
15386 }
15387 .await;
15388 if let Err(err) = &result {
15389 fail_snapshot(snapshot, Some(module_id), None, failure);
15390 error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
15391 }
15392 result
15393}
15394
15395async fn wait_for_registration_release(
15398 registry: &Registry,
15399 module_id: &str,
15400 wait: Duration,
15401) -> Result<(), SuperviseError> {
15402 wait_for_slot_registration_release(
15403 registry,
15404 crate::registry::RegistrationSlot::Active(module_id),
15405 wait,
15406 )
15407 .await
15408}
15409
15410async fn wait_for_slot_registration_release(
15418 registry: &Registry,
15419 slot: crate::registry::RegistrationSlot<'_>,
15420 wait: Duration,
15421) -> Result<(), SuperviseError> {
15422 let deadline = Instant::now() + wait;
15423 let mut release_events = registration_release_events().subscribe();
15424 let still_active = |registration: &crate::registry::ModuleRegistration| {
15425 SuperviseError::RegistrationStillActive {
15426 module_id: registration.manifest.module_id.clone(),
15427 waited: wait,
15428 }
15429 };
15430 loop {
15431 let _observed_generation = *release_events.borrow_and_update();
15432 let Some(registration) = registry
15433 .registration(slot)
15434 .map_err(SuperviseError::Registry)?
15435 else {
15436 return Ok(());
15437 };
15438
15439 let now = Instant::now();
15440 if now >= deadline {
15441 return Err(still_active(®istration));
15442 }
15443
15444 let remaining = deadline.saturating_duration_since(now);
15445 match timeout(remaining, release_events.changed()).await {
15446 Ok(Ok(())) | Ok(Err(_)) => {}
15447 Err(_) => return Err(still_active(®istration)),
15448 }
15449 }
15450}
15451
15452#[cfg(test)]
15453mod slot_registration_wait_tests {
15454 use super::*;
15455 use crate::registry::{ConnectionId, RegistrationSlot};
15456 use subc_protocol::manifest::ModuleManifest;
15457
15458 #[tokio::test]
15459 async fn enable_release_failure_is_failed_and_a_second_enable_retries() {
15460 let registry = Arc::new(Registry::default());
15461 let supervisor = Supervisor::new_for_test(Arc::clone(®istry), RestartPolicy::default());
15462 let runtime = supervisor.runtime_config();
15463 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::disabled()));
15464 let spec = ModuleSpec {
15465 script: None,
15466 module_id: "enable-stale-registration".to_string(),
15467 program: PathBuf::from("/missing/enable-retry-test"),
15468 args: Vec::new(),
15469 env: Vec::new(),
15470 reserved: false,
15471 reserved_prefixes: Vec::new(),
15472 protocol: ModuleProtocol::Subc,
15473 overlap: Default::default(),
15474 carry_containment: false,
15475 };
15476 let connection = ConnectionId::new(90);
15477 registry
15478 .register_with_control_ops(
15479 ModuleManifest::builder(&spec.module_id, "0.1.0").build(),
15480 1,
15481 connection,
15482 Vec::new(),
15483 )
15484 .unwrap();
15485 let mut child = None;
15486 let err = set_child_enabled(
15487 &spec,
15488 &runtime,
15489 ®istry,
15490 &supervisor.process_liveness,
15491 &snapshot,
15492 &mut child,
15493 true,
15494 &runtime.failure_context(false),
15495 )
15496 .await
15497 .unwrap_err();
15498 assert!(matches!(
15499 err,
15500 SuperviseError::RegistrationStillActive { .. }
15501 ));
15502 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15503 assert!(child.is_none());
15504 registry.deregister_connection(connection).unwrap();
15505 let err = set_child_enabled(
15506 &spec,
15507 &runtime,
15508 ®istry,
15509 &supervisor.process_liveness,
15510 &snapshot,
15511 &mut child,
15512 true,
15513 &runtime.failure_context(false),
15514 )
15515 .await
15516 .unwrap_err();
15517 assert!(
15518 matches!(err, SuperviseError::Spawn { .. }),
15519 "second enable must attempt a spawn: {err}"
15520 );
15521 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
15522 }
15523
15524 const INCUMBENT: u64 = 1;
15525 const CANDIDATE: u64 = 2;
15526
15527 fn swapped_registry() -> Arc<Registry> {
15528 let registry = Arc::new(Registry::default());
15529 let manifest = ModuleManifest::builder("m", "0.1.0").build();
15530 registry
15531 .register_with_control_ops(
15532 manifest.clone(),
15533 1,
15534 ConnectionId::new(INCUMBENT),
15535 Vec::new(),
15536 )
15537 .unwrap();
15538 registry
15539 .register_candidate_with_control_ops(
15540 manifest,
15541 1,
15542 ConnectionId::new(CANDIDATE),
15543 Vec::new(),
15544 )
15545 .unwrap();
15546 registry
15547 }
15548
15549 #[tokio::test]
15553 async fn incumbent_release_is_awaited_by_connection_not_by_module_id() {
15554 let registry = swapped_registry();
15555 registry.promote_candidate("m").unwrap().unwrap();
15556
15557 assert!(matches!(
15558 wait_for_registration_release(®istry, "m", Duration::from_millis(50)).await,
15559 Err(SuperviseError::RegistrationStillActive { .. })
15560 ));
15561
15562 assert!(matches!(
15564 wait_for_slot_registration_release(
15565 ®istry,
15566 RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15567 Duration::from_millis(50),
15568 )
15569 .await,
15570 Err(SuperviseError::RegistrationStillActive { .. })
15571 ));
15572
15573 let releaser = Arc::clone(®istry);
15574 let release = tokio::spawn(async move {
15575 sleep(Duration::from_millis(20)).await;
15576 releaser
15577 .deregister_connection(ConnectionId::new(INCUMBENT))
15578 .unwrap();
15579 notify_registration_release();
15580 });
15581 wait_for_slot_registration_release(
15582 ®istry,
15583 RegistrationSlot::Connection(ConnectionId::new(INCUMBENT)),
15584 Duration::from_secs(5),
15585 )
15586 .await
15587 .expect("the incumbent's own registration is released");
15588 release.await.unwrap();
15589 assert!(registry.get_module("m").unwrap().is_some());
15590 }
15591
15592 #[tokio::test]
15595 async fn candidate_slot_wait_ignores_the_incumbents_registration() {
15596 let registry = swapped_registry();
15597 assert!(matches!(
15598 wait_for_slot_registration_release(
15599 ®istry,
15600 RegistrationSlot::Candidate("m"),
15601 Duration::from_millis(50),
15602 )
15603 .await,
15604 Err(SuperviseError::RegistrationStillActive { .. })
15605 ));
15606 registry
15607 .deregister_connection(ConnectionId::new(CANDIDATE))
15608 .unwrap();
15609 wait_for_slot_registration_release(
15610 ®istry,
15611 RegistrationSlot::Candidate("m"),
15612 Duration::from_millis(50),
15613 )
15614 .await
15615 .expect("a candidate slot with no candidate is released");
15616 assert!(registry
15617 .registration(RegistrationSlot::Active("m"))
15618 .unwrap()
15619 .is_some());
15620 }
15621}
15622
15623fn classify_exit(status: &ExitStatus) -> ExitReport {
15624 ExitReport {
15625 kind: if status.success() {
15626 ExitKind::Clean
15627 } else {
15628 ExitKind::Crash
15629 },
15630 code: status.code(),
15631 signal: exit_signal(status),
15632 at_ms: unix_ms_now(),
15633 }
15634}
15635
15636fn wait_error_exit_report() -> ExitReport {
15642 ExitReport {
15643 kind: ExitKind::Crash,
15644 code: None,
15645 signal: None,
15646 at_ms: unix_ms_now(),
15647 }
15648}
15649
15650#[cfg(unix)]
15651fn exit_signal(status: &ExitStatus) -> Option<i32> {
15652 use std::os::unix::process::ExitStatusExt;
15653
15654 status.signal()
15655}
15656
15657#[cfg(not(unix))]
15658fn exit_signal(_status: &ExitStatus) -> Option<i32> {
15659 None
15660}
15661
15662fn reset_restart_count(snapshot: &SharedSnapshot, module_id: &str) -> Result<(), SuperviseError> {
15668 update_snapshot(snapshot, Some(module_id), |state| {
15669 state.clear_crash_restarts();
15670 })
15671}
15672
15673fn set_running(
15674 snapshot: &SharedSnapshot,
15675 child: &SupervisedChild,
15676 module_id: &str,
15677 spawn_events: &SpawnEventFeed,
15678) -> Result<(), SuperviseError> {
15679 let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15680 module_id: Some(module_id.to_string()),
15681 })?;
15682 state.spawn_generation = spawn_events.emit_spawned(
15683 module_id,
15684 child
15685 .registration_spawn
15686 .as_ref()
15687 .map(|spawn| spawn.authority.spawn_number()),
15688 child.pid,
15689 child.spawned_at_ms,
15690 );
15691 if std::mem::take(&mut state.coalesced_restart_pending) {
15692 let generation = state.spawn_generation;
15693 info!(module_id, "restart already satisfied by generation {generation}; coalesced pending request completed");
15694 }
15695 state.drain_disposition_detail = None;
15696 state.spawn_failure = None;
15697 state.admission_refused = None;
15698 state.config_hold_parked = false;
15699 state.config_hold_daemon_initiated = false;
15700 state.config_hold_approval = None;
15701 state.legacy_registration_spawn =
15702 child.registration_spawn.is_some() && child.admission_base.is_none();
15703 state.registration_declaration = child.registration_declaration.clone();
15704 state.stop_reason = None;
15705 state.config_exit_failed_approval = None;
15706 state.waiting_for_previous_pid = None;
15707 state.waiting_for_previous_detail = None;
15708 state.in_alternate_slot = false;
15711 state.configuration_updated_since_spawn = false;
15712 state.spawned_protocol = Some(child.protocol);
15713 state.state = ModuleState::Running;
15714 state.approved_start_failure = None;
15715 state.enabled = true;
15716 state.process_alive = true;
15717 state.pid = child.id();
15718 state.subtree_target = child.subtree_target.clone();
15719 state.health.status = SupervisorHealthStatus::Unknown;
15722 state.last_probe_evidence = None;
15723 state.health.consecutive_failures = 0;
15724 state.health.detail = None;
15725 state.health.metrics = None;
15726 state.health.last_probe_ms = None;
15727 state.failed_retry.healthy_since = None;
15728 state.failed_retry.failed_at = None;
15729 state.failed_retry.running_since = Some(child.spawned_at);
15730 #[cfg(windows)]
15731 {
15732 state.pipe_consumed = child
15733 .nonce_delivery
15734 .as_ref()
15735 .map(|delivery| delivery.consumed());
15736 }
15737 #[cfg(target_os = "macos")]
15738 {
15739 state.report_ready = Some(Arc::clone(&child.report_ready));
15740 }
15741 state.spawned_at_ms = Some(child.spawned_at_ms);
15742 state.exec_outcome = Some(Arc::clone(&child.exec.0));
15743 state.spawned_from = Some(child.spawned_from.clone());
15744 state.launch_spec_digest = Some(child.launch_spec_digest.clone());
15745 state.spawned_file_identity = child.spawned_file_identity.clone();
15746 state.process_start_time = child.process_start_time;
15747 Ok(())
15748}
15749
15750fn clear_current_process_facts(state: &mut SupervisorSnapshot) {
15751 state.legacy_registration_spawn = false;
15752 state.registration_declaration = None;
15753 state.subtree_target = crate::subtree_resources::Target::Unavailable("not_running");
15754 state.failed_retry.healthy_since = None;
15755 state.failed_retry.running_since = None;
15756 state.waiting_for_previous_pid = None;
15757 state.waiting_for_previous_detail = None;
15758 state.process_alive = false;
15759 state.spawned_protocol = None;
15760 state.pid = None;
15761 #[cfg(windows)]
15762 {
15763 state.pipe_consumed = None;
15764 }
15765 #[cfg(target_os = "macos")]
15766 {
15767 state.report_ready = None;
15768 }
15769 state.spawned_at_ms = None;
15770 state.exec_outcome = None;
15771 state.spawned_from = None;
15772 state.launch_spec_digest = None;
15773 state.spawned_file_identity = None;
15774 state.process_start_time = None;
15775 state.deliberate_severance = None;
15776}
15777
15778#[cfg(test)]
15779fn record_deliberate_severance(
15780 snapshot: &SharedSnapshot,
15781 identity: ProcessIdentity,
15782) -> Result<(), SuperviseError> {
15783 update_snapshot(snapshot, None, |state| {
15784 state.deliberate_severance = Some(identity);
15785 })
15786}
15787
15788fn apply_deliberate_severance_marker(
15789 snapshot: &SharedSnapshot,
15790 exited_identity: Option<ProcessIdentity>,
15791 mut exit_report: ExitReport,
15792) -> ExitReport {
15793 let marker = lock_snapshot(snapshot)
15794 .ok()
15795 .and_then(|mut state| state.deliberate_severance.take());
15796 if marker.is_some() && marker == exited_identity {
15797 exit_report.kind = ExitKind::DeliberateSeverance;
15798 }
15799 exit_report
15800}
15801
15802fn classify_reaped_child_exit(
15803 snapshot: &SharedSnapshot,
15804 child: &SupervisedChild,
15805 status: &ExitStatus,
15806) -> ExitReport {
15807 let _ = update_snapshot(snapshot, None, |state| {
15808 state.reaped_pid = Some(child.pid);
15809 state.spawn_failure = child.spawn_failure.clone();
15810 });
15811 if matches!(
15812 child.spawn_failure.as_deref(),
15813 Some("registration_timeout" | "registration_channel_closed")
15814 ) {
15815 registration_failure_exit_report(classify_exit(status))
15816 } else {
15817 apply_deliberate_severance_marker(snapshot, child.process_identity(), classify_exit(status))
15818 }
15819}
15820
15821fn fail_snapshot(
15822 snapshot: &SharedSnapshot,
15823 module_id: Option<&str>,
15824 last_exit: Option<ExitReport>,
15825 failure: &FailureContext,
15826) {
15827 if let Err(err) = update_snapshot(snapshot, module_id, |state| {
15828 state.state = ModuleState::Failed;
15829 state.config_hold_parked = false;
15830 state.config_hold_daemon_initiated = false;
15831 state.config_hold_approval = None;
15832 clear_current_process_facts(state);
15833 if failure.may_retry() && state.enabled {
15834 state.failed_retry.schedule(module_id.unwrap_or("unknown"));
15835 } else if failure.shutdown.is_set() {
15836 state.failed_retry.cancel();
15837 }
15838 if let Some(last_exit) = last_exit {
15839 state.last_exit = Some(last_exit);
15840 }
15841 }) {
15842 error!(error = %err, "failed to mark supervisor state failed");
15843 }
15844}
15845
15846fn update_snapshot(
15847 snapshot: &SharedSnapshot,
15848 module_id: Option<&str>,
15849 update: impl FnOnce(&mut SupervisorSnapshot),
15850) -> Result<(), SuperviseError> {
15851 let mut state = snapshot.lock().map_err(|_| SuperviseError::StatePoisoned {
15852 module_id: module_id.map(ToOwned::to_owned),
15853 })?;
15854 update(&mut state);
15855 Ok(())
15856}
15857
15858const SLOW_SNAPSHOT_LOCK_THRESHOLD: Duration = Duration::from_millis(250);
15859
15860fn lock_snapshot_for_control<'a>(
15861 snapshot: &'a SharedSnapshot,
15862 module_id: &str,
15863 caller: &'static str,
15864) -> Result<std::sync::MutexGuard<'a, SupervisorSnapshot>, SuperviseError> {
15865 let started_at = Instant::now();
15866 let guard = lock_snapshot(snapshot)?;
15867 let waited = started_at.elapsed();
15868 if waited >= SLOW_SNAPSHOT_LOCK_THRESHOLD {
15869 warn!(
15870 module_id = %module_id,
15871 waited_ms = waited.as_millis() as u64,
15872 caller = %caller,
15873 "slow snapshot lock"
15874 );
15875 }
15876 Ok(guard)
15877}
15878
15879fn lock_snapshot(
15880 snapshot: &SharedSnapshot,
15881) -> Result<std::sync::MutexGuard<'_, SupervisorSnapshot>, SuperviseError> {
15882 snapshot
15883 .lock()
15884 .map_err(|_| SuperviseError::StatePoisoned { module_id: None })
15885}
15886
15887#[cfg(test)]
15888mod terminal_history_tests {
15889 include!("supervise_route_open_recovery_tests.rs");
15890 use std::{
15891 path::PathBuf,
15892 sync::Arc,
15893 time::{Duration, Instant},
15894 };
15895
15896 use tokio::{sync::mpsc, time::sleep};
15897
15898 use super::{
15899 apply_deliberate_severance_marker, daemon_will_restart, drain_child_to_state,
15900 drained_after_quiescence_wait, handle_reload_spawn_failure, health_restart_child,
15901 lock_snapshot, on_child_exit, record_deliberate_severance, record_wait_error_terminal,
15902 reset_restart_count, spawn_and_mark_running, update_snapshot, wait_error_exit_report,
15903 ExitKind, ExitReport, ModuleProtocol, ModuleSpec, ModuleState, NextAction, ProcessIdentity,
15904 RestartPolicy, SpawnEventKind, StopNotice, SuperviseError, SupervisedConfiguration,
15905 SupervisedModule, SupervisedModuleInner, Supervisor, SupervisorHandle,
15906 SupervisorHealthStatus, SupervisorSnapshot,
15907 };
15908 use super::Instant as ClockInstant;
15913 use crate::{
15914 registry::Registry,
15915 terminal_ring::{TerminalRing, TerminalRingConfig},
15916 };
15917 use std::sync::Mutex;
15918 use subc_control::TerminalDisposition;
15919
15920 pub(super) fn fake_aft_stub_path() -> PathBuf {
15925 let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
15926 assert!(
15927 path.exists(),
15928 "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
15929 [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
15930 path.display()
15931 );
15932 path
15933 }
15934
15935 #[test]
15936 fn reserved_never_spawned_refuses_every_hello() {
15937 let supervisor = SupervisorHandle::default();
15942 supervisor.apply_identity_configuration(&ModuleSpec {
15943 script: None,
15944 module_id: "never-spawned".to_string(),
15945 program: PathBuf::from("/usr/bin/false"),
15946 args: Vec::new(),
15947 env: Vec::new(),
15948 reserved: true,
15949 reserved_prefixes: Vec::new(),
15950 protocol: ModuleProtocol::Subc,
15951 overlap: Default::default(),
15952 carry_containment: false,
15953 });
15954 assert!(
15955 supervisor
15956 .reserved_hello_verification("never-spawned", Some("any-forged-nonce"))
15957 .is_err(),
15958 "forged nonce must refuse on a reserved never-spawned id"
15959 );
15960 assert!(
15961 supervisor
15962 .reserved_hello_verification("never-spawned", None)
15963 .is_err(),
15964 "absent nonce must refuse on a reserved never-spawned id"
15965 );
15966 supervisor.set_spawn_nonce("never-spawned", "minted".to_string());
15968 supervisor.apply_identity_configuration(&ModuleSpec {
15969 script: None,
15970 module_id: "never-spawned".to_string(),
15971 program: PathBuf::from("/usr/bin/false"),
15972 args: Vec::new(),
15973 env: Vec::new(),
15974 reserved: true,
15975 reserved_prefixes: Vec::new(),
15976 protocol: ModuleProtocol::Subc,
15977 overlap: Default::default(),
15978 carry_containment: false,
15979 });
15980 assert!(supervisor
15981 .reserved_hello_verification("never-spawned", Some("minted"))
15982 .is_ok());
15983 assert!(supervisor
15984 .reserved_hello_verification("never-spawned", Some("forged"))
15985 .is_err());
15986 }
15987
15988 fn seed_crash_restarts(state: &mut SupervisorSnapshot, count: u32) {
15991 let now = ClockInstant::now();
15992 for _ in 0..count {
15993 state.crash_restarts.push_back(now);
15994 }
15995 }
15996
15997 fn age_oldest_crash_restart_out_of_window(state: &mut SupervisorSnapshot, window: Duration) {
16001 let aged = state
16002 .crash_restarts
16003 .front()
16004 .expect("a crash restart must be recorded before it can be aged")
16005 .checked_sub(window + Duration::from_secs(1))
16006 .expect("the test clock is far enough from its origin to age an instant");
16007 state.crash_restarts[0] = aged;
16008 }
16009
16010 fn snapshot_with_restarts(enabled: bool, count: u32) -> SupervisorSnapshot {
16011 let mut state = SupervisorSnapshot::new(ModuleState::Running, enabled);
16012 seed_crash_restarts(&mut state, count);
16013 state
16014 }
16015
16016 #[test]
16017 fn daemon_owned_recovery_predicate_uses_the_pre_increment_budget() {
16018 let policy = RestartPolicy::new(3, Duration::ZERO);
16019 let now = ClockInstant::now();
16020 assert!(daemon_will_restart(
16021 &mut snapshot_with_restarts(true, 2),
16022 &policy,
16023 now
16024 ));
16025 assert!(!daemon_will_restart(
16026 &mut snapshot_with_restarts(true, 3),
16027 &policy,
16028 now
16029 ));
16030 assert!(!daemon_will_restart(
16031 &mut snapshot_with_restarts(false, 0),
16032 &policy,
16033 now
16034 ));
16035 }
16036
16037 #[test]
16038 fn crash_restart_backoff_escalates_with_in_window_count() {
16039 let policy = RestartPolicy::new(4, Duration::from_millis(100))
16040 .with_max_backoff(Duration::from_secs(30));
16041 let now = ClockInstant::now();
16042 let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16043 let schedules = (0..4)
16044 .map(|_| {
16045 let schedule = state
16046 .next_crash_restart(&policy, now)
16047 .expect("the test policy allows four crash restarts");
16048 state.record_crash_restart(&policy, now);
16049 schedule
16050 })
16051 .collect::<Vec<_>>();
16052
16053 assert_eq!(
16054 schedules
16055 .iter()
16056 .map(|schedule| schedule.restart_in_window)
16057 .collect::<Vec<_>>(),
16058 vec![0, 1, 2, 3]
16059 );
16060 assert_eq!(
16061 schedules
16062 .iter()
16063 .map(|schedule| schedule.delay)
16064 .collect::<Vec<_>>(),
16065 vec![
16066 Duration::from_millis(100),
16067 Duration::from_secs(1),
16068 Duration::from_secs(10),
16069 Duration::from_secs(30),
16070 ]
16071 );
16072 }
16073
16074 #[test]
16075 fn crash_restart_backoff_resets_after_ring_clear() {
16076 let policy = RestartPolicy::new(3, Duration::from_millis(100));
16077 let now = ClockInstant::now();
16078 let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16079 assert_eq!(
16080 state.next_crash_restart(&policy, now).unwrap().delay,
16081 Duration::from_millis(100)
16082 );
16083 state.record_crash_restart(&policy, now);
16084 assert_eq!(
16085 state.next_crash_restart(&policy, now).unwrap().delay,
16086 Duration::from_secs(1)
16087 );
16088
16089 state.clear_crash_restarts();
16090 let schedule = state
16091 .next_crash_restart(&policy, now)
16092 .expect("a cleared ring must allow another restart");
16093 assert_eq!(schedule.restart_in_window, 0);
16094 assert_eq!(schedule.delay, Duration::from_millis(100));
16095 }
16096
16097 #[test]
16098 fn crash_restart_backoff_ignores_aged_restarts() {
16099 let policy = RestartPolicy::new(3, Duration::from_millis(100));
16100 let now = ClockInstant::now();
16101 let mut state = SupervisorSnapshot::new(ModuleState::Running, true);
16102 state
16103 .next_crash_restart(&policy, now)
16104 .expect("the first restart is allowed");
16105 state.record_crash_restart(&policy, now);
16106 state
16107 .next_crash_restart(&policy, now)
16108 .expect("the second restart is allowed");
16109 state.record_crash_restart(&policy, now);
16110 state.crash_restarts[0] = now
16111 .checked_sub(policy.window + Duration::from_secs(1))
16112 .expect("the fake clock can age a restart past the window");
16113
16114 let schedule = state
16115 .next_crash_restart(&policy, now)
16116 .expect("an aged restart must release its slot");
16117 assert_eq!(schedule.restart_in_window, 1);
16118 assert_eq!(schedule.delay, Duration::from_secs(1));
16119 state.record_crash_restart(&policy, now);
16120 assert_eq!(state.crash_restarts.len(), 2);
16121 }
16122
16123 #[test]
16127 fn a_budget_spent_before_the_window_no_longer_refuses() {
16128 let policy = RestartPolicy::new(3, Duration::ZERO);
16129 let mut state = snapshot_with_restarts(true, 3);
16130 let now = ClockInstant::now();
16131 assert!(!daemon_will_restart(&mut state, &policy, now));
16132
16133 assert!(daemon_will_restart(
16134 &mut state,
16135 &policy,
16136 now + policy.window + Duration::from_secs(1)
16137 ));
16138 assert!(
16139 state.crash_restarts.is_empty(),
16140 "reading the budget must drop the instants that left the window"
16141 );
16142 }
16143
16144 fn module_with_recovery_snapshot(
16145 state: ModuleState,
16146 enabled: bool,
16147 restart_count: u32,
16148 ) -> SupervisedModule {
16149 let registry = Arc::new(Registry::default());
16150 let supervisor =
16151 Supervisor::new_for_test(Arc::clone(®istry), RestartPolicy::new(3, Duration::ZERO));
16152 let runtime = supervisor.runtime_config();
16153 let spec = ModuleSpec {
16154 script: None,
16155 module_id: "recovery-snapshot".to_string(),
16156 program: fake_aft_stub_path(),
16157 args: Vec::new(),
16158 env: Vec::new(),
16159 reserved: false,
16160 reserved_prefixes: Vec::new(),
16161 protocol: ModuleProtocol::Subc,
16162 overlap: Default::default(),
16163 carry_containment: false,
16164 };
16165 let mut snapshot = SupervisorSnapshot::new(state, enabled);
16166 seed_crash_restarts(&mut snapshot, restart_count);
16167 let (commands, _rx) = mpsc::channel(4);
16170 let configured_enabled = snapshot.enabled;
16171 SupervisedModule {
16172 inner: Arc::new(SupervisedModuleInner {
16173 module_id: spec.module_id.clone(),
16174 registry,
16175 snapshot: Arc::new(Mutex::new(snapshot)),
16176 configuration: Arc::new(Mutex::new(SupervisedConfiguration {
16177 spec,
16178 enabled: configured_enabled,
16179 health: runtime.health,
16180 register_timeout: runtime.register_timeout,
16181 restart_policy: runtime.restart_policy,
16182 })),
16183 stderr_ring: runtime.stderr_ring,
16184 terminal_ring: runtime.terminal_ring,
16185 commands,
16186 monitor: Mutex::new(None),
16187 effective_drain_timeout: runtime.effective_drain_timeout,
16188 provenance_probe: supervisor.provenance_probe.clone(),
16189 retained: runtime.child_roster.retained_view(),
16190 }),
16191 }
16192 }
16193
16194 #[cfg(target_os = "linux")]
16195 #[tokio::test]
16196 async fn no_cgroup_placement_does_not_block_fake_aft_stub_spawn() {
16197 let supervisor =
16198 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
16199 .with_cgroup_placement(None);
16200 let result = supervisor.spawn(ModuleSpec {
16201 script: None,
16202 module_id: "no-cgroup-placement".to_string(),
16203 program: fake_aft_stub_path(),
16204 args: Vec::new(),
16205 env: Vec::new(),
16206 reserved: false,
16207 reserved_prefixes: Vec::new(),
16208 protocol: ModuleProtocol::Subc,
16209 overlap: Default::default(),
16210 carry_containment: false,
16211 });
16212
16213 assert!(
16214 result.is_ok(),
16215 "no delegation must not turn an otherwise valid spawn into a failure: {result:?}"
16216 );
16217 }
16218
16219 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16220 async fn undecided_snapshot_uses_shared_restart_predicate() {
16221 assert!(module_with_recovery_snapshot(ModuleState::Running, true, 2)
16222 .will_recover_after_connection_loss()
16223 .unwrap());
16224 assert!(
16225 !module_with_recovery_snapshot(ModuleState::Running, true, 3)
16226 .will_recover_after_connection_loss()
16227 .unwrap()
16228 );
16229 }
16230
16231 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16232 async fn restarting_snapshot_at_exhausted_budget_is_non_terminal() {
16233 assert!(
16234 module_with_recovery_snapshot(ModuleState::Restarting, true, 3)
16235 .will_recover_after_connection_loss()
16236 .unwrap()
16237 );
16238 }
16239
16240 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16241 async fn terminal_phase_snapshots_are_terminal_before_budget_exhaustion() {
16242 assert!(!module_with_recovery_snapshot(ModuleState::Failed, true, 0)
16243 .will_recover_after_connection_loss()
16244 .unwrap());
16245 assert!(
16246 !module_with_recovery_snapshot(ModuleState::Disabled, true, 0)
16247 .will_recover_after_connection_loss()
16248 .unwrap()
16249 );
16250 }
16251
16252 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16253 async fn warming_snapshot_is_limited_to_startup_phases() {
16254 for state in [
16255 ModuleState::Starting,
16256 ModuleState::Running,
16257 ModuleState::Restarting,
16258 ] {
16259 assert!(
16260 module_with_recovery_snapshot(state, true, 0)
16261 .is_warming()
16262 .unwrap(),
16263 "{state:?} should be warming"
16264 );
16265 }
16266 for state in [
16267 ModuleState::Unresponsive,
16268 ModuleState::Draining,
16269 ModuleState::Stopped,
16270 ModuleState::Failed,
16271 ModuleState::Disabled,
16272 ] {
16273 assert!(
16274 !module_with_recovery_snapshot(state, true, 0)
16275 .is_warming()
16276 .unwrap(),
16277 "{state:?} should not be warming"
16278 );
16279 }
16280 }
16281
16282 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16283 async fn terminal_history_survives_respawn_and_keeps_both_crashes_in_order() {
16284 let registry = Arc::new(Registry::default());
16285 let supervisor =
16286 Supervisor::new_for_test(Arc::clone(®istry), RestartPolicy::new(1, Duration::ZERO));
16287 let module = supervisor
16288 .spawn(ModuleSpec {
16289 script: None,
16290 module_id: "terminal-history".to_string(),
16291 program: fake_aft_stub_path(),
16292 args: Vec::new(),
16293 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16294 reserved: false,
16295 reserved_prefixes: Vec::new(),
16296 protocol: ModuleProtocol::Subc,
16297 overlap: Default::default(),
16298 carry_containment: false,
16299 })
16300 .unwrap();
16301
16302 let deadline = Instant::now() + Duration::from_secs(5);
16303 loop {
16304 let history = module.terminal_history();
16305 if history.entries.len() == 2 {
16306 assert_eq!(module.status().unwrap().state, ModuleState::Failed);
16307 assert_eq!(history.dropped, 0);
16308 assert_eq!(
16309 history
16310 .entries
16311 .iter()
16312 .map(|entry| entry.exit_code)
16313 .collect::<Vec<_>>(),
16314 vec![Some(23), Some(23)]
16315 );
16316 assert!(history.entries[0].at_ms <= history.entries[1].at_ms);
16317 return;
16318 }
16319 assert!(
16320 Instant::now() < deadline,
16321 "module did not retain two terminal exits: {history:?}"
16322 );
16323 sleep(Duration::from_millis(10)).await;
16324 }
16325 }
16326
16327 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16331 async fn disable_during_crash_backoff_cancels_pending_respawn() {
16332 let backoff = Duration::from_secs(2);
16333 let supervisor = Supervisor::new_for_test(
16334 Arc::new(Registry::default()),
16335 RestartPolicy::new(10, backoff),
16336 );
16337 let module = supervisor
16338 .spawn(ModuleSpec {
16339 script: None,
16340 module_id: "disable-during-backoff".to_string(),
16341 program: fake_aft_stub_path(),
16342 args: Vec::new(),
16343 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
16344 reserved: false,
16345 reserved_prefixes: Vec::new(),
16346 protocol: ModuleProtocol::Subc,
16347 overlap: Default::default(),
16348 carry_containment: false,
16349 })
16350 .unwrap();
16351
16352 let deadline = Instant::now() + Duration::from_secs(5);
16354 loop {
16355 if module.status().unwrap().state == ModuleState::Restarting {
16356 break;
16357 }
16358 assert!(
16359 Instant::now() < deadline,
16360 "module never entered the crash backoff"
16361 );
16362 sleep(Duration::from_millis(10)).await;
16363 }
16364
16365 let started = Instant::now();
16366 module.set_enabled(false).await.unwrap();
16367 let waited = started.elapsed();
16368
16369 assert!(
16370 waited < backoff / 2,
16371 "disable waited {waited:?} behind the {backoff:?} crash backoff; the operator command must preempt the pending respawn"
16372 );
16373 assert_eq!(module.status().unwrap().state, ModuleState::Disabled);
16374
16375 sleep(backoff + Duration::from_millis(500)).await;
16377 let status = module.status().unwrap();
16378 assert_eq!(status.state, ModuleState::Disabled);
16379 assert_eq!(
16380 status.spawn_generation, 1,
16381 "module respawned after the operator disabled it"
16382 );
16383 assert_eq!((status.restart_count, status.lifetime_restarts), (0, 0));
16384 }
16385
16386 #[cfg(unix)]
16389 fn protocol_none_sigterm_exits_clean_spec(
16390 module_id: &str,
16391 dir: &std::path::Path,
16392 ) -> (ModuleSpec, PathBuf, PathBuf) {
16393 let ready = dir.join("ready");
16394 let marker = dir.join("sigterm");
16395 let spec = ModuleSpec {
16396 script: None,
16397 module_id: module_id.to_string(),
16398 program: fake_aft_stub_path(),
16399 args: Vec::new(),
16400 env: vec![
16401 ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
16402 (
16403 "FAKE_AFT_SIGTERM_MARKER_PATH".to_string(),
16404 marker.display().to_string(),
16405 ),
16406 (
16407 "FAKE_AFT_NEVER_CONNECT_READY_PATH".to_string(),
16408 ready.display().to_string(),
16409 ),
16410 ],
16411 reserved: false,
16412 reserved_prefixes: Vec::new(),
16413 protocol: ModuleProtocol::None,
16414 overlap: Default::default(),
16415 carry_containment: false,
16416 };
16417 (spec, ready, marker)
16418 }
16419
16420 #[cfg(unix)]
16424 async fn wait_for_file(path: &std::path::Path) {
16425 let deadline = Instant::now() + Duration::from_secs(10);
16426 while !path.exists() {
16427 assert!(
16428 Instant::now() < deadline,
16429 "{} never appeared",
16430 path.display()
16431 );
16432 sleep(Duration::from_millis(10)).await;
16433 }
16434 }
16435
16436 #[cfg(unix)]
16440 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16441 async fn protocol_none_unrequested_clean_exit_restarts_as_a_crash() {
16442 let dir = cortexkit_test_support::ScratchDir::new("none-unrequested-clean-exit");
16443 let (spec, ready, marker) =
16444 protocol_none_sigterm_exits_clean_spec("none-unrequested-clean-exit", dir.path());
16445 let supervisor = Supervisor::new_for_test(
16446 Arc::new(Registry::default()),
16447 RestartPolicy::new(3, Duration::ZERO),
16448 );
16449 let module = supervisor.spawn(spec).unwrap();
16450 wait_for_file(&ready).await;
16451 let deadline = Instant::now() + Duration::from_secs(10);
16455 let first_pid = loop {
16456 let status = module.status().unwrap();
16457 if status.state == ModuleState::Running {
16458 if let Some(pid) = status.pid {
16459 break pid;
16460 }
16461 }
16462 assert!(
16463 Instant::now() < deadline,
16464 "a running module must report its pid after exec confirmation: {status:?}"
16465 );
16466 sleep(Duration::from_millis(10)).await;
16467 };
16468
16469 rustix::process::kill_process(
16470 rustix::process::Pid::from_raw(i32::try_from(first_pid).unwrap()).unwrap(),
16471 rustix::process::Signal::TERM,
16472 )
16473 .unwrap();
16474
16475 let deadline = Instant::now() + Duration::from_secs(10);
16476 let respawned = loop {
16477 let status = module.status().unwrap();
16478 if status.state == ModuleState::Running
16479 && status.pid.is_some_and(|pid| pid != first_pid)
16480 {
16481 break status;
16482 }
16483 assert!(
16484 Instant::now() < deadline,
16485 "protocol-none module was not respawned after an unrequested clean exit: {status:?}"
16486 );
16487 sleep(Duration::from_millis(10)).await;
16488 };
16489 assert_eq!(respawned.spawn_generation, 2);
16490 assert!(
16491 marker.exists(),
16492 "the child must have exited through its SIGTERM handler (exit 0), or this proves nothing about clean exits"
16493 );
16494
16495 let history = module.terminal_history();
16496 assert_eq!(history.entries.len(), 1, "{history:?}");
16497 let entry = &history.entries[0];
16498 assert_eq!(entry.exit_code, Some(0));
16499 assert_eq!(entry.exit_kind, subc_control::TerminalExitKind::Clean);
16500 assert_eq!(entry.disposition, TerminalDisposition::Restarting);
16501
16502 module.stop().await.unwrap();
16503 }
16504
16505 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
16509 async fn protocol_none_repeated_clean_exits_exhaust_the_restart_budget() {
16510 let supervisor = Supervisor::new_for_test(
16511 Arc::new(Registry::default()),
16512 RestartPolicy::new(1, Duration::ZERO),
16513 );
16514 let module = supervisor
16515 .spawn(ModuleSpec {
16516 script: None,
16517 module_id: "none-clean-exit-budget".to_string(),
16518 program: fake_aft_stub_path(),
16519 args: Vec::new(),
16520 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
16521 reserved: false,
16522 reserved_prefixes: Vec::new(),
16523 protocol: ModuleProtocol::None,
16524 overlap: Default::default(),
16525 carry_containment: false,
16526 })
16527 .unwrap();
16528
16529 let deadline = Instant::now() + Duration::from_secs(10);
16532 loop {
16533 let status = module.status().unwrap();
16534 if status.state == ModuleState::Failed {
16535 break;
16536 }
16537 assert!(
16538 Instant::now() < deadline,
16539 "module never exhausted its budget: {status:?} {:?}",
16540 module.terminal_history()
16541 );
16542 sleep(Duration::from_millis(10)).await;
16543 }
16544 let history = module.terminal_history();
16545 assert_eq!(
16546 history
16547 .entries
16548 .iter()
16549 .map(|entry| (entry.exit_code, entry.disposition.clone()))
16550 .collect::<Vec<_>>(),
16551 vec![
16552 (Some(0), TerminalDisposition::Restarting),
16553 (Some(0), TerminalDisposition::Failed),
16554 ]
16555 );
16556 let detail = history.entries[1]
16557 .disposition_detail
16558 .as_deref()
16559 .expect("a budget failure names the budget");
16560 assert!(detail.contains("max_restarts=1"), "{detail}");
16561 assert_eq!(module.status().unwrap().spawn_generation, 2);
16562 }
16563
16564 #[test]
16565 fn restart_budget_failure_is_published_after_its_terminal_record() {
16566 use std::io::{Read, Write};
16567 let supervisor = Supervisor::new_for_test(
16568 Arc::new(Registry::default()),
16569 RestartPolicy::new(0, Duration::ZERO),
16570 );
16571 let runtime = supervisor.runtime_config();
16572 let spec = ModuleSpec {
16573 script: None,
16574 protocol: ModuleProtocol::None,
16575 ..windowed_crash_spec("budget-publication-order")
16576 };
16577 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16578 ModuleState::Running,
16579 true,
16580 )));
16581 lock_snapshot(&snapshot).unwrap().process_alive = true;
16582 let reaped_snapshot = snapshot.clone();
16583 let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16584 let history = runtime.terminal_ring.clone();
16585 let reap = std::thread::spawn(move || {
16586 tokio::runtime::Builder::new_current_thread()
16587 .enable_all()
16588 .build()
16589 .unwrap()
16590 .block_on(on_child_exit(
16591 &spec,
16592 runtime.restart_policy,
16593 &supervisor.registry,
16594 &reaped_snapshot,
16595 &runtime.terminal_ring,
16596 &runtime.spawn_events,
16597 &runtime.child_roster,
16598 ExitReport {
16599 kind: ExitKind::Clean,
16600 code: Some(0),
16601 signal: None,
16602 at_ms: 1,
16603 },
16604 true,
16605 ))
16606 });
16607 let mut reached = [0];
16608 barrier.read_exact(&mut reached).unwrap();
16609 assert_eq!(&reached, b"R");
16610 let (before_state, before_alive) = {
16611 let state = lock_snapshot(&snapshot).unwrap();
16612 (state.state, state.process_alive)
16613 };
16614 let before_history = history.lock().unwrap().snapshot();
16615 barrier.write_all(b"X").unwrap();
16616 assert!(matches!(reap.join().unwrap(), NextAction::Stop { .. }));
16617 assert!(before_history.entries.is_empty());
16618 assert_ne!(
16619 before_state,
16620 ModuleState::Failed,
16621 "Failed was visible before its terminal record could be written"
16622 );
16623 assert!(before_alive);
16624 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16625 let history = history.lock().unwrap().snapshot();
16626 assert_eq!(history.entries.len(), 1);
16627 assert_eq!(history.entries[0].exit_code, Some(0));
16628 assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16629 }
16630
16631 #[test]
16632 fn crash_restart_at_budget_limit_remains_recoverable_while_recording() {
16633 use std::io::{Read, Write};
16634
16635 let supervisor = Supervisor::new_for_test(
16636 Arc::new(Registry::default()),
16637 RestartPolicy::new(3, Duration::ZERO),
16638 );
16639 let mut runtime = supervisor.runtime_config();
16640 let module = module_with_recovery_snapshot(ModuleState::Running, true, 2);
16641 let snapshot = module.inner.snapshot.clone();
16642 lock_snapshot(&snapshot).unwrap().process_alive = true;
16643 runtime.terminal_ring = module.inner.terminal_ring.clone();
16644 let spec = windowed_crash_spec(module.module_id());
16645 let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16646 let reaped_snapshot = snapshot.clone();
16647 let reap = std::thread::spawn(move || {
16648 tokio::runtime::Builder::new_current_thread()
16649 .enable_all()
16650 .build()
16651 .unwrap()
16652 .block_on(on_child_exit(
16653 &spec,
16654 runtime.restart_policy,
16655 &supervisor.registry,
16656 &reaped_snapshot,
16657 &runtime.terminal_ring,
16658 &runtime.spawn_events,
16659 &runtime.child_roster,
16660 ExitReport {
16661 kind: ExitKind::Crash,
16662 code: Some(2),
16663 signal: None,
16664 at_ms: 1,
16665 },
16666 true,
16667 ))
16668 });
16669
16670 let mut reached = [0];
16674 barrier.read_exact(&mut reached).unwrap();
16675 assert_eq!(&reached, b"R");
16676 let before_status = module.status().unwrap();
16677 let before_history = module.terminal_history();
16678 let before_recovers = module.will_recover_after_connection_loss().unwrap();
16679 barrier.write_all(b"X").unwrap();
16680 assert!(matches!(reap.join().unwrap(), NextAction::Restart { .. }));
16681
16682 assert_eq!(before_status.state, ModuleState::Running);
16683 assert!(before_status.process_alive);
16684 assert_eq!(before_status.restart_count, 2);
16685 assert!(before_history.entries.is_empty());
16686 assert!(
16687 before_recovers,
16688 "connection cleanup would report a terminal close for a scheduled crash restart"
16689 );
16690 let restarting = module.status().unwrap();
16691 assert_eq!(restarting.state, ModuleState::Restarting);
16692 assert_eq!(restarting.restart_count, 2);
16693 assert!(module.will_recover_after_connection_loss().unwrap());
16694 let history = module.terminal_history();
16695 assert_eq!(history.entries.len(), 1);
16696 assert_eq!(
16697 history.entries[0].disposition,
16698 TerminalDisposition::Restarting
16699 );
16700
16701 update_snapshot(&snapshot, Some(module.module_id()), |state| {
16704 state.record_crash_restart(&RestartPolicy::new(3, Duration::ZERO), ClockInstant::now());
16705 state.state = ModuleState::Running;
16706 state.respawn_pending = false;
16707 })
16708 .unwrap();
16709 assert!(!module.will_recover_after_connection_loss().unwrap());
16710 update_snapshot(&snapshot, Some(module.module_id()), |state| {
16711 state.enabled = false;
16712 state.respawn_pending = true;
16713 })
16714 .unwrap();
16715 assert!(!module.will_recover_after_connection_loss().unwrap());
16716 }
16717
16718 fn terminal_record_barrier(events: &super::SpawnEventFeed) -> std::net::TcpStream {
16719 use std::net::{TcpListener, TcpStream};
16720 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
16721 let writer = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
16722 let (barrier, _) = listener.accept().unwrap();
16723 for stream in [&writer, &barrier] {
16724 stream
16725 .set_read_timeout(Some(Duration::from_secs(10)))
16726 .unwrap();
16727 stream
16728 .set_write_timeout(Some(Duration::from_secs(10)))
16729 .unwrap();
16730 }
16731 *events.1.lock().unwrap() = Some(writer);
16732 barrier
16733 }
16734
16735 pub(super) fn before_terminal_record(events: &super::SpawnEventFeed) {
16736 use std::io::{Read, Write};
16737 let barrier = events.1.lock().unwrap().take();
16738 if let Some(mut barrier) = barrier {
16739 barrier.write_all(b"R").unwrap();
16740 let mut release = [0];
16741 barrier.read_exact(&mut release).unwrap();
16742 assert_eq!(&release, b"X");
16743 }
16744 }
16745
16746 #[test]
16747 fn health_restart_budget_failure_is_published_after_its_terminal_record() {
16748 use std::io::{Read, Write};
16749
16750 let supervisor = Supervisor::new_for_test(
16751 Arc::new(Registry::default()),
16752 RestartPolicy::new(0, Duration::ZERO),
16753 );
16754 let mut runtime = supervisor.runtime_config();
16755 let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
16756 let snapshot = module.inner.snapshot.clone();
16757 runtime.terminal_ring = module.inner.terminal_ring.clone();
16758 let spec = ModuleSpec {
16759 script: None,
16760 module_id: module.module_id().into(),
16761 program: fake_aft_stub_path(),
16762 protocol: ModuleProtocol::None,
16763 env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16764 ..windowed_crash_spec(module.module_id())
16765 };
16766 let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16767 let reap = std::thread::spawn(move || {
16768 tokio::runtime::Builder::new_current_thread()
16769 .enable_all()
16770 .build()
16771 .unwrap()
16772 .block_on(async {
16773 let mut child =
16774 Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16775 health_restart_child(
16776 &spec,
16777 &runtime,
16778 &supervisor.registry,
16779 &supervisor.process_liveness,
16780 &snapshot,
16781 &mut child,
16782 SupervisorHealthStatus::Failing,
16783 Some("health probe did not answer"),
16784 1,
16785 )
16786 .await
16787 .unwrap();
16788 assert!(child.is_none());
16789 });
16790 });
16791 let mut reached = [0];
16796 barrier.read_exact(&mut reached).unwrap();
16797 assert_eq!(&reached, b"R");
16798 let before_status = module.status().unwrap();
16799 let before_history = module.terminal_history();
16800 barrier.write_all(b"X").unwrap();
16801 reap.join().unwrap();
16802 assert!(before_history.entries.is_empty());
16803 assert_ne!(
16804 before_status.state,
16805 ModuleState::Failed,
16806 "Failed was visible before its terminal record could be written"
16807 );
16808 assert!(
16809 before_status.process_alive,
16810 "process death was visible before its terminal record could be written"
16811 );
16812 let failed = module.status().unwrap();
16813 assert_eq!(failed.state, ModuleState::Failed);
16814 assert!(!failed.process_alive);
16815 let history = module.terminal_history();
16816 assert_eq!(history.entries.len(), 1);
16817 assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16818 assert_eq!(
16819 history.entries[0].disposition_detail.as_deref(),
16820 Some("crash budget exhausted: max_restarts=0 within window_secs=600")
16821 );
16822 }
16823
16824 #[test]
16825 fn observed_exits_publish_process_death_after_terminal_history() {
16826 use std::io::{Read, Write};
16827 for (kind, enabled, shutdown, wait_error, expected_state) in [
16828 (ExitKind::Clean, true, false, false, ModuleState::Stopped),
16829 (ExitKind::Crash, true, false, false, ModuleState::Restarting),
16830 (ExitKind::Crash, false, false, false, ModuleState::Disabled),
16831 (
16832 ExitKind::DeliberateSeverance,
16833 true,
16834 false,
16835 false,
16836 ModuleState::Restarting,
16837 ),
16838 #[cfg(unix)]
16839 (ExitKind::Crash, true, true, false, ModuleState::Stopped),
16840 (ExitKind::Crash, true, false, true, ModuleState::Failed),
16841 ] {
16842 let supervisor = Supervisor::new_for_test(
16843 Arc::new(Registry::default()),
16844 RestartPolicy::new(1, Duration::ZERO),
16845 );
16846 let runtime = supervisor.runtime_config();
16847 #[cfg(unix)]
16848 if shutdown {
16849 runtime.child_roster.close();
16850 }
16851 #[cfg(not(unix))]
16852 let _ = shutdown;
16853 let spec = windowed_crash_spec("exit-publication-order");
16854 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::new(
16855 ModuleState::Running,
16856 enabled,
16857 )));
16858 lock_snapshot(&snapshot).unwrap().process_alive = true;
16859 let reaped_snapshot = snapshot.clone();
16860 let history = runtime.terminal_ring.clone();
16861 let mut barrier = terminal_record_barrier(&runtime.spawn_events);
16862 let reap = std::thread::spawn(move || {
16863 if wait_error {
16864 super::fail_after_wait_error(
16865 &spec.module_id,
16866 &reaped_snapshot,
16867 &runtime.terminal_ring,
16868 &runtime.spawn_events,
16869 "wait failed".into(),
16870 &runtime.failure_context(true),
16871 );
16872 } else {
16873 tokio::runtime::Builder::new_current_thread()
16874 .enable_all()
16875 .build()
16876 .unwrap()
16877 .block_on(on_child_exit(
16878 &spec,
16879 runtime.restart_policy,
16880 &supervisor.registry,
16881 &reaped_snapshot,
16882 &runtime.terminal_ring,
16883 &runtime.spawn_events,
16884 &runtime.child_roster,
16885 ExitReport {
16886 kind,
16887 code: Some(0),
16888 signal: None,
16889 at_ms: 1,
16890 },
16891 true,
16892 ));
16893 }
16894 });
16895 let mut reached = [0];
16896 barrier.read_exact(&mut reached).unwrap();
16897 assert_eq!(&reached, b"R");
16898 let before_alive = lock_snapshot(&snapshot).unwrap().process_alive;
16899 let before_history = history.lock().unwrap().snapshot();
16900 barrier.write_all(b"X").unwrap();
16901 reap.join().unwrap();
16902 assert!(
16903 before_alive,
16904 "{kind:?}: death was published before recording"
16905 );
16906 assert!(before_history.entries.is_empty());
16907 assert_eq!(lock_snapshot(&snapshot).unwrap().state, expected_state);
16908 assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
16909 assert_eq!(history.lock().unwrap().snapshot().entries.len(), 1);
16910 }
16911 }
16912
16913 #[tokio::test]
16914 async fn health_restart_budget_failure_remains_failed_when_journal_append_fails() {
16915 let dir = cortexkit_test_support::ScratchDir::new("health-budget-journal-failure");
16916 let path = dir.join("terminals.jsonl");
16917 std::fs::create_dir(&path).unwrap();
16918 let supervisor = Supervisor::new_for_test(
16919 Arc::new(Registry::default()),
16920 RestartPolicy::new(0, Duration::ZERO),
16921 )
16922 .with_terminal_journal(path, "health-budget-journal-failure".into());
16923 let runtime = supervisor.runtime_config();
16924 let spec = ModuleSpec {
16925 script: None,
16926 program: fake_aft_stub_path(),
16927 protocol: ModuleProtocol::None,
16928 env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16929 ..windowed_crash_spec("health-budget-journal-failure")
16930 };
16931 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
16932 let mut child = Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16933 health_restart_child(
16934 &spec,
16935 &runtime,
16936 &supervisor.registry,
16937 &supervisor.process_liveness,
16938 &snapshot,
16939 &mut child,
16940 SupervisorHealthStatus::Failing,
16941 None,
16942 1,
16943 )
16944 .await
16945 .unwrap();
16946 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
16947 assert!(!lock_snapshot(&snapshot).unwrap().process_alive);
16948 let history = runtime
16949 .terminal_ring
16950 .lock()
16951 .unwrap()
16952 .durable_history(&spec.module_id);
16953 assert!(history.journal_write_failures > 0);
16954 assert_eq!(history.entries.len(), 1);
16955 assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
16956 }
16957
16958 #[test]
16959 fn health_restart_budget_failure_remains_failed_when_exit_recording_panics() {
16960 let supervisor = Supervisor::new_for_test(
16961 Arc::new(Registry::default()),
16962 RestartPolicy::new(0, Duration::ZERO),
16963 );
16964 let runtime = supervisor.runtime_config();
16965 let spec = ModuleSpec {
16966 script: None,
16967 program: fake_aft_stub_path(),
16968 protocol: ModuleProtocol::None,
16969 env: vec![("FAKE_AFT_EXIT_CODE".into(), "17".into())],
16970 ..windowed_crash_spec("health-budget-recording-panic")
16971 };
16972 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
16973 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
16974 tokio::runtime::Builder::new_current_thread()
16975 .enable_all()
16976 .build()
16977 .unwrap()
16978 .block_on(async {
16979 let mut child =
16980 Some(spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap());
16981 runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
16982 health_restart_child(
16983 &spec,
16984 &runtime,
16985 &supervisor.registry,
16986 &supervisor.process_liveness,
16987 &snapshot,
16988 &mut child,
16989 SupervisorHealthStatus::Failing,
16990 None,
16991 1,
16992 )
16993 .await
16994 .unwrap();
16995 });
16996 }));
16997 let panic = result.expect_err("recording must still unwind");
16998 assert_eq!(
16999 panic.downcast_ref::<String>().map(String::as_str),
17000 Some("spawn event sequence exhausted")
17001 );
17002 let state = lock_snapshot(&snapshot).unwrap();
17003 assert_eq!(state.state, ModuleState::Failed);
17004 assert!(!state.process_alive);
17005 assert!(state.last_exit.is_some());
17006 }
17007
17008 #[tokio::test]
17009 async fn restart_budget_failure_remains_failed_when_journal_append_fails() {
17010 let dir = cortexkit_test_support::ScratchDir::new("budget-journal-failure");
17011 let path = dir.join("terminals.jsonl");
17012 std::fs::create_dir(&path).unwrap();
17013 let supervisor = Supervisor::new_for_test(
17014 Arc::new(Registry::default()),
17015 RestartPolicy::new(0, Duration::ZERO),
17016 )
17017 .with_terminal_journal(path, "budget-journal-failure".into());
17018 let runtime = supervisor.runtime_config();
17019 let spec = windowed_crash_spec("budget-journal-failure");
17020 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17021 assert!(matches!(
17022 on_child_exit(
17023 &spec,
17024 runtime.restart_policy,
17025 &supervisor.registry,
17026 &snapshot,
17027 &runtime.terminal_ring,
17028 &runtime.spawn_events,
17029 &runtime.child_roster,
17030 crash_exit_report(1),
17031 true,
17032 )
17033 .await,
17034 NextAction::Stop { .. }
17035 ));
17036 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17037 let history = runtime
17038 .terminal_ring
17039 .lock()
17040 .unwrap()
17041 .durable_history(&spec.module_id);
17042 assert!(history.journal_write_failures > 0);
17043 assert_eq!(history.entries.len(), 1);
17044 assert_eq!(history.entries[0].disposition, TerminalDisposition::Failed);
17045 }
17046
17047 #[test]
17048 fn restart_budget_failure_remains_failed_when_exit_recording_panics() {
17049 let supervisor = Supervisor::new_for_test(
17050 Arc::new(Registry::default()),
17051 RestartPolicy::new(0, Duration::ZERO),
17052 );
17053 let runtime = supervisor.runtime_config();
17054 let spec = windowed_crash_spec("budget-recording-panic");
17055 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17056 runtime
17057 .spawn_events
17058 .emit_spawned(&spec.module_id, None, 1, 1);
17059 runtime.spawn_events.0.lock().unwrap().seq = u64::MAX;
17062 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
17063 tokio::runtime::Builder::new_current_thread()
17064 .enable_all()
17065 .build()
17066 .unwrap()
17067 .block_on(on_child_exit(
17068 &spec,
17069 runtime.restart_policy,
17070 &supervisor.registry,
17071 &snapshot,
17072 &runtime.terminal_ring,
17073 &runtime.spawn_events,
17074 &runtime.child_roster,
17075 crash_exit_report(1),
17076 true,
17077 ))
17078 }));
17079 let panic = result.err().expect("recording must still unwind");
17080 assert_eq!(
17081 panic.downcast_ref::<String>().map(String::as_str),
17082 Some("spawn event sequence exhausted")
17083 );
17084 assert_eq!(lock_snapshot(&snapshot).unwrap().state, ModuleState::Failed);
17085 }
17086
17087 #[cfg(unix)]
17090 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17091 async fn protocol_none_requested_stop_and_disable_do_not_respawn() {
17092 for disable in [false, true] {
17093 let label = if disable {
17094 "none-requested-disable"
17095 } else {
17096 "none-requested-stop"
17097 };
17098 let dir = cortexkit_test_support::ScratchDir::new(label);
17099 let (spec, ready, marker) = protocol_none_sigterm_exits_clean_spec(label, dir.path());
17100 let supervisor = Supervisor::new_for_test(
17101 Arc::new(Registry::default()),
17102 RestartPolicy::new(3, Duration::ZERO),
17103 );
17104 let module = supervisor.spawn(spec).unwrap();
17105 wait_for_file(&ready).await;
17106
17107 if disable {
17108 module.set_enabled(false).await.unwrap();
17109 } else {
17110 module.stop().await.unwrap();
17111 }
17112 assert!(
17113 marker.exists(),
17114 "{label}: the child must have left through its SIGTERM handler with exit 0"
17115 );
17116
17117 sleep(Duration::from_millis(500)).await;
17120 let status = module.status().unwrap();
17121 let expected = if disable {
17122 ModuleState::Disabled
17123 } else {
17124 ModuleState::Stopped
17125 };
17126 assert_eq!(status.state, expected, "{label}");
17127 assert_eq!(
17128 status.spawn_generation, 1,
17129 "{label}: respawned after a requested stop"
17130 );
17131 let history = module.terminal_history();
17132 assert_eq!(history.entries.len(), 1, "{label}: {history:?}");
17133 assert_eq!(history.entries[0].exit_code, Some(0), "{label}");
17134 assert_ne!(
17135 history.entries[0].disposition,
17136 TerminalDisposition::Restarting,
17137 "{label}"
17138 );
17139 }
17140 }
17141
17142 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17145 async fn subc_wire_clean_exit_is_still_a_stop() {
17146 let supervisor = Supervisor::new_for_test(
17147 Arc::new(Registry::default()),
17148 RestartPolicy::new(3, Duration::ZERO),
17149 );
17150 let module = supervisor
17151 .spawn(ModuleSpec {
17152 script: None,
17153 module_id: "wire-clean-exit".to_string(),
17154 program: fake_aft_stub_path(),
17155 args: Vec::new(),
17156 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "0".to_string())],
17157 reserved: false,
17158 reserved_prefixes: Vec::new(),
17159 protocol: ModuleProtocol::Subc,
17160 overlap: Default::default(),
17161 carry_containment: false,
17162 })
17163 .unwrap();
17164
17165 let deadline = Instant::now() + Duration::from_secs(10);
17166 while module.terminal_history().entries.is_empty() {
17167 assert!(Instant::now() < deadline, "module never exited");
17168 sleep(Duration::from_millis(10)).await;
17169 }
17170 sleep(Duration::from_millis(500)).await;
17172 let status = module.status().unwrap();
17173 assert_eq!(status.state, ModuleState::Stopped);
17174 assert_eq!(status.spawn_generation, 1);
17175 let history = module.terminal_history();
17176 assert_eq!(history.entries.len(), 1, "{history:?}");
17177 assert_eq!(history.entries[0].exit_code, Some(0));
17178 assert_eq!(history.entries[0].disposition, TerminalDisposition::Stopped);
17179 }
17180
17181 #[cfg(unix)]
17182 #[tokio::test]
17183 async fn reload_exit_keeps_roster_until_terminal_is_recorded_during_shutdown() {
17184 let dir = cortexkit_test_support::ScratchDir::new("reload-roster-terminal-order");
17185 let record = dir.join("live-children.json");
17186 let supervisor = Supervisor::new_for_test(
17187 Arc::new(Registry::default()),
17188 RestartPolicy::new(0, Duration::ZERO),
17189 );
17190 let mut runtime = supervisor.runtime_config();
17191 runtime.child_roster.record_to(record.clone());
17192 let gate = Arc::new(super::ReloadExitRecordGate::default());
17193 runtime.test_reload_exit_record_gate = Some(Arc::clone(&gate));
17194 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17195 let spec = ModuleSpec {
17196 script: None,
17197 module_id: "reload-exit-roster".into(),
17198 program: fake_aft_stub_path(),
17199 args: Vec::new(),
17200 env: vec![("FAKE_AFT_EXIT_CODE".into(), "23".into())],
17201 reserved: false,
17202 reserved_prefixes: Vec::new(),
17203 protocol: ModuleProtocol::Subc,
17204 overlap: Default::default(),
17205 carry_containment: false,
17206 };
17207 let mut child = None;
17208 let reload = super::finish_reload_child(
17209 &spec,
17210 &runtime,
17211 &supervisor.registry,
17212 &supervisor.process_liveness,
17213 &snapshot,
17214 &mut child,
17215 );
17216 tokio::pin!(reload);
17217 tokio::select! {
17218 result = &mut reload => panic!("reload missed the before-record gate: {result:?}"),
17219 _ = gate.reached.notified() => {}
17220 }
17221 assert!(runtime
17222 .terminal_ring
17223 .lock()
17224 .unwrap()
17225 .snapshot()
17226 .entries
17227 .is_empty());
17228 assert_eq!(
17229 crate::live_children::read_record(&record).unwrap().len(),
17230 1,
17231 "shutdown must still wait for the reaped child until its terminal record exists"
17232 );
17233 runtime.child_roster.close();
17234 gate.resume.notify_one();
17235 assert!(reload.await.is_err());
17236 assert!(crate::live_children::read_record(&record)
17237 .unwrap()
17238 .is_empty());
17239 let history = runtime.terminal_ring.lock().unwrap().snapshot();
17240 assert_eq!(history.entries.len(), 1);
17241 assert_eq!(
17242 history.entries[0].disposition,
17243 TerminalDisposition::DaemonShutdown
17244 );
17245 }
17246
17247 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17250 async fn no_budgeted_recovery_is_counted_before_spawn() {
17251 let supervisor = Supervisor::new_for_test(
17252 Arc::new(Registry::default()),
17253 RestartPolicy::new(1, Duration::ZERO),
17254 );
17255 let runtime = supervisor.runtime_config();
17256 let spec = ModuleSpec {
17257 script: None,
17258 module_id: "lifetime-increment-path".to_string(),
17259 program: PathBuf::from("/unused/lifetime-increment-path"),
17260 args: Vec::new(),
17261 env: Vec::new(),
17262 reserved: false,
17263 reserved_prefixes: Vec::new(),
17264 protocol: ModuleProtocol::Subc,
17265 overlap: Default::default(),
17266 carry_containment: false,
17267 };
17268
17269 let crash_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17270 assert!(matches!(
17271 on_child_exit(
17272 &spec,
17273 runtime.restart_policy,
17274 &supervisor.registry,
17275 &crash_snapshot,
17276 &runtime.terminal_ring,
17277 &runtime.spawn_events,
17278 &runtime.child_roster,
17279 ExitReport {
17280 kind: ExitKind::Crash,
17281 code: Some(1),
17282 signal: None,
17283 at_ms: 1,
17284 },
17285 true,
17286 )
17287 .await,
17288 NextAction::Restart { schedule: _ }
17289 ));
17290 let (crash_restarts, crash_lifetime) = {
17291 let state = lock_snapshot(&crash_snapshot).unwrap();
17292 (state.crash_restarts.len(), state.lifetime_restarts)
17293 };
17294 assert_eq!((crash_restarts, crash_lifetime), (0, 0));
17295
17296 let health_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17297 let mut health_child = None;
17298 assert!(matches!(
17299 health_restart_child(
17300 &spec,
17301 &runtime,
17302 &supervisor.registry,
17303 &supervisor.process_liveness,
17304 &health_snapshot,
17305 &mut health_child,
17306 SupervisorHealthStatus::Failing,
17307 None,
17308 2,
17309 )
17310 .await,
17311 Ok(())
17312 ));
17313 assert!(health_child.is_none());
17314 assert!(lock_snapshot(&health_snapshot).unwrap().respawn_pending);
17315 assert!(runtime.scheduled_respawn.lock().unwrap().take().is_some());
17316 let (health_restarts, health_lifetime) = {
17317 let state = lock_snapshot(&health_snapshot).unwrap();
17318 (state.crash_restarts.len(), state.lifetime_restarts)
17319 };
17320 assert_eq!((health_restarts, health_lifetime), (0, 0));
17321
17322 let reload_snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17323 let mut reload_child = None;
17324 assert!(matches!(
17325 handle_reload_spawn_failure(
17326 &spec,
17327 &runtime,
17328 &supervisor.process_liveness,
17329 &reload_snapshot,
17330 &mut reload_child,
17331 "forced reload spawn failure".to_string(),
17332 )
17333 .await,
17334 Err(SuperviseError::ReloadFailed { .. })
17335 ));
17336 let (reload_restarts, reload_lifetime) = {
17337 let state = lock_snapshot(&reload_snapshot).unwrap();
17338 (state.crash_restarts.len(), state.lifetime_restarts)
17339 };
17340 assert_eq!((reload_restarts, reload_lifetime), (0, 0));
17341 }
17342
17343 #[tokio::test]
17344 async fn deliberately_severed_live_child_records_lifetime_without_spending_restart_budget() {
17345 let supervisor = Supervisor::new_for_test(
17346 Arc::new(Registry::default()),
17347 RestartPolicy::new(3, Duration::ZERO),
17348 );
17349 let runtime = supervisor.runtime_config();
17350 let spec = ModuleSpec {
17351 script: None,
17352 module_id: "deliberately-severed".to_string(),
17353 program: PathBuf::from("/unused/deliberately-severed"),
17354 args: Vec::new(),
17355 env: Vec::new(),
17356 reserved: false,
17357 reserved_prefixes: Vec::new(),
17358 protocol: ModuleProtocol::Subc,
17359 overlap: Default::default(),
17360 carry_containment: false,
17361 };
17362 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17363 let process = ProcessIdentity {
17364 pid: 41,
17365 start_time: 101,
17366 };
17367 record_deliberate_severance(&snapshot, process).unwrap();
17368 let exit_report = apply_deliberate_severance_marker(
17369 &snapshot,
17370 Some(process),
17371 ExitReport {
17372 kind: ExitKind::Crash,
17373 code: Some(1),
17374 signal: None,
17375 at_ms: 1,
17376 },
17377 );
17378 assert_eq!(exit_report.kind, ExitKind::DeliberateSeverance);
17379
17380 assert!(matches!(
17381 on_child_exit(
17382 &spec,
17383 runtime.restart_policy,
17384 &supervisor.registry,
17385 &snapshot,
17386 &runtime.terminal_ring,
17387 &runtime.spawn_events,
17388 &runtime.child_roster,
17389 exit_report,
17390 true,
17391 )
17392 .await,
17393 NextAction::Restart { schedule: _ }
17394 ));
17395 let state = lock_snapshot(&snapshot).unwrap();
17396 assert_eq!(state.lifetime_restarts, 1);
17397 assert_eq!(state.crash_restarts.len(), 0);
17398 }
17399
17400 #[tokio::test]
17401 async fn genuine_crash_spends_restart_budget_and_records_lifetime() {
17402 let supervisor = Supervisor::new_for_test(
17403 Arc::new(Registry::default()),
17404 RestartPolicy::new(3, Duration::ZERO),
17405 );
17406 let runtime = supervisor.runtime_config();
17407 let spec = ModuleSpec {
17408 script: None,
17409 module_id: "genuine-crash".to_string(),
17410 program: PathBuf::from("/unused/genuine-crash"),
17411 args: Vec::new(),
17412 env: Vec::new(),
17413 reserved: false,
17414 reserved_prefixes: Vec::new(),
17415 protocol: ModuleProtocol::Subc,
17416 overlap: Default::default(),
17417 carry_containment: false,
17418 };
17419 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17420
17421 assert!(matches!(
17422 on_child_exit(
17423 &spec,
17424 runtime.restart_policy,
17425 &supervisor.registry,
17426 &snapshot,
17427 &runtime.terminal_ring,
17428 &runtime.spawn_events,
17429 &runtime.child_roster,
17430 ExitReport {
17431 kind: ExitKind::Crash,
17432 code: Some(1),
17433 signal: None,
17434 at_ms: 1,
17435 },
17436 true,
17437 )
17438 .await,
17439 NextAction::Restart { schedule: Some(_) }
17440 ));
17441 let mut state = lock_snapshot(&snapshot).unwrap();
17442 assert!(state.respawn_pending);
17443 assert_eq!(state.lifetime_restarts, 0);
17444 state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17445 assert_eq!(state.lifetime_restarts, 1);
17446 assert_eq!(state.crash_restarts.len(), 1);
17447 }
17448
17449 fn crash_exit_report(at_ms: u64) -> ExitReport {
17450 ExitReport {
17451 kind: ExitKind::Crash,
17452 code: Some(1),
17453 signal: None,
17454 at_ms,
17455 }
17456 }
17457
17458 fn windowed_crash_spec(module_id: &str) -> ModuleSpec {
17459 ModuleSpec {
17460 script: None,
17461 module_id: module_id.to_string(),
17462 program: PathBuf::from("/unused").join(module_id),
17463 args: Vec::new(),
17464 env: Vec::new(),
17465 reserved: false,
17466 reserved_prefixes: Vec::new(),
17467 protocol: ModuleProtocol::Subc,
17468 overlap: Default::default(),
17469 carry_containment: false,
17470 }
17471 }
17472
17473 #[tokio::test]
17479 async fn three_crashes_inside_the_window_stop_the_module_and_name_the_window() {
17480 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::ERROR);
17481 let supervisor = Supervisor::new_for_test(
17482 Arc::new(Registry::default()),
17483 RestartPolicy::new(2, Duration::ZERO),
17484 );
17485 let runtime = supervisor.runtime_config();
17486 let spec = windowed_crash_spec("crash-loop-in-window");
17487 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17488
17489 for attempt in 1..=2 {
17490 assert!(
17491 matches!(
17492 on_child_exit(
17493 &spec,
17494 runtime.restart_policy,
17495 &supervisor.registry,
17496 &snapshot,
17497 &runtime.terminal_ring,
17498 &runtime.spawn_events,
17499 &runtime.child_roster,
17500 crash_exit_report(attempt),
17501 true,
17502 )
17503 .await,
17504 NextAction::Restart { schedule: _ }
17505 ),
17506 "crash {attempt} is inside the budget and must respawn"
17507 );
17508 lock_snapshot(&snapshot)
17509 .unwrap()
17510 .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17511 }
17512
17513 assert!(matches!(
17514 on_child_exit(
17515 &spec,
17516 runtime.restart_policy,
17517 &supervisor.registry,
17518 &snapshot,
17519 &runtime.terminal_ring,
17520 &runtime.spawn_events,
17521 &runtime.child_roster,
17522 crash_exit_report(3),
17523 true,
17524 )
17525 .await,
17526 NextAction::Stop { .. }
17527 ));
17528
17529 {
17530 let state = lock_snapshot(&snapshot).unwrap();
17531 assert_eq!(state.state, ModuleState::Failed);
17532 assert_eq!(state.crash_restarts.len(), 2);
17533 assert_eq!(state.lifetime_restarts, 2);
17534 }
17535
17536 let history = runtime
17537 .terminal_ring
17538 .lock()
17539 .expect("terminal ring is not poisoned")
17540 .snapshot();
17541 let last = history
17542 .entries
17543 .last()
17544 .expect("the refused crash is retained");
17545 assert_eq!(last.disposition, TerminalDisposition::Failed);
17546 assert_eq!(
17547 last.disposition_detail.as_deref(),
17548 Some("crash budget exhausted: max_restarts=2 within window_secs=600")
17549 );
17550
17551 let captured = crate::router::test_log::captured_logs(&logs);
17552 assert!(
17553 captured.contains("crash budget exhausted: max_restarts=2 within window_secs=600"),
17554 "the stop must be logged with its window: {captured}"
17555 );
17556 }
17557
17558 #[tokio::test]
17566 async fn a_crash_older_than_the_window_frees_its_slot_for_a_later_crash() {
17567 let supervisor = Supervisor::new_for_test(
17568 Arc::new(Registry::default()),
17569 RestartPolicy::new(2, Duration::ZERO),
17570 );
17571 let runtime = supervisor.runtime_config();
17572 let spec = windowed_crash_spec("crash-across-windows");
17573 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17574
17575 for attempt in 1..=2 {
17576 assert!(matches!(
17577 on_child_exit(
17578 &spec,
17579 runtime.restart_policy,
17580 &supervisor.registry,
17581 &snapshot,
17582 &runtime.terminal_ring,
17583 &runtime.spawn_events,
17584 &runtime.child_roster,
17585 crash_exit_report(attempt),
17586 true,
17587 )
17588 .await,
17589 NextAction::Restart { schedule: _ }
17590 ));
17591 lock_snapshot(&snapshot)
17592 .unwrap()
17593 .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17594 }
17595
17596 update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17599 age_oldest_crash_restart_out_of_window(state, runtime.restart_policy.window);
17600 })
17601 .unwrap();
17602
17603 assert!(
17604 matches!(
17605 on_child_exit(
17606 &spec,
17607 runtime.restart_policy,
17608 &supervisor.registry,
17609 &snapshot,
17610 &runtime.terminal_ring,
17611 &runtime.spawn_events,
17612 &runtime.child_roster,
17613 crash_exit_report(3),
17614 true,
17615 )
17616 .await,
17617 NextAction::Restart { schedule: _ }
17618 ),
17619 "a crash older than the window must not hold a budget slot"
17620 );
17621
17622 let mut state = lock_snapshot(&snapshot).unwrap();
17623 state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17624 assert_eq!(state.state, ModuleState::Restarting);
17625 assert_eq!(
17626 state.crash_restarts.len(),
17627 2,
17628 "the aged instant is dropped and the new one takes its place"
17629 );
17630 assert_eq!(
17631 state.lifetime_restarts, 3,
17632 "the ledger counts every restart, including the ones the window forgot"
17633 );
17634 }
17635
17636 #[tokio::test]
17641 async fn an_operator_restart_clears_the_ring_and_leaves_the_ledger_alone() {
17642 let supervisor = Supervisor::new_for_test(
17643 Arc::new(Registry::default()),
17644 RestartPolicy::new(2, Duration::ZERO),
17645 );
17646 let runtime = supervisor.runtime_config();
17647 let spec = windowed_crash_spec("operator-cleared-budget");
17648 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17649
17650 for attempt in 1..=2 {
17651 assert!(matches!(
17652 on_child_exit(
17653 &spec,
17654 runtime.restart_policy,
17655 &supervisor.registry,
17656 &snapshot,
17657 &runtime.terminal_ring,
17658 &runtime.spawn_events,
17659 &runtime.child_roster,
17660 crash_exit_report(attempt),
17661 true,
17662 )
17663 .await,
17664 NextAction::Restart { schedule: _ }
17665 ));
17666 lock_snapshot(&snapshot)
17667 .unwrap()
17668 .record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17669 }
17670
17671 reset_restart_count(&snapshot, &spec.module_id).unwrap();
17672 {
17673 let state = lock_snapshot(&snapshot).unwrap();
17674 assert!(
17675 state.crash_restarts.is_empty(),
17676 "an operator restart returns the full budget"
17677 );
17678 assert_eq!(
17679 state.lifetime_restarts, 2,
17680 "clearing the budget must not unmake the crashes"
17681 );
17682 }
17683
17684 assert!(
17685 matches!(
17686 on_child_exit(
17687 &spec,
17688 runtime.restart_policy,
17689 &supervisor.registry,
17690 &snapshot,
17691 &runtime.terminal_ring,
17692 &runtime.spawn_events,
17693 &runtime.child_roster,
17694 crash_exit_report(3),
17695 true,
17696 )
17697 .await,
17698 NextAction::Restart { schedule: _ }
17699 ),
17700 "the cleared budget must be spendable again"
17701 );
17702 let mut state = lock_snapshot(&snapshot).unwrap();
17703 state.record_crash_restart(&runtime.restart_policy, ClockInstant::now());
17704 assert_eq!(state.crash_restarts.len(), 1);
17705 assert_eq!(state.lifetime_restarts, 3);
17706 }
17707
17708 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17709 async fn severance_marker_for_a_dead_child_does_not_label_its_successor() {
17710 let severed = ProcessIdentity {
17711 pid: 41,
17712 start_time: 101,
17713 };
17714 let successor = ProcessIdentity {
17715 pid: 41,
17716 start_time: 202,
17717 };
17718 let module = module_with_recovery_snapshot(ModuleState::Running, true, 0);
17719 update_snapshot(&module.inner.snapshot, Some("recovery-snapshot"), |state| {
17720 state.pid = Some(successor.pid);
17721 state.process_start_time = Some(successor.start_time);
17722 })
17723 .unwrap();
17724 assert!(!module.record_deliberate_severance(severed).unwrap());
17725
17726 let exit_report = apply_deliberate_severance_marker(
17727 &module.inner.snapshot,
17728 Some(successor),
17729 ExitReport {
17730 kind: ExitKind::Crash,
17731 code: Some(1),
17732 signal: None,
17733 at_ms: 1,
17734 },
17735 );
17736
17737 assert_eq!(exit_report.kind, ExitKind::Crash);
17738 }
17739
17740 #[tokio::test]
17741 async fn drain_reap_marks_deliberate_severance_and_records_lifetime_without_budget() {
17742 let registry = Registry::default();
17743 let supervisor = Supervisor::new_for_test(
17744 Arc::new(Registry::default()),
17745 RestartPolicy::new(3, Duration::ZERO),
17746 );
17747 let runtime = supervisor.runtime_config();
17748 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17749 let spec = ModuleSpec {
17750 script: None,
17751 module_id: "drain-deliberate-severance".to_string(),
17752 program: fake_aft_stub_path(),
17753 args: Vec::new(),
17754 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17755 reserved: false,
17756 reserved_prefixes: Vec::new(),
17757 protocol: ModuleProtocol::Subc,
17758 overlap: Default::default(),
17759 carry_containment: false,
17760 };
17761 let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17762 let process = ProcessIdentity {
17763 pid: 41,
17764 start_time: 101,
17765 };
17766 child.process_identity = Some(process);
17767 update_snapshot(&snapshot, Some(&spec.module_id), |state| {
17768 state.pid = Some(process.pid);
17769 state.process_start_time = Some(process.start_time);
17770 })
17771 .unwrap();
17772 record_deliberate_severance(&snapshot, process).unwrap();
17773
17774 drain_child_to_state(
17775 &spec.module_id,
17776 spec.protocol,
17777 StopNotice::SentOverConnection,
17780 ®istry,
17781 None,
17782 &snapshot,
17783 &runtime.terminal_ring,
17784 &runtime.spawn_events,
17785 child,
17786 Duration::from_secs(1),
17787 ModuleState::Stopped,
17788 Some(false),
17789 &super::FailureContext::operator(),
17790 )
17791 .await
17792 .unwrap();
17793
17794 let state = lock_snapshot(&snapshot).unwrap();
17795 assert_eq!(
17796 state.last_exit.as_ref().map(|exit| exit.kind),
17797 Some(ExitKind::DeliberateSeverance)
17798 );
17799 assert_eq!(state.lifetime_restarts, 1);
17800 assert_eq!(state.crash_restarts.len(), 0);
17801 drop(state);
17802 let history = runtime.terminal_ring.lock().unwrap().snapshot();
17803 assert_eq!(
17804 history.entries[0].exit_kind,
17805 subc_control::TerminalExitKind::DeliberateSeverance
17806 );
17807 }
17808
17809 #[tokio::test]
17810 async fn ordinary_drain_reap_does_not_record_a_lifetime_restart() {
17811 let registry = Registry::default();
17812 let supervisor = Supervisor::new_for_test(
17813 Arc::new(Registry::default()),
17814 RestartPolicy::new(3, Duration::ZERO),
17815 );
17816 let runtime = supervisor.runtime_config();
17817 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
17818 let spec = ModuleSpec {
17819 script: None,
17820 module_id: "ordinary-drain".to_string(),
17821 program: fake_aft_stub_path(),
17822 args: Vec::new(),
17823 env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
17824 reserved: false,
17825 reserved_prefixes: Vec::new(),
17826 protocol: ModuleProtocol::Subc,
17827 overlap: Default::default(),
17828 carry_containment: false,
17829 };
17830 let child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
17831
17832 drain_child_to_state(
17833 &spec.module_id,
17834 spec.protocol,
17835 StopNotice::SentOverConnection,
17838 ®istry,
17839 None,
17840 &snapshot,
17841 &runtime.terminal_ring,
17842 &runtime.spawn_events,
17843 child,
17844 Duration::from_secs(1),
17845 ModuleState::Stopped,
17846 Some(false),
17847 &super::FailureContext::operator(),
17848 )
17849 .await
17850 .unwrap();
17851
17852 let state = lock_snapshot(&snapshot).unwrap();
17853 assert_eq!(
17854 state.last_exit.as_ref().map(|exit| exit.kind),
17855 Some(ExitKind::Crash)
17856 );
17857 assert_eq!(state.lifetime_restarts, 0);
17858 assert_eq!(state.crash_restarts.len(), 0);
17859 }
17860
17861 #[test]
17862 fn fatal_connection_teardown_cannot_arm_a_marker_for_a_surviving_process() {
17863 assert!(!include_str!("server.rs")
17869 .contains("router.record_deliberate_connection_severance(ctx.connection_id)"));
17870 }
17871
17872 #[test]
17879 fn drained_after_quiescence_wait_passes_ok_through_and_forces_false_on_err() {
17880 assert!(drained_after_quiescence_wait(&Ok(true)));
17881 assert!(!drained_after_quiescence_wait(&Ok(false)));
17882 assert!(!drained_after_quiescence_wait(&Err(
17883 SuperviseError::StatePoisoned { module_id: None }
17884 )));
17885 }
17886
17887 #[test]
17896 fn wait_error_exit_report_records_a_failed_terminal_with_no_code_or_signal() {
17897 let ring = Arc::new(Mutex::new(TerminalRing::new(
17898 TerminalRingConfig::default(),
17899 0,
17900 )));
17901 record_wait_error_terminal("wait-error", &ring, &super::SpawnEventFeed::default());
17902
17903 let snapshot = ring.lock().unwrap().snapshot();
17904 assert_eq!(snapshot.entries.len(), 1);
17905 let entry = &snapshot.entries[0];
17906 assert_eq!(entry.exit_code, None);
17907 assert_eq!(entry.exit_signal, None);
17908 assert_eq!(entry.disposition, TerminalDisposition::Failed);
17909 }
17910
17911 #[test]
17914 fn spawn_generation_of_a_failed_launch_is_never_reused() {
17915 let feed = super::SpawnEventFeed::default();
17916 feed.configure_incarnation("launch-numbering".to_string());
17917 let (incarnation, failed) = feed.allocate_generation("relaunched");
17918 assert_eq!(incarnation, "launch-numbering");
17919 let (_, next) = feed.allocate_generation("relaunched");
17920 assert!(next > failed);
17921 assert_eq!(feed.emit_spawned("relaunched", Some(next), 7, 1), next);
17922 assert!(feed.emit_spawned("relaunched", None, 8, 2) > next);
17924 assert_eq!(
17925 feed.allocate_generation("other").1,
17926 1,
17927 "numbering is per module"
17928 );
17929 }
17930
17931 #[test]
17932 fn wait_error_exit_path_preserves_spawn_event_density() {
17933 let feed = super::SpawnEventFeed::default();
17934 feed.configure_incarnation("wait-error-density".to_string());
17935 feed.emit_spawned("wait-error", None, 41, 1);
17936 let ring = Arc::new(Mutex::new(TerminalRing::new(
17937 TerminalRingConfig::default(),
17938 0,
17939 )));
17940
17941 record_wait_error_terminal("wait-error", &ring, &feed);
17942 feed.emit_spawned("after-wait-error", None, 42, 2);
17943
17944 let state = feed.0.lock().unwrap();
17945 let sequences = state
17946 .events
17947 .iter()
17948 .map(|event| event.cursor.seq)
17949 .collect::<Vec<_>>();
17950 assert_eq!(sequences, vec![1, 2, 3]);
17951 assert_eq!(state.events[1].kind, SpawnEventKind::Exited);
17952 assert_eq!(state.events[1].exit_code, None);
17953 assert_eq!(state.events[1].exit_signal, None);
17954 }
17955
17956 #[test]
17960 fn wait_error_exit_report_is_classified_as_a_crash() {
17961 assert_eq!(wait_error_exit_report().kind, ExitKind::Crash);
17962 }
17963}
17964
17965#[cfg(all(test, unix))]
17966mod restart_ordering_tests;
17967
17968#[cfg(all(test, unix))]
17969mod health_event_tests {
17970 use super::*;
17971 use cortexkit_test_support::ScratchDir;
17972 use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
17973
17974 struct Actor {
17975 module: SupervisedModule,
17976 registry: Arc<Registry>,
17977 forwarding: Arc<ForwardingTable>,
17978 spec: ModuleSpec,
17979 health: HealthConfig,
17980 rx: mpsc::Receiver<crate::router::OutboundFrame>,
17981 roster: ChildRoster,
17982 _home: ScratchDir,
17983 }
17984
17985 async fn wait_for<T>(reason: &str, mut observe: impl FnMut() -> Option<T>) -> T {
17986 let deadline = std::time::Instant::now() + Duration::from_secs(10);
17990 let tick = Instant::now();
17991 loop {
17992 if let Some(value) = observe() {
17993 assert_eq!(Instant::now(), tick, "{reason} must not wait for a timer");
17994 return value;
17995 }
17996 assert!(
17997 std::time::Instant::now() < deadline,
17998 "timed out waiting for {reason}"
17999 );
18000 tokio::task::yield_now().await;
18001 }
18002 }
18003
18004 impl Actor {
18005 async fn start(protocol: ModuleProtocol, cadence: Duration) -> Self {
18006 Self::start_with_policy(
18007 protocol,
18008 cadence,
18009 DEFAULT_REGISTER_TIMEOUT,
18010 RestartPolicy::new(3, Duration::ZERO),
18011 )
18012 .await
18013 }
18014
18015 async fn start_with_policy(
18016 protocol: ModuleProtocol,
18017 cadence: Duration,
18018 register_timeout: Duration,
18019 policy: RestartPolicy,
18020 ) -> Self {
18021 let home = ScratchDir::new("health-events");
18022 let registry = Arc::new(Registry::default());
18023 let forwarding = Arc::new(ForwardingTable::default());
18024 let health = HealthConfig {
18025 cadence,
18026 deadline: Duration::from_secs(3600),
18027 ..HealthConfig::default()
18028 };
18029 let supervisor = Supervisor::new_for_test(registry.clone(), policy)
18030 .with_forwarding(forwarding.clone())
18031 .with_health_config(health.clone());
18032 let spec = ModuleSpec {
18033 script: None,
18034 module_id: "event-health-child".into(),
18035 program: PathBuf::from("/bin/sleep"),
18043 args: vec!["600".into()],
18046 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18047 .into_iter()
18048 .map(|key| (key.into(), home.path().display().to_string()))
18049 .collect(),
18050 reserved: false,
18051 reserved_prefixes: vec![],
18052 protocol,
18053 overlap: Default::default(),
18054 carry_containment: false,
18055 };
18056 let module = supervisor
18057 .supervise_configured_requested(
18058 spec.clone(),
18059 true,
18060 health.clone(),
18061 Some(0),
18062 policy,
18063 register_timeout,
18064 None,
18065 )
18066 .unwrap();
18067 let (_, rx) = mpsc::channel(8);
18068 let actor = Self {
18069 module,
18070 registry,
18071 forwarding,
18072 spec,
18073 health,
18074 rx,
18075 roster: supervisor.child_roster.clone(),
18076 _home: home,
18077 };
18078 actor
18079 .wait_for_select(|checkpoint| checkpoint.generation > 0)
18080 .await;
18081 actor
18082 }
18083
18084 async fn expire_registration_wait(&self, remaining: Duration) {
18085 tokio::time::advance(remaining).await;
18086 wait_for("registration timeout TERM grace", || {
18087 lock_snapshot(&self.module.inner.snapshot)
18088 .unwrap()
18089 .actor_select
18090 .is_none()
18091 .then_some(())
18092 })
18093 .await;
18094 tokio::time::advance(crate::child_roster::TERM_TO_KILL).await;
18095 }
18096
18097 fn turns(&self) -> u64 {
18098 lock_snapshot(&self.module.inner.snapshot)
18099 .unwrap()
18100 .actor_turns
18101 }
18102
18103 async fn wait_for_select(
18104 &self,
18105 expected: impl Fn(&ActorSelectCheckpoint) -> bool,
18106 ) -> ActorSelectCheckpoint {
18107 wait_for("actor select checkpoint", || {
18108 let state = lock_snapshot(&self.module.inner.snapshot).unwrap();
18109 state.actor_select.filter(|checkpoint| {
18110 checkpoint.generation == state.spawn_generation
18111 && state.state == ModuleState::Running
18112 && state.process_alive
18113 && state.reported_pid().is_some()
18114 && expected(checkpoint)
18115 })
18116 })
18117 .await
18118 }
18119
18120 fn hello(&mut self, connection: u64, health: bool) {
18121 let manifest =
18122 subc_protocol::manifest::ModuleManifest::builder(&self.spec.module_id, "1.0.0")
18123 .protocol_ver(subc_protocol::PROTOCOL_VERSION)
18124 .build();
18125 let connection = ConnectionId::new(connection);
18126 let (tx, rx) = mpsc::channel(8);
18127 self.rx = rx;
18128 self.forwarding
18129 .register_module_connection(
18130 connection,
18131 self.spec.module_id.clone(),
18132 subc_protocol::PROTOCOL_VERSION,
18133 Concurrency::ModuleManaged,
18134 FrameSink::new(tx),
18135 )
18136 .unwrap();
18137 self.registry
18138 .register_with_control_ops(
18139 manifest,
18140 subc_protocol::PROTOCOL_VERSION,
18141 connection,
18142 if health {
18143 vec![MODULE_CONTROL_OP_HEALTH_CHECK.into()]
18144 } else {
18145 vec![]
18146 },
18147 )
18148 .unwrap();
18149 }
18150
18151 async fn probe(&mut self) -> crate::router::OutboundFrame {
18152 let frame = wait_for("outbound health probe", || match self.rx.try_recv() {
18153 Ok(frame) => Some(frame),
18154 Err(mpsc::error::TryRecvError::Empty) => None,
18155 Err(mpsc::error::TryRecvError::Disconnected) => panic!("health peer disconnected"),
18156 })
18157 .await;
18158 let body: Value = serde_json::from_slice(&frame.body).unwrap();
18159 assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
18160 frame
18161 }
18162
18163 fn no_probe(&mut self) {
18164 assert!(matches!(
18165 self.rx.try_recv(),
18166 Err(mpsc::error::TryRecvError::Empty)
18167 ));
18168 }
18169
18170 fn answer(&self, connection: u64, frame: crate::router::OutboundFrame) {
18171 self.forwarding
18172 .complete_module_control_rpc(
18173 ConnectionId::new(connection),
18174 frame.header.corr,
18175 Some(MODULE_CONTROL_OP_HEALTH_CHECK),
18176 ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
18177 status: HealthStatus::Ok,
18178 detail: None,
18179 metrics: None,
18180 }),
18181 )
18182 .unwrap();
18183 }
18184 }
18185
18186 #[tokio::test(start_paused = true)]
18187 async fn registration_timeout_kills_at_120_seconds_and_respawns() {
18188 let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18189 let initial = actor.module.status().unwrap();
18190 tokio::time::advance(Duration::from_secs(119)).await;
18191 tokio::task::yield_now().await;
18192 assert_eq!(actor.module.status().unwrap().pid, initial.pid);
18193 assert!(actor.module.terminal_history().entries.is_empty());
18194 actor.expire_registration_wait(Duration::from_secs(1)).await;
18195 actor
18196 .wait_for_select(|at| at.generation > initial.spawn_generation)
18197 .await;
18198 let status = actor.module.status().unwrap();
18199 assert_ne!(status.pid, initial.pid);
18200 assert!(!cortexkit_test_support::process_alive(
18201 initial.pid.unwrap() as i32
18202 ));
18203 assert_eq!(status.restart_count, 1);
18204 assert_eq!(status.last_exit.unwrap().kind, ExitKind::Crash);
18205 let entries = actor.module.terminal_history().entries;
18206 assert_eq!(entries.len(), 1);
18207 assert_eq!(
18208 entries[0].disposition_detail.as_deref(),
18209 Some("registration_timeout")
18210 );
18211 actor.module.stop().await.unwrap();
18212 }
18213
18214 #[tokio::test(start_paused = true)]
18215 async fn registration_timeout_is_cancelled_by_hello_at_119_seconds() {
18216 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18217 let pid = actor.module.status().unwrap().pid;
18218 tokio::time::advance(Duration::from_secs(119)).await;
18219 actor.hello(1, false);
18220 let registered = actor
18221 .wait_for_select(|at| at.registered_connection.is_some())
18222 .await;
18223 assert_eq!(
18224 registered.wake_after, None,
18225 "HELLO must cancel the deadline"
18226 );
18227 tokio::time::advance(Duration::from_secs(300)).await;
18228 tokio::task::yield_now().await;
18229 assert_eq!(actor.module.status().unwrap().pid, pid);
18230 assert!(actor.module.terminal_history().entries.is_empty());
18231 actor
18233 .registry
18234 .deregister_connection(ConnectionId::new(1))
18235 .unwrap();
18236 actor
18237 .wait_for_select(|at| at.registered_connection.is_none())
18238 .await;
18239 tokio::time::advance(Duration::from_secs(300)).await;
18240 tokio::task::yield_now().await;
18241 assert_eq!(actor.module.status().unwrap().pid, pid);
18242 assert!(actor.module.terminal_history().entries.is_empty());
18243 actor.module.stop().await.unwrap();
18244
18245 let mut transient = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18246 let pid = transient.module.status().unwrap().pid;
18247 tokio::time::advance(Duration::from_secs(119)).await;
18248 let turns = transient.turns();
18249 transient.hello(1, false);
18252 transient
18253 .registry
18254 .deregister_connection(ConnectionId::new(1))
18255 .unwrap();
18256 let parked = transient.wait_for_select(|at| at.turn > turns).await;
18257 assert_eq!(
18258 parked.wake_after, None,
18259 "transient HELLO must cancel the deadline"
18260 );
18261 tokio::time::advance(Duration::from_secs(300)).await;
18262 tokio::task::yield_now().await;
18263 assert_eq!(transient.module.status().unwrap().pid, pid);
18264 assert!(transient.module.terminal_history().entries.is_empty());
18265 transient.module.stop().await.unwrap();
18266 }
18267
18268 #[tokio::test(start_paused = true)]
18269 async fn registration_timeouts_exhaust_budget_and_schedule_slow_retry() {
18270 let actor = Actor::start_with_policy(
18271 ModuleProtocol::Subc,
18272 Duration::from_secs(30),
18273 Duration::from_secs(10),
18274 RestartPolicy::new(1, Duration::ZERO),
18275 )
18276 .await;
18277 let generation = actor.module.status().unwrap().spawn_generation;
18278 actor
18279 .expire_registration_wait(Duration::from_secs(10))
18280 .await;
18281 actor.wait_for_select(|at| at.generation > generation).await;
18282 actor
18283 .expire_registration_wait(Duration::from_secs(10))
18284 .await;
18285 let retry = wait_for("failed retry schedule", || {
18286 let state = lock_snapshot(&actor.module.inner.snapshot).unwrap();
18287 (state.state == ModuleState::Failed)
18288 .then_some(state.failed_retry.pending)
18289 .flatten()
18290 })
18291 .await;
18292 assert_eq!(retry.delay, Duration::from_secs(600));
18293 assert_eq!(retry.attempt, 1);
18294 let entries = actor.module.terminal_history().entries;
18295 assert_eq!(entries.len(), 2);
18296 assert_eq!(entries[1].disposition, TerminalDisposition::Failed);
18297 assert!(entries[1]
18298 .disposition_detail
18299 .as_deref()
18300 .unwrap()
18301 .contains("registration_timeout"));
18302 tokio::time::advance(Duration::from_secs(599)).await;
18303 tokio::task::yield_now().await;
18304 assert_eq!(actor.module.state().unwrap(), ModuleState::Failed);
18305 tokio::time::advance(Duration::from_secs(1)).await;
18306 actor
18307 .wait_for_select(|at| at.generation > generation + 1)
18308 .await;
18309 actor
18311 .expire_registration_wait(Duration::from_secs(10))
18312 .await;
18313 wait_for("slow retry registration timeout", || {
18314 (actor.module.terminal_history().entries.len() == 3).then_some(())
18315 })
18316 .await;
18317 actor.module.stop().await.unwrap();
18318 }
18319
18320 #[tokio::test(start_paused = true)]
18321 async fn registration_timeout_honours_ten_second_override() {
18322 let actor = Actor::start_with_policy(
18323 ModuleProtocol::Subc,
18324 Duration::from_secs(30),
18325 Duration::from_secs(10),
18326 RestartPolicy::new(3, Duration::ZERO),
18327 )
18328 .await;
18329 let generation = actor.module.status().unwrap().spawn_generation;
18330 tokio::time::advance(Duration::from_secs(9)).await;
18331 tokio::task::yield_now().await;
18332 assert!(actor.module.terminal_history().entries.is_empty());
18333 actor.expire_registration_wait(Duration::from_secs(1)).await;
18334 actor.wait_for_select(|at| at.generation > generation).await;
18335 assert_eq!(actor.module.terminal_history().entries.len(), 1);
18336 actor.module.stop().await.unwrap();
18337 }
18338
18339 #[tokio::test]
18340 async fn registration_timeout_kills_term_ignoring_helper_before_reaping_leader() {
18341 use std::os::unix::process::{CommandExt, ExitStatusExt};
18342
18343 struct Helper(std::process::Child);
18344 impl Drop for Helper {
18345 fn drop(&mut self) {
18346 if matches!(self.0.try_wait(), Ok(None)) {
18349 let _ = self.0.kill();
18350 let _ = self.0.wait();
18351 }
18352 }
18353 }
18354
18355 let home = ScratchDir::new("registration-timeout-helper");
18356 let supervisor = Supervisor::new_for_test(
18357 Arc::new(Registry::default()),
18358 RestartPolicy::new(0, Duration::ZERO),
18359 );
18360 let spec = ModuleSpec {
18361 script: None,
18362 module_id: "registration-timeout-group".into(),
18363 program: "/bin/sleep".into(),
18364 args: vec!["120".into()],
18365 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
18366 .into_iter()
18367 .map(|key| (key.into(), home.path().display().to_string()))
18368 .collect(),
18369 reserved: false,
18370 reserved_prefixes: vec![],
18371 protocol: ModuleProtocol::Subc,
18372 overlap: Default::default(),
18373 carry_containment: false,
18374 };
18375 let module = supervisor
18376 .supervise_configured_requested(
18377 spec,
18378 true,
18379 HealthConfig::default(),
18380 None,
18381 RestartPolicy::new(0, Duration::ZERO),
18382 Duration::from_secs(10),
18383 None,
18384 )
18385 .unwrap();
18386 let leader = timeout(Duration::from_secs(5), async {
18387 loop {
18388 if let Some(pid) = module.status().unwrap().pid {
18389 break pid;
18390 }
18391 sleep(Duration::from_millis(5)).await;
18392 }
18393 })
18394 .await
18395 .expect("supervised group leader must be reported before the deadline");
18396 assert!(leader > 1);
18397 let ready = home.join("helper.ready");
18398 let mut helper = Helper(
18401 std::process::Command::new("/bin/sh")
18402 .args([
18403 "-c",
18404 "trap '' TERM; : > \"$1\"; exec /bin/sleep 120",
18405 "helper",
18406 ])
18407 .arg(&ready)
18408 .process_group(i32::try_from(leader).unwrap())
18409 .stdout(std::process::Stdio::null())
18410 .stderr(std::process::Stdio::null())
18411 .spawn()
18412 .unwrap(),
18413 );
18414 timeout(Duration::from_secs(5), async {
18415 while !ready.exists() {
18416 assert!(helper.0.try_wait().unwrap().is_none());
18417 sleep(Duration::from_millis(5)).await;
18418 }
18419 })
18420 .await
18421 .expect("helper must install TERM ignore before the registration deadline");
18422 let helper_pid =
18423 rustix::process::Pid::from_raw(i32::try_from(helper.0.id()).unwrap()).unwrap();
18424 rustix::process::kill_process(helper_pid, rustix::process::Signal::TERM).unwrap();
18425 sleep(Duration::from_millis(20)).await;
18426 assert!(
18427 helper.0.try_wait().unwrap().is_none(),
18428 "helper must ignore TERM"
18429 );
18430
18431 timeout(Duration::from_secs(20), async {
18432 while module.state().unwrap() != ModuleState::Failed {
18433 sleep(Duration::from_millis(5)).await;
18434 }
18435 })
18436 .await
18437 .expect("registration timeout must stop and reap the group leader");
18438 let helper_exit = timeout(Duration::from_secs(3), async {
18439 loop {
18440 if let Some(status) = helper.0.try_wait().unwrap() {
18441 break status;
18442 }
18443 sleep(Duration::from_millis(5)).await;
18444 }
18445 })
18446 .await
18447 .expect("TERM-ignoring helper survived the registration timeout's group KILL");
18448 assert_eq!(helper_exit.signal(), Some(9));
18449 assert!(!cortexkit_test_support::process_alive(
18450 i32::try_from(leader).unwrap()
18451 ));
18452 assert_eq!(
18453 module.status().unwrap().last_exit.unwrap().kind,
18454 ExitKind::Crash
18455 );
18456 assert!(module.terminal_history().entries[0]
18457 .disposition_detail
18458 .as_deref()
18459 .unwrap()
18460 .contains("registration_timeout"));
18461 module.stop().await.unwrap();
18462 }
18463
18464 #[tokio::test(start_paused = true)]
18465 async fn registration_timeout_does_not_count_an_earlier_exit() {
18466 let actor = Actor::start_with_policy(
18467 ModuleProtocol::Subc,
18468 Duration::from_secs(30),
18469 DEFAULT_REGISTER_TIMEOUT,
18470 RestartPolicy::new(0, Duration::ZERO),
18471 )
18472 .await;
18473 let pid = actor.module.status().unwrap().pid.unwrap();
18474 rustix::process::kill_process(
18475 rustix::process::Pid::from_raw(pid as i32).unwrap(),
18476 rustix::process::Signal::TERM,
18477 )
18478 .unwrap();
18479 wait_for("early exit", || {
18480 (actor.module.state().unwrap() == ModuleState::Failed).then_some(())
18481 })
18482 .await;
18483 tokio::time::advance(Duration::from_secs(121)).await;
18484 tokio::task::yield_now().await;
18485 let entries = actor.module.terminal_history().entries;
18486 assert_eq!(entries.len(), 1);
18487 assert!(!entries[0]
18488 .disposition_detail
18489 .as_deref()
18490 .unwrap()
18491 .contains("registration_timeout"));
18492 assert_eq!(actor.module.status().unwrap().lifetime_restarts, 0);
18493 actor.module.stop().await.unwrap();
18494 }
18495
18496 #[tokio::test(start_paused = true)]
18497 async fn registration_timeout_is_cancelled_by_daemon_shutdown() {
18498 let actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18499 let pid = actor.module.status().unwrap().pid;
18500 tokio::time::advance(Duration::from_secs(119)).await;
18501 actor.roster.close();
18502 let turns = actor.turns();
18503 tokio::time::advance(Duration::from_secs(300)).await;
18504 let parked = actor.wait_for_select(|at| at.turn > turns).await;
18505 assert_eq!(parked.wake_after, None);
18506 assert_eq!(actor.module.status().unwrap().pid, pid);
18507 assert!(actor.module.terminal_history().entries.is_empty());
18508 actor.module.stop().await.unwrap();
18509 let status = actor.module.status().unwrap();
18510 assert_eq!(status.restart_count, 0);
18511 assert_eq!(
18512 actor.module.terminal_history().entries[0].disposition,
18513 TerminalDisposition::DaemonShutdown
18514 );
18515 }
18516
18517 #[tokio::test(start_paused = true)]
18518 async fn no_health_children_park_for_sixty_seconds() {
18519 let none = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18520 let unregistered = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18521 let mut unadvertised = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18522 unadvertised.hello(1, false);
18523 for _ in 0..6000 {
18528 tokio::time::advance(Duration::from_millis(10)).await;
18529 tokio::task::yield_now().await;
18530 }
18531 for actor in [&none, &unregistered, &unadvertised] {
18532 assert!(
18533 actor.turns() <= 5,
18534 "no-health actor woke {} times",
18535 actor.turns()
18536 );
18537 assert_eq!(actor.module.state().unwrap(), ModuleState::Running);
18538 }
18539 }
18540
18541 #[tokio::test(start_paused = true)]
18542 async fn late_hello_starts_a_due_probe_in_the_notification_tick() {
18543 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::ZERO).await;
18547 let tick = Instant::now();
18548 actor.hello(1, true);
18549 actor.probe().await;
18550 assert_eq!(Instant::now(), tick, "HELLO must not wait for a poll");
18551 }
18552
18553 #[tokio::test(start_paused = true)]
18554 async fn hello_keeps_the_jittered_cadence_and_catalog_updates_do_not_reset_it() {
18555 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18556 let hello_tick = Instant::now();
18557 actor.hello(1, true);
18558 let armed = actor
18559 .wait_for_select(|checkpoint| {
18560 checkpoint.registered_connection == Some(ConnectionId::new(1))
18561 && checkpoint.next_probe_at.is_some()
18562 })
18563 .await;
18564 let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18565 assert!((Duration::from_secs(30)..Duration::from_secs(33)).contains(&delay));
18566 let first_deadline = hello_tick + delay;
18567 assert_eq!(armed.next_probe_at, Some(first_deadline));
18568 tokio::time::advance(Duration::from_secs(29)).await;
18569 let turns = actor.turns();
18570 actor
18571 .registry
18572 .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
18573 .unwrap();
18574 let updated = actor
18575 .wait_for_select(|checkpoint| checkpoint.turn > turns)
18576 .await;
18577 assert_eq!(
18578 updated.next_probe_at,
18579 Some(first_deadline),
18580 "catalog update must not reset cadence"
18581 );
18582 actor.no_probe();
18583 tokio::time::advance(first_deadline - Instant::now()).await;
18584 let frame = actor.probe().await;
18585 actor.answer(1, frame);
18586 let next = jittered_health_delay(&actor.spec.module_id, 1, actor.health.cadence);
18587 let next_deadline = Instant::now() + next;
18588 let rearmed = actor
18589 .wait_for_select(|checkpoint| {
18590 checkpoint
18591 .next_probe_at
18592 .is_some_and(|deadline| deadline > first_deadline)
18593 })
18594 .await;
18595 assert_eq!(rearmed.next_probe_at, Some(next_deadline));
18596 tokio::time::advance(next - Duration::from_nanos(1)).await;
18597 actor.no_probe();
18598 tokio::time::advance(Duration::from_nanos(1)).await;
18599 actor.probe().await;
18600 }
18601
18602 #[tokio::test(start_paused = true)]
18603 async fn disconnect_disarms_and_reconnect_rearms_health() {
18604 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18605 actor.hello(1, true);
18606 actor
18607 .wait_for_select(|checkpoint| {
18608 checkpoint.registered_connection == Some(ConnectionId::new(1))
18609 && checkpoint.next_probe_at.is_some()
18610 })
18611 .await;
18612 let turns = actor.turns();
18613 let tick = Instant::now();
18614 actor
18615 .registry
18616 .deregister_connection(ConnectionId::new(1))
18617 .unwrap();
18618 let disarmed = actor
18619 .wait_for_select(|checkpoint| {
18620 checkpoint.turn > turns && checkpoint.registered_connection.is_none()
18621 })
18622 .await;
18623 assert_eq!(disarmed.next_probe_at, None);
18624 assert_eq!(disarmed.wake_after, None);
18625 assert_eq!(
18626 Instant::now(),
18627 tick,
18628 "disconnect must disarm in the notification tick"
18629 );
18630 tokio::time::advance(Duration::from_secs(60)).await;
18631 actor.no_probe();
18632 let reconnect_tick = Instant::now();
18633 actor.hello(2, true);
18634 let rearmed = actor
18635 .wait_for_select(|checkpoint| {
18636 checkpoint.registered_connection == Some(ConnectionId::new(2))
18637 && checkpoint.next_probe_at.is_some()
18638 })
18639 .await;
18640 let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18641 assert_eq!(rearmed.next_probe_at, Some(reconnect_tick + delay));
18642 tokio::time::advance(delay).await;
18643 actor.probe().await;
18644 }
18645
18646 #[tokio::test(start_paused = true)]
18647 async fn reregistration_without_health_disarms_the_old_schedule() {
18648 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18649 actor.hello(1, true);
18650 actor
18651 .wait_for_select(|checkpoint| {
18652 checkpoint.registered_connection == Some(ConnectionId::new(1))
18653 && checkpoint.next_probe_at.is_some()
18654 })
18655 .await;
18656 actor
18657 .registry
18658 .deregister_connection(ConnectionId::new(1))
18659 .unwrap();
18660 actor.hello(2, false);
18661 let disarmed = actor
18662 .wait_for_select(|checkpoint| {
18663 checkpoint.registered_connection == Some(ConnectionId::new(2))
18664 })
18665 .await;
18666 assert_eq!(disarmed.next_probe_at, None);
18667 assert_eq!(disarmed.wake_after, None);
18668 tokio::time::advance(Duration::from_secs(60)).await;
18669 actor.no_probe();
18670 }
18671
18672 #[tokio::test(start_paused = true)]
18673 async fn restart_waits_for_its_own_hello_before_rearming_health() {
18674 let mut actor = Actor::start(ModuleProtocol::Subc, Duration::from_secs(30)).await;
18675 actor.hello(1, true);
18676 let armed = actor
18677 .wait_for_select(|checkpoint| {
18678 checkpoint.registered_connection == Some(ConnectionId::new(1))
18679 && checkpoint.next_probe_at.is_some()
18680 })
18681 .await;
18682 actor
18686 .registry
18687 .deregister_connection(ConnectionId::new(1))
18688 .unwrap();
18689 actor.module.restart(Some(0)).await.unwrap();
18690 let parked = actor
18691 .wait_for_select(|checkpoint| {
18692 checkpoint.generation > armed.generation
18693 && checkpoint.registered_connection.is_none()
18694 && checkpoint.next_probe_at.is_none()
18695 })
18696 .await;
18697 assert_eq!(parked.wake_after, Some(DEFAULT_REGISTER_TIMEOUT));
18698 actor.rx.close();
18699 while actor.rx.try_recv().is_ok() {}
18702 let turns = actor.turns();
18703 tokio::time::advance(Duration::from_secs(60)).await;
18704 let after = actor.turns();
18705 eprintln!(
18706 "restart park turns: before={turns} after={after} delta={}",
18707 after - turns
18708 );
18709 assert_eq!(after, turns, "replacement must park before HELLO");
18710 let hello_tick = Instant::now();
18711 actor.hello(2, true);
18712 let rearmed = actor
18713 .wait_for_select(|checkpoint| {
18714 checkpoint.registered_connection == Some(ConnectionId::new(2))
18715 && checkpoint.next_probe_at.is_some()
18716 })
18717 .await;
18718 let delay = jittered_health_delay(&actor.spec.module_id, 0, actor.health.cadence);
18719 assert_eq!(rearmed.next_probe_at, Some(hello_tick + delay));
18720 tokio::time::advance(delay).await;
18721 actor.probe().await;
18722 }
18723
18724 #[tokio::test(start_paused = true)]
18725 async fn http_probe_waits_a_full_cadence_for_each_spawn() {
18726 use tokio::{
18727 io::{AsyncReadExt, AsyncWriteExt},
18728 net::TcpListener,
18729 };
18730 let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18731 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
18732 actor.health.http = Some(format!("http://{}/healthz", listener.local_addr().unwrap()));
18733 let (started_tx, mut started_rx) = mpsc::channel(8);
18734 let peer = tokio::spawn(async move {
18735 loop {
18736 let (mut socket, _) = listener.accept().await.unwrap();
18737 let mut request = [0; 1024];
18738 assert!(socket.read(&mut request).await.unwrap() > 0);
18739 started_tx.send(Instant::now()).await.unwrap();
18740 socket
18741 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
18742 .await
18743 .unwrap();
18744 }
18745 });
18746 actor
18747 .module
18748 .update_configuration(actor.spec.clone(), actor.health.clone(), None)
18749 .await
18750 .unwrap();
18751 let first_tick = Instant::now();
18752 let first = actor
18753 .wait_for_select(|checkpoint| checkpoint.next_probe_at.is_some())
18754 .await;
18755 assert!(first.next_probe_at.unwrap() >= first_tick + actor.health.cadence);
18756 assert!(started_rx.try_recv().is_err());
18757
18758 tokio::time::advance(
18761 first.next_probe_at.unwrap() - Instant::now() - Duration::from_secs(1),
18762 )
18763 .await;
18764 actor.module.restart(Some(0)).await.unwrap();
18765 let spawn_tick = Instant::now();
18766 let replacement = actor
18767 .wait_for_select(|checkpoint| checkpoint.generation > first.generation)
18768 .await;
18769 let deadline = replacement.next_probe_at.unwrap();
18770 assert!(
18771 deadline >= spawn_tick + actor.health.cadence,
18772 "a replacement must not inherit its predecessor's probe deadline"
18773 );
18774 tokio::time::advance(actor.health.cadence - Duration::from_nanos(1)).await;
18775 assert!(
18776 started_rx.try_recv().is_err(),
18777 "no HTTP probe during startup grace"
18778 );
18779 tokio::time::advance(deadline - Instant::now()).await;
18780 let landed = wait_for("first replacement HTTP probe", || {
18781 started_rx.try_recv().ok()
18782 })
18783 .await;
18784 assert!(landed >= spawn_tick + actor.health.cadence);
18785 wait_for("healthy replacement", || {
18786 (actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
18787 .then_some(())
18788 })
18789 .await;
18790 peer.abort();
18791 }
18792
18793 #[tokio::test(start_paused = true)]
18794 async fn rescan_adds_and_removes_http_health_without_polling() {
18795 use tokio::{
18796 io::{AsyncReadExt, AsyncWriteExt},
18797 net::TcpListener,
18798 };
18799 let mut actor = Actor::start(ModuleProtocol::None, Duration::from_secs(30)).await;
18800 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
18801 actor.health.http = Some(format!("http://{}/health", listener.local_addr().unwrap()));
18802 actor.health.cadence = Duration::from_millis(1);
18804 let (started_tx, mut started_rx) = mpsc::channel(8);
18805 let peer = tokio::spawn(async move {
18806 loop {
18807 let (mut socket, _) = listener.accept().await.unwrap();
18808 let mut request = [0; 1024];
18809 assert!(socket.read(&mut request).await.unwrap() > 0);
18810 started_tx.send(()).await.unwrap();
18811 socket
18812 .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
18813 .await
18814 .unwrap();
18815 }
18816 });
18817 let tick = Instant::now();
18818 let turns = actor.turns();
18819 actor
18820 .module
18821 .update_configuration(actor.spec.clone(), actor.health.clone(), None)
18822 .await
18823 .unwrap();
18824 let armed = actor
18825 .wait_for_select(|checkpoint| {
18826 checkpoint.turn > turns && checkpoint.next_probe_at.is_some()
18827 })
18828 .await;
18829 assert_eq!(armed.next_probe_at, Some(tick + Duration::from_millis(1)));
18830 assert_eq!(Instant::now(), tick);
18831 tokio::time::advance(Duration::from_millis(1)).await;
18832 let mut started = false;
18833 wait_for("successful HTTP probe", || {
18834 started |= started_rx.try_recv().is_ok();
18835 (started && actor.module.status().unwrap().health.status == SupervisorHealthStatus::Ok)
18836 .then_some(())
18837 })
18838 .await;
18839 assert!(started, "added HTTP check must start at its first deadline");
18840 assert_eq!(
18841 actor.module.status().unwrap().health.status,
18842 SupervisorHealthStatus::Ok
18843 );
18844 assert_eq!(Instant::now(), tick + Duration::from_millis(1));
18845 actor.health.http = None;
18846 let turns = actor.turns();
18847 actor
18848 .module
18849 .update_configuration(actor.spec.clone(), actor.health.clone(), None)
18850 .await
18851 .unwrap();
18852 let parked = actor
18853 .wait_for_select(|checkpoint| {
18854 checkpoint.turn > turns && checkpoint.next_probe_at.is_none()
18855 })
18856 .await;
18857 assert_eq!(parked.wake_after, None);
18858 let turns = actor.turns();
18859 tokio::time::advance(Duration::from_secs(60)).await;
18860 assert_eq!(
18861 actor.turns(),
18862 turns,
18863 "removed HTTP check must park the actor"
18864 );
18865 assert!(
18866 started_rx.try_recv().is_err(),
18867 "removed HTTP check must stay disarmed"
18868 );
18869 assert_eq!(
18870 actor.module.status().unwrap().health,
18871 ModuleHealthStatus::default()
18872 );
18873 peer.abort();
18874 }
18875}
18876
18877#[cfg(test)]
18878mod drain_busy_reprobe_tests {
18879 use super::*;
18883 use std::collections::BTreeMap;
18884 use std::sync::Mutex as StdMutex;
18885 use subc_protocol::{manifest::Concurrency, session::ModuleControlResponse};
18886
18887 const MODULE_ID: &str = "drain-reprobe-module";
18888 const CONNECTION: u64 = 7;
18889 const GAUGE: &str = "runs_in_flight";
18890 const CADENCE: Duration = Duration::from_secs(30);
18893 const CEILING: Duration = Duration::from_secs(30);
18894
18895 #[derive(Clone, Copy)]
18897 enum Answer {
18898 BusyUntil { until: Instant, latency: Duration },
18901 OmitsGauge,
18903 Silent,
18905 }
18906
18907 struct Drain {
18908 forwarding: Arc<ForwardingTable>,
18909 runtime: SupervisorRuntimeConfig,
18910 endpoint: crate::ModuleEndpointId,
18911 probes: Arc<StdMutex<Vec<Instant>>>,
18913 responder: tokio::task::JoinHandle<()>,
18914 }
18915
18916 impl Drain {
18917 fn start(answer: Answer) -> Self {
18918 let registry = Arc::new(Registry::default());
18919 let forwarding = Arc::new(ForwardingTable::default());
18920 let health = HealthConfig {
18921 cadence: CADENCE,
18922 ..HealthConfig::default()
18923 };
18924 let runtime = Supervisor::new_for_test(registry, RestartPolicy::new(3, Duration::ZERO))
18925 .with_forwarding(forwarding.clone())
18926 .with_health_config(health)
18927 .runtime_config();
18928 let (tx, mut rx) = mpsc::channel::<crate::router::OutboundFrame>(8);
18929 let endpoint = forwarding
18930 .register_module_connection(
18931 ConnectionId::new(CONNECTION),
18932 MODULE_ID.to_string(),
18933 subc_protocol::PROTOCOL_VERSION,
18934 Concurrency::ModuleManaged,
18935 FrameSink::new(tx),
18936 )
18937 .unwrap();
18938 let probes = Arc::new(StdMutex::new(Vec::new()));
18939 let responder = tokio::spawn({
18940 let forwarding = forwarding.clone();
18941 let probes = probes.clone();
18942 async move {
18943 while let Some(frame) = rx.recv().await {
18944 let body: Value = serde_json::from_slice(&frame.body).unwrap();
18945 assert_eq!(body["op"], MODULE_CONTROL_OP_HEALTH_CHECK);
18946 probes.lock().unwrap().push(Instant::now());
18947 let metrics = match answer {
18948 Answer::BusyUntil { until, latency } => {
18949 sleep(latency).await;
18950 let busy = u64::from(Instant::now() < until);
18951 serde_json::json!({ GAUGE: busy })
18952 }
18953 Answer::OmitsGauge => serde_json::json!({ "queue_depth": 0 }),
18954 Answer::Silent => continue,
18955 };
18956 let _ = forwarding.complete_module_control_rpc(
18959 ConnectionId::new(CONNECTION),
18960 frame.header.corr,
18961 Some(MODULE_CONTROL_OP_HEALTH_CHECK),
18962 ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
18963 status: HealthStatus::Ok,
18964 detail: None,
18965 metrics: Some(metrics),
18966 }),
18967 );
18968 }
18969 }
18970 });
18971 Self {
18972 forwarding,
18973 runtime,
18974 endpoint,
18975 probes,
18976 responder,
18977 }
18978 }
18979
18980 async fn run(&self, ceiling: Duration) -> (bool, Duration) {
18983 let (drained, elapsed, _) = self.run_traced(ceiling).await;
18984 (drained, elapsed)
18985 }
18986
18987 async fn run_traced(&self, ceiling: Duration) -> (bool, Duration, DrainGaugeTrace) {
18989 let started = Instant::now();
18990 let mut trace = DrainGaugeTrace::new(&[GAUGE.to_string()]);
18991 let drained = wait_for_forwarding_quiescence(
18992 &self.forwarding,
18993 MODULE_ID,
18994 &self.runtime,
18995 self.endpoint,
18996 started + ceiling,
18997 &[GAUGE.to_string()],
18998 DrainScope::Active,
18999 &mut trace,
19000 )
19001 .await
19002 .unwrap();
19003 (drained, started.elapsed(), trace)
19004 }
19005
19006 fn probes(&self) -> Vec<Instant> {
19007 self.probes.lock().unwrap().clone()
19008 }
19009 }
19010
19011 impl Drop for Drain {
19012 fn drop(&mut self) {
19013 self.responder.abort();
19014 }
19015 }
19016
19017 #[tokio::test(start_paused = true)]
19018 async fn busy_at_first_probe_then_quiet_drains_long_before_the_ceiling() {
19019 let drain = Drain::start(Answer::BusyUntil {
19020 until: Instant::now() + Duration::from_secs(1),
19021 latency: Duration::ZERO,
19022 });
19023 let (drained, elapsed) = drain.run(CEILING).await;
19024 assert!(
19025 drained,
19026 "gauges that read zero during the drain must let it finish drained, \
19027 not wait out the {CADENCE:?} health cadence (elapsed {elapsed:?})"
19028 );
19029 assert!(
19030 elapsed < Duration::from_secs(3),
19031 "drain took {elapsed:?} after the gauges went quiet at 1s"
19032 );
19033 let probes = drain.probes();
19034 assert!(
19035 probes.len() >= 2,
19036 "the module was busy at the first probe, so a quiet verdict needs a second: {probes:?}"
19037 );
19038 }
19039
19040 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
19045 async fn an_instant_busy_first_answer_does_not_stop_later_probes_in_real_time() {
19046 let drain = Drain::start(Answer::BusyUntil {
19047 until: Instant::now() + Duration::from_millis(600),
19048 latency: Duration::ZERO,
19049 });
19050 let (drained, elapsed, trace) = drain.run_traced(CEILING).await;
19051 assert!(drained, "the gauge fell at 600ms: {trace}");
19052 assert!(
19053 elapsed < Duration::from_secs(3),
19054 "drain took {elapsed:?} after the gauge fell at 600ms: {trace}"
19055 );
19056 let probes = drain.probes();
19057 assert!(
19058 probes.len() >= 2 && trace.probes as usize == probes.len(),
19059 "the drain must re-probe after the first busy answer: {probes:?}, {trace}"
19060 );
19061 }
19062
19063 #[tokio::test(start_paused = true)]
19064 async fn busy_throughout_ends_undrained_at_the_ceiling_with_bounded_probes() {
19065 let started = Instant::now();
19066 let drain = Drain::start(Answer::BusyUntil {
19067 until: started + Duration::from_secs(3600),
19068 latency: Duration::ZERO,
19069 });
19070 let (drained, elapsed) = drain.run(CEILING).await;
19071 assert!(!drained, "a module busy throughout must not drain");
19072 assert!(
19073 elapsed >= CEILING && elapsed < CEILING + drain_busy_reprobe_interval(),
19074 "a busy module is held until the ceiling and no longer: {elapsed:?}"
19075 );
19076 let probes = drain.probes();
19079 let max_probes = (CEILING.as_millis() / drain_busy_reprobe_interval().as_millis()) + 1;
19080 assert!(
19081 probes.len() as u128 <= max_probes,
19082 "{} probes in a {CEILING:?} drain exceeds the {max_probes} the interval allows",
19083 probes.len()
19084 );
19085 for pair in probes.windows(2) {
19086 assert!(
19087 pair[1] - pair[0] >= drain_busy_reprobe_interval(),
19088 "consecutive probes {:?} apart",
19089 pair[1] - pair[0]
19090 );
19091 }
19092 }
19093
19094 #[tokio::test(start_paused = true)]
19095 async fn a_slow_probe_is_never_overlapped_by_the_next() {
19096 let latency = Duration::from_secs(1);
19099 let drain = Drain::start(Answer::BusyUntil {
19100 until: Instant::now() + Duration::from_secs(3600),
19101 latency,
19102 });
19103 let (drained, _) = drain.run(Duration::from_secs(5)).await;
19104 assert!(!drained);
19105 let probes = drain.probes();
19106 assert!(probes.len() >= 2, "the drain must re-probe: {probes:?}");
19107 for pair in probes.windows(2) {
19108 assert!(
19109 pair[1] - pair[0] >= latency + drain_busy_reprobe_interval(),
19110 "a probe started {:?} after the previous one, before it could finish",
19111 pair[1] - pair[0]
19112 );
19113 }
19114 }
19115
19116 #[tokio::test(start_paused = true)]
19117 async fn an_unanswered_probe_cannot_hold_the_drain_past_its_ceiling() {
19118 let drain = Drain::start(Answer::Silent);
19119 let ceiling = Duration::from_secs(2);
19120 let (drained, elapsed) = drain.run(ceiling).await;
19121 assert!(!drained, "an unanswered probe counts as busy");
19122 assert!(
19123 elapsed >= ceiling && elapsed < ceiling + drain_busy_reprobe_interval(),
19124 "the probe deadline is capped at the drain ceiling: {elapsed:?}"
19125 );
19126 assert_eq!(
19127 drain.probes().len(),
19128 1,
19129 "the unanswered probe holds the only slot until the ceiling"
19130 );
19131 }
19132
19133 #[derive(Clone, Default)]
19135 struct LogCapture {
19136 events: Arc<StdMutex<Vec<BTreeMap<String, String>>>>,
19137 }
19138
19139 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for LogCapture {
19140 fn on_event(
19141 &self,
19142 event: &tracing::Event<'_>,
19143 _context: tracing_subscriber::layer::Context<'_, S>,
19144 ) {
19145 struct Fields(BTreeMap<String, String>);
19146 impl tracing::field::Visit for Fields {
19147 fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
19148 self.0
19149 .insert(field.name().to_string(), format!("{value:?}"));
19150 }
19151 }
19152 let mut fields = Fields(BTreeMap::new());
19153 event.record(&mut fields);
19154 self.events.lock().unwrap().push(fields.0);
19155 }
19156 }
19157
19158 impl LogCapture {
19159 fn install(&self) -> tracing::subscriber::DefaultGuard {
19160 use tracing_subscriber::layer::SubscriberExt;
19161 tracing::subscriber::set_default(tracing_subscriber::registry().with(self.clone()))
19162 }
19163
19164 fn with_message(&self, needle: &str) -> Vec<BTreeMap<String, String>> {
19165 self.events
19166 .lock()
19167 .unwrap()
19168 .iter()
19169 .filter(|fields| fields.get("message").is_some_and(|m| m.contains(needle)))
19170 .cloned()
19171 .collect()
19172 }
19173 }
19174
19175 #[tokio::test(start_paused = true)]
19180 async fn a_missing_declared_gauge_is_named_on_the_drain_timeout_line() {
19181 let capture = LogCapture::default();
19182 let _guard = capture.install();
19183 let drain = Drain::start(Answer::OmitsGauge);
19184 let (drained, _, trace) = drain.run_traced(Duration::from_secs(2)).await;
19185 assert!(!drained, "a gauge never reported cannot read quiet");
19186 assert!(trace.probes >= 2, "the drain must re-probe: {trace:?}");
19187
19188 let missing = capture.with_message("lacks a declared busy gauge");
19189 assert_eq!(missing.len(), 1, "one warning per drain: {missing:?}");
19190 assert_eq!(
19191 missing[0].get("missing_gauges").map(String::as_str),
19192 Some(GAUGE)
19193 );
19194
19195 warn_drain_timed_out(
19196 MODULE_ID,
19197 Duration::from_secs(2),
19198 RouteCloseReason::Restart,
19199 &Default::default(),
19200 &trace,
19201 );
19202 let timeouts = capture.with_message("route drain timed out");
19203 assert_eq!(timeouts.len(), 1, "{timeouts:?}");
19204 let gauges = &timeouts[0]["busy_gauges"];
19205 assert!(
19206 gauges.starts_with(&format!("{GAUGE}: missing_from_health_body @")),
19207 "the timeout line must name the gauge and why it read busy: {gauges}"
19208 );
19209 assert!(
19210 gauges.ends_with("; no value ever read"),
19211 "no value was ever read for the gauge: {gauges}"
19212 );
19213 assert_eq!(timeouts[0]["gauge_probes"], trace.probes.to_string());
19214 }
19215
19216 #[tokio::test(start_paused = true)]
19220 async fn the_drain_trace_names_a_busy_value_and_an_unanswered_probe() {
19221 let busy = Drain::start(Answer::BusyUntil {
19222 until: Instant::now() + Duration::from_secs(3600),
19223 latency: Duration::ZERO,
19224 });
19225 let (_, _, trace) = busy.run_traced(Duration::from_secs(1)).await;
19226 let rendered = trace.to_string();
19227 assert!(
19228 rendered.starts_with(&format!("{GAUGE}: non_zero(1) @"))
19229 && rendered.contains("; last value non_zero(1) @"),
19230 "{rendered}"
19231 );
19232
19233 let silent = Drain::start(Answer::Silent);
19234 let (_, _, trace) = silent.run_traced(Duration::from_secs(1)).await;
19235 assert_eq!(
19238 trace.to_string(),
19239 format!("{GAUGE}: probe_failed(no-answer) @1000ms; no value ever read")
19240 );
19241 assert_eq!(trace.probes, 1);
19242 }
19243
19244 #[test]
19246 fn a_gauge_that_is_not_a_count_is_busy_and_shown_as_sent() {
19247 let gauges = [GAUGE.to_string()];
19248 let verdicts = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0.0 })), &gauges);
19249 assert_eq!(verdicts, vec![GaugeVerdict::NotACount("0.0".to_string())]);
19250 assert_eq!(
19251 busy_gauge_observation(&verdicts),
19252 BusyGaugeObservation::Busy
19253 );
19254 let zero = gauge_verdicts(Some(&serde_json::json!({ GAUGE: 0 })), &gauges);
19255 assert_eq!(
19256 busy_gauge_observation(&zero),
19257 BusyGaugeObservation::Quiescent
19258 );
19259 let none = gauge_verdicts(None, &gauges);
19260 assert_eq!(busy_gauge_observation(&none), BusyGaugeObservation::Omitted);
19261 }
19262}
19263
19264#[cfg(test)]
19265mod health_evidence_tests {
19266 use super::{HealthProbeError, HealthProbeEvidence};
19267 use std::collections::HashSet;
19268
19269 #[test]
19277 fn only_a_dead_lane_is_proof_of_death() {
19278 assert!(HealthProbeError::lane_dead("gone").is_proof_of_death());
19279 assert!(!HealthProbeError::no_answer("timed out").is_proof_of_death());
19283 assert!(!HealthProbeError::bad_answer("garbage").is_proof_of_death());
19284 assert!(!HealthProbeError::misconfigured("no table").is_proof_of_death());
19285 }
19286
19287 #[test]
19293 fn every_evidence_class_has_a_distinct_label() {
19294 let labels = [
19295 HealthProbeError::lane_dead("").label(),
19296 HealthProbeError::no_answer("").label(),
19297 HealthProbeError::bad_answer("").label(),
19298 HealthProbeError::misconfigured("").label(),
19299 ];
19300 let unique: HashSet<_> = labels.iter().collect();
19301 assert_eq!(unique.len(), labels.len(), "labels collided: {labels:?}");
19302 }
19303
19304 #[test]
19310 fn classification_preserves_the_original_message() {
19311 let err = HealthProbeError::no_answer("module did not answer within 5s");
19312 assert_eq!(err.to_string(), "module did not answer within 5s");
19313 assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19314 }
19315}
19316
19317#[cfg(test)]
19318mod health_tombstone_tests {
19319 use std::{path::PathBuf, sync::Arc, time::Duration};
19320
19321 use subc_protocol::{
19322 manifest::Concurrency,
19323 session::{HealthStatus, ModuleControlResponse},
19324 };
19325 use tokio::sync::mpsc;
19326
19327 use super::{
19328 probe_module_health, HealthAction, HealthConfig, HealthProbeEvidence, ModuleProtocol,
19329 ModuleSpec, RestartPolicy, Supervisor, SupervisorRuntimeConfig,
19330 };
19331 use crate::{
19332 control::ControlHandler,
19333 forwarding::{ForwardingTable, ModuleControlRpcCompletion, ModuleControlRpcOutcome},
19334 registry::{ConnectionId, Registry},
19335 router::FrameSink,
19336 };
19337
19338 struct ProbeHarness {
19339 spec: ModuleSpec,
19340 runtime: SupervisorRuntimeConfig,
19341 forwarding: Arc<ForwardingTable>,
19342 module_connection: ConnectionId,
19343 module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19344 handler: ControlHandler,
19345 module: super::SupervisedModule,
19346 }
19347
19348 fn probe_harness() -> ProbeHarness {
19349 let registry = Arc::new(Registry::default());
19350 let forwarding = Arc::new(ForwardingTable::default());
19351 let supervisor_handle = super::SupervisorHandle::new();
19352 let health = HealthConfig {
19353 http: None,
19354 cadence: Duration::from_secs(30),
19355 deadline: Duration::from_secs(5),
19356 failure_threshold: 3,
19357 on_degraded: HealthAction::Report,
19358 on_failing: HealthAction::Report,
19359 critical: false,
19360 };
19361 let supervisor = Supervisor::new_for_test(Arc::clone(®istry), RestartPolicy::default())
19362 .with_forwarding(Arc::clone(&forwarding))
19363 .with_handle(supervisor_handle.clone())
19364 .with_health_config(health);
19365 let spec = ModuleSpec {
19366 script: None,
19367 module_id: "late-health-module".to_string(),
19368 program: PathBuf::from("disabled-module"),
19369 args: Vec::new(),
19370 env: Vec::new(),
19371 reserved: false,
19372 reserved_prefixes: Vec::new(),
19373 protocol: ModuleProtocol::Subc,
19374 overlap: Default::default(),
19375 carry_containment: false,
19376 };
19377 let module = supervisor
19378 .supervise_configured(spec.clone(), false)
19379 .unwrap();
19380 let runtime = supervisor.runtime_config();
19381 let handler = ControlHandler::with_forwarding(registry, Arc::clone(&forwarding))
19382 .with_supervisor(supervisor_handle);
19383 let module_connection = ConnectionId::new(700);
19384 let (module_tx, module_rx) = mpsc::channel(8);
19385 forwarding
19386 .register_module_connection(
19387 module_connection,
19388 spec.module_id.clone(),
19389 subc_protocol::PROTOCOL_VERSION,
19390 Concurrency::ModuleManaged,
19391 FrameSink::new(module_tx),
19392 )
19393 .unwrap();
19394
19395 ProbeHarness {
19396 spec,
19397 runtime,
19398 forwarding,
19399 module_connection,
19400 module_rx,
19401 handler,
19402 module,
19403 }
19404 }
19405
19406 async fn finish_after(
19407 harness: &mut ProbeHarness,
19408 stall: Duration,
19409 ) -> ModuleControlRpcCompletion {
19410 assert!(stall > harness.runtime.health.deadline);
19411 let deadline = harness.runtime.health.deadline;
19412 let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19413 let answer = async {
19414 let frame = harness.module_rx.recv().await.expect("health.check frame");
19415 tokio::time::advance(deadline).await;
19416 tokio::task::yield_now().await;
19417 tokio::time::advance(stall - deadline).await;
19418 harness
19419 .forwarding
19420 .complete_module_control_rpc(
19421 harness.module_connection,
19422 frame.header.corr,
19423 Some("health.check"),
19424 ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19425 status: HealthStatus::Ok,
19426 detail: None,
19427 metrics: None,
19428 }),
19429 )
19430 .unwrap()
19431 };
19432 let (probe_result, completion) = tokio::join!(probe, answer);
19433 let err = probe_result.expect_err("probe must miss its deadline");
19434 assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19435 completion
19436 }
19437
19438 async fn time_out_without_answer(harness: &mut ProbeHarness) {
19439 let deadline = harness.runtime.health.deadline;
19440 let probe = probe_module_health(&harness.spec.module_id, &harness.runtime, None);
19441 let exhaust_deadline = async {
19442 let _frame = harness.module_rx.recv().await.expect("health.check frame");
19443 tokio::time::advance(deadline).await;
19444 tokio::task::yield_now().await;
19445 };
19446 let (probe_result, ()) = tokio::join!(probe, exhaust_deadline);
19447 let err = probe_result.expect_err("probe must miss its deadline");
19448 assert!(matches!(err.evidence, HealthProbeEvidence::NoAnswer));
19449 }
19450
19451 async fn run_probe_cycle(harness: &mut ProbeHarness, answer: bool) {
19452 let registry = Arc::clone(&harness.module.inner.registry);
19453 let snapshot = Arc::clone(&harness.module.inner.snapshot);
19454 let process_liveness = super::SupervisorProcessLiveness::default();
19455 let mut child = None;
19456 let cycle = super::run_health_probe_cycle(
19457 &harness.spec,
19458 &harness.runtime,
19459 ®istry,
19460 &process_liveness,
19461 &snapshot,
19462 &mut child,
19463 );
19464 let peer = async {
19465 let frame = harness.module_rx.recv().await.expect("health.check frame");
19466 if answer {
19467 harness
19468 .forwarding
19469 .complete_module_control_rpc(
19470 harness.module_connection,
19471 frame.header.corr,
19472 Some("health.check"),
19473 ModuleControlRpcOutcome::Response(ModuleControlResponse::HealthCheck {
19474 status: HealthStatus::Ok,
19475 detail: None,
19476 metrics: Some(serde_json::json!({"ready": true})),
19477 }),
19478 )
19479 .unwrap();
19480 } else {
19481 tokio::time::advance(harness.runtime.health.deadline).await;
19482 tokio::task::yield_now().await;
19483 }
19484 };
19485 tokio::join!(cycle, peer);
19486 }
19487
19488 #[tokio::test(start_paused = true)]
19489 async fn unanswered_probe_is_unknown_until_threshold_and_ok_report_recovers() {
19490 let mut harness = probe_harness();
19491 let monitor = harness.module.inner.monitor.lock().unwrap().take().unwrap();
19495 monitor.abort();
19496 let _ = monitor.await;
19497 super::update_snapshot(&harness.module.inner.snapshot, None, |state| {
19498 state.enabled = true;
19499 state.state = super::ModuleState::Running;
19500 state.process_alive = true;
19501 })
19502 .unwrap();
19503
19504 run_probe_cycle(&mut harness, true).await;
19505 assert_eq!(
19506 harness.module.status().unwrap().health.status,
19507 super::SupervisorHealthStatus::Ok
19508 );
19509
19510 for failures in 1..harness.runtime.health.failure_threshold {
19511 run_probe_cycle(&mut harness, false).await;
19512 let status = harness.module.status().unwrap();
19513 assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19514 assert_eq!(status.health.consecutive_failures, failures);
19515 assert!(status.health.last_probe_ms.is_some());
19516 assert!(status.health.detail.unwrap().starts_with("[no-answer]"));
19517 assert!(status.health.metrics.is_none());
19518 assert_eq!(status.state, super::ModuleState::Running);
19519 assert!(status.process_alive);
19520 assert_eq!(status.restart_count, 0);
19521 assert_eq!(status.lifetime_restarts, 0);
19522 assert!(status.health.last_action.is_none());
19523 assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19524 }
19525
19526 run_probe_cycle(&mut harness, true).await;
19527 let recovered = harness.module.status().unwrap();
19528 assert_eq!(recovered.health.status, super::SupervisorHealthStatus::Ok);
19529 assert_eq!(recovered.health.consecutive_failures, 0);
19530 assert!(recovered.health.detail.is_none());
19531 assert_eq!(
19532 recovered.health.metrics,
19533 Some(serde_json::json!({"ready": true}))
19534 );
19535 assert_eq!(recovered.lifetime_restarts, 0);
19536
19537 for failures in 1..=harness.runtime.health.failure_threshold {
19538 run_probe_cycle(&mut harness, false).await;
19539 let status = harness.module.status().unwrap();
19540 assert_eq!(status.health.consecutive_failures, failures);
19541 if failures < harness.runtime.health.failure_threshold {
19542 assert_eq!(status.health.status, super::SupervisorHealthStatus::Unknown);
19543 assert_eq!(status.state, super::ModuleState::Running);
19544 assert_eq!(status.lifetime_restarts, 0);
19545 assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_none());
19546 } else {
19547 assert_eq!(
19548 status.health.status,
19549 super::SupervisorHealthStatus::Unresponsive
19550 );
19551 assert_eq!(status.state, super::ModuleState::Restarting);
19552 assert_eq!((status.restart_count, status.lifetime_restarts), (0, 0));
19554 assert_eq!(status.health.last_action.as_deref(), Some("restart"));
19555 assert!(harness.runtime.scheduled_respawn.lock().unwrap().is_some());
19556 }
19557 }
19558 }
19559
19560 #[tokio::test(start_paused = true)]
19561 async fn late_health_answers_record_start_anchored_latency_for_two_stalls() {
19562 let mut harness = probe_harness();
19563
19564 let first = finish_after(&mut harness, Duration::from_secs(8)).await;
19565 let first_latency = match &first {
19566 ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19567 other => panic!("late answer was not retained: {other:?}"),
19568 };
19569 assert!(harness.handler.observe_module_control_completion(first));
19570
19571 let second = finish_after(&mut harness, Duration::from_secs(11)).await;
19572 let second_latency = match &second {
19573 ModuleControlRpcCompletion::LateHealthAnswer { latency, .. } => *latency,
19574 other => panic!("late answer was not retained: {other:?}"),
19575 };
19576 assert!(harness.handler.observe_module_control_completion(second));
19577
19578 assert_eq!(first_latency, Duration::from_secs(8));
19579 assert_eq!(
19580 second_latency - first_latency,
19581 Duration::from_secs(3),
19582 "latency must grow linearly with the additional stall"
19583 );
19584 let health = harness.module.status().unwrap().health;
19585 assert_eq!(health.late_answer_count, 2);
19586 assert_eq!(health.last_late_answer_latency_ms, Some(11_000));
19587 }
19588
19589 #[tokio::test(start_paused = true)]
19597 async fn late_answer_clears_the_consecutive_failure_streak() {
19598 let mut harness = probe_harness();
19599
19600 time_out_without_answer(&mut harness).await;
19602 harness
19603 .module
19604 .record_health_probe_failure_for_test("[no-answer] test miss")
19605 .unwrap();
19606 assert_eq!(
19607 harness.module.status().unwrap().health.consecutive_failures,
19608 1,
19609 "precondition: the miss must be on the streak before the late answer"
19610 );
19611
19612 let late = finish_after(&mut harness, Duration::from_secs(9)).await;
19614 assert!(matches!(
19615 late,
19616 ModuleControlRpcCompletion::LateHealthAnswer { .. }
19617 ));
19618 assert!(harness.handler.observe_module_control_completion(late));
19619
19620 let health = harness.module.status().unwrap().health;
19621 assert_eq!(
19622 health.consecutive_failures, 0,
19623 "a late answer is an answer: the streak must reset"
19624 );
19625 assert_eq!(health.late_answer_count, 1);
19626 }
19627
19628 #[tokio::test(start_paused = true)]
19629 async fn repeated_serial_probe_cycles_keep_one_tombstone_per_endpoint() {
19630 let mut harness = probe_harness();
19631
19632 for _ in 0..20 {
19633 time_out_without_answer(&mut harness).await;
19634 assert_eq!(
19635 harness.forwarding.health_probe_tombstone_count().unwrap(),
19636 1
19637 );
19638 }
19639 }
19640}
19641
19642#[cfg(test)]
19643mod child_env_tests {
19644 #[cfg(windows)]
19645 use super::{
19646 clear_current_process_facts, observed_launch_nonce_source, ModuleState, SupervisorSnapshot,
19647 };
19648 #[cfg(windows)]
19649 use std::sync::{Arc, OnceLock};
19650 #[cfg(windows)]
19651 #[test]
19652 fn windows_wire_spawn_prepares_pipe_and_keeps_phase_one_env() {
19653 let spec = spec(Vec::new());
19654 let mut command = Command::new("unused");
19655 let handoff = apply_wire_spawn_args(&mut command, &spec, None, None)
19656 .unwrap()
19657 .unwrap();
19658 let name = command
19659 .as_std()
19660 .get_envs()
19661 .find(|(key, _)| *key == OsStr::new(subc_os::launch_nonce::LAUNCH_NONCE_PIPE_ENV))
19662 .and_then(|(_, value)| value)
19663 .unwrap();
19664 assert_eq!(name, OsStr::new(handoff.name()));
19665 assert!(handoff.name().starts_with(r"\\.\pipe\subc-launch-"));
19666 assert!(command.as_std().get_envs().any(|(key, value)| key
19667 == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
19668 && value == Some(OsStr::new("env"))));
19669 assert!(command
19670 .as_std()
19671 .get_envs()
19672 .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()));
19673 }
19674
19675 #[cfg(windows)]
19676 #[test]
19677 fn windows_source_reporting_tracks_consumption_and_resets_per_spawn() {
19678 let mut snapshot = SupervisorSnapshot::new(ModuleState::Running, true);
19679 snapshot.process_alive = true;
19680 snapshot.spawned_protocol = Some(ModuleProtocol::Subc);
19681 assert_eq!(
19682 observed_launch_nonce_source(&snapshot).as_deref(),
19683 Some("env")
19684 );
19685 let consumed = Arc::new(OnceLock::new());
19686 snapshot.pipe_consumed = Some(consumed.clone());
19687 assert_eq!(
19688 observed_launch_nonce_source(&snapshot).as_deref(),
19689 Some("env")
19690 );
19691 consumed.set(()).unwrap();
19692 assert_eq!(
19693 observed_launch_nonce_source(&snapshot).as_deref(),
19694 Some("pipe")
19695 );
19696 snapshot.pipe_consumed = Some(Arc::new(OnceLock::new()));
19697 assert_eq!(
19698 observed_launch_nonce_source(&snapshot).as_deref(),
19699 Some("env")
19700 );
19701 clear_current_process_facts(&mut snapshot);
19702 assert_eq!(observed_launch_nonce_source(&snapshot), None);
19703 }
19704 use super::{
19705 apply_child_env, apply_spawn_role, apply_wire_spawn_args, LaunchSpecDigest, ModuleProtocol,
19706 ModuleSpec, SpawnRole, SupervisorHandle, SPAWN_ROLE_SWAP_CANDIDATE, SUBC_ARG,
19707 SUBC_LAUNCH_NONCE_ENV, SUBC_MODULE_ID_ENV, SUBC_SPAWN_ROLE_ENV,
19708 };
19709 use std::{ffi::OsStr, path::PathBuf};
19710 use tokio::process::Command;
19711
19712 fn spec(env: Vec<(String, String)>) -> ModuleSpec {
19713 ModuleSpec {
19714 script: None,
19715 module_id: "env-plan".to_string(),
19716 program: PathBuf::from("/nonexistent"),
19717 args: Vec::new(),
19718 env,
19719 reserved: false,
19720 reserved_prefixes: Vec::new(),
19721 protocol: ModuleProtocol::Subc,
19722 overlap: Default::default(),
19723 carry_containment: false,
19724 }
19725 }
19726
19727 #[test]
19728 fn configured_launch_spec_digest_is_canonical_and_excludes_injected_inputs() {
19729 let base = spec(vec![("A".into(), "B=C".into()), ("Z".into(), "v".into())]);
19730 let digest = LaunchSpecDigest::from_spec(&base);
19731 let mut reordered = base.clone();
19732 reordered.env.reverse();
19733 reordered.module_id = "different-id".into();
19734 reordered.reserved = true;
19735 reordered.overlap = Default::default();
19736 assert_eq!(digest, LaunchSpecDigest::from_spec(&reordered));
19737 let mut delimiter_collision = base.clone();
19738 delimiter_collision.env[0] = ("A=B".into(), "C".into());
19739 assert_ne!(digest, LaunchSpecDigest::from_spec(&delimiter_collision));
19740 let mut changed = base.clone();
19741 changed.protocol = ModuleProtocol::None;
19742 assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19743 changed = base.clone();
19744 changed.args.push("--flag".into());
19745 assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19746 changed = base.clone();
19747 changed.program = PathBuf::from("/other");
19748 assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19749 changed = base.clone();
19750 changed.env[1].1 = "other".into();
19751 assert_ne!(digest, LaunchSpecDigest::from_spec(&changed));
19752 assert!(!format!("{digest:?}").contains("B=C"));
19753 assert!(!format!("{digest:?}").contains("[u8"));
19754 }
19755
19756 #[cfg(unix)]
19757 #[test]
19758 fn native_program_bytes_do_not_collapse_through_lossy_utf8() {
19759 use std::os::unix::ffi::OsStringExt;
19760 let mut left = spec(Vec::new());
19761 left.program = std::ffi::OsString::from_vec(vec![b'/', 0xff]).into();
19762 let mut right = left.clone();
19763 right.program = std::ffi::OsString::from_vec(vec![b'/', 0xfe]).into();
19764 assert_eq!(
19765 left.program.to_string_lossy(),
19766 right.program.to_string_lossy()
19767 );
19768 assert_ne!(
19769 LaunchSpecDigest::from_spec(&left),
19770 LaunchSpecDigest::from_spec(&right)
19771 );
19772 }
19773
19774 #[test]
19788 fn ambient_ck_log_is_removed_and_a_configured_one_survives() {
19789 let mut command = Command::new("/nonexistent");
19790 apply_child_env(&mut command, &spec(Vec::new()));
19791 let removed = command
19792 .as_std()
19793 .get_envs()
19794 .any(|(key, value)| key == OsStr::new("CK_LOG") && value.is_none());
19795 assert!(
19796 removed,
19797 "ambient CK_LOG must be explicitly removed for an unconfigured module"
19798 );
19799
19800 let mut configured = Command::new("/nonexistent");
19801 apply_child_env(
19802 &mut configured,
19803 &spec(vec![("CK_LOG".to_string(), "debug".to_string())]),
19804 );
19805 let effective = configured
19806 .as_std()
19807 .get_envs()
19808 .filter(|(key, _)| *key == OsStr::new("CK_LOG"))
19809 .last()
19810 .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
19811 assert_eq!(
19812 effective,
19813 Some(Some("debug".to_string())),
19814 "a module's configured CK_LOG must survive the ambient removal"
19815 );
19816 }
19817
19818 #[test]
19827 fn protocol_none_spawn_carries_no_subc_argument_and_no_nonce() {
19828 let connection_file = std::path::Path::new("/run/subc-connection.json");
19829 let handle = SupervisorHandle::new();
19830
19831 let mut none_spec = spec(Vec::new());
19832 none_spec.protocol = ModuleProtocol::None;
19833 let mut none = Command::new("/nonexistent");
19834 let none_handoff =
19835 apply_wire_spawn_args(&mut none, &none_spec, Some(connection_file), Some(&handle))
19836 .expect("protocol-none spawn args apply");
19837 assert!(
19838 none_handoff.is_none(),
19839 "protocol:none spawn must not receive a nonce descriptor"
19840 );
19841 #[cfg(windows)]
19842 assert!(!none.as_std().get_envs().any(|(key, value)| key
19843 == OsStr::new(subc_os::LAUNCH_NONCE_PIPE_FALLBACK_ENV)
19844 && value.is_some()));
19845 assert!(
19846 !none.as_std().get_envs().any(|(key, value)| key
19847 == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV)
19848 && value.is_some()),
19849 "protocol:none spawn must not name a nonce descriptor"
19850 );
19851 let none_args: Vec<String> = none
19852 .as_std()
19853 .get_args()
19854 .map(|a| a.to_string_lossy().into_owned())
19855 .collect();
19856 assert!(
19857 !none_args.iter().any(|a| a == SUBC_ARG),
19858 "protocol:none argv must not carry --subc; got {none_args:?}"
19859 );
19860 let none_has_nonce = none
19861 .as_std()
19862 .get_envs()
19863 .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some());
19864 assert!(
19865 !none_has_nonce,
19866 "protocol:none spawn must not receive a launch nonce"
19867 );
19868 let none_has_module_id = none
19869 .as_std()
19870 .get_envs()
19871 .any(|(key, value)| key == OsStr::new(SUBC_MODULE_ID_ENV) && value.is_some());
19872 assert!(
19873 none_has_module_id,
19874 "SUBC_MODULE_ID is inert and stays on every path"
19875 );
19876 assert!(
19877 handle.spawn_nonce(&none_spec.module_id).is_none(),
19878 "no nonce record for a process that will never present one"
19879 );
19880
19881 let wire_spec = spec(Vec::new());
19883 let mut wire = Command::new("/nonexistent");
19884 let wire_handoff =
19885 apply_wire_spawn_args(&mut wire, &wire_spec, Some(connection_file), Some(&handle))
19886 .expect("subc-wire spawn args apply");
19887 let wire_fd_env = wire
19888 .as_std()
19889 .get_envs()
19890 .find(|(key, _)| *key == OsStr::new(subc_os::LAUNCH_NONCE_FD_ENV))
19891 .and_then(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()));
19892 #[cfg(unix)]
19893 assert_eq!(
19894 wire_fd_env,
19895 Some(wire_handoff.expect("a descriptor handoff").fd_env_value()),
19896 "a subc-wire spawn names the pipe it will receive at descriptor 3"
19897 );
19898 #[cfg(windows)]
19899 assert!(wire_handoff.is_some() && wire_fd_env.is_none());
19900 #[cfg(not(any(unix, windows)))]
19901 assert!(wire_handoff.is_none() && wire_fd_env.is_none());
19902 let wire_args: Vec<String> = wire
19903 .as_std()
19904 .get_args()
19905 .map(|a| a.to_string_lossy().into_owned())
19906 .collect();
19907 assert_eq!(
19908 wire_args,
19909 vec![
19910 SUBC_ARG.to_string(),
19911 connection_file.to_string_lossy().into_owned()
19912 ],
19913 "a subc-wire spawn still carries --subc <path>"
19914 );
19915 assert_eq!(
19916 wire.as_std()
19917 .get_envs()
19918 .any(|(key, value)| key == OsStr::new(SUBC_LAUNCH_NONCE_ENV) && value.is_some()),
19919 !cfg!(unix),
19920 "only Windows supplies the environment nonce"
19921 );
19922 assert!(handle.spawn_nonce(&wire_spec.module_id).is_some());
19923 }
19924
19925 #[test]
19935 fn plain_spawn_removes_the_spawn_role_even_when_the_spec_sets_it() {
19936 let role = |command: &Command| {
19937 command
19938 .as_std()
19939 .get_envs()
19940 .filter(|(key, _)| *key == OsStr::new(SUBC_SPAWN_ROLE_ENV))
19941 .last()
19942 .map(|(_, value)| value.map(|v| v.to_string_lossy().into_owned()))
19943 };
19944 let forged = spec(vec![(
19945 SUBC_SPAWN_ROLE_ENV.to_string(),
19946 SPAWN_ROLE_SWAP_CANDIDATE.to_string(),
19947 )]);
19948
19949 let mut plain = Command::new("/nonexistent");
19950 apply_child_env(&mut plain, &forged);
19951 apply_spawn_role(&mut plain, SpawnRole::Plain);
19952 assert_eq!(
19953 role(&plain),
19954 Some(None),
19955 "a plain spawn must remove SUBC_SPAWN_ROLE, whatever the spec says"
19956 );
19957
19958 let mut candidate = Command::new("/nonexistent");
19959 apply_child_env(&mut candidate, &spec(Vec::new()));
19960 apply_spawn_role(&mut candidate, SpawnRole::SwapCandidate);
19961 assert_eq!(
19962 role(&candidate),
19963 Some(Some(SPAWN_ROLE_SWAP_CANDIDATE.to_string()))
19964 );
19965 }
19966
19967 #[test]
19973 fn daemon_private_capture_keys_are_not_passed_to_the_child() {
19974 let mut command = Command::new("/nonexistent");
19975 apply_child_env(
19976 &mut command,
19977 &spec(vec![
19978 (super::CAPTURE_KEEP_ENV.to_string(), "5".to_string()),
19979 ("KEPT".to_string(), "yes".to_string()),
19980 ]),
19981 );
19982 let keys: Vec<String> = command
19983 .as_std()
19984 .get_envs()
19985 .filter(|(_, value)| value.is_some())
19986 .map(|(key, _)| key.to_string_lossy().into_owned())
19987 .collect();
19988 assert!(keys.contains(&"KEPT".to_string()), "got {keys:?}");
19989 assert!(
19990 !keys.contains(&super::CAPTURE_KEEP_ENV.to_string()),
19991 "daemon-private capture key leaked to the child: {keys:?}"
19992 );
19993 }
19994}
19995
19996#[cfg(test)]
19997mod jitter_tests {
19998 use super::jittered_health_delay;
19999 use std::{collections::HashSet, time::Duration};
20000
20001 const FLEET: [&str; 14] = [
20010 "aft",
20011 "alfonso-core",
20012 "magic-context",
20013 "broca",
20014 "thalamus",
20015 "quota",
20016 "engram",
20017 "plexus",
20018 "cerebellum",
20019 "astrocyte",
20020 "synapse",
20021 "subc-mcp",
20022 "cortexkit-credentials",
20023 "subc-federation",
20024 ];
20025
20026 #[test]
20034 fn probe_delays_disperse_across_the_fleet() {
20035 let cadence = Duration::from_secs(30);
20036 let delays: HashSet<Duration> = FLEET
20037 .iter()
20038 .map(|id| jittered_health_delay(id, 0, cadence))
20039 .collect();
20040 assert_eq!(
20041 delays.len(),
20042 FLEET.len(),
20043 "every supervised module must land on its own probe offset"
20044 );
20045 }
20046
20047 #[test]
20053 fn jitter_only_delays_and_stays_within_one_tenth_of_cadence() {
20054 let cadence = Duration::from_secs(30);
20055 let span = cadence / 10;
20056 for id in FLEET {
20057 for probe_index in 0..8 {
20058 let delay = jittered_health_delay(id, probe_index, cadence);
20059 assert!(
20060 delay >= cadence,
20061 "{id}#{probe_index}: jitter must not shorten the cadence"
20062 );
20063 assert!(
20064 delay < cadence + span,
20065 "{id}#{probe_index}: jitter must stay inside one tenth of the cadence"
20066 );
20067 }
20068 }
20069 }
20070
20071 #[test]
20077 fn a_module_offset_is_stable_across_restarts() {
20078 let cadence = Duration::from_secs(30);
20079 for id in FLEET {
20080 assert_eq!(
20081 jittered_health_delay(id, 0, cadence),
20082 jittered_health_delay(id, 0, cadence),
20083 "{id}: the same module and probe index must produce the same offset"
20084 );
20085 }
20086 }
20087
20088 #[test]
20090 fn zero_cadence_yields_zero_delay() {
20091 assert_eq!(
20092 jittered_health_delay("aft", 0, Duration::ZERO),
20093 Duration::ZERO
20094 );
20095 }
20096}
20097
20098#[cfg(all(test, target_os = "linux"))]
20099mod cgroup_placement_tests {
20100 use super::{
20101 apply_cgroup_placement, remove_module_cgroup, LaunchSpecDigest, ModuleProtocol, ModuleSpec,
20102 SuperviseError, SupervisedChild,
20103 };
20104 use crate::stderr_tail::{StderrRing, StderrTailConfig};
20105 use cortexkit_test_support::ScratchDir;
20106 use std::{
20107 fs, io,
20108 path::{Path, PathBuf},
20109 sync::{Arc, Mutex},
20110 };
20111 use tokio::process::Command;
20112
20113 #[tokio::test]
20114 async fn unique_spawn_cgroups_clean_up_across_restarts_and_shutdown() {
20115 use super::*;
20116 let dir = ScratchDir::new("unique-spawn-cgroups");
20117 let root = PathBuf::from(format!(
20118 "/sys/fs/cgroup/subc-unique-test-{}-{}",
20119 std::process::id(),
20120 unix_ms_now()
20121 ));
20122 if let Err(error) = fs::create_dir(&root) {
20123 assert!(
20124 std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
20125 "required cgroup test cannot execute: {error}"
20126 );
20127 eprintln!("SKIP unique_spawn_cgroups_clean_up_across_restarts_and_shutdown: {error}");
20128 return;
20129 }
20130 let placement = subc_cgroup::prepare_at(&root).unwrap().unwrap();
20131 let group_count = || {
20132 fs::read_dir(root.join("subc-modules"))
20133 .unwrap()
20134 .map(|entry| entry.unwrap().file_type().unwrap())
20135 .filter(|kind| kind.is_dir())
20136 .count()
20137 };
20138 let supervisor =
20139 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
20140 .with_cgroup_placement(Some(placement.clone()));
20141 let runtime = supervisor.runtime_config();
20142 let mut spec = ModuleSpec {
20143 script: None,
20144 module_id: "unique-spawn".into(),
20145 program: PathBuf::from("/bin/sleep"),
20146 args: vec!["60".into()],
20147 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
20148 .into_iter()
20149 .map(|key| (key.into(), dir.to_string_lossy().into_owned()))
20150 .collect(),
20151 reserved: false,
20152 reserved_prefixes: vec![],
20153 protocol: ModuleProtocol::None,
20154 overlap: Default::default(),
20155 carry_containment: false,
20156 };
20157 let spawn = |spec: &ModuleSpec| {
20158 spawn_child(
20159 spec,
20160 None,
20161 None,
20162 &runtime.stderr_ring,
20163 None,
20164 &runtime.child_roster,
20165 runtime.spawn_delivery(),
20166 Some(&placement),
20167 runtime.register_timeout,
20168 )
20169 .unwrap()
20170 };
20171 let mut live = spawn(&spec);
20172 for _ in 0..3 {
20173 let next = spawn(&spec);
20175 assert_ne!(live.module_id, next.module_id);
20176 live.start_kill().unwrap();
20177 live.wait().await.unwrap();
20178 live.finish_exit(false).await.unwrap();
20179 live = next;
20180 assert!(
20181 live.child.try_wait().unwrap().is_none(),
20182 "retiring the old slot must not kill the replacement"
20183 );
20184 assert_eq!(
20185 group_count(),
20186 1,
20187 "only the live spawn's cgroup should remain"
20188 );
20189 }
20190 supervisor.begin_daemon_shutdown();
20191 let reap = tokio::spawn(async move {
20192 live.wait().await.unwrap();
20193 live.finish_exit(false).await.unwrap();
20194 });
20195 supervisor
20196 .end_children_for_daemon_shutdown(false, std::future::pending())
20197 .await;
20198 reap.await.unwrap();
20199 assert_eq!(group_count(), 0);
20200 spec.program = PathBuf::from("/bin/true");
20202 spec.args.clear();
20203 let fresh_roster = ChildRoster::default();
20204 let mut short = spawn_child(
20205 &spec,
20206 None,
20207 None,
20208 &runtime.stderr_ring,
20209 None,
20210 &fresh_roster,
20211 None,
20212 Some(&placement),
20213 runtime.register_timeout,
20214 )
20215 .unwrap();
20216 short.wait().await.unwrap();
20217 short.finish_exit(false).await.unwrap();
20218 assert_eq!(group_count(), 0);
20219 spec.module_id = "_".repeat(255);
20220 let mut long_id = spawn_child(
20221 &spec,
20222 None,
20223 None,
20224 &runtime.stderr_ring,
20225 None,
20226 &fresh_roster,
20227 None,
20228 Some(&placement),
20229 runtime.register_timeout,
20230 )
20231 .unwrap();
20232 long_id.wait().await.unwrap();
20233 long_id.finish_exit(false).await.unwrap();
20234 assert_eq!(
20235 group_count(),
20236 0,
20237 "valid long module IDs must not exceed cgroup NAME_MAX"
20238 );
20239 fs::remove_dir(root.join("subc-modules")).unwrap();
20240 fs::remove_dir(root).unwrap();
20241 eprintln!("EXECUTED unique_spawn_cgroups_clean_up_across_restarts_and_shutdown");
20242 }
20243
20244 #[test]
20245 fn failed_parent_cgroup_open_is_a_cgroup_supervision_error() {
20246 let path = Path::new("/definitely-missing-subc-cgroup");
20247 let mut command = Command::new("true");
20248 let error = apply_cgroup_placement(
20249 &mut command,
20250 &ModuleSpec {
20251 script: None,
20252 module_id: "broken-cgroup".to_string(),
20253 program: PathBuf::from("true"),
20254 args: Vec::new(),
20255 env: Vec::new(),
20256 reserved: false,
20257 reserved_prefixes: Vec::new(),
20258 protocol: ModuleProtocol::Subc,
20259 overlap: Default::default(),
20260 carry_containment: false,
20261 },
20262 path,
20263 )
20264 .expect_err("a parent cgroup open failure must reject the supervised spawn");
20265 let reason = error.to_string();
20266
20267 assert!(
20268 matches!(error, SuperviseError::Cgroup { .. }),
20269 "parent cgroup open must be reported as a cgroup supervision error: {reason}"
20270 );
20271 assert!(
20272 reason.contains("/definitely-missing-subc-cgroup/cgroup.procs"),
20273 "parent cgroup open failure must name cgroup.procs: {reason}"
20274 );
20275 }
20276
20277 #[tokio::test]
20278 async fn reaping_a_child_does_not_treat_missing_cgroup_events_as_empty() {
20279 let root = ScratchDir::new("supervisor-reap-cgroup");
20280 fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20281 let placement = subc_cgroup::prepare_at(&root)
20282 .expect("prepare scratch cgroup root")
20283 .expect("scratch root has a cgroup.procs marker");
20284 let module_id = "reaped-module";
20285 let module = placement
20286 .module_path(module_id)
20287 .expect("create scratch module cgroup");
20288 let child = Command::new("true")
20289 .env("XDG_DATA_HOME", root.path())
20290 .env("XDG_RUNTIME_DIR", root.path())
20291 .env("XDG_CONFIG_HOME", root.path())
20292 .spawn()
20293 .expect("spawn short-lived child");
20294 let pid = child.id().expect("spawned child has pid");
20295 let mut child = SupervisedChild {
20296 registration_channel: None,
20297 registration_spawn: None,
20298 live_program_binding: None,
20299 registered_config_connection: None,
20300 admission_base: None,
20301 registration_declaration: None,
20302 _program_binding: None,
20303 subtree_target: crate::subtree_resources::Target::Cgroup(module.clone()),
20304 child: crate::supervise::containment::ProcessChild::plain(child, pid),
20305 exec: crate::activity::ExecOwner(Arc::new(crate::activity::ExecOutcome::new())),
20306 protocol: ModuleProtocol::Subc,
20307 module_id: module_id.to_string(),
20308 cgroup_placement: Some(placement),
20309 unresolved_cgroup: None,
20310 stdout_pump: None,
20311 stderr_pump: None,
20312 capture_stop: None,
20313 late_output_lost: false,
20314 stderr_ring: Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default()))),
20315 spawned_at: tokio::time::Instant::now(),
20316 config_delivery: None,
20317 registration_deadline: None,
20318 registration_watch: None,
20319 spawned_at_ms: 0,
20320 spawned_from: PathBuf::from("true"),
20321 launch_spec_digest: LaunchSpecDigest([0; 32]),
20322 spawned_file_identity: None,
20323 process_start_time: None,
20324 process_identity: None,
20325 pid,
20326 roster_guard: None,
20327 #[cfg(target_os = "macos")]
20328 privacy_exec: None,
20329 spawn_failure: None,
20330 admission_kill_sent: false,
20331 };
20332
20333 child.wait().await.expect("reap short-lived child");
20334
20335 child.cleanup_ordinary_cgroup().await;
20336 assert!(module.is_dir());
20337 assert!(child
20338 .exit_cleanup_detail(None)
20339 .unwrap()
20340 .contains(&module.display().to_string()));
20341 child.finish_exit(false).await.unwrap();
20342 }
20343
20344 #[test]
20345 fn non_empty_cgroup_removal_is_reported_without_blocking_teardown() {
20346 let root = ScratchDir::new("supervisor-non-empty-cgroup");
20347 fs::write(root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
20348 let placement = subc_cgroup::prepare_at(&root)
20349 .expect("prepare scratch cgroup root")
20350 .expect("scratch root has a cgroup.procs marker");
20351 let module = placement
20352 .module_path("surviving-module")
20353 .expect("create scratch module cgroup");
20354 fs::write(module.join("surviving-process"), b"still present")
20355 .expect("make scratch cgroup non-empty");
20356 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
20357
20358 remove_module_cgroup(&placement, "surviving-module");
20359
20360 let logs = crate::router::test_log::captured_logs(&logs);
20361 assert!(
20362 module.exists(),
20363 "failed removal must leave the cgroup intact"
20364 );
20365 assert!(
20366 logs.contains("could not remove module cgroup after process exit; continuing teardown")
20367 && logs.contains("surviving-module"),
20368 "best-effort removal must report the failure without returning it: {logs}"
20369 );
20370 }
20371
20372 #[test]
20373 fn cgroup_pre_exec_spawn_failure_names_the_cgroup_path() {
20374 let cgroup_path = PathBuf::from("/sys/fs/cgroup/subc-modules/broken-module");
20375 let reason = SuperviseError::Spawn {
20376 program: PathBuf::from("/bin/true"),
20377 source: io::Error::from_raw_os_error(13),
20378 cgroup_path: Some(cgroup_path.clone()),
20379 }
20380 .to_string();
20381
20382 assert!(
20383 reason.contains(&cgroup_path.display().to_string()),
20384 "a pre_exec spawn failure must name the cgroup path: {reason}"
20385 );
20386 }
20387}
20388
20389#[cfg(test)]
20390mod spawn_subscriber_lag_tests {
20391 use super::*;
20392
20393 #[tokio::test]
20398 async fn lagged_spawn_subscriber_receives_a_terminal_lagged_error_after_its_queued_frames() {
20399 let feed = SpawnEventFeed::default();
20400 feed.configure_incarnation("lag-incarnation".to_string());
20401 let (tx, mut rx) = mpsc::channel(1);
20404 feed.subscribe(ConnectionId::new(1), 7, 1, None, FrameSink::new(tx))
20405 .expect("subscribe");
20406 let emitted = SPAWN_SUBSCRIBER_BUFFER + 16;
20407 for index in 0..emitted {
20408 feed.emit_spawned(&format!("lag-module-{index}"), None, 1000, 0);
20409 tokio::task::yield_now().await;
20412 }
20413 assert_eq!(
20414 feed.subscriber_count(),
20415 0,
20416 "the lagged subscriber must be removed"
20417 );
20418
20419 let mut data = Vec::new();
20420 let mut last = None;
20421 loop {
20422 let next = tokio::time::timeout(Duration::from_secs(5), rx.recv())
20423 .await
20424 .expect("the forwarder must finish once the subscriber is dropped");
20425 let Some(outbound) = next else { break };
20426 let frame = outbound.frame;
20427 if frame.header.ty == FrameType::StreamData {
20428 assert!(last.is_none(), "no data may follow the terminal frame");
20429 let event: SpawnEvent = serde_json::from_slice(&frame.body).unwrap();
20430 data.push(event.cursor.seq);
20431 } else {
20432 assert!(last.is_none(), "exactly one terminal frame");
20433 last = Some(frame);
20434 }
20435 }
20436 assert!(!data.is_empty(), "queued frames drain before the terminal");
20437 for pair in data.windows(2) {
20438 assert_eq!(
20439 pair[1],
20440 pair[0] + 1,
20441 "queued frames arrive dense and in order"
20442 );
20443 }
20444 let terminal = last.expect("a lagged subscriber must receive a terminal frame");
20445 assert_eq!(terminal.header.ty, FrameType::Error);
20446 assert_eq!(terminal.header.corr, 7);
20447 let body: subc_protocol::ErrorBody = serde_json::from_slice(&terminal.body).unwrap();
20448 assert_eq!(body.code, SPAWN_SUBSCRIBER_LAGGED_CODE);
20449 let detail = body.detail.expect("lagged error carries detail");
20450 assert_eq!(
20451 detail["first_undelivered_cursor"]["seq"],
20452 data.last().unwrap() + 1,
20453 "the named cursor is the first event the subscriber did not receive"
20454 );
20455 assert_eq!(
20456 detail["first_undelivered_cursor"]["daemon_incarnation"],
20457 "lag-incarnation"
20458 );
20459 }
20460}
20461
20462#[cfg(test)]
20463mod terminal_history_read_concurrency_tests {
20464 use super::*;
20465 use crate::terminal_journal::read_pause;
20466 use cortexkit_test_support::ScratchDir;
20467 use std::sync::mpsc as std_mpsc;
20468
20469 fn journaled_ring(
20470 journal: &Arc<crate::terminal_journal::TerminalJournal>,
20471 ) -> Arc<Mutex<TerminalRing>> {
20472 Arc::new(Mutex::new(
20473 TerminalRing::new(TerminalRingConfig::default(), 1)
20474 .with_journal(Some(Arc::clone(journal))),
20475 ))
20476 }
20477
20478 fn crash(at_ms: u64) -> ExitReport {
20479 ExitReport {
20480 kind: ExitKind::Crash,
20481 code: Some(1),
20482 signal: None,
20483 at_ms,
20484 }
20485 }
20486
20487 fn record_within(
20490 module_id: &'static str,
20491 ring: &Arc<Mutex<TerminalRing>>,
20492 at_ms: u64,
20493 bound: Duration,
20494 ) -> bool {
20495 let ring = Arc::clone(ring);
20496 let (done, done_rx) = std_mpsc::channel();
20497 std::thread::spawn(move || {
20498 record_terminal(
20499 module_id,
20500 &ring,
20501 &SpawnEventFeed::default(),
20502 &crash(at_ms),
20503 TerminalDisposition::Restarting,
20504 );
20505 let _ = done.send(());
20506 });
20507 done_rx.recv_timeout(bound).is_ok()
20508 }
20509
20510 #[test]
20515 fn exits_recorded_during_a_paused_history_read_are_not_blocked_or_half_merged() {
20516 let dir = ScratchDir::new("terminal-history-concurrent-read");
20517 let path = dir.join("terminals.jsonl");
20518 let journal = Arc::new(crate::terminal_journal::TerminalJournal::open(
20519 path.clone(),
20520 "daemon".into(),
20521 ));
20522 let reader_ring = journaled_ring(&journal);
20523 let other_ring = journaled_ring(&journal);
20524 assert!(record_within(
20525 "reader-module",
20526 &reader_ring,
20527 10,
20528 Duration::from_secs(5)
20529 ));
20530
20531 let (started, release) = read_pause::install(&path);
20532 let reading = {
20533 let ring = Arc::clone(&reader_ring);
20534 std::thread::spawn(move || durable_terminal_history_of(&ring, "reader-module"))
20535 };
20536 started
20537 .recv_timeout(Duration::from_secs(5))
20538 .expect("the history read reached its pause");
20539
20540 let bound = Duration::from_secs(1);
20541 assert!(
20542 record_within("other-module", &other_ring, 20, bound),
20543 "another module's exit waited on a history read (journal writer held)"
20544 );
20545 assert!(
20546 record_within("reader-module", &reader_ring, 30, bound),
20547 "the read module's own exit waited on its history read (ring held)"
20548 );
20549
20550 drop(release);
20551 let paused = reading.join().unwrap();
20552 assert_eq!(
20553 paused.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20554 vec![10],
20555 "an exit recorded after the read began lands in neither half of it"
20556 );
20557 assert_eq!(paused.journal_skipped_lines, 0);
20558 assert_eq!(paused.journal_read_errors, 0);
20559
20560 let after = durable_terminal_history_of(&reader_ring, "reader-module");
20561 assert_eq!(
20562 after.entries.iter().map(|e| e.at_ms).collect::<Vec<_>>(),
20563 vec![10, 30],
20564 "the next read merges ring and journal with no duplicate"
20565 );
20566 assert_eq!(after.journal_skipped_lines, 0);
20567 }
20568}
20569
20570#[cfg(test)]
20575mod stderr_settle_tests {
20576 use std::{
20577 future::Future,
20578 io,
20579 pin::Pin,
20580 sync::{Arc, Mutex},
20581 task::{Context, Poll},
20582 time::Duration,
20583 };
20584
20585 use tokio::{
20586 io::{AsyncRead, ReadBuf},
20587 sync::oneshot,
20588 time::Instant,
20589 };
20590
20591 use super::{settle_stderr_pump, settle_stdout_pump, StderrPump};
20592 use crate::stderr_tail::{
20593 pump_stderr_to, pump_stdout_to, split_capture_stamp, untimed, CaptureState,
20594 ChildOutputSink, OutputSink, StderrRing, StderrTailConfig, TailEntry,
20595 };
20596
20597 const BOUND: Duration = Duration::from_millis(250);
20598
20599 struct HeldReader {
20603 before: Option<Vec<u8>>,
20604 gate: Option<oneshot::Receiver<()>>,
20605 after: io::Cursor<Vec<u8>>,
20606 }
20607
20608 impl AsyncRead for HeldReader {
20609 fn poll_read(
20610 mut self: Pin<&mut Self>,
20611 cx: &mut Context<'_>,
20612 buf: &mut ReadBuf<'_>,
20613 ) -> Poll<io::Result<()>> {
20614 if let Some(bytes) = self.before.take() {
20615 buf.put_slice(&bytes);
20616 return Poll::Ready(Ok(()));
20617 }
20618 if let Some(gate) = self.gate.as_mut() {
20619 match Pin::new(gate).poll(cx) {
20620 Poll::Pending => return Poll::Pending,
20621 Poll::Ready(_) => self.gate = None,
20622 }
20623 }
20624 Pin::new(&mut self.after).poll_read(cx, buf)
20625 }
20626 }
20627
20628 struct DiscardSink;
20629
20630 impl OutputSink for DiscardSink {
20631 fn write_line(&mut self, _line: &[u8]) {}
20632 }
20633
20634 fn line(text: &str) -> TailEntry {
20635 TailEntry::Line {
20636 text: text.to_string(),
20637 truncated: false,
20638 at_ms: None,
20639 }
20640 }
20641
20642 fn lock(ring: &Arc<Mutex<StderrRing>>) -> std::sync::MutexGuard<'_, StderrRing> {
20643 ring.lock().unwrap()
20644 }
20645
20646 fn held_pump(
20650 ring: &Arc<Mutex<StderrRing>>,
20651 before: &str,
20652 after: &str,
20653 ) -> (StderrPump<tokio::task::JoinHandle<()>>, oneshot::Sender<()>) {
20654 let generation = lock(ring).begin_process();
20655 let (release, gate) = oneshot::channel();
20656 let reader = HeldReader {
20657 before: Some(before.as_bytes().to_vec()),
20658 gate: Some(gate),
20659 after: io::Cursor::new(after.as_bytes().to_vec()),
20660 };
20661 let task = tokio::spawn(pump_stderr_to(
20662 reader,
20663 Arc::clone(ring),
20664 generation,
20665 DiscardSink,
20666 ));
20667 (StderrPump { task, generation }, release)
20668 }
20669
20670 async fn wait_until(ring: &Arc<Mutex<StderrRing>>, done: impl Fn(&StderrRing) -> bool) {
20671 for _ in 0..1000 {
20672 if done(&lock(ring)) {
20673 return;
20674 }
20675 tokio::time::sleep(Duration::from_millis(1)).await;
20676 }
20677 panic!(
20678 "ring never reached the expected state: {:?}",
20679 lock(ring).snapshot(None, None)
20680 );
20681 }
20682
20683 #[tokio::test(start_paused = true)]
20684 async fn a_crash_line_the_reader_had_not_reached_by_the_bound_is_kept_before_the_restart() {
20685 let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20686 let (pump, release) = held_pump(&ring, "booting\n", "config error: missing storage\n");
20687
20688 settle_stderr_pump("crasher", &ring, pump, BOUND).await;
20689 let before_release = lock(&ring).snapshot(None, None);
20690 assert!(
20691 matches!(before_release.capture, CaptureState::Incomplete { .. }),
20692 "a reader that has not reached EOF cannot claim a whole tail: {before_release:?}"
20693 );
20694
20695 let next = lock(&ring).begin_process();
20698 lock(&ring).push_line_from(next, "next process booting");
20699 release.send(()).unwrap();
20700 wait_until(&ring, |ring| {
20701 ring.snapshot(None, None).capture == CaptureState::Captured
20702 })
20703 .await;
20704
20705 assert_eq!(
20706 untimed(lock(&ring).snapshot(None, None).entries),
20707 vec![
20708 line("booting"),
20709 line("config error: missing storage"),
20710 TailEntry::ProcessStart,
20711 line("next process booting"),
20712 ],
20713 "the crash's last line must survive a slow reader and stay in the crashed process's section"
20714 );
20715 }
20716
20717 #[tokio::test(start_paused = true)]
20718 async fn a_pipe_held_open_by_a_descendant_reads_incomplete_without_delaying_the_restart_past_the_bound(
20719 ) {
20720 let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20721 let (pump, _held) = held_pump(&ring, "parent exiting\n", "");
20724
20725 let started = Instant::now();
20726 settle_stderr_pump("orphaning", &ring, pump, BOUND).await;
20727 assert_eq!(
20728 started.elapsed(),
20729 BOUND,
20730 "the restart must wait exactly the bound for a pipe that stays open, no longer"
20731 );
20732
20733 let next = lock(&ring).begin_process();
20734 lock(&ring).push_line_from(next, "next process booting");
20735 tokio::time::sleep(Duration::from_secs(60)).await;
20736
20737 let snapshot = lock(&ring).snapshot(None, None);
20738 match &snapshot.capture {
20739 CaptureState::Incomplete { reason } => assert!(
20740 reason.contains("had not reached EOF") && reason.contains("250ms"),
20741 "the reason must say what is missing and after how long: {reason}"
20742 ),
20743 other => panic!("expected Incomplete while the pipe is held open, got {other:?}"),
20744 }
20745 assert_eq!(
20746 untimed(snapshot.entries),
20747 vec![
20748 line("parent exiting"),
20749 TailEntry::ProcessStart,
20750 line("next process booting"),
20751 ]
20752 );
20753 }
20754
20755 #[tokio::test(start_paused = true)]
20756 async fn a_reader_that_reaches_eof_within_the_bound_leaves_the_tail_captured() {
20757 let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20758 let (pump, release) = held_pump(&ring, "one\n", "two\n");
20759 release.send(()).unwrap();
20760
20761 settle_stderr_pump("clean", &ring, pump, BOUND).await;
20762
20763 let snapshot = lock(&ring).snapshot(None, None);
20764 assert_eq!(snapshot.capture, CaptureState::Captured);
20765 assert_eq!(untimed(snapshot.entries), vec![line("one"), line("two")]);
20766 }
20767
20768 #[tokio::test(start_paused = true)]
20769 async fn stdout_buffered_past_the_exit_drain_bound_reaches_the_capture_file() {
20770 const BURST: usize = 150;
20771 let capture = cortexkit_test_support::ScratchDir::new("stdout-exit-drain");
20772 let path = capture.join("two-pipe.stderr.log");
20773 let sink = ChildOutputSink::open(&path, cortexkit_log::Retention::default()).unwrap();
20774 let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
20775 let generation = lock(&ring).begin_process();
20776 let stdout = (0..BURST)
20777 .map(|i| format!("out-{i:04}-{}\n", "o".repeat(64)))
20778 .collect::<String>();
20779 let stderr = (0..BURST)
20780 .map(|i| format!("err-{i:04}-{}\n", "e".repeat(64)))
20781 .collect::<String>();
20782 let first_chunk = stdout.find('\n').unwrap() + 1 + "out-0001-".len();
20787 let (release, gate) = oneshot::channel();
20788 let reader = HeldReader {
20789 before: Some(stdout.as_bytes()[..first_chunk].to_vec()),
20790 gate: Some(gate),
20791 after: io::Cursor::new(stdout.as_bytes()[first_chunk..stdout.len() - 1].to_vec()),
20792 };
20793 let (finished, completion) = oneshot::channel();
20794 let stdout_sink = sink.clone();
20795 let pump = tokio::spawn(async move {
20796 pump_stdout_to(reader, stdout_sink).await;
20797 finished.send(()).unwrap();
20798 });
20799 pump_stderr_to(io::Cursor::new(stderr.into_bytes()), ring, generation, sink).await;
20800
20801 let started = Instant::now();
20802 settle_stdout_pump("two-pipe", pump, BOUND).await;
20803 assert_eq!(
20804 started.elapsed(),
20805 BOUND,
20806 "a late reader must not hold up restart"
20807 );
20808 assert_eq!(
20809 std::fs::read_to_string(&path).unwrap().lines().count(),
20810 BURST + 1
20811 );
20812
20813 release
20814 .send(())
20815 .expect("stdout reader must survive the exit drain bound");
20816 tokio::time::timeout(Duration::from_secs(1), completion)
20817 .await
20818 .expect("released stdout reader must reach EOF")
20819 .expect("stdout capture must finish at EOF, not be cancelled");
20820 let contents = std::fs::read_to_string(&path).unwrap();
20821 let mut lines = contents
20822 .lines()
20823 .map(|line| split_capture_stamp(line).expect("capture stamp").1)
20824 .collect::<Vec<_>>();
20825 let mut expected = (0..BURST)
20826 .flat_map(|i| {
20827 [
20828 format!("out-{i:04}-{}", "o".repeat(64)),
20829 format!("err-{i:04}-{}", "e".repeat(64)),
20830 ]
20831 })
20832 .collect::<Vec<_>>();
20833 lines.sort_unstable();
20834 expected.sort_unstable();
20835 assert_eq!(
20836 lines, expected,
20837 "both pipes must retain every complete line exactly once"
20838 );
20839 }
20840}
20841
20842#[cfg(all(test, windows))]
20856mod job_containment_tests {
20857 use super::*;
20858 use cortexkit_test_support::ScratchDir;
20859 use std::{
20860 path::{Path, PathBuf},
20861 sync::{Arc, Mutex},
20862 time::{Duration, Instant},
20863 };
20864
20865 fn stub_path() -> PathBuf {
20871 let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
20872 assert!(
20873 path.exists(),
20874 "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
20875 [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
20876 path.display()
20877 );
20878 path
20879 }
20880
20881 fn read_grandchild_pid(path: &Path) -> u32 {
20883 let deadline = Instant::now() + Duration::from_secs(10);
20884 loop {
20885 if let Ok(contents) = std::fs::read_to_string(path) {
20886 if let Ok(pid) = contents.trim().parse() {
20887 return pid;
20888 }
20889 }
20890 assert!(
20891 Instant::now() < deadline,
20892 "the stub never recorded a grandchild pid at {}",
20893 path.display()
20894 );
20895 std::thread::sleep(Duration::from_millis(10));
20896 }
20897 }
20898
20899 struct Fixture {
20902 _dir: ScratchDir,
20903 _roster: ChildRoster,
20904 module_id: String,
20905 grandchild: u32,
20906 child: Option<SupervisedChild>,
20907 registry: Arc<Registry>,
20908 snapshot: Arc<Mutex<SupervisorSnapshot>>,
20909 terminal_ring: Arc<Mutex<TerminalRing>>,
20910 spawn_events: SpawnEventFeed,
20911 }
20912
20913 fn fixture(label: &str, module_id: &str) -> Fixture {
20914 fixture_with_carry(label, module_id, false)
20915 }
20916
20917 fn fixture_with_carry(label: &str, module_id: &str, carry_containment: bool) -> Fixture {
20918 let dir = ScratchDir::new(label);
20919 let pid_file = dir.join("grandchild.pid");
20920 let supervisor = Supervisor::new_for_test(
20921 Arc::new(Registry::default()),
20922 RestartPolicy::new(3, Duration::ZERO),
20923 );
20924 let runtime = supervisor.runtime_config();
20925 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
20926 let spec = ModuleSpec {
20927 script: None,
20928 module_id: module_id.to_string(),
20929 program: stub_path(),
20930 args: Vec::new(),
20934 env: vec![
20935 ("FAKE_AFT_NEVER_CONNECT".to_string(), "1".to_string()),
20936 (
20937 "FAKE_AFT_GRANDCHILD_PID_FILE".to_string(),
20938 pid_file.display().to_string(),
20939 ),
20940 ],
20941 reserved: false,
20942 reserved_prefixes: Vec::new(),
20943 protocol: ModuleProtocol::Subc,
20944 overlap: Default::default(),
20945 carry_containment,
20946 };
20947 let child = spawn_and_mark_running(&spec, &runtime, &snapshot)
20948 .expect("spawn the supervised fixture");
20949 let grandchild = read_grandchild_pid(&pid_file);
20950 Fixture {
20951 _dir: dir,
20952 _roster: runtime.child_roster.clone(),
20953 module_id: module_id.to_string(),
20954 grandchild,
20955 child: Some(child),
20956 registry: Arc::new(Registry::default()),
20957 snapshot,
20958 terminal_ring: Arc::clone(&runtime.terminal_ring),
20959 spawn_events: SpawnEventFeed::default(),
20960 }
20961 }
20962
20963 async fn assert_admission_kill_reaps_grandchild(carry: bool) {
20964 let label = if carry {
20965 "admission-kill-carried-tree"
20966 } else {
20967 "admission-kill-plain-tree"
20968 };
20969 let mut fixture = fixture_with_carry(label, label, carry);
20970 let descendant = subc_os::Process::open(fixture.grandchild)
20971 .unwrap()
20972 .expect("the stub descendant must be alive before admission kill");
20973 assert!(descendant.observe().is_some());
20974 let child = fixture.child.as_mut().unwrap();
20975 assert_eq!(child.child.container().is_some(), carry);
20976 assert_eq!(child.job.is_some(), !carry);
20977
20978 child.start_admission_kill().unwrap();
20979 assert!(child.admission_kill_sent);
20980 let status = timeout(Duration::from_secs(10), child.wait())
20981 .await
20982 .unwrap()
20983 .unwrap();
20984 assert_eq!(
20985 status.code(),
20986 Some(admission_exit::WINDOWS_ADMISSION_KILL_EXIT_CODE),
20987 "containment teardown must preserve the leader's distinctive status"
20988 );
20989 assert!(
20992 descendant.wait_for_exit(Duration::from_secs(10)).unwrap(),
20993 "admission kill left a descendant running before exit finalization"
20994 );
20995 assert_eq!(child.child.container().is_some(), carry);
20996 assert_eq!(child.job.is_some(), !carry);
20997 child.finish_exit(false).await.unwrap();
20998 }
20999
21000 #[tokio::test]
21001 async fn admission_kill_reaps_grandchild_with_plain_job() {
21002 assert_admission_kill_reaps_grandchild(false).await;
21003 }
21004
21005 #[tokio::test]
21006 async fn admission_kill_reaps_grandchild_with_carried_job() {
21007 assert_admission_kill_reaps_grandchild(true).await;
21008 }
21009
21010 #[tokio::test]
21011 async fn admission_kill_retires_registration_before_wait() {
21012 let mut fixture = fixture("admission-registration", "admission-registration");
21013 let handle = SupervisorHandle::new();
21014 let spawn =
21015 RegistrationSpawn::new(&handle, "admission-registration", SpawnRole::Plain, None);
21016 spawn.ready();
21017 let child = fixture.child.as_mut().unwrap();
21018 child.registration_spawn = Some(spawn.clone());
21019 child.start_admission_kill().unwrap();
21020 assert!(
21021 !spawn.launch_ready(),
21022 "admission kill must retire before its caller can await the child"
21023 );
21024 timeout(Duration::from_secs(10), child.wait())
21025 .await
21026 .unwrap()
21027 .unwrap();
21028 child.finish_exit(false).await.unwrap();
21029 }
21030
21031 impl Fixture {
21032 async fn drain(&mut self) {
21034 let child = self
21035 .child
21036 .take()
21037 .expect("the fixture child is still present");
21038 drain_child_to_state(
21039 &self.module_id,
21040 ModuleProtocol::Subc,
21041 StopNotice::NotSent,
21044 &self.registry,
21045 None,
21046 &self.snapshot,
21047 &self.terminal_ring,
21048 &self.spawn_events,
21049 child,
21050 Duration::from_millis(500),
21051 ModuleState::Stopped,
21052 Some(false),
21053 &FailureContext::operator(),
21054 )
21055 .await
21056 .expect("drain the supervised fixture");
21057 }
21058 }
21059
21060 #[tokio::test]
21066 async fn teardown_reaps_the_grandchild() {
21067 let mut fixture = fixture("teardown-grandchild", "tree-teardown");
21068 let grandchild = fixture.grandchild;
21069
21070 assert!(
21071 subc_jobobject::process_exists(grandchild),
21072 "grandchild {grandchild} must be alive before teardown, or this proves nothing"
21073 );
21074
21075 fixture.drain().await;
21076
21077 assert!(
21078 subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21079 "grandchild {grandchild} outlived module teardown: the tree was not contained"
21080 );
21081 }
21082
21083 #[test]
21096 fn an_uncontained_grandchild_survives_a_direct_child_kill() {
21097 let dir = ScratchDir::new("teardown-uncontained");
21098 let pid_file = dir.join("grandchild.pid");
21099 let mut child = std::process::Command::new(stub_path())
21100 .env("FAKE_AFT_NEVER_CONNECT", "1")
21101 .env(
21102 "FAKE_AFT_GRANDCHILD_PID_FILE",
21103 pid_file.display().to_string(),
21104 )
21105 .stdin(std::process::Stdio::null())
21106 .stdout(std::process::Stdio::null())
21107 .stderr(std::process::Stdio::null())
21108 .spawn()
21109 .expect("spawn the uncontained fixture");
21110 let grandchild = read_grandchild_pid(&pid_file);
21111
21112 child.kill().expect("kill the direct child");
21114 let _ = child.wait();
21115
21116 assert!(
21117 subc_jobobject::process_exists(grandchild),
21118 "grandchild {grandchild} died with the direct child, so this control no longer \
21119 distinguishes contained from uncontained teardown and the regression test is \
21120 passing vacuously"
21121 );
21122
21123 kill_tree(grandchild);
21126 }
21127
21128 #[tokio::test]
21137 async fn dropping_containment_reaps_the_grandchild() {
21138 let mut fixture = fixture("drop-containment", "tree-drop");
21139 let grandchild = fixture.grandchild;
21140
21141 assert!(subc_jobobject::process_exists(grandchild));
21142
21143 fixture.child.as_mut().expect("child present").job = None;
21145
21146 assert!(
21147 subc_jobobject::wait_for_process_exit(grandchild, Duration::from_secs(10)),
21148 "grandchild {grandchild} survived the containment handle closing, so a daemon \
21149 crash would leave the tree behind"
21150 );
21151 }
21152
21153 fn kill_tree(pid: u32) {
21155 let _ = std::process::Command::new("taskkill.exe")
21156 .args(["/PID", &pid.to_string(), "/T", "/F"])
21157 .stdin(std::process::Stdio::null())
21158 .stdout(std::process::Stdio::null())
21159 .stderr(std::process::Stdio::null())
21160 .status();
21161 assert!(
21162 subc_jobobject::wait_for_process_exit(pid, Duration::from_secs(10)),
21163 "could not clean up grandchild {pid}"
21164 );
21165 }
21166}
21167
21168#[cfg(test)]
21169mod privacy_trampoline_configuration_tests {
21170 #[tokio::test]
21171 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21172 async fn macos_spawn_without_a_configured_trampoline_refuses_by_name() {
21173 #[cfg(target_os = "macos")]
21174 {
21175 let supervisor = super::Supervisor::new(
21176 std::sync::Arc::new(crate::Registry::default()),
21177 super::RestartPolicy::default(),
21178 );
21179 let error = supervisor.spawn(spec()).unwrap_err();
21180 assert!(
21181 error
21182 .to_string()
21183 .contains("no privacy trampoline configured"),
21184 "{error}"
21185 );
21186 }
21187 }
21188
21189 #[tokio::test]
21190 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21191 async fn macos_wrong_trampoline_is_rejected_by_the_startup_probe() {
21192 #[cfg(target_os = "macos")]
21193 {
21194 let supervisor = super::Supervisor::new(
21195 std::sync::Arc::new(crate::Registry::default()),
21196 super::RestartPolicy::default(),
21197 )
21198 .with_privacy_trampoline(std::env::current_exe().unwrap());
21199 let error = supervisor.spawn(spec()).unwrap_err();
21200 assert!(
21201 error
21202 .to_string()
21203 .contains("binary does not implement the privacy trampoline protocol"),
21204 "{error}"
21205 );
21206 }
21207 }
21208
21209 #[cfg(target_os = "macos")]
21210 fn spec() -> super::ModuleSpec {
21211 super::ModuleSpec {
21212 module_id: "privacy-configuration".into(),
21213 program: "/bin/sleep".into(),
21214 args: vec!["30".into()],
21215 env: vec![],
21216 reserved: false,
21217 reserved_prefixes: vec![],
21218 protocol: subc_control::ModuleProtocol::None,
21219 overlap: super::ModuleOverlap::Exclusive,
21220 carry_containment: false,
21221 script: None,
21222 }
21223 }
21224}
21225
21226#[cfg(test)]
21227mod privacy_exec_boundary_tests {
21228 #[cfg(target_os = "macos")]
21229 use super::*;
21230 #[cfg(target_os = "macos")]
21231 use std::{
21232 io::{Read, Write},
21233 net::{TcpListener, TcpStream},
21234 };
21235
21236 #[cfg(target_os = "macos")]
21239 pub(super) fn before_image_sample(spec: &ModuleSpec, pid: u32) {
21240 if let Some((_, path)) = spec
21241 .env
21242 .iter()
21243 .find(|(key, _)| key == "SUBC_TEST_PRIVACY_SAMPLE_BARRIER")
21244 {
21245 let mut barrier = TcpStream::connect(path).unwrap();
21246 barrier
21247 .set_read_timeout(Some(Duration::from_secs(30)))
21248 .unwrap();
21249 barrier.write_all(&pid.to_ne_bytes()).unwrap();
21250 let mut release = [0];
21251 barrier.read_exact(&mut release).unwrap();
21252 assert_eq!(&release, b"X");
21253 }
21254 }
21255
21256 #[cfg(target_os = "macos")]
21257 fn spec(program: &str, args: &[&str]) -> ModuleSpec {
21258 ModuleSpec {
21259 script: None,
21260 module_id: "privacy-boundary".into(),
21261 program: program.into(),
21262 args: args.iter().map(|arg| (*arg).into()).collect(),
21263 env: vec![],
21264 reserved: false,
21265 reserved_prefixes: vec![],
21266 protocol: ModuleProtocol::None,
21267 overlap: ModuleOverlap::Exclusive,
21268 carry_containment: false,
21269 }
21270 }
21271
21272 #[cfg(target_os = "macos")]
21273 async fn accept(listener: TcpListener) -> TcpStream {
21274 let listener = tokio::net::TcpListener::from_std({
21276 listener.set_nonblocking(true).unwrap();
21277 listener
21278 })
21279 .unwrap();
21280 let (stream, _) = tokio::time::timeout(Duration::from_secs(30), listener.accept())
21281 .await
21282 .unwrap()
21283 .unwrap();
21284 let stream = stream.into_std().unwrap();
21285 stream.set_nonblocking(false).unwrap();
21286 stream
21287 .set_read_timeout(Some(Duration::from_secs(30)))
21288 .unwrap();
21289 stream
21290 }
21291
21292 #[tokio::test]
21293 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21294 async fn macos_roster_withholds_a_nonnull_trampoline_image_until_exec_confirmation() {
21295 #[cfg(target_os = "macos")]
21296 {
21297 let root = cortexkit_test_support::ScratchDir::new("privacy-roster-barrier");
21298 let exec_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21301 let sample_listener = TcpListener::bind("127.0.0.1:0").unwrap();
21302 let record = root.join("live-children.json");
21303 let supervisor =
21304 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21305 .with_live_children_record(&record);
21306 let runtime = supervisor.runtime_config();
21307 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21308 let mut spec = spec("/bin/sleep", &["30"]);
21309 spec.env = vec![
21310 (
21311 "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21312 exec_listener.local_addr().unwrap().to_string(),
21313 ),
21314 (
21315 "SUBC_TEST_PRIVACY_SAMPLE_BARRIER".into(),
21316 sample_listener.local_addr().unwrap().to_string(),
21317 ),
21318 ];
21319 let spawn = tokio::task::spawn_blocking(move || {
21320 spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap()
21321 });
21322 let mut sample = accept(sample_listener).await;
21323 let mut pid = [0; 4];
21324 sample.read_exact(&mut pid).unwrap();
21325 let pid = u32::from_ne_bytes(pid);
21326 let mut exec = accept(exec_listener).await;
21327 let mut ready = [0];
21328 exec.read_exact(&mut ready).unwrap();
21329 assert_eq!(&ready, b"R");
21330 let trampoline = subc_os::file_identity(&test_privacy_trampoline()).unwrap();
21333 assert_eq!(
21334 observe_spawned_image(pid).unwrap().executable,
21335 Some(trampoline)
21336 );
21337 sample.write_all(b"X").unwrap();
21338 let mut child = spawn.await.unwrap();
21339 let early = crate::live_children::read_record(&record).unwrap();
21340 assert_eq!(early.len(), 1);
21341 assert_eq!(early[0].pid, pid);
21342 assert_eq!(
21343 early[0].executable, None,
21344 "unconfirmed trampoline image entered the roster"
21345 );
21346 assert!(child.report_ready.get().is_none());
21347 child.privacy_exec.as_mut().unwrap().deadline =
21350 tokio::time::Instant::now() + Duration::from_secs(30);
21351 exec.write_all(b"X").unwrap();
21352 child.confirm_privacy_exec().await;
21353 assert_eq!(child.spawn_failure, None);
21354 assert!(child.report_ready.get().is_some());
21355 let confirmed = crate::live_children::read_record(&record).unwrap();
21356 let module = subc_os::file_identity(std::path::Path::new("/bin/sleep")).unwrap();
21357 assert_ne!(module, trampoline);
21358 assert_eq!(confirmed[0].executable, Some(module.into()));
21359 child.start_kill().unwrap();
21360 child.wait().await.unwrap();
21361 child.release_roster();
21362 }
21363 }
21364
21365 #[tokio::test]
21366 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21367 async fn macos_unstamped_reexec_records_the_observed_native_image() {
21368 #[cfg(target_os = "macos")]
21369 {
21370 let root = cortexkit_test_support::ScratchDir::new("privacy-reexec");
21371 let record = root.join("live-children.json");
21372 let supervisor =
21373 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21374 .with_live_children_record(&record);
21375 let runtime = supervisor.runtime_config();
21376 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21377 let fixture = crate::config_gate::program::native_fixture_for_test();
21378 let mut spec = spec(
21379 "/bin/sh",
21380 &["-c", "exec \"$1\" 600", "reexec", fixture.to_str().unwrap()],
21381 );
21382 spec.env
21383 .push(("SUBC_TEST_PRIVACY_IMAGE_DELAY_MS".into(), "5".into()));
21384 let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21385 let native_image = subc_os::file_identity(&fixture).unwrap();
21386 let reexec = tokio::time::timeout(Duration::from_secs(5), async {
21389 while observe_spawned_image(child.pid).and_then(|image| image.executable)
21390 != Some(native_image)
21391 {
21392 tokio::time::sleep(Duration::from_millis(1)).await;
21393 }
21394 })
21395 .await;
21396 child.confirm_privacy_exec().await;
21397 let failure = child.spawn_failure.clone();
21398 let ready = child.report_ready.get().is_some();
21399 let confirmed = crate::live_children::read_record(&record).unwrap();
21400 child.start_kill().unwrap();
21401 tokio::time::timeout(Duration::from_secs(5), child.wait())
21402 .await
21403 .unwrap()
21404 .unwrap();
21405 child.release_roster();
21406
21407 reexec.expect("the shell must re-exec the native fixture");
21408 assert_eq!(
21409 failure, None,
21410 "an unstamped program may re-exec before observation"
21411 );
21412 assert!(ready);
21413 assert_eq!(confirmed.len(), 1);
21414 assert_eq!(confirmed[0].executable, Some(native_image.into()));
21415 }
21416 }
21417
21418 #[tokio::test]
21419 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21420 async fn macos_unstamped_ack_without_exec_still_refuses_the_trampoline() {
21421 #[cfg(target_os = "macos")]
21422 {
21423 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
21424 let supervisor =
21425 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
21426 let runtime = supervisor.runtime_config();
21427 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21428 let fixture = crate::config_gate::program::native_fixture_for_test();
21429 let mut spec = spec(fixture.to_str().unwrap(), &["600"]);
21430 spec.env.push((
21431 "SUBC_TEST_PRIVACY_EXEC_BARRIER".into(),
21432 listener.local_addr().unwrap().to_string(),
21433 ));
21434 let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21435 let mut exec = accept(listener).await;
21436 let mut ready = [0];
21437 exec.read_exact(&mut ready).unwrap();
21438 assert_eq!(&ready, b"R");
21439 assert_eq!(
21440 observe_spawned_image(child.pid).unwrap().executable,
21441 subc_os::file_identity(&test_privacy_trampoline())
21442 );
21443 let (reader, writer) = std::io::pipe().unwrap();
21446 drop(writer);
21447 child.privacy_exec.as_mut().unwrap().reader =
21448 tokio::io::unix::AsyncFd::new(reader).unwrap();
21449 child.confirm_privacy_exec().await;
21450 let failure = child.spawn_failure.clone();
21451 let ready = child.report_ready.get().is_some();
21452 child.start_kill().unwrap();
21453 tokio::time::timeout(Duration::from_secs(5), child.wait())
21454 .await
21455 .unwrap()
21456 .unwrap();
21457 child.release_roster();
21458 assert_eq!(
21459 failure.as_deref(),
21460 Some("privacy identity trampoline did not exec the module")
21461 );
21462 assert!(!ready);
21463 }
21464 }
21465
21466 #[tokio::test]
21467 #[cfg_attr(not(target_os = "macos"), ignore = "requires macOS privacy trampoline")]
21468 async fn macos_resumed_121_is_a_module_exit_not_a_trampoline_refusal() {
21469 #[cfg(target_os = "macos")]
21470 {
21471 let registry = Arc::new(Registry::default());
21472 let policy = RestartPolicy::new(0, Duration::ZERO);
21473 let fixture = crate::config_gate::program::native_fixture_for_test();
21474 let spec = spec(fixture.to_str().unwrap(), &["exit121"]);
21475 let scratch = cortexkit_test_support::ScratchDir::new("resumed-exit");
21476 let supervisor = Supervisor::new_for_test(Arc::clone(®istry), policy)
21477 .with_config_runtime(suspended_spawn_tests::gated_owner(&scratch, &spec, true));
21478 let runtime = supervisor.runtime_config();
21479 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21480 let mut child = spawn_and_mark_running(&spec, &runtime, &snapshot).unwrap();
21483 child.confirm_privacy_exec().await;
21484 assert_eq!(child.spawn_failure, None);
21485 assert!(child.report_ready.get().is_some());
21486 let pid = child.pid;
21487 tokio::task::spawn_blocking(move || {
21488 subc_os::fork_exec_test::wait_for_child_exit_without_reaping(pid)
21489 })
21490 .await
21491 .unwrap()
21492 .unwrap();
21493 let status = child.wait().await.unwrap();
21494 assert_eq!(status.code(), Some(121));
21495 assert!(child.privacy_exec.is_none());
21496 let report = classify_reaped_child_exit(&snapshot, &child, &status);
21497 on_child_exit(
21498 &spec,
21499 policy,
21500 ®istry,
21501 &snapshot,
21502 &runtime.terminal_ring,
21503 &runtime.spawn_events,
21504 &runtime.child_roster,
21505 report,
21506 true,
21507 )
21508 .await;
21509 let state = lock_snapshot(&snapshot).unwrap();
21510 assert_eq!(state.state, ModuleState::Failed);
21511 assert_eq!(state.last_exit.as_ref().unwrap().code, Some(121));
21512 assert_eq!(state.reported_pid(), None);
21513 drop(state);
21514 let history = runtime.terminal_ring.lock().unwrap().snapshot();
21515 assert_eq!(history.entries.len(), 1);
21516 let terminal = &history.entries[0];
21517 assert_eq!(terminal.exit_code, Some(121));
21518 assert_eq!(terminal.exit_kind, subc_control::TerminalExitKind::Crash);
21519 assert_eq!(terminal.disposition, TerminalDisposition::Failed);
21520 assert_eq!(
21521 terminal.disposition_detail.as_deref(),
21522 Some(policy.budget_exhausted_detail().as_str()),
21523 "module exit 121 was classified as a trampoline refusal: {terminal:?}"
21524 );
21525 assert_eq!(child.spawn_failure, None);
21526 child.release_roster();
21527 }
21528 }
21529}
21530
21531#[cfg(all(test, target_os = "macos"))]
21532#[path = "supervise/suspended_spawn_tests.rs"]
21533mod suspended_spawn_tests;
21534
21535#[cfg(all(test, unix))]
21539mod launch_nonce_descriptor_tests {
21540 use super::{ChildRoster, ModuleProtocol, ModuleSpec, SupervisorHandle};
21541 use crate::stderr_tail::{StderrRing, StderrTailConfig};
21542 use cortexkit_test_support::ScratchDir;
21543 use std::{
21544 path::PathBuf,
21545 sync::{Arc, Mutex},
21546 time::{Duration, Instant},
21547 };
21548
21549 async fn probe(role: super::SpawnRole) {
21550 let scratch = ScratchDir::new("launch-nonce-descriptor");
21551 let fd_copy = scratch.join("from-descriptor");
21552 let env_copy = scratch.join("environment");
21553 let script = format!(
21554 "env > '{env}.tmp' && mv '{env}.tmp' '{env}'; cat <&3 > '{fd}.tmp' && mv '{fd}.tmp' '{fd}'; sleep 30",
21555 fd = fd_copy.display(), env = env_copy.display(),
21556 );
21557 let xdg = |name: &str| (name.to_string(), scratch.join(name).display().to_string());
21558 let spec = ModuleSpec {
21559 script: None,
21560 module_id: "nonce-descriptor-probe".to_string(),
21561 program: PathBuf::from("/bin/sh"),
21562 args: vec!["-c".to_string(), script],
21563 env: vec![
21564 xdg("XDG_DATA_HOME"),
21565 xdg("XDG_RUNTIME_DIR"),
21566 xdg("XDG_CONFIG_HOME"),
21567 ("SUBC_LAUNCH_NONCE".to_string(), "must-not-leak".to_string()),
21568 ],
21569 reserved: true,
21570 reserved_prefixes: Vec::new(),
21571 protocol: ModuleProtocol::Subc,
21572 overlap: Default::default(),
21573 carry_containment: false,
21574 };
21575 let handle = SupervisorHandle::new();
21576 let ring = Arc::new(Mutex::new(StderrRing::new(StderrTailConfig::default())));
21577 let roster = ChildRoster::default();
21578 #[cfg(target_os = "macos")]
21579 {
21580 let path = super::test_privacy_trampoline();
21581 roster.set_privacy_trampoline(super::probe_privacy_trampoline(&path).map(|()| path));
21582 }
21583 let child = super::spawn_child_in_slot(
21584 &spec,
21585 None,
21586 Some(&handle),
21587 &ring,
21588 None,
21589 &roster,
21590 None,
21591 #[cfg(target_os = "linux")]
21592 None,
21593 role,
21594 matches!(role, super::SpawnRole::SwapCandidate),
21595 super::DEFAULT_REGISTER_TIMEOUT,
21596 )
21597 .expect("spawn probe");
21598 let deadline = Instant::now() + Duration::from_secs(10);
21599 while !(fd_copy.exists() && env_copy.exists()) {
21600 assert!(Instant::now() < deadline, "probe never wrote its copies");
21601 tokio::time::sleep(Duration::from_millis(20)).await;
21602 }
21603 let nonce = std::fs::read_to_string(fd_copy).unwrap();
21604 assert!(!nonce.is_empty());
21605 let environment = std::fs::read_to_string(env_copy).unwrap();
21606 assert!(environment
21607 .lines()
21608 .any(|line| line.starts_with("SUBC_LAUNCH_NONCE_FD=3:")));
21609 let copy = environment
21610 .lines()
21611 .find_map(|line| line.strip_prefix("SUBC_LAUNCH_NONCE="));
21612 assert_eq!(
21613 copy, None,
21614 "Unix children must never receive the environment nonce"
21615 );
21616 if matches!(role, super::SpawnRole::Plain) {
21617 assert_eq!(
21618 handle.spawn_nonce(&spec.module_id).as_deref(),
21619 Some(nonce.as_str())
21620 );
21621 }
21622 drop(child);
21623 }
21624
21625 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21626 async fn a_spawned_module_receives_its_nonce_only_on_descriptor_3() {
21627 probe(super::SpawnRole::Plain).await;
21628 }
21629
21630 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21631 async fn swap_candidate_receives_its_nonce_only_on_descriptor_3() {
21632 probe(super::SpawnRole::SwapCandidate).await;
21633 }
21634}
21635
21636#[cfg(all(test, target_os = "linux"))]
21637#[path = "supervise/cgroup_reap_tests.rs"]
21638mod cgroup_reap_tests;
21639
21640#[cfg(all(test, target_os = "linux"))]
21641mod cgroup_containment_tests {
21642 use super::*;
21643 use cortexkit_test_support::ScratchDir;
21644
21645 #[tokio::test]
21646 async fn linux_subtree_memory_covers_module_children() {
21647 let dir = ScratchDir::new("subtree-memory");
21648 let root = PathBuf::from(format!(
21649 "/sys/fs/cgroup/subc-memory-test-{}-{}",
21650 std::process::id(),
21651 unix_ms_now()
21652 ));
21653 if let Err(error) = std::fs::create_dir(&root) {
21654 assert!(
21655 std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21656 "required cgroup test cannot execute: {error}"
21657 );
21658 eprintln!("SKIP linux_subtree_memory_covers_module_children: {error}");
21659 return;
21660 }
21661 let placement = subc_cgroup::prepare_at(&root)
21662 .unwrap()
21663 .expect("delegated cgroup");
21664 let supervisor = Supervisor::new_for_test(
21665 Arc::new(Registry::default()),
21666 RestartPolicy::new(3, Duration::ZERO),
21667 )
21668 .with_cgroup_placement(Some(placement));
21669 let ready = dir.join("ready");
21670 let module = supervisor
21671 .spawn(ModuleSpec {
21672 script: None,
21673 module_id: "memory-tree".into(),
21674 program: PathBuf::from("/bin/sh"),
21675 args: vec![
21676 "-c".into(),
21677 "sleep 600 & sleep 600 & sleep 600 & echo ready > \"$1\"; wait".into(),
21678 "fixture".into(),
21679 ready.display().to_string(),
21680 ],
21681 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
21682 .into_iter()
21683 .map(|key| (key.into(), dir.display().to_string()))
21684 .collect(),
21685 reserved: false,
21686 reserved_prefixes: Vec::new(),
21687 protocol: ModuleProtocol::None,
21688 overlap: Default::default(),
21689 carry_containment: false,
21690 })
21691 .unwrap();
21692 let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
21693 while !ready.exists() {
21694 assert!(
21695 tokio::time::Instant::now() < deadline,
21696 "children never started"
21697 );
21698 tokio::time::sleep(Duration::from_millis(10)).await;
21699 }
21700 let readings = crate::subtree_resources::read(vec![module.subtree_target()]).await;
21701 let reading = &readings[0];
21702 assert!(
21703 reading.process_count.is_some_and(|count| count >= 4),
21704 "{reading:?}"
21705 );
21706 assert!(
21707 reading.memory_bytes.is_some_and(|bytes| bytes > 0),
21708 "{reading:?}"
21709 );
21710 module.stop().await.unwrap();
21711 drop(module);
21712 std::fs::remove_dir(root.join("subc-modules")).unwrap();
21713 std::fs::remove_dir(&root).unwrap();
21714 eprintln!("EXECUTED linux_subtree_memory_covers_module_children: {reading:?}");
21715 }
21716
21717 fn running(pid: u32) -> bool {
21718 std::fs::read_to_string(format!("/proc/{pid}/stat"))
21720 .ok()
21721 .and_then(|stat| {
21722 stat.rsplit_once(") ")
21723 .map(|(_, rest)| rest.starts_with('Z'))
21724 })
21725 .is_some_and(|zombie| !zombie)
21726 }
21727
21728 #[tokio::test]
21729 async fn linux_teardown_reaps_the_grandchild() {
21730 teardown_tree("linux_teardown_reaps_the_grandchild", false).await;
21731 }
21732
21733 #[tokio::test]
21734 async fn linux_shutdown_straggler_reaps_the_grandchild() {
21735 teardown_tree("linux_shutdown_straggler_reaps_the_grandchild", true).await;
21736 }
21737
21738 async fn teardown_tree(test_name: &str, shutdown: bool) {
21739 let dir = ScratchDir::new(test_name);
21740 let root = PathBuf::from(format!(
21741 "/sys/fs/cgroup/subc-tree-test-{test_name}-{}-{}",
21742 std::process::id(),
21743 unix_ms_now()
21744 ));
21745 if let Err(error) = std::fs::create_dir(&root) {
21746 assert!(
21747 std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21748 "required cgroup test cannot execute: {error}"
21749 );
21750 eprintln!(
21751 "SKIP {test_name}: no writable delegated cgroup at {}: {error}",
21752 root.display()
21753 );
21754 return;
21755 }
21756 let placement = subc_cgroup::prepare_at(&root)
21757 .expect("prepare isolated kernel cgroup")
21758 .expect("isolated cgroup is delegated");
21759 let module_id = "tree-teardown";
21760 let module = placement
21761 .module_path(module_id)
21762 .expect("create isolated module cgroup");
21763 if !module.join("cgroup.kill").exists() {
21764 std::fs::remove_dir(&module).unwrap();
21765 std::fs::remove_dir(root.join("subc-modules")).unwrap();
21766 std::fs::remove_dir(&root).unwrap();
21767 assert!(
21768 std::env::var_os("SUBC_REQUIRE_CGROUP_TEST").is_none(),
21769 "required cgroup.kill interface unavailable"
21770 );
21771 eprintln!("SKIP {test_name}: cgroup.kill unavailable (kernel < 5.14)");
21772 return;
21773 }
21774 let supervisor = Supervisor::new_for_test(
21775 Arc::new(Registry::default()),
21776 RestartPolicy::new(3, Duration::ZERO),
21777 )
21778 .with_cgroup_placement(Some(placement));
21779 let mut runtime = supervisor.runtime_config();
21780 runtime.child_roster = runtime
21781 .child_roster
21782 .for_module(Arc::new(Mutex::new(Duration::from_millis(100))));
21783 let snapshot = Arc::new(Mutex::new(SupervisorSnapshot::starting()));
21784 let pid_file = dir.join("grandchild.pid");
21785 let spec = ModuleSpec {
21786 script: None,
21787 module_id: module_id.to_string(),
21788 program: PathBuf::from("/bin/sh"),
21789 args: vec![
21790 "-c".into(),
21791 "trap '' TERM; sleep 600 & echo $! > \"$1\"; wait".into(),
21792 "fixture".into(),
21793 pid_file.display().to_string(),
21794 ],
21795 env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
21796 .into_iter()
21797 .map(|key| (key.to_string(), dir.display().to_string()))
21798 .collect(),
21799 reserved: false,
21800 reserved_prefixes: Vec::new(),
21801 protocol: ModuleProtocol::None,
21802 overlap: Default::default(),
21803 carry_containment: false,
21804 };
21805 let child =
21806 spawn_and_mark_running(&spec, &runtime, &snapshot).expect("spawn supervised tree");
21807 let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
21808 let grandchild: u32 = loop {
21809 if let Ok(contents) = std::fs::read_to_string(&pid_file) {
21810 if let Ok(pid) = contents.trim().parse() {
21811 break pid;
21812 }
21813 }
21814 assert!(
21815 tokio::time::Instant::now() < deadline,
21816 "grandchild pid was not recorded"
21817 );
21818 tokio::time::sleep(Duration::from_millis(10)).await;
21819 };
21820 assert!(
21821 running(grandchild),
21822 "grandchild must be alive before teardown"
21823 );
21824 if shutdown {
21825 let mut child = child;
21826 crate::child_roster::end_children_for_daemon_shutdown(
21827 &runtime.child_roster,
21828 false,
21829 std::future::pending(),
21830 )
21831 .await;
21832 child.wait().await.expect("reap shutdown straggler");
21833 child
21834 .finish_exit(false)
21835 .await
21836 .expect("finalize shutdown straggler's cgroup");
21837 } else {
21838 drain_child_to_state(
21839 module_id,
21840 ModuleProtocol::None,
21841 StopNotice::NotSent,
21842 &Registry::default(),
21843 None,
21844 &snapshot,
21845 &runtime.terminal_ring,
21846 &SpawnEventFeed::default(),
21847 child,
21848 Duration::from_millis(100),
21849 ModuleState::Stopped,
21850 Some(false),
21851 &FailureContext::operator(),
21852 )
21853 .await
21854 .expect("real supervisor teardown");
21855 }
21856 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
21857 while running(grandchild) && tokio::time::Instant::now() < deadline {
21858 tokio::time::sleep(Duration::from_millis(10)).await;
21859 }
21860 let survived = running(grandchild);
21861 if survived {
21863 let pid = rustix::process::Pid::from_raw(grandchild as i32).unwrap();
21864 let _ = rustix::process::kill_process(pid, rustix::process::Signal::KILL);
21865 tokio::time::sleep(Duration::from_millis(100)).await;
21866 }
21867 if module.exists() {
21868 std::fs::remove_dir(&module).expect("remove empty module cgroup");
21869 }
21870 std::fs::remove_dir(root.join("subc-modules")).unwrap();
21871 std::fs::remove_dir(&root).unwrap();
21872 assert!(
21873 !survived,
21874 "grandchild {grandchild} outlived module teardown"
21875 );
21876 eprintln!("EXECUTED {test_name}: grandchild {grandchild} killed in isolated cgroup");
21877 }
21878}
21879
21880#[cfg(all(test, unix))]
21883mod record_write_stall_tests {
21884 use super::*;
21885 use std::sync::atomic::{AtomicBool, Ordering};
21886 use subc_transport::{authenticate_client, ConnectionInfo, Endpoint, SCHEMA_VERSION};
21887
21888 const MODULE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
21891 const HELD_RECORD_WRITE: Duration = Duration::from_secs(3);
21895
21896 fn sleeping_spec() -> ModuleSpec {
21908 ModuleSpec {
21909 script: None,
21910 module_id: "record-write-stall".into(),
21911 program: "/bin/sleep".into(),
21912 args: vec!["600".into()],
21913 env: vec![],
21914 reserved: false,
21915 reserved_prefixes: vec![],
21916 protocol: ModuleProtocol::None,
21917 overlap: Default::default(),
21918 carry_containment: false,
21919 }
21920 }
21921
21922 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
21923 async fn module_auth_completes_while_the_restart_waits_on_the_record_write() {
21924 let home = cortexkit_test_support::ScratchDir::new("record-write-stall");
21925 let supervisor =
21926 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
21927 .with_live_children_record(home.join("live-children.json"));
21928 let module = supervisor.spawn(sleeping_spec()).unwrap();
21929 let old_pid = tokio::time::timeout(Duration::from_secs(10), async {
21934 loop {
21935 if let Some(pid) = lock_snapshot(&module.inner.snapshot)
21936 .unwrap()
21937 .reported_pid()
21938 {
21939 return pid;
21940 }
21941 tokio::time::sleep(Duration::from_millis(10)).await;
21942 }
21943 })
21944 .await
21945 .expect("the first process was admitted as the module");
21946
21947 let key = vec![0x42; 32];
21950 let daemon_id = [0x24; 16];
21951 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
21952 let port = listener.local_addr().unwrap().port();
21953 let server = tokio::spawn(crate::server::serve_listener(
21954 listener,
21955 Arc::new(crate::router::Router::with_default_self_handler()),
21956 crate::server::ServerAuth::with_limits(
21957 key.clone(),
21958 daemon_id,
21959 "test",
21960 crate::server::DEFAULT_AUTH_DEADLINE,
21961 4,
21962 ),
21963 ));
21964
21965 let (held_tx, held_rx) = std::sync::mpsc::channel();
21968 let armed = AtomicBool::new(true);
21969 supervisor
21970 .child_roster
21971 .set_record_write_hook_for_test(move |live| {
21972 let admitting_replacement = live.values().any(|entry| entry.pid != old_pid);
21973 if admitting_replacement && armed.swap(false, Ordering::SeqCst) {
21974 let _ = held_tx.send(());
21975 std::thread::sleep(HELD_RECORD_WRITE);
21976 }
21977 });
21978
21979 let module_process = std::thread::spawn(move || {
21982 held_rx
21983 .recv_timeout(Duration::from_secs(30))
21984 .expect("the restart reached the replacement's record write");
21985 let conn = ConnectionInfo {
21986 schema: SCHEMA_VERSION,
21987 wire_version: None,
21988 endpoints: vec![Endpoint {
21989 host: "127.0.0.1".to_owned(),
21990 port,
21991 }],
21992 key,
21993 daemon_id,
21994 pid: std::process::id(),
21995 daemon_ver: "test".to_owned(),
21996 };
21997 tokio::runtime::Builder::new_current_thread()
21998 .enable_all()
21999 .build()
22000 .unwrap()
22001 .block_on(async {
22002 let started = Instant::now();
22003 let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
22004 .await
22005 .unwrap();
22006 let result =
22007 authenticate_client(&mut stream, &conn, MODULE_AUTH_DEADLINE).await;
22008 (result, started.elapsed())
22009 })
22010 });
22011
22012 module.restart(Some(0)).await.unwrap();
22013 let (auth, elapsed) = tokio::task::spawn_blocking(move || module_process.join().unwrap())
22014 .await
22015 .unwrap();
22016 assert!(
22017 auth.is_ok(),
22018 "the daemon must answer a module's handshake while a restart waits on the \
22019 live-children record write; got {auth:?} after {elapsed:?}"
22020 );
22021
22022 tokio::time::timeout(Duration::from_secs(20), async {
22023 while lock_snapshot(&module.inner.snapshot)
22024 .unwrap()
22025 .reported_pid()
22026 .is_none_or(|pid| pid == old_pid)
22027 {
22028 tokio::time::sleep(Duration::from_millis(10)).await;
22029 }
22030 })
22031 .await
22032 .expect("the restart published its replacement");
22033 module.stop().await.unwrap();
22034 server.abort();
22035 }
22036}
22037
22038#[cfg(all(test, unix))]
22039mod retained_status_tests {
22040 use super::*;
22041
22042 #[tokio::test]
22043 async fn cached_container_block_is_visible_in_status_and_health_without_rechecking() {
22044 use crate::live_children::{ContainerIdentity, RetainedReason};
22045 for (reason, carried, expected) in [
22046 (
22047 RetainedReason::ContainerSurvivors(vec![4242]),
22048 true,
22049 Some("waiting: container survivors (pids [4242])".to_owned()),
22050 ),
22051 (
22052 RetainedReason::ContainerUnverifiable("member inspection denied".into()),
22053 true,
22054 Some(
22055 "waiting: container survivors could not be verified: member inspection denied"
22056 .to_owned(),
22057 ),
22058 ),
22059 (RetainedReason::Survived, false, None),
22060 ] {
22061 let supervisor =
22062 Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
22063 let spec = ModuleSpec {
22064 script: None,
22065 module_id: "retained-status-fixture".into(),
22066 program: PathBuf::from("/not-spawned"),
22067 args: Vec::new(),
22068 env: Vec::new(),
22069 reserved: false,
22070 reserved_prefixes: Vec::new(),
22071 protocol: ModuleProtocol::None,
22072 overlap: ModuleOverlap::Exclusive,
22073 carry_containment: carried,
22074 };
22075 let module = supervisor
22076 .supervise_configured(spec.clone(), false)
22077 .unwrap();
22078 let guard = supervisor
22082 .child_roster
22083 .admit(
22084 spec.module_id,
22085 0,
22086 ModuleProtocol::None,
22087 None,
22088 crate::child_roster::RecordedIdentity {
22089 container: carried.then_some(ContainerIdentity {
22090 pgid: Some(0),
22091 created_start_time: Some(0),
22092 cgroup_path: None,
22093 ..ContainerIdentity::test_metadata()
22094 }),
22095 ..crate::child_roster::RecordedIdentity::default()
22096 },
22097 )
22098 .unwrap();
22099 guard.retain(reason);
22100 let status = module.status().unwrap();
22101 assert_eq!(status.waiting_for_previous_detail, expected.clone());
22102 assert_eq!(status.health.detail, expected);
22103 assert!(!status.process_alive);
22104 }
22105 }
22106}
22107
22108fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
22109 child.try_wait().is_ok_and(|status| status.is_none())
22110}