Skip to main content

muse_code_sdk/spawn/
exit.rs

1use std::io::{self, Read};
2use std::process::ExitStatus;
3use std::sync::{Arc, Mutex};
4
5use super::STDERR_TAIL_LIMIT;
6
7/// Semantic host-exit class shared with the Python and TypeScript SDKs.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ExitKind {
11    /// Exit code 0: the host shut down cleanly.
12    CleanShutdown,
13    /// Exit code 1: the host failed for a reason it could not report over the
14    /// protocol; its stderr says why.
15    UnhandledError,
16    /// Exit code 2: the host refused its command-line arguments.
17    UsageError,
18    /// Exit code 3: the host could not load a usable configuration, profile or
19    /// credentials.
20    ConfigError,
21    /// Exit code 4: another live process owns the session the host was started
22    /// to load.
23    LeaseUnavailable,
24    /// Exit code 5: this host build does not serve the SDK surface, whatever the
25    /// arguments.
26    SdkSurfaceUnavailable,
27    /// Any other exit code, or an exit by signal (an out-of-memory kill, for
28    /// example).
29    Crash,
30}
31
32/// Whether retrying a documented host refusal can help.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum RetryGuidance {
36    /// Do not retry: the same launch fails the same way.
37    Never,
38    /// Retry after fixing the host's configuration.
39    FixConfig,
40    /// Retry once the other process releases the session.
41    AfterLeaseRelease,
42}
43
44/// How the spawned-host close path credits available exit evidence.
45///
46/// On Unix, `Ours` records an accepted SDK escalation signal (`SIGTERM` or
47/// `SIGKILL`) followed by an observed exit signal matching that signal. On
48/// Windows and other non-Unix targets, it records an accepted kill request
49/// before reap. Neither is proof that the request caused the exit: another
50/// actor can win the race and leave indistinguishable exit evidence.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52#[non_exhaustive]
53pub enum CloseAttribution {
54    /// The SDK asked the host to stop: on Unix it sent `SIGTERM` or `SIGKILL`
55    /// and the process died by that signal; on other targets its kill request
56    /// was accepted before the exit was collected, whatever the exit code.
57    Ours,
58    /// The exit does not meet [`Self::Ours`]. This includes a host that exited
59    /// on its own after the SDK closed its input, and, on Unix, one that caught
60    /// the SDK's stop signal and then exited with a code.
61    Theirs,
62}
63
64/// Classified exit evidence. A crash may carry a code or a signal.
65#[derive(Debug, Clone, PartialEq, Eq)]
66#[non_exhaustive]
67pub struct ExitClassification {
68    /// The exit class.
69    pub kind: ExitKind,
70    /// The process exit code, when it exited with one.
71    pub exit_code: Option<i32>,
72    /// The signal that ended the process, when one did (Unix only).
73    pub exit_signal: Option<i32>,
74    /// The last lines the host wrote to stderr, at most
75    /// [`STDERR_TAIL_LIMIT`](crate::spawn::STDERR_TAIL_LIMIT) bytes in all.
76    pub stderr_tail: Vec<String>,
77    /// Whether a retry can help, for exit codes 2 to 5; `None` otherwise.
78    pub retry: Option<RetryGuidance>,
79    /// Who the exit is credited to; see [`CloseAttribution`].
80    pub close_attribution: CloseAttribution,
81}
82
83/// Classify raw process evidence using the host's documented exit table.
84#[must_use]
85pub fn classify_exit(
86    exit_code: Option<i32>,
87    exit_signal: Option<i32>,
88    stderr_tail: Vec<String>,
89    close_attribution: CloseAttribution,
90) -> ExitClassification {
91    let (kind, retry) = match exit_code {
92        Some(0) => (ExitKind::CleanShutdown, None),
93        Some(1) => (ExitKind::UnhandledError, None),
94        Some(2) => (ExitKind::UsageError, Some(RetryGuidance::Never)),
95        Some(3) => (ExitKind::ConfigError, Some(RetryGuidance::FixConfig)),
96        Some(4) => (
97            ExitKind::LeaseUnavailable,
98            Some(RetryGuidance::AfterLeaseRelease),
99        ),
100        Some(5) => (ExitKind::SdkSurfaceUnavailable, Some(RetryGuidance::Never)),
101        _ => (ExitKind::Crash, None),
102    };
103    ExitClassification {
104        kind,
105        exit_code,
106        exit_signal,
107        stderr_tail: bounded_stderr_tail(stderr_tail),
108        retry,
109        close_attribution,
110    }
111}
112
113pub(super) fn classify_status(
114    status: ExitStatus,
115    stderr_tail: Vec<String>,
116    close_attribution: CloseAttribution,
117) -> ExitClassification {
118    let exit = raw_exit(status);
119    classify_exit(exit.0, exit.1, stderr_tail, close_attribution)
120}
121
122pub(super) fn raw_exit(status: ExitStatus) -> (Option<i32>, Option<i32>) {
123    #[cfg(unix)]
124    let signal = std::os::unix::process::ExitStatusExt::signal(&status);
125    #[cfg(not(unix))]
126    let signal = None;
127    (status.code(), signal)
128}
129
130#[derive(Debug, Clone, Default)]
131pub(super) struct StderrTailBuffer(Arc<Mutex<Vec<u8>>>);
132
133impl StderrTailBuffer {
134    fn push(&self, bytes: &[u8]) {
135        let mut tail = self
136            .0
137            .lock()
138            .unwrap_or_else(|poisoned| poisoned.into_inner());
139        let bytes = &bytes[bytes.len().saturating_sub(STDERR_TAIL_LIMIT)..];
140        let overflow = (tail.len() + bytes.len()).saturating_sub(STDERR_TAIL_LIMIT);
141        tail.drain(..overflow);
142        tail.extend(bytes);
143    }
144
145    pub(super) fn snapshot(&self) -> Vec<String> {
146        let bytes = self
147            .0
148            .lock()
149            .unwrap_or_else(|poisoned| poisoned.into_inner())
150            .clone();
151        bounded_stderr_tail(
152            String::from_utf8_lossy(&bytes)
153                .lines()
154                .map(str::to_owned)
155                .collect(),
156        )
157    }
158
159    #[cfg(test)]
160    pub(super) fn len(&self) -> usize {
161        self.0.lock().map_or(usize::MAX, |tail| tail.len())
162    }
163}
164
165pub(super) fn drain_stderr(mut reader: impl Read, tail: StderrTailBuffer) {
166    let mut chunk = [0_u8; 4096];
167    loop {
168        match reader.read(&mut chunk) {
169            Ok(0) => break,
170            Ok(read) => tail.push(&chunk[..read]),
171            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
172            Err(_) => break,
173        }
174    }
175}
176
177fn bounded_stderr_tail(lines: Vec<String>) -> Vec<String> {
178    let mut kept = Vec::new();
179    let mut kept_bytes = 0;
180    for line in lines.into_iter().rev() {
181        let separator = usize::from(!kept.is_empty());
182        if kept_bytes + separator >= STDERR_TAIL_LIMIT {
183            break;
184        }
185        let remaining = STDERR_TAIL_LIMIT - kept_bytes - separator;
186        let line = if line.len() <= remaining {
187            line
188        } else {
189            let mut start = line.len() - remaining;
190            while !line.is_char_boundary(start) {
191                start += 1;
192            }
193            line[start..].to_owned()
194        };
195        kept_bytes += separator + line.len();
196        kept.push(line);
197    }
198    kept.reverse();
199    kept
200}