Skip to content

Commit 33795af

Browse files
authored
perf(rolldown): speed up session logs (#628)
1 parent f6b5384 commit 33795af

4 files changed

Lines changed: 409 additions & 66 deletions

File tree

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import type { ReaderIndex } from '../reader-index-codec'
2+
import { Buffer } from 'node:buffer'
3+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
4+
import { tmpdir } from 'node:os'
5+
import { join } from 'pathe'
6+
import { afterEach, describe, expect, it } from 'vitest'
7+
import { RolldownEventsReader } from '../events-reader'
8+
import { decodeReaderIndex, encodeReaderIndex } from '../reader-index-codec'
9+
10+
const dirs: string[] = []
11+
afterEach(() => {
12+
for (const dir of dirs.splice(0))
13+
rmSync(dir, { recursive: true, force: true })
14+
})
15+
16+
function createIndex(): ReaderIndex {
17+
const location = (offset: number, length = 10) => ({ offset, length })
18+
return {
19+
lastBytes: 5 * 1024 ** 3,
20+
lastTimestamp: 1793700062071,
21+
moduleEventIndex: new Map([
22+
['/src/ä/main.ts', {
23+
resolveIds: new Map([['r1', { start: location(0), end: location(10) }]]),
24+
loads: new Map(),
25+
// Offsets past 4 GiB must survive the round trip.
26+
transforms: new Map([['t1', { start: location(4.5 * 1024 ** 3), end: location(4.5 * 1024 ** 3 + 20, 300) }]]),
27+
}],
28+
]),
29+
stringRefIndex: new Map([['ref-1', location(42, 7)]]),
30+
pendingHookCallStarts: new Map([
31+
['p1', { module: '\0virtual', location: location(1) }],
32+
['p2', { location: location(2) }],
33+
]),
34+
assetsReadyLocations: [location(99, 3)],
35+
}
36+
}
37+
38+
describe('reader index codec', () => {
39+
const stat = { size: 123, mtime: 456 }
40+
41+
it('round-trips every index field', async () => {
42+
const index = createIndex()
43+
const decoded = await decodeReaderIndex(Buffer.concat(await encodeReaderIndex(index, stat)), stat)
44+
expect(decoded).toEqual(index)
45+
})
46+
47+
it('rejects an index written for another log version', async () => {
48+
const buffer = Buffer.concat(await encodeReaderIndex(createIndex(), stat))
49+
expect(await decodeReaderIndex(buffer, { size: 124, mtime: 456 })).toBeUndefined()
50+
expect(await decodeReaderIndex(buffer, { size: 123, mtime: 457 })).toBeUndefined()
51+
})
52+
53+
it('rejects truncated or padded data', async () => {
54+
const buffer = Buffer.concat(await encodeReaderIndex(createIndex(), stat))
55+
expect(await decodeReaderIndex(buffer.subarray(0, buffer.length - 1), stat)).toBeUndefined()
56+
expect(await decodeReaderIndex(Buffer.concat([buffer, Buffer.from([0])]), stat)).toBeUndefined()
57+
})
58+
})
59+
60+
describe('rolldown log cache', () => {
61+
function writeLog() {
62+
const dir = mkdtempSync(join(tmpdir(), 'rolldown-log-cache-'))
63+
dirs.push(dir)
64+
const base = { build_id: 'bid_1', session_id: 'sid_1' }
65+
const lines = [
66+
{ timestamp: 1, action: 'BuildStart', ...base },
67+
{ timestamp: 2, action: 'HookResolveIdCallStart', importer: null, module_request: '/src/main.ts', import_kind: 'import-statement', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c1', ...base },
68+
{ timestamp: 3, action: 'HookResolveIdCallEnd', resolved_id: '/src/main.ts', is_external: false, plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c1', ...base },
69+
{ timestamp: 4, action: 'HookTransformCallStart', module_id: '/src/main.ts', content: 'a', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c2', ...base },
70+
{ timestamp: 5, action: 'HookTransformCallEnd', module_id: '/src/main.ts', content: 'b', plugin_name: 'p', plugin_id: 0, trigger: 'automatic', call_id: 'c2', ...base },
71+
{ timestamp: 6, action: 'BuildEnd', ...base },
72+
]
73+
const filepath = join(dir, 'logs.json')
74+
writeFileSync(filepath, `${lines.map(line => JSON.stringify(line)).join('\n')}\n`)
75+
return filepath
76+
}
77+
78+
const indexOf = (reader: RolldownEventsReader) => {
79+
const state = reader as unknown as Record<string, unknown>
80+
return [state.moduleEventIndex, state.stringRefIndex, state.pendingHookCallStarts, state.assetsReadyLocations]
81+
}
82+
83+
it('restores the summary with module metrics but without the index, then restores the same index on a full read', async () => {
84+
const filepath = writeLog()
85+
const cold = RolldownEventsReader.get(filepath)
86+
await cold.read()
87+
expect((cold as unknown as { moduleEventIndex: Map<string, unknown> }).moduleEventIndex.size).toBeGreaterThan(0)
88+
const coldIndex = structuredClone(indexOf(cold))
89+
const coldEvents = cold.manager.eventCount
90+
const coldModules = cold.manager.module_build_metrics.size
91+
const coldMetrics = cold.manager.module_build_metrics.get('/src/main.ts')!
92+
expect(coldMetrics.transforms).toHaveLength(1)
93+
cold.dispose()
94+
95+
const warm = RolldownEventsReader.get(filepath)
96+
try {
97+
await warm.readSummary()
98+
expect(warm.manager.eventCount).toBe(coldEvents)
99+
expect((warm as unknown as { moduleEventIndex: Map<string, unknown> }).moduleEventIndex.size).toBe(0)
100+
// The summary keeps the compacted metrics the module list and chunk sizes rely on.
101+
const warmMetrics = warm.manager.module_build_metrics.get('/src/main.ts')
102+
expect(warm.manager.module_build_metrics.size).toBe(coldModules)
103+
expect(warmMetrics?.transforms.at(-1)?.transformed_code_size).toBe(coldMetrics.transforms.at(-1)!.transformed_code_size)
104+
expect(warmMetrics?.resolve_ids[0]?.duration).toBe(coldMetrics.resolve_ids[0]!.duration)
105+
106+
await warm.read()
107+
expect(indexOf(warm)).toEqual(coldIndex)
108+
expect(warm.manager.eventCount).toBe(coldEvents)
109+
}
110+
finally {
111+
warm.dispose()
112+
}
113+
})
114+
})

‎packages/rolldown/src/node/rolldown/events-reader.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const MAX_READERS = 32
1515
const MAX_MODULE_METRICS_CACHE = 32
1616
const MAX_MODULE_METRICS_CACHE_BYTES = 64 * 1024 * 1024
1717
const READ_STREAM_HIGH_WATER_MARK = 1024 * 1024
18+
const PARSE_SLICE_MS = 8
1819
const LINE_FEED = '\n'.charCodeAt(0)
1920
const CARRIAGE_RETURN = '\r'.charCodeAt(0)
2021
const ACTION_PREVIEW_BYTES = 512
@@ -341,7 +342,7 @@ export class RolldownEventsReader {
341342
if (restoredSummary) {
342343
this.clearModuleMetricsCache()
343344
this.pendingModuleMetrics.clear()
344-
this.summaryOnly = restoredSummary !== 'complete'
345+
this.summaryOnly = true
345346
this.packageSummaryOnly = false
346347
this.assetsHydrated = false
347348
return
@@ -455,6 +456,7 @@ export class RolldownEventsReader {
455456
lineStartOffset = nextLineStartOffset
456457
}
457458

459+
let sliceStart = performance.now()
458460
for await (const chunk of stream) {
459461
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
460462
let segmentStart = 0
@@ -482,6 +484,11 @@ export class RolldownEventsReader {
482484
}
483485
await processLine(line, location)
484486
}
487+
// Large logs take seconds to parse; yield so the server keeps answering meanwhile.
488+
if (performance.now() - sliceStart > PARSE_SLICE_MS) {
489+
await new Promise(resolve => setImmediate(resolve))
490+
sliceStart = performance.now()
491+
}
485492

486493
segmentStart = newline + 1
487494
resetLine(absoluteOffset + segmentStart)

‎packages/rolldown/src/node/rolldown/log-cache.ts‎

Lines changed: 59 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@ import type { ModuleBuildMetrics, PluginBuildMetrics } from '../../shared/types'
44
import type { RolldownEventsManager } from './events-manager'
55
import fs from 'node:fs/promises'
66
import { basename, dirname, join } from 'pathe'
7+
import { decodeReaderIndex, encodeReaderIndex } from './reader-index-codec'
78

89
export const ROLLDOWN_LOG_CACHE_DIR = '.cache'
910
export const ROLLDOWN_LOG_SESSION_SUMMARY_CACHE_FILENAME = 'session-summary.json'
10-
export const ROLLDOWN_LOG_READER_INDEX_CACHE_FILENAME = 'reader-index.json'
11+
export const ROLLDOWN_LOG_READER_INDEX_CACHE_FILENAME = 'reader-index.bin'
1112
export const ROLLDOWN_LOG_PACKAGE_SUMMARY_CACHE_FILENAME = 'package-summary.json'
1213
export const ROLLDOWN_LOG_PLUGIN_SUMMARY_CACHE_FILENAME = 'plugin-summary.json'
1314
export const ROLLDOWN_LOG_MODULE_METRICS_SUMMARY_CACHE_FILENAME = 'module-metrics-summary.json'
14-
const ROLLDOWN_LOG_CACHE_VERSION = 2
15+
const ROLLDOWN_LOG_CACHE_VERSION = 3
1516

1617
type ManagerSnapshot = ReturnType<RolldownEventsManager['snapshot']>
1718

@@ -91,21 +92,6 @@ interface RolldownPluginSummaryCacheSnapshot {
9192
plugins: Array<[number, PluginBuildMetricsSummary]>
9293
}
9394

94-
interface RolldownReaderIndexCacheSnapshot {
95-
reader: {
96-
lastBytes: number
97-
lastTimestamp: number
98-
moduleEventIndex: Array<[string, {
99-
resolveIds: Array<[string, IndexedHookCall]>
100-
loads: Array<[string, IndexedHookCall]>
101-
transforms: Array<[string, IndexedHookCall]>
102-
}]>
103-
stringRefIndex: Array<[string, LineLocation]>
104-
pendingHookCallStarts: Array<[string, PendingHookCallStart]>
105-
assetsReadyLocations: LineLocation[]
106-
}
107-
}
108-
10995
interface RolldownPackageSummaryCacheSnapshot {
11096
packageSummaryTimestamp: number
11197
manager: ManagerSnapshot
@@ -167,6 +153,46 @@ class RolldownLogCacheFile<T> {
167153
}
168154
}
169155

156+
class RolldownReaderIndexCacheFile {
157+
private constructor(
158+
readonly filepath: string,
159+
) {
160+
}
161+
162+
static forLogFile(logFilepath: string) {
163+
if (basename(logFilepath) !== 'logs.json')
164+
return undefined
165+
166+
return new RolldownReaderIndexCacheFile(join(dirname(logFilepath), ROLLDOWN_LOG_CACHE_DIR, ROLLDOWN_LOG_READER_INDEX_CACHE_FILENAME))
167+
}
168+
169+
async read(stat: Stats) {
170+
try {
171+
return await decodeReaderIndex(await fs.readFile(this.filepath), toLogStat(stat))
172+
}
173+
catch {
174+
return undefined
175+
}
176+
}
177+
178+
async write(stat: Stats, state: RolldownLogCacheState) {
179+
try {
180+
const chunks = await encodeReaderIndex(state, toLogStat(stat))
181+
const temporaryFilepath = `${this.filepath}.tmp`
182+
await fs.mkdir(dirname(this.filepath), { recursive: true })
183+
await fs.writeFile(temporaryFilepath, chunks)
184+
await fs.rename(temporaryFilepath, this.filepath)
185+
}
186+
catch {
187+
// The cache is best-effort. The reader can always rebuild from logs.json.
188+
}
189+
}
190+
}
191+
192+
function toLogStat(stat: Stats) {
193+
return { size: stat.size, mtime: stat.mtime.getTime() }
194+
}
195+
170196
function createMetricSummary(): PluginMetricSummary {
171197
return {
172198
count: 0,
@@ -297,7 +323,7 @@ export class RolldownLogCache {
297323
private sessionSummaryCache: RolldownLogCacheFile<RolldownSessionSummaryCacheSnapshot> | undefined
298324
private moduleMetricsSummaryCache: RolldownLogCacheFile<RolldownModuleMetricsSummaryCacheSnapshot> | undefined
299325
private pluginSummaryCache: RolldownLogCacheFile<RolldownPluginSummaryCacheSnapshot> | undefined
300-
private readerIndexCache: RolldownLogCacheFile<RolldownReaderIndexCacheSnapshot> | undefined
326+
private readerIndexCache: RolldownReaderIndexCacheFile | undefined
301327
private packageSummaryCache: RolldownLogCacheFile<RolldownPackageSummaryCacheSnapshot> | undefined
302328
private completeSessionWriteAttempted = false
303329
private summaryWriteAttempted = false
@@ -308,7 +334,7 @@ export class RolldownLogCache {
308334
this.sessionSummaryCache = RolldownLogCacheFile.forLogFile(logFilepath, ROLLDOWN_LOG_SESSION_SUMMARY_CACHE_FILENAME)
309335
this.moduleMetricsSummaryCache = RolldownLogCacheFile.forLogFile(logFilepath, ROLLDOWN_LOG_MODULE_METRICS_SUMMARY_CACHE_FILENAME)
310336
this.pluginSummaryCache = RolldownLogCacheFile.forLogFile(logFilepath, ROLLDOWN_LOG_PLUGIN_SUMMARY_CACHE_FILENAME)
311-
this.readerIndexCache = RolldownLogCacheFile.forLogFile(logFilepath, ROLLDOWN_LOG_READER_INDEX_CACHE_FILENAME)
337+
this.readerIndexCache = RolldownReaderIndexCacheFile.forLogFile(logFilepath)
312338
}
313339
this.packageSummaryCache = RolldownLogCacheFile.forLogFile(logFilepath, ROLLDOWN_LOG_PACKAGE_SUMMARY_CACHE_FILENAME)
314340
}
@@ -351,11 +377,14 @@ export class RolldownLogCache {
351377
if (!sessionSummaryCache || !moduleMetricsCache || !pluginSummaryCacheExists || !indexCache)
352378
return false
353379

354-
if (sessionSummaryCache.reader.lastBytes !== stat.size || indexCache.reader.lastBytes !== stat.size)
380+
if (sessionSummaryCache.reader.lastBytes !== stat.size || indexCache.lastBytes !== stat.size)
355381
return false
356382

357383
this.restoreSessionSnapshot(sessionSummaryCache, state, moduleMetricsCache)
358-
this.restoreReaderIndexSnapshot(indexCache, state)
384+
state.moduleEventIndex = indexCache.moduleEventIndex
385+
state.stringRefIndex = indexCache.stringRefIndex
386+
state.pendingHookCallStarts = indexCache.pendingHookCallStarts
387+
state.assetsReadyLocations = indexCache.assetsReadyLocations
359388
this.completeSessionWriteAttempted = true
360389
this.summaryWriteAttempted = true
361390
return true
@@ -365,27 +394,18 @@ export class RolldownLogCache {
365394
if (state.lastBytes || state.manager.eventCount)
366395
return false
367396

368-
const [sessionSummaryCache, moduleMetricsCache, _pluginSummaryCache, indexCache] = await Promise.all([
397+
// The module list needs the metrics; the index is loaded on a full read.
398+
const [sessionSummaryCache, moduleMetricsCache] = await Promise.all([
369399
this.sessionSummaryCache?.read(stat),
370400
this.moduleMetricsSummaryCache?.read(stat),
371-
this.pluginSummaryCache?.read(stat),
372-
this.readerIndexCache?.read(stat),
373401
])
374-
if (!sessionSummaryCache)
375-
return false
376-
377-
if (sessionSummaryCache.reader.lastBytes !== stat.size)
402+
if (!sessionSummaryCache || sessionSummaryCache.reader.lastBytes !== stat.size)
378403
return false
379404

380405
this.restoreSessionSnapshot(sessionSummaryCache, state, moduleMetricsCache)
381-
const hasCompleteCache = !!moduleMetricsCache && !!_pluginSummaryCache && !!indexCache
382-
if (indexCache?.reader.lastBytes === stat.size)
383-
this.restoreReaderIndexSnapshot(indexCache, state)
384-
else
385-
this.clearReaderIndexState(state)
406+
this.clearReaderIndexState(state)
386407
this.summaryWriteAttempted = true
387-
this.completeSessionWriteAttempted = hasCompleteCache
388-
return hasCompleteCache ? 'complete' : 'summary'
408+
return 'summary' as const
389409
}
390410

391411
async restorePackageSummary(stat: Stats, state: RolldownLogCacheState) {
@@ -416,17 +436,19 @@ export class RolldownLogCache {
416436
this.sessionSummaryCache?.write(stat, this.createSessionSummarySnapshot(state)),
417437
this.moduleMetricsSummaryCache?.write(stat, this.createModuleMetricsSummarySnapshot(state)),
418438
this.pluginSummaryCache?.write(stat, this.createPluginSummarySnapshot(state)),
419-
this.readerIndexCache?.write(stat, this.createReaderIndexSnapshot(state)),
439+
this.readerIndexCache?.write(stat, state),
420440
])
421441
}
422442

423443
async writeSummary(stat: Stats, state: RolldownLogCacheState) {
424444
this.summaryWriteAttempted = true
445+
// Writes the same sidecars as a complete session, so don't write them again for the full read.
446+
this.completeSessionWriteAttempted = true
425447
await Promise.all([
426448
this.sessionSummaryCache?.write(stat, this.createSessionSummarySnapshot(state)),
427449
this.moduleMetricsSummaryCache?.write(stat, this.createModuleMetricsSummarySnapshot(state)),
428450
this.pluginSummaryCache?.write(stat, this.createPluginSummarySnapshot(state)),
429-
this.readerIndexCache?.write(stat, this.createReaderIndexSnapshot(state)),
451+
this.readerIndexCache?.write(stat, state),
430452
])
431453
}
432454

@@ -471,23 +493,6 @@ export class RolldownLogCache {
471493
}
472494
}
473495

474-
private createReaderIndexSnapshot(state: RolldownLogCacheState): RolldownReaderIndexCacheSnapshot {
475-
return {
476-
reader: {
477-
lastBytes: state.lastBytes,
478-
lastTimestamp: state.lastTimestamp,
479-
moduleEventIndex: Array.from(state.moduleEventIndex.entries()).map(([module, index]) => [module, {
480-
resolveIds: Array.from(index.resolveIds.entries()),
481-
loads: Array.from(index.loads.entries()),
482-
transforms: Array.from(index.transforms.entries()),
483-
}]),
484-
stringRefIndex: Array.from(state.stringRefIndex.entries()),
485-
pendingHookCallStarts: Array.from(state.pendingHookCallStarts.entries()),
486-
assetsReadyLocations: state.assetsReadyLocations,
487-
},
488-
}
489-
}
490-
491496
private createPackageSummarySnapshot(state: RolldownLogCacheState): RolldownPackageSummaryCacheSnapshot {
492497
return {
493498
packageSummaryTimestamp: state.packageSummaryTimestamp,
@@ -521,17 +526,6 @@ export class RolldownLogCache {
521526
})
522527
}
523528

524-
private restoreReaderIndexSnapshot(snapshot: RolldownReaderIndexCacheSnapshot, state: RolldownLogCacheState) {
525-
state.moduleEventIndex = new Map(snapshot.reader.moduleEventIndex.map(([module, item]) => [module, {
526-
resolveIds: new Map(item.resolveIds),
527-
loads: new Map(item.loads),
528-
transforms: new Map(item.transforms),
529-
}]))
530-
state.stringRefIndex = new Map(snapshot.reader.stringRefIndex)
531-
state.pendingHookCallStarts = new Map(snapshot.reader.pendingHookCallStarts)
532-
state.assetsReadyLocations = snapshot.reader.assetsReadyLocations
533-
}
534-
535529
private restorePackageSummarySnapshot(snapshot: RolldownPackageSummaryCacheSnapshot, state: RolldownLogCacheState) {
536530
state.manager.restore(snapshot.manager)
537531
state.packageSummaryTimestamp = snapshot.packageSummaryTimestamp

0 commit comments

Comments
 (0)