diff --git a/crates/ide-build/src/process.rs b/crates/ide-build/src/process.rs index 12d2b4621..53f039830 100644 --- a/crates/ide-build/src/process.rs +++ b/crates/ide-build/src/process.rs @@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024; /// `Output::text` stops growing past this while the pipes keep draining: a chatty build can /// print far more than is ever parsed back out of the retained copy. pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024; +/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than +/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of +/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]). +const LINE_QUEUE: usize = 64; +/// What [`pump_bounded`] reads from a pipe at a time. +const PUMP_CHUNK: usize = 64 * 1024; + +/// One line of a child's output, with the stream it came from. +type Line = (Stream, String); + +/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the +/// consumer is behind. +fn line_queue() -> (mpsc::SyncSender, mpsc::Receiver) { + mpsc::sync_channel(LINE_QUEUE) +} pub(crate) struct Output { pub success: bool, @@ -33,20 +48,20 @@ pub(crate) struct Output { pub truncated: bool, } -/// Bounded pump for callers that stream every line and only summarize errors: reads fixed -/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and -/// never grows one line buffer without bound. -fn pump_bounded(stream: Box, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) { +/// Bounded pump for callers that stream every line and only summarize errors: reads +/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, +/// and never grows one line buffer without bound. +fn pump_bounded(stream: Box, kind: Stream, tx: &mpsc::SyncSender) { let mut reader = BufReader::new(stream); // `terminated`: the buffer ends in the stream's newline. A segment cut from a // newline-free run at the line cap must keep a trailing `\r` — it is data. - let send = |buf: &mut Vec, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| { + let send = |buf: &mut Vec, terminated: bool, tx: &mpsc::SyncSender| { let line = ide_core::output_encoding::decode_tool_output(buf); let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line }; buf.clear(); tx.send((kind, line)).is_ok() }; - let mut chunk = vec![0u8; 64 * 1024]; + let mut chunk = vec![0u8; PUMP_CHUNK]; let mut line: Vec = Vec::with_capacity(256); 'read: loop { let n = match reader.read(&mut chunk) { @@ -179,8 +194,8 @@ fn run_with_env_capture( } let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?; - let (tx, rx) = mpsc::channel::<(Stream, String)>(); - let pump = |stream: Box, kind: Stream, tx: mpsc::Sender<(Stream, String)>| { + let (tx, rx) = line_queue(); + let pump = |stream: Box, kind: Stream, tx: mpsc::SyncSender| { std::thread::spawn(move || { if bounded { pump_bounded(stream, kind, &tx); @@ -212,7 +227,8 @@ fn run_with_env_capture( // Retained copy of the output: the first half of the cap, then — once output overflows — // a rolling tail instead of the middle. Error summaries read the end of the output, while // listings parsed out of a successful run read from the start. The pipes keep draining - // either way: `on_line` still sees every line, so the child never blocks on a full pipe. + // either way: `on_line` still sees every line, and the child waits on its pipe only + // while `on_line` is behind, never because the retained copy is full. let cap = MAX_TEXT_BYTES / 2; let mut head = String::new(); let mut tail: std::collections::VecDeque> = Default::default(); @@ -295,6 +311,9 @@ fn run_with_env_capture( #[cfg(test)] mod tests { use super::*; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Instant; #[test] fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() { @@ -500,4 +519,124 @@ mod tests { assert!(out.text.starts_with("pad\n")); assert!(out.text.ends_with("FATAL: the real error\n")); } + + /// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that + /// reports when it is dropped, which is when the pump owning it ends. + const LINE_LEN: usize = 100; + + struct NumberedLines { + next: usize, + lines: usize, + taken: Arc, + gone: mpsc::Sender<()>, + } + + fn numbered(n: usize) -> String { + format!("{n:0width$}", width = LINE_LEN - 1) + } + + impl Read for NumberedLines { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let mut n = 0; + while self.next < self.lines && n + LINE_LEN <= buf.len() { + buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes()); + buf[n + LINE_LEN - 1] = b'\n'; + self.next += 1; + n += LINE_LEN; + } + self.taken.fetch_add(n, Ordering::SeqCst); + Ok(n) + } + } + + impl Drop for NumberedLines { + fn drop(&mut self) { + let _ = self.gone.send(()); + } + } + + #[test] + fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() { + const LINES: usize = 50_000; + let taken = Arc::new(AtomicUsize::new(0)); + let (gone, _) = mpsc::channel(); + let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone }; + let (tx, rx) = line_queue(); + let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx)); + let (mut count, mut peak) = (0usize, 0usize); + loop { + match rx.recv_timeout(Duration::from_secs(60)) { + Ok((stream, line)) => { + assert_eq!(stream, Stream::Stdout); + assert_eq!(line, numbered(count), "a line arrived out of order or damaged"); + // Read from the pipe but not yet handed over: the rest of the chunk the pump + // is cutting into lines, and the queue. + peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN); + count += 1; + // A consumer that cannot keep up with the process. + if count.is_multiple_of(LINE_QUEUE) { + std::thread::sleep(Duration::from_millis(1)); + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"), + } + } + pump.join().unwrap(); + assert_eq!(count, LINES); + let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN; + assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}"); + } + + #[test] + fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() { + let taken = Arc::new(AtomicUsize::new(0)); + let (gone_tx, gone) = mpsc::channel(); + // Far more than the queue and a few chunks hold. + let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx }; + let (tx, rx) = line_queue(); + let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx)); + // A consumer that takes nothing: the queue fills, with the pump inside its first chunk. + let deadline = Instant::now() + Duration::from_secs(30); + while taken.load(Ordering::SeqCst) == 0 { + assert!(Instant::now() < deadline, "the pump never read"); + std::thread::sleep(Duration::from_millis(1)); + } + // Time for a pump that does not wait to run ahead. + std::thread::sleep(Duration::from_millis(100)); + assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue"); + assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there"); + drop(rx); + gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone"); + pump.join().unwrap(); + } + + #[test] + fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() { + if cfg!(windows) { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()]; + for bounded in [false, true] { + let mut next = 1usize; + let on_line = |stream: Stream, line: &str| { + assert_eq!(stream, Stream::Stdout); + assert_eq!(line, next.to_string()); + next += 1; + if next.is_multiple_of(1000) { + std::thread::sleep(Duration::from_millis(1)); + } + }; + let cancel = CancellationToken::new(); + let out = if bounded { + run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line) + } else { + run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line) + } + .unwrap(); + assert!(!out.success); + assert_eq!(next, 300_001, "lines were lost"); + } + } } diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 9995cd8f1..773c3aa55 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -12,11 +12,17 @@ use std::path::{Path, PathBuf}; use std::process::{Command, ExitStatus, Stdio}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{self, RecvTimeoutError, Sender}; +use std::sync::mpsc::{self, RecvTimeoutError, SyncSender}; use std::time::{Duration, Instant}; const BATCH_INTERVAL: Duration = Duration::from_millis(8); const BATCH_BYTES: usize = 64 * 1024; +/// Size of one pipe read, so the most one queued [`Msg::Data`] holds. +const READ_BUF: usize = 16 * 1024; +/// Chunks the readers may queue ahead of the pump (at most `OUTPUT_QUEUE_CHUNKS * READ_BUF`, +/// 2 MiB). A process printing faster than the console takes its output waits on its full +/// pipe, as it would on a terminal, instead of piling the flood up in memory here. +const OUTPUT_QUEUE_CHUNKS: usize = 128; /// After the main process exits, how long to wait for pipes still held by /// orphaned descendants before reporting the exit. const EXIT_DRAIN: Duration = Duration::from_millis(500); @@ -112,6 +118,12 @@ enum Msg { Exited(Exit), } +/// The queue from the readers (and the waiter) to the pump: bounded, so the readers wait +/// while the pump is behind. +fn output_queue() -> (SyncSender, mpsc::Receiver) { + mpsc::sync_channel(OUTPUT_QUEUE_CHUNKS) +} + /// The program and arguments actually executed, plus the echoed command line. pub(crate) struct Invocation { pub program: PathBuf, @@ -484,7 +496,7 @@ impl ProcessManager { on_output(OutputChunk::System { text: format!("{}\n", inv.display) }); - let (tx, rx) = mpsc::channel(); + let (tx, rx) = output_queue(); let stdout = child.stdout.take(); let stderr = child.stderr.take(); let result = (|| -> std::io::Result<()> { @@ -631,7 +643,7 @@ impl ProcessManager { self.register(entry.clone()); on_output(OutputChunk::System { text: format!("{}\n", inv.display) }); - let (tx, rx) = mpsc::channel(); + let (tx, rx) = output_queue(); let result = spawn_reader( id, Stream::Stdout, @@ -824,7 +836,7 @@ fn run_followup( config: &RunConfig, cwd: &Path, entry: &Entry, - tx: &Sender, + tx: &SyncSender, ) -> std::io::Result { let mut pid = entry.pid.lock(); if entry.stopping.load(Ordering::Acquire) { @@ -1106,16 +1118,19 @@ fn kill_tree(entry: &Entry, pid: u32, _force: bool) { .status(); } +/// Reads `pipe` into `tx` until EOF. It waits in `send` while the pump is a full queue behind +/// (the process then waits on its pipe). The pump dropping its receiver fails the `send` +/// and ends the reader, so no reader stays blocked once the pump is gone. fn spawn_reader( id: RunId, stream: Stream, mut pipe: impl Read + Send + 'static, - tx: Sender, + tx: SyncSender, #[cfg(unix)] mut wait_readable: Option std::io::Result<()> + Send>>, ) -> std::io::Result<()> { let label = if stream == Stream::Stdout { "out" } else { "err" }; std::thread::Builder::new().name(format!("openidea-run-{label}-{}", id.0)).spawn(move || { - let mut buf = vec![0u8; 16 * 1024]; + let mut buf = vec![0u8; READ_BUF]; loop { match pipe.read(&mut buf) { Ok(0) => break, @@ -1424,6 +1439,7 @@ fn input_writer( #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::AtomicUsize; #[cfg(unix)] #[test] @@ -1569,4 +1585,109 @@ mod tests { assert_eq!(resolve_program("./gradlew", cwd, &config, true), cwd.join("./gradlew")); assert_eq!(resolve_program(".venv/bin/python", cwd, &config, false), cwd.join(".venv/bin/python")); } + + /// A pipe stand-in that counts the bytes taken from it. + struct Counted { + inner: R, + taken: Arc, + } + + impl Read for Counted { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.taken.fetch_add(n, Ordering::SeqCst); + Ok(n) + } + } + + #[cfg(unix)] + #[test] + fn a_slow_pump_holds_a_flooding_process_back_instead_of_queueing_its_output() { + const LINES: usize = 2_000_000; + // (Not `seq`: macOS prints large numbers in exponent form.) + let mut child = Command::new("awk") + .arg(format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}")) + .stdout(Stdio::piped()) + .spawn() + .expect("awk"); + let taken = Arc::new(AtomicUsize::new(0)); + let pipe = Counted { inner: child.stdout.take().unwrap(), taken: taken.clone() }; + let (tx, rx) = output_queue(); + spawn_reader(RunId::next(), Stream::Stdout, pipe, tx, None).unwrap(); + let (mut received, mut peak, mut all) = (0usize, 0usize, Vec::new()); + loop { + match rx.recv_timeout(Duration::from_secs(60)) { + Ok(Msg::Data(stream, bytes)) => { + assert!(stream == Stream::Stdout); + // Read from the pipe but not yet handled: the queue, plus the chunk the + // reader holds while it waits for room, plus the one just received. + peak = peak.max(taken.load(Ordering::SeqCst) - received); + received += bytes.len(); + all.extend_from_slice(&bytes); + // A console that cannot keep up with the process. + std::thread::sleep(Duration::from_millis(1)); + } + Ok(Msg::Exited(_)) => unreachable!("only the waiter sends the exit"), + Err(mpsc::RecvTimeoutError::Disconnected) => break, + Err(mpsc::RecvTimeoutError::Timeout) => panic!("the reader stalled"), + } + } + assert!(child.wait().unwrap().success()); + let bound = (OUTPUT_QUEUE_CHUNKS + 2) * READ_BUF; + assert!(peak <= bound, "{peak} bytes queued ahead of the pump, more than {bound}"); + let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect(); + assert!(all == expected.as_bytes(), "the output arrived incomplete or out of order"); + } + + /// Endless output (cut at a size an unbounded queue could still hold in a test) that + /// reports when it is dropped, which is when the reader thread owning it ends. + struct Endless { + served: Arc, + gone: mpsc::Sender<()>, + } + + impl Read for Endless { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.served.load(Ordering::SeqCst) >= 8 * OUTPUT_QUEUE_CHUNKS { + return Ok(0); + } + self.served.fetch_add(1, Ordering::SeqCst); + buf.fill(b'x'); + Ok(buf.len()) + } + } + + impl Drop for Endless { + fn drop(&mut self) { + let _ = self.gone.send(()); + } + } + + #[test] + fn a_reader_blocked_on_a_full_queue_ends_when_the_pump_is_gone() { + let served = Arc::new(AtomicUsize::new(0)); + let (gone_tx, gone) = mpsc::channel(); + let (tx, rx) = output_queue(); + spawn_reader( + RunId::next(), + Stream::Stdout, + Endless { served: served.clone(), gone: gone_tx }, + tx, + #[cfg(unix)] + None, + ) + .unwrap(); + // A pump that takes nothing: the queue fills and the reader holds one more chunk. + let deadline = Instant::now() + Duration::from_secs(30); + while served.load(Ordering::SeqCst) < OUTPUT_QUEUE_CHUNKS + 1 { + assert!(Instant::now() < deadline, "the reader never filled the queue"); + std::thread::sleep(Duration::from_millis(1)); + } + // Time for a reader that does not wait to run ahead. + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(served.load(Ordering::SeqCst), OUTPUT_QUEUE_CHUNKS + 1, "the reader ran past the full queue"); + assert!(gone.try_recv().is_err(), "the reader ended while its pump was still there"); + drop(rx); + gone.recv_timeout(Duration::from_secs(30)).expect("the reader stayed blocked after the pump was gone"); + } } diff --git a/crates/ide-run/tests/process.rs b/crates/ide-run/tests/process.rs index 422696d01..ab3401d1d 100644 --- a/crates/ide-run/tests/process.rs +++ b/crates/ide-run/tests/process.rs @@ -278,6 +278,73 @@ fn large_output_is_complete_and_batched() { assert!(chunks.lock().len() < 3000); } +#[test] +fn a_console_slower_than_the_process_still_gets_all_output_in_order_and_the_exit() { + const LINES: usize = 1_000_000; + let h = harness(); + let chunks: Chunks = Arc::default(); + let sink = chunks.clone(); + let info = + h.pm.start( + h.root.path(), + &cfg("t:slow-console", "awk", &[&format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}")]), + &StartOptions::default(), + h.sink.clone(), + Box::new(move |c| { + sink.lock().push(c); + std::thread::sleep(Duration::from_millis(1)); + }), + ) + .expect("start"); + assert_eq!(wait_exit(&h, info.id, Duration::from_secs(120)), Some(0)); + let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect(); + assert!(text(&chunks, stdout) == expected, "the output arrived incomplete or out of order"); + // The exit is reported after the output, never before the last of it. + let all = chunks.lock(); + assert!(matches!(all.last(), Some(OutputChunk::System { text }) if text.contains("exit code 0"))); +} + +#[test] +fn stop_ends_a_flooding_run_whose_console_stalled() { + let h = harness(); + let chunks: Chunks = Arc::default(); + let sink = chunks.clone(); + let (stalled_tx, stalled) = mpsc::channel(); + let (resume_tx, resume) = mpsc::channel::<()>(); + // The first output blocks the console until `resume_tx` is dropped. + let resume = Mutex::new(Some(resume)); + let info = + h.pm.start( + h.root.path(), + &cfg("t:stalled-console", "yes", &[]), + &StartOptions::default(), + h.sink.clone(), + Box::new(move |c| { + let output = matches!(c, OutputChunk::Stdout { .. }); + sink.lock().push(c); + if output && let Some(resume) = resume.lock().take() { + let _ = stalled_tx.send(()); + let _ = resume.recv(); + } + }), + ) + .expect("start"); + stalled.recv_timeout(Duration::from_secs(10)).expect("no output reached the console"); + // The pipe and the queue behind the stalled console fill up and `yes` waits on its pipe. + std::thread::sleep(Duration::from_millis(300)); + h.pm.stop(info.id).unwrap(); + let pid = i32::try_from(info.pid.expect("pid")).unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while alive(pid) { + assert!(Instant::now() < deadline, "the stalled run survived Stop"); + std::thread::sleep(Duration::from_millis(20)); + } + drop(resume_tx); + assert_eq!(wait_exit(&h, info.id, Duration::from_secs(30)), Some(130)); + let out = text(&chunks, stdout); + assert!(!out.is_empty() && out.lines().all(|l| l == "y"), "the output was damaged"); +} + #[test] fn relative_program_resolves_against_cwd() { let h = harness();