Unverified Commit 8911fe36 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

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).
parent 7d29e358
......@@ -1221,7 +1221,7 @@ export default async function build(
})
Log.info('Complete')
await flushAllTraces()
flushAllTraces()
teardownTraceSubscriber()
process.exit(0)
}
......@@ -4704,8 +4704,8 @@ export default async function build(
await telemetry.flush()
}
// Ensure all traces are flushed before finishing the command
await flushAllTraces()
// Ensure all buffered spans are on disk before `uploadTrace` reads the file.
flushAllTraces()
teardownTraceSubscriber()
if (traceUploadUrl && loadedConfig) {
......
......@@ -264,7 +264,7 @@ export async function startServer(
'memory.heapSizeLimit': String(memoryRestartStats.heap_size_limit),
'memory.heapUsed': String(memoryRestartStats.used_heap_size),
}).stop()
await flushAllTraces()
flushAllTraces()
process.exit(RESTART_EXIT_CODE)
}
}
......@@ -428,7 +428,7 @@ export async function startServer(
])
// Flush any remaining traces to the trace file on shutdown
await flushAllTraces()
flushAllTraces()
// Flush telemetry if this is a dev server
if (isDev) {
......
......@@ -53,7 +53,7 @@ export function backgroundLogCompilationEvents(
// tend to happen at the very end of a build so to make sure they are logged we need to
// flush.
// NOTE: in a `next build` environment where we are reporting events to the parent thread, this is a no-op.
await flushAllTraces()
flushAllTraces()
} catch {}
continue // don't log these events, they just go to the trace file
}
......
import { mkdtemp, readFile } from 'fs/promises'
import { mkdtemp, readFile, rm } from 'fs/promises'
import { reporter } from '.'
import { setGlobal } from '../shared'
import { join } from 'path'
......@@ -20,13 +20,25 @@ const WEBPACK_INVALIDATED_EVENT = {
}
describe('Trace Reporter', () => {
const tmpDirs: string[] = []
afterAll(async () => {
// Windows refuses to remove a directory containing an open file, so the
// trace file handle has to go first.
reporter.close()
await Promise.all(
tmpDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
)
})
describe('JSON reporter', () => {
it('should write the trace events to JSON file', async () => {
const tmpDir = await mkdtemp(join(tmpdir(), 'json-reporter'))
tmpDirs.push(tmpDir)
setGlobal('distDir', tmpDir)
setGlobal('phase', 'anything')
reporter.report(TRACE_EVENT)
await reporter.flushAll()
reporter.flushAll()
const traceFilename = join(tmpDir, 'trace')
const traces = JSON.parse(await readFile(traceFilename, 'utf-8'))
expect(traces.length).toEqual(1)
......
......@@ -11,8 +11,12 @@ class MultiReporter implements Reporter {
this.reporters = reporters
}
async flushAll(opts?: { end: boolean }) {
await Promise.all(this.reporters.map((reporter) => reporter.flushAll(opts)))
flushAll() {
this.reporters.forEach((reporter) => reporter.flushAll())
}
close() {
this.reporters.forEach((reporter) => reporter.close?.())
}
report(event: TraceEvent) {
......
This diff is collapsed.
import type { TraceEvent } from '../types'
export type Reporter = {
flushAll: (opts?: { end: boolean }) => Promise<void> | void
flushAll: () => void
report: (event: TraceEvent) => void
/**
* Release any file handles. Optional: only reporters that hold one need it,
* and only callers that must act on the file afterwards (tests removing a
* temp dir on Windows) need to call it.
*/
close?: () => void
}
This diff is collapsed.
......@@ -161,8 +161,13 @@ export const trace = (
return new Span({ name, parentId, attrs })
}
export const flushAllTraces = (opts?: { end: boolean }) =>
reporter.flushAll(opts)
export const flushAllTraces = () => reporter.flushAll()
/**
* Flush and release the trace file handle. Intended for tests that need to
* delete the directory holding the trace afterwards.
*/
export const closeAllTraces = () => reporter.close()
// This code supports workers by serializing the state of tracers when the
// worker is initialized, and serializing the trace events from the worker back
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment