Skip to content

fix: don't lose worker output on teardown, deflake timing-sensitive tests - #10842

Merged
sheremet-va merged 4 commits into
mainfrom
test/deflake-pool-and-timing
Aug 7, 2026
Merged

sheremet-va merged 4 commits into
mainfrom
test/deflake-pool-and-timing

Conversation

@sheremet-va

@sheremet-va sheremet-va commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Description

Second batch of CI deflaking, addressing the next flake families from the failure analysis of the last week of CI runs (see #10841 for the first one). Stacked on top of #10841; retarget to main once that merges.

One product bug:

  • Trailing worker stdio is lost on teardown (test/pool.test.ts "can capture worker's stdout and stderr", 17 failures). Worker-thread stdio is proxied over a MessagePort with a backpressure protocol, and a chunk stays buffered inside the worker until the parent acks the previous one. The pool starts runner.stop() as soon as it receives testfileFinished, and thread.terminate() halts the worker before buffered chunks are ever posted. Workers now flush stdout/stderr before signaling testfileFinished/stopped (an empty write's callback only fires after every buffered chunk is acked), and both worker classes wait for the source streams to end before unpiping. Keeping the pipes attached until the streams end requires pipe(dest, { end: false }): the logger streams are shared by every worker, and the default end: true lets the first ending worker stream end them for everyone else (a latent unpipe race on main; it only stays invisible there because Node's pipe() never closes process.stdout/stderr, which the real CLI logger uses).

Three test-side fixes:

  • test/concurrent.test.ts deadlock tests (4 failures): whether a deadlocked test is reported as timed out depends on its own elapsed time the moment the deadlock resolves, and "b" starts its clock a few event-loop turns after "a", so "c" releasing the deadlock could let "b" finish within its own budget. "c" now resolves the deadlock only after "b" reported its timeout via onTestFailed. The fixture is parameterized because the passing variants share it and would hang on an unconditional gate.
  • test/reporters/import-durations.test.ts (6 failures): the e2e main project runs with isolate: false, so process.exitCode is shared by ~80 files in one worker and a stray unhandled rejection leaked by an earlier file flips it to 1 while the inner run is fully green. The two exitCode === 0 assertions now assert on the run's own state instead (same treatment as 29b8b56/12138f622 gave the first test in this file).
  • server-url tests (7 failures): the fixed API ports sat inside the OS ephemeral port range, so a kernel-assigned outbound socket occasionally held them; strictPort is off and Vite's "Port is in use" notice is info-level (below the logger's warn), so the server silently bound port+1 and the exact-port assertions failed. The browser fixture now uses ports below the ephemeral range, and the e2e test asserts the resolved config port plus a port-agnostic API started at line (the bound port is exactly what a collision changes, and ctx.vite.resolvedUrls is already null by the time a non-watch run's assertions execute).

The macOS-only pool-worker-exit.test.ts family (EPIPE surfacing before the worker's exit event, dead runner reused as a shared runner) is diagnosed from CI logs but was not reproducible locally; a fix was drafted and then dropped from this PR pending empirical evidence.

Each fix was verified locally with loops of the affected suites, plus a full e2e run, lint and typecheck; the stdio race doesn't reproduce on a fast local machine, so its verification is the mechanism analysis above plus no-regression runs.

@sheremet-va
sheremet-va force-pushed the test/deflake-pool-and-timing branch 2 times, most recently from 3e89607 to 1129402 Compare July 27, 2026 13:27
@sheremet-va

Copy link
Copy Markdown
Member Author

AI slopped, but seems genuine. Most of the changes here are related to properly flushing stdout/stderr in forks/threads. @AriPerkkio what do you think?

Comment on lines +53 to +54
// `end: false`: the logger streams are shared by every worker, so one
// ending worker stream must not end them for everyone else

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, would love to see minimal Node script that demonstrates this. Weird that we haven't ran into this before, as we've been calling unpipe after fork.kill() always. So that kill() doesn't terminate the stream? Only crashes do? 🤔

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sloppyty slop


kill() does terminate the stream — both kill and crash end it. The race is when the source's 'end' is processed relative to our unpipe(), and the unpipe usually loses:

import { fork } from 'node:child_process'
import { PassThrough } from 'node:stream'

if (process.env.CHILD) {
  process.stdout.write(`start:${'x'.repeat(64)}:end\n`)
  setInterval(() => {}, 1000) // stay alive until killed, like a pool worker
}
else {
  const child = fork(new URL(import.meta.url), [], { stdio: 'pipe', env: { ...process.env, CHILD: '1' } })
  const dest = new PassThrough()
  dest.on('data', () => {})
  dest.on('finish', () => console.log('destination was end()ed'))
  child.stdout.pipe(dest) // what `start()` does today

  setTimeout(async () => {
    // exactly ForksPoolWorker.stop(): kill -> await exit -> unpipe
    const exited = new Promise(r => child.once('exit', r))
    child.kill()
    await exited
    child.stdout.unpipe(dest)
  }, 150)
}

This prints destination was end()ed deterministically on my machine: the child's stdout reaches EOF, and pipe's end-propagation calls dest.end() before the await exit continuation gets to the unpipe. So a dying fork ends logger.outputStream for every other worker piped into it.

The reason we've never run into it is pipe()'s documented special case: "process.stderr and process.stdout are never closed until the process exits, regardless of the specified options" — and in the real CLI logger.outputStream is process.stdout (logger.ts:42), so end-propagation is a no-op there. It only has teeth when the logger streams are plain Writables: custom streams, and our own e2e harness's captured streams. It's also self-masking: pipe() installs an 'error' listener on the destination, so a later worker writing into the ended shared stream doesn't crash anything — its pipe just errors and detaches, and that worker's output silently disappears, which looks exactly like the capture flakes this PR is chasing.

It became load-bearing in this PR because stop() now deliberately waits for the source's 'end' before unpiping (to not drop the drained tail), which turns "usually loses the race" into "always ends the destination" — without { end: false } that hangs the threads pool immediately: once the shared stream is ended, the next worker's stdio backpressure acks never flow, its flush never resolves, and stop() times out. I hit that as a reproducible hang in pool.test.ts while working on this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That reproduction is confusing. What should be visible instead? Should I see it working properly if I added delay before fork.kill()?

So a dying fork ends logger.outputStream for every other worker piped into it.

There's a single worker in the repro?

@sheremet-va
sheremet-va force-pushed the test/deflake-shared-watch-fixture branch from 2b96c81 to b932b01 Compare July 27, 2026 14:11
@sheremet-va
sheremet-va force-pushed the test/deflake-pool-and-timing branch 2 times, most recently from fee8336 to 01d3689 Compare July 27, 2026 15:30
AriPerkkio
AriPerkkio previously approved these changes Jul 28, 2026

@AriPerkkio AriPerkkio left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The streamFlushed on main thread before unpipe does make sense.

I think Tinypool had some related logic to worker side flushStdio. It was never added to Vitest.

https://github.com/tinylibs/tinypool/blob/abc247f85cba0309e3f1e5655db1837a2a1c2483/src/entry/worker.ts#L121-L130

@sheremet-va
sheremet-va force-pushed the test/deflake-pool-and-timing branch from 01d3689 to ab9152b Compare August 7, 2026 12:15
@sheremet-va
sheremet-va force-pushed the test/deflake-shared-watch-fixture branch from b932b01 to c9b36ca Compare August 7, 2026 12:15
Base automatically changed from test/deflake-shared-watch-fixture to main August 7, 2026 12:34
@sheremet-va
sheremet-va force-pushed the test/deflake-pool-and-timing branch from ab9152b to dd75e17 Compare August 7, 2026 12:34
@sheremet-va
sheremet-va merged commit 1216b5a into main Aug 7, 2026
@sheremet-va
sheremet-va deleted the test/deflake-pool-and-timing branch August 7, 2026 12:34
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 22, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants