Skip to content

Commit eda6b67

Browse files
authored
perf(vite): speed up inspect and stop storing sourcemaps (#617)
1 parent 6bd7543 commit eda6b67

12 files changed

Lines changed: 333 additions & 252 deletions

File tree

‎docs/errors/VDT0004.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
outline: deep
3+
---
4+
5+
# VDT0004: Inspect Storage Fallback
6+
7+
## Message
8+
9+
> Vite inspect could not write the `{archive}` archive to disk and now keeps new records in memory.
10+
11+
## Cause
12+
13+
The Vite inspect collector writes transform payloads and plugin-call records to archives in the Vite cache directory. When a write fails, for example because the disk is full or the directory became unwritable, the collector keeps the failed batch and every later record in memory. Every transform stays available in the Vite UI, and memory use grows until the dev server restarts.
14+
15+
## Example
16+
17+
Filling up the disk that holds `node_modules/.vite/devtools/inspect` while the dev server is transforming modules triggers this warning.
18+
19+
## Fix
20+
21+
Check that the Vite cache directory is writable and has free disk space, then restart the Vite dev server to resume writing to disk.
22+
23+
## Source
24+
25+
- [`packages/vite/src/node/inspect/store/payload.ts`](https://github.com/vitejs/devtools/blob/main/packages/vite/src/node/inspect/store/payload.ts) — the payload archive emits this when a batched write fails and it switches to in-memory payloads.
26+
- [`packages/vite/src/node/inspect/store/plugin-calls.ts`](https://github.com/vitejs/devtools/blob/main/packages/vite/src/node/inspect/store/plugin-calls.ts) — the plugin-call archive emits this when a segment write fails and it switches to in-memory segments.

‎docs/errors/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Emitted by `@vitejs/devtools-vite`.
6060
| [VDT0001](./VDT0001) | error | Inspect Context Unavailable |
6161
| [VDT0002](./VDT0002) | error | Inspect Target Not Found |
6262
| [VDT0003](./VDT0003) | error | Inspect Storage Error |
63+
| [VDT0004](./VDT0004) | warn | Inspect Storage Fallback |
6364

6465
## Vitest DevTools (VTDT)
6566

‎packages/vite/src/node/__tests__/inspect-context.test.ts‎

Lines changed: 125 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { Environment, Plugin, ResolvedConfig } from 'vite'
22
import type { ViteInspectStoreOptions } from '../inspect/store'
33
import type { ViteInspectPluginCallInfo } from '../inspect/types'
44
import { existsSync, mkdtempSync, rmSync, statSync, truncateSync } from 'node:fs'
5+
import { open } from 'node:fs/promises'
56
import { tmpdir } from 'node:os'
67
import { join } from 'node:path'
78
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -410,19 +411,11 @@ describe('vite inspect context', () => {
410411
const envCtx = vite.getEnvContext(env)
411412
const result = `export const value = '${'café'.repeat(4096)}'`
412413
const source = `const value = '${'source'.repeat(4096)}'`
413-
const sourcemaps = {
414-
version: 3,
415-
sources: ['/src/main.ts'],
416-
sourcesContent: [source],
417-
mappings: 'AAAA;'.repeat(4096),
418-
}
419-
420414
envCtx.recordTransform('/src/main.ts', {
421415
name: 'plugin-a',
422416
result,
423417
start: 0,
424418
end: 1,
425-
sourcemaps,
426419
}, source)
427420
expect(await envCtx.getModulesList()).toHaveLength(1)
428421
await expect(envCtx.getModuleTransformInfo('/src/main.ts')).resolves.toEqual({
@@ -433,15 +426,13 @@ describe('vite inspect context', () => {
433426
result: source,
434427
start: 0,
435428
end: 0,
436-
sourcemaps,
437429
},
438430
{
439431
name: 'plugin-a',
440432
plugin_id: 0,
441433
result,
442434
start: 0,
443435
end: 1,
444-
sourcemaps,
445436
},
446437
],
447438
})
@@ -467,32 +458,6 @@ describe('vite inspect context', () => {
467458
rmSync(dir, { recursive: true, force: true })
468459
})
469460

470-
it('serializes each sourcemap once before writing its payload', async () => {
471-
const { ctx, envCtx, vite } = await createFixture()
472-
const toJSON = vi.fn(() => ({
473-
version: 3,
474-
mappings: 'AAAA',
475-
}))
476-
477-
envCtx.recordTransform('/src/serialized.ts', {
478-
name: 'plugin-a',
479-
result: 'export const serialized = true',
480-
start: 0,
481-
end: 1,
482-
sourcemaps: { toJSON },
483-
}, 'const serialized = true', vite.config.plugins[1])
484-
485-
await ctx.store.flush()
486-
expect(toJSON).toHaveBeenCalledOnce()
487-
await expect(envCtx.getModuleTransformInfo('/src/serialized.ts')).resolves.toMatchObject({
488-
transforms: [
489-
{ sourcemaps: { version: 3, mappings: 'AAAA' } },
490-
{ sourcemaps: { version: 3, mappings: 'AAAA' } },
491-
],
492-
})
493-
expect(toJSON).toHaveBeenCalledOnce()
494-
})
495-
496461
it('reuses released file payload ranges after invalidation', async () => {
497462
const dir = mkdtempSync(join(tmpdir(), 'vite-inspect-reuse-'))
498463
const filename = join(dir, 'payloads.bin')
@@ -507,10 +472,6 @@ describe('vite inspect context', () => {
507472
result: `export const value = '${'result'.repeat(4096)}'`,
508473
start: 0,
509474
end: 1,
510-
sourcemaps: {
511-
version: 3,
512-
mappings: 'AAAA;'.repeat(4096),
513-
},
514475
}, `const value = '${'source'.repeat(4096)}'`, vite.config.plugins[1])
515476
await ctx.store.flush()
516477
}
@@ -706,11 +667,11 @@ describe('vite inspect context', () => {
706667
hijackPlugin(plugin, ctx)
707668
await ctx.close()
708669

709-
await expect((plugin.transform as any).call(
670+
expect((plugin.transform as any).call(
710671
{ environment: env },
711672
'export const value = 1',
712673
'/src/module.ts',
713-
)).resolves.toBe('export const value = 1\n// transformed')
674+
)).toBe('export const value = 1\n// transformed')
714675
})
715676

716677
it('persists an oversized record without truncating it', async () => {
@@ -795,21 +756,17 @@ describe('vite inspect context', () => {
795756
maxBatchItems: 1,
796757
},
797758
})
798-
let sourcemapRef: WeakRef<object> | undefined
759+
let infoRef: WeakRef<object> | undefined
799760

800761
await (async () => {
801-
const sourcemaps = {
802-
version: 3,
803-
mappings: 'x'.repeat(8 * 1024 * 1024),
804-
}
805-
sourcemapRef = new WeakRef(sourcemaps)
806-
await envCtx.recordTransform('/src/retained.ts', {
762+
const info = {
807763
name: 'plugin-a',
808-
result: 'export const retained = true',
764+
result: `export const retained = '${'x'.repeat(8 * 1024 * 1024)}'`,
809765
start: 0,
810766
end: 1,
811-
sourcemaps,
812-
}, 'const retained = true', vite.config.plugins[1]!)
767+
}
768+
infoRef = new WeakRef(info)
769+
await envCtx.recordTransform('/src/retained.ts', info, 'const retained = true', vite.config.plugins[1]!)
813770
})()
814771

815772
await ctx.store.flush()
@@ -818,7 +775,7 @@ describe('vite inspect context', () => {
818775
await new Promise(resolve => setImmediate(resolve))
819776
}
820777

821-
expect(sourcemapRef?.deref()).toBeUndefined()
778+
expect(infoRef?.deref()).toBeUndefined()
822779
expect(ctx.store.getStats()).toMatchObject({
823780
queuedItems: 0,
824781
inFlightItems: 0,
@@ -1214,3 +1171,118 @@ describe('vite inspect context', () => {
12141171
}
12151172
})
12161173
})
1174+
1175+
describe('vite inspect storage fallback', () => {
1176+
it('keeps records in memory after an archive write fails', async () => {
1177+
const dir = mkdtempSync(join(tmpdir(), 'vite-inspect-fallback-'))
1178+
const handle = await open(join(dir, 'probe.bin'), 'w+')
1179+
const fileHandlePrototype = Object.getPrototypeOf(handle)
1180+
await handle.close()
1181+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
1182+
const { ctx, envCtx, vite } = await createFixture({
1183+
store: {
1184+
filename: join(dir, 'payloads.bin'),
1185+
},
1186+
})
1187+
const pluginA = vite.config.plugins[1]!
1188+
const record = (index: number) => {
1189+
envCtx.recordTransform(`/src/module-${index}.ts`, {
1190+
name: 'plugin-a',
1191+
result: `export const value = ${index}`,
1192+
start: index,
1193+
end: index + 1,
1194+
}, `const value = ${index}`, pluginA)
1195+
}
1196+
1197+
try {
1198+
record(0)
1199+
await ctx.store.flush()
1200+
1201+
const writev = vi.spyOn(fileHandlePrototype, 'writev').mockRejectedValue(new Error('ENOSPC'))
1202+
record(1)
1203+
record(2)
1204+
await ctx.store.flush()
1205+
writev.mockRestore()
1206+
1207+
for (let index = 0; index < 3; index++) {
1208+
await expect(envCtx.getModuleTransformInfo(`/src/module-${index}.ts`)).resolves.toMatchObject({
1209+
transforms: [
1210+
{ name: '__load__', result: `const value = ${index}` },
1211+
{ name: 'plugin-a', result: `export const value = ${index}` },
1212+
],
1213+
})
1214+
}
1215+
expect((await envCtx.getPluginDetails(1)).calls).toHaveLength(3)
1216+
const warnings = warn.mock.calls.map(args => args.map(String).join(' ')).filter(message => message.includes('VDT0004'))
1217+
expect(warnings).toHaveLength(2)
1218+
1219+
// Released fallback payloads must not leak into reused ranges.
1220+
envCtx.invalidate('/src/module-1.ts')
1221+
record(3)
1222+
await ctx.store.flush()
1223+
await expect(envCtx.getModuleTransformInfo('/src/module-3.ts')).resolves.toMatchObject({
1224+
transforms: [
1225+
{ name: '__load__', result: 'const value = 3' },
1226+
{ name: 'plugin-a', result: 'export const value = 3' },
1227+
],
1228+
})
1229+
}
1230+
finally {
1231+
warn.mockRestore()
1232+
await ctx.close()
1233+
rmSync(dir, { recursive: true, force: true })
1234+
}
1235+
})
1236+
})
1237+
1238+
describe('vite inspect hook timing', () => {
1239+
it('keeps sync hooks sync and still records them', async () => {
1240+
const { ctx, env, envCtx, vite } = await createFixture()
1241+
const plugin = vite.config.plugins[1]! as Plugin & {
1242+
transform: NonNullable<Plugin['transform']>
1243+
}
1244+
plugin.transform = code => `${code}\n// sync`
1245+
hijackPlugin(plugin, ctx)
1246+
1247+
const result = (plugin.transform as any).call({ environment: env }, 'const value = 1', '/src/sync.ts')
1248+
expect(result).toBe('const value = 1\n// sync')
1249+
1250+
await ctx.store.flush()
1251+
await expect(envCtx.getModuleTransformInfo('/src/sync.ts')).resolves.toMatchObject({
1252+
transforms: [
1253+
{ name: '__load__', result: 'const value = 1' },
1254+
{ name: 'plugin-a', result: 'const value = 1\n// sync' },
1255+
],
1256+
})
1257+
})
1258+
1259+
it('records async hooks and rethrows sync errors', async () => {
1260+
const { ctx, env, envCtx, vite } = await createFixture()
1261+
const asyncPlugin = vite.config.plugins[1]! as Plugin & {
1262+
transform: NonNullable<Plugin['transform']>
1263+
}
1264+
asyncPlugin.transform = async code => `${code}\n// async`
1265+
hijackPlugin(asyncPlugin, ctx)
1266+
const failingPlugin = vite.config.plugins[2]! as Plugin & {
1267+
transform: NonNullable<Plugin['transform']>
1268+
}
1269+
failingPlugin.transform = () => {
1270+
throw new Error('sync failure')
1271+
}
1272+
hijackPlugin(failingPlugin, ctx)
1273+
1274+
const pending = (asyncPlugin.transform as any).call({ environment: env }, 'const value = 1', '/src/async.ts')
1275+
expect(pending).toBeInstanceOf(Promise)
1276+
await expect(pending).resolves.toBe('const value = 1\n// async')
1277+
expect(() => (failingPlugin.transform as any).call({ environment: env }, 'const value = 1', '/src/async.ts')).toThrow('sync failure')
1278+
1279+
await ctx.store.flush()
1280+
await expect(envCtx.getModuleTransformInfo('/src/async.ts')).resolves.toMatchObject({
1281+
transforms: [
1282+
{ name: '__load__', result: 'const value = 1' },
1283+
{ name: 'plugin-a', result: 'const value = 1\n// async' },
1284+
{ name: 'plugin-b', result: '[Error]' },
1285+
],
1286+
})
1287+
})
1288+
})

‎packages/vite/src/node/__tests__/inspect-server.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,8 +449,8 @@ describe('vite inspect server invalidation', () => {
449449
const source = 'export const value = 1'
450450
writeFileSync(id, source)
451451
let fail = true
452-
let now = Date.now()
453-
const clock = vi.spyOn(Date, 'now').mockImplementation(() => now)
452+
let now = performance.now()
453+
const clock = vi.spyOn(performance, 'now').mockImplementation(() => now)
454454
const declined: Plugin = {
455455
name: 'test:declined-file-load',
456456
enforce: 'pre',

‎packages/vite/src/node/diagnostics.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,9 @@ export const diagnostics = /* #__PURE__ */ defineDiagnostics({
1414
why: (p: { operation: string }) => `Vite inspect storage failed while ${p.operation}.`,
1515
fix: 'Restart the Vite dev server. If the error persists, clear the Vite cache directory and reinstall dependencies.',
1616
},
17+
VDT0004: {
18+
why: (p: { archive: string }) => `Vite inspect could not write the ${p.archive} archive to disk and now keeps new records in memory.`,
19+
fix: 'Check that the Vite cache directory is writable and has free disk space, then restart the Vite dev server to resume writing to disk.',
20+
},
1721
},
1822
})

0 commit comments

Comments
 (0)