Skip to main content

sysprims_timeout/
lib.rs

1//! sysprims-timeout: Process timeout with group-by-default tree management.
2//!
3//! This crate provides:
4//! - Process execution with timeout ([`run_with_timeout`])
5//! - Group-by-default semantics (cooperative process groups signaled on timeout)
6//! - Signal escalation (SIGTERM → SIGKILL after configurable delay)
7//! - Observable fallback status for tree-kill reliability
8//!
9//! # Group-by-Default
10//!
11//! The core differentiator of sysprims over GNU timeout. When a command times
12//! out, the acquired process group is signaled, not just the direct child:
13//!
14//! - **Unix**: Creates a new process group; child is group leader
15//! - **Windows**: Creates a Job Object with `KILL_ON_JOB_CLOSE`
16//!
17//! This gives race-free group acquisition and signaling eligibility. It is not
18//! an OS-enforced promise that descendants cannot later leave the group.
19//!
20//! # Examples
21//!
22//! ```no_run
23//! use std::time::Duration;
24//! use sysprims_timeout::{run_with_timeout, TimeoutConfig, TimeoutOutcome};
25//!
26//! let result = run_with_timeout(
27//!     "sleep",
28//!     &["60"],
29//!     Duration::from_secs(5),
30//!     TimeoutConfig::default(),
31//! ).unwrap();
32//!
33//! match result {
34//!     TimeoutOutcome::Completed { exit_status } => {
35//!         println!("Command completed: {:?}", exit_status);
36//!     }
37//!     TimeoutOutcome::TimedOut { signal_sent, escalated, .. } => {
38//!         println!("Timed out, sent signal {}, escalated: {}", signal_sent, escalated);
39//!     }
40//! }
41//! ```
42
43use std::process::{Child, Command, ExitStatus};
44use std::time::Duration;
45
46use serde::{Deserialize, Serialize};
47use sysprims_core::schema::TERMINATE_TREE_RESULT_V1;
48use sysprims_core::time::now_rfc3339;
49use sysprims_core::{get_platform, SysprimsError, SysprimsResult};
50use sysprims_proc::wait_pid;
51
52#[cfg(unix)]
53mod unix;
54#[cfg(windows)]
55mod windows;
56
57// Re-export signal constants for convenience
58pub use sysprims_signal::{SIGKILL, SIGTERM};
59#[cfg(windows)]
60pub use windows::{PreparedWindowsJob, WindowsJobReceipt};
61
62/// Process grouping strategy.
63///
64/// Controls whether timeout creates a process group (Unix) or Job Object
65/// (Windows) to enable tree-kill on timeout.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
67#[serde(rename_all = "snake_case")]
68pub enum GroupingMode {
69    /// Create new process group (Unix) or Job Object (Windows).
70    /// Signal the acquired group/job on timeout. **This is the default.**
71    #[default]
72    GroupByDefault,
73
74    /// Run in foreground. Only kills direct child on timeout.
75    /// Use when the child must inherit the parent's process group.
76    Foreground,
77}
78
79/// Configuration for timeout execution.
80#[derive(Debug, Clone)]
81pub struct TimeoutConfig {
82    /// Initial signal to send on timeout.
83    ///
84    /// Default: `SIGTERM` (15)
85    pub signal: i32,
86
87    /// Delay before escalating to SIGKILL if process doesn't exit.
88    ///
89    /// Default: 10 seconds
90    pub kill_after: Duration,
91
92    /// Process grouping strategy.
93    ///
94    /// Default: `GroupByDefault`
95    pub grouping: GroupingMode,
96
97    /// Propagate child exit code when command completes normally.
98    ///
99    /// When `true`, the timeout exit code matches the child's exit code.
100    /// When `false`, successful completion returns exit code 0.
101    ///
102    /// Default: `false`
103    pub preserve_status: bool,
104}
105
106impl Default for TimeoutConfig {
107    fn default() -> Self {
108        Self {
109            signal: SIGTERM,
110            kill_after: Duration::from_secs(10),
111            grouping: GroupingMode::GroupByDefault,
112            preserve_status: false,
113        }
114    }
115}
116
117/// Reliability of tree-kill operation.
118///
119/// Distinguishes proven spawn-time acquisition, post-spawn containment with an
120/// escape window, and direct-child best effort.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
122#[serde(rename_all = "snake_case")]
123pub enum TreeKillReliability {
124    /// Spawn-time containment acquisition and group-signaling eligibility were
125    /// proven. On Unix, descendants can still leave a cooperative process
126    /// group later; this is not a non-escape guarantee.
127    Guaranteed,
128
129    /// A containment capability is owned, but it was attached after the child
130    /// started and descendants may have escaped before attachment completed.
131    Unproven,
132
133    /// Best-effort only. No owned, proven containment capability is retained;
134    /// coverage may be limited to the direct child.
135    BestEffort,
136}
137
138/// Strength of the acquired containment boundary.
139///
140/// This is independent of [`TreeKillReliability`]. Reliability describes when
141/// termination authority was acquired; boundary strength describes whether
142/// descendants are constrained by a cooperative group or a kernel-enforced
143/// non-breakaway Job.
144#[non_exhaustive]
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
146#[serde(rename_all = "snake_case")]
147pub enum ContainmentBoundaryStrength {
148    /// The exact Windows child was assigned before first execution to an owned
149    /// Job configured without either breakaway mode.
150    KernelEnforcedJob,
151    /// A Unix session/process-group boundary. Descendants may later leave.
152    CooperativeGroup,
153    /// The stronger boundary property was not proven.
154    Unknown,
155}
156
157pub(crate) const MAX_COMPLETION_OBSERVED_PIDS: usize = 4096;
158pub(crate) const MAX_COMPLETION_OBSERVATION_RETRIES: usize = 3;
159
160/// Read-only mechanism used to observe containment membership.
161#[non_exhaustive]
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
163#[serde(rename_all = "snake_case")]
164pub enum ContainmentObservation {
165    /// Linux `/proc` process-group and session scan.
166    LinuxProcfsProcessGroup,
167    /// macOS libproc process-group scan.
168    MacosLibprocProcessGroup,
169    /// Windows Job process-ID-list query.
170    WindowsJobProcessIdList,
171    /// No trustworthy platform observation mechanism was available.
172    UnsupportedPlatform,
173}
174
175/// Point-in-time evidence observed after the final containment cleanup action.
176///
177/// This evidence is independent of leader reap and containment acquisition
178/// reliability. Survivor PIDs are evidence only: PID reuse makes them unsafe to
179/// pass to process-signaling APIs or treat as suggested cleanup targets.
180#[non_exhaustive]
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
182#[serde(tag = "status", rename_all = "snake_case")]
183pub enum ContainmentCompletionEvidence {
184    /// A complete supported observation found no live containment members.
185    Empty { observation: ContainmentObservation },
186    /// A complete supported observation found live containment members.
187    Survivors {
188        observation: ContainmentObservation,
189        observed_count: u32,
190        survivor_pids: Vec<u32>,
191    },
192    /// A complete, trustworthy observation was unavailable.
193    Unknown { observation: ContainmentObservation },
194}
195
196pub(crate) fn unknown_completion(
197    observation: ContainmentObservation,
198) -> ContainmentCompletionEvidence {
199    ContainmentCompletionEvidence::Unknown { observation }
200}
201
202pub(crate) fn completion_from_pids(
203    observation: ContainmentObservation,
204    mut pids: Vec<u32>,
205) -> ContainmentCompletionEvidence {
206    if pids.len() >= MAX_COMPLETION_OBSERVED_PIDS
207        || pids
208            .iter()
209            .any(|pid| *pid == 0 || *pid > sysprims_signal::MAX_SAFE_PID)
210    {
211        return unknown_completion(observation);
212    }
213
214    let observed_count = pids.len();
215    pids.sort_unstable();
216    pids.dedup();
217    if pids.len() != observed_count {
218        return unknown_completion(observation);
219    }
220    if pids.is_empty() {
221        ContainmentCompletionEvidence::Empty { observation }
222    } else {
223        ContainmentCompletionEvidence::Survivors {
224            observation,
225            observed_count: pids.len() as u32,
226            survivor_pids: pids,
227        }
228    }
229}
230
231impl TreeKillReliability {
232    pub fn as_str(self) -> &'static str {
233        match self {
234            Self::Guaranteed => "guaranteed",
235            Self::Unproven => "unproven",
236            Self::BestEffort => "best_effort",
237        }
238    }
239}
240
241impl ContainmentBoundaryStrength {
242    pub fn as_str(self) -> &'static str {
243        match self {
244            Self::KernelEnforcedJob => "kernel_enforced_job",
245            Self::CooperativeGroup => "cooperative_group",
246            Self::Unknown => "unknown",
247        }
248    }
249}
250
251/// Stable process evidence captured when containment is acquired.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
253pub struct ContainmentIdentity {
254    pub pid: u32,
255    /// Zero only when a sealed same-spawn receipt is paired with an already
256    /// exited, unreaped child before live metadata can be captured.
257    pub start_time_unix_ms: u64,
258    /// Observational executable metadata captured when containment is acquired.
259    ///
260    /// Unix guards backed by a sealed same-spawn receipt allow this value to
261    /// change across `exec` and may leave it empty when it is unavailable.
262    /// Adopted guards require it to remain available and unchanged. It is also
263    /// empty for the receipt-bound fast-exit state described above.
264    pub exe_path: String,
265}
266
267/// Minimal owned-child contract used by [`ContainmentGuard`].
268///
269/// Consumers can wrap an external child type without exposing PTY handles or
270/// terminal data to sysprims. The adapter must retain exclusive reap ownership
271/// from receipt consumption through guard finalization; `process_id` must name
272/// that unreaped child for the adapter's lifetime.
273pub trait ContainmentChild {
274    fn process_id(&self) -> Option<u32>;
275    /// Poll and reap the child when it has exited.
276    fn try_wait(&mut self) -> std::io::Result<bool>;
277
278    #[cfg(windows)]
279    fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle>;
280}
281
282impl ContainmentChild for Child {
283    fn process_id(&self) -> Option<u32> {
284        Some(self.id())
285    }
286
287    fn try_wait(&mut self) -> std::io::Result<bool> {
288        Child::try_wait(self).map(|status| status.is_some())
289    }
290
291    #[cfg(windows)]
292    fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
293        use std::os::windows::io::AsRawHandle;
294        Some(self.as_raw_handle())
295    }
296}
297
298/// Error returned when containment cannot be acquired.
299///
300/// The child is returned so acquisition failure never silently loses the
301/// caller's only reap handle.
302pub struct ContainmentAdoptionError<C> {
303    pub error: SysprimsError,
304    pub child: C,
305}
306
307impl<C> std::fmt::Debug for ContainmentAdoptionError<C> {
308    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309        formatter
310            .debug_struct("ContainmentAdoptionError")
311            .field("error", &self.error)
312            .finish_non_exhaustive()
313    }
314}
315
316impl<C> std::fmt::Display for ContainmentAdoptionError<C> {
317    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        self.error.fmt(formatter)
319    }
320}
321
322impl<C> std::error::Error for ContainmentAdoptionError<C> {}
323
324/// Error returned when an owned contained spawn cannot complete.
325#[derive(Debug)]
326pub enum ContainmentSpawnError {
327    Spawn(SysprimsError),
328    Adoption(SysprimsError),
329}
330
331impl std::fmt::Display for ContainmentSpawnError {
332    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333        match self {
334            Self::Spawn(error) => error.fmt(formatter),
335            Self::Adoption(error) => error.fmt(formatter),
336        }
337    }
338}
339
340impl std::error::Error for ContainmentSpawnError {}
341
342/// An owned, stateful containment capability and child lifecycle.
343///
344/// Termination and normal completion mutably borrow the guard and are one-shot.
345/// Dropping an active guard kills the contained tree and makes a bounded attempt
346/// to reap the child. The guard never reconstructs containment from a
347/// caller-supplied PID.
348pub struct ContainmentGuard<C: ContainmentChild> {
349    child: Option<C>,
350    identity: ContainmentIdentity,
351    reliability: TreeKillReliability,
352    boundary_strength: ContainmentBoundaryStrength,
353    finalized: bool,
354    #[cfg(unix)]
355    pgid: u32,
356    #[cfg(unix)]
357    session_id: u32,
358    #[cfg(unix)]
359    session_receipt: Option<sysprims_session::UnixSessionReceipt>,
360    #[cfg(windows)]
361    job: std::os::windows::io::OwnedHandle,
362}
363
364impl<C: ContainmentChild> ContainmentGuard<C> {
365    pub fn identity(&self) -> &ContainmentIdentity {
366        &self.identity
367    }
368
369    pub fn tree_kill_reliability(&self) -> TreeKillReliability {
370        self.reliability
371    }
372
373    pub fn boundary_strength(&self) -> ContainmentBoundaryStrength {
374        self.boundary_strength
375    }
376
377    /// Recover the child adapter after successful termination or completion.
378    pub fn into_child(mut self) -> Result<C, Self> {
379        if self.finalized {
380            Ok(self
381                .child
382                .take()
383                .expect("finalized guard retains its child"))
384        } else {
385            Err(self)
386        }
387    }
388
389    /// Finalize a normally exited child without surrendering containment early.
390    ///
391    /// This observes leader exit without reaping. When the leader has exited,
392    /// the method cleans any remaining descendants before reaping and returns
393    /// the resulting outcome. It returns `Ok(None)` while the leader is running.
394    pub fn try_complete(
395        &mut self,
396        config: TerminateTreeConfig,
397    ) -> SysprimsResult<Option<ContainmentOutcome>> {
398        if self.finalized {
399            return Err(SysprimsError::invalid_argument(
400                "containment guard has already been finalized",
401            ));
402        }
403
404        #[cfg(unix)]
405        if !unix::contained_child_has_exited(self)? {
406            return Ok(None);
407        }
408
409        #[cfg(windows)]
410        if !windows::contained_child_has_exited(self)? {
411            return Ok(None);
412        }
413
414        self.terminate(config).map(Some)
415    }
416
417    /// Terminate the owned containment once, preserving the child until reap.
418    pub fn terminate(&mut self, config: TerminateTreeConfig) -> SysprimsResult<ContainmentOutcome> {
419        if self.finalized {
420            return Err(SysprimsError::invalid_argument(
421                "containment guard has already been finalized",
422            ));
423        }
424
425        #[cfg(unix)]
426        return unix::terminate_contained_impl(self, config);
427
428        #[cfg(windows)]
429        return windows::terminate_contained_impl(self, config);
430    }
431}
432
433impl<C: ContainmentChild> Drop for ContainmentGuard<C> {
434    fn drop(&mut self) {
435        if self.finalized || self.child.is_none() {
436            return;
437        }
438
439        #[cfg(unix)]
440        unix::drop_contained_impl(self);
441
442        #[cfg(windows)]
443        windows::drop_contained_impl(self);
444    }
445}
446
447/// Result from terminating an owned containment guard.
448#[derive(Debug, Clone, Serialize)]
449pub struct ContainmentOutcome {
450    pub identity: ContainmentIdentity,
451    #[serde(skip_serializing_if = "Option::is_none")]
452    pub pgid: Option<u32>,
453    #[serde(skip_serializing_if = "Option::is_none")]
454    pub signal_sent: Option<i32>,
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub kill_signal: Option<i32>,
457    pub escalated: bool,
458    pub exited: bool,
459    pub timed_out: bool,
460    pub tree_kill_reliability: TreeKillReliability,
461    pub boundary_strength: ContainmentBoundaryStrength,
462    /// Point-in-time membership evidence collected before leader reap or Job release.
463    pub completion: ContainmentCompletionEvidence,
464    pub warnings: Vec<String>,
465}
466
467/// Adopt an already-running child into an owned containment guard.
468///
469/// Post-spawn adoption is reported as [`TreeKillReliability::Unproven`]
470/// because descendants may escape before acquisition completes.
471pub fn adopt_contained<C: ContainmentChild>(
472    child: C,
473) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
474    #[cfg(unix)]
475    return unix::adopt_contained_impl(child);
476
477    #[cfg(windows)]
478    return windows::adopt_contained_impl(child);
479}
480
481/// Consume a sealed same-spawn session receipt with its owned child.
482///
483/// This is the Unix entry point for an external spawner that installed
484/// [`sysprims_session::UnixSessionAcquisitionHook`] in place of its own
485/// `setsid`/`setpgid` acquisition. The receipt is destroyed on every failure,
486/// and the child is returned through [`ContainmentAdoptionError`].
487///
488/// # Safety
489///
490/// `child` must be the same spawned child that emitted `receipt`. The adapter
491/// must hold exclusive, unreaped ownership, keep `process_id()` stable, and
492/// perform no external wait or reap until the guard finalizes. Violating these
493/// requirements can let PID reuse redirect a group signal to an unrelated
494/// process. Runtime ownership and identity checks remain defense-in-depth.
495#[cfg(unix)]
496pub unsafe fn contain_acquired_session<C: ContainmentChild>(
497    child: C,
498    receipt: sysprims_session::UnixSessionReceipt,
499) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
500    unix::contain_acquired_session_impl(child, receipt)
501}
502
503/// Consume a sealed pre-execution Windows Job receipt with its owned child.
504///
505/// The receipt can only be produced by [`PreparedWindowsJob::assign_process`],
506/// which assigns and verifies the exact process in a non-breakaway Job before
507/// this transition. The child remains suspended until the adapter has received
508/// the guard and explicitly resumes its separately owned primary thread.
509///
510/// # Safety
511///
512/// `child` must own the exact process handle passed to
513/// [`PreparedWindowsJob::assign_process`]. The adapter must still own the
514/// corresponding suspended primary thread, must not have resumed it, and must
515/// transfer exclusive wait/reap authority to the returned guard.
516#[cfg(windows)]
517pub unsafe fn contain_acquired_windows_job<C: ContainmentChild>(
518    child: C,
519    receipt: WindowsJobReceipt,
520) -> Result<ContainmentGuard<C>, ContainmentAdoptionError<C>> {
521    windows::contain_acquired_windows_job_impl(child, receipt)
522}
523
524/// Spawn a standard-library child and return its owned containment guard.
525///
526/// Unix uses the same sealed spawn-time session receipt as
527/// [`contain_acquired_session`] and reports guaranteed acquisition/group
528/// signaling eligibility. Windows fails closed until a create-suspended Job
529/// assignment path is available; use [`adopt_contained`] for explicitly
530/// unproven adoption.
531pub fn spawn_contained(command: Command) -> Result<ContainmentGuard<Child>, ContainmentSpawnError> {
532    #[cfg(unix)]
533    return unix::spawn_contained_impl(command);
534
535    #[cfg(windows)]
536    return windows::spawn_contained_impl(command);
537}
538
539fn capture_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
540    capture_containment_identity_with_mode(pid, ContainmentIdentityValidation::Strict)
541}
542
543#[cfg(unix)]
544fn capture_receipt_bound_containment_identity(pid: u32) -> SysprimsResult<ContainmentIdentity> {
545    capture_containment_identity_with_mode(
546        pid,
547        ContainmentIdentityValidation::ReceiptBoundExecVolatile,
548    )
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552enum ContainmentIdentityValidation {
553    Strict,
554    #[cfg(unix)]
555    ReceiptBoundExecVolatile,
556}
557
558fn capture_containment_identity_with_mode(
559    pid: u32,
560    mode: ContainmentIdentityValidation,
561) -> SysprimsResult<ContainmentIdentity> {
562    if pid == 0 || pid > sysprims_signal::MAX_SAFE_PID {
563        return Err(SysprimsError::invalid_argument(format!(
564            "pid {pid} is outside the safe process identity range"
565        )));
566    }
567
568    let process = sysprims_proc::get_process(pid)?;
569    let start_time_unix_ms = process.start_time_unix_ms.ok_or_else(|| {
570        SysprimsError::system(
571            "process start time unavailable during containment acquisition",
572            0,
573        )
574    })?;
575    let exe_path = match (mode, process.exe_path.filter(|path| !path.is_empty())) {
576        (_, Some(path)) => path,
577        (ContainmentIdentityValidation::Strict, None) => {
578            return Err(SysprimsError::system(
579                "process executable unavailable during containment acquisition",
580                0,
581            ));
582        }
583        #[cfg(unix)]
584        (ContainmentIdentityValidation::ReceiptBoundExecVolatile, None) => String::new(),
585    };
586
587    Ok(ContainmentIdentity {
588        pid,
589        start_time_unix_ms,
590        exe_path,
591    })
592}
593
594#[cfg(unix)]
595fn verify_containment_identity(
596    expected: &ContainmentIdentity,
597    mode: ContainmentIdentityValidation,
598) -> SysprimsResult<bool> {
599    let process = match sysprims_proc::get_process(expected.pid) {
600        Ok(process) => process,
601        Err(SysprimsError::NotFound { .. } | SysprimsError::PermissionDenied { .. }) => {
602            return Ok(false);
603        }
604        Err(error) => return Err(error),
605    };
606
607    verify_containment_identity_observation(
608        expected,
609        process.start_time_unix_ms,
610        process.exe_path.as_deref(),
611        mode,
612    )
613}
614
615#[cfg(unix)]
616fn verify_containment_identity_observation(
617    expected: &ContainmentIdentity,
618    actual_start_time_unix_ms: Option<u64>,
619    actual_exe_path: Option<&str>,
620    mode: ContainmentIdentityValidation,
621) -> SysprimsResult<bool> {
622    if actual_start_time_unix_ms.is_some_and(|actual| actual != expected.start_time_unix_ms) {
623        return Err(SysprimsError::invalid_argument(
624            "process identity changed; refusing containment operation",
625        ));
626    }
627
628    match mode {
629        ContainmentIdentityValidation::Strict => {
630            if actual_exe_path.is_some_and(|actual| actual != expected.exe_path) {
631                return Err(SysprimsError::invalid_argument(
632                    "process identity changed; refusing containment operation",
633                ));
634            }
635            Ok(actual_start_time_unix_ms.is_some() && actual_exe_path.is_some())
636        }
637        ContainmentIdentityValidation::ReceiptBoundExecVolatile => {
638            Ok(actual_start_time_unix_ms.is_some())
639        }
640    }
641}
642
643// =============================================================================
644// Terminate Tree (PID-based)
645// =============================================================================
646
647/// Configuration for PID-based terminate-tree.
648///
649/// This is intentionally small and conservative; higher-level spawn-in-group
650/// APIs can provide stronger guarantees.
651#[derive(Debug, Clone, Deserialize)]
652#[serde(deny_unknown_fields)]
653pub struct TerminateTreeConfig {
654    /// Timeout before escalation.
655    #[serde(default = "default_grace_timeout_ms")]
656    pub grace_timeout_ms: u64,
657
658    /// Timeout to wait after escalation signal.
659    #[serde(default = "default_kill_timeout_ms")]
660    pub kill_timeout_ms: u64,
661
662    /// Signal to send first (default SIGTERM).
663    #[serde(default = "default_grace_signal")]
664    pub signal: i32,
665
666    /// Signal to send on escalation (default SIGKILL).
667    #[serde(default = "default_kill_signal")]
668    pub kill_signal: i32,
669}
670
671fn default_grace_timeout_ms() -> u64 {
672    10_000
673}
674
675fn default_kill_timeout_ms() -> u64 {
676    2_000
677}
678
679fn default_grace_signal() -> i32 {
680    SIGTERM
681}
682
683fn default_kill_signal() -> i32 {
684    SIGKILL
685}
686
687impl Default for TerminateTreeConfig {
688    fn default() -> Self {
689        Self {
690            grace_timeout_ms: default_grace_timeout_ms(),
691            kill_timeout_ms: default_kill_timeout_ms(),
692            signal: default_grace_signal(),
693            kill_signal: default_kill_signal(),
694        }
695    }
696}
697
698#[derive(Debug, Clone, Serialize)]
699pub struct TerminateTreeResult {
700    pub schema_id: &'static str,
701    pub timestamp: String,
702    pub platform: &'static str,
703    pub pid: u32,
704
705    #[serde(skip_serializing_if = "Option::is_none")]
706    pub pgid: Option<u32>,
707
708    pub signal_sent: i32,
709    #[serde(skip_serializing_if = "Option::is_none")]
710    pub kill_signal: Option<i32>,
711    pub escalated: bool,
712    pub exited: bool,
713    pub timed_out: bool,
714    pub tree_kill_reliability: String,
715    pub warnings: Vec<String>,
716}
717
718// =============================================================================
719// Spawn In Group / Job
720// =============================================================================
721
722/// Configuration for [`spawn_in_group`].
723#[derive(Debug, Clone, Deserialize)]
724#[serde(deny_unknown_fields)]
725pub struct SpawnInGroupConfig {
726    /// argv[0] is the command, argv[1..] are args.
727    pub argv: Vec<String>,
728
729    /// Optional working directory.
730    #[serde(default)]
731    pub cwd: Option<String>,
732
733    /// Environment variable overrides/additions.
734    ///
735    /// By default the child inherits the parent's environment.
736    #[serde(default)]
737    pub env: Option<std::collections::BTreeMap<String, String>>,
738}
739
740#[derive(Debug, Clone, Serialize)]
741pub struct SpawnInGroupResult {
742    pub schema_id: &'static str,
743    pub timestamp: String,
744    pub platform: &'static str,
745    pub pid: u32,
746
747    #[serde(skip_serializing_if = "Option::is_none")]
748    pub pgid: Option<u32>,
749
750    pub tree_kill_reliability: String,
751    pub warnings: Vec<String>,
752}
753
754/// Spawn a process in a new process group on Unix.
755///
756/// Use this when you would otherwise shell out to `setsid`/wrapper scripts to
757/// make jobs kill-tree safe.
758///
759/// This PID-returning compatibility API cannot retain the owned child and
760/// sealed receipt required for [`TreeKillReliability::Guaranteed`]. Unix
761/// therefore reports `best_effort`; Windows fails closed because it cannot
762/// retain an owned Job handle. Use [`spawn_contained`] instead.
763///
764/// # Examples
765///
766/// ```rust,no_run
767/// use sysprims_timeout::{spawn_in_group, SpawnInGroupConfig};
768///
769/// // Replaces: setsid sleep 5
770/// let result = spawn_in_group(SpawnInGroupConfig {
771///     argv: vec!["sleep".into(), "5".into()],
772///     cwd: None,
773///     env: None,
774/// })
775/// .unwrap();
776/// println!("spawned pid: {}", result.pid);
777/// ```
778pub fn spawn_in_group(config: SpawnInGroupConfig) -> SysprimsResult<SpawnInGroupResult> {
779    if config.argv.is_empty() {
780        return Err(SysprimsError::invalid_argument("argv must not be empty"));
781    }
782
783    #[cfg(unix)]
784    return unix::spawn_in_group_impl(config);
785
786    #[cfg(windows)]
787    return windows::spawn_in_group_impl(config);
788}
789
790// Timestamp generation consolidated in sysprims_core::time::now_rfc3339()
791
792/// Terminate a process by PID with escalation.
793///
794/// This compatibility API has no owned child or sealed containment receipt, so
795/// it signals only the supplied PID and always reports `best_effort`. Use an
796/// owned [`ContainmentGuard`] for process-group or Job Object termination.
797///
798/// # Examples
799///
800/// ```rust,no_run
801/// use sysprims_timeout::{terminate_tree, TerminateTreeConfig};
802///
803/// // Replaces: kill -TERM 1234; sleep 2; kill -KILL 1234
804/// let result = terminate_tree(1234, TerminateTreeConfig::default()).unwrap();
805/// println!("exited={} timed_out={}", result.exited, result.timed_out);
806/// ```
807pub fn terminate_tree(
808    pid: u32,
809    config: TerminateTreeConfig,
810) -> SysprimsResult<TerminateTreeResult> {
811    if pid == 0 {
812        return Err(SysprimsError::invalid_argument("pid must be > 0"));
813    }
814
815    // Defense in depth: avoid unsafe casts on Unix.
816    // See ADR-0011 (PID Validation Safety).
817    if pid > sysprims_signal::MAX_SAFE_PID {
818        return Err(SysprimsError::invalid_argument(format!(
819            "pid {} exceeds maximum safe value {}",
820            pid,
821            sysprims_signal::MAX_SAFE_PID
822        )));
823    }
824
825    let mut warnings: Vec<String> = Vec::new();
826    let pgid: Option<u32> = None;
827    let reliability = TreeKillReliability::BestEffort;
828
829    #[cfg(windows)]
830    warnings.push(
831        "Windows PID termination is best-effort; use an owned containment guard for Job Objects"
832            .to_string(),
833    );
834    #[cfg(unix)]
835    warnings.push(
836        "PID-only termination has no sealed group capability; signaling the target PID only"
837            .to_string(),
838    );
839
840    // Step 1: send graceful signal
841    sysprims_signal::kill(pid, config.signal)?;
842
843    // Step 2: wait for exit
844    let grace = Duration::from_millis(config.grace_timeout_ms);
845    let grace_wait = wait_pid(pid, grace)?;
846    if grace_wait.exited {
847        return Ok(TerminateTreeResult {
848            schema_id: TERMINATE_TREE_RESULT_V1,
849            timestamp: now_rfc3339(),
850            platform: get_platform(),
851            pid,
852            pgid,
853            signal_sent: config.signal,
854            kill_signal: None,
855            escalated: false,
856            exited: true,
857            timed_out: false,
858            tree_kill_reliability: reliability.as_str().to_string(),
859            warnings,
860        });
861    }
862
863    // Step 3: escalate
864    sysprims_signal::kill(pid, config.kill_signal)?;
865
866    let kill_wait = wait_pid(pid, Duration::from_millis(config.kill_timeout_ms))?;
867    let mut exited = kill_wait.exited;
868    let mut timed_out = kill_wait.timed_out;
869
870    // If we timed out, attempt one final best-effort confirmation.
871    // On some platforms/permission contexts, a process may become unobservable
872    // (or a zombie) even after it has exited.
873    if timed_out {
874        match sysprims_proc::get_process(pid) {
875            Ok(_) => {
876                // Still observable -> treat as still running.
877            }
878            Err(SysprimsError::NotFound { .. }) => {
879                exited = true;
880                timed_out = false;
881                warnings.push("PID no longer found after timeout; treating as exited".to_string());
882            }
883            Err(SysprimsError::PermissionDenied { .. }) => {
884                warnings.push("Permission denied while confirming exit after timeout".to_string());
885            }
886            Err(e) => {
887                warnings.push(format!("Failed to confirm exit after timeout: {}", e));
888            }
889        }
890    }
891
892    Ok(TerminateTreeResult {
893        schema_id: TERMINATE_TREE_RESULT_V1,
894        timestamp: now_rfc3339(),
895        platform: get_platform(),
896        pid,
897        pgid,
898        signal_sent: config.signal,
899        kill_signal: Some(config.kill_signal),
900        escalated: true,
901        exited,
902        timed_out,
903        tree_kill_reliability: reliability.as_str().to_string(),
904        warnings,
905    })
906}
907
908/// Outcome of timeout execution.
909#[derive(Debug)]
910pub enum TimeoutOutcome {
911    /// Command completed within timeout.
912    Completed {
913        /// Exit status of the child process.
914        exit_status: ExitStatus,
915    },
916
917    /// Command timed out and was killed.
918    TimedOut {
919        /// Signal that was sent to terminate the process.
920        signal_sent: i32,
921
922        /// Whether escalation to SIGKILL occurred.
923        ///
924        /// `true` if the process didn't exit after receiving `signal_sent`
925        /// and had to be forcefully killed with SIGKILL.
926        escalated: bool,
927
928        /// Whether tree-kill was reliable.
929        ///
930        /// `Guaranteed` when spawn-time acquisition and group/job signaling
931        /// eligibility were proven.
932        /// `BestEffort` if only the direct child was killed.
933        tree_kill_reliability: TreeKillReliability,
934    },
935}
936
937/// Run a command with timeout.
938///
939/// Spawns the command and waits for it to complete or timeout. If the command
940/// times out, the acquired process group or Job is signaled (when using
941/// `GroupByDefault`). Cooperative descendants in that containment are targeted;
942/// Unix descendants can still leave a process group later.
943///
944/// # Arguments
945///
946/// * `command` - Command to execute (path or name in PATH)
947/// * `args` - Command arguments
948/// * `timeout` - Maximum duration to wait for command completion
949/// * `config` - Timeout configuration (signal, escalation, grouping)
950///
951/// # Returns
952///
953/// * `Ok(TimeoutOutcome::Completed { .. })` - Command finished within timeout
954/// * `Ok(TimeoutOutcome::TimedOut { .. })` - Command was killed due to timeout
955/// * `Err(SysprimsError)` - Failed to spawn or fatal error
956///
957/// # Examples
958///
959/// ```no_run
960/// use std::time::Duration;
961/// use sysprims_timeout::{run_with_timeout, TimeoutConfig};
962///
963/// // Replaces: timeout 300s make build
964/// let result = run_with_timeout(
965///     "make",
966///     &["build"],
967///     Duration::from_secs(300),
968///     TimeoutConfig::default(),
969/// );
970/// ```
971pub fn run_with_timeout(
972    command: &str,
973    args: &[&str],
974    timeout: Duration,
975    config: TimeoutConfig,
976) -> SysprimsResult<TimeoutOutcome> {
977    #[cfg(unix)]
978    return unix::run_with_timeout_impl(command, args, timeout, &config);
979
980    #[cfg(windows)]
981    return windows::run_with_timeout_impl(command, args, timeout, &config);
982}
983
984/// Run a command with timeout using default configuration.
985///
986/// Equivalent to `run_with_timeout(command, args, timeout, TimeoutConfig::default())`.
987///
988/// Default configuration:
989/// - Signal: SIGTERM
990/// - Kill after: 10 seconds
991/// - Grouping: GroupByDefault
992/// - Preserve status: false
993///
994/// # Examples
995///
996/// ```rust,no_run
997/// use std::time::Duration;
998/// use sysprims_timeout::run_with_timeout_default;
999///
1000/// // Replaces: timeout 2s sleep 1
1001/// let _ = run_with_timeout_default("sleep", &["1"], Duration::from_secs(2));
1002/// ```
1003pub fn run_with_timeout_default(
1004    command: &str,
1005    args: &[&str],
1006    timeout: Duration,
1007) -> SysprimsResult<TimeoutOutcome> {
1008    run_with_timeout(command, args, timeout, TimeoutConfig::default())
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::*;
1014    use std::process::{Command, Stdio};
1015
1016    struct ChildWithoutPid;
1017
1018    impl ContainmentChild for ChildWithoutPid {
1019        fn process_id(&self) -> Option<u32> {
1020            None
1021        }
1022
1023        fn try_wait(&mut self) -> std::io::Result<bool> {
1024            Ok(false)
1025        }
1026
1027        #[cfg(windows)]
1028        fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
1029            None
1030        }
1031    }
1032
1033    #[test]
1034    fn default_config_uses_sigterm() {
1035        let config = TimeoutConfig::default();
1036        assert_eq!(config.signal, SIGTERM);
1037    }
1038
1039    #[test]
1040    fn default_config_uses_group_by_default() {
1041        let config = TimeoutConfig::default();
1042        assert_eq!(config.grouping, GroupingMode::GroupByDefault);
1043    }
1044
1045    #[test]
1046    fn default_config_kill_after_is_10_seconds() {
1047        let config = TimeoutConfig::default();
1048        assert_eq!(config.kill_after, Duration::from_secs(10));
1049    }
1050
1051    #[test]
1052    fn default_config_does_not_preserve_status() {
1053        let config = TimeoutConfig::default();
1054        assert!(!config.preserve_status);
1055    }
1056
1057    #[test]
1058    fn reliability_strings_include_unproven() {
1059        assert_eq!(TreeKillReliability::Guaranteed.as_str(), "guaranteed");
1060        assert_eq!(TreeKillReliability::Unproven.as_str(), "unproven");
1061        assert_eq!(TreeKillReliability::BestEffort.as_str(), "best_effort");
1062    }
1063
1064    #[test]
1065    fn boundary_strength_strings_are_independent() {
1066        assert_eq!(
1067            ContainmentBoundaryStrength::KernelEnforcedJob.as_str(),
1068            "kernel_enforced_job"
1069        );
1070        assert_eq!(
1071            ContainmentBoundaryStrength::CooperativeGroup.as_str(),
1072            "cooperative_group"
1073        );
1074        assert_eq!(ContainmentBoundaryStrength::Unknown.as_str(), "unknown");
1075    }
1076
1077    #[test]
1078    #[cfg(unix)]
1079    fn receipt_bound_identity_treats_executable_as_observational() {
1080        let expected = ContainmentIdentity {
1081            pid: 42,
1082            start_time_unix_ms: 1_000,
1083            exe_path: "/before-exec".to_string(),
1084        };
1085
1086        assert!(verify_containment_identity_observation(
1087            &expected,
1088            Some(1_000),
1089            Some("/after-two-execs"),
1090            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1091        )
1092        .unwrap());
1093        assert!(verify_containment_identity_observation(
1094            &expected,
1095            Some(1_000),
1096            None,
1097            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1098        )
1099        .unwrap());
1100    }
1101
1102    #[test]
1103    #[cfg(unix)]
1104    fn receipt_bound_identity_requires_matching_observable_start_time() {
1105        let expected = ContainmentIdentity {
1106            pid: 42,
1107            start_time_unix_ms: 1_000,
1108            exe_path: "/before-exec".to_string(),
1109        };
1110
1111        assert!(!verify_containment_identity_observation(
1112            &expected,
1113            None,
1114            Some("/after-exec"),
1115            ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1116        )
1117        .unwrap());
1118        assert!(matches!(
1119            verify_containment_identity_observation(
1120                &expected,
1121                Some(2_000),
1122                Some("/after-exec"),
1123                ContainmentIdentityValidation::ReceiptBoundExecVolatile,
1124            ),
1125            Err(SysprimsError::InvalidArgument { .. })
1126        ));
1127    }
1128
1129    #[test]
1130    #[cfg(unix)]
1131    fn adopted_identity_keeps_strict_executable_validation() {
1132        let expected = ContainmentIdentity {
1133            pid: 42,
1134            start_time_unix_ms: 1_000,
1135            exe_path: "/before-exec".to_string(),
1136        };
1137
1138        assert!(matches!(
1139            verify_containment_identity_observation(
1140                &expected,
1141                Some(1_000),
1142                Some("/after-exec"),
1143                ContainmentIdentityValidation::Strict,
1144            ),
1145            Err(SysprimsError::InvalidArgument { .. })
1146        ));
1147        assert!(!verify_containment_identity_observation(
1148            &expected,
1149            Some(1_000),
1150            None,
1151            ContainmentIdentityValidation::Strict,
1152        )
1153        .unwrap());
1154    }
1155
1156    #[test]
1157    fn completion_evidence_sorts_unique_safe_pids() {
1158        assert_eq!(
1159            completion_from_pids(
1160                ContainmentObservation::LinuxProcfsProcessGroup,
1161                vec![42, 7, 19],
1162            ),
1163            ContainmentCompletionEvidence::Survivors {
1164                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1165                observed_count: 3,
1166                survivor_pids: vec![7, 19, 42],
1167            }
1168        );
1169    }
1170
1171    #[test]
1172    fn duplicate_completion_evidence_is_unknown() {
1173        assert_eq!(
1174            completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, vec![7, 7],),
1175            ContainmentCompletionEvidence::Unknown {
1176                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1177            }
1178        );
1179    }
1180
1181    #[test]
1182    fn completion_evidence_at_pid_limit_is_unknown() {
1183        let pids = (2..2 + MAX_COMPLETION_OBSERVED_PIDS as u32).collect();
1184        assert_eq!(
1185            completion_from_pids(ContainmentObservation::LinuxProcfsProcessGroup, pids),
1186            ContainmentCompletionEvidence::Unknown {
1187                observation: ContainmentObservation::LinuxProcfsProcessGroup,
1188            }
1189        );
1190    }
1191
1192    #[test]
1193    fn completion_evidence_serializes_as_a_tagged_receipt() {
1194        let value = serde_json::to_value(ContainmentCompletionEvidence::Survivors {
1195            observation: ContainmentObservation::MacosLibprocProcessGroup,
1196            observed_count: 2,
1197            survivor_pids: vec![17, 23],
1198        })
1199        .expect("completion evidence should serialize");
1200        assert_eq!(
1201            value,
1202            serde_json::json!({
1203                "status": "survivors",
1204                "observation": "macos_libproc_process_group",
1205                "observed_count": 2,
1206                "survivor_pids": [17, 23],
1207            })
1208        );
1209    }
1210
1211    #[test]
1212    fn failed_adoption_returns_child_ownership() {
1213        let error = match adopt_contained(ChildWithoutPid) {
1214            Ok(_) => panic!("adoption without a pid must fail"),
1215            Err(error) => error,
1216        };
1217        assert!(matches!(error.error, SysprimsError::InvalidArgument { .. }));
1218        assert!(error.child.process_id().is_none());
1219    }
1220
1221    #[test]
1222    fn terminate_tree_rejects_pid_zero() {
1223        let err = terminate_tree(0, TerminateTreeConfig::default()).unwrap_err();
1224        assert!(matches!(err, SysprimsError::InvalidArgument { .. }));
1225    }
1226
1227    #[test]
1228    #[cfg(unix)]
1229    fn terminate_tree_kills_spawned_child() {
1230        // SAFETY: We spawn this process ourselves and control its PID.
1231        let mut child = Command::new("sleep")
1232            .arg("60")
1233            .stdin(Stdio::null())
1234            .stdout(Stdio::null())
1235            .stderr(Stdio::null())
1236            .spawn()
1237            .expect("Failed to spawn sleep process");
1238
1239        let pid = child.id();
1240        let result = terminate_tree(
1241            pid,
1242            TerminateTreeConfig {
1243                grace_timeout_ms: 100,
1244                kill_timeout_ms: 5000,
1245                ..TerminateTreeConfig::default()
1246            },
1247        )
1248        .expect("terminate_tree should succeed");
1249
1250        assert_eq!(result.pid, pid);
1251        assert!(
1252            result.exited,
1253            "expected child to be exited, got: {result:?}"
1254        );
1255        assert!(!result.timed_out, "unexpected timeout: {result:?}");
1256        assert_eq!(result.tree_kill_reliability, "best_effort");
1257        assert_eq!(result.pgid, None);
1258
1259        let _ = child.wait();
1260    }
1261
1262    #[test]
1263    #[cfg(windows)]
1264    fn terminate_tree_kills_spawned_child() {
1265        // SAFETY: We spawn this process ourselves and control its PID.
1266        let mut child = Command::new("cmd")
1267            .args(["/C", "ping -n 60 127.0.0.1 >NUL"])
1268            .stdin(Stdio::null())
1269            .stdout(Stdio::null())
1270            .stderr(Stdio::null())
1271            .spawn()
1272            .expect("Failed to spawn ping sleep process");
1273
1274        let pid = child.id();
1275        let result = terminate_tree(
1276            pid,
1277            TerminateTreeConfig {
1278                grace_timeout_ms: 100,
1279                kill_timeout_ms: 5000,
1280                ..TerminateTreeConfig::default()
1281            },
1282        )
1283        .expect("terminate_tree should succeed");
1284
1285        assert_eq!(result.pid, pid);
1286        let _ = child.wait();
1287    }
1288}