Skip to main content

ftui_runtime/
process_subscription.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Process subscription for spawning and monitoring external processes.
3//!
4//! [`ProcessSubscription`] wraps [`std::process::Command`] as a first-class
5//! runtime [`Subscription`]. It spawns a child process, captures stdout
6//! line-by-line, and sends messages to the model. When the subscription is
7//! stopped (via [`StopSignal`]), termination of the immediate child is requested
8//! and its cleanup outcome is checked.
9//!
10//! # Migration rationale
11//!
12//! Web Worker APIs and child-process patterns in source frameworks translate
13//! to process-based subscriptions in the terminal context. This provides a
14//! clean target for the migration code emitter.
15//!
16//! # Example
17//!
18//! ```ignore
19//! use ftui_runtime::process_subscription::{ProcessSubscription, ProcessEvent};
20//! use std::time::Duration;
21//!
22//! #[derive(Debug)]
23//! enum Msg {
24//!     ProcessOutput(ProcessEvent),
25//!     // ...
26//! }
27//!
28//! fn subscriptions() -> Vec<Box<dyn Subscription<Msg>>> {
29//!     vec![Box::new(
30//!         ProcessSubscription::new("tail", Msg::ProcessOutput)
31//!             .arg("-f")
32//!             .arg("/var/log/syslog")
33//!             .timeout(Duration::from_secs(60))
34//!     )]
35//! }
36//! ```
37
38#![forbid(unsafe_code)]
39
40use crate::subscription::{StopSignal, StopTrigger, SubId, Subscription, SubscriptionSender};
41use std::collections::hash_map::DefaultHasher;
42use std::hash::{Hash, Hasher};
43use std::io::{self, BufRead, Read, Write};
44use std::process::{Command, Stdio};
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::{Arc, Mutex, mpsc};
47use web_time::{Duration, Instant};
48
49/// Events emitted by a [`ProcessSubscription`].
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub enum ProcessEvent {
52    /// A UTF-8 stdout line, without LF or CRLF, up to [`MAX_PROCESS_LINE_BYTES`].
53    Stdout(String),
54    /// A UTF-8 stderr line, without LF or CRLF, up to [`MAX_PROCESS_LINE_BYTES`].
55    Stderr(String),
56    /// Cumulative valid UTF-8 prefix of the pending stdout line.
57    ///
58    /// Emitted only with [`ProcessSubscription::partial_output`]. Replace the
59    /// previous preview; do not append it or count it as a completed line.
60    /// The original controls are retained for whole-prefix sanitization.
61    StdoutPartial(String),
62    /// Cumulative pending stderr prefix, with the same contract as
63    /// [`Self::StdoutPartial`].
64    StderrPartial(String),
65    /// The process exited with a status code.
66    Exited(i32),
67    /// The process was terminated by a Unix signal.
68    Signaled(i32),
69    /// Termination was requested and the immediate child was reaped.
70    ///
71    /// On Unix its observed status must be SIGKILL. Pending input/output may
72    /// be incomplete. Failed or unconfirmed cleanup produces [`Self::Error`].
73    Killed,
74    /// Spawning, monitoring, or process pipe I/O failed.
75    Error(String),
76}
77
78/// Result of the most recent interrupt request for one process run.
79#[derive(Clone, Debug, PartialEq, Eq)]
80pub enum ProcessInterruptStatus {
81    /// No interrupt has been requested.
82    Idle,
83    /// One interrupt is waiting for the supervisor.
84    Pending,
85    /// The operating system accepted SIGINT; the child may ignore it.
86    Sent,
87    /// Signal delivery failed; no successful delivery is claimed.
88    Failed(String),
89    /// The run closed before the pending request was delivered.
90    Canceled,
91}
92
93/// A snapshot of one process run, independent of model queue capacity.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct ProcessControlStatus {
96    /// Immediate child PID while control is open. Never use it to send signals.
97    pub pid: Option<u32>,
98    /// The supervisor accepts no further requests for this run.
99    pub closed: bool,
100    /// No child was spawned, or its owner confirmed that it was reaped.
101    ///
102    /// This does not prove output drain completion. Wait for this run's terminal
103    /// [`ProcessEvent`] as well before replacing its subscription. A retained
104    /// background reaper can set this after an unconfirmed-cleanup error.
105    pub can_restart: bool,
106    /// Outcome of the most recent interrupt request.
107    pub interrupt: ProcessInterruptStatus,
108}
109
110/// Why an interrupt could not be admitted. No child I/O occurs during admission.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum ProcessControlError {
113    /// The supervisor has not spawned this run yet.
114    NotRunning,
115    /// This run no longer accepts requests.
116    Closed,
117    /// One request is already waiting; there is no unbounded request queue.
118    AlreadyPending,
119    /// SIGINT delivery is not supported on this platform.
120    Unsupported,
121}
122
123#[derive(Debug)]
124struct ProcessControlState {
125    claimed: bool,
126    status: ProcessControlStatus,
127}
128
129/// Cloneable interrupt control for exactly one [`ProcessSubscription`] run.
130///
131/// Keep the handle in the model, rebuilding subscriptions with clones. Tag
132/// process messages with [`generation`](Self::generation) to reject delayed
133/// messages after a restart. Use a fresh handle for each new run. Dropping a
134/// descriptor or a handle clone does not close an active run.
135///
136/// Requests never wait for child I/O or model/stdin queue capacity. The owning
137/// supervisor sends SIGINT to the immediate child on Unix, without a shell or
138/// process-group signal. Linux requires a retained pidfd; if unavailable,
139/// delivery fails instead of falling back to a potentially reused PID. Other
140/// Unix platforms require the supervisor to remain the child's sole reaper.
141#[derive(Clone, Debug)]
142pub struct ProcessControl {
143    id: u64,
144    state: Arc<Mutex<ProcessControlState>>,
145}
146
147impl Default for ProcessControl {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153impl ProcessControl {
154    /// Create control for a future process run.
155    #[must_use]
156    pub fn new() -> Self {
157        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
158        Self {
159            id: NEXT_ID
160                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
161                .expect("process control identity space exhausted"),
162            state: Arc::new(Mutex::new(ProcessControlState {
163                claimed: false,
164                status: ProcessControlStatus {
165                    pid: None,
166                    closed: false,
167                    can_restart: true,
168                    interrupt: ProcessInterruptStatus::Idle,
169                },
170            })),
171        }
172    }
173
174    /// Stable identity shared by clones; fresh handles have distinct identities.
175    #[must_use]
176    pub const fn generation(&self) -> u64 {
177        self.id
178    }
179
180    /// Read one consistent snapshot. A closed handle need not mean output drained.
181    #[must_use]
182    pub fn status(&self) -> ProcessControlStatus {
183        self.state
184            .lock()
185            .unwrap_or_else(|error| error.into_inner())
186            .status
187            .clone()
188    }
189
190    /// Admit one interrupt for the supervisor to deliver.
191    ///
192    /// Admission is not delivery. Read [`status`](Self::status) for the outcome;
193    /// even `Sent` does not imply that a child handler ran or the child exited.
194    pub fn request_interrupt(&self) -> Result<(), ProcessControlError> {
195        if !cfg!(unix) {
196            return Err(ProcessControlError::Unsupported);
197        }
198        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
199        let status = &mut state.status;
200        if status.closed {
201            return Err(ProcessControlError::Closed);
202        }
203        if status.pid.is_none() {
204            return Err(ProcessControlError::NotRunning);
205        }
206        if status.interrupt == ProcessInterruptStatus::Pending {
207            return Err(ProcessControlError::AlreadyPending);
208        }
209        status.interrupt = ProcessInterruptStatus::Pending;
210        Ok(())
211    }
212
213    fn claim(&self) -> Option<ProcessControlRun> {
214        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
215        if state.claimed {
216            return None;
217        }
218        state.claimed = true;
219        Some(ProcessControlRun(self.clone()))
220    }
221
222    fn started(&self, pid: u32) {
223        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
224        state.status.pid = Some(pid);
225        state.status.can_restart = false;
226    }
227
228    fn close(&self) {
229        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
230        state.status.pid = None;
231        state.status.closed = true;
232        if state.status.interrupt == ProcessInterruptStatus::Pending {
233            state.status.interrupt = ProcessInterruptStatus::Canceled;
234        }
235    }
236
237    fn confirm_reaped(&self) {
238        self.state
239            .lock()
240            .unwrap_or_else(|error| error.into_inner())
241            .status
242            .can_restart = true;
243    }
244
245    fn dispatch_interrupt(&self, child: &std::process::Child) {
246        let status = self.status();
247        if status.closed || status.interrupt != ProcessInterruptStatus::Pending {
248            return;
249        }
250        // Only the supervisor calls this, before reaping. No state lock spans
251        // the OS call, and no message queue is needed to publish its result.
252        let result = interrupt_child(child);
253        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
254        state.status.interrupt = match result {
255            Ok(()) => ProcessInterruptStatus::Sent,
256            Err(error) => ProcessInterruptStatus::Failed(error.to_string()),
257        };
258    }
259}
260
261struct ProcessControlRun(ProcessControl);
262
263impl Drop for ProcessControlRun {
264    fn drop(&mut self) {
265        self.0.close();
266    }
267}
268
269#[cfg(unix)]
270fn interrupt_child(child: &std::process::Child) -> io::Result<()> {
271    #[cfg(target_os = "linux")]
272    std::os::linux::process::ChildExt::pidfd(child).map_err(|error| {
273        io::Error::new(
274            io::ErrorKind::Unsupported,
275            format!("retained pidfd unavailable; interrupt not sent: {error}"),
276        )
277    })?;
278    std::os::unix::process::ChildExt::send_signal(child, rustix::process::Signal::INT.as_raw())
279}
280
281#[cfg(not(unix))]
282fn interrupt_child(_child: &std::process::Child) -> io::Result<()> {
283    Err(io::Error::new(
284        io::ErrorKind::Unsupported,
285        "SIGINT is unsupported",
286    ))
287}
288
289/// Maximum queued input lines, excluding the one currently being written.
290pub const PROCESS_INPUT_CAPACITY: usize = 16;
291
292/// A rejected input line. The original text is returned without modification.
293#[derive(Debug, PartialEq, Eq)]
294pub enum ProcessInputError {
295    /// The bounded queue has no room; retry after the child reads input.
296    Full(String),
297    /// Input was closed, or its process run ended.
298    Closed(String),
299    /// The line exceeds [`MAX_PROCESS_LINE_BYTES`] UTF-8 bytes.
300    TooLong(String),
301}
302
303#[derive(Debug)]
304struct ProcessInputState {
305    sender: Option<mpsc::SyncSender<Box<str>>>,
306    receiver: Option<mpsc::Receiver<Box<str>>>,
307}
308
309/// Bounded, cloneable input for one [`ProcessSubscription`] run.
310///
311/// Keep this handle in the model and pass a clone to [`ProcessSubscription::stdin`]
312/// each time `subscriptions()` is rebuilt. Clones share one queue and identity.
313/// A fresh handle is required to start another process run. Dropping a clone
314/// does not close input; call [`close`](Self::close) to request EOF.
315///
316/// Sending never waits for pipe I/O or queue capacity. At most
317/// [`PROCESS_INPUT_CAPACITY`] lines are queued, plus one being written, each
318/// limited to [`MAX_PROCESS_LINE_BYTES`] bytes. Acceptance means queued, not
319/// acknowledged by the child; stop, exit, or I/O failure can discard pending
320/// input. A worker writes accepted lines in FIFO order with an appended LF.
321#[derive(Clone, Debug)]
322pub struct ProcessInput {
323    id: u64,
324    state: Arc<Mutex<ProcessInputState>>,
325}
326
327impl Default for ProcessInput {
328    fn default() -> Self {
329        Self::new()
330    }
331}
332
333impl ProcessInput {
334    /// Create input for a single future process run. Lines may be queued now.
335    #[must_use]
336    pub fn new() -> Self {
337        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
338        let (sender, receiver) = mpsc::sync_channel(PROCESS_INPUT_CAPACITY);
339        Self {
340            id: NEXT_ID
341                .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
342                .expect("process input identity space exhausted"),
343            state: Arc::new(Mutex::new(ProcessInputState {
344                sender: Some(sender),
345                receiver: Some(receiver),
346            })),
347        }
348    }
349
350    /// Queue UTF-8 text followed by LF, preserving any embedded newlines.
351    ///
352    /// Returns the unchanged text on rejection. Oversized input is checked
353    /// before queue state. The short state lock never covers child I/O.
354    pub fn try_send_line(&self, line: String) -> Result<(), ProcessInputError> {
355        if line.len() > MAX_PROCESS_LINE_BYTES {
356            return Err(ProcessInputError::TooLong(line));
357        }
358        let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
359        let Some(sender) = &state.sender else {
360            return Err(ProcessInputError::Closed(line));
361        };
362        // Do not retain excess capacity supplied by the caller in the queue.
363        match sender.try_send(line.into_boxed_str()) {
364            Ok(()) => Ok(()),
365            Err(mpsc::TrySendError::Full(line)) => Err(ProcessInputError::Full(line.into())),
366            Err(mpsc::TrySendError::Disconnected(line)) => {
367                Err(ProcessInputError::Closed(line.into()))
368            }
369        }
370    }
371
372    /// Reject future sends, drain accepted lines, then close the child's stdin.
373    ///
374    /// This is idempotent across clones. Drain still depends on the child
375    /// reading; stop/timeout can cancel it. Closing before spawn gives EOF
376    /// after any lines already queued.
377    pub fn close(&self) {
378        self.state
379            .lock()
380            .unwrap_or_else(|error| error.into_inner())
381            .sender
382            .take();
383    }
384
385    fn claim(&self) -> Option<(ProcessInputRun, mpsc::Receiver<Box<str>>)> {
386        let receiver = self
387            .state
388            .lock()
389            .unwrap_or_else(|error| error.into_inner())
390            .receiver
391            .take()?;
392        Some((ProcessInputRun(self.clone()), receiver))
393    }
394}
395
396struct ProcessInputRun(ProcessInput);
397
398impl Drop for ProcessInputRun {
399    fn drop(&mut self) {
400        self.0.close();
401    }
402}
403
404fn write_process_input(
405    stdin: std::process::ChildStdin,
406    receiver: mpsc::Receiver<Box<str>>,
407    stop: StopSignal,
408) -> io::Result<()> {
409    #[cfg(unix)]
410    let mut stdin = process_pipe(stdin, stop.clone())?;
411    #[cfg(not(unix))]
412    let mut stdin = stdin;
413    loop {
414        match receiver.recv_timeout(PROCESS_READER_JOIN_POLL) {
415            Ok(line) => {
416                if stop.is_stopped() {
417                    return Err(io::Error::other("queued stdin was canceled before writing"));
418                }
419                stdin.write_all(line.as_bytes())?;
420                stdin.write_all(b"\n")?;
421            }
422            Err(mpsc::RecvTimeoutError::Timeout) if stop.is_stopped() => break,
423            Err(mpsc::RecvTimeoutError::Timeout) => {}
424            Err(mpsc::RecvTimeoutError::Disconnected) => break,
425        }
426    }
427    Ok(())
428}
429
430// Only the parent-owned endpoint becomes nonblocking. The child's opposite
431// endpoint remains blocking, including copies inherited by its descendants.
432#[cfg(unix)]
433fn process_pipe<P: std::os::fd::AsFd>(pipe: P, stop: StopSignal) -> io::Result<ProcessPipe<P>> {
434    rustix::io::ioctl_fionbio(&pipe, true)?;
435    Ok(ProcessPipe { pipe, stop })
436}
437
438#[cfg(unix)]
439struct ProcessPipe<P> {
440    pipe: P,
441    stop: StopSignal,
442}
443
444#[cfg(unix)]
445impl<P: std::os::fd::AsFd> ProcessPipe<P> {
446    fn wait_ready(&self, interest: rustix::event::PollFlags) -> io::Result<()> {
447        let mut fds = [rustix::event::PollFd::new(&self.pipe, interest)];
448        // Readiness wakes immediately for data/space/EOF. The finite timeout
449        // bounds cancellation latency even when a descendant holds the pipe.
450        let timeout = rustix::event::Timespec {
451            tv_sec: 0,
452            tv_nsec: 50_000_000,
453        };
454        match rustix::event::poll(&mut fds, Some(&timeout)) {
455            Ok(_) | Err(rustix::io::Errno::INTR) => Ok(()),
456            Err(error) => Err(error.into()),
457        }
458    }
459}
460
461#[cfg(unix)]
462impl<P: Read + std::os::fd::AsFd> Read for ProcessPipe<P> {
463    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
464        loop {
465            if self.stop.is_stopped() {
466                // read_process_line checks stop before retrying Interrupted.
467                return Err(io::Error::from(io::ErrorKind::Interrupted));
468            }
469            match self.pipe.read(buffer) {
470                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
471                    self.wait_ready(rustix::event::PollFlags::IN)?;
472                }
473                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
474                result => return result,
475            }
476        }
477    }
478}
479
480#[cfg(unix)]
481impl<P: Write + std::os::fd::AsFd> Write for ProcessPipe<P> {
482    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
483        loop {
484            if self.stop.is_stopped() {
485                // write_all retries Interrupted; cancellation must terminate
486                // that loop rather than spinning on a permanently stopped run.
487                return Err(io::Error::other("stdin write canceled before completion"));
488            }
489            match self.pipe.write(buffer) {
490                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
491                    self.wait_ready(rustix::event::PollFlags::OUT)?;
492                }
493                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
494                result => return result,
495            }
496        }
497    }
498
499    fn flush(&mut self) -> io::Result<()> {
500        self.pipe.flush()
501    }
502}
503
504/// A subscription that spawns and monitors an external process.
505///
506/// Captures stdout/stderr line-by-line and sends [`ProcessEvent`] messages.
507/// Termination is requested when the subscription's [`StopSignal`] fires or
508/// when the optional timeout expires. [`ProcessEvent::Killed`] requires a
509/// successful kill request and confirmed reaping (with SIGKILL status on Unix).
510/// Failed or unconfirmed cleanup produces [`ProcessEvent::Error`].
511///
512/// Normal exit waits for stdout/stderr forwarding to finish, including bounded
513/// channel backpressure. The timeout remains active during that drain. If the
514/// drain is canceled after the child exits, an error describes the exit and
515/// incomplete output. Cancellation can reject an unsent line, preview, or final
516/// status when the model queue is full; final-status delivery is not guaranteed.
517/// Each UTF-8 line is limited to [`MAX_PROCESS_LINE_BYTES`] payload bytes.
518/// LF and its immediately preceding CR are excluded from the limit. An
519/// unterminated final line is delivered at EOF (preserving any trailing CR).
520/// Opt-in [`partial_output`](Self::partial_output) also previews growing valid
521/// prefixes before the next read blocks. It does not change completed lines.
522/// Oversized lines, invalid UTF-8, and read failures stop forwarding, request
523/// termination of the immediate child, and produce one error instead of a
524/// normal exit. That error reports incomplete output and the cleanup outcome.
525/// Monitoring and input failures use the same cleanup path. After an accepted
526/// kill request, foreground reaping is limited to 500 ms; a rejected request
527/// never leads to a blocking foreground wait. If ownership remains safe, an
528/// unconfirmed child is handed to a background reaper. If that thread cannot
529/// start, the error says so; a later wait failure is logged and leaves restart
530/// disabled. Late reaping does not turn the earlier error into success. Linux
531/// retains a pidfd when available; after a wait error, targets without a
532/// retained process handle refuse further waits and signals for that PID.
533/// On Unix, parent pipe endpoints use nonblocking I/O and readiness waits;
534/// cancellation stops the workers even if descendants retain their endpoints.
535/// Other targets still use blocking pipes and bounded joins, so an inherited
536/// endpoint can keep a detached worker alive after cancellation.
537/// Input is closed by default; [`stdin`](Self::stdin) enables a bounded input
538/// worker. Descendant termination and reaping are not provided on any target.
539/// Cancellation is not an atomic write boundary: a prefix may already have
540/// reached the child, and an I/O syscall can race with the stop request.
541/// Optional [`control`](Self::control) admits interrupts independently of those
542/// queues. Its generation belongs to one run. Restart only after that run's
543/// terminal event and confirmed child cleanup, using a fresh control handle.
544pub struct ProcessSubscription<M: Send + 'static> {
545    program: String,
546    args: Vec<String>,
547    env: Vec<(String, String)>,
548    timeout: Option<Duration>,
549    input: Option<ProcessInput>,
550    control: Option<ProcessControl>,
551    partial_output: bool,
552    id: SubId,
553    explicit_id: bool,
554    make_msg: std::sync::Arc<dyn Fn(ProcessEvent) -> M + Send + Sync>,
555}
556
557const PROCESS_READER_JOIN_TIMEOUT: Duration = Duration::from_millis(250);
558const PROCESS_READER_JOIN_POLL: Duration = Duration::from_millis(5);
559const PROCESS_REAP_TIMEOUT: Duration = Duration::from_millis(500);
560
561/// Maximum UTF-8 payload bytes in a process stdout/stderr line (64 KiB).
562///
563/// The LF or CRLF delimiter is excluded. Each reader's assembly buffer holds
564/// at most this many bytes plus one possible CR delimiter, alongside an 8 KiB
565/// input buffer and one in-flight line or preview of at most this many bytes.
566/// This does not bound allocations in the message conversion callback or model.
567pub const MAX_PROCESS_LINE_BYTES: usize = 64 * 1024;
568
569#[derive(Debug)]
570enum ProcessReadError {
571    LineTooLong,
572    InvalidUtf8(std::str::Utf8Error),
573    Io(io::Error),
574}
575
576impl std::fmt::Display for ProcessReadError {
577    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578        match self {
579            Self::LineTooLong => write!(f, "line exceeds {MAX_PROCESS_LINE_BYTES} payload bytes"),
580            Self::InvalidUtf8(error) => write!(f, "invalid UTF-8: {error}"),
581            Self::Io(error) => write!(f, "read failed: {error}"),
582        }
583    }
584}
585
586fn read_process_line<R: BufRead>(
587    reader: &mut R,
588    line: &mut Vec<u8>,
589    stop: &StopSignal,
590    mut preview: Option<&mut dyn FnMut(&str) -> bool>,
591) -> Result<Option<String>, ProcessReadError> {
592    line.clear();
593    let mut previewed_bytes = 0;
594    loop {
595        if stop.is_stopped() {
596            return Ok(None);
597        }
598        let available = match reader.fill_buf() {
599            Ok(available) => available,
600            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
601            Err(error) => return Err(ProcessReadError::Io(error)),
602        };
603        if available.is_empty() {
604            if line.is_empty() {
605                return Ok(None);
606            }
607            break;
608        }
609        let end = available.iter().position(|byte| *byte == b'\n');
610        let count = end.unwrap_or(available.len());
611        let payload = &available[..count];
612        let total = line.len().saturating_add(count);
613        // Retain one extra CR only while it could still be part of CRLF.
614        // Check before appending so allocation never follows untrusted length.
615        if total > MAX_PROCESS_LINE_BYTES
616            && (total != MAX_PROCESS_LINE_BYTES + 1
617                || payload.last().or_else(|| line.last()) != Some(&b'\r'))
618        {
619            return Err(ProcessReadError::LineTooLong);
620        }
621        line.extend_from_slice(payload);
622        reader.consume(count + usize::from(end.is_some()));
623        if end.is_some() {
624            if line.last() == Some(&b'\r') {
625                line.pop();
626            }
627            break;
628        }
629        if let Some(preview) = preview.as_mut() {
630            let prefix = match std::str::from_utf8(line) {
631                Ok(text) => text,
632                Err(error) if error.error_len().is_none() => {
633                    // Preserve an incomplete scalar for the next physical read.
634                    std::str::from_utf8(&line[..error.valid_up_to()])
635                        .map_err(ProcessReadError::InvalidUtf8)?
636                }
637                Err(error) => return Err(ProcessReadError::InvalidUtf8(error)),
638            };
639            // A final CR might be the first half of CRLF. Keep it in assembly
640            // but do not expose it until another payload byte or EOF resolves it.
641            let prefix = if line.last() == Some(&b'\r') {
642                prefix.strip_suffix('\r').unwrap_or(prefix)
643            } else {
644                prefix
645            };
646            if prefix.len() > previewed_bytes {
647                if !preview(prefix) {
648                    return Ok(None);
649                }
650                previewed_bytes = prefix.len();
651            }
652        }
653    }
654    if line.len() > MAX_PROCESS_LINE_BYTES {
655        return Err(ProcessReadError::LineTooLong);
656    }
657    let text = std::str::from_utf8(line).map_err(ProcessReadError::InvalidUtf8)?;
658    // Copy only the payload; the reusable maximum-sized assembly buffer stays
659    // with the reader instead of inflating every short queued message.
660    Ok(Some(text.to_owned()))
661}
662
663fn forward_lines<R: Read, M: Send + 'static>(
664    reader: R,
665    sender: SubscriptionSender<M>,
666    stop: StopSignal,
667    partial_output: bool,
668    make_msg: impl Fn(String) -> M,
669    make_partial: impl Fn(String) -> M,
670) -> Result<(), ProcessReadError> {
671    let mut reader = io::BufReader::with_capacity(8 * 1024, reader);
672    let mut line = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
673    let mut preview = |prefix: &str| {
674        if stop.is_stopped() {
675            return false;
676        }
677        let message = make_partial(prefix.to_owned());
678        !stop.is_stopped() && sender.send(message).is_ok()
679    };
680    while let Some(line) = read_process_line(
681        &mut reader,
682        &mut line,
683        &stop,
684        partial_output.then_some(&mut preview as &mut dyn FnMut(&str) -> bool),
685    )? {
686        if stop.is_stopped() {
687            break;
688        }
689        let message = make_msg(line);
690        if stop.is_stopped() || sender.send(message).is_err() {
691            break;
692        }
693    }
694    Ok(())
695}
696
697fn take_reader_error<E: std::fmt::Display>(
698    handle: &mut Option<std::thread::JoinHandle<Result<(), E>>>,
699    stream: &str,
700) -> Option<String> {
701    if !handle
702        .as_ref()
703        .is_some_and(std::thread::JoinHandle::is_finished)
704    {
705        return None;
706    }
707    match handle.take()?.join() {
708        Ok(Ok(())) => None,
709        Ok(Err(error)) => Some(format!("{stream} {error}")),
710        Err(_) => Some(format!("{stream} worker panicked")),
711    }
712}
713
714#[derive(Debug)]
715struct ChildCleanup {
716    status: Option<std::process::ExitStatus>,
717    kill_sent: bool,
718    detail: String,
719}
720
721impl ChildCleanup {
722    fn reaped(status: std::process::ExitStatus, kill_sent: bool, prior_error: &str) -> Self {
723        Self {
724            status: Some(status),
725            kill_sent,
726            detail: format!(
727                "{prior_error}child reaped: {:?}",
728                process_exit_event(status)
729            ),
730        }
731    }
732
733    fn unconfirmed(detail: String) -> Self {
734        Self {
735            status: None,
736            kill_sent: false,
737            detail: format!("{detail}; child may still be running or unreaped"),
738        }
739    }
740}
741
742fn reap_child_until(
743    child: &mut std::process::Child,
744    deadline: Instant,
745    wait_error: &mut Option<String>,
746) -> io::Result<Option<std::process::ExitStatus>> {
747    loop {
748        match try_wait_child(child, wait_error) {
749            Ok(Some(status)) => return Ok(Some(status)),
750            Ok(None) => {}
751            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
752            Err(error) => return Err(error),
753        }
754        let remaining = deadline.saturating_duration_since(Instant::now());
755        if remaining.is_zero() {
756            return Ok(None);
757        }
758        // A stopped cancellation token would return immediately and spin.
759        std::thread::sleep(PROCESS_READER_JOIN_POLL.min(remaining));
760    }
761}
762
763fn has_retained_process_handle(child: &std::process::Child) -> bool {
764    #[cfg(target_os = "linux")]
765    {
766        std::os::linux::process::ChildExt::pidfd(child).is_ok()
767    }
768    #[cfg(not(target_os = "linux"))]
769    {
770        let _ = child;
771        // Windows retains a process handle; other Unix targets only retain a
772        // PID, which must not be signaled after ownership becomes uncertain.
773        cfg!(windows)
774    }
775}
776
777fn try_wait_child(
778    child: &mut std::process::Child,
779    wait_error: &mut Option<String>,
780) -> io::Result<Option<std::process::ExitStatus>> {
781    if let Some(error) = wait_error.as_ref()
782        && !has_retained_process_handle(child)
783    {
784        // Ownership uncertainty is sticky. A later numeric-PID wait could
785        // observe a different child that reused this PID, even without a kill.
786        return Err(io::Error::other(error.clone()));
787    }
788    let result = child.try_wait();
789    if let Err(error) = &result {
790        wait_error.get_or_insert_with(|| error.to_string());
791    }
792    result
793}
794
795fn cleanup_child(child: &mut std::process::Child, wait_error: &mut Option<String>) -> ChildCleanup {
796    let prior_error = match try_wait_child(child, wait_error) {
797        Ok(Some(status)) => return ChildCleanup::reaped(status, false, ""),
798        Ok(None) => String::new(),
799        Err(error) => {
800            let context = format!("child wait failed: {error}; ");
801            if !has_retained_process_handle(child) {
802                return ChildCleanup::unconfirmed(format!(
803                    "{context}kill and further waits not attempted without a retained process handle"
804                ));
805            }
806            context
807        }
808    };
809    if let Err(error) = child.kill() {
810        let context = format!("{prior_error}child kill failed: {error}; ");
811        // An exit can race with kill. Observe it once; never block waiting for
812        // a still-running child after the termination request was rejected.
813        return match try_wait_child(child, wait_error) {
814            Ok(Some(status)) => ChildCleanup::reaped(status, false, &context),
815            Ok(None) => ChildCleanup::unconfirmed(format!("{context}child has not exited")),
816            Err(error) => ChildCleanup::unconfirmed(format!("{context}reaping failed: {error}")),
817        };
818    }
819    // This budget is independent of an already-expired subscription timeout.
820    match reap_child_until(child, Instant::now() + PROCESS_REAP_TIMEOUT, wait_error) {
821        Ok(Some(status)) => ChildCleanup::reaped(status, true, &prior_error),
822        Ok(None) => ChildCleanup::unconfirmed(format!(
823            "{prior_error}child kill accepted but reaping exceeded {} ms",
824            PROCESS_REAP_TIMEOUT.as_millis()
825        )),
826        Err(error) => ChildCleanup::unconfirmed(format!(
827            "{prior_error}child kill accepted but reaping failed: {error}"
828        )),
829    }
830}
831
832fn cleanup_failure_event(error: &str, cleanup: &ChildCleanup) -> ProcessEvent {
833    ProcessEvent::Error(format!(
834        "{error}; {}; stdout/stderr output is incomplete",
835        cleanup.detail
836    ))
837}
838
839fn output_failure_event(
840    error: &str,
841    child: &mut std::process::Child,
842    wait_error: &mut Option<String>,
843) -> ProcessEvent {
844    cleanup_failure_event(error, &cleanup_child(child, wait_error))
845}
846
847fn stopped_process_event(
848    reason: &str,
849    child: &mut std::process::Child,
850    wait_error: &mut Option<String>,
851) -> ProcessEvent {
852    let cleanup = cleanup_child(child, wait_error);
853    let terminated = cleanup.status.is_some_and(|status| {
854        #[cfg(unix)]
855        {
856            use std::os::unix::process::ExitStatusExt;
857            status.signal() == Some(rustix::process::Signal::KILL.as_raw())
858        }
859        #[cfg(not(unix))]
860        {
861            let _ = status;
862            true
863        }
864    });
865    if cleanup.kill_sent && terminated {
866        ProcessEvent::Killed
867    } else {
868        cleanup_failure_event(reason, &cleanup)
869    }
870}
871
872fn reap_child_in_background(
873    mut child: std::process::Child,
874    control: Option<ProcessControl>,
875    sub_id: SubId,
876) -> io::Result<()> {
877    std::thread::Builder::new()
878        .name("ftui-process-reaper".to_owned())
879        .spawn(move || match child.wait() {
880            Ok(status) => {
881                if let Some(control) = control {
882                    control.confirm_reaped();
883                }
884                tracing::debug!(sub_id, ?status, "background child reaping completed");
885            }
886            Err(error) => {
887                tracing::warn!(sub_id, %error, "background child reaping failed");
888            }
889        })
890        .map(|_| ())
891}
892
893impl<M: Send + 'static> ProcessSubscription<M> {
894    fn computed_id(
895        program: &str,
896        args: &[String],
897        env: &[(String, String)],
898        timeout: Option<Duration>,
899        input: Option<&ProcessInput>,
900        control: Option<&ProcessControl>,
901        partial_output: bool,
902    ) -> SubId {
903        let mut h = DefaultHasher::new();
904        "ProcessSubscription".hash(&mut h);
905        program.hash(&mut h);
906        args.hash(&mut h);
907        env.hash(&mut h);
908        timeout.map(|duration| duration.as_nanos()).hash(&mut h);
909        input.map(|input| input.id).hash(&mut h);
910        control.map(ProcessControl::generation).hash(&mut h);
911        partial_output.hash(&mut h);
912        h.finish()
913    }
914
915    fn refresh_id(&mut self) {
916        if !self.explicit_id {
917            self.id = Self::computed_id(
918                &self.program,
919                &self.args,
920                &self.env,
921                self.timeout,
922                self.input.as_ref(),
923                self.control.as_ref(),
924                self.partial_output,
925            );
926        }
927    }
928
929    /// Create a new process subscription for the given program.
930    ///
931    /// The `make_msg` closure converts [`ProcessEvent`] into your model's
932    /// message type.
933    pub fn new(
934        program: impl Into<String>,
935        make_msg: impl Fn(ProcessEvent) -> M + Send + Sync + 'static,
936    ) -> Self {
937        let program = program.into();
938        let id = Self::computed_id(&program, &[], &[], None, None, None, false);
939        Self {
940            program,
941            args: Vec::new(),
942            env: Vec::new(),
943            timeout: None,
944            input: None,
945            control: None,
946            partial_output: false,
947            id,
948            explicit_id: false,
949            make_msg: std::sync::Arc::new(make_msg),
950        }
951    }
952
953    /// Add a command-line argument.
954    #[must_use]
955    pub fn arg(mut self, arg: impl Into<String>) -> Self {
956        self.args.push(arg.into());
957        self.refresh_id();
958        self
959    }
960
961    /// Add multiple command-line arguments.
962    #[must_use]
963    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
964        for a in args {
965            self = self.arg(a);
966        }
967        self
968    }
969
970    /// Set an environment variable for the child process.
971    #[must_use]
972    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
973        self.env.push((key.into(), value.into()));
974        self.refresh_id();
975        self
976    }
977
978    /// Set a timeout after which the process is killed.
979    #[must_use]
980    pub fn timeout(mut self, duration: Duration) -> Self {
981        self.timeout = Some(duration);
982        self.refresh_id();
983        self
984    }
985
986    /// Connect bounded input for this process run.
987    ///
988    /// Reuse clones of the same handle when rebuilding subscriptions. A new
989    /// handle changes the automatic subscription ID. An already-used handle
990    /// produces an error before spawning; use a new handle for a restart.
991    #[must_use]
992    pub fn stdin(mut self, input: ProcessInput) -> Self {
993        self.input = Some(input);
994        self.refresh_id();
995        self
996    }
997
998    /// Attach supervisor-owned interrupt control for this run.
999    ///
1000    /// Clones preserve the automatic subscription ID. A fresh handle changes
1001    /// it, including when stdin is disabled. A used handle cannot spawn again.
1002    #[must_use]
1003    pub fn control(mut self, control: ProcessControl) -> Self {
1004        self.control = Some(control);
1005        self.refresh_id();
1006        self
1007    }
1008
1009    /// Preview pending stdout/stderr lines before LF or EOF (default: false).
1010    ///
1011    /// Each nonempty preview replaces the prior preview for that stream. It
1012    /// contains the original cumulative valid UTF-8 prefix, including controls;
1013    /// sanitize the whole prefix when rendering, rather than individual pieces.
1014    /// An incomplete UTF-8 scalar and one possible CRLF delimiter are retained
1015    /// until resolved. Completed [`ProcessEvent::Stdout`] and
1016    /// [`ProcessEvent::Stderr`] events remain unchanged, including trailing CR
1017    /// at EOF. Clear previews on completed lines and terminal events.
1018    ///
1019    /// Previews share the bounded, interruptible output queue and the 64 KiB
1020    /// line bound; they can be delayed by backpressure. Earlier prefixes may
1021    /// already be visible when a later read fails UTF-8 or size validation.
1022    /// This does not force an unflushed child to write or provide arbitrary
1023    /// binary streaming. Unix pipe cancellation is independent of this setting;
1024    /// other targets can still block in OS reads. Changing this setting changes
1025    /// the automatic subscription ID.
1026    #[must_use]
1027    pub fn partial_output(mut self, enabled: bool) -> Self {
1028        self.partial_output = enabled;
1029        self.refresh_id();
1030        self
1031    }
1032
1033    /// Override the subscription ID (for explicit deduplication control).
1034    #[must_use]
1035    pub fn with_id(mut self, id: SubId) -> Self {
1036        self.id = id;
1037        self.explicit_id = true;
1038        self
1039    }
1040}
1041
1042impl<M: Send + 'static> Subscription<M> for ProcessSubscription<M> {
1043    fn id(&self) -> SubId {
1044        self.id
1045    }
1046
1047    fn run(&self, sender: SubscriptionSender<M>, stop: StopSignal) {
1048        let spawn_start = web_time::Instant::now();
1049        let sub_id = self.id;
1050        let _control_guard = if let Some(control) = &self.control {
1051            let Some(guard) = control.claim() else {
1052                let _ = send_terminal_message(
1053                    &sender,
1054                    &stop,
1055                    self.timeout.map(|timeout| spawn_start + timeout),
1056                    (self.make_msg)(ProcessEvent::Error(
1057                        "control handle was already used; create fresh control for a new run"
1058                            .to_owned(),
1059                    )),
1060                );
1061                return;
1062            };
1063            Some(guard)
1064        } else {
1065            None
1066        };
1067        let input_run = if let Some(input) = &self.input {
1068            let Some(run) = input.claim() else {
1069                if let Some(control) = &self.control {
1070                    control.close();
1071                }
1072                let _ = send_terminal_message(
1073                    &sender,
1074                    &stop,
1075                    self.timeout.map(|timeout| spawn_start + timeout),
1076                    (self.make_msg)(ProcessEvent::Error(
1077                        "stdin handle was already used; create fresh input for a new run"
1078                            .to_owned(),
1079                    )),
1080                );
1081                return;
1082            };
1083            Some(run)
1084        } else {
1085            None
1086        };
1087        let (_input_guard, input_receiver) = input_run.unzip();
1088
1089        let mut cmd = Command::new(&self.program);
1090        cmd.args(&self.args)
1091            .stdout(Stdio::piped())
1092            .stderr(Stdio::piped())
1093            .stdin(if input_receiver.is_some() {
1094                Stdio::piped()
1095            } else {
1096                Stdio::null()
1097            });
1098
1099        for (k, v) in &self.env {
1100            cmd.env(k, v);
1101        }
1102
1103        #[cfg(target_os = "linux")]
1104        {
1105            std::os::linux::process::CommandExt::create_pidfd(&mut cmd, true);
1106        }
1107
1108        let mut child = match cmd.spawn() {
1109            Ok(c) => {
1110                tracing::debug!(
1111                    target: crate::telemetry_schema::TARGET_PROCESS,
1112                    sub_id,
1113                    program = %self.program,
1114                    args = ?self.args,
1115                    spawn_us = spawn_start.elapsed().as_micros() as u64,
1116                    "process spawned"
1117                );
1118                c
1119            }
1120            Err(e) => {
1121                if let Some(control) = &self.control {
1122                    control.close();
1123                }
1124                if let Some(input) = &self.input {
1125                    input.close();
1126                }
1127                tracing::warn!(
1128                    target: crate::telemetry_schema::TARGET_PROCESS,
1129                    sub_id,
1130                    program = %self.program,
1131                    error = %e,
1132                    "process spawn failed"
1133                );
1134                let message = (self.make_msg.as_ref())(ProcessEvent::Error(format!(
1135                    "Failed to spawn '{}': {}",
1136                    self.program, e
1137                )));
1138                let _ = send_terminal_message(
1139                    &sender,
1140                    &stop,
1141                    self.timeout.map(|timeout| spawn_start + timeout),
1142                    message,
1143                );
1144                return;
1145            }
1146        };
1147
1148        if let Some(control) = &self.control {
1149            control.started(child.id());
1150        }
1151
1152        let deadline = self.timeout.map(|t| web_time::Instant::now() + t);
1153        let stdout = child.stdout.take();
1154        let stderr = child.stderr.take();
1155        let make_msg_ref = std::sync::Arc::clone(&self.make_msg);
1156        // Use the cancellation token for cooperative stop coordination.
1157        let token = stop.cancellation_token().clone();
1158        let (reader_stop, reader_trigger) = StopSignal::new();
1159        let (input_stop, input_trigger) = StopSignal::new();
1160        let stop_input = || {
1161            if let Some(input) = &self.input {
1162                input.close();
1163            }
1164            input_trigger.stop();
1165        };
1166        let stop_process_io = || {
1167            if let Some(control) = &self.control {
1168                control.close();
1169            }
1170            reader_trigger.stop();
1171            stop_input();
1172        };
1173        let mut input_handle = input_receiver
1174            .zip(child.stdin.take())
1175            .map(|(receiver, stdin)| {
1176                std::thread::spawn(move || write_process_input(stdin, receiver, input_stop))
1177            });
1178        let reader_sender = sender.with_stop_signal(reader_stop.clone());
1179        let poll_interval = Duration::from_millis(50);
1180        let partial_output = self.partial_output;
1181        let mut stdout_handle = stdout.map(|stdout| {
1182            let sender_out = reader_sender.clone();
1183            let stop_out = reader_stop.clone();
1184            let make_msg_out = std::sync::Arc::clone(&make_msg_ref);
1185            std::thread::spawn(move || {
1186                #[cfg(unix)]
1187                let stdout =
1188                    process_pipe(stdout, stop_out.clone()).map_err(ProcessReadError::Io)?;
1189                forward_lines(
1190                    stdout,
1191                    sender_out,
1192                    stop_out,
1193                    partial_output,
1194                    |line| (make_msg_out.as_ref())(ProcessEvent::Stdout(line)),
1195                    |prefix| (make_msg_out.as_ref())(ProcessEvent::StdoutPartial(prefix)),
1196                )
1197            })
1198        });
1199        let mut stderr_handle = stderr.map(|stderr| {
1200            let sender_err = reader_sender.clone();
1201            let stop_err = reader_stop.clone();
1202            let make_msg_err = std::sync::Arc::clone(&make_msg_ref);
1203            std::thread::spawn(move || {
1204                #[cfg(unix)]
1205                let stderr =
1206                    process_pipe(stderr, stop_err.clone()).map_err(ProcessReadError::Io)?;
1207                forward_lines(
1208                    stderr,
1209                    sender_err,
1210                    stop_err,
1211                    partial_output,
1212                    |line| (make_msg_err.as_ref())(ProcessEvent::Stderr(line)),
1213                    |prefix| (make_msg_err.as_ref())(ProcessEvent::StderrPartial(prefix)),
1214                )
1215            })
1216        });
1217
1218        let mut child_wait_error = None;
1219        let mut final_event = loop {
1220            // Reader results bypass the model queue: a full queue must never
1221            // prevent supervising a child whose other stream has failed.
1222            if let Some(error) = take_reader_error(&mut stdout_handle, "stdout")
1223                .or_else(|| take_reader_error(&mut stderr_handle, "stderr"))
1224                .or_else(|| take_reader_error(&mut input_handle, "stdin write failed"))
1225            {
1226                stop_process_io();
1227                break output_failure_event(&error, &mut child, &mut child_wait_error);
1228            }
1229            match try_wait_child(&mut child, &mut child_wait_error) {
1230                Ok(Some(status)) => {
1231                    let event = process_exit_event(status);
1232                    if let ProcessEvent::Exited(code) = &event {
1233                        tracing::debug!(
1234                            target: crate::telemetry_schema::TARGET_PROCESS,
1235                            sub_id,
1236                            exit_code = *code,
1237                            elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1238                            "process exited"
1239                        );
1240                    } else if let ProcessEvent::Signaled(signal) = &event {
1241                        tracing::debug!(
1242                            target: crate::telemetry_schema::TARGET_PROCESS,
1243                            sub_id,
1244                            signal = *signal,
1245                            elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1246                            "process terminated by signal"
1247                        );
1248                    }
1249                    break event;
1250                }
1251                Ok(None) => {}
1252                Err(e) => {
1253                    tracing::warn!(
1254                        target: crate::telemetry_schema::TARGET_PROCESS,
1255                        sub_id,
1256                        error = %e,
1257                        "process wait error"
1258                    );
1259                    stop_process_io();
1260                    break output_failure_event(
1261                        &format!("wait error: {e}"),
1262                        &mut child,
1263                        &mut child_wait_error,
1264                    );
1265                }
1266            }
1267
1268            if let Some(dl) = deadline
1269                && web_time::Instant::now() >= dl
1270            {
1271                tracing::debug!(
1272                    target: crate::telemetry_schema::TARGET_PROCESS,
1273                    sub_id,
1274                    elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1275                    reason = "timeout",
1276                    "killing process"
1277                );
1278                // Keep the child's pipes open until termination is observed.
1279                // Closing a reader first can turn our kill into SIGPIPE while
1280                // the child is blocked writing to a full model queue.
1281                let event =
1282                    stopped_process_event("process timed out", &mut child, &mut child_wait_error);
1283                stop_process_io();
1284                break event;
1285            }
1286
1287            if token.wait_timeout(poll_interval) {
1288                tracing::debug!(
1289                    target: crate::telemetry_schema::TARGET_PROCESS,
1290                    sub_id,
1291                    elapsed_ms = spawn_start.elapsed().as_millis() as u64,
1292                    reason = "cancellation",
1293                    "killing process"
1294                );
1295                let event =
1296                    stopped_process_event("process canceled", &mut child, &mut child_wait_error);
1297                stop_process_io();
1298                break event;
1299            }
1300            if let Some(control) = &self.control {
1301                control.dispatch_interrupt(&child);
1302            }
1303        };
1304
1305        if let Some(control) = &self.control {
1306            control.close();
1307            // Closing admission is not proof of cleanup. Only an observed
1308            // reaped status permits a consumer to offer a safe restart.
1309            if matches!(
1310                try_wait_child(&mut child, &mut child_wait_error),
1311                Ok(Some(_))
1312            ) {
1313                control.confirm_reaped();
1314            }
1315        }
1316        stop_input();
1317
1318        if matches!(
1319            final_event,
1320            ProcessEvent::Exited(_) | ProcessEvent::Signaled(_)
1321        ) {
1322            // A child can exit while its reader is waiting for model queue
1323            // capacity. Preserve every line on normal completion, however
1324            // slowly the model drains, while still honoring stop and timeout.
1325            loop {
1326                if let Some(error) = take_reader_error(&mut stdout_handle, "stdout")
1327                    .or_else(|| take_reader_error(&mut stderr_handle, "stderr"))
1328                    .or_else(|| take_reader_error(&mut input_handle, "stdin write failed"))
1329                {
1330                    reader_trigger.stop();
1331                    final_event = output_failure_event(&error, &mut child, &mut child_wait_error);
1332                    break;
1333                }
1334                if stdout_handle.is_none() && stderr_handle.is_none() {
1335                    break;
1336                }
1337                let interruption = if stop.is_stopped() {
1338                    Some("canceled")
1339                } else if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1340                    Some("timed out")
1341                } else {
1342                    None
1343                };
1344                if let Some(reason) = interruption {
1345                    reader_trigger.stop();
1346                    final_event = ProcessEvent::Error(format!(
1347                        "output drain {reason} after {final_event:?}; stdout/stderr output is incomplete"
1348                    ));
1349                    break;
1350                }
1351                token.wait_timeout(PROCESS_READER_JOIN_POLL);
1352            }
1353        }
1354
1355        if let Some(handle) = stdout_handle {
1356            let _ = join_reader_thread_bounded(handle, "stdout", sub_id, &reader_trigger);
1357        }
1358        if let Some(handle) = stderr_handle {
1359            let _ = join_reader_thread_bounded(handle, "stderr", sub_id, &reader_trigger);
1360        }
1361        if let Some(handle) = input_handle
1362            && let Some(error) = join_reader_thread_bounded(handle, "stdin", sub_id, &input_trigger)
1363            && matches!(
1364                final_event,
1365                ProcessEvent::Exited(_) | ProcessEvent::Signaled(_)
1366            )
1367        {
1368            final_event = output_failure_event(&error, &mut child, &mut child_wait_error);
1369        }
1370
1371        // Keep ownership when foreground cleanup could not confirm reaping.
1372        // A late wait can update restart eligibility, but the error already
1373        // observed by this run remains an error. Descendants are not managed.
1374        match try_wait_child(&mut child, &mut child_wait_error) {
1375            Ok(Some(_)) => {
1376                if let Some(control) = &self.control {
1377                    control.confirm_reaped();
1378                }
1379            }
1380            _ if child_wait_error.is_some() && !has_retained_process_handle(&child) => {
1381                tracing::warn!(
1382                    sub_id,
1383                    "further child waits refused: prior wait failed without a retained process handle"
1384                );
1385            }
1386            _ => {
1387                if let Err(error) = reap_child_in_background(child, self.control.clone(), sub_id) {
1388                    final_event = ProcessEvent::Error(format!(
1389                        "{final_event:?}; background reaper could not start: {error}; child may remain unreaped"
1390                    ));
1391                }
1392            }
1393        }
1394
1395        if send_terminal_message(
1396            &sender,
1397            &stop,
1398            deadline,
1399            (make_msg_ref.as_ref())(final_event),
1400        )
1401        .is_err()
1402        {
1403            tracing::warn!(
1404                target: crate::telemetry_schema::TARGET_PROCESS,
1405                sub_id,
1406                "process terminal event was not delivered: queue disconnected or stop/timeout interrupted backpressure"
1407            );
1408        }
1409    }
1410}
1411
1412fn send_terminal_message<M>(
1413    sender: &SubscriptionSender<M>,
1414    stop: &StopSignal,
1415    deadline: Option<Instant>,
1416    mut message: M,
1417) -> Result<(), mpsc::SendError<M>> {
1418    loop {
1419        // Preserve the sender's one immediate attempt after cancellation.
1420        match sender.try_send(message) {
1421            Ok(()) => return Ok(()),
1422            Err(mpsc::TrySendError::Disconnected(message)) => {
1423                return Err(mpsc::SendError(message));
1424            }
1425            Err(mpsc::TrySendError::Full(unsent)) => message = unsent,
1426        }
1427        if stop.is_stopped() || deadline.is_some_and(|deadline| Instant::now() >= deadline) {
1428            return Err(mpsc::SendError(message));
1429        }
1430        stop.wait_timeout(PROCESS_READER_JOIN_POLL);
1431    }
1432}
1433
1434fn process_exit_event(status: std::process::ExitStatus) -> ProcessEvent {
1435    #[cfg(unix)]
1436    {
1437        use std::os::unix::process::ExitStatusExt;
1438
1439        if let Some(signal) = status.signal() {
1440            return ProcessEvent::Signaled(signal);
1441        }
1442    }
1443
1444    ProcessEvent::Exited(status.code().unwrap_or(-1))
1445}
1446
1447fn join_reader_thread_bounded<E: std::fmt::Display + Send + 'static>(
1448    handle: std::thread::JoinHandle<Result<(), E>>,
1449    stream: &'static str,
1450    sub_id: SubId,
1451    reader_trigger: &StopTrigger,
1452) -> Option<String> {
1453    let start = Instant::now();
1454    while !handle.is_finished() {
1455        if start.elapsed() >= PROCESS_READER_JOIN_TIMEOUT {
1456            reader_trigger.stop();
1457            tracing::warn!(
1458                target: crate::telemetry_schema::TARGET_PROCESS,
1459                sub_id,
1460                stream,
1461                timeout_ms = PROCESS_READER_JOIN_TIMEOUT.as_millis() as u64,
1462                "process pipe worker did not exit within timeout; detaching"
1463            );
1464            detach_reader_join(handle, stream);
1465            return Some(format!(
1466                "{stream} worker did not stop; I/O may be incomplete"
1467            ));
1468        }
1469        std::thread::sleep(PROCESS_READER_JOIN_POLL);
1470    }
1471    match handle.join() {
1472        Ok(Ok(())) => None,
1473        Ok(Err(error)) => Some(format!("{stream} I/O failed: {error}")),
1474        Err(_) => Some(format!("{stream} worker panicked")),
1475    }
1476}
1477
1478fn detach_reader_join<E: Send + 'static>(
1479    handle: std::thread::JoinHandle<Result<(), E>>,
1480    stream: &'static str,
1481) {
1482    let _ = std::thread::Builder::new()
1483        .name(format!("ftui-process-{stream}-detached-join"))
1484        .spawn(move || {
1485            let _ = handle.join();
1486        });
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492    use std::sync::mpsc as stdmpsc;
1493    use std::thread;
1494
1495    #[derive(Debug, Clone, PartialEq)]
1496    enum TestMsg {
1497        Proc(ProcessEvent),
1498    }
1499
1500    #[cfg(unix)]
1501    fn spawn_cleanup_probe() -> (
1502        std::process::Child,
1503        std::process::ChildStdin,
1504        io::BufReader<std::process::ChildStdout>,
1505    ) {
1506        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nline=sys.stdin.readline()\nprint('RELEASED '+line.removesuffix('\\n'),flush=True)\nraise SystemExit(67)";
1507        let mut command = Command::new("python3");
1508        command
1509            .args(["-u", "-c", script])
1510            .stdin(Stdio::piped())
1511            .stdout(Stdio::piped());
1512        #[cfg(target_os = "linux")]
1513        std::os::linux::process::CommandExt::create_pidfd(&mut command, true);
1514        let mut child = command.spawn().expect("spawn actual cleanup probe");
1515        #[cfg(target_os = "linux")]
1516        std::os::linux::process::ChildExt::pidfd(&child)
1517            .expect("cleanup probe requires retained PID ownership");
1518        // Hold stdin outside Child so a background Child::wait cannot turn the
1519        // test's pending child into a completed child by implicitly closing it.
1520        let stdin = child.stdin.take().unwrap();
1521        let mut output = io::BufReader::new(child.stdout.take().unwrap());
1522        let mut ready = String::new();
1523        output.read_line(&mut ready).unwrap();
1524        assert_eq!(ready, "READY\n");
1525        (child, stdin, output)
1526    }
1527
1528    #[test]
1529    #[cfg(unix)]
1530    fn cleanup_live_child_reports_killed_only_after_sigkill_reaping() {
1531        use std::os::unix::process::ExitStatusExt;
1532
1533        for reason in ["process canceled", "process timed out"] {
1534            let (mut child, _stdin, mut output) = spawn_cleanup_probe();
1535            let mut wait_error = None;
1536            let start = Instant::now();
1537            let event = stopped_process_event(reason, &mut child, &mut wait_error);
1538            let elapsed = start.elapsed();
1539            let observed = child.try_wait().unwrap();
1540            let mut tail = String::new();
1541            output.read_to_string(&mut tail).unwrap();
1542            assert_eq!(event, ProcessEvent::Killed);
1543            assert!(elapsed < Duration::from_secs(2));
1544            assert_eq!(
1545                observed.unwrap().signal(),
1546                Some(rustix::process::Signal::KILL.as_raw())
1547            );
1548            assert!(tail.is_empty(), "the held input was never released");
1549        }
1550    }
1551
1552    #[test]
1553    #[cfg(unix)]
1554    fn cleanup_already_exited_child_retains_status_instead_of_reporting_killed() {
1555        let (mut child, mut stdin, mut output) = spawn_cleanup_probe();
1556        let mut wait_error = None;
1557        stdin.write_all(b"release\n").unwrap();
1558        drop(stdin);
1559        let mut tail = String::new();
1560        output.read_to_string(&mut tail).unwrap();
1561        let status = reap_child_until(
1562            &mut child,
1563            Instant::now() + Duration::from_secs(2),
1564            &mut wait_error,
1565        )
1566        .unwrap()
1567        .expect("actual natural exit");
1568        assert_eq!(tail, "RELEASED release\n");
1569        assert_eq!(status.code(), Some(67));
1570        let cleanup = cleanup_child(&mut child, &mut wait_error);
1571        assert_eq!(cleanup.status.unwrap().code(), Some(67));
1572        assert!(!cleanup.kill_sent);
1573        assert_eq!(cleanup.detail, "child reaped: Exited(67)");
1574        assert_eq!(
1575            stopped_process_event("process canceled", &mut child, &mut wait_error),
1576            ProcessEvent::Error(
1577                "process canceled; child reaped: Exited(67); stdout/stderr output is incomplete"
1578                    .to_owned()
1579            )
1580        );
1581    }
1582
1583    #[test]
1584    #[cfg(unix)]
1585    fn cleanup_expired_reap_deadline_leaves_live_child_unconfirmed() {
1586        let (mut child, _stdin, _output) = spawn_cleanup_probe();
1587        let mut wait_error = None;
1588        let control = ProcessControl::new();
1589        let _guard = control.claim().unwrap();
1590        control.started(child.id());
1591        control.close();
1592        let start = Instant::now();
1593        let result = reap_child_until(&mut child, start, &mut wait_error);
1594        let elapsed = start.elapsed();
1595        let still_running = child.try_wait();
1596        let status_before_cleanup = control.status();
1597        // This exercises an explicitly expired helper deadline on a healthy
1598        // child, not an unkillable kernel task. Capture the refusal first;
1599        // the following explicit cleanup must not count as foreground proof.
1600        let cleanup = cleanup_child(&mut child, &mut wait_error);
1601        assert!(matches!(result, Ok(None)));
1602        assert!(matches!(still_running, Ok(None)));
1603        assert!(elapsed < Duration::from_secs(1));
1604        assert!(status_before_cleanup.closed);
1605        assert!(!status_before_cleanup.can_restart);
1606        assert!(cleanup.kill_sent);
1607        assert!(cleanup.status.is_some());
1608        assert!(!control.status().can_restart);
1609    }
1610
1611    #[test]
1612    #[cfg(unix)]
1613    fn cleanup_background_reaper_confirms_only_after_real_stdin_release() {
1614        let (child, mut stdin, mut output) = spawn_cleanup_probe();
1615        let pid = rustix::process::Pid::from_child(&child);
1616        let control = ProcessControl::new();
1617        let _guard = control.claim().unwrap();
1618        control.started(child.id());
1619        control.close();
1620        let start = Instant::now();
1621        reap_child_in_background(child, Some(control.clone()), 991).unwrap();
1622        assert!(start.elapsed() < Duration::from_secs(1));
1623        // The real child's read cannot finish while this test retains stdin.
1624        thread::sleep(Duration::from_millis(30));
1625        assert!(control.status().closed);
1626        assert!(!control.status().can_restart);
1627        stdin.write_all(b"release\n").unwrap();
1628        drop(stdin);
1629        let mut tail = String::new();
1630        output.read_to_string(&mut tail).unwrap();
1631        let deadline = Instant::now() + Duration::from_secs(2);
1632        while !control.status().can_restart && Instant::now() < deadline {
1633            thread::sleep(Duration::from_millis(5));
1634        }
1635        assert_eq!(tail, "RELEASED release\n");
1636        assert_eq!(
1637            control.status(),
1638            ProcessControlStatus {
1639                pid: None,
1640                closed: true,
1641                can_restart: true,
1642                interrupt: ProcessInterruptStatus::Idle,
1643            }
1644        );
1645        // Independently confirm that the reaper consumed the actual child's
1646        // exit status; an early can_restart update must not hide a zombie.
1647        let subsequent_wait =
1648            rustix::process::waitpid(Some(pid), rustix::process::WaitOptions::NOHANG);
1649        assert_eq!(subsequent_wait.unwrap_err(), rustix::io::Errno::CHILD);
1650        assert_eq!(
1651            control.request_interrupt(),
1652            Err(ProcessControlError::Closed)
1653        );
1654    }
1655
1656    #[test]
1657    #[cfg(target_os = "linux")]
1658    fn cleanup_externally_reaped_child_uses_retained_handle_without_false_killed() {
1659        use rustix::process::{Pid, WaitOptions, waitpid};
1660
1661        let (mut child, mut stdin, mut output) = spawn_cleanup_probe();
1662        let mut wait_error = None;
1663        let pid = Pid::from_child(&child);
1664        let control = ProcessControl::new();
1665        let _guard = control.claim().unwrap();
1666        control.started(child.id());
1667        control.close();
1668        stdin.write_all(b"release\n").unwrap();
1669        drop(stdin);
1670        let deadline = Instant::now() + Duration::from_secs(2);
1671        let externally_reaped = loop {
1672            match waitpid(Some(pid), WaitOptions::NOHANG) {
1673                Ok(Some(observed)) => break observed,
1674                Ok(None) if Instant::now() < deadline => {
1675                    thread::sleep(Duration::from_millis(5));
1676                }
1677                other => {
1678                    // Retained pidfd keeps this failure cleanup safe even if
1679                    // the exact child was reaped outside std::Child.
1680                    let cleanup = cleanup_child(&mut child, &mut wait_error);
1681                    panic!("external exact-child wait failed: {other:?}; {cleanup:?}");
1682                }
1683            }
1684        };
1685        let mut tail = String::new();
1686        output.read_to_string(&mut tail).unwrap();
1687        assert_eq!(tail, "RELEASED release\n");
1688        assert_eq!(externally_reaped.0, pid);
1689        assert_eq!(externally_reaped.1.exit_status(), Some(67));
1690        assert!(has_retained_process_handle(&child));
1691        match try_wait_child(&mut child, &mut wait_error) {
1692            Ok(Some(status)) => {
1693                // Newer kernels let std recover the reaped child's status
1694                // through the retained pidfd. This is not ECHILD evidence.
1695                eprintln!("retained pidfd recovered exit67; ECHILD branch not exercised");
1696                assert_eq!(status.code(), Some(67));
1697                assert!(wait_error.is_none());
1698                let cleanup = cleanup_child(&mut child, &mut wait_error);
1699                assert_eq!(cleanup.status.unwrap().code(), Some(67));
1700                assert!(!cleanup.kill_sent);
1701                assert_eq!(cleanup.detail, "child reaped: Exited(67)");
1702                assert_eq!(
1703                    stopped_process_event("process canceled", &mut child, &mut wait_error),
1704                    ProcessEvent::Error(
1705                        "process canceled; child reaped: Exited(67); stdout/stderr output is incomplete"
1706                            .to_owned()
1707                    )
1708                );
1709            }
1710            Err(error) => {
1711                eprintln!("retained pidfd could not recover exit67; checking actual ECHILD");
1712                assert_eq!(
1713                    error.raw_os_error(),
1714                    Some(rustix::io::Errno::CHILD.raw_os_error())
1715                );
1716                let error_text = error.to_string();
1717                assert_eq!(wait_error.as_deref(), Some(error_text.as_str()));
1718                let cleanup = cleanup_child(&mut child, &mut wait_error);
1719                let kill_error =
1720                    io::Error::from_raw_os_error(rustix::io::Errno::SRCH.raw_os_error());
1721                let expected = format!(
1722                    "child wait failed: {error}; child kill failed: {kill_error}; reaping failed: {error}; child may still be running or unreaped"
1723                );
1724                assert!(cleanup.status.is_none());
1725                assert!(!cleanup.kill_sent);
1726                assert_eq!(cleanup.detail, expected);
1727                assert_eq!(
1728                    stopped_process_event("process canceled", &mut child, &mut wait_error),
1729                    ProcessEvent::Error(format!(
1730                        "process canceled; {expected}; stdout/stderr output is incomplete"
1731                    ))
1732                );
1733            }
1734            Ok(None) => panic!("the externally reaped child cannot still be running"),
1735        }
1736        assert!(!control.status().can_restart);
1737    }
1738
1739    #[test]
1740    #[cfg(target_os = "linux")]
1741    fn cleanup_sticky_wait_error_refuses_signal_and_repoll_without_retained_handle() {
1742        use rustix::process::{Pid, WaitOptions, waitpid};
1743
1744        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nline=sys.stdin.readline()\nprint('RELEASED '+line.removesuffix('\\n'),flush=True)\nraise SystemExit(67)";
1745        let mut command = Command::new("python3");
1746        command
1747            .args(["-u", "-c", script])
1748            .stdin(Stdio::piped())
1749            .stdout(Stdio::piped());
1750        std::os::linux::process::CommandExt::create_pidfd(&mut command, false);
1751        let mut child = command
1752            .spawn()
1753            .expect("spawn actual no-pidfd cleanup probe");
1754        assert!(!has_retained_process_handle(&child));
1755        let pid = Pid::from_child(&child);
1756        let child_id = child.id();
1757        let mut stdin = child.stdin.take().unwrap();
1758        let mut output = io::BufReader::new(child.stdout.take().unwrap());
1759        let mut ready = String::new();
1760        output.read_line(&mut ready).unwrap();
1761        assert_eq!(ready, "READY\n");
1762        let control = ProcessControl::new();
1763        let _guard = control.claim().unwrap();
1764        control.started(child_id);
1765        control.close();
1766
1767        // Inject only the previously observed error state. The child remains
1768        // real and owned; this is not evidence of an actual OS wait failure.
1769        let saved_error = "injected prior wait failure";
1770        let mut wait_error = Some(saved_error.to_owned());
1771        let expected = format!(
1772            "child wait failed: {saved_error}; kill and further waits not attempted without a retained process handle; child may still be running or unreaped"
1773        );
1774        assert_eq!(
1775            try_wait_child(&mut child, &mut wait_error)
1776                .unwrap_err()
1777                .to_string(),
1778            saved_error
1779        );
1780        let cleanup = cleanup_child(&mut child, &mut wait_error);
1781        assert!(cleanup.status.is_none());
1782        assert!(!cleanup.kill_sent);
1783        assert_eq!(cleanup.detail, expected);
1784        assert_eq!(
1785            stopped_process_event("process canceled", &mut child, &mut wait_error),
1786            ProcessEvent::Error(format!(
1787                "process canceled; {expected}; stdout/stderr output is incomplete"
1788            ))
1789        );
1790        assert!(!control.status().can_restart);
1791
1792        // Exact output after the refusal proves that cleanup did not signal
1793        // this live child. The test, not Child::wait, releases its stdin.
1794        stdin.write_all(b"release\n").unwrap();
1795        drop(stdin);
1796        let mut tail = String::new();
1797        output.read_to_string(&mut tail).unwrap();
1798        assert_eq!(tail, "RELEASED release\n");
1799        let deadline = Instant::now() + Duration::from_secs(2);
1800        loop {
1801            let status = std::fs::read_to_string(format!("/proc/{child_id}/status")).unwrap();
1802            if status.lines().any(|line| line.starts_with("State:\tZ")) {
1803                break;
1804            }
1805            assert!(Instant::now() < deadline, "actual child did not exit");
1806            thread::sleep(Duration::from_millis(5));
1807        }
1808        // The now-waitable child makes a forbidden re-poll observable: only
1809        // the independent exact-child wait below may consume its exit status.
1810        assert_eq!(
1811            reap_child_until(&mut child, Instant::now(), &mut wait_error)
1812                .unwrap_err()
1813                .to_string(),
1814            saved_error
1815        );
1816        let cleanup = cleanup_child(&mut child, &mut wait_error);
1817        assert!(cleanup.status.is_none());
1818        assert!(!cleanup.kill_sent);
1819        assert_eq!(cleanup.detail, expected);
1820        assert_eq!(wait_error.as_deref(), Some(saved_error));
1821        let reaped = waitpid(Some(pid), WaitOptions::NOHANG)
1822            .unwrap()
1823            .expect("sticky helpers must leave the exact child waitable");
1824        assert_eq!(reaped.0, pid);
1825        assert_eq!(reaped.1.exit_status(), Some(67));
1826        assert!(!control.status().can_restart);
1827        assert_eq!(
1828            control.request_interrupt(),
1829            Err(ProcessControlError::Closed)
1830        );
1831    }
1832
1833    #[test]
1834    fn control_generation_claim_and_descriptor_identity_are_single_run() {
1835        let control = ProcessControl::new();
1836        assert_eq!(control.generation(), control.clone().generation());
1837        assert_ne!(control.generation(), ProcessControl::new().generation());
1838        assert_eq!(
1839            control.status(),
1840            ProcessControlStatus {
1841                pid: None,
1842                closed: false,
1843                can_restart: true,
1844                interrupt: ProcessInterruptStatus::Idle,
1845            }
1846        );
1847        assert_eq!(
1848            control.request_interrupt(),
1849            Err(if cfg!(unix) {
1850                ProcessControlError::NotRunning
1851            } else {
1852                ProcessControlError::Unsupported
1853            })
1854        );
1855        let descriptor =
1856            || ProcessSubscription::new("child", |event| event).control(control.clone());
1857        let id = descriptor().id();
1858        assert_eq!(id, descriptor().id());
1859        assert_ne!(id, ProcessSubscription::new("child", |event| event).id());
1860        assert_ne!(
1861            id,
1862            ProcessSubscription::new("child", |event| event)
1863                .control(ProcessControl::new())
1864                .id()
1865        );
1866        assert_eq!(
1867            descriptor().with_id(71).control(ProcessControl::new()).id(),
1868            71
1869        );
1870        let guard = control.claim().expect("first claim");
1871        assert!(control.claim().is_none());
1872        drop(descriptor());
1873        assert!(
1874            !control.status().closed,
1875            "unused descriptors do not close the owner"
1876        );
1877        drop(guard);
1878        assert!(control.status().closed);
1879        assert!(control.status().can_restart, "no child was spawned");
1880        assert!(
1881            control.claim().is_none(),
1882            "closed generations cannot be reused"
1883        );
1884    }
1885
1886    #[test]
1887    #[cfg(unix)]
1888    fn control_pending_close_preserves_uncertain_cleanup_and_completed_outcomes() {
1889        // These are state-machine assertions, not evidence of child execution.
1890        let control = ProcessControl::new();
1891        let guard = control.claim().unwrap();
1892        control.started(123);
1893        assert!(!control.status().can_restart);
1894        assert_eq!(control.request_interrupt(), Ok(()));
1895        assert_eq!(
1896            control.request_interrupt(),
1897            Err(ProcessControlError::AlreadyPending)
1898        );
1899        drop(guard);
1900        assert_eq!(
1901            control.status(),
1902            ProcessControlStatus {
1903                pid: None,
1904                closed: true,
1905                can_restart: false,
1906                interrupt: ProcessInterruptStatus::Canceled,
1907            }
1908        );
1909        assert_eq!(
1910            control.request_interrupt(),
1911            Err(ProcessControlError::Closed)
1912        );
1913        control.confirm_reaped();
1914        assert!(control.status().can_restart);
1915        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Canceled);
1916
1917        for outcome in [
1918            ProcessInterruptStatus::Sent,
1919            ProcessInterruptStatus::Failed("delivery failed".to_owned()),
1920        ] {
1921            let control = ProcessControl::new();
1922            let guard = control.claim().unwrap();
1923            control.started(123);
1924            control.state.lock().unwrap().status.interrupt = outcome.clone();
1925            drop(guard);
1926            assert_eq!(control.status().interrupt, outcome);
1927            assert!(!control.status().can_restart);
1928        }
1929    }
1930
1931    #[cfg(unix)]
1932    fn controlled_python(
1933        script: &str,
1934        control: &ProcessControl,
1935    ) -> ProcessSubscription<ProcessEvent> {
1936        ProcessSubscription::new("python3", |event| event)
1937            .args(["-u", "-c", script])
1938            .control(control.clone())
1939            .timeout(Duration::from_secs(5))
1940    }
1941
1942    #[test]
1943    #[cfg(unix)]
1944    fn real_control_interrupt_continues_stdin_and_duplicate_claim_keeps_owner() {
1945        let control = ProcessControl::new();
1946        let input = ProcessInput::new();
1947        let script = "import signal,sys\ncount=0\ndef interrupt(signum,frame):\n global count\n count+=1\n print('INT-ACK',flush=True)\n if count==2:\n  raise SystemExit(0)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY',flush=True)\nfor line in sys.stdin:\n print('reply='+line.removesuffix('\\n'),flush=True)\nprint('EOF',flush=True)\nwhile True:\n signal.pause()";
1948        let sub = controlled_python(script, &control).stdin(input.clone());
1949        let (sender, receiver) = mpsc::sync_channel(256);
1950        let (stop, trigger) = StopSignal::new();
1951        let handle = thread::spawn(move || {
1952            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
1953        });
1954        assert_eq!(
1955            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
1956            ProcessEvent::Stdout("READY".to_owned())
1957        );
1958        let running = control.status();
1959        assert!(running.pid.is_some());
1960        assert!(!running.closed);
1961        assert!(!running.can_restart);
1962
1963        let duplicate = controlled_python("raise SystemExit(99)", &control);
1964        let (duplicate_sender, duplicate_receiver) = mpsc::sync_channel(1);
1965        let (duplicate_stop, _duplicate_trigger) = StopSignal::new();
1966        duplicate.run(
1967            SubscriptionSender::new(duplicate_sender, duplicate_stop.clone()),
1968            duplicate_stop,
1969        );
1970        assert_eq!(
1971            duplicate_receiver.into_iter().collect::<Vec<_>>(),
1972            [ProcessEvent::Error(
1973                "control handle was already used; create fresh control for a new run".to_owned()
1974            )]
1975        );
1976        assert_eq!(
1977            control.status(),
1978            running,
1979            "duplicate claim must not close its owner"
1980        );
1981
1982        control.request_interrupt().unwrap();
1983        assert_eq!(
1984            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
1985            ProcessEvent::Stdout("INT-ACK".to_owned())
1986        );
1987        let deadline = Instant::now() + Duration::from_secs(2);
1988        while control.status().interrupt == ProcessInterruptStatus::Pending
1989            && Instant::now() < deadline
1990        {
1991            thread::sleep(Duration::from_millis(5));
1992        }
1993        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
1994        assert_eq!(control.status().pid, running.pid);
1995        input
1996            .try_send_line("still alive 🦀 $() \\".to_owned())
1997            .unwrap();
1998        assert_eq!(
1999            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2000            ProcessEvent::Stdout("reply=still alive 🦀 $() \\".to_owned())
2001        );
2002        input.close();
2003        assert_eq!(
2004            receiver.recv_timeout(Duration::from_secs(5)).unwrap(),
2005            ProcessEvent::Stdout("EOF".to_owned())
2006        );
2007        assert_eq!(control.status().pid, running.pid, "EOF only closes stdin");
2008        assert!(!control.status().closed);
2009        control.request_interrupt().unwrap();
2010        let events: Vec<_> = (0..2)
2011            .map(|_| receiver.recv_timeout(Duration::from_secs(5)).unwrap())
2012            .collect();
2013        handle.join().unwrap();
2014        // All positive observations precede any test-requested stop.
2015        trigger.stop();
2016        assert_eq!(
2017            events,
2018            [
2019                ProcessEvent::Stdout("INT-ACK".to_owned()),
2020                ProcessEvent::Exited(0)
2021            ]
2022        );
2023        assert!(receiver.try_recv().is_err());
2024        assert_eq!(
2025            control.status(),
2026            ProcessControlStatus {
2027                pid: None,
2028                closed: true,
2029                can_restart: true,
2030                interrupt: ProcessInterruptStatus::Sent,
2031            }
2032        );
2033        assert_eq!(
2034            control.request_interrupt(),
2035            Err(ProcessControlError::Closed)
2036        );
2037    }
2038
2039    #[test]
2040    fn control_spawn_failure_closes_admission_without_claiming_a_child() {
2041        let control = ProcessControl::new();
2042        let sub =
2043            ProcessSubscription::new("/ftui-process-control-command-does-not-exist", |event| {
2044                event
2045            })
2046            .control(control.clone())
2047            .timeout(Duration::from_secs(2));
2048        let (sender, receiver) = mpsc::sync_channel(1);
2049        let (stop, _trigger) = StopSignal::new();
2050        sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2051        let events: Vec<_> = receiver.into_iter().collect();
2052        assert!(
2053            matches!(events.as_slice(), [ProcessEvent::Error(error)] if error.starts_with("Failed to spawn"))
2054        );
2055        assert_eq!(
2056            control.status(),
2057            ProcessControlStatus {
2058                pid: None,
2059                closed: true,
2060                can_restart: true,
2061                interrupt: ProcessInterruptStatus::Idle,
2062            }
2063        );
2064        assert!(control.claim().is_none());
2065    }
2066
2067    #[test]
2068    #[cfg(target_os = "linux")]
2069    fn control_interrupt_refuses_child_without_retained_pidfd() {
2070        let script = "import signal,sys\nsignal.alarm(5)\nprint('READY',flush=True)\nprint(sys.stdin.readline().removesuffix('\\n'),flush=True)";
2071        let mut command = Command::new("python3");
2072        command
2073            .args(["-u", "-c", script])
2074            .stdin(Stdio::piped())
2075            .stdout(Stdio::piped());
2076        std::os::linux::process::CommandExt::create_pidfd(&mut command, false);
2077        let mut child = command.spawn().unwrap();
2078        let mut output = io::BufReader::new(child.stdout.take().unwrap());
2079        let mut ready = String::new();
2080        output.read_line(&mut ready).unwrap();
2081        let result = interrupt_child(&child);
2082        let mut stdin = child.stdin.take().unwrap();
2083        let written = stdin.write_all(b"STILL-ALIVE\n");
2084        drop(stdin);
2085        let mut tail = String::new();
2086        let read = output.read_to_string(&mut tail);
2087        let status = child.wait().unwrap();
2088        // Refusal and the subsequent actual roundtrip are checked after natural
2089        // completion; no cleanup signal can manufacture successful survival.
2090        let error = result.unwrap_err();
2091        assert_eq!(error.kind(), io::ErrorKind::Unsupported);
2092        assert!(
2093            error
2094                .to_string()
2095                .starts_with("retained pidfd unavailable; interrupt not sent:")
2096        );
2097        assert_eq!(ready, "READY\n");
2098        written.unwrap();
2099        read.unwrap();
2100        assert_eq!(tail, "STILL-ALIVE\n");
2101        assert!(status.success());
2102    }
2103
2104    #[test]
2105    #[cfg(target_os = "linux")]
2106    fn real_control_interrupt_bypasses_full_output_and_blocked_input_queues() {
2107        let control = ProcessControl::new();
2108        let input = ProcessInput::new();
2109        let payload = "x".repeat(MAX_PROCESS_LINE_BYTES);
2110        for _ in 0..PROCESS_INPUT_CAPACITY {
2111            input.try_send_line(payload.clone()).unwrap();
2112        }
2113        let (observed_sender, observed_receiver) = mpsc::channel();
2114        let script = "import os,signal\ncount=0\ndef interrupt(signum,frame):\n global count\n count+=1\n if count==1:\n  os.write(2,b'INT-ACK\\n')\n else:\n  os._exit(73)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY '+str(os.getpid()),flush=True)\nfor index in range(257):\n print('out:'+str(index),flush=True)\nwhile True:\n signal.pause()";
2115        let sub = ProcessSubscription::new("python3", move |event| {
2116            // These observations precede model-channel admission. They prove
2117            // supervision while full, not delivery of the unaccepted suffix.
2118            if matches!(&event, ProcessEvent::Stdout(line) if line == "out:256")
2119                || matches!(&event, ProcessEvent::Stderr(line) if line == "INT-ACK")
2120                || matches!(&event, ProcessEvent::Error(_))
2121            {
2122                observed_sender.send(event.clone()).unwrap();
2123            }
2124            event
2125        })
2126        .args(["-u", "-c", script])
2127        .stdin(input.clone())
2128        .control(control.clone())
2129        .timeout(Duration::from_secs(5));
2130        let (sender, receiver) = mpsc::sync_channel(256);
2131        let (stop, trigger) = StopSignal::new();
2132        let handle = thread::spawn(move || {
2133            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2134        });
2135        let ProcessEvent::Stdout(ready) = receiver.recv_timeout(Duration::from_secs(5)).unwrap()
2136        else {
2137            panic!("missing actual child readiness");
2138        };
2139        let pid: u32 = ready.strip_prefix("READY ").unwrap().parse().unwrap();
2140        assert_eq!(
2141            observed_receiver
2142                .recv_timeout(Duration::from_secs(5))
2143                .unwrap(),
2144            ProcessEvent::Stdout("out:256".to_owned())
2145        );
2146        // The only stdout reader reached conversion of line 257 after putting
2147        // exactly 256 lines into the undrained channel. The child never reads
2148        // stdin; a maximum-sized write plus LF cannot finish in its pipe.
2149        let mut input_full = false;
2150        for _ in 0..PROCESS_INPUT_CAPACITY + 2 {
2151            match input.try_send_line(payload.clone()) {
2152                Ok(()) => {}
2153                Err(ProcessInputError::Full(line)) => {
2154                    assert_eq!(line, payload);
2155                    input_full = true;
2156                    break;
2157                }
2158                other => panic!("unexpected input admission: {other:?}"),
2159            }
2160        }
2161        assert!(input_full);
2162        let requested_at = Instant::now();
2163        control.request_interrupt().unwrap();
2164        assert_eq!(
2165            observed_receiver
2166                .recv_timeout(Duration::from_secs(2))
2167                .unwrap(),
2168            ProcessEvent::Stderr("INT-ACK".to_owned())
2169        );
2170        let deadline = Instant::now() + Duration::from_secs(2);
2171        while control.status().interrupt == ProcessInterruptStatus::Pending
2172            && Instant::now() < deadline
2173        {
2174            thread::sleep(Duration::from_millis(5));
2175        }
2176        assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
2177        // This is a distinct request after the first handler acknowledgment.
2178        control.request_interrupt().unwrap();
2179        let terminal = observed_receiver.recv_timeout(Duration::from_secs(2));
2180        let status_before_drain = control.status();
2181        let elapsed_before_drain = requested_at.elapsed();
2182        let reaped_before_drain = std::fs::metadata(format!("/proc/{pid}"))
2183            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
2184        // Release backpressure only after capturing the child and supervisor
2185        // observations. Cleanup cannot make those prior observations pass.
2186        let delivered: Vec<_> = receiver.into_iter().collect();
2187        handle.join().unwrap();
2188        trigger.stop();
2189        let terminal = terminal.unwrap();
2190        assert!(
2191            matches!(&terminal, ProcessEvent::Error(error)
2192                if error.starts_with("stdin write failed")
2193                    && error.contains("reaped:")
2194                    && error.contains("Exited(73)")),
2195            "pending stdin must report its actual SIGINT exit and incomplete I/O: {terminal:?}"
2196        );
2197        assert!(
2198            reaped_before_drain,
2199            "child still existed before model drain"
2200        );
2201        assert!(elapsed_before_drain < Duration::from_secs(2));
2202        assert_eq!(
2203            status_before_drain,
2204            ProcessControlStatus {
2205                pid: None,
2206                closed: true,
2207                can_restart: true,
2208                interrupt: ProcessInterruptStatus::Sent,
2209            }
2210        );
2211        let mut expected: Vec<_> = (0..256)
2212            .map(|index| ProcessEvent::Stdout(format!("out:{index}")))
2213            .collect();
2214        expected.push(terminal);
2215        assert_eq!(delivered, expected, "accepted FIFO prefix must survive");
2216        assert_eq!(
2217            control.request_interrupt(),
2218            Err(ProcessControlError::Closed)
2219        );
2220        assert_eq!(
2221            input.try_send_line("late".to_owned()),
2222            Err(ProcessInputError::Closed("late".to_owned()))
2223        );
2224    }
2225
2226    #[test]
2227    #[cfg(unix)]
2228    fn real_control_fresh_generation_restarts_after_terminal_without_stale_interrupts() {
2229        use crate::subscription::SubscriptionManager;
2230        let mut manager = SubscriptionManager::new();
2231        let script = "import signal\ndef interrupt(signum,frame):\n print('INT-EXIT',flush=True)\n raise SystemExit(37)\nsignal.signal(signal.SIGINT,interrupt)\nprint('READY',flush=True)\nwhile True:\n signal.pause()";
2232        let receive = |manager: &SubscriptionManager<(u64, ProcessEvent)>, count: usize| {
2233            let deadline = Instant::now() + Duration::from_secs(5);
2234            let mut events = Vec::new();
2235            while events.len() < count && Instant::now() < deadline {
2236                events.extend(manager.drain_messages());
2237                thread::sleep(Duration::from_millis(5));
2238            }
2239            events
2240        };
2241        let mut previous: Option<(ProcessControl, SubId)> = None;
2242        for _ in 0..2 {
2243            let control = ProcessControl::new();
2244            let generation = control.generation();
2245            let descriptor = || {
2246                ProcessSubscription::new("python3", move |event| (generation, event))
2247                    .args(["-u", "-c", script])
2248                    .control(control.clone())
2249                    .timeout(Duration::from_secs(5))
2250            };
2251            let id = descriptor().id();
2252            if let Some((old, old_id)) = &previous {
2253                assert_ne!(old.generation(), generation);
2254                assert_ne!(*old_id, id);
2255            }
2256            // There is deliberately no intermediate reconcile([]): the fresh
2257            // generation must replace the finished, still-registered old ID.
2258            manager.reconcile(vec![Box::new(descriptor())]);
2259            assert_eq!(
2260                receive(&manager, 1),
2261                [(generation, ProcessEvent::Stdout("READY".to_owned()))]
2262            );
2263            let running = control.status();
2264            if let Some((old, _)) = &previous {
2265                assert_eq!(old.request_interrupt(), Err(ProcessControlError::Closed));
2266                assert_eq!(old.request_interrupt(), Err(ProcessControlError::Closed));
2267                assert_eq!(control.status(), running);
2268            }
2269            manager.reconcile(vec![Box::new(descriptor())]);
2270            assert_eq!(manager.active_count(), 1);
2271            assert_eq!(control.status(), running);
2272            control.request_interrupt().unwrap();
2273            assert_eq!(
2274                receive(&manager, 2),
2275                [
2276                    (generation, ProcessEvent::Stdout("INT-EXIT".to_owned())),
2277                    (generation, ProcessEvent::Exited(37)),
2278                ]
2279            );
2280            assert!(control.status().closed);
2281            assert!(control.status().can_restart);
2282            assert_eq!(control.status().interrupt, ProcessInterruptStatus::Sent);
2283            assert!(manager.drain_messages().is_empty());
2284            previous = Some((control, id));
2285        }
2286        manager.stop_all();
2287    }
2288
2289    #[test]
2290    fn input_admission_bounds_payload_and_returns_rejected_text() {
2291        let input = ProcessInput::new();
2292        let mut overallocated = String::with_capacity(MAX_PROCESS_LINE_BYTES * 8);
2293        overallocated.push_str("tiny");
2294        input.try_send_line(overallocated).unwrap();
2295        for index in 1..PROCESS_INPUT_CAPACITY {
2296            input.try_send_line(index.to_string()).unwrap();
2297        }
2298        assert_eq!(
2299            input.try_send_line("retry 🦀".to_owned()),
2300            Err(ProcessInputError::Full("retry 🦀".to_owned()))
2301        );
2302        let oversized = "x".repeat(MAX_PROCESS_LINE_BYTES + 1);
2303        assert_eq!(
2304            input.try_send_line(oversized.clone()),
2305            Err(ProcessInputError::TooLong(oversized))
2306        );
2307        input.clone().close();
2308        assert_eq!(
2309            input.try_send_line("closed".to_owned()),
2310            Err(ProcessInputError::Closed("closed".to_owned()))
2311        );
2312        let (_guard, receiver) = input.claim().expect("close still permits first run");
2313        assert_eq!(receiver.recv().unwrap().into_string().capacity(), 4);
2314        for index in 1..PROCESS_INPUT_CAPACITY {
2315            assert_eq!(&*receiver.recv().unwrap(), index.to_string());
2316        }
2317        assert!(matches!(receiver.recv(), Err(mpsc::RecvError)));
2318        assert!(input.claim().is_none());
2319    }
2320
2321    #[test]
2322    fn input_identity_and_claim_ownership_survive_descriptor_rebuilds() {
2323        let input = ProcessInput::new();
2324        let sub = || ProcessSubscription::new("sh", |event| event).stdin(input.clone());
2325        let id = sub().id();
2326        assert_eq!(
2327            sub().with_id(7).arg("one").stdin(ProcessInput::new()).id(),
2328            7
2329        );
2330        assert_eq!(id, sub().id());
2331        assert_ne!(id, ProcessSubscription::new("sh", |event| event).id());
2332        assert_ne!(
2333            id,
2334            ProcessSubscription::new("sh", |event| event)
2335                .stdin(ProcessInput::new())
2336                .id()
2337        );
2338        let (guard, receiver) = input.claim().unwrap();
2339        assert!(input.claim().is_none());
2340        drop(sub());
2341        input.try_send_line("still open".to_owned()).unwrap();
2342        assert_eq!(&*receiver.recv().unwrap(), "still open");
2343        drop(guard);
2344        assert_eq!(
2345            input.try_send_line("late".to_owned()),
2346            Err(ProcessInputError::Closed("late".to_owned()))
2347        );
2348    }
2349
2350    #[cfg(unix)]
2351    fn input_process(script: &str, input: &ProcessInput) -> ProcessSubscription<ProcessEvent> {
2352        ProcessSubscription::new("sh", |event| event)
2353            .args(["-c", script])
2354            .stdin(input.clone())
2355            .timeout(Duration::from_secs(5))
2356    }
2357
2358    #[test]
2359    #[cfg(unix)]
2360    fn real_input_roundtrip_eof_and_fresh_run_survive_reconciliation() {
2361        use crate::subscription::SubscriptionManager;
2362        let mut manager = SubscriptionManager::new();
2363        let script = "printf 'pid=%s\\n' \"$$\"; while IFS= read -r line; do printf '%s\\n' \"$line\"; done; printf 'EOF\\n'";
2364        let receive = |manager: &SubscriptionManager<ProcessEvent>, count: usize| {
2365            let deadline = Instant::now() + Duration::from_secs(5);
2366            let mut events = Vec::new();
2367            while events.len() < count && Instant::now() < deadline {
2368                events.extend(manager.drain_messages());
2369                thread::sleep(Duration::from_millis(5));
2370            }
2371            events
2372        };
2373        let mut previous_id = None;
2374        for _ in 0..2 {
2375            let input = ProcessInput::new();
2376            let id = input_process(script, &input).id();
2377            assert_ne!(previous_id, Some(id));
2378            previous_id = Some(id);
2379            manager.reconcile(vec![Box::new(input_process(script, &input))]);
2380            let started = receive(&manager, 1);
2381            assert!(
2382                matches!(started.as_slice(), [ProcessEvent::Stdout(line)] if line.starts_with("pid="))
2383            );
2384            for (text, expected) in [
2385                ("alpha", vec!["alpha"]),
2386                ("🦀 $() \\ literal", vec!["🦀 $() \\ literal"]),
2387                ("", vec![""]),
2388                ("embedded\nline", vec!["embedded", "line"]),
2389            ] {
2390                manager.reconcile(vec![Box::new(input_process(script, &input))]);
2391                input.try_send_line(text.to_owned()).unwrap();
2392                let expected: Vec<_> = expected
2393                    .into_iter()
2394                    .map(|line| ProcessEvent::Stdout(line.to_owned()))
2395                    .collect();
2396                assert_eq!(receive(&manager, expected.len()), expected);
2397            }
2398            input.close();
2399            assert_eq!(
2400                receive(&manager, 2),
2401                [
2402                    ProcessEvent::Stdout("EOF".to_owned()),
2403                    ProcessEvent::Exited(0)
2404                ]
2405            );
2406            assert_eq!(
2407                input.try_send_line("after EOF".to_owned()),
2408                Err(ProcessInputError::Closed("after EOF".to_owned()))
2409            );
2410            assert!(manager.drain_messages().is_empty());
2411        }
2412        manager.stop_all();
2413    }
2414
2415    #[test]
2416    #[cfg(unix)]
2417    fn real_input_drains_full_queue_and_maximum_line_before_eof() {
2418        let input = ProcessInput::new();
2419        let mut expected = Vec::new();
2420        for index in 0..PROCESS_INPUT_CAPACITY {
2421            let line = if index == 0 {
2422                "x".repeat(MAX_PROCESS_LINE_BYTES)
2423            } else {
2424                index.to_string()
2425            };
2426            input.try_send_line(line.clone()).unwrap();
2427            expected.push(ProcessEvent::Stdout(line));
2428        }
2429        assert_eq!(
2430            input.try_send_line("overflow".to_owned()),
2431            Err(ProcessInputError::Full("overflow".to_owned()))
2432        );
2433        input.close();
2434        let sub = input_process("cat", &input);
2435        let (sender, receiver) = mpsc::sync_channel(256);
2436        let (stop, _trigger) = StopSignal::new();
2437        sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2438        expected.push(ProcessEvent::Exited(0));
2439        assert_eq!(receiver.into_iter().collect::<Vec<_>>(), expected);
2440    }
2441
2442    #[test]
2443    #[cfg(unix)]
2444    fn real_input_natural_exit_and_spawn_failure_close_open_ingress() {
2445        for program in ["sh", "/ftui-process-input-command-does-not-exist"] {
2446            let input = ProcessInput::new();
2447            let sub = ProcessSubscription::new(program, |event| event)
2448                .args(["-c", "exit 0"])
2449                .stdin(input.clone())
2450                .timeout(Duration::from_secs(5));
2451            let (sender, receiver) = mpsc::sync_channel(256);
2452            let (stop, _trigger) = StopSignal::new();
2453            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2454            let events: Vec<_> = receiver.into_iter().collect();
2455            if program == "sh" {
2456                assert_eq!(events, [ProcessEvent::Exited(0)]);
2457            } else {
2458                assert!(
2459                    matches!(events.as_slice(), [ProcessEvent::Error(error)] if error.starts_with("Failed to spawn"))
2460                );
2461            }
2462            assert_eq!(
2463                input.try_send_line("late".to_owned()),
2464                Err(ProcessInputError::Closed("late".to_owned()))
2465            );
2466        }
2467    }
2468
2469    #[test]
2470    #[cfg(unix)]
2471    fn input_writer_reports_canceled_pending_line_instead_of_success() {
2472        let input = ProcessInput::new();
2473        input.try_send_line("pending".to_owned()).unwrap();
2474        let (_guard, receiver) = input.claim().unwrap();
2475        let mut child = Command::new("sh")
2476            .args(["-c", "exec sleep 60"])
2477            .stdin(Stdio::piped())
2478            .spawn()
2479            .unwrap();
2480        let (stop, trigger) = StopSignal::new();
2481        trigger.stop();
2482        let result = write_process_input(child.stdin.take().unwrap(), receiver, stop);
2483        child.kill().unwrap();
2484        child.wait().unwrap();
2485        assert_eq!(
2486            result.unwrap_err().to_string(),
2487            "queued stdin was canceled before writing"
2488        );
2489    }
2490
2491    #[test]
2492    #[cfg(target_os = "linux")]
2493    fn real_input_blocked_pipe_does_not_block_admission_or_stop() {
2494        let input = ProcessInput::new();
2495        let sub = input_process("printf '%s\\n' \"$$\"; exec sleep 60", &input);
2496        let (sender, receiver) = mpsc::sync_channel(256);
2497        let (stop, trigger) = StopSignal::new();
2498        let handle =
2499            thread::spawn(move || sub.run(SubscriptionSender::new(sender, stop.clone()), stop));
2500        let ProcessEvent::Stdout(pid) = receiver.recv_timeout(Duration::from_secs(5)).unwrap()
2501        else {
2502            panic!("missing live child PID")
2503        };
2504        let pid: u32 = pid.parse().unwrap();
2505        let payload = "x".repeat(MAX_PROCESS_LINE_BYTES);
2506        let started = Instant::now();
2507        let mut full = false;
2508        for _ in 0..PROCESS_INPUT_CAPACITY + 2 {
2509            match input.try_send_line(payload.clone()) {
2510                Ok(()) => {}
2511                Err(ProcessInputError::Full(unsent)) => {
2512                    assert_eq!(unsent, payload);
2513                    full = true;
2514                    break;
2515                }
2516                other => panic!("unexpected admission: {other:?}"),
2517            }
2518        }
2519        let admission_elapsed = started.elapsed();
2520        // Give the worker time to enter a write exceeding the pipe capacity.
2521        thread::sleep(Duration::from_millis(100));
2522        let retry = input.try_send_line(payload);
2523        let before_stop = Instant::now();
2524        trigger.stop();
2525        handle.join().unwrap();
2526        let stopped_in = before_stop.elapsed();
2527        let reaped = std::fs::metadata(format!("/proc/{pid}"))
2528            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
2529        assert!(full);
2530        assert!(admission_elapsed < Duration::from_secs(1));
2531        // One line can move from the queue to the blocked worker after Full.
2532        assert!(matches!(retry, Ok(()) | Err(ProcessInputError::Full(_))));
2533        assert!(stopped_in < Duration::from_secs(2));
2534        assert!(reaped, "child must be reaped before test cleanup");
2535        assert_eq!(
2536            input.try_send_line("late".to_owned()),
2537            Err(ProcessInputError::Closed("late".to_owned()))
2538        );
2539        assert_eq!(
2540            receiver.into_iter().collect::<Vec<_>>(),
2541            [ProcessEvent::Killed]
2542        );
2543    }
2544
2545    #[cfg(target_os = "linux")]
2546    fn await_pipe_wait(task: &std::path::Path) {
2547        let deadline = Instant::now() + Duration::from_secs(3);
2548        loop {
2549            let state = std::fs::read_to_string(task.join("wchan")).unwrap();
2550            // Observe an actual kernel pipe/readiness wait before cancellation.
2551            // The blocking implementation reaches pipe_read/pipe_write; the
2552            // interruptible implementation reaches poll_schedule_timeout.
2553            if state.contains("poll") || state.contains("pipe_read") || state.contains("pipe_write")
2554            {
2555                return;
2556            }
2557            assert!(
2558                Instant::now() < deadline,
2559                "worker never waited on its pipe: {state}"
2560            );
2561            thread::sleep(Duration::from_millis(5));
2562        }
2563    }
2564
2565    #[test]
2566    #[cfg(target_os = "linux")]
2567    fn real_output_workers_cancel_while_child_keeps_both_pipes_open() {
2568        // Seed the original blocking-pipe defect as a live negative control;
2569        // the same observer must reject completion before fixture cleanup.
2570        assert_output_worker_lifetime(false);
2571        assert_output_worker_lifetime(true);
2572    }
2573
2574    #[cfg(target_os = "linux")]
2575    fn assert_output_worker_lifetime(nonblocking: bool) {
2576        let script = "import os,signal\nsignal.alarm(8)\nassert os.read(0,1)==b'R'\nassert all(os.get_blocking(fd) for fd in (0,1,2))\nos.write(1,b'out-prefix')\nos.write(2,b'err-prefix')\nsignal.pause()";
2577        let mut child = Command::new("python3")
2578            .args(["-u", "-c", script])
2579            .stdin(Stdio::piped())
2580            .stdout(Stdio::piped())
2581            .stderr(Stdio::piped())
2582            .spawn()
2583            .unwrap();
2584        let stdout = child.stdout.take().unwrap();
2585        let stderr = child.stderr.take().unwrap();
2586        let (stop, trigger) = StopSignal::new();
2587        let (sender, receiver) = mpsc::sync_channel(8);
2588        let (task_sender, task_receiver) = mpsc::channel();
2589        let start_worker = |pipe: Box<dyn ReadPipe>, stream: &'static str| {
2590            let stop = stop.clone();
2591            let sender = sender.clone();
2592            let task_sender = task_sender.clone();
2593            thread::spawn(move || {
2594                let pipe = process_pipe(pipe, stop.clone()).map_err(ProcessReadError::Io)?;
2595                if !nonblocking {
2596                    rustix::io::ioctl_fionbio(&pipe.pipe, false)
2597                        .map_err(|error| ProcessReadError::Io(error.into()))?;
2598                }
2599                task_sender
2600                    .send(std::fs::read_link("/proc/thread-self").unwrap())
2601                    .unwrap();
2602                forward_lines(
2603                    pipe,
2604                    SubscriptionSender::new(sender, stop.clone()),
2605                    stop,
2606                    true,
2607                    |line| format!("{stream}:line:{line}"),
2608                    |prefix| format!("{stream}:partial:{prefix}"),
2609                )
2610            })
2611        };
2612        let stdout_worker = start_worker(Box::new(stdout), "out");
2613        let stderr_worker = start_worker(Box::new(stderr), "err");
2614        let tasks = [task_receiver.recv().unwrap(), task_receiver.recv().unwrap()];
2615        child.stdin.as_mut().unwrap().write_all(b"R").unwrap();
2616        let mut previews = [
2617            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
2618            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
2619        ];
2620        previews.sort();
2621        assert_eq!(
2622            previews,
2623            ["err:partial:err-prefix", "out:partial:out-prefix"]
2624        );
2625        for task in tasks {
2626            await_pipe_wait(&std::path::Path::new("/proc").join(task));
2627        }
2628        trigger.stop();
2629        let deadline = Instant::now() + Duration::from_secs(2);
2630        while !(stdout_worker.is_finished() && stderr_worker.is_finished())
2631            && Instant::now() < deadline
2632        {
2633            thread::sleep(Duration::from_millis(5));
2634        }
2635        let workers_finished_before_cleanup =
2636            stdout_worker.is_finished() && stderr_worker.is_finished();
2637        let child_alive_before_cleanup = child.try_wait().unwrap().is_none();
2638        child.kill().unwrap();
2639        child.wait().unwrap();
2640        stdout_worker.join().unwrap().unwrap();
2641        stderr_worker.join().unwrap().unwrap();
2642        assert_eq!(
2643            workers_finished_before_cleanup, nonblocking,
2644            "only nonblocking workers should finish before peer cleanup"
2645        );
2646        assert!(child_alive_before_cleanup);
2647        assert!(
2648            receiver.try_iter().next().is_none(),
2649            "cancellation must not complete the pending prefixes as EOF lines"
2650        );
2651    }
2652
2653    #[cfg(target_os = "linux")]
2654    trait ReadPipe: Read + std::os::fd::AsFd + Send {}
2655
2656    #[cfg(target_os = "linux")]
2657    impl<P: Read + std::os::fd::AsFd + Send> ReadPipe for P {}
2658
2659    #[test]
2660    #[cfg(target_os = "linux")]
2661    fn real_input_worker_cancels_full_pipe_and_closes_it_before_child_exits() {
2662        use std::os::unix::process::ChildExt;
2663
2664        let script = "import fcntl,os,signal,sys,time\nsignal.alarm(8)\nfcntl.fcntl(0,fcntl.F_SETPIPE_SZ,4096)\nready=False\ndef release(*args):\n global ready\n ready=True\nsignal.signal(signal.SIGUSR1,release)\nprint('READY',flush=True)\nwhile not ready:\n time.sleep(0.005)\ndata=sys.stdin.buffer.read()\nprint(str(len(data))+':'+str(data==b'x'*len(data))+':'+str(os.get_blocking(0)),flush=True)";
2665        let mut child = Command::new("python3")
2666            .args(["-u", "-c", script])
2667            .stdin(Stdio::piped())
2668            .stdout(Stdio::piped())
2669            .spawn()
2670            .unwrap();
2671        let mut stdout = io::BufReader::new(child.stdout.take().unwrap());
2672        let mut ready = String::new();
2673        stdout.read_line(&mut ready).unwrap();
2674        assert_eq!(ready, "READY\n");
2675        let input = ProcessInput::new();
2676        input
2677            .try_send_line("x".repeat(MAX_PROCESS_LINE_BYTES))
2678            .unwrap();
2679        let (_guard, receiver) = input.claim().unwrap();
2680        let stdin = child.stdin.take().unwrap();
2681        let (stop, trigger) = StopSignal::new();
2682        let (task_sender, task_receiver) = mpsc::channel();
2683        let worker = thread::spawn(move || {
2684            task_sender
2685                .send(std::fs::read_link("/proc/thread-self").unwrap())
2686                .unwrap();
2687            write_process_input(stdin, receiver, stop)
2688        });
2689        await_pipe_wait(&std::path::Path::new("/proc").join(task_receiver.recv().unwrap()));
2690        trigger.stop();
2691        let deadline = Instant::now() + Duration::from_secs(2);
2692        while !worker.is_finished() && Instant::now() < deadline {
2693            thread::sleep(Duration::from_millis(5));
2694        }
2695        let worker_finished_before_release = worker.is_finished();
2696        let child_alive_before_release = child.try_wait().unwrap().is_none();
2697        child
2698            .send_signal(rustix::process::Signal::USR1.as_raw())
2699            .unwrap();
2700        let result = worker.join().unwrap();
2701        let mut output = String::new();
2702        stdout.read_to_string(&mut output).unwrap();
2703        let status = child.wait().unwrap();
2704        assert!(
2705            worker_finished_before_release,
2706            "stdin worker depended on child reading or exiting"
2707        );
2708        assert!(child_alive_before_release);
2709        assert_eq!(
2710            result.unwrap_err().to_string(),
2711            "stdin write canceled before completion"
2712        );
2713        assert!(status.success());
2714        assert_eq!(
2715            output, "4096:True:True\n",
2716            "only the exact written prefix should arrive, without LF, duplication or changed child blocking mode"
2717        );
2718    }
2719
2720    #[test]
2721    #[cfg(target_os = "linux")]
2722    fn real_input_write_failure_reaps_child_despite_full_model_queue() {
2723        let input = ProcessInput::new();
2724        let (observed_tx, observed_rx) = mpsc::channel();
2725        let sub = ProcessSubscription::new("sh", move |event| {
2726            observed_tx.send(event.clone()).unwrap();
2727            event
2728        })
2729        .args(["-c", "exec 0<&-; printf '%s\\n' \"$$\"; exec sleep 60"])
2730        .stdin(input.clone())
2731        .timeout(Duration::from_secs(5));
2732        let (sender, receiver) = mpsc::sync_channel(1);
2733        sender
2734            .send(ProcessEvent::Stdout("prefix".to_owned()))
2735            .unwrap();
2736        let (stop, trigger) = StopSignal::new();
2737        let handle =
2738            thread::spawn(move || sub.run(SubscriptionSender::new(sender, stop.clone()), stop));
2739        let ProcessEvent::Stdout(pid) = observed_rx.recv_timeout(Duration::from_secs(5)).unwrap()
2740        else {
2741            panic!("missing live PID")
2742        };
2743        let pid: u32 = pid.parse().unwrap();
2744        input
2745            .try_send_line("cannot reach closed pipe".to_owned())
2746            .unwrap();
2747        let terminal = observed_rx.recv_timeout(Duration::from_secs(5));
2748        let reaped = std::fs::metadata(format!("/proc/{pid}"))
2749            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
2750        // Observe supervision/reaping before releasing model backpressure.
2751        assert_eq!(
2752            receiver.recv().unwrap(),
2753            ProcessEvent::Stdout("prefix".to_owned())
2754        );
2755        let delivered = receiver.recv_timeout(Duration::from_secs(5));
2756        trigger.stop();
2757        handle.join().unwrap();
2758        let terminal = terminal.unwrap();
2759        assert!(
2760            matches!(&terminal, ProcessEvent::Error(error) if error.starts_with("stdin write failed") && error.contains("reaped:")),
2761            "{terminal:?}"
2762        );
2763        assert_eq!(delivered.unwrap(), terminal);
2764        assert!(reaped, "writer error must reap child before model drains");
2765        assert_eq!(
2766            input.try_send_line("late".to_owned()),
2767            Err(ProcessInputError::Closed("late".to_owned()))
2768        );
2769        assert!(receiver.try_recv().is_err());
2770    }
2771
2772    fn collect_lines(bytes: &[u8], read_capacity: usize) -> Result<Vec<String>, ProcessReadError> {
2773        let mut reader = io::BufReader::with_capacity(read_capacity, bytes);
2774        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
2775        let (stop, _trigger) = StopSignal::new();
2776        let mut lines = Vec::new();
2777        while let Some(line) = read_process_line(&mut reader, &mut pending, &stop, None)? {
2778            lines.push(line);
2779        }
2780        Ok(lines)
2781    }
2782
2783    #[test]
2784    fn partial_output_identity_is_stable_and_distinct_from_line_only() {
2785        let plain = ProcessSubscription::new("cat", |event| event);
2786        let enabled = ProcessSubscription::new("cat", |event| event).partial_output(true);
2787        assert_ne!(plain.id(), enabled.id());
2788        assert_eq!(
2789            enabled.id(),
2790            ProcessSubscription::new("cat", |event| event)
2791                .partial_output(true)
2792                .id()
2793        );
2794        assert_eq!(plain.id(), enabled.partial_output(false).id());
2795        assert_eq!(
2796            ProcessSubscription::new("cat", |event| event)
2797                .with_id(42)
2798                .partial_output(true)
2799                .id(),
2800            42
2801        );
2802    }
2803
2804    #[test]
2805    fn partial_prefixes_preserve_utf8_controls_and_crlf_across_read_boundaries() {
2806        let input = "\n🦀é\x1b]2;hidden\x07prompt>\r\ninside\rcarriage\nlast\r";
2807        for capacity in 1..=input.len() {
2808            let mut reader = io::BufReader::with_capacity(capacity, input.as_bytes());
2809            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
2810            let (stop, _trigger) = StopSignal::new();
2811            let mut complete = Vec::new();
2812            loop {
2813                let mut previews = Vec::new();
2814                let mut preview = |text: &str| {
2815                    previews.push(text.to_owned());
2816                    true
2817                };
2818                let line = read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview))
2819                    .unwrap();
2820                let Some(line) = line else {
2821                    assert!(previews.is_empty());
2822                    break;
2823                };
2824                let mut length = 0;
2825                for prefix in previews {
2826                    assert!(!prefix.is_empty());
2827                    assert!(line.starts_with(&prefix));
2828                    assert!(prefix.len() > length);
2829                    length = prefix.len();
2830                    assert!(!prefix.contains('\u{fffd}'));
2831                }
2832                complete.push(line);
2833            }
2834            assert_eq!(
2835                complete,
2836                [
2837                    "",
2838                    "🦀é\x1b]2;hidden\x07prompt>",
2839                    "inside\rcarriage",
2840                    "last\r"
2841                ]
2842            );
2843        }
2844    }
2845
2846    #[test]
2847    fn partial_prefix_validation_keeps_line_bounds_and_stop_before_another_read() {
2848        for delimiter in ["", "\n", "\r\n"] {
2849            let input = format!("{}{delimiter}", "x".repeat(MAX_PROCESS_LINE_BYTES));
2850            let mut reader = io::BufReader::with_capacity(8192, input.as_bytes());
2851            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
2852            let capacity = pending.capacity();
2853            let (stop, _trigger) = StopSignal::new();
2854            let mut largest = 0;
2855            let mut preview = |prefix: &str| {
2856                assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
2857                largest = largest.max(prefix.len());
2858                true
2859            };
2860            let line = read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview))
2861                .unwrap()
2862                .unwrap();
2863            assert_eq!(line.len(), MAX_PROCESS_LINE_BYTES);
2864            assert!(largest > 0);
2865            assert_eq!(pending.capacity(), capacity);
2866        }
2867
2868        for input in [
2869            vec![b'x'; MAX_PROCESS_LINE_BYTES + 1],
2870            b"safe\xff".to_vec(),
2871            b"safe\xf0\x9f".to_vec(),
2872        ] {
2873            let mut reader = io::BufReader::with_capacity(8192, input.as_slice());
2874            let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
2875            let (stop, _trigger) = StopSignal::new();
2876            let mut preview = |prefix: &str| {
2877                assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
2878                assert!(!prefix.contains('\u{fffd}'));
2879                true
2880            };
2881            assert!(matches!(
2882                read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview)),
2883                Err(ProcessReadError::LineTooLong | ProcessReadError::InvalidUtf8(_))
2884            ));
2885            assert!(pending.len() <= MAX_PROCESS_LINE_BYTES + 1);
2886        }
2887
2888        let mut reader = io::BufReader::with_capacity(3, io::Cursor::new(b"pending forever"));
2889        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
2890        let (stop, trigger) = StopSignal::new();
2891        let mut preview = |prefix: &str| {
2892            assert_eq!(prefix, "pen");
2893            trigger.stop();
2894            false
2895        };
2896        assert_eq!(
2897            read_process_line(&mut reader, &mut pending, &stop, Some(&mut preview)).unwrap(),
2898            None
2899        );
2900        assert_eq!(reader.get_ref().position(), 3);
2901    }
2902
2903    #[test]
2904    #[cfg(unix)]
2905    fn real_partial_prompt_precedes_reply_and_preserves_split_utf8_controls_and_crlf() {
2906        let input = ProcessInput::new();
2907        let control = ProcessControl::new();
2908        let script = r#"import os,signal,sys
2909signal.alarm(5)
2910os.write(1,b'prompt \xf0\x9f')
2911assert sys.stdin.readline() == 'utf8\n'
2912os.write(1,b'\xa6\x80 \x1b]')
2913assert sys.stdin.readline() == 'osc\n'
2914os.write(1,b'2;hidden\x07 ready>')
2915assert sys.stdin.readline() == 'answer\n'
2916os.write(1,b'\r')
2917os.write(2,b'CR-WRITTEN\n')
2918assert sys.stdin.readline() == 'lf\n'
2919os.write(1,b'\nnormal\r\n')
2920os.write(2,b'err>')
2921assert sys.stdin.readline() == 'err\n'
2922os.write(2,b'\r\n')
2923os.write(1,b'tail\r')
2924"#;
2925        let sub = controlled_python(script, &control)
2926            .stdin(input.clone())
2927            .partial_output(true);
2928        let (sender, receiver) = mpsc::sync_channel(256);
2929        let (stop, _trigger) = StopSignal::new();
2930        let handle = thread::spawn(move || {
2931            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
2932        });
2933        let mut previous_length = 0;
2934        for (expected, reply) in [
2935            ("prompt ", "utf8"),
2936            ("prompt 🦀 \x1b]", "osc"),
2937            ("prompt 🦀 \x1b]2;hidden\x07 ready>", "answer"),
2938        ] {
2939            loop {
2940                let ProcessEvent::StdoutPartial(prefix) =
2941                    receiver.recv_timeout(Duration::from_secs(3)).unwrap()
2942                else {
2943                    panic!("expected a pending stdout prefix before the reply");
2944                };
2945                assert!(expected.starts_with(&prefix));
2946                assert!(prefix.len() > previous_length);
2947                previous_length = prefix.len();
2948                if prefix == expected {
2949                    break;
2950                }
2951            }
2952            assert!(!control.status().closed);
2953            // The real child is waiting for this reply: no LF/EOF can unlock
2954            // the expected preview. Disabled previews fail at the first wait.
2955            input.try_send_line(reply.to_owned()).unwrap();
2956        }
2957        loop {
2958            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
2959                ProcessEvent::StderrPartial(prefix) => assert!("CR-WRITTEN".starts_with(&prefix)),
2960                ProcessEvent::Stderr(line) => {
2961                    assert_eq!(line, "CR-WRITTEN");
2962                    break;
2963                }
2964                event => panic!("unexpected event while CR is held: {event:?}"),
2965            }
2966        }
2967        assert!(matches!(
2968            receiver.recv_timeout(Duration::from_millis(100)),
2969            Err(mpsc::RecvTimeoutError::Timeout)
2970        ));
2971        input.try_send_line("lf".to_owned()).unwrap();
2972        let expected_stdout = ["prompt 🦀 \x1b]2;hidden\x07 ready>", "normal", "tail\r"];
2973        let mut stdout = Vec::new();
2974        loop {
2975            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
2976                ProcessEvent::Stdout(line) => stdout.push(line),
2977                ProcessEvent::StdoutPartial(prefix) => {
2978                    assert!(expected_stdout[stdout.len()].starts_with(&prefix));
2979                }
2980                ProcessEvent::StderrPartial(prefix) => {
2981                    assert!("err>".starts_with(&prefix));
2982                    if prefix == "err>" {
2983                        break;
2984                    }
2985                }
2986                event => panic!("unexpected event before stderr reply: {event:?}"),
2987            }
2988        }
2989        input.try_send_line("err".to_owned()).unwrap();
2990        let mut stderr = Vec::new();
2991        loop {
2992            match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
2993                ProcessEvent::Stdout(line) => stdout.push(line),
2994                ProcessEvent::Stderr(line) => stderr.push(line),
2995                ProcessEvent::StdoutPartial(prefix) => {
2996                    assert!(expected_stdout[stdout.len()].starts_with(&prefix));
2997                    assert!(!prefix.ends_with('\r'));
2998                }
2999                ProcessEvent::Exited(code) => {
3000                    assert_eq!(code, 0);
3001                    break;
3002                }
3003                event => panic!("unexpected event after reply: {event:?}"),
3004            }
3005        }
3006        handle.join().unwrap();
3007        assert_eq!(stdout, expected_stdout);
3008        assert_eq!(stderr, ["err>"]);
3009        assert!(receiver.try_recv().is_err());
3010        assert!(control.status().can_restart);
3011    }
3012
3013    #[test]
3014    #[cfg(unix)]
3015    fn real_partial_output_is_disabled_by_default_without_changing_completed_lines() {
3016        let input = ProcessInput::new();
3017        let control = ProcessControl::new();
3018        let script = "import os,signal,sys\nsignal.alarm(5)\nos.write(1,b'prompt>')\nos.write(2,b'READY\\n')\nassert sys.stdin.readline()=='reply\\n'\nos.write(1,b'\\r\\nnormal\\n')";
3019        let sub = controlled_python(script, &control).stdin(input.clone());
3020        let (sender, receiver) = mpsc::sync_channel(256);
3021        let (stop, _trigger) = StopSignal::new();
3022        let handle = thread::spawn(move || {
3023            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3024        });
3025        assert_eq!(
3026            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
3027            ProcessEvent::Stderr("READY".to_owned())
3028        );
3029        assert!(matches!(
3030            receiver.recv_timeout(Duration::from_millis(100)),
3031            Err(mpsc::RecvTimeoutError::Timeout)
3032        ));
3033        input.try_send_line("reply".to_owned()).unwrap();
3034        let events: Vec<_> = (0..3)
3035            .map(|_| receiver.recv_timeout(Duration::from_secs(3)).unwrap())
3036            .collect();
3037        handle.join().unwrap();
3038        assert_eq!(
3039            events,
3040            [
3041                ProcessEvent::Stdout("prompt>".to_owned()),
3042                ProcessEvent::Stdout("normal".to_owned()),
3043                ProcessEvent::Exited(0)
3044            ]
3045        );
3046        assert!(receiver.try_recv().is_err());
3047    }
3048
3049    #[test]
3050    #[cfg(unix)]
3051    fn real_partial_queue_backpressure_remains_interruptible() {
3052        let input = ProcessInput::new();
3053        let control = ProcessControl::new();
3054        let (observed_sender, observed_receiver) = mpsc::channel();
3055        let sub = ProcessSubscription::new("python3", move |event| {
3056            if let ProcessEvent::StdoutPartial(prefix) = &event {
3057                observed_sender.send(prefix.clone()).unwrap();
3058            }
3059            event
3060        })
3061        .args(["-u", "-c", "import os,signal,sys\nsignal.alarm(5)\nos.write(1,b'a')\nassert sys.stdin.readline()=='next\\n'\nos.write(1,b'b')\nsignal.pause()"])
3062        .stdin(input.clone())
3063        .control(control.clone())
3064        .partial_output(true)
3065        .timeout(Duration::from_secs(5));
3066        let (sender, receiver) = mpsc::sync_channel(1);
3067        let (stop, trigger) = StopSignal::new();
3068        let handle = thread::spawn(move || {
3069            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3070        });
3071        // Do not drain the first admitted prefix. The second conversion is
3072        // observed before bounded queue admission, not as delivered output.
3073        assert_eq!(
3074            observed_receiver
3075                .recv_timeout(Duration::from_secs(3))
3076                .unwrap(),
3077            "a"
3078        );
3079        input.try_send_line("next".to_owned()).unwrap();
3080        assert_eq!(
3081            observed_receiver
3082                .recv_timeout(Duration::from_secs(3))
3083                .unwrap(),
3084            "ab"
3085        );
3086        let stopped = Instant::now();
3087        trigger.stop();
3088        handle.join().unwrap();
3089        assert!(stopped.elapsed() < Duration::from_secs(2));
3090        assert_eq!(
3091            receiver.into_iter().collect::<Vec<_>>(),
3092            [ProcessEvent::StdoutPartial("a".to_owned())]
3093        );
3094        assert!(control.status().can_restart);
3095    }
3096
3097    #[test]
3098    #[cfg(unix)]
3099    fn real_partial_output_errors_preserve_bounds_and_never_report_success() {
3100        for (payload, reason) in [
3101            ("b'x'*65537", "line exceeds"),
3102            ("b'valid\\xff'", "invalid UTF-8"),
3103            ("b'valid\\xf0\\x9f'", "invalid UTF-8"),
3104        ] {
3105            let control = ProcessControl::new();
3106            let script = format!("import os,signal\nsignal.alarm(5)\nos.write(1,{payload})");
3107            let sub = controlled_python(&script, &control).partial_output(true);
3108            let (sender, receiver) = mpsc::sync_channel(256);
3109            let (stop, _trigger) = StopSignal::new();
3110            let handle = thread::spawn(move || {
3111                sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
3112            });
3113            loop {
3114                match receiver.recv_timeout(Duration::from_secs(3)).unwrap() {
3115                    ProcessEvent::StdoutPartial(prefix) => {
3116                        assert!(prefix.len() <= MAX_PROCESS_LINE_BYTES);
3117                        assert!(!prefix.contains('\u{fffd}'));
3118                    }
3119                    ProcessEvent::Error(error) => {
3120                        assert!(error.contains(reason), "{error}");
3121                        break;
3122                    }
3123                    event => panic!("invalid output must not succeed: {event:?}"),
3124                }
3125            }
3126            handle.join().unwrap();
3127            assert!(receiver.try_recv().is_err());
3128            assert!(control.status().can_restart);
3129        }
3130    }
3131
3132    #[test]
3133    fn bounded_lines_preserve_delimiters_unicode_and_eof_across_reads() {
3134        let input = "\nalpha\r\n\r\n🦀é\ninside\rcarriage\nlast\r";
3135        let expected = ["", "alpha", "", "🦀é", "inside\rcarriage", "last\r"];
3136        for capacity in 1..=input.len() {
3137            assert_eq!(collect_lines(input.as_bytes(), capacity).unwrap(), expected);
3138            assert!(collect_lines(b"", capacity).unwrap().is_empty());
3139            assert_eq!(collect_lines(b"tail\n", capacity).unwrap(), ["tail"]);
3140        }
3141    }
3142
3143    #[test]
3144    fn bounded_lines_enforce_payload_limit_for_lf_crlf_and_eof() {
3145        for size in [MAX_PROCESS_LINE_BYTES - 1, MAX_PROCESS_LINE_BYTES] {
3146            let payload = "x".repeat(size);
3147            for delimiter in ["", "\n", "\r\n"] {
3148                let input = format!("{payload}{delimiter}");
3149                for capacity in [1, 8192, MAX_PROCESS_LINE_BYTES + 1] {
3150                    assert_eq!(
3151                        collect_lines(input.as_bytes(), capacity).unwrap(),
3152                        [payload.as_str()],
3153                        "size={size}, delimiter={delimiter:?}, read capacity={capacity}"
3154                    );
3155                }
3156            }
3157        }
3158        let unicode = "🦀".repeat(MAX_PROCESS_LINE_BYTES / 4);
3159        assert_eq!(collect_lines(unicode.as_bytes(), 3).unwrap(), [unicode]);
3160        for tail in ["x", "x\n", "x\r\n", "\r"] {
3161            let input = format!("{}{tail}", "x".repeat(MAX_PROCESS_LINE_BYTES));
3162            assert!(matches!(
3163                collect_lines(input.as_bytes(), 8192),
3164                Err(ProcessReadError::LineTooLong)
3165            ));
3166        }
3167    }
3168
3169    #[test]
3170    fn bounded_lines_reject_invalid_utf8_without_lossy_substitution() {
3171        for input in [b"secret\xff\n".as_slice(), b"\xf0\x9f\xa6", b"\xc0\x80\r\n"] {
3172            for capacity in 1..=input.len() {
3173                assert!(matches!(
3174                    collect_lines(input, capacity),
3175                    Err(ProcessReadError::InvalidUtf8(_))
3176                ));
3177            }
3178        }
3179    }
3180
3181    #[test]
3182    fn bounded_lines_stop_reading_before_oversized_input_allocates() {
3183        let input = vec![b'x'; MAX_PROCESS_LINE_BYTES * 16];
3184        let cursor = io::Cursor::new(input);
3185        let mut reader = io::BufReader::with_capacity(8192, cursor);
3186        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3187        let capacity = pending.capacity();
3188        let (stop, trigger) = StopSignal::new();
3189        assert!(matches!(
3190            read_process_line(&mut reader, &mut pending, &stop, None),
3191            Err(ProcessReadError::LineTooLong)
3192        ));
3193        assert!(pending.len() <= MAX_PROCESS_LINE_BYTES + 1);
3194        assert_eq!(pending.capacity(), capacity);
3195        let consumed = reader.get_ref().position();
3196        assert!(consumed <= (MAX_PROCESS_LINE_BYTES + 8192) as u64);
3197        trigger.stop();
3198        assert_eq!(
3199            read_process_line(&mut reader, &mut pending, &stop, None).unwrap(),
3200            None
3201        );
3202        assert_eq!(reader.get_ref().position(), consumed);
3203    }
3204
3205    #[test]
3206    fn bounded_lines_retry_interrupted_reads_and_report_io_failures() {
3207        struct FaultingReader {
3208            calls: usize,
3209        }
3210        impl Read for FaultingReader {
3211            fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
3212                self.calls += 1;
3213                match self.calls {
3214                    1 => Err(io::ErrorKind::Interrupted.into()),
3215                    2 => {
3216                        let bytes = b"good\npartial";
3217                        buffer[..bytes.len()].copy_from_slice(bytes);
3218                        Ok(bytes.len())
3219                    }
3220                    _ => Err(io::Error::other("injected read failure")),
3221                }
3222            }
3223        }
3224        let mut reader = io::BufReader::new(FaultingReader { calls: 0 });
3225        let mut pending = Vec::with_capacity(MAX_PROCESS_LINE_BYTES + 1);
3226        let (stop, _trigger) = StopSignal::new();
3227        assert_eq!(
3228            read_process_line(&mut reader, &mut pending, &stop, None).unwrap(),
3229            Some("good".to_owned())
3230        );
3231        assert!(matches!(
3232            read_process_line(&mut reader, &mut pending, &stop, None),
3233            Err(ProcessReadError::Io(error)) if error.kind() == io::ErrorKind::Other
3234        ));
3235    }
3236
3237    fn collect_real_process(script: &str) -> Vec<ProcessEvent> {
3238        let sub = ProcessSubscription::new("sh", |event| event).args(["-c", script]);
3239        let (tx, rx) = stdmpsc::sync_channel(256);
3240        let (signal, trigger) = StopSignal::new();
3241        let handle = thread::spawn(move || {
3242            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3243        });
3244        let mut events = Vec::new();
3245        loop {
3246            match rx.recv_timeout(Duration::from_secs(5)) {
3247                Ok(event) => events.push(event),
3248                Err(stdmpsc::RecvTimeoutError::Disconnected) => break,
3249                Err(stdmpsc::RecvTimeoutError::Timeout) => {
3250                    trigger.stop();
3251                    handle.join().expect("stop timed-out child");
3252                    panic!("child supervision stalled after {} events", events.len());
3253                }
3254            }
3255        }
3256        handle.join().expect("supervisor finished");
3257        events
3258    }
3259
3260    #[test]
3261    fn real_process_preserves_complete_lines_and_maximum_payload_on_both_streams() {
3262        let events = collect_real_process(
3263            "printf '\\nalpha\\r\\n🦀é\\nlast\\r'; printf '%065536d\\r\\n' 0 >&2; printf 'tail' >&2",
3264        );
3265        let stdout: Vec<_> = events
3266            .iter()
3267            .filter_map(|event| match event {
3268                ProcessEvent::Stdout(line) => Some(line.as_str()),
3269                _ => None,
3270            })
3271            .collect();
3272        let stderr: Vec<_> = events
3273            .iter()
3274            .filter_map(|event| match event {
3275                ProcessEvent::Stderr(line) => Some(line.as_str()),
3276                _ => None,
3277            })
3278            .collect();
3279        assert_eq!(stdout, ["", "alpha", "🦀é", "last\r"]);
3280        assert_eq!(
3281            stderr,
3282            ["0".repeat(MAX_PROCESS_LINE_BYTES), "tail".to_owned()]
3283        );
3284        assert_eq!(events.len(), 7);
3285        assert_eq!(events.last(), Some(&ProcessEvent::Exited(0)));
3286
3287        let events = collect_real_process("printf '%065536d\\n' 0");
3288        assert_eq!(
3289            events,
3290            [
3291                ProcessEvent::Stdout("0".repeat(MAX_PROCESS_LINE_BYTES)),
3292                ProcessEvent::Exited(0)
3293            ]
3294        );
3295    }
3296
3297    #[test]
3298    fn real_process_invalid_or_oversized_output_reports_one_error() {
3299        for (output, reason) in [
3300            ("printf '\\377\\n'", "invalid UTF-8"),
3301            ("printf '%065537d' 0", "line exceeds 65536 payload bytes"),
3302        ] {
3303            for stream in ["stdout", "stderr"] {
3304                let redirect = if stream == "stderr" { " >&2" } else { "" };
3305                for ending in ["exit 0", "exec sleep 60"] {
3306                    let events = collect_real_process(&format!("{output}{redirect}; {ending}"));
3307                    assert_eq!(events.len(), 1, "one terminal error: {events:?}");
3308                    let ProcessEvent::Error(error) = &events[0] else {
3309                        panic!("reader failure misreported: {events:?}");
3310                    };
3311                    assert!(error.starts_with(&format!("{stream} {reason}")), "{error}");
3312                    assert!(error.contains("reaped:"), "{error}");
3313                    assert!(
3314                        error.ends_with("stdout/stderr output is incomplete"),
3315                        "{error}"
3316                    );
3317                }
3318            }
3319        }
3320    }
3321
3322    #[test]
3323    #[cfg(target_os = "linux")]
3324    fn real_process_reader_failure_reaps_child_while_model_queue_is_full() {
3325        for (output, reason) in [
3326            ("printf '\\377\\n'", "stderr invalid UTF-8:"),
3327            (
3328                "printf '%065537d' 0",
3329                "stderr line exceeds 65536 payload bytes",
3330            ),
3331        ] {
3332            assert_reader_failure_with_full_queue(output, reason);
3333        }
3334    }
3335
3336    #[cfg(target_os = "linux")]
3337    fn child_has_sigstop(pid: rustix::process::Pid) -> rustix::io::Result<bool> {
3338        use rustix::process::{Signal, WaitId, WaitIdOptions, waitid};
3339
3340        // A ptraced child can report /proc state `t` for an unrelated syscall
3341        // stop. Require the actual SIGSTOP event, leaving it waitable so this
3342        // observer never takes child status away from the supervisor.
3343        Ok(waitid(
3344            WaitId::Pid(pid),
3345            WaitIdOptions::STOPPED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
3346        )?
3347        .is_some_and(|status| status.stopping_signal() == Some(Signal::STOP.as_raw())))
3348    }
3349
3350    #[test]
3351    #[cfg(target_os = "linux")]
3352    fn real_process_stop_oracle_rejects_running_child_without_reaping() {
3353        let (mut child, _stdin, _output) = spawn_cleanup_probe();
3354        let observed = child_has_sigstop(rustix::process::Pid::from_child(&child));
3355        let still_running = child.try_wait();
3356        // Retain observations before explicit cleanup; cleanup is not the
3357        // evidence that the stop oracle left a live child under its owner.
3358        let cleanup = cleanup_child(&mut child, &mut None);
3359        assert_eq!(observed, Ok(false), "a running child has no SIGSTOP event");
3360        assert!(matches!(still_running, Ok(None)));
3361        assert!(cleanup.kill_sent);
3362        assert_eq!(
3363            cleanup.status.map(process_exit_event),
3364            Some(ProcessEvent::Signaled(
3365                rustix::process::Signal::KILL.as_raw()
3366            ))
3367        );
3368    }
3369
3370    #[cfg(target_os = "linux")]
3371    fn assert_reader_failure_with_full_queue(output: &str, reason: &str) {
3372        let (observed_tx, observed_rx) = stdmpsc::channel();
3373        let sub = ProcessSubscription::new("sh", move |event| {
3374            observed_tx
3375                .send(event.clone())
3376                .expect("observe child and supervision");
3377            event
3378        })
3379        .args([
3380            "-c",
3381            &format!("printf '%s\\n' \"$$\"; kill -STOP \"$$\"; {output} >&2; exec sleep 60"),
3382        ]);
3383        let (tx, rx) = stdmpsc::sync_channel(256);
3384        let prefix: Vec<_> = (0..256)
3385            .map(|index| ProcessEvent::Stdout(format!("accepted-{index}")))
3386            .collect();
3387        for event in &prefix {
3388            tx.send(event.clone()).expect("fill application queue");
3389        }
3390        let (signal, trigger) = StopSignal::new();
3391        let handle = thread::spawn(move || {
3392            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3393        });
3394        // This observer is before the blocked application send. Hold the real
3395        // child stopped until its PID is observed so reader scheduling cannot
3396        // race the PID callback against the other stream's failure.
3397        let first = observed_rx.recv_timeout(Duration::from_secs(5));
3398        let pid = match &first {
3399            Ok(ProcessEvent::Stdout(line)) => line.parse::<u32>().ok(),
3400            _ => None,
3401        };
3402        let Some(pid) = pid else {
3403            trigger.stop();
3404            handle.join().expect("stop child without PID");
3405            panic!("expected actual child PID, got {first:?}");
3406        };
3407        let wait_pid =
3408            rustix::process::Pid::from_raw(i32::try_from(pid).expect("Linux child PID fits i32"))
3409                .expect("child PID is nonzero");
3410        let deadline = Instant::now() + Duration::from_secs(5);
3411        loop {
3412            let stopped = child_has_sigstop(wait_pid);
3413            if matches!(stopped, Ok(true)) {
3414                break;
3415            }
3416            if stopped.is_err() || Instant::now() >= deadline {
3417                trigger.stop();
3418                handle.join().expect("stop child that did not pause");
3419                panic!("child never reported SIGSTOP: {stopped:?}");
3420            }
3421            thread::sleep(Duration::from_millis(5));
3422        }
3423        let retained_stop = child_has_sigstop(wait_pid);
3424        if !matches!(retained_stop, Ok(true)) {
3425            trigger.stop();
3426            handle.join().expect("stop child whose status was consumed");
3427            panic!("SIGSTOP observation must leave status waitable: {retained_stop:?}");
3428        }
3429        let resumed = Command::new("kill")
3430            .args(["-CONT", &pid.to_string()])
3431            .status();
3432        if !resumed
3433            .as_ref()
3434            .is_ok_and(std::process::ExitStatus::success)
3435        {
3436            trigger.stop();
3437            handle.join().expect("stop child that did not resume");
3438            panic!("child resume failed: {resumed:?}");
3439        }
3440        // The other stream must fail and be supervised without any drain.
3441        let mut observed = vec![first.unwrap()];
3442        loop {
3443            match observed_rx.recv_timeout(Duration::from_secs(5)) {
3444                Ok(event) => {
3445                    let terminal = matches!(event, ProcessEvent::Error(_));
3446                    observed.push(event);
3447                    if terminal {
3448                        break;
3449                    }
3450                }
3451                Err(error) => {
3452                    trigger.stop();
3453                    handle.join().expect("stop stalled supervision");
3454                    panic!("full queue hid reader failure: {error:?}");
3455                }
3456            }
3457        }
3458        let terminal = observed.last().unwrap().clone();
3459        // Retain the observations before releasing queue backpressure. This
3460        // detects a live child or unreaped zombie, not just a reported status.
3461        let child_reaped = std::fs::metadata(format!("/proc/{pid}"))
3462            .is_err_and(|error| error.kind() == io::ErrorKind::NotFound);
3463        let mut received: Vec<_> = (0..256)
3464            .map(|_| rx.recv().expect("accepted prefix"))
3465            .collect();
3466        received.push(
3467            rx.recv_timeout(Duration::from_secs(5))
3468                .expect("terminal error after drain"),
3469        );
3470        trigger.stop();
3471        handle.join().expect("supervisor finished");
3472        assert!(
3473            child_reaped,
3474            "child must be reaped before any model queue drain: {observed:?}"
3475        );
3476        assert!(
3477            matches!(&terminal, ProcessEvent::Error(error)
3478            if error.starts_with(reason)
3479                && error.contains("reaped:")
3480                && error.ends_with("stdout/stderr output is incomplete")),
3481            "{terminal:?}"
3482        );
3483        let mut expected = prefix;
3484        expected.push(terminal);
3485        assert_eq!(received, expected);
3486        assert!(
3487            rx.try_iter().next().is_none(),
3488            "no late reader output or duplicate status"
3489        );
3490        assert!(
3491            observed_rx.try_iter().next().is_none(),
3492            "readers finished before final event"
3493        );
3494    }
3495
3496    #[test]
3497    fn process_event_variants() {
3498        let stdout = ProcessEvent::Stdout("hello".into());
3499        let stderr = ProcessEvent::Stderr("warn".into());
3500        let exited = ProcessEvent::Exited(0);
3501        let signaled = ProcessEvent::Signaled(15);
3502        let killed = ProcessEvent::Killed;
3503        let error = ProcessEvent::Error("oops".into());
3504
3505        assert_eq!(stdout, ProcessEvent::Stdout("hello".into()));
3506        assert_eq!(stderr, ProcessEvent::Stderr("warn".into()));
3507        assert_eq!(exited, ProcessEvent::Exited(0));
3508        assert_eq!(signaled, ProcessEvent::Signaled(15));
3509        assert_eq!(killed, ProcessEvent::Killed);
3510        assert_eq!(error, ProcessEvent::Error("oops".into()));
3511    }
3512
3513    #[test]
3514    fn subscription_id_is_stable() {
3515        let s1: ProcessSubscription<TestMsg> =
3516            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
3517        let s2: ProcessSubscription<TestMsg> =
3518            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
3519        assert_eq!(s1.id(), s2.id());
3520    }
3521
3522    #[test]
3523    fn different_args_produce_different_ids() {
3524        let s1: ProcessSubscription<TestMsg> =
3525            ProcessSubscription::new("echo", TestMsg::Proc).arg("hello");
3526        let s2: ProcessSubscription<TestMsg> =
3527            ProcessSubscription::new("echo", TestMsg::Proc).arg("world");
3528        assert_ne!(s1.id(), s2.id());
3529    }
3530
3531    #[test]
3532    fn different_programs_produce_different_ids() {
3533        let s1: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc);
3534        let s2: ProcessSubscription<TestMsg> = ProcessSubscription::new("cat", TestMsg::Proc);
3535        assert_ne!(s1.id(), s2.id());
3536    }
3537
3538    #[test]
3539    fn custom_id_overrides_default() {
3540        let s: ProcessSubscription<TestMsg> =
3541            ProcessSubscription::new("echo", TestMsg::Proc).with_id(42);
3542        assert_eq!(s.id(), 42);
3543    }
3544
3545    #[test]
3546    fn env_changes_affect_subscription_id() {
3547        let s1: ProcessSubscription<TestMsg> =
3548            ProcessSubscription::new("echo", TestMsg::Proc).env("FTUI_TEST_VAR", "a");
3549        let s2: ProcessSubscription<TestMsg> =
3550            ProcessSubscription::new("echo", TestMsg::Proc).env("FTUI_TEST_VAR", "b");
3551        assert_ne!(s1.id(), s2.id());
3552    }
3553
3554    #[test]
3555    fn timeout_changes_affect_subscription_id() {
3556        let s1: ProcessSubscription<TestMsg> =
3557            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_millis(10));
3558        let s2: ProcessSubscription<TestMsg> =
3559            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_millis(20));
3560        assert_ne!(s1.id(), s2.id());
3561    }
3562
3563    #[test]
3564    fn explicit_id_remains_stable_after_builder_changes() {
3565        let s: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc)
3566            .with_id(42)
3567            .arg("hello")
3568            .env("FTUI_TEST_VAR", "value")
3569            .timeout(Duration::from_millis(10));
3570        assert_eq!(s.id(), 42);
3571    }
3572
3573    #[test]
3574    fn echo_captures_stdout() {
3575        let sub = ProcessSubscription::new("echo", TestMsg::Proc).arg("hello world");
3576        let (tx, rx) = stdmpsc::sync_channel(256);
3577        let (signal, trigger) = StopSignal::new();
3578
3579        let handle = thread::spawn(move || {
3580            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3581        });
3582
3583        // Wait for process to complete
3584        thread::sleep(Duration::from_millis(500));
3585        trigger.stop();
3586        handle.join().unwrap();
3587
3588        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3589        let has_stdout = msgs.iter().any(|m| match m {
3590            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("hello world"),
3591            _ => false,
3592        });
3593        assert!(
3594            has_stdout,
3595            "Expected stdout with 'hello world', got: {msgs:?}"
3596        );
3597
3598        let has_exit = msgs
3599            .iter()
3600            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Exited(0))));
3601        assert!(has_exit, "Expected Exited(0), got: {msgs:?}");
3602    }
3603
3604    #[test]
3605    fn nonexistent_program_sends_error() {
3606        let sub =
3607            ProcessSubscription::new("/nonexistent/program/that/should/not/exist", TestMsg::Proc);
3608        let (tx, rx) = stdmpsc::sync_channel(256);
3609        let (signal, _trigger) = StopSignal::new();
3610
3611        let handle = thread::spawn(move || {
3612            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3613        });
3614
3615        handle.join().unwrap();
3616        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3617        let has_error = msgs
3618            .iter()
3619            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Error(_))));
3620        assert!(has_error, "Expected Error event, got: {msgs:?}");
3621    }
3622
3623    #[test]
3624    fn stop_signal_kills_long_running_process() {
3625        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
3626        let (tx, rx) = stdmpsc::sync_channel(256);
3627        let (signal, trigger) = StopSignal::new();
3628        let start = web_time::Instant::now();
3629
3630        let handle = thread::spawn(move || {
3631            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3632        });
3633
3634        // Give it a moment to start, then stop
3635        thread::sleep(Duration::from_millis(100));
3636        trigger.stop();
3637        handle.join().unwrap();
3638        assert!(
3639            start.elapsed() < Duration::from_secs(2),
3640            "stop should kill a quiet process promptly"
3641        );
3642
3643        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3644        let has_killed = msgs
3645            .iter()
3646            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed)));
3647        assert!(has_killed, "Expected Killed event, got: {msgs:?}");
3648    }
3649
3650    #[test]
3651    fn timeout_kills_process() {
3652        let sub = ProcessSubscription::new("sleep", TestMsg::Proc)
3653            .arg("60")
3654            .timeout(Duration::from_millis(100));
3655        let (tx, rx) = stdmpsc::sync_channel(256);
3656        let (signal, _trigger) = StopSignal::new();
3657        let start = web_time::Instant::now();
3658
3659        let handle = thread::spawn(move || {
3660            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3661        });
3662
3663        handle.join().unwrap();
3664        assert!(
3665            start.elapsed() < Duration::from_secs(2),
3666            "timeout should kill a quiet process promptly"
3667        );
3668        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3669        let has_killed = msgs
3670            .iter()
3671            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed)));
3672        assert!(has_killed, "Expected Killed on timeout, got: {msgs:?}");
3673    }
3674
3675    #[test]
3676    fn env_vars_are_passed() {
3677        let sub =
3678            ProcessSubscription::new("env", TestMsg::Proc).env("FTUI_TEST_VAR", "test_value_42");
3679        let (tx, rx) = stdmpsc::sync_channel(256);
3680        let (signal, trigger) = StopSignal::new();
3681
3682        let handle = thread::spawn(move || {
3683            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3684        });
3685
3686        thread::sleep(Duration::from_millis(500));
3687        trigger.stop();
3688        handle.join().unwrap();
3689
3690        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3691        let has_var = msgs.iter().any(|m| match m {
3692            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("FTUI_TEST_VAR=test_value_42"),
3693            _ => false,
3694        });
3695        assert!(has_var, "Expected env var in output, got: {msgs:?}");
3696    }
3697
3698    #[test]
3699    fn multiple_args_via_args_method() {
3700        let sub = ProcessSubscription::new("echo", TestMsg::Proc).args(["hello", "world"]);
3701        let (tx, rx) = stdmpsc::sync_channel(256);
3702        let (signal, trigger) = StopSignal::new();
3703
3704        let handle = thread::spawn(move || {
3705            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3706        });
3707
3708        thread::sleep(Duration::from_millis(500));
3709        trigger.stop();
3710        handle.join().unwrap();
3711
3712        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3713        let has_output = msgs.iter().any(|m| match m {
3714            TestMsg::Proc(ProcessEvent::Stdout(s)) => s.contains("hello world"),
3715            _ => false,
3716        });
3717        assert!(has_output, "Expected combined output, got: {msgs:?}");
3718    }
3719
3720    #[test]
3721    fn stderr_captured() {
3722        // Use sh -c to write to stderr
3723        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
3724            .arg("-c")
3725            .arg("echo error_msg >&2");
3726        let (tx, rx) = stdmpsc::sync_channel(256);
3727        let (signal, trigger) = StopSignal::new();
3728
3729        let handle = thread::spawn(move || {
3730            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3731        });
3732
3733        thread::sleep(Duration::from_millis(500));
3734        trigger.stop();
3735        handle.join().unwrap();
3736
3737        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3738        let has_stderr = msgs.iter().any(|m| match m {
3739            TestMsg::Proc(ProcessEvent::Stderr(s)) => s.contains("error_msg"),
3740            _ => false,
3741        });
3742        assert!(has_stderr, "Expected stderr output, got: {msgs:?}");
3743    }
3744
3745    #[test]
3746    fn exit_code_captured() {
3747        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
3748            .arg("-c")
3749            .arg("exit 42");
3750        let (tx, rx) = stdmpsc::sync_channel(256);
3751        let (signal, trigger) = StopSignal::new();
3752
3753        let handle = thread::spawn(move || {
3754            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3755        });
3756
3757        thread::sleep(Duration::from_millis(500));
3758        trigger.stop();
3759        handle.join().unwrap();
3760
3761        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3762        let has_exit = msgs
3763            .iter()
3764            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Exited(42))));
3765        assert!(has_exit, "Expected Exited(42), got: {msgs:?}");
3766    }
3767
3768    #[cfg(unix)]
3769    #[test]
3770    fn signal_exit_is_preserved() {
3771        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
3772            .arg("-c")
3773            .arg("kill -TERM $$");
3774        let (tx, rx) = stdmpsc::sync_channel(256);
3775        let (signal, trigger) = StopSignal::new();
3776
3777        let handle = thread::spawn(move || {
3778            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3779        });
3780
3781        thread::sleep(Duration::from_millis(500));
3782        trigger.stop();
3783        handle.join().unwrap();
3784
3785        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3786        let has_signal = msgs
3787            .iter()
3788            .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Signaled(15))));
3789        assert!(has_signal, "Expected Signaled(15), got: {msgs:?}");
3790    }
3791
3792    // =========================================================================
3793    // PROCESS LIFECYCLE CONTRACT TESTS (bd-3s3yw)
3794    //
3795    // These tests capture the observable process supervision contract that
3796    // the Asupersync migration must preserve.
3797    // =========================================================================
3798
3799    /// CONTRACT: Process subscription uses CancellationToken internally for
3800    /// stop coordination (via StopSignal::cancellation_token()).
3801    #[test]
3802    fn contract_uses_cancellation_token_for_stop() {
3803        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
3804        let (tx, rx) = stdmpsc::sync_channel(256);
3805        let (signal, trigger) = StopSignal::new();
3806
3807        // Verify the cancellation token is accessible
3808        let token = signal.cancellation_token().clone();
3809        assert!(!token.is_cancelled());
3810
3811        let handle = thread::spawn(move || {
3812            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3813        });
3814
3815        thread::sleep(Duration::from_millis(100));
3816
3817        // Stopping via trigger should cancel the token
3818        trigger.stop();
3819        assert!(token.is_cancelled());
3820
3821        handle.join().unwrap();
3822
3823        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3824        assert!(
3825            msgs.iter()
3826                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
3827            "process must be killed on cancellation, got: {msgs:?}"
3828        );
3829    }
3830
3831    /// CONTRACT: Final event is always sent, even on error paths.
3832    /// The subscription must always emit exactly one terminal event
3833    /// (Exited, Signaled, Killed, or Error).
3834    #[test]
3835    fn contract_always_emits_terminal_event() {
3836        // Happy path: process exits normally
3837        {
3838            let sub = ProcessSubscription::new("true", TestMsg::Proc);
3839            let (tx, rx) = stdmpsc::sync_channel(256);
3840            let (signal, trigger) = StopSignal::new();
3841
3842            let handle = thread::spawn(move || {
3843                sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3844            });
3845
3846            thread::sleep(Duration::from_millis(500));
3847            trigger.stop();
3848            handle.join().unwrap();
3849
3850            let msgs: Vec<TestMsg> = rx.try_iter().collect();
3851            let terminal_events: Vec<_> = msgs
3852                .iter()
3853                .filter(|m| {
3854                    matches!(
3855                        m,
3856                        TestMsg::Proc(
3857                            ProcessEvent::Exited(_)
3858                                | ProcessEvent::Signaled(_)
3859                                | ProcessEvent::Killed
3860                                | ProcessEvent::Error(_)
3861                        )
3862                    )
3863                })
3864                .collect();
3865            assert_eq!(
3866                terminal_events.len(),
3867                1,
3868                "must emit exactly one terminal event, got: {terminal_events:?}"
3869            );
3870        }
3871
3872        // Error path: nonexistent program
3873        {
3874            let sub = ProcessSubscription::new(
3875                "/nonexistent/program/that/should/not/exist",
3876                TestMsg::Proc,
3877            );
3878            let (tx, rx) = stdmpsc::sync_channel(256);
3879            let (signal, _trigger) = StopSignal::new();
3880
3881            let handle = thread::spawn(move || {
3882                sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3883            });
3884
3885            handle.join().unwrap();
3886
3887            let msgs: Vec<TestMsg> = rx.try_iter().collect();
3888            let terminal_events: Vec<_> = msgs
3889                .iter()
3890                .filter(|m| {
3891                    matches!(
3892                        m,
3893                        TestMsg::Proc(
3894                            ProcessEvent::Exited(_)
3895                                | ProcessEvent::Signaled(_)
3896                                | ProcessEvent::Killed
3897                                | ProcessEvent::Error(_)
3898                        )
3899                    )
3900                })
3901                .collect();
3902            assert_eq!(
3903                terminal_events.len(),
3904                1,
3905                "must emit exactly one terminal event on error, got: {terminal_events:?}"
3906            );
3907        }
3908    }
3909
3910    /// CONTRACT: stdout and stderr lines arrive before the terminal event.
3911    /// The output forwarding threads must join before the final event is sent.
3912    #[test]
3913    fn contract_output_precedes_terminal_event() {
3914        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
3915            .arg("-c")
3916            .arg("echo FIRST && echo SECOND >&2 && exit 0");
3917        let (tx, rx) = stdmpsc::sync_channel(256);
3918        let (signal, trigger) = StopSignal::new();
3919
3920        let handle = thread::spawn(move || {
3921            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
3922        });
3923
3924        thread::sleep(Duration::from_millis(500));
3925        trigger.stop();
3926        handle.join().unwrap();
3927
3928        let msgs: Vec<TestMsg> = rx.try_iter().collect();
3929
3930        assert_eq!(
3931            msgs.len(),
3932            3,
3933            "both output lines and one terminal event: {msgs:?}"
3934        );
3935        assert!(msgs.contains(&TestMsg::Proc(ProcessEvent::Stdout("FIRST".to_owned()))));
3936        assert!(msgs.contains(&TestMsg::Proc(ProcessEvent::Stderr("SECOND".to_owned()))));
3937        assert_eq!(msgs.last(), Some(&TestMsg::Proc(ProcessEvent::Exited(0))));
3938
3939        // Find the position of the terminal event
3940        let terminal_pos = msgs
3941            .iter()
3942            .position(|m| {
3943                matches!(
3944                    m,
3945                    TestMsg::Proc(
3946                        ProcessEvent::Exited(_)
3947                            | ProcessEvent::Signaled(_)
3948                            | ProcessEvent::Killed
3949                            | ProcessEvent::Error(_)
3950                    )
3951                )
3952            })
3953            .expect("process must report its terminal event");
3954
3955        // Find positions of stdout/stderr events
3956        let output_positions: Vec<usize> = msgs
3957            .iter()
3958            .enumerate()
3959            .filter_map(|(i, m)| match m {
3960                TestMsg::Proc(ProcessEvent::Stdout(_) | ProcessEvent::Stderr(_)) => Some(i),
3961                _ => None,
3962            })
3963            .collect();
3964
3965        for &out_pos in &output_positions {
3966            assert!(
3967                out_pos < terminal_pos,
3968                "output event at position {out_pos} must precede terminal event at {terminal_pos}"
3969            );
3970        }
3971    }
3972
3973    #[test]
3974    fn real_process_flood_backpressures_and_drains_in_order() {
3975        use crate::subscription::SubscriptionManager;
3976
3977        let (progress_tx, progress_rx) = stdmpsc::channel();
3978        let sub = ProcessSubscription::new("sh", move |event| {
3979            if let ProcessEvent::Stdout(line) = &event
3980                && matches!(line.as_str(), "256" | "257")
3981            {
3982                progress_tx
3983                    .send(line.clone())
3984                    .expect("observe actual child output");
3985            }
3986            TestMsg::Proc(event)
3987        })
3988        .args([
3989            "-c",
3990            "i=0; while [ \"$i\" -lt 1024 ]; do printf '%s\\n' \"$i\"; i=$((i+1)); done",
3991        ]);
3992        let mut manager = SubscriptionManager::new();
3993        manager.reconcile(vec![Box::new(sub)]);
3994
3995        // The conversion callback observes the real 257th line before its
3996        // send. With no manager drain, that send must wait on the full queue.
3997        assert_eq!(
3998            progress_rx
3999                .recv_timeout(Duration::from_secs(5))
4000                .expect("child reached capacity"),
4001            "256"
4002        );
4003        // Hold backpressure longer than the old reader join timeout.
4004        assert_eq!(
4005            progress_rx.recv_timeout(PROCESS_READER_JOIN_TIMEOUT + Duration::from_millis(100)),
4006            Err(stdmpsc::RecvTimeoutError::Timeout),
4007            "the reader must not reach line 257 while 256 messages remain undrained"
4008        );
4009
4010        let mut received = manager.drain_messages();
4011        assert_eq!(
4012            received.len(),
4013            64,
4014            "one runtime turn has a fixed batch budget"
4015        );
4016        assert_eq!(
4017            progress_rx
4018                .recv_timeout(Duration::from_secs(5))
4019                .expect("drain released backpressure"),
4020            "257"
4021        );
4022        let deadline = Instant::now() + Duration::from_secs(10);
4023        while !matches!(
4024            received.last(),
4025            Some(TestMsg::Proc(ProcessEvent::Exited(0)))
4026        ) {
4027            assert!(
4028                Instant::now() < deadline,
4029                "actual child output did not finish: {} messages",
4030                received.len()
4031            );
4032            let batch = manager.drain_messages();
4033            assert!(
4034                batch.len() <= 64,
4035                "every drain must preserve the runtime batch budget"
4036            );
4037            if batch.is_empty() {
4038                thread::sleep(Duration::from_millis(1));
4039            }
4040            received.extend(batch);
4041        }
4042        manager.stop_all();
4043        received.extend(manager.drain_messages());
4044        let mut expected: Vec<_> = (0..1024)
4045            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(index.to_string())))
4046            .collect();
4047        expected.push(TestMsg::Proc(ProcessEvent::Exited(0)));
4048        assert_eq!(
4049            received, expected,
4050            "all real child lines precede exactly one exit"
4051        );
4052        assert!(manager.drain_messages().is_empty());
4053    }
4054
4055    #[test]
4056    fn real_process_full_queue_stop_is_prompt() {
4057        use crate::subscription::SubscriptionManager;
4058
4059        let (capacity_tx, capacity_rx) = stdmpsc::channel();
4060        let (terminal_tx, terminal_rx) = stdmpsc::channel();
4061        let sub = ProcessSubscription::new("sh", move |event| {
4062            if matches!(&event, ProcessEvent::Stdout(line) if line == "256") {
4063                capacity_tx
4064                    .send(())
4065                    .expect("observe actual full-queue output");
4066            }
4067            if matches!(
4068                &event,
4069                ProcessEvent::Killed
4070                    | ProcessEvent::Exited(_)
4071                    | ProcessEvent::Signaled(_)
4072                    | ProcessEvent::Error(_)
4073            ) {
4074                terminal_tx
4075                    .send(event.clone())
4076                    .expect("observe actual child termination");
4077            }
4078            TestMsg::Proc(event)
4079        })
4080        .args([
4081            "-c",
4082            "i=0; while [ \"$i\" -lt 1024 ]; do printf '%s\\n' \"$i\"; i=$((i+1)); done; exec sleep 60",
4083        ]);
4084        let mut manager = SubscriptionManager::new();
4085        manager.reconcile(vec![Box::new(sub)]);
4086        capacity_rx
4087            .recv_timeout(Duration::from_secs(5))
4088            .expect("child reached capacity");
4089
4090        let stop_start = Instant::now();
4091        manager.stop_all();
4092        assert!(
4093            stop_start.elapsed() < Duration::from_secs(2),
4094            "full output queue must not block subscription stop"
4095        );
4096        assert_eq!(
4097            terminal_rx
4098                .recv_timeout(Duration::from_secs(2))
4099                .expect("supervisor reported termination"),
4100            ProcessEvent::Killed
4101        );
4102        assert_eq!(
4103            terminal_rx.recv_timeout(Duration::from_secs(2)),
4104            Err(stdmpsc::RecvTimeoutError::Disconnected),
4105            "the supervisor and reader callbacks must finish before draining"
4106        );
4107
4108        // Cancellation may reject the final status on a full data queue. The
4109        // callback above observes supervision; only these 256 lines were sent.
4110        let mut received = Vec::new();
4111        loop {
4112            let batch = manager.drain_messages();
4113            assert!(batch.len() <= 64);
4114            if batch.is_empty() {
4115                break;
4116            }
4117            received.extend(batch);
4118        }
4119        let expected: Vec<_> = (0..256)
4120            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(index.to_string())))
4121            .collect();
4122        assert_eq!(
4123            received, expected,
4124            "already accepted output remains in FIFO order"
4125        );
4126    }
4127
4128    #[test]
4129    #[cfg(target_os = "linux")]
4130    fn real_process_cancel_kills_blocked_writer_before_closing_pipe() {
4131        assert_blocked_writer_is_killed(false);
4132    }
4133
4134    #[test]
4135    #[cfg(target_os = "linux")]
4136    fn real_process_timeout_kills_blocked_writer_before_closing_pipe() {
4137        assert_blocked_writer_is_killed(true);
4138    }
4139
4140    #[cfg(target_os = "linux")]
4141    fn assert_blocked_writer_is_killed(timeout: bool) {
4142        let (tx, rx) = stdmpsc::sync_channel(256);
4143        let expected: Vec<_> = (0..256)
4144            .map(|index| ProcessEvent::Stdout(format!("accepted-{index}")))
4145            .collect();
4146        for event in &expected {
4147            tx.send(event.clone()).expect("fill application queue");
4148        }
4149        let (observed_tx, observed_rx) = stdmpsc::channel();
4150        let (done_tx, done_rx) = stdmpsc::channel();
4151        // Restore SIGPIPE's default action so premature reader closure has an
4152        // observable terminal status. The child stays inside an actual blocking
4153        // pipe write while the reader waits for model queue capacity.
4154        let script = "import os,signal\nsignal.alarm(15)\nsignal.signal(signal.SIGPIPE,signal.SIG_DFL)\nprint(os.getpid(),flush=True)\nwhile True: os.write(1,b'x'*65536)";
4155        let mut sub = ProcessSubscription::new("python3", move |event| {
4156            observed_tx
4157                .send(event.clone())
4158                .expect("observe process callback before model backpressure");
4159            event
4160        })
4161        .args(["-u", "-c", script]);
4162        if timeout {
4163            sub = sub.timeout(Duration::from_secs(3));
4164        }
4165        let (signal, trigger) = StopSignal::new();
4166        let handle = thread::spawn(move || {
4167            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4168            done_tx.send(()).expect("observe supervisor completion");
4169        });
4170        let first = observed_rx.recv_timeout(Duration::from_secs(5));
4171        let pid = match &first {
4172            Ok(ProcessEvent::Stdout(line)) => line.parse::<u32>().ok(),
4173            _ => None,
4174        };
4175        let Some(pid) = pid else {
4176            trigger.stop();
4177            handle.join().expect("stop child without PID");
4178            panic!("expected actual blocked writer PID, got {first:?}");
4179        };
4180        let deadline = Instant::now() + Duration::from_secs(2);
4181        loop {
4182            let wait = std::fs::read_to_string(format!("/proc/{pid}/wchan")).unwrap_or_default();
4183            if wait.contains("pipe_write") {
4184                break;
4185            }
4186            if Instant::now() >= deadline {
4187                trigger.stop();
4188                handle
4189                    .join()
4190                    .expect("stop child that did not block writing");
4191                panic!("child never entered a blocking pipe write: {wait:?}");
4192            }
4193            thread::sleep(Duration::from_millis(5));
4194        }
4195        if !timeout {
4196            trigger.stop();
4197        }
4198        let done = done_rx.recv_timeout(Duration::from_secs(5));
4199        // Cleanup precedes assertions even when termination failed. No model
4200        // queue slot is released until both the child and workers have stopped.
4201        trigger.stop();
4202        handle.join().expect("join blocked writer supervisor");
4203        assert!(done.is_ok(), "full queue blocked termination: {done:?}");
4204        assert_eq!(
4205            observed_rx.try_iter().collect::<Vec<_>>(),
4206            [ProcessEvent::Killed],
4207            "cancel and timeout must reap SIGKILL, not induce SIGPIPE or EOF"
4208        );
4209        assert!(
4210            std::fs::metadata(format!("/proc/{pid}"))
4211                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound),
4212            "the immediate child must already be reaped"
4213        );
4214        assert_eq!(
4215            rx.try_iter().collect::<Vec<_>>(),
4216            expected,
4217            "the entire previously accepted prefix survives without a drain"
4218        );
4219    }
4220
4221    #[test]
4222    fn real_process_exit_drain_timeout_cannot_block_on_final_status() {
4223        let (tx, rx) = stdmpsc::sync_channel(256);
4224        let expected: Vec<_> = (0..256)
4225            .map(|index| TestMsg::Proc(ProcessEvent::Stdout(format!("queued-{index}"))))
4226            .collect();
4227        // Control the queue state independently of the real child's one-line
4228        // output so this exercises timeout after exit, not a sleeping child.
4229        for message in &expected {
4230            tx.send(message.clone()).expect("fill model queue");
4231        }
4232        let (observed_tx, observed_rx) = stdmpsc::channel();
4233        let (done_tx, done_rx) = stdmpsc::channel();
4234        let sub = ProcessSubscription::new("sh", move |event| {
4235            observed_tx
4236                .send(event.clone())
4237                .expect("observe actual process callbacks");
4238            TestMsg::Proc(event)
4239        })
4240        .args(["-c", "printf 'tail\\n'; exit 42"])
4241        .timeout(Duration::from_millis(500));
4242        let (signal, _trigger) = StopSignal::new();
4243        let handle = thread::spawn(move || {
4244            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4245            done_tx.send(()).expect("report completed supervision");
4246        });
4247
4248        assert_eq!(
4249            observed_rx
4250                .recv_timeout(Duration::from_secs(5))
4251                .expect("real child output"),
4252            ProcessEvent::Stdout("tail".to_owned())
4253        );
4254        assert_eq!(
4255            observed_rx
4256                .recv_timeout(Duration::from_secs(5))
4257                .expect("interrupted output drain"),
4258            ProcessEvent::Error(
4259                "output drain timed out after Exited(42); stdout/stderr output is incomplete"
4260                    .to_owned()
4261            )
4262        );
4263        done_rx
4264            .recv_timeout(Duration::from_secs(2))
4265            .expect("a full final-status send must honor the timeout");
4266        handle.join().expect("supervisor thread");
4267        assert_eq!(
4268            observed_rx.recv_timeout(Duration::from_secs(2)),
4269            Err(stdmpsc::RecvTimeoutError::Disconnected)
4270        );
4271        assert_eq!(
4272            rx.try_iter().collect::<Vec<_>>(),
4273            expected,
4274            "timeout preserves accepted messages and rejects the unsent tail/status"
4275        );
4276    }
4277
4278    /// CONTRACT: ProcessSubscription ID includes timeout in the hash.
4279    /// Changing timeout creates a different subscription identity.
4280    #[test]
4281    fn contract_id_includes_timeout() {
4282        let s1: ProcessSubscription<TestMsg> =
4283            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_secs(5));
4284        let s2: ProcessSubscription<TestMsg> =
4285            ProcessSubscription::new("echo", TestMsg::Proc).timeout(Duration::from_secs(10));
4286        let s3: ProcessSubscription<TestMsg> = ProcessSubscription::new("echo", TestMsg::Proc);
4287
4288        assert_ne!(
4289            s1.id(),
4290            s2.id(),
4291            "different timeouts must produce different IDs"
4292        );
4293        assert_ne!(
4294            s1.id(),
4295            s3.id(),
4296            "timeout vs no-timeout must produce different IDs"
4297        );
4298    }
4299
4300    /// CONTRACT: Kill is prompt — process is killed within poll_interval (50ms)
4301    /// of the stop signal, not blocked waiting for process output.
4302    #[test]
4303    fn contract_kill_is_prompt() {
4304        let sub = ProcessSubscription::new("sleep", TestMsg::Proc).arg("60");
4305        let (tx, rx) = stdmpsc::sync_channel(256);
4306        let (signal, trigger) = StopSignal::new();
4307
4308        let handle = thread::spawn(move || {
4309            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4310        });
4311
4312        thread::sleep(Duration::from_millis(100));
4313
4314        let kill_start = web_time::Instant::now();
4315        trigger.stop();
4316        handle.join().unwrap();
4317        let kill_elapsed = kill_start.elapsed();
4318
4319        // The child sleeps 60 s; a prompt kill returns in about one poll
4320        // interval (50 ms). The 5 s bound is a hang guard with room for a
4321        // loaded runner, and it still fails when the kill waited for the
4322        // child (G04.2).
4323        assert!(
4324            kill_elapsed < Duration::from_secs(5),
4325            "kill must complete promptly after the stop signal, took {kill_elapsed:?}"
4326        );
4327
4328        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4329        assert!(
4330            msgs.iter()
4331                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
4332            "must emit Killed event"
4333        );
4334    }
4335
4336    #[test]
4337    #[cfg(target_os = "linux")]
4338    fn real_descendant_output_pipes_close_after_leader_exit_before_fixture_release() {
4339        use rustix::process::{Pid, WaitOptions, set_child_subreaper, waitpid};
4340        use std::net::TcpListener;
4341        use std::path::PathBuf;
4342
4343        const CHILD_ENV: &str = "FTUI_DESCENDANT_PIPE_ISOLATED_TEST";
4344        const TEST_NAME: &str = concat!(
4345            "process_subscription::tests::",
4346            "real_descendant_output_pipes_close_after_leader_exit_before_fixture_release"
4347        );
4348        let isolated_parent = std::env::var(CHILD_ENV)
4349            .ok()
4350            .and_then(|value| value.parse::<i32>().ok());
4351        let isolated_run = isolated_parent.is_some()
4352            && isolated_parent == rustix::process::getppid().map(|pid| pid.as_raw_nonzero().get())
4353            && std::env::args().skip(1).eq([
4354                "--exact",
4355                TEST_NAME,
4356                "--nocapture",
4357                "--test-threads=1",
4358            ]);
4359        if !isolated_run {
4360            // Subreaper state belongs only to this exact-test subprocess. The
4361            // ordinary test runner must not adopt or reap unrelated children.
4362            let mut isolated = Command::new(std::env::current_exe().unwrap())
4363                .args(["--exact", TEST_NAME, "--nocapture", "--test-threads=1"])
4364                .env(CHILD_ENV, std::process::id().to_string())
4365                .stdout(Stdio::piped())
4366                .stderr(Stdio::inherit())
4367                .spawn()
4368                .expect("spawn isolated descendant test");
4369            let deadline = Instant::now() + Duration::from_secs(30);
4370            loop {
4371                if let Some(status) = isolated.try_wait().unwrap() {
4372                    let mut report = String::new();
4373                    isolated
4374                        .stdout
4375                        .take()
4376                        .unwrap()
4377                        .read_to_string(&mut report)
4378                        .unwrap();
4379                    print!("{report}");
4380                    assert!(
4381                        status.success(),
4382                        "isolated descendant test failed: {status}"
4383                    );
4384                    assert!(
4385                        report.contains(&format!("test {TEST_NAME} ... ok"))
4386                            && report.contains("1 passed; 0 failed"),
4387                        "the exact isolated test must execute, not pass with zero selected tests"
4388                    );
4389                    return;
4390                }
4391                if Instant::now() >= deadline {
4392                    isolated.kill().expect("stop timed-out isolated test");
4393                    isolated.wait().expect("reap isolated test");
4394                    panic!("isolated descendant test exceeded its safety deadline");
4395                }
4396                thread::sleep(Duration::from_millis(10));
4397            }
4398        }
4399        // rustix 1.1.3 represents this boolean prctl argument as Option<Pid>.
4400        set_child_subreaper(Pid::from_raw(1)).expect("enable isolated fixture adoption");
4401        let baseline_tasks: Vec<_> = std::fs::read_dir("/proc/self/task")
4402            .unwrap()
4403            .map(|entry| entry.unwrap().path())
4404            .collect();
4405        let await_output_workers = || {
4406            let deadline = Instant::now() + Duration::from_secs(3);
4407            loop {
4408                let mut workers = Vec::new();
4409                for entry in std::fs::read_dir("/proc/self/task").unwrap() {
4410                    let task = entry.unwrap().path();
4411                    if baseline_tasks.contains(&task) {
4412                        continue;
4413                    }
4414                    let state = match std::fs::read_to_string(task.join("wchan")) {
4415                        Ok(state) => state,
4416                        Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
4417                        Err(error) => panic!("cannot inspect actual worker wait: {error}"),
4418                    };
4419                    if state.contains("poll") || state.contains("pipe_read") {
4420                        workers.push(task);
4421                    }
4422                }
4423                if workers.len() == 2 {
4424                    return workers;
4425                }
4426                assert!(
4427                    Instant::now() < deadline,
4428                    "expected two actual output pipe waits, found {workers:?}"
4429                );
4430                thread::sleep(Duration::from_millis(5));
4431            }
4432        };
4433        let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
4434        listener.set_nonblocking(true).unwrap();
4435        let script = r#"import os,signal,socket,sys
4436signal.alarm(15)
4437gate_read,gate_write=os.pipe()
4438leader=os.getpid()
4439descendant=os.fork()
4440if descendant:
4441 os.close(gate_write)
4442 assert os.read(gate_read,1)==b'X'
4443 os._exit(42)
4444os.close(gate_read)
4445signal.alarm(15)
4446sock=socket.create_connection(('127.0.0.1',int(sys.argv[1])),timeout=5)
4447sock.sendall((str(leader)+' '+str(os.getpid())+' '+os.readlink('/proc/self/fd/1')+' '+os.readlink('/proc/self/fd/2')+'\n').encode())
4448assert sock.recv(1)==b'B'
4449sock.sendall(('BLOCKING '+str(os.get_blocking(1))+' '+str(os.get_blocking(2))+'\n').encode())
4450os.write(1,b'accepted-out\nheld-out')
4451os.write(2,b'accepted-err\nheld-err')
4452assert sock.recv(1)==b'X'
4453os.write(gate_write,b'X')
4454os.close(gate_write)
4455assert sock.recv(1)==b'R'
4456closed=[]
4457for fd in (1,2):
4458 try:
4459  os.write(fd,b'probe')
4460  closed.append(False)
4461 except BrokenPipeError:
4462  closed.append(True)
4463sock.sendall(('CLOSED '+str(closed[0])+' '+str(closed[1])+'\n').encode())
4464assert sock.recv(1)==b'F'
4465os._exit(7)
4466"#;
4467        let control = ProcessControl::new();
4468        let sub = ProcessSubscription::new("python3", TestMsg::Proc)
4469            .args(["-u", "-c", script])
4470            .arg(listener.local_addr().unwrap().port().to_string())
4471            .control(control.clone());
4472        let (sender, receiver) = stdmpsc::sync_channel(256);
4473        let (stop, trigger) = StopSignal::new();
4474        let supervisor = thread::spawn(move || {
4475            sub.run(SubscriptionSender::new(sender, stop.clone()), stop);
4476        });
4477        let deadline = Instant::now() + Duration::from_secs(3);
4478        let socket = loop {
4479            match listener.accept() {
4480                Ok((socket, _)) => break socket,
4481                Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
4482                    assert!(Instant::now() < deadline, "descendant did not connect");
4483                    thread::sleep(Duration::from_millis(5));
4484                }
4485                Err(error) => panic!("descendant connection failed: {error}"),
4486            }
4487        };
4488        socket
4489            .set_read_timeout(Some(Duration::from_secs(3)))
4490            .unwrap();
4491        socket
4492            .set_write_timeout(Some(Duration::from_secs(3)))
4493            .unwrap();
4494        let mut socket = io::BufReader::new(socket);
4495        let mut hello = String::new();
4496        socket.read_line(&mut hello).unwrap();
4497        let fields: Vec<_> = hello.split_whitespace().collect();
4498        assert_eq!(fields.len(), 4, "actual descendant identities and pipe IDs");
4499        let leader: u32 = fields[0].parse().unwrap();
4500        let descendant = Pid::from_raw(fields[1].parse().unwrap()).unwrap();
4501        let pipe_ids = [PathBuf::from(fields[2]), PathBuf::from(fields[3])];
4502        assert_ne!(pipe_ids[0], pipe_ids[1]);
4503        assert!(fields[2..].iter().all(|pipe| pipe.starts_with("pipe:[")));
4504        // A real read/readiness wait means both adapters have been configured.
4505        // Only then ask the descendant to inspect its own endpoint flags.
4506        await_output_workers();
4507        socket.get_mut().write_all(b"B").unwrap();
4508        let mut flags = String::new();
4509        socket.read_line(&mut flags).unwrap();
4510        assert_eq!(flags, "BLOCKING True True\n");
4511        let mut accepted = [
4512            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
4513            receiver.recv_timeout(Duration::from_secs(3)).unwrap(),
4514        ];
4515        accepted.sort_by_key(|event| matches!(event, TestMsg::Proc(ProcessEvent::Stderr(_))));
4516        assert_eq!(
4517            accepted,
4518            [
4519                TestMsg::Proc(ProcessEvent::Stdout("accepted-out".to_owned())),
4520                TestMsg::Proc(ProcessEvent::Stderr("accepted-err".to_owned())),
4521            ]
4522        );
4523        let workers = await_output_workers();
4524        socket.get_mut().write_all(b"X").unwrap();
4525        let deadline = Instant::now() + Duration::from_secs(3);
4526        while !control.status().can_restart {
4527            assert!(Instant::now() < deadline, "leader was not reaped");
4528            thread::sleep(Duration::from_millis(5));
4529        }
4530        assert!(
4531            std::fs::metadata(format!("/proc/{leader}"))
4532                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
4533        );
4534        assert!(
4535            waitpid(Some(descendant), WaitOptions::NOHANG)
4536                .unwrap()
4537                .is_none()
4538        );
4539        assert!(workers.iter().all(|task| task.exists()));
4540        trigger.stop();
4541        let deadline = Instant::now() + Duration::from_secs(2);
4542        while !supervisor.is_finished() && Instant::now() < deadline {
4543            thread::sleep(Duration::from_millis(5));
4544        }
4545        let supervisor_finished = supervisor.is_finished();
4546        let workers_gone = workers.iter().all(|task| {
4547            std::fs::metadata(task).is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
4548        });
4549        let mut retained_pipes = Vec::new();
4550        for entry in std::fs::read_dir("/proc/self/fd").unwrap() {
4551            match std::fs::read_link(entry.unwrap().path()) {
4552                Ok(target) if pipe_ids.contains(&target) => retained_pipes.push(target),
4553                Ok(_) => {}
4554                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
4555                Err(error) => panic!("cannot inspect retained pipe endpoint: {error}"),
4556            }
4557        }
4558        let descendant_alive = waitpid(Some(descendant), WaitOptions::NOHANG)
4559            .unwrap()
4560            .is_none();
4561        // Capture worker/FD state before any fixture release or child cleanup.
4562        // R only probes the still-live descendant's endpoints; F permits exit.
4563        socket.get_mut().write_all(b"R").unwrap();
4564        let mut closed = String::new();
4565        socket.read_line(&mut closed).unwrap();
4566        let alive_after_probe = waitpid(Some(descendant), WaitOptions::NOHANG)
4567            .unwrap()
4568            .is_none();
4569        socket.get_mut().write_all(b"F").unwrap();
4570        let deadline = Instant::now() + Duration::from_secs(3);
4571        let status = loop {
4572            if let Some((pid, status)) = waitpid(Some(descendant), WaitOptions::NOHANG).unwrap() {
4573                assert_eq!(pid, descendant);
4574                break status;
4575            }
4576            assert!(Instant::now() < deadline, "adopted descendant did not exit");
4577            thread::sleep(Duration::from_millis(5));
4578        };
4579        supervisor.join().unwrap();
4580        assert!(
4581            supervisor_finished,
4582            "supervision depended on fixture release"
4583        );
4584        assert!(workers_gone, "output workers survived canceled pipe reads");
4585        assert!(
4586            retained_pipes.is_empty(),
4587            "retained endpoints: {retained_pipes:?}"
4588        );
4589        assert!(descendant_alive && alive_after_probe);
4590        assert_eq!(closed, "CLOSED True True\n");
4591        assert_eq!(status.exit_status(), Some(7));
4592        assert_eq!(
4593            waitpid(Some(descendant), WaitOptions::NOHANG).unwrap_err(),
4594            rustix::io::Errno::CHILD
4595        );
4596        assert!(
4597            std::fs::metadata(format!("/proc/{}", descendant.as_raw_nonzero()))
4598                .is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
4599        );
4600        assert_eq!(
4601            receiver.try_iter().collect::<Vec<_>>(),
4602            [TestMsg::Proc(ProcessEvent::Error(
4603                "output drain canceled after Exited(42); stdout/stderr output is incomplete"
4604                    .to_owned()
4605            ))],
4606            "accepted lines stay exact; pending prefixes must not become EOF lines"
4607        );
4608    }
4609
4610    #[test]
4611    fn stop_signal_does_not_block_when_background_descendant_keeps_pipes_open() {
4612        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4613            .arg("-c")
4614            .arg("sleep 60 & sleep 60");
4615        let (tx, rx) = stdmpsc::sync_channel(256);
4616        let (signal, trigger) = StopSignal::new();
4617        let start = web_time::Instant::now();
4618
4619        let handle = thread::spawn(move || {
4620            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4621        });
4622
4623        thread::sleep(Duration::from_millis(100));
4624        trigger.stop();
4625        handle.join().unwrap();
4626
4627        assert!(
4628            start.elapsed() < Duration::from_secs(2),
4629            "stop should not block behind inherited stdout/stderr pipes"
4630        );
4631
4632        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4633        assert!(
4634            msgs.iter()
4635                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
4636            "expected Killed event, got: {msgs:?}"
4637        );
4638    }
4639
4640    #[test]
4641    fn timeout_does_not_block_when_background_descendant_keeps_pipes_open() {
4642        let sub = ProcessSubscription::new("sh", TestMsg::Proc)
4643            .arg("-c")
4644            .arg("sleep 60 & sleep 60")
4645            .timeout(Duration::from_millis(100));
4646        let (tx, rx) = stdmpsc::sync_channel(256);
4647        let (signal, _trigger) = StopSignal::new();
4648        let start = web_time::Instant::now();
4649
4650        let handle = thread::spawn(move || {
4651            sub.run(SubscriptionSender::new(tx, signal.clone()), signal);
4652        });
4653
4654        handle.join().unwrap();
4655
4656        assert!(
4657            start.elapsed() < Duration::from_secs(2),
4658            "timeout should not block behind inherited stdout/stderr pipes"
4659        );
4660
4661        let msgs: Vec<TestMsg> = rx.try_iter().collect();
4662        assert!(
4663            msgs.iter()
4664                .any(|m| matches!(m, TestMsg::Proc(ProcessEvent::Killed))),
4665            "expected Killed event, got: {msgs:?}"
4666        );
4667    }
4668}