Repository navigation
fix: don't lose worker output on teardown, deflake timing-sensitive tests - #10842
Conversation
3e89607 to
1129402
Compare
|
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? |
1129402 to
a47355c
Compare
| // `end: false`: the logger streams are shared by every worker, so one | ||
| // ending worker stream must not end them for everyone else |
There was a problem hiding this comment.
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? 🤔
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
2b96c81 to
b932b01
Compare
fee8336 to
01d3689
Compare
AriPerkkio
left a comment
There was a problem hiding this comment.
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.
01d3689 to
ab9152b
Compare
b932b01 to
c9b36ca
Compare
ab9152b to
dd75e17
Compare
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
mainonce that merges.One product bug:
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 startsrunner.stop()as soon as it receivestestfileFinished, andthread.terminate()halts the worker before buffered chunks are ever posted. Workers now flush stdout/stderr before signalingtestfileFinished/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 requirespipe(dest, { end: false }): the logger streams are shared by every worker, and the defaultend: truelets the first ending worker stream end them for everyone else (a latent unpipe race onmain; it only stays invisible there because Node'spipe()never closesprocess.stdout/stderr, which the real CLI logger uses).Three test-side fixes:
test/concurrent.test.tsdeadlock 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 viaonTestFailed. 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 e2emainproject runs withisolate: false, soprocess.exitCodeis 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 twoexitCode === 0assertions now assert on the run's own state instead (same treatment as 29b8b56/12138f622 gave the first test in this file).strictPortis off and Vite's "Port is in use" notice is info-level (below the logger'swarn), 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-agnosticAPI started atline (the bound port is exactly what a collision changes, andctx.vite.resolvedUrlsis alreadynullby the time a non-watch run's assertions execute).The macOS-only
pool-worker-exit.test.tsfamily (EPIPE surfacing before the worker'sexitevent, 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.