Skip to content
Closed
137 changes: 115 additions & 22 deletions src/runtime/cli/test/parallel/Coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use bun_jsc::virtual_machine::VirtualMachine;
use bun_ptr::Interned;

use super::frame::{self, Frame};
use super::worker::{Worker, WorkerPipe};
use super::worker::{PendingLine, Worker, WorkerPipe};
use crate::test_command::CommandLineReporter;

// `Status` lives in `crate::api::bun::process`
Expand Down Expand Up @@ -147,6 +147,7 @@ impl<'a> Coordinator<'a> {
return;
}
self.vm.event_loop_ref().tick();
self.print_arrived_lines();
self.run_pending_reaps();
self.maybe_scale_up();
self.run_pending_reaps();
Expand Down Expand Up @@ -408,19 +409,118 @@ impl<'a> Coordinator<'a> {
}
}

fn flush_captured(&mut self, w: &mut Worker) {
if w.captured.is_empty() {
/// Prints `captured[..end]` under the header of file `idx`.
fn print_captured(&mut self, w: &mut Worker, end: usize, idx: Option<u32>) {
if end == 0 {
return;
}
// The worker already ended the dots line.
if w.captured[0] == b'\n' {
self.last_printed_dot = false;
}
self.break_dots();
if let Some(idx) = w.inflight {
if let Some(idx) = idx {
self.ensure_header(idx);
}
let _ = Output::error_writer().write_all(&w.captured);
let _ = Output::error_writer().write_all(&w.captured[..end]);
w.captured.drain(..end);
Output::flush();
}

/// Drains the worker's pipes (POSIX only: the worker wrote the result
/// line before it sent the frame, so the drain sees it), then prints
/// through each result line that has arrived.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn flush_captured_lines(&mut self, w: &mut Worker) {
#[cfg(unix)]
{
let wp: *mut Worker = w;
// SAFETY: `wp` is the live worker slot; `w` is not used until
// `read` returns.
unsafe {
for pipe in [&raw mut (*wp).out, &raw mut (*wp).err] {
if !(*pipe).done && (*pipe).reader.get_fd() != bun_sys::Fd::INVALID {
bun_io::BufferedReader::read(&raw mut (*pipe).reader);
}
}
}
}
self.print_pending_lines(w);
}

/// Prints pending results in frame order: a stream line once its copy is
/// in `captured`, a dot right away behind the complete lines before it.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn print_pending_lines(&mut self, w: &mut Worker) {
while let Some(p) = w.pending_lines.front() {
let (file_idx, end) = if p.in_stream {
let Some(pos) = strings::index_of(&w.captured, &p.line) else {
break;
};
(p.file_idx, pos + p.line.len())
} else {
(
p.file_idx,
strings::last_index_of_char(&w.captured, b'\n').map_or(0, |nl| nl + 1),
)
Comment thread
robobun marked this conversation as resolved.
Resolved
};
let p = w.pending_lines.pop_front().expect("front was Some");
self.print_captured(w, end, Some(file_idx));
if !p.in_stream && !p.line.is_empty() {
let is_dot = self.dots;
if !is_dot {
self.break_dots();
self.ensure_header(file_idx);
}
let _ = Output::error_writer().write_all(&p.line);
self.last_printed_dot = is_dot;
Output::flush();
}
}
}

/// Windows reads complete through libuv only, so a result line can land
/// after its frame. Called once per loop tick.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn print_arrived_lines(&mut self) {
for i in 0..self.spawned_count as usize {
// SAFETY: `i < spawned_count <= workers.len()`; fresh derivation per slot.
let w = unsafe { &mut *self.workers.as_mut_ptr().add(i) };
if !w.pending_lines.is_empty() {
self.print_pending_lines(w);
}
}
}

/// File end. On POSIX the drain has read everything, so a line still
/// pending never reached the pipe. On Windows it prints with the chunk
/// that carries it.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn flush_file_end(&mut self, w: &mut Worker) {
if cfg!(unix) {
self.flush_captured(w);
return;
}
self.flush_captured_lines(w);
if w.pending_lines.is_empty() {
self.flush_rest(w);
}
}

/// Prints everything, result lines that never reached the pipe included.
fn flush_captured(&mut self, w: &mut Worker) {
self.flush_captured_lines(w);
for p in w.pending_lines.drain(..) {
w.captured.extend_from_slice(&p.line);
}
self.flush_rest(w);
}

fn flush_rest(&mut self, w: &mut Worker) {
if w.captured.is_empty() {
return;
}
if !strings::ends_with_char(&w.captured, b'\n') {
let _ = Output::error_writer().write_all(b"\n");
w.captured.push(b'\n');
}
w.captured.clear();
let end = w.captured.len();
self.print_captured(w, end, w.inflight);
}

pub(crate) fn on_frame(&mut self, w: &mut Worker, kind: frame::Kind, rd: &mut frame::Reader) {
Expand All @@ -442,20 +542,12 @@ impl<'a> Coordinator<'a> {
if let Some(file) = self.test_records.get_mut(idx as usize) {
file.tests.push(Box::from(rd.p));
}
self.flush_captured(w);
if formatted.is_empty() {
return; // e.g. pass under --only-failures
}
// dots-mode failures print a full line (writeTestStatusLine);
// dots themselves are unterminated.
let is_dot = self.dots && !strings::ends_with_char(formatted, b'\n');
if !is_dot {
self.break_dots();
self.ensure_header(idx);
}
let _ = Output::error_writer().write_all(formatted);
self.last_printed_dot = is_dot;
Output::flush();
w.pending_lines.push_back(PendingLine {
file_idx: idx,
line: Box::from(formatted),
in_stream: strings::ends_with_char(formatted, b'\n'),
});
self.flush_captured_lines(w);
}
frame::Kind::FileDone => {
let mut nums = [0u32; 9];
Expand All @@ -477,7 +569,7 @@ impl<'a> Coordinator<'a> {
file.elapsed_ns = rd.u64();
}

self.flush_captured(w);
self.flush_file_end(w);
if self.last_header_idx == Some(idx) {
self.end_group();
}
Expand Down Expand Up @@ -728,6 +820,7 @@ impl<'a> Coordinator<'a> {
w.out = WorkerPipe::new(core::ptr::null());
w.err = WorkerPipe::new(core::ptr::null());
let _ = core::mem::take(&mut w.captured);
w.pending_lines.clear();
}
}

Expand Down
17 changes: 15 additions & 2 deletions src/runtime/cli/test/parallel/Worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! spawn/dispatch/shutdown mechanics.

use core::ffi::c_void;
use std::collections::VecDeque;

#[cfg(unix)]
use crate::api::bun::process::PosixStdio as Stdio;
Expand All @@ -22,6 +23,17 @@ use super::coordinator::Coordinator;
use super::file_range::FileRange;
use super::frame;

/// One `test_done` result the coordinator has not printed yet.
pub struct PendingLine {
pub(crate) file_idx: u32,
pub(crate) line: Box<[u8]>,
/// The worker wrote `line` to its stderr before it sent the frame, so it
/// prints when its copy is found in `captured`. A dot or the agent
/// status is not in the stream and prints right behind the entry
/// before it.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) in_stream: bool,
}

pub struct Worker {
// BACKREF to the owning Coordinator. Stored as `*const` for LIFETIMES.tsv
// parity, but mutation sites (`live_workers`, `on_worker_exit`, `frame`)
Expand Down Expand Up @@ -61,9 +73,10 @@ pub struct Worker {
/// Millisecond timestamp at the most recent dispatch; drives lazy
/// scale-up.
pub(crate) dispatched_at: i64,
/// Worker stdout+stderr since the last `test_done`. Flushed atomically
/// under the right file header so concurrent files don't interleave.
/// Worker stdout+stderr not yet printed.
pub(crate) captured: Vec<u8>,
/// Results from `test_done` frames not printed yet, in frame order.
pub(crate) pending_lines: VecDeque<PendingLine>,
pub(crate) alive: bool,
/// Set when the process-exit notification arrives. Reaping waits for both
/// this and `ipc.done` so trailing IPC frames are decoded first.
Expand Down
1 change: 1 addition & 0 deletions src/runtime/cli/test/parallel/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ pub(crate) fn run_as_coordinator(
inflight: None,
dispatched_at: 0,
captured: Vec::new(),
pending_lines: std::collections::VecDeque::new(),
alive: false,
exit_status: None,
reap_pending: false,
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/cli/test_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,12 @@ impl CommandLineReporter {
Self::test_case_report(result, buntest, sequence, test_entry, elapsed_ns, failure)
});
if let Some(idx) = this.worker_ipc_file_idx {
// A full line goes into stderr first, in sequence with the error
// output. The coordinator prints captured stderr up to it when
// the frame arrives. Dots stay out of the stream.
Comment thread
robobun marked this conversation as resolved.
Resolved
if strings::ends_with_char(formatted_line, b'\n') {
let _ = Output::error_writer().write_all(formatted_line);
}
ParallelRunner::worker_emit_test_done(idx, formatted_line, report.as_ref());
} else {
let _ = Output::error_writer().write_all(formatted_line);
Expand Down
54 changes: 54 additions & 0 deletions test/cli/test/parallel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,60 @@ test("--parallel never interleaves console output across files", async () => {
expect(exitCode).toBe(0);
});

test("--parallel keeps each failure's error output and GitHub annotation with its (fail) line", async () => {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Many failures with a long message per file. The error output rides the
// worker's stderr pipe and the result line rides the IPC channel, so the
// coordinator must print the stderr bytes that precede each result line
// before that line, and nothing past it.
const body = (tag: string) =>
`import {test} from "bun:test";
const big = Buffer.alloc(3000, "X").toString();
for (let i = 0; i < 60; i++) test("${tag}" + i, async () => {
if (i % 7 == 0) await Bun.sleep(1);
throw new Error("E-${tag}" + i + "\\n" + big + "\\nend");
});`;
using dir = tempDir("parallel-error-order", {
"a.test.js": body("a"),
"b.test.js": body("b"),
"c.test.js": body("c"),
});
await using proc = Bun.spawn({
cmd: [bunExe(), "test", "--parallel=3"],
env: { ...bunEnv, GITHUB_ACTIONS: "true", BUN_TEST_PARALLEL_SCALE_MS: "0" },
cwd: String(dir),
stderr: "pipe",
stdout: "pipe",
});
const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

// Every annotation is one intact line that names its test.
const annotations = stderr.split("\n").filter(line => line.startsWith("::error "));
expect(annotations.length).toBe(180);
for (const line of annotations) {
expect(line).toMatch(/^::error file=[abc]\.test\.js,line=\d+,col=\d+,title=error: E-[abc]\d+::end%0A/);
}
// The code frame for a test is followed by that test's own (fail) line.
let pendingError: string | null = null;
let checked = 0;
for (const line of stderr.split("\n")) {
const err = line.match(/^error: (E-[abc]\d+)$/);
if (err) {
expect(pendingError).toBeNull();
pendingError = err[1];
continue;
}
const fail = line.match(/^\(fail\) ([abc]\d+)/);
if (fail) {
expect(pendingError).toBe("E-" + fail[1]);
pendingError = null;
checked++;
}
}
expect(checked).toBe(180);
expect(stderr).toContain("180 fail");
expect(exitCode).toBe(1);
});

test("--parallel lazily scales workers based on file duration", async () => {
// Each test file appends its PID so we can count distinct worker processes.
const body = (sleepMs: number) =>
Expand Down
Loading