From a10d7c5da5d72db71ad2746872aa0242cf340bf0 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:05:20 -0500 Subject: [PATCH 1/6] perf: scan the process table once per tick, not once per pane Linux: every pane's reader read /proc//stat of every process in the PID namespace about 2.5 times a second (8 panes, 275 processes: 18% of a core on an Intel N100). Two changes, finding the same members: 1. A cheaper scan. Each stat is read into a reused buffer and parsed in place (bytes, no String, no Vec of fields); the children and the group/session indexes are built once per snapshot instead of filtering the whole map per call. 2. One snapshot per tick. A holder-wide procs::Shared hands every pane's periodic look the same scan if it began less than 250 ms ago and not before the pane was spawned. The stop paths (soft_stop, await_tree_gone, release) still take their own fresh Tree::refresh, and signals still re-read the pid's start time. Lock order: a pane's tree, then Shared's lock, which is a leaf. macOS keeps its per-question kernel calls (Shared is a no-op there). One difference in what is found: a process whose command name is not valid UTF-8 was invisible to the old read_to_string-based parser (so it was never in a tree and never signalled); the byte parser sees it. Docs: operations.md says the periodic look may use a 250 ms old read. Verified (Linux x86_64 build host, no cargo on the laptop): - cargo fmt --check, clippy --all-targets -D warnings: clean. - cargo test, whole suite, 2 runs at the final tree: 981 lib + all integration tests pass, 0 failed (3 more runs before the last test-only fixture fix, same). No existing assertion was edited. - New tests: parser on a comm with spaces/parentheses, 100 KB comm, non UTF-8 comm, zombie, cut lines, a real zombie and a pid that vanished between readdir and read; fixture tree finds exactly its 4 members via refresh and refresh_shared; age limit and not_before; 8 trees share one scan; 8 panes cost <= 14 scans in 1.5 s; stop kills a child the shared snapshot missed. - Equivalence: while the old text parser and BFS were kept as a test oracle, the new snapshot matched it (start, children, peers on the fixture, start of every common process, same member set); the oracle is deleted in this commit and the fixture tests assert explicit members. - Mutation check: soft_stop/await_tree_gone/release switched to refresh_shared makes a_stop_scans_afresh_and_ends_a_child_the_shared_ snapshot_missed fail ("outlived kill: the stop used a stale snapshot"); reverted. - 50 runs of the process, stop and contract tests with 4 busy loops: 50/50. - Idle holder, 8 panes, 300 s, ps %cpu: base 15.2 (18.05 earlier run), new 1.8. Front restart, 8 full panes, 6 runs each: wall to quiet 0.55-0.74 s new, 0.51-0.68 s base (not changed; neither reproduces the 3.1-3.9 s of the report). - macOS not built here (data volume has under 5 GiB free): hosted CI. --- docs/operations.md | 4 +- src/native/host/local.rs | 31 +- src/native/host/mod.rs | 2 + src/native/host/procs.rs | 621 ++++++++++++++++++++++++++++++++-- src/native/host/tests_scan.rs | 78 +++++ 5 files changed, 699 insertions(+), 37 deletions(-) create mode 100644 src/native/host/tests_scan.rs diff --git a/docs/operations.md b/docs/operations.md index 4e5fdef..9aab297 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -803,7 +803,9 @@ Pane ids are `n:` child, by pid and start time: by parent pid every 250 ms while the child runs and again before any stop, and by membership of the child's group and session. So a descendant that moves to its own group or session, or whose parent exits, is - still known. Removing a pane (`remove_pane`) and Shepherd's exit on SIGINT, + still known. On Linux the periodic look reads the process table once for all + panes, and a pane may use a read up to 250 ms old (so a descendant is seen + within about 500 ms, not 250 ms); a stop always reads it afresh. Removing a pane (`remove_pane`) and Shepherd's exit on SIGINT, SIGTERM or SIGHUP send SIGHUP and SIGTERM to the group and the descendants, wait up to 2 s (for `remove_pane`, its `timeout`), then stop (SIGSTOP) the group and descendants until no new one appears and SIGKILL them all. When the program exits diff --git a/src/native/host/local.rs b/src/native/host/local.rs index f21fa31..8ecd580 100644 --- a/src/native/host/local.rs +++ b/src/native/host/local.rs @@ -5,7 +5,9 @@ //! //! Locking: a pane's `tree` is taken before its `state`; nothing here holds a //! lock across a sleep, a poll or a wait, except the condvar waits, which -//! release `state`. The registry lock is held only to look a pane up or +//! release `state`. The shared process-table snapshot (`procs::Shared`) has a +//! lock of its own, taken under a pane's `tree` and never with anything else +//! held; only the readers' periodic look uses it, never a stop. The registry lock is held only to look a pane up or //! change the list, never across a call into the sink or a wait. use super::tail::TailRing; @@ -85,6 +87,8 @@ pub(crate) struct LocalHost { /// no memory and no copy per chunk. tail_cap: Option, finished_backstop: usize, + /// One snapshot of the process table for every pane's periodic look. + scans: Arc, } pub(crate) struct Proc { @@ -98,6 +102,10 @@ pub(crate) struct Proc { changed: Condvar, /// Every descendant seen so far (ADR §11). Taken before `state`. tree: Mutex, + /// The host's snapshot, for the reader's periodic look at the tree. + scans: Arc, + /// When the pane was created: a snapshot that began earlier is not used. + born: Instant, /// A removal or shutdown is ending the pane: the reaper leaves the /// descendants' grace to it and reaps once it has released the pane. stopping: AtomicBool, @@ -148,6 +156,7 @@ impl LocalHost { sink: Arc::new(Mutex::new(None)), tail_cap: None, finished_backstop: FINISHED_BACKSTOP, + scans: Arc::new(procs::Shared::new()), } } @@ -167,6 +176,19 @@ impl LocalHost { self } + /// Test hook: the age limit of the shared process-table snapshot. + #[cfg(test)] + pub(crate) fn with_scan_max_age(mut self, max_age: Duration) -> Self { + self.scans = Arc::new(procs::Shared::with_max_age(max_age)); + self + } + + /// Test hook: how many scans of the process table the host has taken. + #[cfg(all(test, target_os = "linux"))] + pub(crate) fn scans(&self) -> usize { + self.scans.scans() + } + /// With a tail kept, make room for one more finished pane: forget the /// oldest finished ones beyond the backstop. fn evict_finished(&self) { @@ -247,6 +269,8 @@ impl PtyHost for LocalHost { }), changed: Condvar::new(), tree: Mutex::new(procs::Tree::default()), + scans: Arc::clone(&self.scans), + born: Instant::now(), stopping: AtomicBool::new(false), shutdown: AtomicBool::new(false), reader: Mutex::new(None), @@ -678,10 +702,11 @@ fn read_loop(pane: Arc, sink: SinkCell) { pane.reading.store(false, Ordering::SeqCst); if Instant::now() >= next_tree { // try_lock: a stop holds the tree, and the reader must keep - // draining the terminal meanwhile. + // draining the terminal meanwhile. The snapshot is shared with + // the other panes' readers; a stop takes its own fresh scan. if let Ok(mut tree) = pane.tree.try_lock() { if pane.is_live() && pane.owns_group() { - let _ = tree.refresh(pane.pid); + let _ = tree.refresh_shared(pane.pid, &pane.scans, pane.born); } } next_tree = Instant::now() + TREE_POLL; diff --git a/src/native/host/mod.rs b/src/native/host/mod.rs index f2cc2c5..853390a 100644 --- a/src/native/host/mod.rs +++ b/src/native/host/mod.rs @@ -26,6 +26,8 @@ pub(super) mod tail; mod tests_drain; #[cfg(test)] pub(super) mod tests_link; +#[cfg(all(test, target_os = "linux"))] +mod tests_scan; pub(super) mod wire; use crate::backend::BackendError; diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index 8becb36..8a25b60 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -8,8 +8,19 @@ //! (on macOS: the processes whose controlling terminal is the pane's). The //! reader thread refreshes the tree every `TREE_POLL` while the //! leader runs, and the stop path refreshes it again before signalling. +//! +//! On Linux every refresh needs the whole process table. The reader threads +//! of all the holder's panes share one [`Shared`] snapshot of it, at most +//! [`SNAPSHOT_MAX_AGE`] old, so a tick costs one scan, not one per pane. The +//! stop path never uses it: it takes its own fresh scan ([`Tree::refresh`]), +//! and a signal is sent only after the pid and its start time are read again. +//! `Shared`'s lock is a leaf: nothing else is taken while it is held. use std::collections::HashMap; +use std::time::{Duration, Instant}; + +/// The oldest a shared snapshot may be when a pane's reader uses it. +pub(crate) const SNAPSHOT_MAX_AGE: Duration = Duration::from_millis(250); /// When a process started, in platform units. With the pid it names one /// process: a pid that is reused gets a later start time. @@ -31,6 +42,25 @@ impl Tree { /// processes were new. pub(crate) fn refresh(&mut self, leader: i32) -> usize { let snap = os::Snapshot::take(leader, &mut self.tty); + self.apply(leader, &snap) + } + + /// Like [`Tree::refresh`], from the holder-wide snapshot when it is + /// recent enough and was taken at or after `not_before` (when the pane + /// was spawned, so it cannot predate the leader). For the periodic + /// look only: a stop must use `refresh`, because a snapshot up to + /// `SNAPSHOT_MAX_AGE` old can miss a process forked since. + pub(crate) fn refresh_shared( + &mut self, + leader: i32, + shared: &Shared, + not_before: Instant, + ) -> usize { + let snap = shared.0.snapshot(leader, &mut self.tty, not_before); + self.apply(leader, &snap) + } + + fn apply(&mut self, leader: i32, snap: &os::Snapshot) -> usize { let mut known: HashMap = self .members .iter() @@ -80,6 +110,33 @@ impl Tree { } } +/// The process table as seen by one holder, shared by its panes' readers. +pub(crate) struct Shared(os::Shared); + +impl Shared { + pub(crate) fn new() -> Self { + Self(os::Shared::new(SNAPSHOT_MAX_AGE)) + } + + /// Test hook: a different age limit. + #[cfg(test)] + pub(crate) fn with_max_age(max_age: Duration) -> Self { + Self(os::Shared::new(max_age)) + } + + /// How many scans of the process table this has taken. + #[cfg(all(test, target_os = "linux"))] + pub(crate) fn scans(&self) -> usize { + self.0.scans() + } +} + +impl Default for Shared { + fn default() -> Self { + Self::new() + } +} + /// Signal `pid` only if it is still the process that started at `start`. /// The window between the check and the kill is a few microseconds; a pid /// is reused only after the pid space wraps, so a reuse inside it is not a @@ -97,6 +154,7 @@ fn signal_if_same(pid: i32, start: Start, signal: libc::c_int) { mod os { use super::Start; use std::mem::{size_of, MaybeUninit}; + use std::time::{Duration, Instant}; /// `PROC_TTY_ONLY` in ``: processes whose session's /// controlling terminal is the given device. @@ -177,59 +235,144 @@ mod os { out } } + + /// macOS asks the kernel per question and keeps no table, so there is + /// nothing to share: each look is its own. + pub(super) struct Shared; + + impl Shared { + pub(super) fn new(_max_age: Duration) -> Self { + Self + } + + pub(super) fn snapshot( + &self, + leader: i32, + tty: &mut Option, + _not_before: Instant, + ) -> Snapshot { + Snapshot::take(leader, tty) + } + } } #[cfg(target_os = "linux")] mod os { use super::Start; use std::collections::HashMap; + use std::fmt::Write as _; + use std::fs::File; + use std::io::Read; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex, PoisonError}; + use std::time::{Duration, Instant}; - struct Stat { - ppid: i32, - pgrp: i32, - session: i32, - start: Start, + pub(super) struct Stat { + pub(super) ppid: i32, + pub(super) pgrp: i32, + pub(super) session: i32, + pub(super) start: Start, } - /// `/proc//stat`, or None when it is gone or a zombie. - fn stat(pid: i32) -> Option { - let text = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + fn int(token: &[u8]) -> Option { + std::str::from_utf8(token).ok()?.parse().ok() + } + + /// The fields of one `/proc//stat` line, or None for a zombie, a + /// dead process, or a line that is cut short. Read in place: no + /// allocation. Bytes, not text, so a command name that is not UTF-8 + /// does not hide the process. + pub(super) fn parse_stat(line: &[u8]) -> Option { // The command name may hold spaces and parentheses: fields start // after the last ')'. - let rest = &text[text.rfind(')')? + 1..]; - let fields: Vec<&str> = rest.split_whitespace().collect(); - // fields[0] is field 3 of proc(5): state, ppid, pgrp, session, ..., - // starttime (field 22). - if matches!(fields.first(), Some(&"Z") | Some(&"X") | None) { + let rest = &line[line.iter().rposition(|&b| b == b')')? + 1..]; + let mut fields = rest + .split(|b| b.is_ascii_whitespace()) + .filter(|field| !field.is_empty()); + // The first field is field 3 of proc(5): state, ppid, pgrp, session, + // ..., starttime (field 22, 15 fields after session). + if matches!(fields.next()?, b"Z" | b"X") { return None; } + let ppid = int(fields.next()?)?; + let pgrp = int(fields.next()?)?; + let session = int(fields.next()?)?; + let start = int(fields.nth(15)?)?; Some(Stat { - ppid: fields.get(1)?.parse().ok()?, - pgrp: fields.get(2)?.parse().ok()?, - session: fields.get(3)?.parse().ok()?, - start: fields.get(19)?.parse().ok()?, + ppid, + pgrp, + session, + start, }) } + /// Reads `/proc//stat` into a path and a buffer it keeps, so a scan + /// of every process allocates once, not once per process. + #[derive(Default)] + pub(super) struct Reader { + path: String, + buf: Vec, + } + + impl Reader { + /// `/proc//stat`, or None when it is gone or a zombie. + pub(super) fn stat(&mut self, pid: i32) -> Option { + self.path.clear(); + write!(self.path, "/proc/{pid}/stat").ok()?; + self.buf.clear(); + File::open(&self.path) + .ok()? + .read_to_end(&mut self.buf) + .ok()?; + parse_stat(&self.buf) + } + } + pub(super) fn start_time(pid: i32) -> Option { - stat(pid).map(|s| s.start) + Reader::default().stat(pid).map(|s| s.start) } - /// One read of every process in `/proc`. + /// One read of every process in `/proc`, with the lookups the tree needs + /// indexed once: by parent, and by process group and session. pub(super) struct Snapshot { procs: HashMap, + children: HashMap>, + /// Members of each process group and session, by its id. + peers: HashMap>, } impl Snapshot { pub(super) fn take(_leader: i32, _tty: &mut Option) -> Self { - let procs = std::fs::read_dir("/proc") + let pids = std::fs::read_dir("/proc") .into_iter() .flatten() .flatten() - .filter_map(|entry| entry.file_name().to_str()?.parse::().ok()) - .filter_map(|pid| Some((pid, stat(pid)?))) + .filter_map(|entry| entry.file_name().to_str()?.parse::().ok()); + Self::of(pids) + } + + /// The listed processes that can still be read: one that left + /// between the listing and the read is skipped. + pub(super) fn of(pids: impl IntoIterator) -> Self { + let mut reader = Reader::default(); + let procs: HashMap = pids + .into_iter() + .filter_map(|pid| Some((pid, reader.stat(pid)?))) .collect(); - Self { procs } + let mut children: HashMap> = HashMap::new(); + let mut peers: HashMap> = HashMap::new(); + for (&pid, s) in &procs { + children.entry(s.ppid).or_default().push(pid); + peers.entry(s.pgrp).or_default().push(pid); + if s.session != s.pgrp { + peers.entry(s.session).or_default().push(pid); + } + } + Self { + procs, + children, + peers, + } } pub(super) fn start(&self, pid: i32) -> Option { @@ -237,20 +380,57 @@ mod os { } pub(super) fn children(&self, pid: i32) -> Vec { - self.procs - .iter() - .filter(|(_, s)| s.ppid == pid) - .map(|(&p, _)| p) - .collect() + self.children.get(&pid).cloned().unwrap_or_default() } /// The leader's group and session. pub(super) fn peers(&self, leader: i32) -> Vec { - self.procs - .iter() - .filter(|(_, s)| s.pgrp == leader || s.session == leader) - .map(|(&p, _)| p) - .collect() + self.peers.get(&leader).cloned().unwrap_or_default() + } + } + + /// The newest scan and when it began. One scan serves every reader that + /// asks within `max_age`; the lock is held across the scan, so readers + /// that arrive meanwhile wait for it instead of each taking their own. + pub(super) struct Shared { + max_age: Duration, + last: Mutex)>>, + scans: AtomicUsize, + } + + impl Shared { + pub(super) fn new(max_age: Duration) -> Self { + Self { + max_age, + last: Mutex::new(None), + scans: AtomicUsize::new(0), + } + } + + /// A scan that began at or after `not_before` and less than + /// `max_age` ago, taking one if there is none. + pub(super) fn snapshot( + &self, + leader: i32, + tty: &mut Option, + not_before: Instant, + ) -> Arc { + let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((began, snap)) = &*last { + if *began >= not_before && began.elapsed() < self.max_age { + return Arc::clone(snap); + } + } + let began = Instant::now(); + let snap = Arc::new(Snapshot::take(leader, tty)); + self.scans.fetch_add(1, Ordering::Relaxed); + *last = Some((began, Arc::clone(&snap))); + snap + } + + #[cfg(test)] + pub(super) fn scans(&self) -> usize { + self.scans.load(Ordering::Relaxed) } } } @@ -292,6 +472,381 @@ mod tests { } } + /// A process tree to look for: `sh` leads its own session and runs a + /// sleep, a subshell with a sleep of its own, and a child that moved to + /// another session (found by parent, not by group or session). + /// Returns the leader and the pids the script reported. + struct Fixture { + leader: std::process::Child, + members: Vec, + dir: crate::testutil::TempDir, + } + + impl Fixture { + fn new(name: &str) -> Self { + use std::os::unix::process::CommandExt; + let dir = crate::testutil::TempDir::new(name); + let file = dir.path().join("pids"); + let script = "sleep 60 & echo $! >>\"$F\"; \ + (sleep 60 & echo $! >>\"$F\"; wait) & echo $! >>\"$F\"; \ + perl -MPOSIX -e 'POSIX::setsid(); sleep 60' & echo $! >>\"$F\"; wait"; + let mut cmd = Command::new("/bin/sh"); + cmd.args(["-c", script]) + .env("F", &file) + .stdin(Stdio::null()) + .stdout(Stdio::null()); + // SAFETY: setsid between fork and exec, nothing else. + unsafe { + cmd.pre_exec(|| { + libc::setsid(); + Ok(()) + }); + } + let leader = cmd.spawn().unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + let mut members: Vec; + loop { + members = std::fs::read_to_string(&file) + .unwrap_or_default() + .lines() + .filter_map(|l| l.trim().parse().ok()) + .collect(); + // Four pids, all running. + let ready = members.len() == 4 + && members.iter().all(|&p| os::start_time(p).is_some()) + // The perl has left the leader's session (it leads its own). + // SAFETY: getsid only reads a process's session id. + && members.iter().any(|&p| unsafe { libc::getsid(p) } == p); + if ready { + break; + } + assert!(Instant::now() < deadline, "the fixture did not start"); + thread_sleep(20); + } + members.sort_unstable(); + Self { + leader, + members, + dir, + } + } + + fn pid(&self) -> i32 { + self.leader.id() as i32 + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // SAFETY: kill on the fixture's own group. + unsafe { + libc::killpg(self.pid(), libc::SIGKILL); + } + for pid in &self.members { + // SAFETY: kill on a pid the fixture started. + unsafe { + libc::kill(*pid, libc::SIGKILL); + } + } + let _ = self.leader.wait(); + let _ = &self.dir; + } + } + + fn sorted(tree: &Tree) -> Vec { + let mut pids: Vec = tree.members.keys().copied().collect(); + pids.sort_unstable(); + pids + } + + /// `refresh` finds the leader's group, its session and a child that left + /// both, and nothing else; a second refresh adds nothing. + #[test] + fn refresh_finds_exactly_the_fixture_tree() { + let fx = Fixture::new("procs-fixture-fresh"); + let mut tree = Tree::default(); + assert_eq!(tree.refresh(fx.pid()), 4); + assert_eq!(sorted(&tree), fx.members); + assert_eq!(tree.refresh(fx.pid()), 0); + assert_eq!(sorted(&tree), fx.members); + assert!(tree.any_alive()); + } + + /// The shared snapshot finds the same members as a fresh scan. + #[test] + fn refresh_shared_finds_exactly_the_fixture_tree() { + let fx = Fixture::new("procs-fixture-shared"); + let shared = Shared::new(); + let mut tree = Tree::default(); + assert_eq!( + tree.refresh_shared(fx.pid(), &shared, Instant::now() - Duration::from_secs(60)), + 4 + ); + assert_eq!(sorted(&tree), fx.members); + } + + /// A member that has gone is dropped by the next refresh. + #[test] + fn a_member_that_exited_is_dropped() { + let fx = Fixture::new("procs-fixture-drop"); + let mut tree = Tree::default(); + tree.refresh(fx.pid()); + let gone = *fx.members.last().unwrap(); + // SAFETY: kill on a pid the fixture started. + unsafe { + libc::kill(gone, libc::SIGKILL); + } + let deadline = Instant::now() + Duration::from_secs(5); + while os::start_time(gone).is_some() { + assert!(Instant::now() < deadline, "{gone} did not exit"); + thread_sleep(20); + } + tree.refresh(fx.pid()); + assert!(!tree.members.contains_key(&gone)); + // Whatever else is still running (a sleep whose parent was killed + // is re-parented, but is still in the leader's session) stays. + let alive: Vec = fx + .members + .iter() + .copied() + .filter(|&p| os::start_time(p).is_some()) + .collect(); + assert!(!alive.is_empty() && !alive.contains(&gone)); + assert_eq!(sorted(&tree), alive); + } + + #[cfg(target_os = "linux")] + mod linux { + use super::*; + use os::{parse_stat, Reader, Snapshot}; + + /// A stat line with `comm` between the parentheses; the fields after + /// it are state, ppid 10, pgrp 20, session 30, then filler up to + /// starttime 4242 (field 22), then more fields. + fn line(pid: i32, comm: &[u8], state: &str) -> Vec { + let mut out = format!("{pid} (").into_bytes(); + out.extend_from_slice(comm); + // fields 3..=21 are state, ppid, pgrp, session, then 15 more. + out.extend_from_slice(format!(") {state} 10 20 30").as_bytes()); + for n in 0..15 { + out.extend_from_slice(format!(" {}", 100 + n).as_bytes()); + } + out.extend_from_slice(b" 4242 999 888 777\n"); + out + } + + fn fields(bytes: &[u8]) -> Option<(i32, i32, i32, u64)> { + parse_stat(bytes).map(|s| (s.ppid, s.pgrp, s.session, s.start)) + } + + #[test] + fn a_plain_line_is_parsed() { + assert_eq!(fields(&line(7, b"sleep", "S")), Some((10, 20, 30, 4242))); + } + + #[test] + fn a_comm_with_spaces_and_parentheses_is_parsed() { + for comm in [ + &b"a b c"[..], + b"(x)", + b") R 1 2 3 (", + b"((((", + b"))))", + b"", + b" ", + ] { + assert_eq!( + fields(&line(7, comm, "R")), + Some((10, 20, 30, 4242)), + "comm {:?}", + String::from_utf8_lossy(comm) + ); + } + } + + #[test] + fn a_very_long_comm_is_parsed() { + let comm = vec![b'x'; 100_000]; + assert_eq!(fields(&line(7, &comm, "S")), Some((10, 20, 30, 4242))); + let mut tricky = b") ".repeat(20_000); + tricky.extend_from_slice(b"("); + assert_eq!(fields(&line(7, &tricky, "S")), Some((10, 20, 30, 4242))); + } + + /// The old text parser dropped such a process; ending it matters + /// more than the name. + #[test] + fn a_comm_that_is_not_utf8_is_parsed() { + assert_eq!( + fields(&line(7, &[0xff, 0xfe, b'(', 0x80], "S")), + Some((10, 20, 30, 4242)) + ); + } + + #[test] + fn a_zombie_or_dead_process_is_not_found() { + assert_eq!(fields(&line(7, b"z", "Z")), None); + assert_eq!(fields(&line(7, b"x", "X")), None); + assert!(fields(&line(7, b"x", "x")).is_some()); + } + + #[test] + fn a_cut_or_malformed_line_is_not_found() { + assert_eq!(fields(b""), None); + assert_eq!(fields(b"7 (sleep"), None); + assert_eq!(fields(b"7 (sleep)"), None); + assert_eq!(fields(b"7 (sleep) S 10 20"), None); + let full = line(7, b"sleep", "S"); + // Cut before starttime (field 22): no start, no process. + let before_start = full.len() - " 4242 999 888 777\n".len(); + assert_eq!(fields(&full[..before_start]), None); + assert_eq!( + fields(b"7 (sleep) S x 20 30 1 2 3 4 5 6 7 8 9 10 11 12 13 4242"), + None + ); + } + + /// A real zombie is not in a snapshot; its parent is. + #[test] + fn a_real_zombie_is_not_in_a_snapshot() { + let mut child = Command::new("/bin/true").spawn().unwrap(); + let pid = child.id() as i32; + let deadline = Instant::now() + Duration::from_secs(5); + let mut reader = Reader::default(); + // Not waited for: the process stays a zombie once it has exited. + while std::fs::read_to_string(format!("/proc/{pid}/stat")) + .map(|t| !t.contains(") Z ")) + .unwrap_or(true) + { + assert!(Instant::now() < deadline, "no zombie appeared"); + thread_sleep(10); + } + assert!(reader.stat(pid).is_none()); + assert!(os::start_time(pid).is_none()); + let snap = Snapshot::take(0, &mut None); + assert!(snap.start(pid).is_none()); + assert!(snap.start(std::process::id() as i32).is_some()); + child.wait().unwrap(); + } + + /// A process listed by readdir but gone at the read is skipped. + #[test] + fn a_process_that_vanished_between_listing_and_reading_is_skipped() { + let me = std::process::id() as i32; + let mut child = Command::new("/bin/true").spawn().unwrap(); + let gone = child.id() as i32; + child.wait().unwrap(); + let snap = Snapshot::of([me, gone, i32::MAX, 0, -5]); + assert!(snap.start(me).is_some()); + assert!(snap.start(gone).is_none()); + assert!(snap.start(i32::MAX).is_none()); + assert_eq!(Reader::default().stat(i32::MAX).map(|s| s.start), None); + } + + /// The snapshot's indexes agree with the stat of each process. + #[test] + fn the_indexes_list_each_process_once_under_its_parent_group_and_session() { + let fx = Fixture::new("procs-index"); + let snap = Snapshot::take(0, &mut None); + let mut reader = Reader::default(); + for &pid in &fx.members { + let s = reader.stat(pid).unwrap(); + let kids = snap.children(s.ppid); + assert_eq!(kids.iter().filter(|&&k| k == pid).count(), 1); + for id in [s.pgrp, s.session] { + let peers = snap.peers(id); + assert_eq!( + peers.iter().filter(|&&k| k == pid).count(), + 1, + "{pid} in {id}" + ); + } + } + assert!(snap.children(i32::MAX).is_empty()); + assert!(snap.peers(i32::MAX).is_empty()); + } + + /// A snapshot within the age limit is reused; an older one is not. + #[test] + fn a_shared_snapshot_is_reused_within_the_age_limit_only() { + let long = Shared::with_max_age(Duration::from_secs(3600)); + let epoch = Instant::now() - Duration::from_secs(60); + let mut tty = None; + let a = long.0.snapshot(1, &mut tty, epoch); + let b = long.0.snapshot(1, &mut tty, epoch); + assert!(std::sync::Arc::ptr_eq(&a, &b)); + assert_eq!(long.scans(), 1); + + let short = Shared::with_max_age(Duration::from_millis(60)); + let a = short.0.snapshot(1, &mut tty, epoch); + thread_sleep(100); + let b = short.0.snapshot(1, &mut tty, epoch); + assert!(!std::sync::Arc::ptr_eq(&a, &b)); + assert_eq!(short.scans(), 2); + + let none = Shared::with_max_age(Duration::ZERO); + none.0.snapshot(1, &mut tty, epoch); + none.0.snapshot(1, &mut tty, epoch); + assert_eq!(none.scans(), 2); + } + + /// A snapshot that began before the pane did is never used for it. + #[test] + fn a_shared_snapshot_older_than_the_pane_is_not_used() { + let shared = Shared::with_max_age(Duration::from_secs(3600)); + let mut tty = None; + let epoch = Instant::now() - Duration::from_secs(60); + shared.0.snapshot(1, &mut tty, epoch); + thread_sleep(5); + shared.0.snapshot(1, &mut tty, Instant::now()); + assert_eq!(shared.scans(), 2); + } + + /// Panes that poll together cost one scan: 8 trees, one snapshot. + #[test] + fn eight_trees_refreshed_together_take_one_scan() { + let shared = Shared::with_max_age(Duration::from_secs(3600)); + let epoch = Instant::now() - Duration::from_secs(60); + let me = std::process::id() as i32; + for _ in 0..8 { + Tree::default().refresh_shared(me, &shared, epoch); + } + assert_eq!(shared.scans(), 1); + } + + /// On the fixture the snapshot answers with the known tree: three + /// children of the leader (one in another session), and the leader + /// and three more in its group and session (the grandchild sleep, + /// but not the perl). + #[test] + fn the_snapshot_answers_for_the_fixture_with_the_known_members() { + let fx = Fixture::new("procs-known"); + let snap = Snapshot::take(0, &mut None); + let mut reader = Reader::default(); + let mut kids = Vec::new(); + // The leader leads its own group and session. + let mut group = vec![fx.pid()]; + for &pid in &fx.members { + let s = reader.stat(pid).unwrap(); + assert_eq!(snap.start(pid), Some(s.start)); + if s.ppid == fx.pid() { + kids.push(pid); + } + if s.pgrp == fx.pid() || s.session == fx.pid() { + group.push(pid); + } + } + assert_eq!(kids.len(), 3, "{kids:?}"); + assert_eq!(group.len(), 4, "{group:?}"); + let sorted_set = |mut v: Vec| { + v.sort_unstable(); + v + }; + assert_eq!(sorted_set(snap.children(fx.pid())), sorted_set(kids)); + assert_eq!(sorted_set(snap.peers(fx.pid())), sorted_set(group)); + } + } + fn thread_sleep(ms: u64) { std::thread::sleep(Duration::from_millis(ms)); } diff --git a/src/native/host/tests_scan.rs b/src/native/host/tests_scan.rs new file mode 100644 index 0000000..c11a974 --- /dev/null +++ b/src/native/host/tests_scan.rs @@ -0,0 +1,78 @@ +//! The shared process-table snapshot (`procs::Shared`) and the stop path: +//! the readers' periodic look shares one scan, a stop takes its own. + +use super::contract::{gone_within, process_alive, Rig, LONG}; +use super::local::LocalHost; +use super::PtyHost; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn wait_for(what: &str, mut ready: impl FnMut() -> bool) { + let end = Instant::now() + LONG; + while !ready() { + assert!(Instant::now() < end, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// With a snapshot that never ages out, the readers cannot see a process +/// forked after it, yet a kill ends that process: the stop scans afresh. +/// (Mutation check: make `soft_stop`, `await_tree_gone` and `release` call +/// `refresh_shared` instead of `refresh`, and this test fails.) +#[test] +fn a_stop_scans_afresh_and_ends_a_child_the_shared_snapshot_missed() { + let host = Arc::new(LocalHost::new().with_scan_max_age(Duration::from_secs(3600))); + let rig = Rig::new(Arc::clone(&host) as Arc, "scan-stop"); + let pane = rig.sh("echo ready; read x; \ + perl -MPOSIX -e 'POSIX::setsid() != -1 or die; print \"gc:$$\\n\"; \ + close STDIN; close STDOUT; close STDERR; sleep 60' & sleep 60"); + rig.sink.wait_text(&pane.id, "ready"); + wait_for("the first scan", || host.scans() >= 1); + let scans = host.scans(); + super::contract::wait_write(&rig, &pane.id, b"\n"); + rig.sink.wait_text(&pane.id, "gc:"); + let text = rig.sink.text(&pane.id); + let gc: i32 = text + .split("gc:") + .nth(1) + .and_then(|rest| rest.trim().lines().next()) + .and_then(|pid| pid.trim().parse().ok()) + .unwrap_or_else(|| panic!("no grandchild pid in {text:?}")); + // Several polls pass; every one reuses the old snapshot. + std::thread::sleep(Duration::from_millis(900)); + assert_eq!(host.scans(), scans, "the readers took a scan"); + assert!(process_alive(gc), "the grandchild died early"); + host.kill(&pane.id, Duration::from_secs(2)).unwrap(); + let ended = gone_within(gc, Duration::from_secs(5)); + if !ended { + // SAFETY: kill on the pid the pane reported, to clean up. + unsafe { + libc::kill(gc, libc::SIGKILL); + } + } + assert!(ended, "{gc} outlived kill: the stop used a stale snapshot"); + assert_eq!( + host.scans(), + scans, + "a stop must not use the shared snapshot" + ); +} + +/// Eight panes polling for descendants cost about one scan per tick, not +/// eight. +#[test] +fn eight_panes_share_one_scan_per_tick() { + let host = Arc::new(LocalHost::new()); + let rig = Rig::new(Arc::clone(&host) as Arc, "scan-share"); + let panes: Vec<_> = (0..8).map(|_| rig.spawn(&["sleep", "30"])).collect(); + // Past the first look of every pane, and a few ticks in. + std::thread::sleep(Duration::from_millis(700)); + let before = host.scans(); + std::thread::sleep(Duration::from_millis(1500)); + let taken = host.scans() - before; + // About 6 ticks; one scan per pane per tick would be about 48. + assert!(taken <= 14, "{taken} scans in 1.5 s for 8 panes"); + for pane in &panes { + host.kill(&pane.id, Duration::from_secs(2)).unwrap(); + } +} From fcc8434ae5dc6acc11b06a11281b5ab70926df18 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:35:50 -0500 Subject: [PATCH 2/6] fix: build the scan age-limit test hooks on Linux test builds only macOS clippy -D warnings flagged them as dead code (their only callers are Linux-only tests). Checked: cargo fmt --check and clippy --all-targets -D warnings clean on a Linux x86_64 host and on macOS; native::host tests pass on both. --- src/native/host/local.rs | 2 +- src/native/host/procs.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/native/host/local.rs b/src/native/host/local.rs index 8ecd580..f0dd071 100644 --- a/src/native/host/local.rs +++ b/src/native/host/local.rs @@ -177,7 +177,7 @@ impl LocalHost { } /// Test hook: the age limit of the shared process-table snapshot. - #[cfg(test)] + #[cfg(all(test, target_os = "linux"))] pub(crate) fn with_scan_max_age(mut self, max_age: Duration) -> Self { self.scans = Arc::new(procs::Shared::with_max_age(max_age)); self diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index 8a25b60..ebb2d1d 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -119,7 +119,7 @@ impl Shared { } /// Test hook: a different age limit. - #[cfg(test)] + #[cfg(all(test, target_os = "linux"))] pub(crate) fn with_max_age(max_age: Duration) -> Self { Self(os::Shared::new(max_age)) } From 05f27b0559e4856238aa11d353be27472ba9c76b Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Wed, 18 Nov 2026 17:04:29 -0500 Subject: [PATCH 3/6] fix: keep degraded process-table scans out of the cache and tree pruning A /proc scan that cannot list the directory or read a process (for example when file descriptors run out) is now marked incomplete. The shared snapshot does not cache an incomplete scan, and Tree::apply keeps each member it cannot check instead of pruning it. A member whose pid shows another start time is still dropped. Items addressed: - (a) Degraded scans: Snapshot::build/take track completeness; Shared::snapshot_at caches only complete scans; Tree::apply prunes only on a complete snapshot. Tests: a_degraded_snapshot_prunes_no_pane_member, a_degraded_snapshot_is_not_cached. - (b) Scan count: eight_pollers_take_exactly_one_scan_per_window asserts exactly six scans in 1.5 s for eight 250 ms pollers on a supplied clock, and a_snapshot_is_reused_until_the_age_limit_and_no_longer pins the 250 ms limit. The real-PTY eight_panes_share_one_scan_per_tick now asserts 2 to 7 scans, because panes started together cluster on the 200 ms reader wake and gave 3. - (c) Docs: adr/native-core.md and operations.md state the Linux window as 500 ms nominal and at most about 700 ms (macOS about 450 ms), including the owner-decision paragraph. - (d) CHANGELOG: latency change, and processes whose command name is not UTF-8 are now tracked. - (f) Removed the unused Default impl for Shared, documented that the Linux snapshot ignores leader and tty (parameters kept: the signature is shared with macOS), and corrected the parse_stat and read_loop comments. Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings; cargo test --locked): - macOS build host: 1019 passed, 0 failed, 6 ignored (12 test binaries) - Linux build host: 1039 passed, 0 failed, 6 ignored (12 test binaries) Refs #3 --- CHANGELOG.md | 8 ++ docs/adr/native-core.md | 6 +- docs/operations.md | 19 ++- src/native/host/local.rs | 3 +- src/native/host/procs.rs | 241 +++++++++++++++++++++++++++++----- src/native/host/tests_scan.rs | 14 +- 6 files changed, 244 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79ae5f4..d086a9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ is now accepted, so `answer_dialog` can answer it. Web search and wrapped shell commands stay refused. Fixtures for the new-file write, web fetch and web search keys and the wrapped shell dialogs are added under `tests/fixtures/kiro-3.3.0/`. +- Native panes (Linux): the holder reads the process table once per 250 ms for all its panes, + not once per pane, so idle CPU for eight panes drops from about 14.9 % to about 1.9 %. The + cost is detection latency. A descendant that detaches with `setsid` and whose parents exit is + now seen within about 500 ms nominal and at most about 700 ms (it was about 250 ms nominal). + On macOS the bound stays about 450 ms. Stops still read the table afresh, and a failed read + never removes a process from a pane's tree. +- Native panes: a process whose command name is not valid UTF-8 is now tracked. Before, it + escaped the descendant tree, so `remove_pane` and shutdown did not signal it. They now do. ## 0.5.0 diff --git a/docs/adr/native-core.md b/docs/adr/native-core.md index 9d9d5e6..b799415 100644 --- a/docs/adr/native-core.md +++ b/docs/adr/native-core.md @@ -258,7 +258,7 @@ PaneState { vt: vt100::Parser, status, reported, turn, status_ms, **Reader thread** (one per pane). It loops: - `poll(master, POLLIN, 200 ms)`; on each wake it checks `shutdown`. `shutdown` is set only after the leader has been reaped (§11), so the terminal is drained for as long as any pane process may still be exiting. -- Every 250 ms (`TREE_POLL`), while the leader runs, it refreshes the descendant tree with `tree.try_lock()` (a stop in progress holds the tree; the reader must not block on it, or it would stop draining). +- Every 250 ms (`TREE_POLL`, nominal: looks are up to about 450 ms apart, see the known limit under "Descendant tree"), while the leader runs, it refreshes the descendant tree with `tree.try_lock()` (a stop in progress holds the tree; the reader must not block on it, or it would stop draining). On Linux that refresh may use the holder-wide process-table snapshot, up to `SNAPSHOT_MAX_AGE` (250 ms) old; a stop never does. - It reads up to 16 KiB. - `read` returning 0 or `EIO` means the slave side has closed, and the thread exits its loop. `EAGAIN` or `EINTR` means retry. Any other error is logged once (`native: : read failed: `) and ends the loop. - For each chunk, under `state`: @@ -356,9 +356,9 @@ Nothing else passes, by construction (`env_clear()` first). In particular, `OPEN - **Removal failures:** `NotFound` for an unknown ref. If `kill` on the group fails with an error other than ESRCH, it is logged at warn level and removal still completes; EPERM after the leader has exited is not logged, because macOS answers EPERM for a group left with only its zombie leader (measured). - **Descendant tree (issue #10).** Measured on macOS with main `b446018`: kiro-cli starts `bun`, which starts `node …/acp-server.js` in a new session (`ps` STAT `Ss` without `+`: it called `setsid`, so it is a session and group leader with no controlling terminal; Node's `detached: true`). It is found only by the parent-pid walk from `bun`, never through the pane's group or terminal. Killing the pane's group never reached it, and after a pane ended it lived on with ppid 1 for over an hour. `procs::Tree` (in `src/native/procs.rs`) records every descendant as `(pid, start time)`: - **Found by** parent pid, from the leader and from every member still alive (a breadth-first walk), and by membership of the leader's group and session: on Linux, `/proc//stat` fields `ppid`, `pgrp`, `session` and `starttime`, from one scan of `/proc`; on macOS, `proc_listchildpids`, `proc_listpgrppids`, and `proc_listpids(PROC_TTY_ONLY, tdev)` with the leader's controlling terminal (`proc_bsdinfo.e_tdev`; macOS has no list-by-session call, and every process of the session has that terminal while the leader runs), with the start time from `proc_pidinfo(PROC_PIDTBSDINFO)` (`pbi_start_tvsec`/`usec`). - - **Refreshed** every 250 ms by the reader while the leader runs, and at the start of every soft and hard stop. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. + - **Refreshed** every 250 ms (nominal) by the reader while the leader runs, and at the start of every soft and hard stop. A scan that could not read every process is neither cached nor allowed to prune: the tree keeps its members. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. - **Signalled** only after re-reading the pid's start time and finding it unchanged. A reused pid has a later start time and is skipped. The check and the `kill` are a few microseconds apart; a pid is reused only after the pid space wraps, so a reuse inside that window is not a practical risk. Zombies are skipped (Linux state `Z`/`X`; macOS does not answer `proc_pidinfo` for zombies). Shepherd's own pid and pids 0 and 1 are never members. - - **Known limit (owner decision after review):** a descendant that is re-parented and fully detaches before the next tree poll (about 250 ms) is not seen: it calls `setsid` (no group, session or terminal link to the pane) and every ancestor between it and a known member exits first, as in a daemon's double fork. It survives removal, the program's own exit, shutdown and drop. One that only changes its process group is still found through the session (macOS: the terminal) while the leader runs, and one whose parent lives until the next poll is found by the parent-pid walk. Measured on macOS 15.7 (remote build host, a C probe with a `setsid` double fork): kqueue `EVFILT_PROC` with `NOTE_TRACK` is refused with `EV_ERROR`, data 45 (`ENOTSUP`); every process inherits its parent's coalition ids (`PROC_PIDCOALITIONINFO`), but creating a coalition needs root, so a pane cannot get its own; macOS has no subreaper and no cgroup; `p_puniqueid` (`PROC_PIDUNIQIDENTIFIERINFO`) survives the reparent to pid 1, but it names the intermediate that was never seen, so the chain stays broken. No public unprivileged macOS mechanism closes the gap. Linux can close it with `PR_SET_CHILD_SUBREAPER` in a per-pane supervisor; that is a follow-up to build and test with a Linux build. + - **Known limit (owner decision after review):** a descendant that is re-parented and fully detaches before the first look that would see it is not seen: it calls `setsid` (no group, session or terminal link to the pane) and every ancestor between it and a known member exits first, as in a daemon's double fork. That look comes within about 700 ms of the fork on Linux (a snapshot up to 250 ms old, plus looks up to about 450 ms apart because the reader wakes every 200 ms; the nominal figure is 500 ms) and within about 450 ms on macOS, which caches nothing. It survives removal, the program's own exit, shutdown and drop. One that only changes its process group is still found through the session (macOS: the terminal) while the leader runs, and one whose parent lives until the next look is found by the parent-pid walk. Measured on macOS 15.7 (remote build host, a C probe with a `setsid` double fork): kqueue `EVFILT_PROC` with `NOTE_TRACK` is refused with `EV_ERROR`, data 45 (`ENOTSUP`); every process inherits its parent's coalition ids (`PROC_PIDCOALITIONINFO`), but creating a coalition needs root, so a pane cannot get its own; macOS has no subreaper and no cgroup; `p_puniqueid` (`PROC_PIDUNIQIDENTIFIERINFO`) survives the reparent to pid 1, but it names the intermediate that was never seen, so the chain stays broken. No public unprivileged macOS mechanism closes the gap. Linux can close it with `PR_SET_CHILD_SUBREAPER` in a per-pane supervisor; that is a follow-up to build and test with a Linux build. - **Alternatives considered.** (a) Signal only the group or session: misses `setsid` children, and neither kernel has kill-by-session. (b) Snapshot the tree only at stop time: misses a descendant whose parent already exited (the measured orphan), so tracking is required. (c) Linux `PR_SET_CHILD_SUBREAPER` would reparent orphans to Shepherd, but macOS has no equivalent and Shepherd would then have to reap foreign children; one mechanism on both platforms is simpler to test. (d) A per-pane cgroup (Linux) or job object does not exist on macOS. (e) pidfds would close the check-to-kill window on Linux only; not worth a second code path given (c). - **The zombie and the lost exit code (issue #10).** Measured: `remove_pane` on Kiro returned `stopped: killed, exit_code: null`, and the leader stayed `?Es` (exiting, not yet a zombie) with Shepherd as parent. Cause: removal set `shutdown` first, so the reader stopped reading the master. A process that exits with output still queued on its terminal waits in the tty close for it to drain; with the master open and unread, the leader stayed in that state (`?Es`, measured on macOS) and never finished exiting, so `waitid` never returned and no code was recorded. The same unread output is why Kiro, which writes as it restores the terminal, did not exit within the 2 s grace. Fix: the reader drains until the leader is reaped (`shutdown` is set after), and every stop path waits for the reaper. Reproduced in `cargo test` before the fix with `trap '' HUP TERM; exec yes` (killed, `exit_code: None`, `ps` showed `?Es`) and with a shell that writes 400 KB on SIGHUP (killed instead of exiting with its code). - **Graceful stop for Kiro (decided).** SIGHUP and SIGTERM with the output drained, no keystrokes. Typing `/quit` would need Kiro to be idle and not in a dialog, and would put text into a pane the caller may not expect; Ctrl-D/Esc have the same problem (`interrupt_pane` exists for a clean turn end). Measured with `examples/native_leak_check` on a developer machine (kiro-cli 3.1.0): with the drain fix kiro-cli exited on the signals in 148 to 269 ms with code 1 in 4 of 5 runs (one of them with a 15 s grace); in the other it had not exited after 2 s and was killed (137, reaped, none of its processes left). Callers who want more time pass `remove_pane`'s `timeout`. diff --git a/docs/operations.md b/docs/operations.md index 9aab297..a635bc6 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -804,17 +804,21 @@ Pane ids are `n:` again before any stop, and by membership of the child's group and session. So a descendant that moves to its own group or session, or whose parent exits, is still known. On Linux the periodic look reads the process table once for all - panes, and a pane may use a read up to 250 ms old (so a descendant is seen - within about 500 ms, not 250 ms); a stop always reads it afresh. Removing a pane (`remove_pane`) and Shepherd's exit on SIGINT, - SIGTERM or SIGHUP send SIGHUP and SIGTERM to the group and the descendants, wait + panes, and a pane may use a read up to 250 ms old. A look is nominally every + 250 ms, and up to about 450 ms apart because the reader wakes every 200 ms. So a + descendant is seen within about 500 ms nominal and at most about 700 ms (see + Known limits). A stop always reads it afresh. Removing a pane (`remove_pane`) + and Shepherd's exit on SIGINT, SIGTERM or SIGHUP send SIGHUP and SIGTERM to the + group and the descendants, wait up to 2 s (for `remove_pane`, its `timeout`), then stop (SIGSTOP) the group and descendants until no new one appears and SIGKILL them all. When the program exits on its own, what it left behind gets the same treatment at once. The leader stays an unreaped zombie only during that stop, so its pid (the group and session id) cannot be reused while Shepherd signals by it; a descendant is signalled only while its pid still has the recorded start time. Known limit: a descendant that - is re-parented and fully detaches (new session, no terminal) before the next - look at the process table (about every 250 ms) is never seen and survives + is re-parented and fully detaches (new session, no terminal) before the first + look that would see it (within about 700 ms of its fork on Linux, about 450 ms + on macOS; see Known limits) is never seen and survives (see Known limits). If Shepherd is killed with SIGKILL, children get only the PTY hangup. - **Status.** OSC 7501 reports from the program are parsed in the emulator's @@ -1651,8 +1655,9 @@ try to update itself at run time). without cursor save) is not emulated. - **Native: a fast daemon escapes.** A descendant that is re-parented and fully detaches (calls `setsid`, so it has no group, session or terminal link to the - pane, and its parents exit) before the next look at the process table, about - every 250 ms, is never seen. It survives `remove_pane`, the program's own exit, + pane, and its parents exit) before the first look that would see it, is never + seen. That look comes within about 700 ms of the fork on Linux and about 450 ms + on macOS. It survives `remove_pane`, the program's own exit, and Shepherd's shutdown. One that only changes process group, or stays under a live parent until the next look, is ended (issue #10). macOS offers no unprivileged way to close this: kqueue `NOTE_TRACK` answers `ENOTSUP`, only root diff --git a/src/native/host/local.rs b/src/native/host/local.rs index f0dd071..ec742ac 100644 --- a/src/native/host/local.rs +++ b/src/native/host/local.rs @@ -663,7 +663,8 @@ impl Proc { } /// The reader thread: output to the sink until EOF, EIO or removal, and every -/// `TREE_POLL` a fresh look for the pane's descendants. +/// `TREE_POLL` a look at the pane's descendants (on Linux, from the holder's +/// shared process-table snapshot, up to `SNAPSHOT_MAX_AGE` old). fn read_loop(pane: Arc, sink: SinkCell) { let fd = pane.master.as_raw_fd(); let mut buf = vec![0u8; READ_CHUNK]; diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index ebb2d1d..5aed927 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -14,7 +14,9 @@ //! [`SNAPSHOT_MAX_AGE`] old, so a tick costs one scan, not one per pane. The //! stop path never uses it: it takes its own fresh scan ([`Tree::refresh`]), //! and a signal is sent only after the pid and its start time are read again. -//! `Shared`'s lock is a leaf: nothing else is taken while it is held. +//! `Shared`'s lock is a leaf: nothing else is taken while it is held. A scan +//! that could not read every process is not kept, and a tree applied from it +//! keeps the members it could not check. use std::collections::HashMap; use std::time::{Duration, Instant}; @@ -60,11 +62,18 @@ impl Tree { self.apply(leader, &snap) } + /// A member the snapshot shows with another start time has been replaced + /// and is dropped. A member the snapshot does not show is dropped only + /// when the snapshot is complete: a degraded one (a failed read) cannot + /// tell "gone" from "not read", so it keeps the member. fn apply(&mut self, leader: i32, snap: &os::Snapshot) -> usize { let mut known: HashMap = self .members .iter() - .filter(|(&pid, &start)| snap.start(pid) == Some(start)) + .filter(|(&pid, &start)| match snap.start(pid) { + Some(now) => now == start, + None => !snap.complete(), + }) .map(|(&pid, &start)| (pid, start)) .collect(); let me = std::process::id() as i32; @@ -131,12 +140,6 @@ impl Shared { } } -impl Default for Shared { - fn default() -> Self { - Self::new() - } -} - /// Signal `pid` only if it is still the process that started at `start`. /// The window between the check and the kill is a few microseconds; a pid /// is reused only after the pid space wraps, so a reuse inside it is not a @@ -216,6 +219,11 @@ mod os { start_time(pid) } + /// Every answer is a live kernel query, so nothing here is degraded. + pub(super) fn complete(&self) -> bool { + true + } + pub(super) fn children(&self, pid: i32) -> Vec { // SAFETY: the buffer and its size come from `pids`. pids(|buf, size| unsafe { libc::proc_listchildpids(pid, buf, size) }) @@ -290,7 +298,7 @@ mod os { .split(|b| b.is_ascii_whitespace()) .filter(|field| !field.is_empty()); // The first field is field 3 of proc(5): state, ppid, pgrp, session, - // ..., starttime (field 22, 15 fields after session). + // ..., starttime (field 22, the 16th field after session). if matches!(fields.next()?, b"Z" | b"X") { return None; } @@ -306,6 +314,16 @@ mod os { }) } + /// What one read of `/proc//stat` found. `Gone` is normal (the + /// process exited, or is a zombie). `Failed` is not: the read could not + /// be made (for example, out of file descriptors), so the process may + /// well be alive. + pub(super) enum StatRead { + Stat(Stat), + Gone, + Failed, + } + /// Reads `/proc//stat` into a path and a buffer it keeps, so a scan /// of every process allocates once, not once per process. #[derive(Default)] @@ -315,16 +333,27 @@ mod os { } impl Reader { - /// `/proc//stat`, or None when it is gone or a zombie. - pub(super) fn stat(&mut self, pid: i32) -> Option { + pub(super) fn read(&mut self, pid: i32) -> StatRead { self.path.clear(); - write!(self.path, "/proc/{pid}/stat").ok()?; + if write!(self.path, "/proc/{pid}/stat").is_err() { + return StatRead::Failed; + } self.buf.clear(); - File::open(&self.path) - .ok()? - .read_to_end(&mut self.buf) - .ok()?; - parse_stat(&self.buf) + match File::open(&self.path).and_then(|mut f| f.read_to_end(&mut self.buf)) { + Ok(_) => parse_stat(&self.buf).map_or(StatRead::Gone, StatRead::Stat), + Err(err) if matches!(err.raw_os_error(), Some(libc::ENOENT | libc::ESRCH)) => { + StatRead::Gone + } + Err(_) => StatRead::Failed, + } + } + + /// `/proc//stat`, or None when it cannot be read. + pub(super) fn stat(&mut self, pid: i32) -> Option { + match self.read(pid) { + StatRead::Stat(stat) => Some(stat), + StatRead::Gone | StatRead::Failed => None, + } } } @@ -334,31 +363,74 @@ mod os { /// One read of every process in `/proc`, with the lookups the tree needs /// indexed once: by parent, and by process group and session. + /// + /// The snapshot does not depend on the leader it was taken for. A + /// degraded one (the listing failed, or a read failed) is `incomplete`: + /// it can miss live processes, so it must not be cached or used to drop + /// members. pub(super) struct Snapshot { procs: HashMap, children: HashMap>, /// Members of each process group and session, by its id. peers: HashMap>, + complete: bool, } impl Snapshot { + /// Scans `/proc`. The leader and the tty are not used on Linux, so + /// the result serves every pane. pub(super) fn take(_leader: i32, _tty: &mut Option) -> Self { - let pids = std::fs::read_dir("/proc") - .into_iter() - .flatten() - .flatten() - .filter_map(|entry| entry.file_name().to_str()?.parse::().ok()); - Self::of(pids) + let mut listed = true; + let mut pids = Vec::new(); + match std::fs::read_dir("/proc") { + Ok(entries) => { + for entry in entries { + match entry { + Ok(entry) => { + if let Some(pid) = entry + .file_name() + .to_str() + .and_then(|name| name.parse::().ok()) + { + pids.push(pid); + } + } + Err(_) => listed = false, + } + } + } + Err(_) => listed = false, + } + let mut reader = Reader::default(); + Self::build(pids, listed, |pid| reader.read(pid)) } /// The listed processes that can still be read: one that left /// between the listing and the read is skipped. + #[cfg(test)] pub(super) fn of(pids: impl IntoIterator) -> Self { let mut reader = Reader::default(); - let procs: HashMap = pids - .into_iter() - .filter_map(|pid| Some((pid, reader.stat(pid)?))) - .collect(); + Self::build(pids, true, |pid| reader.read(pid)) + } + + /// Builds the snapshot from the listing and one `read` per listed + /// process. A `Failed` read makes the snapshot incomplete. + pub(super) fn build( + pids: impl IntoIterator, + listed: bool, + mut read: impl FnMut(i32) -> StatRead, + ) -> Self { + let mut complete = listed; + let mut procs = HashMap::new(); + for pid in pids { + match read(pid) { + StatRead::Stat(stat) => { + procs.insert(pid, stat); + } + StatRead::Gone => {} + StatRead::Failed => complete = false, + } + } let mut children: HashMap> = HashMap::new(); let mut peers: HashMap> = HashMap::new(); for (&pid, s) in &procs { @@ -372,9 +444,16 @@ mod os { procs, children, peers, + complete, } } + /// Whether every process was listed and read. A snapshot that is not + /// complete can miss live processes. + pub(super) fn complete(&self) -> bool { + self.complete + } + pub(super) fn start(&self, pid: i32) -> Option { self.procs.get(&pid).map(|s| s.start) } @@ -408,23 +487,37 @@ mod os { } /// A scan that began at or after `not_before` and less than - /// `max_age` ago, taking one if there is none. + /// `max_age` before `now`, taking one if there is none. A scan that + /// is not complete is returned to its caller but not kept, so the + /// next reader takes a fresh one. pub(super) fn snapshot( &self, leader: i32, tty: &mut Option, not_before: Instant, + ) -> Arc { + self.snapshot_at(Instant::now(), not_before, || Snapshot::take(leader, tty)) + } + + /// [`Shared::snapshot`] with the time and the scan supplied, so the + /// age limit can be tested exactly. + pub(super) fn snapshot_at( + &self, + now: Instant, + not_before: Instant, + take: impl FnOnce() -> Snapshot, ) -> Arc { let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); if let Some((began, snap)) = &*last { - if *began >= not_before && began.elapsed() < self.max_age { + if *began >= not_before && now.saturating_duration_since(*began) < self.max_age { return Arc::clone(snap); } } - let began = Instant::now(); - let snap = Arc::new(Snapshot::take(leader, tty)); + let snap = Arc::new(take()); self.scans.fetch_add(1, Ordering::Relaxed); - *last = Some((began, Arc::clone(&snap))); + if snap.complete() { + *last = Some((now, Arc::clone(&snap))); + } snap } @@ -618,7 +711,7 @@ mod tests { #[cfg(target_os = "linux")] mod linux { use super::*; - use os::{parse_stat, Reader, Snapshot}; + use os::{parse_stat, Reader, Snapshot, StatRead}; /// A stat line with `comm` between the parentheses; the fields after /// it are state, ppid 10, pgrp 20, session 30, then filler up to @@ -814,6 +907,88 @@ mod tests { assert_eq!(shared.scans(), 1); } + /// The snapshot is reused just before `SNAPSHOT_MAX_AGE` and replaced + /// at it. The window is 250 ms; a doubled constant fails here. + #[test] + fn a_snapshot_is_reused_until_the_age_limit_and_no_longer() { + assert_eq!(SNAPSHOT_MAX_AGE, Duration::from_millis(250)); + let shared = Shared::new(); + let t0 = Instant::now(); + let not_before = t0 - Duration::from_secs(60); + let first = shared + .0 + .snapshot_at(t0, not_before, || Snapshot::of(std::iter::empty())); + let before_limit = + shared + .0 + .snapshot_at(t0 + Duration::from_millis(249), not_before, || { + Snapshot::of(std::iter::empty()) + }); + assert!(std::sync::Arc::ptr_eq(&first, &before_limit)); + let at_limit = shared.0.snapshot_at(t0 + SNAPSHOT_MAX_AGE, not_before, || { + Snapshot::of(std::iter::empty()) + }); + assert!(!std::sync::Arc::ptr_eq(&first, &at_limit)); + assert_eq!(shared.scans(), 2); + } + + /// Eight panes, each polling every 250 ms from its own phase, take one + /// scan per 250 ms window: exactly six in 1.5 s. A doubled window + /// gives three. + #[test] + fn eight_pollers_take_exactly_one_scan_per_window() { + let shared = Shared::with_max_age(SNAPSHOT_MAX_AGE); + let t0 = Instant::now(); + let not_before = t0 - Duration::from_secs(60); + let mut polls: Vec = (0..8u64) + .flat_map(|pane| (0..6u64).map(move |k| Duration::from_millis(pane * 31 + 250 * k))) + .collect(); + polls.sort(); + for at in polls { + shared + .0 + .snapshot_at(t0 + at, not_before, || Snapshot::of(std::iter::empty())); + } + assert_eq!(shared.scans(), 6); + } + + /// A degraded scan (a read failed, here every read) is handed to its + /// caller but not kept, so the next reader takes a fresh scan. + #[test] + fn a_degraded_snapshot_is_not_cached() { + let shared = Shared::with_max_age(Duration::from_secs(3600)); + let t0 = Instant::now(); + let not_before = t0 - Duration::from_secs(60); + let degraded = shared.0.snapshot_at(t0, not_before, || { + Snapshot::build(std::iter::empty(), false, |_| StatRead::Failed) + }); + assert!(!degraded.complete()); + let next = shared + .0 + .snapshot_at(t0, not_before, || Snapshot::of(std::iter::empty())); + assert!(next.complete()); + assert_eq!(shared.scans(), 2); + } + + /// A failed read (out of file descriptors, say) cannot tell a gone + /// member from an unread one, so a degraded snapshot prunes nothing: + /// two panes keep every member they had. + #[test] + fn a_degraded_snapshot_prunes_no_pane_member() { + let fx = Fixture::new("procs-degraded"); + let mut first = Tree::default(); + let mut second = Tree::default(); + assert_eq!(first.refresh(fx.pid()), 4); + assert_eq!(second.refresh(fx.pid()), 4); + let before = sorted(&first); + let degraded = Snapshot::build(fx.members.iter().copied(), true, |_| StatRead::Failed); + assert!(!degraded.complete()); + assert_eq!(first.apply(fx.pid(), °raded), 0); + assert_eq!(second.apply(fx.pid(), °raded), 0); + assert_eq!(sorted(&first), before); + assert_eq!(sorted(&second), before); + } + /// On the fixture the snapshot answers with the known tree: three /// children of the leader (one in another session), and the leader /// and three more in its group and session (the grandchild sleep, diff --git a/src/native/host/tests_scan.rs b/src/native/host/tests_scan.rs index c11a974..bf4a99d 100644 --- a/src/native/host/tests_scan.rs +++ b/src/native/host/tests_scan.rs @@ -59,7 +59,13 @@ fn a_stop_scans_afresh_and_ends_a_child_the_shared_snapshot_missed() { } /// Eight panes polling for descendants cost about one scan per tick, not -/// eight. +/// eight. The exact count (one scan per 250 ms window) is pinned by +/// `eight_pollers_take_exactly_one_scan_per_window` in `procs.rs`, where the +/// clock is supplied. Real pane readers wake every 200 ms, so their looks +/// land where the scheduler and the wake grid put them: panes started +/// together cluster and gave 3 scans in 1.5 s. The hard limit is one scan per +/// window, at most 7 in 1.5 s. Zero scans (no periodic look) and about 48 (no +/// sharing) both fail. #[test] fn eight_panes_share_one_scan_per_tick() { let host = Arc::new(LocalHost::new()); @@ -70,8 +76,10 @@ fn eight_panes_share_one_scan_per_tick() { let before = host.scans(); std::thread::sleep(Duration::from_millis(1500)); let taken = host.scans() - before; - // About 6 ticks; one scan per pane per tick would be about 48. - assert!(taken <= 14, "{taken} scans in 1.5 s for 8 panes"); + assert!( + (2..=7).contains(&taken), + "{taken} scans in 1.5 s for 8 panes, expected 2 to 7 (at most one per 250 ms window)" + ); for pane in &panes { host.kill(&pane.id, Duration::from_secs(2)).unwrap(); } From aeb7fc2f88ebb3a99e28be372cf2f565e1a0254d Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Wed, 18 Nov 2026 17:19:37 -0500 Subject: [PATCH 4/6] fix: treat unparseable stat lines as failed reads and align docs with the window A /proc stat line that cannot be parsed is now a failed read, so the snapshot is incomplete and keeps the member. Before, it was read as an exited process, and a complete snapshot could drop a live member. A zombie or exited process is still treated as gone. Items addressed (from the bot review on the previous head): - Unparseable stat line: parse_stat returns Result; an error maps to StatRead::Failed. Test: an_unparseable_line_is_a_failed_read_not_a_gone_process. - README: the periodic-look and fast-escape passages state the Linux nominal and worst-case bounds and the macOS bound. - docs/operations.md: the snapshot memory grows with the host process count, and a degraded scan keeps every member it cannot check. - Real-PTY scan count: the test asserts 1 to 7 scans in 1.5 s (at most one per 250 ms window). The exact count stays in eight_pollers_take_exactly_one_scan_per_window. - CHANGELOG: removed the uncontrolled CPU figures. - Not changed: readers queue on the shared lock when a scan is incomplete or takes longer than 250 ms. Reusing an incomplete snapshot would reverse the approved degraded-scan rule, so this is recorded as a follow-up. Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings; cargo test --locked): - macOS build host: 1019 passed, 0 failed, 6 ignored (12 test binaries) - Linux build host: 1040 passed, 0 failed, 6 ignored (12 test binaries) Refs #3 --- CHANGELOG.md | 10 +++---- README.md | 11 +++++-- docs/operations.md | 10 +++++-- src/native/host/procs.rs | 56 ++++++++++++++++++++++++----------- src/native/host/tests_scan.rs | 4 +-- 5 files changed, 61 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d086a9f..cdf32a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,11 @@ refused. Fixtures for the new-file write, web fetch and web search keys and the wrapped shell dialogs are added under `tests/fixtures/kiro-3.3.0/`. - Native panes (Linux): the holder reads the process table once per 250 ms for all its panes, - not once per pane, so idle CPU for eight panes drops from about 14.9 % to about 1.9 %. The - cost is detection latency. A descendant that detaches with `setsid` and whose parents exit is - now seen within about 500 ms nominal and at most about 700 ms (it was about 250 ms nominal). - On macOS the bound stays about 450 ms. Stops still read the table afresh, and a failed read - never removes a process from a pane's tree. + not once per pane, so idle CPU for eight panes drops. The cost is detection latency. A + descendant that detaches with `setsid` and whose parents exit is now seen within about 500 ms + nominal and at most about 700 ms (it was about 250 ms nominal). On macOS the bound stays about + 450 ms. Stops still read the table afresh, and a failed read never removes a process from a + pane's tree. - Native panes: a process whose command name is not valid UTF-8 is now tracked. Before, it escaped the descendant tree, so `remove_pane` and shutdown did not signal it. They now do. diff --git a/README.md b/README.md index defd0a7..0357072 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,10 @@ which answers a permission dialog may receive. - **Process-tree cleanup.** `remove_pane`, a program's own exit and Shepherd's shutdown signal the pane's process group and every descendant Shepherd has seen, then kill what is left. Descendants are found by looking at the process table - about every 250 ms, so a process that fully detaches faster than that is missed + about every 250 ms (up to about 450 ms apart), so a process that fully detaches + before the next look is missed. On Linux a look may use a snapshot up to 250 ms + old: a descendant is seen within about 500 ms nominal and at most about 700 ms. + On macOS the bound is about 450 ms (see [Status and known limits](#status-and-known-limits)). - **Container image.** The `Dockerfile` builds a Debian image that runs as uid 1000 under tini, with kiro-cli pinned to 3.3.0 (the version the Kiro dialog parser was measured on) and checked against a SHA-256. The image @@ -220,8 +223,10 @@ is in [docs/adr/restart-survival-and-shared-panes.md](docs/adr/restart-survival- `deny_once` is answered with Esc; `allow_once` presses Enter only when the styled screen cells show `Allow once` with a background that differs from the other two options, which match each other. - **A fast detached descendant escapes cleanup.** A descendant that is re-parented - and fully detaches (new session, no terminal, parents gone) within the 250 ms - between looks at the process table is never seen and survives. macOS has no + and fully detaches (new session, no terminal, parents gone) before the first look + at the process table that would see it is never seen and survives. That look comes + within about 500 ms nominal and at most about 700 ms on Linux, and about 450 ms on + macOS. macOS has no unprivileged way to close this gap. On Linux the holder is deliberately not a subreaper; an orphan that escapes the scan is reaped by PID 1 (tini in the image). - **Panes survive a server restart only under `hold`.** A bare `openab-shepherd` owns diff --git a/docs/operations.md b/docs/operations.md index a635bc6..9a419fc 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -807,9 +807,13 @@ Pane ids are `n:` panes, and a pane may use a read up to 250 ms old. A look is nominally every 250 ms, and up to about 450 ms apart because the reader wakes every 200 ms. So a descendant is seen within about 500 ms nominal and at most about 700 ms (see - Known limits). A stop always reads it afresh. Removing a pane (`remove_pane`) - and Shepherd's exit on SIGINT, SIGTERM or SIGHUP send SIGHUP and SIGTERM to the - group and the descendants, wait + Known limits). A stop always reads it afresh. The snapshot lists every process + on the host, so its memory grows with the host's process count (about 0.9 MiB + more than the base at 302 processes). A scan that cannot read every process is + not kept, and it prunes nothing: under a lasting read failure a tree keeps a + member until a complete scan no longer lists it. Each signal still re-checks the + start time. Removing a pane (`remove_pane`) and Shepherd's exit on SIGINT, + SIGTERM or SIGHUP send SIGHUP and SIGTERM to the group and the descendants, wait up to 2 s (for `remove_pane`, its `timeout`), then stop (SIGSTOP) the group and descendants until no new one appears and SIGKILL them all. When the program exits on its own, what it left behind gets the same treatment at once. The leader stays diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index 5aed927..770397f 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -286,32 +286,34 @@ mod os { std::str::from_utf8(token).ok()?.parse().ok() } - /// The fields of one `/proc//stat` line, or None for a zombie, a - /// dead process, or a line that is cut short. Read in place: no - /// allocation. Bytes, not text, so a command name that is not UTF-8 - /// does not hide the process. - pub(super) fn parse_stat(line: &[u8]) -> Option { + /// The fields of one `/proc//stat` line: `Ok(Some)` for a process, + /// `Ok(None)` for a zombie or dead one, and `Err` for a line that is not + /// a stat line (cut short or malformed). Read in place: no allocation. + /// Bytes, not text, so a command name that is not UTF-8 does not hide the + /// process. + pub(super) fn parse_stat(line: &[u8]) -> Result, ()> { // The command name may hold spaces and parentheses: fields start // after the last ')'. - let rest = &line[line.iter().rposition(|&b| b == b')')? + 1..]; - let mut fields = rest + let after = line.iter().rposition(|&b| b == b')').ok_or(())?; + let mut fields = line[after + 1..] .split(|b| b.is_ascii_whitespace()) .filter(|field| !field.is_empty()); // The first field is field 3 of proc(5): state, ppid, pgrp, session, // ..., starttime (field 22, the 16th field after session). - if matches!(fields.next()?, b"Z" | b"X") { - return None; + let state = fields.next().ok_or(())?; + if matches!(state, b"Z" | b"X") { + return Ok(None); } - let ppid = int(fields.next()?)?; - let pgrp = int(fields.next()?)?; - let session = int(fields.next()?)?; - let start = int(fields.nth(15)?)?; - Some(Stat { + let ppid = int(fields.next().ok_or(())?).ok_or(())?; + let pgrp = int(fields.next().ok_or(())?).ok_or(())?; + let session = int(fields.next().ok_or(())?).ok_or(())?; + let start = int(fields.nth(15).ok_or(())?).ok_or(())?; + Ok(Some(Stat { ppid, pgrp, session, start, - }) + })) } /// What one read of `/proc//stat` found. `Gone` is normal (the @@ -340,7 +342,12 @@ mod os { } self.buf.clear(); match File::open(&self.path).and_then(|mut f| f.read_to_end(&mut self.buf)) { - Ok(_) => parse_stat(&self.buf).map_or(StatRead::Gone, StatRead::Stat), + Ok(_) if self.buf.is_empty() => StatRead::Gone, + Ok(_) => match parse_stat(&self.buf) { + Ok(Some(stat)) => StatRead::Stat(stat), + Ok(None) => StatRead::Gone, + Err(()) => StatRead::Failed, + }, Err(err) if matches!(err.raw_os_error(), Some(libc::ENOENT | libc::ESRCH)) => { StatRead::Gone } @@ -729,7 +736,22 @@ mod tests { } fn fields(bytes: &[u8]) -> Option<(i32, i32, i32, u64)> { - parse_stat(bytes).map(|s| (s.ppid, s.pgrp, s.session, s.start)) + parse_stat(bytes) + .ok() + .flatten() + .map(|s| (s.ppid, s.pgrp, s.session, s.start)) + } + + /// A zombie is gone; a line that is not a stat line is an unreadable + /// process, so the snapshot is incomplete and keeps its members. + #[test] + fn an_unparseable_line_is_a_failed_read_not_a_gone_process() { + assert!(matches!(parse_stat(&line(7, b"z", "Z")), Ok(None))); + assert!(matches!( + parse_stat(b"7 (sleep) S x 20 30 1 2 3 4 5 6 7 8 9 10 11 12 13 4242"), + Err(()) + )); + assert!(matches!(parse_stat(b""), Err(()))); } #[test] diff --git a/src/native/host/tests_scan.rs b/src/native/host/tests_scan.rs index bf4a99d..dd50269 100644 --- a/src/native/host/tests_scan.rs +++ b/src/native/host/tests_scan.rs @@ -77,8 +77,8 @@ fn eight_panes_share_one_scan_per_tick() { std::thread::sleep(Duration::from_millis(1500)); let taken = host.scans() - before; assert!( - (2..=7).contains(&taken), - "{taken} scans in 1.5 s for 8 panes, expected 2 to 7 (at most one per 250 ms window)" + (1..=7).contains(&taken), + "{taken} scans in 1.5 s for 8 panes, expected 1 to 7 (at most one per 250 ms window)" ); for pane in &panes { host.kill(&pane.id, Duration::from_secs(2)).unwrap(); From 4f56bc1a2f60ec433d39530bf50b041dca2531e1 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Wed, 18 Nov 2026 18:33:08 -0500 Subject: [PATCH 5/6] fix: scan failures prune nothing, exact scan count, precise Linux bound Fixes for the second council pass on aeb7fc2. - Degraded scans: Snapshot::take reads through take_in(root). Two new Linux tests make a real failure: a listing that cannot be read, and a stat path that cannot be read (EISDIR). Both leave the snapshot incomplete, and both prune no pane member. - Exact scan count: eight_panes_share_one_scan_per_tick replays every look the real pane readers made against the rule of one scan per 250 ms window (a literal, so changing SNAPSHOT_MAX_AGE fails it), and asserts the scan count that rule predicts for those looks. The 700 ms sleep before counting is gone, so the pane-creation burst is measured. - Linux bound: docs/adr/native-core.md, docs/operations.md, README.md and CHANGELOG.md state the about 700 ms worst case with its condition: each scan must finish within the 250 ms age limit. A longer scan, or a wait on the shared lock, adds its own time. The nominal figure is 500 ms. The bare "nominal" wording is replaced with the stated bound. - Shared::snapshot doc comment: an incomplete scan does not replace an older complete one, so a reader may still reuse that older one. - CHANGELOG: a process whose command name is not valid UTF-8 is now trackable, so it is found and signalled on stop. - Left unchanged: the leader and tty parameters of the Linux Snapshot::take. The signature is shared with macOS, where both are used. Tests (cargo fmt --check; cargo clippy --locked --all-targets -- -D warnings; cargo test --locked --no-fail-fast): - macOS build host: 1019 passed, 0 failed, 6 ignored. - Linux build host: 1042 passed, 0 failed, 6 ignored. Refs #3 --- CHANGELOG.md | 8 +- README.md | 11 ++- docs/adr/native-core.md | 6 +- docs/operations.md | 26 ++--- src/native/host/local.rs | 6 ++ src/native/host/procs.rs | 172 +++++++++++++++++++++++++++++----- src/native/host/tests_scan.rs | 54 ++++++++--- 7 files changed, 223 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cdf32a7..e4dbffa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,11 @@ - Native panes (Linux): the holder reads the process table once per 250 ms for all its panes, not once per pane, so idle CPU for eight panes drops. The cost is detection latency. A descendant that detaches with `setsid` and whose parents exit is now seen within about 500 ms - nominal and at most about 700 ms (it was about 250 ms nominal). On macOS the bound stays about - 450 ms. Stops still read the table afresh, and a failed read never removes a process from a + in the nominal case, and at most about 700 ms provided each scan finishes within 250 ms (it was + about 250 ms nominal). On macOS the bound stays about 450 ms. Stops still read the table afresh, and a failed read never removes a process from a pane's tree. -- Native panes: a process whose command name is not valid UTF-8 is now tracked. Before, it - escaped the descendant tree, so `remove_pane` and shutdown did not signal it. They now do. +- Native panes: a process whose command name is not valid UTF-8 is now trackable, so it is found + and, on `remove_pane` or shutdown, signalled. Before, it escaped the descendant tree and survived. ## 0.5.0 diff --git a/README.md b/README.md index 0357072..e491303 100644 --- a/README.md +++ b/README.md @@ -78,10 +78,11 @@ which answers a permission dialog may receive. - **Process-tree cleanup.** `remove_pane`, a program's own exit and Shepherd's shutdown signal the pane's process group and every descendant Shepherd has seen, then kill what is left. Descendants are found by looking at the process table - about every 250 ms (up to about 450 ms apart), so a process that fully detaches + about every 250 ms (at most about 450 ms apart), so a process that fully detaches before the next look is missed. On Linux a look may use a snapshot up to 250 ms - old: a descendant is seen within about 500 ms nominal and at most about 700 ms. - On macOS the bound is about 450 ms + old: a descendant is seen within about 500 ms in the nominal case, and at most + about 700 ms provided each scan finishes within 250 ms. On macOS the bound is + about 450 ms (see [Status and known limits](#status-and-known-limits)). - **Container image.** The `Dockerfile` builds a Debian image that runs as uid 1000 under tini, with kiro-cli pinned to 3.3.0 (the version the Kiro dialog parser was measured on) and checked against a SHA-256. The image @@ -225,8 +226,8 @@ is in [docs/adr/restart-survival-and-shared-panes.md](docs/adr/restart-survival- - **A fast detached descendant escapes cleanup.** A descendant that is re-parented and fully detaches (new session, no terminal, parents gone) before the first look at the process table that would see it is never seen and survives. That look comes - within about 500 ms nominal and at most about 700 ms on Linux, and about 450 ms on - macOS. macOS has no + within about 500 ms in the nominal case, and at most about 700 ms on Linux + provided each scan finishes within 250 ms, and about 450 ms on macOS. macOS has no unprivileged way to close this gap. On Linux the holder is deliberately not a subreaper; an orphan that escapes the scan is reaped by PID 1 (tini in the image). - **Panes survive a server restart only under `hold`.** A bare `openab-shepherd` owns diff --git a/docs/adr/native-core.md b/docs/adr/native-core.md index b799415..84d73f0 100644 --- a/docs/adr/native-core.md +++ b/docs/adr/native-core.md @@ -258,7 +258,7 @@ PaneState { vt: vt100::Parser, status, reported, turn, status_ms, **Reader thread** (one per pane). It loops: - `poll(master, POLLIN, 200 ms)`; on each wake it checks `shutdown`. `shutdown` is set only after the leader has been reaped (§11), so the terminal is drained for as long as any pane process may still be exiting. -- Every 250 ms (`TREE_POLL`, nominal: looks are up to about 450 ms apart, see the known limit under "Descendant tree"), while the leader runs, it refreshes the descendant tree with `tree.try_lock()` (a stop in progress holds the tree; the reader must not block on it, or it would stop draining). On Linux that refresh may use the holder-wide process-table snapshot, up to `SNAPSHOT_MAX_AGE` (250 ms) old; a stop never does. +- Every 250 ms (`TREE_POLL`; the reader wakes every 200 ms, so a look comes at most about 450 ms after the previous one, see the known limit under "Descendant tree"), while the leader runs, it refreshes the descendant tree with `tree.try_lock()` (a stop in progress holds the tree; the reader must not block on it, or it would stop draining). On Linux that refresh may use the holder-wide process-table snapshot, up to `SNAPSHOT_MAX_AGE` (250 ms) old; a stop never does. - It reads up to 16 KiB. - `read` returning 0 or `EIO` means the slave side has closed, and the thread exits its loop. `EAGAIN` or `EINTR` means retry. Any other error is logged once (`native: : read failed: `) and ends the loop. - For each chunk, under `state`: @@ -356,9 +356,9 @@ Nothing else passes, by construction (`env_clear()` first). In particular, `OPEN - **Removal failures:** `NotFound` for an unknown ref. If `kill` on the group fails with an error other than ESRCH, it is logged at warn level and removal still completes; EPERM after the leader has exited is not logged, because macOS answers EPERM for a group left with only its zombie leader (measured). - **Descendant tree (issue #10).** Measured on macOS with main `b446018`: kiro-cli starts `bun`, which starts `node …/acp-server.js` in a new session (`ps` STAT `Ss` without `+`: it called `setsid`, so it is a session and group leader with no controlling terminal; Node's `detached: true`). It is found only by the parent-pid walk from `bun`, never through the pane's group or terminal. Killing the pane's group never reached it, and after a pane ended it lived on with ppid 1 for over an hour. `procs::Tree` (in `src/native/procs.rs`) records every descendant as `(pid, start time)`: - **Found by** parent pid, from the leader and from every member still alive (a breadth-first walk), and by membership of the leader's group and session: on Linux, `/proc//stat` fields `ppid`, `pgrp`, `session` and `starttime`, from one scan of `/proc`; on macOS, `proc_listchildpids`, `proc_listpgrppids`, and `proc_listpids(PROC_TTY_ONLY, tdev)` with the leader's controlling terminal (`proc_bsdinfo.e_tdev`; macOS has no list-by-session call, and every process of the session has that terminal while the leader runs), with the start time from `proc_pidinfo(PROC_PIDTBSDINFO)` (`pbi_start_tvsec`/`usec`). - - **Refreshed** every 250 ms (nominal) by the reader while the leader runs, and at the start of every soft and hard stop. A scan that could not read every process is neither cached nor allowed to prune: the tree keeps its members. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. + - **Refreshed** by the reader while the leader runs, at most about 450 ms between looks (target 250 ms, see the known limit), and at the start of every soft and hard stop. A scan that could not read every process is neither cached nor allowed to prune: the tree keeps its members. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. - **Signalled** only after re-reading the pid's start time and finding it unchanged. A reused pid has a later start time and is skipped. The check and the `kill` are a few microseconds apart; a pid is reused only after the pid space wraps, so a reuse inside that window is not a practical risk. Zombies are skipped (Linux state `Z`/`X`; macOS does not answer `proc_pidinfo` for zombies). Shepherd's own pid and pids 0 and 1 are never members. - - **Known limit (owner decision after review):** a descendant that is re-parented and fully detaches before the first look that would see it is not seen: it calls `setsid` (no group, session or terminal link to the pane) and every ancestor between it and a known member exits first, as in a daemon's double fork. That look comes within about 700 ms of the fork on Linux (a snapshot up to 250 ms old, plus looks up to about 450 ms apart because the reader wakes every 200 ms; the nominal figure is 500 ms) and within about 450 ms on macOS, which caches nothing. It survives removal, the program's own exit, shutdown and drop. One that only changes its process group is still found through the session (macOS: the terminal) while the leader runs, and one whose parent lives until the next look is found by the parent-pid walk. Measured on macOS 15.7 (remote build host, a C probe with a `setsid` double fork): kqueue `EVFILT_PROC` with `NOTE_TRACK` is refused with `EV_ERROR`, data 45 (`ENOTSUP`); every process inherits its parent's coalition ids (`PROC_PIDCOALITIONINFO`), but creating a coalition needs root, so a pane cannot get its own; macOS has no subreaper and no cgroup; `p_puniqueid` (`PROC_PIDUNIQIDENTIFIERINFO`) survives the reparent to pid 1, but it names the intermediate that was never seen, so the chain stays broken. No public unprivileged macOS mechanism closes the gap. Linux can close it with `PR_SET_CHILD_SUBREAPER` in a per-pane supervisor; that is a follow-up to build and test with a Linux build. + - **Known limit (owner decision after review):** a descendant that is re-parented and fully detaches before the first look that would see it is not seen: it calls `setsid` (no group, session or terminal link to the pane) and every ancestor between it and a known member exits first, as in a daemon's double fork. On Linux that look comes at most about 700 ms after the fork, provided each scan finishes within the 250 ms snapshot age: a snapshot up to 250 ms old, plus looks at most about 450 ms apart because the reader wakes every 200 ms. A scan that runs longer, or a look that waits on another pane's scan under the shared lock, adds its own time to that bound. The nominal figure is 500 ms (250 ms snapshot age plus a 250 ms look interval). On macOS the bound is about 450 ms, because macOS caches nothing. It survives removal, the program's own exit, shutdown and drop. One that only changes its process group is still found through the session (macOS: the terminal) while the leader runs, and one whose parent lives until the next look is found by the parent-pid walk. Measured on macOS 15.7 (remote build host, a C probe with a `setsid` double fork): kqueue `EVFILT_PROC` with `NOTE_TRACK` is refused with `EV_ERROR`, data 45 (`ENOTSUP`); every process inherits its parent's coalition ids (`PROC_PIDCOALITIONINFO`), but creating a coalition needs root, so a pane cannot get its own; macOS has no subreaper and no cgroup; `p_puniqueid` (`PROC_PIDUNIQIDENTIFIERINFO`) survives the reparent to pid 1, but it names the intermediate that was never seen, so the chain stays broken. No public unprivileged macOS mechanism closes the gap. Linux can close it with `PR_SET_CHILD_SUBREAPER` in a per-pane supervisor; that is a follow-up to build and test with a Linux build. - **Alternatives considered.** (a) Signal only the group or session: misses `setsid` children, and neither kernel has kill-by-session. (b) Snapshot the tree only at stop time: misses a descendant whose parent already exited (the measured orphan), so tracking is required. (c) Linux `PR_SET_CHILD_SUBREAPER` would reparent orphans to Shepherd, but macOS has no equivalent and Shepherd would then have to reap foreign children; one mechanism on both platforms is simpler to test. (d) A per-pane cgroup (Linux) or job object does not exist on macOS. (e) pidfds would close the check-to-kill window on Linux only; not worth a second code path given (c). - **The zombie and the lost exit code (issue #10).** Measured: `remove_pane` on Kiro returned `stopped: killed, exit_code: null`, and the leader stayed `?Es` (exiting, not yet a zombie) with Shepherd as parent. Cause: removal set `shutdown` first, so the reader stopped reading the master. A process that exits with output still queued on its terminal waits in the tty close for it to drain; with the master open and unread, the leader stayed in that state (`?Es`, measured on macOS) and never finished exiting, so `waitid` never returned and no code was recorded. The same unread output is why Kiro, which writes as it restores the terminal, did not exit within the 2 s grace. Fix: the reader drains until the leader is reaped (`shutdown` is set after), and every stop path waits for the reaper. Reproduced in `cargo test` before the fix with `trap '' HUP TERM; exec yes` (killed, `exit_code: None`, `ps` showed `?Es`) and with a shell that writes 400 KB on SIGHUP (killed instead of exiting with its code). - **Graceful stop for Kiro (decided).** SIGHUP and SIGTERM with the output drained, no keystrokes. Typing `/quit` would need Kiro to be idle and not in a dialog, and would put text into a pane the caller may not expect; Ctrl-D/Esc have the same problem (`interrupt_pane` exists for a clean turn end). Measured with `examples/native_leak_check` on a developer machine (kiro-cli 3.1.0): with the drain fix kiro-cli exited on the signals in 148 to 269 ms with code 1 in 4 of 5 runs (one of them with a 15 s grace); in the other it had not exited after 2 s and was killed (137, reaped, none of its processes left). Callers who want more time pass `remove_pane`'s `timeout`. diff --git a/docs/operations.md b/docs/operations.md index 9a419fc..09fe054 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -800,14 +800,15 @@ Pane ids are `n:` `OPENAB_SHEPHERD_BACKEND` and everything else never reach a child. Shepherd's own descriptors are close-on-exec and native spawns are serialized, so one pane's terminal does not reach another pane. Shepherd does not sweep descriptors inherited from its parent; launch it with a clean descriptor table. - **Process groups and descendants.** Each child is a session and group leader with the PTY as its controlling terminal. Shepherd also tracks every descendant of the - child, by pid and start time: by parent pid every 250 ms while the child runs and - again before any stop, and by membership of the child's group and session. So a - descendant that moves to its own group or session, or whose parent exits, is - still known. On Linux the periodic look reads the process table once for all - panes, and a pane may use a read up to 250 ms old. A look is nominally every - 250 ms, and up to about 450 ms apart because the reader wakes every 200 ms. So a - descendant is seen within about 500 ms nominal and at most about 700 ms (see - Known limits). A stop always reads it afresh. The snapshot lists every process + child, by pid and start time: by parent pid at each periodic look while the child + runs (every 250 ms as the target; at most about 450 ms apart because the reader + wakes every 200 ms) and again before any stop, and by membership of the child's + group and session. So a descendant that moves to its own group or session, or + whose parent exits, is still known. On Linux the periodic look reads the process + table once for all panes, and a look may use a read up to 250 ms old. A + descendant is seen within about 500 ms in the nominal case, and at most about + 700 ms provided each scan finishes within the 250 ms age limit (see Known + limits). A stop always reads it afresh. The snapshot lists every process on the host, so its memory grows with the host's process count (about 0.9 MiB more than the base at 302 processes). A scan that cannot read every process is not kept, and it prunes nothing: under a lasting read failure a tree keeps a @@ -821,8 +822,9 @@ Pane ids are `n:` cannot be reused while Shepherd signals by it; a descendant is signalled only while its pid still has the recorded start time. Known limit: a descendant that is re-parented and fully detaches (new session, no terminal) before the first - look that would see it (within about 700 ms of its fork on Linux, about 450 ms - on macOS; see Known limits) is never seen and survives + look that would see it (at most about 700 ms after its fork on Linux, provided + each scan finishes within 250 ms; about 450 ms on macOS; see Known limits) is + never seen and survives (see Known limits). If Shepherd is killed with SIGKILL, children get only the PTY hangup. - **Status.** OSC 7501 reports from the program are parsed in the emulator's @@ -1660,8 +1662,8 @@ try to update itself at run time). - **Native: a fast daemon escapes.** A descendant that is re-parented and fully detaches (calls `setsid`, so it has no group, session or terminal link to the pane, and its parents exit) before the first look that would see it, is never - seen. That look comes within about 700 ms of the fork on Linux and about 450 ms - on macOS. It survives `remove_pane`, the program's own exit, + seen. That look comes at most about 700 ms after the fork on Linux, provided each + scan finishes within 250 ms, and about 450 ms on macOS. It survives `remove_pane`, the program's own exit, and Shepherd's shutdown. One that only changes process group, or stays under a live parent until the next look, is ended (issue #10). macOS offers no unprivileged way to close this: kqueue `NOTE_TRACK` answers `ENOTSUP`, only root diff --git a/src/native/host/local.rs b/src/native/host/local.rs index ec742ac..59ac7c3 100644 --- a/src/native/host/local.rs +++ b/src/native/host/local.rs @@ -189,6 +189,12 @@ impl LocalHost { self.scans.scans() } + /// Test hook: every periodic look at the shared snapshot, in order. + #[cfg(all(test, target_os = "linux"))] + pub(crate) fn scan_requests(&self) -> Vec { + self.scans.requests() + } + /// With a tail kept, make room for one more finished pane: forget the /// oldest finished ones beyond the backstop. fn evict_finished(&self) { diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index 770397f..a8bfb26 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -28,6 +28,9 @@ pub(crate) const SNAPSHOT_MAX_AGE: Duration = Duration::from_millis(250); /// process: a pid that is reused gets a later start time. pub(crate) type Start = u64; +#[cfg(all(test, target_os = "linux"))] +pub(crate) use os::Request; + /// The pane's known descendants (the leader itself is not a member). #[derive(Default)] pub(crate) struct Tree { @@ -138,6 +141,12 @@ impl Shared { pub(crate) fn scans(&self) -> usize { self.0.scans() } + + /// Every request this has answered, in order, and whether each scanned. + #[cfg(all(test, target_os = "linux"))] + pub(crate) fn requests(&self) -> Vec { + self.0.requests() + } } /// Signal `pid` only if it is still the process that started at `start`. @@ -275,6 +284,9 @@ mod os { use std::sync::{Arc, Mutex, PoisonError}; use std::time::{Duration, Instant}; + /// The root of the process table on Linux. + const PROC: &str = "/proc"; + pub(super) struct Stat { pub(super) ppid: i32, pub(super) pgrp: i32, @@ -326,18 +338,33 @@ mod os { Failed, } - /// Reads `/proc//stat` into a path and a buffer it keeps, so a scan + /// Reads `//stat` into a path and a buffer it keeps, so a scan /// of every process allocates once, not once per process. - #[derive(Default)] pub(super) struct Reader { + root: String, path: String, buf: Vec, } + impl Default for Reader { + fn default() -> Self { + Self::in_root(PROC) + } + } + impl Reader { + /// A reader over another table with the same layout: a test seam. + pub(super) fn in_root(root: &str) -> Self { + Self { + root: root.to_owned(), + path: String::new(), + buf: Vec::new(), + } + } + pub(super) fn read(&mut self, pid: i32) -> StatRead { self.path.clear(); - if write!(self.path, "/proc/{pid}/stat").is_err() { + if write!(self.path, "{}/{pid}/stat", self.root).is_err() { return StatRead::Failed; } self.buf.clear(); @@ -386,10 +413,16 @@ mod os { impl Snapshot { /// Scans `/proc`. The leader and the tty are not used on Linux, so /// the result serves every pane. - pub(super) fn take(_leader: i32, _tty: &mut Option) -> Self { + pub(super) fn take(leader: i32, tty: &mut Option) -> Self { + Self::take_in(PROC, leader, tty) + } + + /// [`Snapshot::take`] over the table at `root`. A listing that + /// cannot be read makes the snapshot incomplete, not empty. + pub(super) fn take_in(root: &str, _leader: i32, _tty: &mut Option) -> Self { let mut listed = true; let mut pids = Vec::new(); - match std::fs::read_dir("/proc") { + match std::fs::read_dir(root) { Ok(entries) => { for entry in entries { match entry { @@ -408,7 +441,7 @@ mod os { } Err(_) => listed = false, } - let mut reader = Reader::default(); + let mut reader = Reader::in_root(root); Self::build(pids, listed, |pid| reader.read(pid)) } @@ -475,13 +508,26 @@ mod os { } } - /// The newest scan and when it began. One scan serves every reader that - /// asks within `max_age`; the lock is held across the scan, so readers - /// that arrive meanwhile wait for it instead of each taking their own. + /// One request to [`Shared::snapshot_at`] and what it decided. + #[cfg(test)] + #[derive(Clone, Copy)] + pub(crate) struct Request { + pub(crate) at: Instant, + pub(crate) not_before: Instant, + pub(crate) scanned: bool, + } + + /// The newest complete scan and when it began. One scan serves every + /// reader that asks within `max_age`; the lock is held across the scan, + /// so readers that arrive meanwhile wait for it instead of each taking + /// their own. pub(super) struct Shared { max_age: Duration, last: Mutex)>>, scans: AtomicUsize, + /// Every request in order, for the exact-count test. + #[cfg(test)] + requests: Mutex>, } impl Shared { @@ -490,13 +536,16 @@ mod os { max_age, last: Mutex::new(None), scans: AtomicUsize::new(0), + #[cfg(test)] + requests: Mutex::new(Vec::new()), } } - /// A scan that began at or after `not_before` and less than - /// `max_age` before `now`, taking one if there is none. A scan that - /// is not complete is returned to its caller but not kept, so the - /// next reader takes a fresh one. + /// A complete scan that began at or after `not_before` and less than + /// `max_age` before `now` is reused; otherwise a new scan is taken. + /// An incomplete scan is returned to its caller only and never kept. + /// It does not replace an older complete scan, so a later reader may + /// still reuse that older one while it is within `max_age`. pub(super) fn snapshot( &self, leader: i32, @@ -515,16 +564,37 @@ mod os { take: impl FnOnce() -> Snapshot, ) -> Arc { let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((began, snap)) = &*last { - if *began >= not_before && now.saturating_duration_since(*began) < self.max_age { - return Arc::clone(snap); + let reused = match &*last { + Some((began, snap)) + if *began >= not_before + && now.saturating_duration_since(*began) < self.max_age => + { + Some(Arc::clone(snap)) } - } - let snap = Arc::new(take()); - self.scans.fetch_add(1, Ordering::Relaxed); - if snap.complete() { - *last = Some((now, Arc::clone(&snap))); - } + _ => None, + }; + #[cfg(test)] + let scanned = reused.is_none(); + let snap = match reused { + Some(snap) => snap, + None => { + let snap = Arc::new(take()); + self.scans.fetch_add(1, Ordering::Relaxed); + if snap.complete() { + *last = Some((now, Arc::clone(&snap))); + } + snap + } + }; + #[cfg(test)] + self.requests + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(Request { + at: now, + not_before, + scanned, + }); snap } @@ -532,6 +602,15 @@ mod os { pub(super) fn scans(&self) -> usize { self.scans.load(Ordering::Relaxed) } + + /// Every request so far, in order. + #[cfg(test)] + pub(super) fn requests(&self) -> Vec { + self.requests + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } } } @@ -974,6 +1053,55 @@ mod tests { assert_eq!(shared.scans(), 6); } + /// A listing that cannot be read (here `/proc` does not exist under + /// the root) is a degraded scan: it finds nothing, so it must not + /// prune any pane, and it is not kept. + #[test] + fn a_missing_listing_is_degraded_and_prunes_no_pane_member() { + let fx = Fixture::new("procs-no-listing"); + let mut tree = Tree::default(); + assert_eq!(tree.refresh(fx.pid()), 4); + let before = sorted(&tree); + let dir = crate::testutil::TempDir::new("procs-no-listing-root"); + let missing = dir.path().join("no-such-proc"); + let degraded = Snapshot::take_in(missing.to_str().unwrap(), fx.pid(), &mut None); + assert!(!degraded.complete()); + assert_eq!(tree.apply(fx.pid(), °raded), 0); + assert_eq!(sorted(&tree), before); + let shared = Shared::with_max_age(Duration::from_secs(3600)); + let t0 = Instant::now(); + let not_before = t0 - Duration::from_secs(60); + shared.0.snapshot_at(t0, not_before, || { + Snapshot::take_in(missing.to_str().unwrap(), 0, &mut None) + }); + let next = shared.0.snapshot_at(t0, not_before, || { + Snapshot::take_in(missing.to_str().unwrap(), 0, &mut None) + }); + assert!(!next.complete()); + assert_eq!(shared.scans(), 2, "a degraded scan was reused"); + } + + /// Every read fails with an error that is not "gone" (a directory + /// where `stat` should be fails with EISDIR, as a read does when a + /// descriptor is not usable). The listing works, so the scan is + /// degraded, and the pane keeps every member it had. + #[test] + fn a_failed_read_on_disk_prunes_no_pane_member() { + let fx = Fixture::new("procs-eisdir"); + let mut tree = Tree::default(); + assert_eq!(tree.refresh(fx.pid()), 4); + let before = sorted(&tree); + let dir = crate::testutil::TempDir::new("procs-eisdir-root"); + for &pid in &fx.members { + std::fs::create_dir_all(dir.path().join(pid.to_string()).join("stat")).unwrap(); + } + let root = dir.path().to_str().unwrap(); + let degraded = Snapshot::take_in(root, fx.pid(), &mut None); + assert!(!degraded.complete()); + assert_eq!(tree.apply(fx.pid(), °raded), 0); + assert_eq!(sorted(&tree), before); + } + /// A degraded scan (a read failed, here every read) is handed to its /// caller but not kept, so the next reader takes a fresh scan. #[test] diff --git a/src/native/host/tests_scan.rs b/src/native/host/tests_scan.rs index dd50269..f9a63ea 100644 --- a/src/native/host/tests_scan.rs +++ b/src/native/host/tests_scan.rs @@ -58,28 +58,54 @@ fn a_stop_scans_afresh_and_ends_a_child_the_shared_snapshot_missed() { ); } -/// Eight panes polling for descendants cost about one scan per tick, not -/// eight. The exact count (one scan per 250 ms window) is pinned by -/// `eight_pollers_take_exactly_one_scan_per_window` in `procs.rs`, where the -/// clock is supplied. Real pane readers wake every 200 ms, so their looks -/// land where the scheduler and the wake grid put them: panes started -/// together cluster and gave 3 scans in 1.5 s. The hard limit is one scan per -/// window, at most 7 in 1.5 s. Zero scans (no periodic look) and about 48 (no -/// sharing) both fail. +/// The window one scan serves. A literal, so a change to `SNAPSHOT_MAX_AGE` +/// fails the test rather than moving its expectation with it. +const WINDOW: Duration = Duration::from_millis(250); + +/// Eight panes take exactly one scan per 250 ms window. Every look the pane +/// readers made is replayed against that rule: a look reuses the last scan +/// when the scan began within the window and not before the look's pane was +/// spawned, and otherwise a scan must have been taken. The expected count is +/// the number of scans the rule gives for the looks that really happened, so +/// it does not depend on the readers' wake timing. A doubled window, or a +/// look that scans when it could reuse, fails. #[test] fn eight_panes_share_one_scan_per_tick() { let host = Arc::new(LocalHost::new()); let rig = Rig::new(Arc::clone(&host) as Arc, "scan-share"); let panes: Vec<_> = (0..8).map(|_| rig.spawn(&["sleep", "30"])).collect(); - // Past the first look of every pane, and a few ticks in. - std::thread::sleep(Duration::from_millis(700)); - let before = host.scans(); std::thread::sleep(Duration::from_millis(1500)); - let taken = host.scans() - before; + let looks = host.scan_requests(); assert!( - (1..=7).contains(&taken), - "{taken} scans in 1.5 s for 8 panes, expected 1 to 7 (at most one per 250 ms window)" + looks.len() >= 8, + "{} looks for 8 panes: not every pane looked", + looks.len() + ); + let mut began: Option = None; + let mut expected = 0; + for look in &looks { + let reusable = began + .is_some_and(|b| b >= look.not_before && look.at.saturating_duration_since(b) < WINDOW); + assert_eq!( + look.scanned, + !reusable, + "look at {:?} (pane spawned at {:?}): the shared snapshot rule says {}", + look.at, + look.not_before, + if reusable { "reuse" } else { "scan" } + ); + if !reusable { + began = Some(look.at); + expected += 1; + } + } + assert_eq!( + host.scans(), + expected, + "scans taken for {} looks", + looks.len() ); + assert!(expected >= 1); for pane in &panes { host.kill(&pane.id, Duration::from_secs(2)).unwrap(); } From 84ffce41876d86ae88faca9c7a1a873227bfa516 Mon Sep 17 00:00:00 2001 From: chaodu-agent Date: Wed, 18 Nov 2026 18:44:37 -0500 Subject: [PATCH 6/6] fix: read the snapshot age after the shared lock, document the degraded cost Refs #3 Addressed from the pass-3 review of 4f56bc1: - Snapshot age (procs.rs, Linux Shared): the clock is read after the shared lock is taken, in reuse_or_take, so a reader that waited for another pane's scan judges the snapshot when it uses it. snapshot_at, the supplied-clock seam, is now test-only. Without this gate the lib build fails under -D warnings on Linux. - Docs (docs/operations.md, docs/adr/native-core.md): the memory sentence gives the measured values, about 720 KiB more than the isolated base run and about 864 KiB more than the concurrent base run, at 302 processes. The degraded-scan rule now states its cost: while a read keeps failing, no scan is kept, so each pane's look takes its own scan. - Formatting (README.md, CHANGELOG.md, docs/operations.md, src/native/host/ local.rs): over-long lines rewrapped; a dangling line fragment in README.md removed. Unchanged: the test that replays the scan window (eight_panes_share_one_scan_ per_tick) keeps its complete-scan assumption, which holds on a healthy /proc. Tests, run on the head of this commit: - macOS build host (Apple Silicon): cargo fmt --check, cargo clippy --locked --all-targets -- -D warnings, cargo test --locked --no-fail-fast. Result: 1019 passed, 0 failed, 6 ignored. - Linux build host (x86_64): the same three commands. Result: 1042 passed, 0 failed, 6 ignored, including the Linux-only tests that read /proc. --- CHANGELOG.md | 4 ++-- README.md | 3 +-- docs/adr/native-core.md | 2 +- docs/operations.md | 15 +++++++++------ src/native/host/local.rs | 5 +++-- src/native/host/procs.rs | 27 ++++++++++++++++++++++----- 6 files changed, 38 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4dbffa..b516d46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ not once per pane, so idle CPU for eight panes drops. The cost is detection latency. A descendant that detaches with `setsid` and whose parents exit is now seen within about 500 ms in the nominal case, and at most about 700 ms provided each scan finishes within 250 ms (it was - about 250 ms nominal). On macOS the bound stays about 450 ms. Stops still read the table afresh, and a failed read never removes a process from a - pane's tree. + about 250 ms nominal). On macOS the bound stays about 450 ms. Stops still read the table afresh, + and a failed read never removes a process from a pane's tree. - Native panes: a process whose command name is not valid UTF-8 is now trackable, so it is found and, on `remove_pane` or shutdown, signalled. Before, it escaped the descendant tree and survived. diff --git a/README.md b/README.md index e491303..5443e9d 100644 --- a/README.md +++ b/README.md @@ -82,8 +82,7 @@ which answers a permission dialog may receive. before the next look is missed. On Linux a look may use a snapshot up to 250 ms old: a descendant is seen within about 500 ms in the nominal case, and at most about 700 ms provided each scan finishes within 250 ms. On macOS the bound is - about 450 ms - (see [Status and known limits](#status-and-known-limits)). + about 450 ms (see [Status and known limits](#status-and-known-limits)). - **Container image.** The `Dockerfile` builds a Debian image that runs as uid 1000 under tini, with kiro-cli pinned to 3.3.0 (the version the Kiro dialog parser was measured on) and checked against a SHA-256. The image holds no token and no profiles file. Its default command runs the pane holder diff --git a/docs/adr/native-core.md b/docs/adr/native-core.md index 84d73f0..b77fcd3 100644 --- a/docs/adr/native-core.md +++ b/docs/adr/native-core.md @@ -356,7 +356,7 @@ Nothing else passes, by construction (`env_clear()` first). In particular, `OPEN - **Removal failures:** `NotFound` for an unknown ref. If `kill` on the group fails with an error other than ESRCH, it is logged at warn level and removal still completes; EPERM after the leader has exited is not logged, because macOS answers EPERM for a group left with only its zombie leader (measured). - **Descendant tree (issue #10).** Measured on macOS with main `b446018`: kiro-cli starts `bun`, which starts `node …/acp-server.js` in a new session (`ps` STAT `Ss` without `+`: it called `setsid`, so it is a session and group leader with no controlling terminal; Node's `detached: true`). It is found only by the parent-pid walk from `bun`, never through the pane's group or terminal. Killing the pane's group never reached it, and after a pane ended it lived on with ppid 1 for over an hour. `procs::Tree` (in `src/native/procs.rs`) records every descendant as `(pid, start time)`: - **Found by** parent pid, from the leader and from every member still alive (a breadth-first walk), and by membership of the leader's group and session: on Linux, `/proc//stat` fields `ppid`, `pgrp`, `session` and `starttime`, from one scan of `/proc`; on macOS, `proc_listchildpids`, `proc_listpgrppids`, and `proc_listpids(PROC_TTY_ONLY, tdev)` with the leader's controlling terminal (`proc_bsdinfo.e_tdev`; macOS has no list-by-session call, and every process of the session has that terminal while the leader runs), with the start time from `proc_pidinfo(PROC_PIDTBSDINFO)` (`pbi_start_tvsec`/`usec`). - - **Refreshed** by the reader while the leader runs, at most about 450 ms between looks (target 250 ms, see the known limit), and at the start of every soft and hard stop. A scan that could not read every process is neither cached nor allowed to prune: the tree keeps its members. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. + - **Refreshed** by the reader while the leader runs, at most about 450 ms between looks (target 250 ms, see the known limit), and at the start of every soft and hard stop. A scan that could not read every process is neither cached nor allowed to prune: the tree keeps its members. While a read keeps failing, no scan is kept, so each pane's look takes its own scan until one reads every process. A member is kept across refreshes while its pid still has the recorded start time, so a descendant whose parent exits (reparented to pid 1) stays known. Group and session lookups by the leader's pid run only while that pid is reserved (the leader is unreaped), and the reaper reaps under the tree lock, so no lookup can run on a freed pid. - **Signalled** only after re-reading the pid's start time and finding it unchanged. A reused pid has a later start time and is skipped. The check and the `kill` are a few microseconds apart; a pid is reused only after the pid space wraps, so a reuse inside that window is not a practical risk. Zombies are skipped (Linux state `Z`/`X`; macOS does not answer `proc_pidinfo` for zombies). Shepherd's own pid and pids 0 and 1 are never members. - **Known limit (owner decision after review):** a descendant that is re-parented and fully detaches before the first look that would see it is not seen: it calls `setsid` (no group, session or terminal link to the pane) and every ancestor between it and a known member exits first, as in a daemon's double fork. On Linux that look comes at most about 700 ms after the fork, provided each scan finishes within the 250 ms snapshot age: a snapshot up to 250 ms old, plus looks at most about 450 ms apart because the reader wakes every 200 ms. A scan that runs longer, or a look that waits on another pane's scan under the shared lock, adds its own time to that bound. The nominal figure is 500 ms (250 ms snapshot age plus a 250 ms look interval). On macOS the bound is about 450 ms, because macOS caches nothing. It survives removal, the program's own exit, shutdown and drop. One that only changes its process group is still found through the session (macOS: the terminal) while the leader runs, and one whose parent lives until the next look is found by the parent-pid walk. Measured on macOS 15.7 (remote build host, a C probe with a `setsid` double fork): kqueue `EVFILT_PROC` with `NOTE_TRACK` is refused with `EV_ERROR`, data 45 (`ENOTSUP`); every process inherits its parent's coalition ids (`PROC_PIDCOALITIONINFO`), but creating a coalition needs root, so a pane cannot get its own; macOS has no subreaper and no cgroup; `p_puniqueid` (`PROC_PIDUNIQIDENTIFIERINFO`) survives the reparent to pid 1, but it names the intermediate that was never seen, so the chain stays broken. No public unprivileged macOS mechanism closes the gap. Linux can close it with `PR_SET_CHILD_SUBREAPER` in a per-pane supervisor; that is a follow-up to build and test with a Linux build. - **Alternatives considered.** (a) Signal only the group or session: misses `setsid` children, and neither kernel has kill-by-session. (b) Snapshot the tree only at stop time: misses a descendant whose parent already exited (the measured orphan), so tracking is required. (c) Linux `PR_SET_CHILD_SUBREAPER` would reparent orphans to Shepherd, but macOS has no equivalent and Shepherd would then have to reap foreign children; one mechanism on both platforms is simpler to test. (d) A per-pane cgroup (Linux) or job object does not exist on macOS. (e) pidfds would close the check-to-kill window on Linux only; not worth a second code path given (c). diff --git a/docs/operations.md b/docs/operations.md index 09fe054..d488de6 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -809,10 +809,13 @@ Pane ids are `n:` descendant is seen within about 500 ms in the nominal case, and at most about 700 ms provided each scan finishes within the 250 ms age limit (see Known limits). A stop always reads it afresh. The snapshot lists every process - on the host, so its memory grows with the host's process count (about 0.9 MiB - more than the base at 302 processes). A scan that cannot read every process is - not kept, and it prunes nothing: under a lasting read failure a tree keeps a - member until a complete scan no longer lists it. Each signal still re-checks the + on the host, so its memory grows with the host's process count (measured on + the Linux build host at 302 processes: about 720 KiB more than the isolated + base run and about 864 KiB more than the concurrent base run). A scan that + cannot read every process is not kept, and it prunes nothing: under a lasting + read failure a tree keeps a member until a complete scan no longer lists it. + While the failure lasts, no scan is kept, so each pane's look takes its own + scan, as it did before this change. Each signal still re-checks the start time. Removing a pane (`remove_pane`) and Shepherd's exit on SIGINT, SIGTERM or SIGHUP send SIGHUP and SIGTERM to the group and the descendants, wait up to 2 s (for `remove_pane`, its `timeout`), then stop (SIGSTOP) the group and @@ -1663,8 +1666,8 @@ try to update itself at run time). detaches (calls `setsid`, so it has no group, session or terminal link to the pane, and its parents exit) before the first look that would see it, is never seen. That look comes at most about 700 ms after the fork on Linux, provided each - scan finishes within 250 ms, and about 450 ms on macOS. It survives `remove_pane`, the program's own exit, - and Shepherd's shutdown. One that only changes process group, or stays under a + scan finishes within 250 ms, and about 450 ms on macOS. It survives + `remove_pane`, the program's own exit, and Shepherd's shutdown. One that only changes process group, or stays under a live parent until the next look, is ended (issue #10). macOS offers no unprivileged way to close this: kqueue `NOTE_TRACK` answers `ENOTSUP`, only root can create a coalition, and there is no subreaper or cgroup (measured on macOS diff --git a/src/native/host/local.rs b/src/native/host/local.rs index 59ac7c3..3c4ea9a 100644 --- a/src/native/host/local.rs +++ b/src/native/host/local.rs @@ -7,8 +7,9 @@ //! lock across a sleep, a poll or a wait, except the condvar waits, which //! release `state`. The shared process-table snapshot (`procs::Shared`) has a //! lock of its own, taken under a pane's `tree` and never with anything else -//! held; only the readers' periodic look uses it, never a stop. The registry lock is held only to look a pane up or -//! change the list, never across a call into the sink or a wait. +//! held; only the readers' periodic look uses it, never a stop. The registry +//! lock is held only to look a pane up or change the list, never across a call +//! into the sink or a wait. use super::tail::TailRing; use super::{ diff --git a/src/native/host/procs.rs b/src/native/host/procs.rs index a8bfb26..f1075ed 100644 --- a/src/native/host/procs.rs +++ b/src/native/host/procs.rs @@ -542,21 +542,27 @@ mod os { } /// A complete scan that began at or after `not_before` and less than - /// `max_age` before `now` is reused; otherwise a new scan is taken. - /// An incomplete scan is returned to its caller only and never kept. - /// It does not replace an older complete scan, so a later reader may - /// still reuse that older one while it is within `max_age`. + /// `max_age` before the time the lock was taken is reused; otherwise a + /// new scan is taken. The age is read after the lock, so a reader that + /// waited for another's scan judges the snapshot at the moment it uses + /// it. An incomplete scan is returned to its caller only and never + /// kept. It does not replace an older complete scan, so a later reader + /// may still reuse that older one while it is within `max_age`. pub(super) fn snapshot( &self, leader: i32, tty: &mut Option, not_before: Instant, ) -> Arc { - self.snapshot_at(Instant::now(), not_before, || Snapshot::take(leader, tty)) + let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + self.reuse_or_take(&mut last, Instant::now(), not_before, || { + Snapshot::take(leader, tty) + }) } /// [`Shared::snapshot`] with the time and the scan supplied, so the /// age limit can be tested exactly. + #[cfg(test)] pub(super) fn snapshot_at( &self, now: Instant, @@ -564,6 +570,17 @@ mod os { take: impl FnOnce() -> Snapshot, ) -> Arc { let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner); + self.reuse_or_take(&mut last, now, not_before, take) + } + + /// The decision of [`Shared::snapshot`], made under the lock. + fn reuse_or_take( + &self, + last: &mut Option<(Instant, Arc)>, + now: Instant, + not_before: Instant, + take: impl FnOnce() -> Snapshot, + ) -> Arc { let reused = match &*last { Some((began, snap)) if *began >= not_before