Write traces with buffered synchronous IO (#96874)
### What?
Writes `.next/trace` with a fixed buffer and `fs.writeSync` instead of
an `fs.WriteStream`. `Reporter.flushAll` becomes synchronous and drops
its unused `opts.end` parameter.
### Why?
**A production build could hang on the trace reporter.**
`flushAll` ended the write stream whenever the phase was not
`PHASE_DEVELOPMENT_SERVER`:
```ts
if (opts?.end || phase !== PHASE_DEVELOPMENT_SERVER) {
return writeStream.end()
}
```
No caller ever passed `opts.end`, so in production the stream was ended
on *every* flush. But builds flush repeatedly — after each Turbopack
compilation event in `backgroundLogCompilationEvents`, and again in the
`finally` of `next build` before `uploadTrace` reads the file. Only the
last of those is terminal.
That gives a flush → write → flush sequence against a stream that is
already finished:
1. The first flush calls `writeStream.end()`.
2. A later span is reported. `write()` on an ended stream returns
`false` and, because the stream will never drain again, never emits
`'drain'`.
3. The reporter parks on `await this.drainPromise`.
4. The next flush awaits that write. Nothing resolves it.
The build hangs in its `finally`, and every span after the first flush
is missing from the trace file.
### How?
`RotatingWriteStream` now holds a 16KB `Buffer`, encodes each event into
it directly, and writes with `fs.writeSync` when it fills or when
`flushAll` is called. There is no close, so the end-of-stream state that
caused the hang no longer exists.
Trace files are small — under 1KB for a production build, a few MB for a
long dev session — so the async write path was never buying throughput.
Buffering to 16KB keeps a build at a handful of writes rather than one
per span, which matters because the webpack/rspack profiling plugins
open a span per module(!!).
### Testing
`packages/next/src/trace/trace.test.ts` covers the reporter directly:
flushing repeatedly, auto-flush when the buffer fills,
truncate-vs-append per phase, rotation at the size limit (counted in
UTF-8 bytes, not UTF-16 code units), complete batches across a sweep of
event sizes that land on the buffer boundary, an event too large to
buffer at all, and a partially encoded multi-byte event.
Verified end to end against a real `next build` (34 spans, valid NDJSON,
`next-build` span present) and a real `next dev` session (spans landing
mid-session, and accumulating across a restart).
Showing
This diff is collapsed.
This diff is collapsed.
Please
register
or
sign in
to comment