From 90aa3003acab2497b9a4ca7c6be8523f6740c9b4 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sat, 5 Dec 2026 09:33:48 -0500 Subject: [PATCH 1/2] Supervise reply-driven Plan usage reads in the process module (#2443) --- docs/code-navigation.md | 3 +- src/plan_usage/read.rs | 69 ++++++++----------- src/process.rs | 143 ++++++++++++++++++++++++--------------- src/process/pipe.rs | 85 +++++++++++++++++++++++ src/process/tests.rs | 145 ++++++++++++++++++++++++++++++++++------ tests/plan_usage.rs | 11 +-- 6 files changed, 334 insertions(+), 122 deletions(-) create mode 100644 src/process/pipe.rs diff --git a/docs/code-navigation.md b/docs/code-navigation.md index 092a974c9..4783e4d75 100644 --- a/docs/code-navigation.md +++ b/docs/code-navigation.md @@ -42,7 +42,8 @@ Start with the issue's terms in `GLOSSARY.md`, then use this index to find their | Session trace calls | `src/session/trace/calls.rs` — `Calls`: the one call lifecycle shared by recording and the Waterfall, with causal keys, span identities, retained identity overrides (`Retained`), parent recovery, first observation, completion, late amendments and closure | `src/session/trace/calls/tests.rs` | | Session usage | `src/session/usage.rs` — normalized-event and buffered retained-span adapters, one owned summary, partial-total precedence, inclusive cache normalization and addition across Sessions; `src/logs/session_signals.rs` and `src/evals/experiment/usage.rs` — Run metrics and Arm projections | `src/session/usage/tests.rs`, `tests/metrics.rs`, `tests/run_metrics.rs`, `tests/experiments.rs`, `src/evals/experiment/reading/tests.rs` | | Plan usage observation (subscription Harnesses) | `src/plan_usage/observation.rs` — `SUBSCRIPTION` (the subscription Harnesses Plan usage watches), `claude_rate_limit`, `claude_api_error`, `codex_token_count`, `terminal_failure`; `src/harness/interpretation/stream.rs` (Claude and Grok wire frames) and `src/harness/codex/stream.rs`, `src/harness/muse/stream.rs`, `src/harness/agy/stream.rs` — passive capture as `Evidence::PlanUsage`, saved by `src/session/recording.rs` through `plan_usage::record`; `src/plan_usage/read.rs` — official non-billed reads (`READABLE`, `WINDOWED`, `Probe::read`: `codex app-server`, `muse serve`, `claude auth status --json` and `src/plan_usage/read/slash.rs` for Claude and Agy `/usage`); `src/plan_usage/model_scope.rs` — matches Plan windows to the resolved Model; `src/plan_usage.rs` — `refresh` and `FRESH` (viewing) and `refresh_for_routing` with `router::FRESH_MINUTES`; `src/plan_usage/store.rs` — `~/.thirdshift/plan-usage.json`, `State::exhaust` cooldowns and the revalidation backoff (`FIRST_BACKOFF_MINUTES`, `LAST_BACKOFF_MINUTES`), `Store::clear` | Inline tests; `tests/plan_usage.rs`, `src/harness/interpretation_tests.rs` | -| One-shot Plan usage reads | `src/plan_usage/read.rs` and `src/plan_usage/read/slash.rs` — prepare Claude and Agy `/usage`, Claude `auth status --json` and Codex `login status` and interpret the results; `src/process.rs` — `one_shot` owns spawn, the deadline, stdout collection and interruption; `src/process/tree.rs` — whole-tree cleanup; `src/plan_usage/read.rs` — Codex and Muse JSON-RPC reply collection | `src/process/tests.rs`, `tests/plan_usage.rs` | +| One-shot Plan usage reads | `src/plan_usage/read.rs` and `src/plan_usage/read/slash.rs` — prepare Claude and Agy `/usage`, Claude `auth status --json` and Codex `login status` and interpret the results; `src/process.rs` — `one_shot` owns spawn, the deadline, stdout collection and interruption; `src/process/tree.rs` — whole-tree cleanup | `src/process/tests.rs`, `tests/plan_usage.rs` | +| Reply-driven Plan usage reads | `src/plan_usage/read.rs` — Codex and Muse JSON-RPC framing, reply collection and interpretation; `src/process.rs` — `exchange` owns spawn, the deadline, interruption and reply-driven completion; `src/process/pipe.rs` — cancellable stdin and stdout; `src/process/tree.rs` — whole-tree cleanup | `src/process/tests.rs`, `tests/plan_usage.rs` | | Route selection, `[harness] routes`, `max_utilization`, `allow_credits`, `[security] routes` | `src/plan_usage/route.rs` — `Route`, `Routing` (`first`, `ceiling`, `allows_credits`), `parse_routes`, `percentage`; `src/config.rs` — `UserConfig::routing` and the `DEFAULTS` lines Setup and `thirdshift config` inventory; `src/asks.rs` — `Flags::harness` and `security_harness` (a command naming no Harness, Model or Effort takes the first route, `ChosenBy::Routes`); `src/plan_usage/router.rs` — `Router::of` (ordinary and Security candidates, pinning), `harnesses` (every route's Factory skills), `pick` and `select` (proactive), `Router::exhaustion`; `src/plan_usage/view.rs` — `Availability`; `src/plan_usage.rs` — `credits_allowed`; `src/harness/agy.rs` — `NO_CREDITS` (`--settings '{"useG1Credits":false}'`); `src/session.rs` — `Sessions::run_step` and `take_route` (reactive reroute), `OnMachine::worktree_at_start` and `reset` (mid-Step clean reset and conflict re-merge); `src/implement.rs` — `continue_with` (Continuation prompt after commits or an open PR); `src/harness/interpretation.rs` — `SessionFailure::plan_usage_exhausted` | Inline tests in `src/plan_usage/route.rs`, `src/plan_usage/router.rs` and `src/session.rs`; `src/asks.rs` (first route); `tests/plan_usage_routing.rs` | | Plan-usage Paused Command, Pass skip | `src/session.rs` — `pause_if_exhausted` (no route before a Step) and `paused_at_a_limit` (no route after a stop); `src/session/limits.rs` — `PlanUsagePaused`, `NO_ROUTE`, `plan_usage_paused`; `src/plan_usage/exhaustion.rs` — `Exhaustion`, `judge`; `src/run_ending.rs` — `PAUSED_EXIT`; `src/run.rs` — the resume command via `logs::resumable`; `src/child_run.rs` — `Ended::Paused` from a child's exit code; `src/spec_run/ticket_board.rs` and `src/spec_run.rs` — a paused Ticket stops queued Tickets; `src/claim.rs` — `Ending::Paused`, `release_paused` (no `agent-failed`, `ready-for-agent` back, untrusted-edit `needs-triage`); `src/logs.rs` — `paused`, `handed_back_for_pickup`; `src/logs/command_record.rs` — `handed_back_for_pickup`; `src/logs/reading/inbox.rs` — `NeedsYouKind::Paused`, Done when retaken; `src/notification.rs` — saved, not emailed, under `email.unless_merged` when retaken; `src/command_limit.rs` — `Why::PlanUsage` Pass skip; `src/plan_usage.rs` — `pass_exhaustion`, `machine_exhaustion`, `banner` (shown by `src/logs/status.rs` and the Inbox) | Inline Claim tests; `tests/plan_usage_pause.rs`, `tests/console/inbox.rs`, `tests/run_notification.rs`, `tests/pickup_run.rs` | | Session trace recording and Trace ancestry | `src/session/trace.rs` — recording adapter: streaming records, flushing first completions, closing unfinished calls and rewriting one final span per ID; `src/logs/trace.rs` — deterministic Command, Ticket run and stage identities; `src/logs/trace/ancestry.rs` — `of`: the one record-derived ancestry and Session attachment for a selected record subtree under its owning Command, shared by the Waterfall and whole Trace export (dispatch-parent stage, descendant-first Session claims, first naming stage, Run fallback) | `tests/session_traces.rs`, `src/session/trace/tests.rs`, `src/session/recording/tests.rs`, `src/logs/recording/tests.rs`, `src/logs/trace/ancestry/tests.rs` | diff --git a/src/plan_usage/read.rs b/src/plan_usage/read.rs index e3a265b6b..2db4d11c8 100644 --- a/src/plan_usage/read.rs +++ b/src/plan_usage/read.rs @@ -7,8 +7,7 @@ use std::collections::BTreeMap; use std::io::{BufRead, BufReader, Write}; use std::os::unix::fs::MetadataExt; use std::path::PathBuf; -use std::process::{Command, Stdio}; -use std::sync::mpsc; +use std::process::Command; use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail}; @@ -18,7 +17,7 @@ use serde_json::{Value, json}; use super::observation::{Exhausted, Window, from_percent, milliseconds, seconds, token}; use super::store::{Credits, ExecutableStamp, State}; use crate::harness::Harness; -use crate::{interrupt, process}; +use crate::process; mod slash; @@ -441,40 +440,30 @@ fn rpc( requests: &[Value], wanted: &[i64], ) -> Result> { - interrupt::check()?; - let mut child = Command::new(cli) - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .with_context(|| format!("could not run {cli}"))?; - let stdout = child.stdout.take().expect("piped stdout"); - let (sender, receiver) = mpsc::channel(); - std::thread::spawn(move || { - for line in BufReader::new(stdout).lines() { - let Ok(line) = line else { break }; - if sender.send(line).is_err() { - break; - } - } - }); - let mut stdin = child.stdin.take().expect("piped stdin"); + let deadline = Instant::now() + TIMEOUT; + let mut input = Vec::new(); for request in requests { - if writeln!(stdin, "{request}").is_err() { - break; - } + writeln!(input, "{request}")?; } - let _ = stdin.flush(); - let deadline = Instant::now() + TIMEOUT; + let wanted = wanted.to_vec(); + let responses = process::exchange( + Command::new(cli).args(args), + cli, + &input, + deadline, + move |stdout| collect_replies(BufReader::new(stdout), &wanted), + )? + .unwrap_or_default(); + if responses.is_empty() { + bail!("{cli} {} gave no answer", args.join(" ")); + } + Ok(responses) +} + +fn collect_replies(stdout: impl BufRead, wanted: &[i64]) -> BTreeMap { let mut responses = BTreeMap::new(); - while !interrupt::requested() && wanted.iter().any(|id| !responses.contains_key(id)) { - let left = deadline.saturating_duration_since(Instant::now()); - let line = match receiver.recv_timeout(left.min(Duration::from_millis(100))) { - Ok(line) => line, - Err(mpsc::RecvTimeoutError::Timeout) if !left.is_zero() => continue, - Err(mpsc::RecvTimeoutError::Timeout | mpsc::RecvTimeoutError::Disconnected) => break, - }; + for line in stdout.lines() { + let Ok(line) = line else { break }; let Ok(message) = serde_json::from_str::(&line) else { continue; }; @@ -482,16 +471,12 @@ fn rpc( && (message.get("result").is_some() || message.get("error").is_some()) { responses.insert(id, message); + if wanted.iter().all(|id| responses.contains_key(id)) { + break; + } } } - drop(stdin); - let _ = child.kill(); - let _ = child.wait(); - interrupt::check()?; - if responses.is_empty() { - bail!("{cli} {} gave no answer", args.join(" ")); - } - Ok(responses) + responses } #[cfg(test)] diff --git a/src/process.rs b/src/process.rs index c80b14ba5..872561a9f 100644 --- a/src/process.rs +++ b/src/process.rs @@ -1,10 +1,9 @@ //! Own a Command CLI child and all its I/O until completion or whole-tree cleanup. use std::io::{self, Read, Write}; -use std::os::fd::AsRawFd; use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; -use std::process::{Child, ChildStdout, Command, ExitStatus, Output, Stdio}; +use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, mpsc}; use std::thread::{self, JoinHandle}; @@ -14,6 +13,7 @@ use anyhow::{Context, Result, anyhow, bail}; use crate::interrupt; +mod pipe; pub(crate) mod session; mod tree; pub(crate) use tree::{is_alive, signal, stop}; @@ -155,11 +155,9 @@ pub(crate) fn one_shot( Some(deadline), &|| Ok(()), move |pipe| { - read(CancellableStdout { - pipe, - cancelled: reader_cancelled, - }) - .with_context(|| format!("could not read {cli}'s stdout")) + pipe::Cancellable::new(pipe, reader_cancelled) + .and_then(read) + .with_context(|| format!("could not read {cli}'s stdout")) }, ); let output = execution?; @@ -169,6 +167,43 @@ pub(crate) fn one_shot( }) } +/// Send input and keep stdin open until the stdout consumer returns or the +/// deadline or interruption stops the exchange. The consumer returns any +/// replies it collected, including at a deadline. A cancelled read reports +/// an I/O error, so the consumer can distinguish it from actual EOF. +/// Interruption discards replies. Every return stops and reaps owned work. +/// An expired deadline can leave no consumer result if the reader never ran. +pub(crate) fn exchange( + command: &mut Command, + name: &str, + input: &[u8], + deadline: Instant, + consume: impl FnOnce(&mut dyn Read) -> T + Send + 'static, +) -> Result> { + let cancelled = Arc::new(AtomicBool::new(false)); + let reader_cancelled = Arc::clone(&cancelled); + let (completed, recovered) = mpsc::sync_channel(1); + let (execution, _) = execute( + command, + Some(input), + Operation::Exchange { + name, + cancelled: &cancelled, + }, + Some(deadline), + &|| Ok(()), + move |pipe| { + let mut stdout = pipe::Cancellable::new(pipe, reader_cancelled)?; + let _ = completed.send(consume(&mut stdout)); + Ok(()) + }, + ); + match execution { + Err(error) if !error.is::() => Err(error), + Ok(_) | Err(_) => Ok(recovered.try_recv().ok()), + } +} + #[derive(Debug)] pub(crate) struct TimedOut; @@ -278,31 +313,6 @@ fn read(mut pipe: impl Read) -> std::io::Result> { Ok(bytes) } -struct CancellableStdout { - pipe: ChildStdout, - cancelled: Arc, -} - -impl Read for CancellableStdout { - fn read(&mut self, buffer: &mut [u8]) -> io::Result { - let mut descriptor = libc::pollfd { - fd: self.pipe.as_raw_fd(), - events: libc::POLLIN, - revents: 0, - }; - // A writer outside the tracked tree must not hold up worker cleanup. - while !self.cancelled.load(Ordering::Acquire) { - // SAFETY: poll borrows one initialized descriptor owned by this reader. - match unsafe { libc::poll(&mut descriptor, 1, 100) } { - 0 => continue, - -1 => return Err(io::Error::last_os_error()), - _ => return self.pipe.read(buffer), - } - } - Ok(0) - } -} - #[derive(Clone, Copy)] enum Operation<'a> { Capture(Control<'a>), @@ -310,7 +320,11 @@ enum Operation<'a> { OneShot { name: &'a str, stdout: Stdout, - cancelled: &'a AtomicBool, + cancelled: &'a Arc, + }, + Exchange { + name: &'a str, + cancelled: &'a Arc, }, } @@ -341,7 +355,9 @@ fn execute<'a, T: Send + 'static>( Operation::Capture(control) | Operation::Stream(control) => { (control.name, control.interruption) } - Operation::OneShot { name, .. } => (name, Interruption::Ordinary), + Operation::OneShot { name, .. } | Operation::Exchange { name, .. } => { + (name, Interruption::Ordinary) + } }; let capture_stdout = !matches!( operation, @@ -356,7 +372,10 @@ fn execute<'a, T: Send + 'static>( bail!("interrupted"); } check()?; - if matches!(operation, Operation::OneShot { .. }) { + if matches!( + operation, + Operation::OneShot { .. } | Operation::Exchange { .. } + ) { check_deadline(deadline)?; } let cli = name.to_owned(); @@ -381,7 +400,7 @@ fn execute<'a, T: Send + 'static>( Operation::Capture(_) => { command.stderr(Stdio::piped()); } - Operation::OneShot { .. } => { + Operation::OneShot { .. } | Operation::Exchange { .. } => { command.stderr(Stdio::null()); } Operation::Stream(_) => {} @@ -394,7 +413,7 @@ fn execute<'a, T: Send + 'static>( Stop::Configured(control.stop), session::Session::of(command), ), - Operation::OneShot { cancelled, .. } => ( + Operation::OneShot { cancelled, .. } | Operation::Exchange { cancelled, .. } => ( Stop::Hard { group: tree::OwnedGroup::new(&child), cancelled, @@ -417,6 +436,7 @@ fn execute<'a, T: Send + 'static>( stdout: None, stderr: None, stdin: None, + finish_on_stdout: matches!(operation, Operation::Exchange { .. }), completed: false, }; let result = (|| { @@ -471,6 +491,12 @@ fn execute<'a, T: Send + 'static>( #[cfg(test)] fault.fire("stdin-start")?; let input = input.to_vec(); + let exchange_cancelled = match operation { + Operation::Exchange { cancelled, .. } => Some(Arc::clone(cancelled)), + Operation::Capture(_) | Operation::Stream(_) | Operation::OneShot { .. } => { + None + } + }; #[cfg(test)] let stdin_fault = fault.clone(); owned.stdin = Some(Worker::start( @@ -479,9 +505,16 @@ fn execute<'a, T: Send + 'static>( move || { #[cfg(test)] stdin_fault.fire("stdin-write")?; + if let Some(cancelled) = exchange_cancelled { + let mut pipe = pipe::Cancellable::new(pipe, cancelled)?; + // A server can close its input and still reply. + let _ = pipe.write_all(&input); + return Ok(Some(pipe.into_inner())); + } pipe.write_all(&input) - .with_context(|| format!("could not write the prompt to {cli}")) + .with_context(|| format!("could not write the prompt to {cli}"))?; // Dropping the pipe closes stdin, including for an empty prompt. + Ok(None) }, )?); } @@ -501,18 +534,14 @@ fn execute<'a, T: Send + 'static>( stderr, }) })(); - if result.is_err() || interruption.requested() { - owned.cleanup(); - // Interruption can also arrive during stopping or joining. Preserve - // the original transport failure unless an interruption was observed. - if interruption.requested() { - bail!("interrupted"); - } + if !owned.completed && (result.is_err() || interruption.requested()) { + let _ = owned.cleanup(); } else { owned.completed = true; } result })(); + // Interruption may arrive while stopping or joining workers. (interruption.check().and(result), started) } @@ -528,7 +557,8 @@ struct Execution<'a, T> { awakened: mpsc::Receiver<()>, stdout: Option>, stderr: Option>>, - stdin: Option>, + stdin: Option>>, + finish_on_stdout: bool, completed: bool, } @@ -563,6 +593,11 @@ impl Execution<'_, T> { .map(Worker::poll) .transpose()? .unwrap_or(true); + if self.finish_on_stdout && stdout_done { + return self + .cleanup() + .with_context(|| format!("could not wait for {}", self.name)); + } let stderr_done = self .stderr .as_mut() @@ -608,24 +643,21 @@ impl Execution<'_, T> { } } - fn cleanup(&mut self) { - if self.completed { - return; - } + fn cleanup(&mut self) -> io::Result { match &mut self.stop { Stop::Configured(stop) => stop(&mut self.child), Stop::Hard { group, cancelled } => { - group.kill(&mut self.child); cancelled.store(true, Ordering::Release); + group.kill(&mut self.child); } } self.sweep_session_after_stop(); - let _ = self.child.wait(); + let status = self.child.wait(); // Pipes may still be attached if worker startup failed. drop(self.child.stdin.take()); drop(self.child.stdout.take()); drop(self.child.stderr.take()); - if let Some(worker) = &mut self.stdin { + if let Some(mut worker) = self.stdin.take() { worker.join(); } if let Some(worker) = &mut self.stdout { @@ -635,6 +667,7 @@ impl Execution<'_, T> { worker.join(); } self.completed = true; + status } fn sweep_session(&mut self) { @@ -657,7 +690,9 @@ impl Execution<'_, T> { impl Drop for Execution<'_, T> { fn drop(&mut self) { - self.cleanup(); + if !self.completed { + let _ = self.cleanup(); + } // Cleanup owns stopping, reaping and joining, including on unwind. // Keep the last observation after all of them; never rerun `check`. self.observe(); diff --git a/src/process/pipe.rs b/src/process/pipe.rs new file mode 100644 index 000000000..f4f39c312 --- /dev/null +++ b/src/process/pipe.rs @@ -0,0 +1,85 @@ +//! Nonblocking pipe I/O for bounded executions. + +use std::io::{self, Read, Write}; +use std::os::fd::AsRawFd; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +pub(super) struct Cancellable

{ + pipe: P, + cancelled: Arc, +} + +impl Cancellable

{ + pub(super) fn new(pipe: P, cancelled: Arc) -> io::Result { + let fd = pipe.as_raw_fd(); + // SAFETY: both calls use a live descriptor borrowed from the pipe. + unsafe { + let flags = libc::fcntl(fd, libc::F_GETFL); + if flags == -1 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) == -1 { + return Err(io::Error::last_os_error()); + } + } + Ok(Self { pipe, cancelled }) + } + + pub(super) fn into_inner(self) -> P { + self.pipe + } + + fn check_cancelled(&self) -> io::Result<()> { + if self.cancelled.load(Ordering::Acquire) { + // A read cancelled with a buffered partial line must not look + // like EOF to a consumer. Interrupted would cause a retry. + return Err(io::Error::other("process pipe cancelled")); + } + Ok(()) + } + + fn with_ready( + &mut self, + events: libc::c_short, + mut io: impl FnMut(&mut P) -> io::Result, + ) -> io::Result { + let mut descriptor = libc::pollfd { + fd: self.pipe.as_raw_fd(), + events, + revents: 0, + }; + loop { + self.check_cancelled()?; + match io(&mut self.pipe) { + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} + result => return result, + } + // SAFETY: poll borrows one initialized descriptor owned by this pipe. + if unsafe { libc::poll(&mut descriptor, 1, 100) } == -1 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::Interrupted { + return Err(error); + } + } + } + } +} + +impl Read for Cancellable

{ + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + let read = self.with_ready(libc::POLLIN, |pipe| pipe.read(buffer))?; + if read == 0 { + self.check_cancelled()?; + } + Ok(read) + } +} + +impl Write for Cancellable

{ + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.with_ready(libc::POLLOUT, |pipe| pipe.write(buffer)) + } + + fn flush(&mut self) -> io::Result<()> { + self.pipe.flush() + } +} diff --git a/src/process/tests.rs b/src/process/tests.rs index c1e38e3ab..5214809fd 100644 --- a/src/process/tests.rs +++ b/src/process/tests.rs @@ -246,6 +246,32 @@ impl RecordedProcess { fn assert_stopped(&self) { assert!(!is_alive(self.pid()), "the owned child survived cleanup"); } + + fn assert_exited(&self) { + // An orphan's reaper can run later. A zombie has already stopped. + let pid = self.pid(); + let process = sysinfo::Pid::from_u32(pid as u32); + let mut system = sysinfo::System::new(); + let deadline = Instant::now() + Duration::from_secs(3); + while is_alive(pid) { + system.refresh_processes_specifics( + sysinfo::ProcessesToUpdate::Some(&[process]), + true, + sysinfo::ProcessRefreshKind::nothing().without_tasks(), + ); + if system + .process(process) + .is_some_and(|process| process.status() == sysinfo::ProcessStatus::Zombie) + { + break; + } + assert!( + Instant::now() < deadline, + "owned process {pid} survived cleanup" + ); + thread::sleep(Duration::from_millis(10)); + } + } } impl Drop for RecordedProcess { @@ -530,27 +556,7 @@ fn one_shot_deadline_stops_a_stdout_holder_after_its_launcher_exits() { "{result:?}" ); assert!(started.elapsed() < Duration::from_secs(6)); - // The launcher is reaped by one_shot, but the orphan's reaper can run - // later. Check that it has stopped even if it is still a zombie. - let pid = holder.pid(); - let process = sysinfo::Pid::from_u32(pid as u32); - let mut system = sysinfo::System::new(); - let deadline = Instant::now() + Duration::from_secs(3); - while is_alive(pid) { - system.refresh_processes_specifics( - sysinfo::ProcessesToUpdate::Some(&[process]), - true, - sysinfo::ProcessRefreshKind::nothing().without_tasks(), - ); - if system - .process(process) - .is_some_and(|process| process.status() == sysinfo::ProcessStatus::Zombie) - { - break; - } - assert!(Instant::now() < deadline, "stdout holder survived cleanup"); - thread::sleep(Duration::from_millis(10)); - } + holder.assert_exited(); } #[test] @@ -650,6 +656,103 @@ fn one_shot_returns_raw_stdout_or_status_only_with_null_stdin_and_stderr() { } } +#[test] +fn exchange_finishes_on_the_reply_while_stdin_and_launcher_are_still_open() { + use std::io::{BufRead, BufReader}; + + let launcher = RecordedProcess::new(); + let mut command = launcher.command( + r#" + echo $$ > "$PID_FILE" + read -r request && [ "$request" = 'request' ] || exit 1 + read -r -t 1 extra + [ "$?" -gt 128 ] || exit 2 + printf 'reply\n' + exec sleep 20 + "#, + ); + let started = Instant::now(); + let reply = exchange( + &mut command, + "fixture", + b"request\n", + started + Duration::from_secs(10), + |stdout| BufReader::new(stdout).lines().next().transpose().unwrap(), + ) + .unwrap(); + + assert_eq!(reply.flatten().as_deref(), Some("reply")); + assert!(started.elapsed() < Duration::from_secs(8)); + launcher.assert_stopped(); +} + +#[test] +fn exchange_keeps_complete_replies_at_the_deadline_with_both_pipes_held_open() { + use std::io::{BufRead, BufReader}; + + let launcher = RecordedProcess::new(); + let holder = RecordedProcess::new(); + let mut command = launcher.command( + r#" + echo $$ > "$PID_FILE" + set -m + (printf 'reply\nunfinished'; exec sleep 20) <&0 & + echo "$!" > "$HOLDER_PID_FILE" + wait + "#, + ); + command.env("HOLDER_PID_FILE", holder.0.path().join("pid")); + let started = Instant::now(); + let timeout = Duration::from_secs(5); + let replies = exchange( + &mut command, + "fixture", + &vec![b'x'; 2 * 1024 * 1024], + started + timeout, + |stdout| { + BufReader::new(stdout) + .lines() + .map_while(|line| line.ok()) + .collect::>() + }, + ) + .unwrap(); + + assert_eq!(replies.unwrap(), ["reply"]); + assert!(started.elapsed() >= timeout); + assert!(started.elapsed() < Duration::from_secs(9)); + launcher.assert_stopped(); + holder.assert_exited(); +} + +#[test] +fn exchange_collects_a_final_line_at_stdout_eof_even_if_the_write_ends_early() { + use std::io::{BufRead, BufReader}; + + let launcher = RecordedProcess::new(); + let mut command = launcher.command( + "echo $$ > \"$PID_FILE\"; exec 0<&-; printf 'final reply'; exec 1>&-; exec sleep 20", + ); + let started = Instant::now(); + let replies = exchange( + &mut command, + "fixture", + &vec![b'x'; 2 * 1024 * 1024], + started + Duration::from_secs(10), + |stdout| { + BufReader::new(stdout) + .lines() + .collect::>>() + .unwrap() + }, + ) + .unwrap(); + + assert_eq!(replies.unwrap(), ["final reply"]); + assert!(started.elapsed() < Duration::from_secs(8)); + launcher.assert_stopped(); +} + #[test] fn normal_completion_leaves_background_work_without_owned_io_running() { for captured in [true, false] { diff --git a/tests/plan_usage.rs b/tests/plan_usage.rs index 1b1c79c15..6b0d1b1ec 100644 --- a/tests/plan_usage.rs +++ b/tests/plan_usage.rs @@ -91,8 +91,11 @@ fn interrupting_a_local_refresh_stops_the_probes_and_keeps_saved_plan_usage() { [ "$1" = serve ] || exit 2 read -r request printf '%s\n' '{"id":1,"result":{"usage":{"window":{"usedPercent":88}}}}' -printf '%s\n' "$$" > "$PROBE_DIR/muse-pid" -exec sleep 30 +set -m +sleep 30 & +printf '%s\n%s\n' "$$" "$!" > "$PROBE_DIR/muse-pids" +: > "$PROBE_DIR/muse-started" +wait "#, ); scripted( @@ -100,7 +103,7 @@ exec sleep 30 "claude", r#" [ "$*" = 'auth status --json' ] || exit 2 -until [ -s "$PROBE_DIR/muse-pid" ]; do sleep 0.01; done +until [ -e "$PROBE_DIR/muse-started" ]; do sleep 0.01; done set -m sleep 30 & printf '%s\n%s\n' "$$" "$!" > "$PROBE_DIR/claude-pids" @@ -125,7 +128,7 @@ wait "{}", result.stderr ); - for file in ["claude-pids", "muse-pid"] { + for file in ["claude-pids", "muse-pids"] { for pid in std::fs::read_to_string(scenario.path(file)) .unwrap() .lines() From 45074ee8d7c273c996e9ea8b25d5a93095ae82b0 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sat, 5 Dec 2026 09:42:10 -0500 Subject: [PATCH 2/2] Apply review findings for bounded Plan usage exchanges --- src/process.rs | 136 ++++++++++++++++++++++--------------------- src/process/pipe.rs | 66 ++++++++++++++------- src/process/tests.rs | 57 ++++++++++++++++++ 3 files changed, 174 insertions(+), 85 deletions(-) diff --git a/src/process.rs b/src/process.rs index 872561a9f..cd7663c8e 100644 --- a/src/process.rs +++ b/src/process.rs @@ -141,21 +141,20 @@ pub(crate) fn one_shot( stdout: Stdout, deadline: Instant, ) -> Result { - let cancelled = Arc::new(AtomicBool::new(false)); - let reader_cancelled = Arc::clone(&cancelled); + let limit = pipe::Limit::new(deadline); + let reader_limit = limit.clone(); let cli = name.to_owned(); let (execution, _) = execute( command, None, - Operation::OneShot { + Operation::Bounded { name, - stdout, - cancelled: &cancelled, + mode: BoundedMode::OneShot(stdout), + limit: &limit, }, - Some(deadline), &|| Ok(()), move |pipe| { - pipe::Cancellable::new(pipe, reader_cancelled) + pipe::Cancellable::new(pipe, reader_limit) .and_then(read) .with_context(|| format!("could not read {cli}'s stdout")) }, @@ -171,7 +170,10 @@ pub(crate) fn one_shot( /// deadline or interruption stops the exchange. The consumer returns any /// replies it collected, including at a deadline. A cancelled read reports /// an I/O error, so the consumer can distinguish it from actual EOF. -/// Interruption discards replies. Every return stops and reaps owned work. +/// The consumer must return on EOF or a read error and avoid blocking +/// independently of the supplied reader, because cleanup joins its worker. +/// Interruption discards replies. Cleanup stops owned work, reaps the +/// launcher and joins both I/O workers before returning. /// An expired deadline can leave no consumer result if the reader never ran. pub(crate) fn exchange( command: &mut Command, @@ -180,20 +182,20 @@ pub(crate) fn exchange( deadline: Instant, consume: impl FnOnce(&mut dyn Read) -> T + Send + 'static, ) -> Result> { - let cancelled = Arc::new(AtomicBool::new(false)); - let reader_cancelled = Arc::clone(&cancelled); + let limit = pipe::Limit::new(deadline); + let reader_limit = limit.clone(); let (completed, recovered) = mpsc::sync_channel(1); let (execution, _) = execute( command, Some(input), - Operation::Exchange { + Operation::Bounded { name, - cancelled: &cancelled, + mode: BoundedMode::Exchange, + limit: &limit, }, - Some(deadline), &|| Ok(()), move |pipe| { - let mut stdout = pipe::Cancellable::new(pipe, reader_cancelled)?; + let mut stdout = pipe::Cancellable::new(pipe, reader_limit)?; let _ = completed.send(consume(&mut stdout)); Ok(()) }, @@ -248,8 +250,7 @@ fn captured( let (execution, _) = execute( command, input, - Operation::Capture(control), - deadline, + Operation::Capture(control, deadline), check, move |pipe| read(pipe).with_context(|| format!("could not read {cli}'s stdout")), ); @@ -287,8 +288,7 @@ pub(crate) fn streaming( let (execution, started) = execute( command, input, - Operation::Stream(control), - deadline, + Operation::Stream(control, deadline), &|| Ok(()), move |pipe| { let result = consume(pipe, &mut state); @@ -315,24 +315,26 @@ fn read(mut pipe: impl Read) -> std::io::Result> { #[derive(Clone, Copy)] enum Operation<'a> { - Capture(Control<'a>), - Stream(Control<'a>), - OneShot { + Capture(Control<'a>, Option), + Stream(Control<'a>, Option), + Bounded { name: &'a str, - stdout: Stdout, - cancelled: &'a Arc, - }, - Exchange { - name: &'a str, - cancelled: &'a Arc, + mode: BoundedMode, + limit: &'a pipe::Limit, }, } +#[derive(Clone, Copy)] +enum BoundedMode { + OneShot(Stdout), + Exchange, +} + enum Stop<'a> { Configured(&'a dyn Fn(&mut Child)), Hard { group: tree::OwnedGroup, - cancelled: &'a AtomicBool, + limit: &'a pipe::Limit, }, } @@ -346,36 +348,42 @@ fn execute<'a, T: Send + 'static>( invocation: &'a mut dyn Invocation, input: Option<&[u8]>, operation: Operation<'a>, - deadline: Option, check: &'a dyn Fn() -> Result<()>, consume: impl FnOnce(ChildStdout) -> Result + Send + 'static, ) -> (Result>, bool) { let (command, observer) = invocation.parts(); - let (name, interruption) = match operation { - Operation::Capture(control) | Operation::Stream(control) => { - (control.name, control.interruption) + let (name, interruption, deadline) = match operation { + Operation::Capture(control, deadline) | Operation::Stream(control, deadline) => { + (control.name, control.interruption, deadline) } - Operation::OneShot { name, .. } | Operation::Exchange { name, .. } => { - (name, Interruption::Ordinary) + Operation::Bounded { name, limit, .. } => { + (name, Interruption::Ordinary, Some(limit.deadline)) } }; let capture_stdout = !matches!( operation, - Operation::OneShot { - stdout: Stdout::Discard, + Operation::Bounded { + mode: BoundedMode::OneShot(Stdout::Discard), .. } ); + let exchange_limit = if let Operation::Bounded { + mode: BoundedMode::Exchange, + limit, + .. + } = operation + { + Some(limit) + } else { + None + }; let mut started = false; let result = (|| { if interruption.requested() { bail!("interrupted"); } check()?; - if matches!( - operation, - Operation::OneShot { .. } | Operation::Exchange { .. } - ) { + if matches!(operation, Operation::Bounded { .. }) { check_deadline(deadline)?; } let cli = name.to_owned(); @@ -397,26 +405,26 @@ fn execute<'a, T: Send + 'static>( // Streaming callers can retain private stderr in a file. Otherwise a // new Command's default already inherits it, as ordinary sessions do. match operation { - Operation::Capture(_) => { + Operation::Capture(..) => { command.stderr(Stdio::piped()); } - Operation::OneShot { .. } | Operation::Exchange { .. } => { + Operation::Bounded { .. } => { command.stderr(Stdio::null()); } - Operation::Stream(_) => {} + Operation::Stream(..) => {} } let child = command .spawn() .with_context(|| NotStarted { name: cli.clone() })?; let (stop, session) = match operation { - Operation::Capture(control) | Operation::Stream(control) => ( + Operation::Capture(control, _) | Operation::Stream(control, _) => ( Stop::Configured(control.stop), session::Session::of(command), ), - Operation::OneShot { cancelled, .. } | Operation::Exchange { cancelled, .. } => ( + Operation::Bounded { limit, .. } => ( Stop::Hard { group: tree::OwnedGroup::new(&child), - cancelled, + limit, }, None, ), @@ -436,7 +444,7 @@ fn execute<'a, T: Send + 'static>( stdout: None, stderr: None, stdin: None, - finish_on_stdout: matches!(operation, Operation::Exchange { .. }), + finish_on_stdout: exchange_limit.is_some(), completed: false, }; let result = (|| { @@ -448,7 +456,7 @@ fn execute<'a, T: Send + 'static>( .stdout .take() .with_context(|| format!("no stdout from {name}"))?; - let reader = if matches!(operation, Operation::Stream(_)) { + let reader = if matches!(operation, Operation::Stream(..)) { "the session stream reader".to_string() } else { format!("{cli}'s stdout reader") @@ -463,7 +471,7 @@ fn execute<'a, T: Send + 'static>( consume(pipe) })?); } - if matches!(operation, Operation::Capture(_)) { + if matches!(operation, Operation::Capture(..)) { #[cfg(test)] fault.fire("stderr-pipe")?; let pipe = owned.child.stderr.take().context("no captured stderr")?; @@ -491,12 +499,7 @@ fn execute<'a, T: Send + 'static>( #[cfg(test)] fault.fire("stdin-start")?; let input = input.to_vec(); - let exchange_cancelled = match operation { - Operation::Exchange { cancelled, .. } => Some(Arc::clone(cancelled)), - Operation::Capture(_) | Operation::Stream(_) | Operation::OneShot { .. } => { - None - } - }; + let exchange_limit = exchange_limit.cloned(); #[cfg(test)] let stdin_fault = fault.clone(); owned.stdin = Some(Worker::start( @@ -505,8 +508,8 @@ fn execute<'a, T: Send + 'static>( move || { #[cfg(test)] stdin_fault.fire("stdin-write")?; - if let Some(cancelled) = exchange_cancelled { - let mut pipe = pipe::Cancellable::new(pipe, cancelled)?; + if let Some(limit) = exchange_limit { + let mut pipe = pipe::Cancellable::new(pipe, limit)?; // A server can close its input and still reply. let _ = pipe.write_all(&input); return Ok(Some(pipe.into_inner())); @@ -587,12 +590,13 @@ impl Execution<'_, T> { .map(Worker::poll) .transpose()? .unwrap_or(true); - let stdout_done = self - .stdout - .as_mut() - .map(Worker::poll) - .transpose()? - .unwrap_or(true); + let stdout = self.stdout.as_mut().map(Worker::poll).transpose(); + if matches!(self.stop, Stop::Hard { .. }) { + // A pipe can reach the shared deadline between the start + // of this iteration and polling its worker. + check_deadline(self.deadline)?; + } + let stdout_done = stdout?.unwrap_or(true); if self.finish_on_stdout && stdout_done { return self .cleanup() @@ -619,6 +623,8 @@ impl Execution<'_, T> { return Ok(status); } if let Stop::Hard { group, .. } = &mut self.stop { + #[cfg(test)] + tests::before_group_observation(); group.observe(status.is_none()); } // Worker completion (including unwind) wakes us immediately. @@ -646,8 +652,8 @@ impl Execution<'_, T> { fn cleanup(&mut self) -> io::Result { match &mut self.stop { Stop::Configured(stop) => stop(&mut self.child), - Stop::Hard { group, cancelled } => { - cancelled.store(true, Ordering::Release); + Stop::Hard { group, limit } => { + limit.cancel(); group.kill(&mut self.child); } } diff --git a/src/process/pipe.rs b/src/process/pipe.rs index f4f39c312..87220b8b4 100644 --- a/src/process/pipe.rs +++ b/src/process/pipe.rs @@ -4,14 +4,47 @@ use std::io::{self, Read, Write}; use std::os::fd::AsRawFd; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +#[derive(Clone)] +pub(super) struct Limit { + pub(super) deadline: Instant, + cancelled: Arc, +} + +impl Limit { + pub(super) fn new(deadline: Instant) -> Self { + Self { + deadline, + cancelled: Arc::new(AtomicBool::new(false)), + } + } + + pub(super) fn cancel(&self) { + self.cancelled.store(true, Ordering::Release); + } + + fn remaining(&self) -> io::Result { + if self.cancelled.load(Ordering::Acquire) { + // A read cancelled with a buffered partial line must not look + // like EOF to a consumer. Interrupted would cause a retry. + return Err(io::Error::other("process pipe cancelled")); + } + let remaining = self.deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(io::ErrorKind::TimedOut.into()); + } + Ok(remaining) + } +} pub(super) struct Cancellable

{ pipe: P, - cancelled: Arc, + limit: Limit, } impl Cancellable

{ - pub(super) fn new(pipe: P, cancelled: Arc) -> io::Result { + pub(super) fn new(pipe: P, limit: Limit) -> io::Result { let fd = pipe.as_raw_fd(); // SAFETY: both calls use a live descriptor borrowed from the pipe. unsafe { @@ -20,22 +53,13 @@ impl Cancellable

{ return Err(io::Error::last_os_error()); } } - Ok(Self { pipe, cancelled }) + Ok(Self { pipe, limit }) } pub(super) fn into_inner(self) -> P { self.pipe } - fn check_cancelled(&self) -> io::Result<()> { - if self.cancelled.load(Ordering::Acquire) { - // A read cancelled with a buffered partial line must not look - // like EOF to a consumer. Interrupted would cause a retry. - return Err(io::Error::other("process pipe cancelled")); - } - Ok(()) - } - fn with_ready( &mut self, events: libc::c_short, @@ -47,14 +71,20 @@ impl Cancellable

{ revents: 0, }; loop { - self.check_cancelled()?; + let remaining = self.limit.remaining()?; match io(&mut self.pipe) { Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, Err(error) if error.kind() == io::ErrorKind::WouldBlock => {} - result => return result, + result => { + // Cleanup can close the peer during this call, and the + // deadline can pass while the supervisor is observing. + self.limit.remaining()?; + return result; + } } + let millis = remaining.as_millis().clamp(1, 100) as libc::c_int; // SAFETY: poll borrows one initialized descriptor owned by this pipe. - if unsafe { libc::poll(&mut descriptor, 1, 100) } == -1 { + if unsafe { libc::poll(&mut descriptor, 1, millis) } == -1 { let error = io::Error::last_os_error(); if error.kind() != io::ErrorKind::Interrupted { return Err(error); @@ -66,11 +96,7 @@ impl Cancellable

{ impl Read for Cancellable

{ fn read(&mut self, buffer: &mut [u8]) -> io::Result { - let read = self.with_ready(libc::POLLIN, |pipe| pipe.read(buffer))?; - if read == 0 { - self.check_cancelled()?; - } - Ok(read) + self.with_ready(libc::POLLIN, |pipe| pipe.read(buffer)) } } diff --git a/src/process/tests.rs b/src/process/tests.rs index 5214809fd..28a43186a 100644 --- a/src/process/tests.rs +++ b/src/process/tests.rs @@ -9,6 +9,17 @@ use std::time::Instant; use tempfile::TempDir; +thread_local! { + static BEFORE_GROUP_OBSERVATION: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +pub(super) fn before_group_observation() { + if let Some(before_observation) = BEFORE_GROUP_OBSERVATION.with(|hook| hook.take()) { + before_observation(); + } +} + fn shell(script: &str) -> Command { let mut command = Command::new("bash"); command.args(["-c", script]); @@ -725,6 +736,52 @@ fn exchange_keeps_complete_replies_at_the_deadline_with_both_pipes_held_open() { holder.assert_exited(); } +#[test] +fn exchange_rejects_replies_after_the_deadline_during_a_slow_group_observation() { + use std::io::{BufRead, BufReader}; + + let launcher = RecordedProcess::new(); + let release = launcher.0.path().join("release"); + let mut command = launcher.command( + r#" + echo $$ > "$PID_FILE" + read -r request && [ "$request" = 'request' ] || exit 1 + until [ -e "$RELEASE" ]; do sleep 0.01; done + printf 'late reply\n' + exec sleep 20 + "#, + ); + command.env("RELEASE", &release); + let deadline = Instant::now() + Duration::from_secs(5); + let (reader_done, observed_done) = mpsc::channel(); + BEFORE_GROUP_OBSERVATION.with(|hook| { + hook.replace(Some(Box::new(move || { + thread::sleep(deadline.saturating_duration_since(Instant::now())); + fs::write(release, b"").unwrap(); + observed_done.recv_timeout(Duration::from_secs(4)).unwrap(); + }))); + }); + + let reply = exchange( + &mut command, + "fixture", + b"request\n", + deadline, + move |stdout| { + let reply = BufReader::new(stdout) + .lines() + .next() + .and_then(|line| line.ok()); + let _ = reader_done.send(()); + reply + }, + ) + .unwrap(); + + assert_eq!(reply.flatten(), None); + launcher.assert_stopped(); +} + #[test] fn exchange_collects_a_final_line_at_stdout_eof_even_if_the_write_ends_early() { use std::io::{BufRead, BufReader};