Backtestsvuerun-20261013-093701#15478
compiler-sfc: loadTSConfig re-parses the whole tsconfig extends chain for every config it walks
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the root cause the same way. Each adds a module-level `Map<string, TS.ExtendedConfigCacheEntry>` and passes it as the 8th argument to `parseJsonConfigFileContent`. Each also clears it, together with `tsConfigCache`, from `invalidateTypeCache`. The patches differ in how they invalidate and in what they test. Invalidation: Patch A clears only when the changed filename is a key in the extended-config cache, checking both the exact path and the lowercased path that TS uses on case-insensitive file systems. That targets exactly the files whose edits can leave the cache stale, and it also covers chained extends. Patch B clears both caches whenever any `.json` file is invalidated. That is safe, but crude: editing package.json, a locale file or any other JSON data throws away all parsed tsconfigs. This partly undoes the performance gain the issue is about in dev/HMR. Patch A carries a minor risk if a caller passes a path in a different form from TS's resolved key (for example backslashes), but the conventional callers pass normalized forward-slash paths. Tests: both add a read-counting test that fails without the cache and checks that the shared base is read only once across project references. Patch A goes further in two ways. It checks reuse across separate top-level `loadTSConfig` calls, a separate package extending the same base, which is the cross-call scenario the issue highlights. It also adds a test for the caveat the issue says a fix must answer: an edited base config is picked up after `invalidateTypeCache`, so `paths` resolve to the new target. Patch B has no invalidation test, so its staleness handling is unverified. Scope and craft are comparable. Both changes are minimal, and the comments are clear in each. Overall, Patch A's more precise invalidation and its stronger tests, particularly the cache-invalidation test, make it the better fix.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
5m 56s
Wall-clock time in the container
Full test suite
No new failures
634 passed · 1 skipped · 635 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
119vs 74 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.42 (latest release; also present on main at 5409708)
Link to minimal reproduction
https://github.com/cainrus/vue-compiler-sfc-tsconfig-repro
Steps to reproduce
git clone https://github.com/cainrus/vue-compiler-sfc-tsconfig-repro
cd vue-compiler-sfc-tsconfig-repro
npm install
npm run repro
The generator builds a workspace of 150 packages, each with its own tsconfig.json thatextends one shared base and declares references to its group, plus one SFC per package whose
props type is imported from another package by alias. Both arms compile the same components; thecached arm differs only in that it supplies an extendedConfigCache, through the publicregisterTS hook, as the 8th argument the package leaves undefined.
What is expected?
Parsing the same extends chain repeatedly should reuse the parsed parent configs, as TypeScript's
own extendedConfigCache parameter exists to allow.
What is actually happening?
loadTSConfig calls ts.parseJsonConfigFileContent with five arguments, so the 8th
(extendedConfigCache) is always undefined:
https://github.com/vuejs/core/blob/main/packages/compiler-sfc/src/script/resolveType.ts
const config = ts.parseJsonConfigFileContent(
ts.readConfigFile(configPath, fs.readFile).config,
parseConfigHost, // 2
dirname(configPath), // 3
undefined, // 4
configPath, // 5
) // 6, 7, 8 omitted -- the 8th is extendedConfigCache
and then recurses through project references:
res.unshift(...loadTSConfig(refPath, ts, fs, visited))
So in a workspace whose packages all extend a shared base, that base is re-read and re-parsed once
per config the traversal reaches, and each parse allocates its own fully expanded paths map.visited is a default parameter: it de-duplicates within one top-level call, never across calls.
Measured on the reproduction — node 22.23.2, @vue/compiler-sfc 3.5.41, typescript 5.9, one arm
per process (tsConfigCache is module scope):
| arm | config parses | distinct expanded paths objects | time | retained heap |
|---|---|---|---|---|
| stock | 2900 | 2900 | 11.1 s | 1346.8 MB |
| cached | 2900 | **1** | 1.9 s | 30.2 MB |
The parse count is identical in both arms. The cache does not remove parses — it makes each one
cheap and stops the expanded options object from being rebuilt. Retained heap is heapUsed after a
forced GC.
On a production Vue monorepo (2432 components, 514 tsconfigs, 4051 project references, a 118 KB
shared base with 1342 paths entries), compiling 400 of its real components throughcompileScript with the same two arms:
| arm | config parses | distinct expanded paths objects | time | retained heap |
|---|---|---|---|---|
| stock | 7351 | 7350 | 25.4 s | 2615.8 MB |
| cached | 7351 | **3** | 8.0 s | 188.7 MB |
That is what led to this report: tsconfig parsing dominated the allocation profile of that
application's production build.
Does the cache change the result?
node parity.mjs in the reproduction re-implements loadTSConfig verbatim and runs it twice per
entry config, differing only in the 8th argument, comparing resolved compilerOptions,projectReferences and fileNames for every parse the traversal produces:
| run | parses compared | paths entries compared | mismatches |
|---|---|---|---|
node parity.mjs | 400 | 176 000 | **0** |
MUTATE=1 node parity.mjs (cached arm reads a different config) | 400 | 176 000 | 336 |
MUTATE=2 node parity.mjs (one paths entry altered after parsing) | 400 | 176 000 | 400 |
The two controls are there because a comparator that always prints zero proves nothing. The same
comparison over the production monorepo's configs: 831 parses, 1 116 033 paths entries, 0
mismatches, with the controls reporting 114 and 831.
One consequence worth stating explicitly: with the cache, the expanded options object is **shared
by reference** (that is where the memory saving comes from), so it must not be handed to a consumer
that mutates it. resolveWithTS only reads matchedConfig.config.options, so that holds today.
Suggested fix
A module-level Map threaded into the 8th argument. One caveat a fix has to answer:invalidateTypeCache currently clears tsConfigCache and tsConfigRefMap, and would need to clear
the new cache too, or an edited tsconfig.base.json would go stale in dev/HMR — TypeScript keysextendedConfigCache by resolved path, so that is a targeted delete.
PR: #15480 — it also explains why a plain Map rather than createCache(), and whyinvalidateTypeCache clears the cache instead of deleting one entry.
System Info
node 22.23.2, darwin arm64
@vue/compiler-sfc 3.5.41
typescript 5.9
Any additional comments?
There is a second, independent problem in the same function's caller — tsConfigCache is an LRU
capped at 500 — which I am filing separately, since the fix for it is a capacity decision rather
than a one-line change.
The two patches
packages/compiler-sfc/__tests__/compileScript/resolveType.spec.tsindex ad066c7a0..c3d3dc280 100644@@ -1405,6 +1405,107 @@ describe('resolveType', () => { expect(deps && [...deps]).toStrictEqual(['/src/types.ts']) }) + test('ts module resolve reuses a shared extended tsconfig across configs', () => {+ const base = JSON.stringify({+ compilerOptions: {+ paths: {+ '@shared/*': ['./shared/*'],+ },+ },+ })+ const files: Record<string, string> = {+ '/tsconfig.base.json': base,+ // project references: both referenced configs extend the same base+ '/tsconfig.json': JSON.stringify({+ files: [],+ references: [+ { path: './tsconfig.app.json' },+ { path: './tsconfig.node.json' },+ ],+ }),+ '/tsconfig.app.json': JSON.stringify({+ extends: './tsconfig.base.json',+ include: ['./app/**/*'],+ }),+ '/tsconfig.node.json': JSON.stringify({+ extends: './tsconfig.base.json',+ include: ['./node/**/*'],+ }),+ // a separate package whose own tsconfig extends the same base+ '/pkg/tsconfig.json': JSON.stringify({+ extends: '../tsconfig.base.json',+ }),+ '/shared/types.ts': 'export type Props = { foo: string }',+ }+ let baseReads = 0+ const fs = {+ fileExists(file: string) {+ return !!(files[file] ?? files[normalize(file)])+ },+ readFile(file: string) {+ if (normalize(file) === normalize('/tsconfig.base.json')) {+ baseReads+++ }+ return files[file] ?? files[normalize(file)]+ },+ }+ const code = `+ import type { Props } from '@shared/types'+ defineProps<Props>()+ `++ const app = resolve(code, files, { fs }, '/app/Foo.vue')+ expect(app.props).toStrictEqual({ foo: ['String'] })+ expect(app.deps && [...app.deps]).toStrictEqual(['/shared/types.ts'])+ // parsed once for both referenced configs+ expect(baseReads).toBe(1)++ // a different top-level tsconfig extending the same base reuses it,+ // while still resolving paths relative to the base+ const pkg = resolve(code, files, { fs }, '/pkg/Foo.vue', false)+ expect(pkg.props).toStrictEqual({ foo: ['String'] })+ expect(pkg.deps && [...pkg.deps]).toStrictEqual(['/shared/types.ts'])+ expect(baseReads).toBe(1)+ })++ test('ts module resolve picks up edits to an extended tsconfig after invalidation', () => {+ const files: Record<string, string> = {+ '/tsconfig.json': JSON.stringify({+ extends: './tsconfig.base.json',+ }),+ '/tsconfig.base.json': JSON.stringify({+ compilerOptions: {+ paths: {+ '@/*': ['./a/*'],+ },+ },+ }),+ '/a/types.ts': 'export type Props = { foo: string }',+ '/b/types.ts': 'export type Props = { bar: number }',+ }+ const code = `+ import type { Props } from '@/types'+ defineProps<Props>()+ `++ const before = resolve(code, files)+ expect(before.props).toStrictEqual({ foo: ['String'] })++ files['/tsconfig.base.json'] = JSON.stringify({+ compilerOptions: {+ paths: {+ '@/*': ['./b/*'],+ },+ },+ })+ // only the edited base config is invalidated, as a dev server would do+ invalidateTypeCache('/tsconfig.base.json')+ invalidateTypeCache('/a/types.ts')+ const after = resolve(code, files, {}, '/Test.vue', false)+ expect(after.props).toStrictEqual({ bar: ['Number'] })+ expect(after.deps && [...after.deps]).toStrictEqual(['/b/types.ts'])+ })+ test('ts module resolve w/ project reference folder', () => { const files = { '/tsconfig.json': JSON.stringify({packages/compiler-sfc/src/script/resolveType.tsindex 2d57438f1..349f723a2 100644@@ -1079,6 +1079,11 @@ interface CachedConfig { const tsConfigCache = createCache<CachedConfig[]>() const tsConfigRefMap = new Map<string, string>()+// Shared across loadTSConfig calls so that a base config `extends`-ed by many+// tsconfigs is parsed once and its expanded options are reused. TS keys it by+// the resolved path of the extended config (lowercased on case-insensitive+// file systems).+const tsExtendedConfigCache = new Map<string, TS.ExtendedConfigCacheEntry>() function resolveWithTS( containingFile: string,@@ -1193,6 +1198,9 @@ function loadTSConfig( dirname(configPath), undefined, configPath,+ undefined,+ undefined,+ tsExtendedConfigCache, ) const res = [config] visited.add(configPath)@@ -1226,6 +1234,16 @@ export function invalidateTypeCache(filename: string): void { tsConfigCache.delete(filename) const affectedConfig = tsConfigRefMap.get(filename) if (affectedConfig) tsConfigCache.delete(affectedConfig)+ if (+ tsExtendedConfigCache.has(filename) ||+ tsExtendedConfigCache.has(filename.toLowerCase())+ ) {+ // an extended config changed: cached entries of configs extending it+ // (directly or through another extended config) embed its content, and+ // so do the parsed configs of every tsconfig built on top of it.+ tsExtendedConfigCache.clear()+ tsConfigCache.clear()+ } } export function fileToScope(
packages/compiler-sfc/__tests__/compileScript/resolveType.spec.tsindex ad066c7a0..5b5df37c3 100644@@ -1405,6 +1405,63 @@ describe('resolveType', () => { expect(deps && [...deps]).toStrictEqual(['/src/types.ts']) }) + test('ts module resolve parses a shared extended config once', () => {+ const base = '/tsconfig.base.json'+ const files: Record<string, string> = {+ '/tsconfig.json': JSON.stringify({+ files: [],+ references: [+ { path: './tsconfig.a.json' },+ { path: './tsconfig.b.json' },+ { path: './tsconfig.c.json' },+ ],+ }),+ [base]: JSON.stringify({+ compilerOptions: {+ composite: true,+ paths: {+ bar: ['./user.ts'],+ },+ },+ }),+ '/user.ts': 'export type User = { bar: string }',+ }+ for (const name of ['a', 'b', 'c']) {+ files[`/tsconfig.${name}.json`] = JSON.stringify({+ extends: base,+ include: ['**/*.ts', '**/*.vue'],+ })+ }++ // Counting reads of the shared base is what makes this test able to fail: the+ // traversal reaches three configs that extend it, and without a shared+ // `extendedConfigCache` each one re-reads and re-parses it.+ let baseReads = 0+ const { props } = resolve(+ `+ import { User } from 'bar'+ defineProps<User>()+ `,+ files,+ {+ fs: {+ fileExists(file) {+ return !!(files[file] ?? files[normalize(file)])+ },+ readFile(file) {+ if (normalize(file) === normalize(base)) baseReads+++ return files[file] ?? files[normalize(file)]+ },+ },+ },+ )++ expect(props).toStrictEqual({+ bar: ['String'],+ })+ expect(baseReads).toBe(1)+ })+ test('ts module resolve w/ project reference folder', () => { const files = { '/tsconfig.json': JSON.stringify({packages/compiler-sfc/src/script/resolveType.tsindex 2d57438f1..3f27fa578 100644@@ -1080,6 +1080,13 @@ interface CachedConfig { const tsConfigCache = createCache<CachedConfig[]>() const tsConfigRefMap = new Map<string, string>() +// `loadTSConfig` recurses through project references, so in a workspace where every+// package extends a shared base, that base is re-read and re-parsed once per config the+// traversal reaches - each parse allocating its own fully expanded options. TypeScript+// takes this cache as the 8th argument of `parseJsonConfigFileContent` and shares the+// parsed parents instead.+const extendedConfigCache = new Map<string, TS.ExtendedConfigCacheEntry>()+ function resolveWithTS( containingFile: string, source: string,@@ -1193,6 +1200,9 @@ function loadTSConfig( dirname(configPath), undefined, configPath,+ undefined,+ undefined,+ extendedConfigCache, ) const res = [config] visited.add(configPath)@@ -1224,6 +1234,13 @@ export function invalidateTypeCache(filename: string): void { fileToScopeCache.delete(filename) fileToGlobalScopeCache.delete(filename) tsConfigCache.delete(filename)+ // A changed config can be extended by any number of others and is cached under its own+ // resolved path, so there is no single entry to drop; clearing is cheap because this+ // only runs when a config file itself changed.+ if (filename.endsWith('.json')) {+ extendedConfigCache.clear()+ tsConfigCache.clear()+ } const affectedConfig = tsConfigRefMap.get(filename) if (affectedConfig) tsConfigCache.delete(affectedConfig) }