Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
test(cli): drain layout probe output while waiting for exit
ldm02392c3994915
diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rsindex a14f027e1..1ceba3c36 100644--- a/moli/tests/fetch_cli.rs+++ b/moli/tests/fetch_cli.rs@@ -59,6 +59,8 @@ mod markdown;mod readiness;#[path = "fetch_cli/redirect_chain.rs"]mod redirect_chain;+#[path = "fetch_cli/subprocess.rs"]+mod subprocess;struct Output {status: OutputStatus,diff --git a/moli/tests/fetch_cli/http_fail.rs b/moli/tests/fetch_cli/http_fail.rsindex a9e41ec17..c01bb7617 100644--- a/moli/tests/fetch_cli/http_fail.rs+++ b/moli/tests/fetch_cli/http_fail.rs@@ -1,4 +1,4 @@-use anyhow::{Context, Result, ensure};+use anyhow::{Context, Result};use axum::{Router,extract::Path,@@ -11,9 +11,9 @@ use clap::Parser;use moli::{app, cli::Cli};use serde_json::{Value, json};use std::{- io::{self, Read, Write},- process::{Child, Command, ExitCode, Output, Stdio},- time::{Duration, Instant},+ io::{self, Write},+ process::{Command, ExitCode, Output},+ time::Duration,};use tokio::{io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},@@ -21,6 +21,8 @@ use tokio::{task::JoinHandle,};+use super::subprocess::run_command_with_process_timeout;+const HTML: &str ="<!doctype html><title>HTTP fixture</title><h1>HTTP fixture</h1><p>response body</p>";const RAW_BODY: &[u8] = b"\0\xffraw HTTP error body";@@ -187,57 +189,6 @@ impl Drop for HttpFailureFixture {}}-struct KillOnDropChild(Child);--impl Drop for KillOnDropChild {- fn drop(&mut self) {- let _ = self.0.kill();- let _ = self.0.wait();- }-}--fn read_process_pipe(mut pipe: impl Read) -> io::Result<Vec<u8>> {- let mut bytes = Vec::new();- pipe.read_to_end(&mut bytes)?;- Ok(bytes)-}--fn run_command_with_process_timeout(mut command: Command, timeout: Duration) -> Result<Output> {- std::thread::scope(|scope| {- let mut child = KillOnDropChild(- command- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()?,- );- let stdout = child.0.stdout.take().expect("CLI stdout must be piped");- let stderr = child.0.stderr.take().expect("CLI stderr must be piped");- // Drain both pipes while polling so large output cannot block exit.- let stdout = scope.spawn(move || read_process_pipe(stdout));- let stderr = scope.spawn(move || read_process_pipe(stderr));- let started = Instant::now();- let status = loop {- if let Some(status) = child.0.try_wait()? {- break status;- }- // The guard kills and reaps the child before the scoped pipe- // readers are joined, including on timeout or an early error.- ensure!(- started.elapsed() < timeout,- "CLI subprocess did not exit within {} ms",- timeout.as_millis()- );- std::thread::sleep(Duration::from_millis(10));- };- Ok(Output {- status,- stdout: stdout.join().expect("CLI stdout reader must not panic")?,- stderr: stderr.join().expect("CLI stderr reader must not panic")?,- })- })-}-struct FailingOutput {fail_on_flush: bool,written: Vec<u8>,diff --git a/moli/tests/fetch_cli/layout_regressions.rs b/moli/tests/fetch_cli/layout_regressions.rsindex f59afec7b..7a879052f 100644--- a/moli/tests/fetch_cli/layout_regressions.rs+++ b/moli/tests/fetch_cli/layout_regressions.rs@@ -1,12 +1,8 @@-use super::clean_output;-use anyhow::{Context, Result, bail};+use super::{clean_output, subprocess::run_command_with_process_timeout};+use anyhow::{Context, Result, ensure};use base64::{Engine as _, engine::general_purpose::STANDARD};use serde_json::Value;-use std::{- process::{Command, Stdio},- thread,- time::{Duration, Instant},-};+use std::{process::Command, time::Duration};fn run_layout(html: &str, expression: &str, fonts: bool) -> Result<Value> {let url = format!("data:text/html;base64,{}", STANDARD.encode(html));@@ -26,25 +22,16 @@ fn run_layout(html: &str, expression: &str, fonts: bool) -> Result<Value> {if fonts {command.arg("--font");}- let mut child = command- .arg(url)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()?;- let started = Instant::now();- loop {- if child.try_wait()?.is_some() {- break;- }- if started.elapsed() >= Duration::from_secs(10) {- child.kill()?;- let output = child.wait_with_output()?;- bail!("layout did not terminate: {}", clean_output(&output.stderr));- }- thread::sleep(Duration::from_millis(10));- }- let output = child.wait_with_output()?;- assert!(output.status.success(), "{}", clean_output(&output.stderr));+ command.arg(url);+ let output = run_command_with_process_timeout(command, Duration::from_secs(10))+ .context("layout probe process failed")?;+ ensure!(+ output.status.success(),+ "layout probe exited with {}: stdout={} stderr={}",+ output.status,+ clean_output(&output.stdout),+ clean_output(&output.stderr)+ );serde_json::from_slice(&output.stdout).context("layout probe must return JSON")}@@ -67,6 +54,35 @@ fn fractional_grid_track_limits_terminate_with_a_finite_item_width() -> Result<(Ok(())}+#[test]+fn layout_probe_drains_large_evaluation_results_before_waiting_for_exit() -> Result<()> {+ const PAYLOAD_SIZE: usize = 256 * 1024;+ let expression = format!(+ "JSON.stringify({{width:document.querySelector('#item').getBoundingClientRect().width,payload:'x'.repeat({PAYLOAD_SIZE})}})"+ );+ let value = run_layout(+ "<!doctype html><div id='item' style='width:123px'></div>",+ &expression,+ false,+ )?;+ assert_eq!(value["width"], 123);+ assert_eq!(value["payload"], "x".repeat(PAYLOAD_SIZE));+ Ok(())+}++#[test]+fn layout_probe_drains_large_script_errors_before_reporting_exit_failure() {+ let error = run_layout(+ "<!doctype html><p>probe</p>",+ "throw new Error('layout-stderr-marker:' + 'x'.repeat(256 * 1024))",+ false,+ )+ .expect_err("the script error must fail the probe");+ let message = format!("{error:#}");+ assert!(message.contains("layout probe exited with"));+ assert!(message.contains("layout-stderr-marker:"));+}+fn probe_font_document(body: &str) -> String {let font = STANDARD.encode(include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"),diff --git a/moli/tests/fetch_cli/subprocess.rs b/moli/tests/fetch_cli/subprocess.rsnew file mode 100644index 000000000..2a1110745--- /dev/null+++ b/moli/tests/fetch_cli/subprocess.rs@@ -0,0 +1,150 @@+use super::clean_output;+use anyhow::{Context, Result};+use std::{+ fmt,+ io::{self, Read},+ process::{Child, Command, Output, Stdio},+ time::{Duration, Instant},+};++struct KillOnDropChild(Child);++impl Drop for KillOnDropChild {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+}++#[derive(Debug)]+struct ProcessTimeout {+ child_id: u32,+ timeout: Duration,+ output: Output,+}++fn output_preview(bytes: &[u8]) -> String {+ const LIMIT: usize = 4096;+ let mut preview = clean_output(&bytes[..bytes.len().min(LIMIT)]);+ if bytes.len() > LIMIT {+ preview.push_str("... (truncated)");+ }+ preview+}++impl fmt::Display for ProcessTimeout {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(+ f,+ "CLI subprocess {} did not exit within {} ms; status={}; stdout={:?}; stderr={:?}",+ self.child_id,+ self.timeout.as_millis(),+ self.output.status,+ output_preview(&self.output.stdout),+ output_preview(&self.output.stderr)+ )+ }+}++impl std::error::Error for ProcessTimeout {}++fn read_process_pipe(mut pipe: impl Read) -> io::Result<Vec<u8>> {+ let mut bytes = Vec::new();+ pipe.read_to_end(&mut bytes)?;+ Ok(bytes)+}++pub(super) fn run_command_with_process_timeout(+ mut command: Command,+ timeout: Duration,+) -> Result<Output> {+ std::thread::scope(|scope| {+ let mut child = KillOnDropChild(+ command+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()?,+ );+ let child_id = child.0.id();+ let stdout = child.0.stdout.take().expect("CLI stdout must be piped");+ let stderr = child.0.stderr.take().expect("CLI stderr must be piped");+ // Read both streams while the child runs. Waiting for exit first can+ // deadlock even after layout finishes if either pipe fills up.+ let stdout = scope.spawn(move || read_process_pipe(stdout));+ let stderr = scope.spawn(move || read_process_pipe(stderr));+ let started = Instant::now();+ let timed_out = loop {+ if child.0.try_wait()?.is_some() {+ break false;+ }+ if started.elapsed() >= timeout {+ child+ .0+ .kill()+ .context("failed to kill timed-out CLI child")?;+ break true;+ }+ std::thread::sleep(Duration::from_millis(10));+ };+ // Reap before joining readers, including after a timeout. The guard+ // does the same on early errors so a blocked child cannot outlive us.+ let output = Output {+ status: child.0.wait()?,+ stdout: stdout.join().expect("CLI stdout reader must not panic")?,+ stderr: stderr.join().expect("CLI stderr reader must not panic")?,+ };+ if timed_out {+ return Err(ProcessTimeout {+ child_id,+ timeout,+ output,+ }+ .into());+ }+ Ok(output)+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ const CHILD_MODE: &str = "MOLI_CLI_TEST_SUBPROCESS_MODE";++ #[test]+ fn timeout_kills_and_reaps_child_and_preserves_both_output_streams() -> Result<()> {+ if std::env::var(CHILD_MODE).as_deref() == Ok("hang") {+ std::io::stdout().write_all(b"stdout-before-hang\n")?;+ std::io::stdout().flush()?;+ std::io::stderr().write_all(b"stderr-before-hang\n")?;+ std::io::stderr().flush()?;+ loop {+ std::thread::park();+ }+ }+ let current = std::thread::current();+ let test_name = current+ .name()+ .context("libtest must name the test thread")?;+ let mut command = Command::new(std::env::current_exe()?);+ command+ .args(["--exact", test_name, "--nocapture"])+ .env(CHILD_MODE, "hang");+ let error = run_command_with_process_timeout(command, Duration::from_secs(2))+ .expect_err("the child deliberately never exits");+ let message = error.to_string();+ assert!(message.contains("stdout-before-hang"));+ assert!(message.contains("stderr-before-hang"));+ let timeout = error.downcast::<ProcessTimeout>()?;+ assert_eq!(timeout.timeout, Duration::from_secs(2));+ assert!(!timeout.output.status.success());+ #[cfg(target_os = "linux")]+ assert!(+ !std::path::Path::new(&format!("/proc/{}", timeout.child_id)).exists(),+ "timed-out child must be reaped"+ );+ Ok(())+ }+}