Keep extracted auto-import packages across cancelled builds #65412
A workspace edit can miss invalidation when an older completion build has not yet inserted that package's pending extraction: this scan finds no key, so the new snapshot shares the cache. The older build can then publish exports from its old snapshot, which the newer build reuses despite the edit. Make invalidation cover later insertions from older snapshots, for example through generation tracking, and add a deterministic test for this interleaving.
Package-root containment misses files read outside the package during extraction, such as a workspace package at packages/a re-exporting ../shared/index. After a cancelled build, editing packages/shared/index.d.ts leaves the cached extraction usable if no extraction key covers that directory, so the retry installs stale re-export names. Track extraction dependencies, including files read through alias resolution and redirected project-reference sources, and invalidate results when those paths change.
If a cancelled warm-up initialized the shared cache before preferences or project-reference mappings changed, each subsequent warm-up creates a replacement only on its builder. Session.warmAutoImportCache discards cancelled clones, leaving the canonical registry's incompatible cache unchanged, so repeated cancellation restarts extraction from scratch again. Keep compatible replacements reachable through shared state, or rotate the cache on an adopted snapshot before warming begins.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Active cache invalidation gaps can reuse stale exports after workspace edits, while cancelled warm-ups can repeatedly restart extraction because compatible cache replacements are not retained.
<details open>
<summary><strong>3 open issues</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Addresses #65410 by retaining package extraction work across cancelled auto-import builds, reducing repeated parsing while typing in the language server.
Changes:
node_modules changes.| File | Description |
| ---- | ----------- |
| tsc/internal/ls/autoimport/registry.go | Adds shared extraction caching, single-flight coordination, and invalidation. |
| tsc/internal/ls/autoimport/registry_test.go | Tests cancelled-build reuse and re-extraction after package changes. |
</details>
<sub>Review effort: Balanced</sub>
good bot, legit race tbh. Every clone that keeps the cache now records its changed files as a new generation (with its parent, so sibling snapshots don't see each other's edits), and each extraction is tagged with the generation of the build that ran it. Reuse gets checked when reading, against the changes between the two generations, so it doesn't matter anymore if the older build inserts after the edit landed. Deterministic test for that interleaving in extractions_test.go (older build publishing after an edit is not reused).
Fixed in cde9454a5.
ok clanker, fair. Changed my stuff so each extraction now records every source file it reads through the host (entrypoints plus whatever alias resolution pulls in, redirected project-reference sources too since they go through GetSourceFile as well), and a change to any of those invalidates it. Created/deleted files and package.json edits drop the whole cache, since those can change resolution without touching a file that was read. TestCancelledBuildTracksExtractionDependencies covers your packages/a -> ../shared/index case, it fails on the previous commit.
Fixed in cde9454a5.
The set matching the current prefs + project-reference outputs now lives on the shared object (setFor swaps it under the lock), so the replacement made by a cancelled warm-up stays reachable from the canonical registry and the next warm-up picks it up instead of starting over.
Fixed in cde9454a5.
After a cancelled build caches a package, replacing the filesystem without enumerating changed paths can make the next build reuse exports from the old filesystem. Snapshot.Clone sets FileChangeSummary.InvalidateAll, but does not pass it through RegistryChange, so this switch preserves the cached extraction. Propagate that flag and discard partial extractions when it is set.
After a cancelled build extracts an unimported package, a bulk batch of changes to its declaration files can leave stale exports cached: Snapshot.processFileChanges clears watch changes that do not overlap the snapshot cache, while auto-import-only files are deliberately excluded from that cache. The registry then sees no changes and reuses the old extraction. Preserve invalidation for retained extractions before filtering watch events, or include their dependencies in the overlap check, and add a regression test for this path.
Successful reuse leaves the extraction tagged with its original generation, so repeated cancelled warm-ups rescan every intervening unrelated edit. Across N successive edits and retries, this produces N(N+1)/2 change checks per retained package while holding the shared mutex. Advance the generation after successful validation so later retries only check changes since the last validated snapshot.
A cancelled waiter can start a fresh extraction if pending.done wins the select and the completed result is stale for its snapshot. The retry reaches this branch without rechecking cancellation, then runs with context.WithoutCancel, potentially forcing the current build to wait for obsolete work. Check ctx.Err() before reserving a new extraction.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Critical invalidation gaps can reuse stale auto-import exports after filesystem changes, while cancellation handling and repeated validation also risk obsolete work and excessive locking.
<details open>
<summary><strong>4 open issues</strong></summary>
</details>
<details>
<summary><strong>3 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
good bot, yep. RegistryChange now has an InvalidateAll flag, Snapshot.Clone passes it through, and it drops the whole partial extraction cache. fwiw completed buckets have the same gap on main since the flag never reached the registry before, I kept that out of this PR to keep it scoped.
Fixed in 247459b7f.
nice catch clanker, that one's sneaky. When processFileChanges clears a bulk batch because nothing overlaps the snapshot cache, it now marks the summary, and the registry gets that as InvalidateAll, so the partial cache goes away. Simpler than matching every dependency against the batch, and bulk batches are rare enough that losing the reuse there kinda doesn't matter. Regression test: bulk node_modules changes discard extracted packages (1001 watch events, fails on the previous commit).
Fixed in 247459b7f.
Aight clanker, a result that passes validation now gets retagged with the consumer's generation, so the next retry only walks the edits since then. That's safe: if a result is valid for both generations, nothing it depends on changed on the path between them, so checking against either one gives the same answer. Test: validated reuse advances the generation.
Fixed in 247459b7f.
Fair, the loop now checks ctx.Err() at the top, so a cancelled waiter bails out before it can reserve a fresh extraction. Test: cancelled waiter does not start a new extraction.
Fixed in 247459b7f.
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
Cache invalidation gaps can reuse stale auto-import exports after manifest changes or directory deletions, while unbounded change history and detached cancellation can cause memory growth and delay session shutdown.
<details open>
<summary><strong>2 open issues</strong></summary>
</details>
<details>
<summary><strong>5 previously missed issues</strong></summary>
In code that hasn't changed since last review
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Add concurrent single-flight and waiter-cancellation tests</summary>
tsc/internal/ls/autoimport/registry.go:475
The new single-flight path has no concurrent test; the current cancellation subtest cancels before calling extract, so it never exercises a blocked waiter. Add deterministic testing/synctest coverage that blocks the owner, starts another caller for the same key, and verifies both receive the same result from one extraction callback. Also cancel a caller while it is actually waiting and assert that it returns nil without starting another extraction.
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Manifest invalidation ignores case-insensitive filename matches</summary>
tsc/internal/ls/autoimport/registry.go:486
On a case-insensitive filesystem, a watch event for packages/shared/Package.json refers to the same manifest the resolver reads as package.json, but this comparison does not invalidate it. If cached workspace package a re-exports ../shared, changing that manifest's types field can therefore reuse stale exports after cancellation: the manifest is neither a GetSourceFile dependency nor inside a's directory. Compare the canonical basename using the supplied case sensitivity.
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Partial-cache change history grows without bound</summary>
tsc/internal/ls/autoimport/registry.go:577
Once a cancelled build leaves partial results for project B, typing in an already-prepared project A can skip warm-up but still append a change record on every snapshot. These records are never pruned, so memory grows with the editing session and returning to B makes each retained package scan the accumulated history under p.mu. Bound the history by rotating the partial cache after a limit, or prune it while preserving generations still reachable by snapshots and pending extractions.
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Warm-up tasks can block session shutdown</summary>
tsc/internal/ls/autoimport/registry.go:1644
context.WithoutCancel also removes session-shutdown cancellation, while Session.Close() waits in backgroundQueue.Close() for the warm-up task. On large workspaces, shutdown can therefore wait for all already-started package extractions to finish. Detach from build cancellation while retaining a session-lifetime cancellation signal, and remove aborted pending entries rather than caching incomplete results.
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Directory deletions can leave stale partial-cache exports</summary>
tsc/internal/project/snapshot.go:682
After a cancelled extraction of packages/a re-exporting ../shared/index, a single deletion event for packages/shared is discarded by expandAndFilterWatchEvents because its auto-import-only files are not in the snapshot cache. DroppedWatchChanges is only set for bulk events, so the retry can reuse exports from the deleted dependency. Preserve partial-cache invalidation before ordinary directory-event filtering, and add a directory-deletion variant of TestCancelledBuildTracksExtractionDependencies.
</details>
</details>
<details>
<summary><strong>2 resolved since last review</strong></summary>
</details>
<sub>Review effort: Max</sub>
ok clanker, went through the 5 "previously missed" ones from the last review:
TestPartialExtractionsConcurrency on testing/synctest. The owner gets blocked, a second caller for the same key gets the same result from one extraction, and a caller cancelled while waiting returns nil without starting another one.Package.json on case-insensitive fs: the basename now gets compared through the case sensitivity.WithoutCancel: the warm-up context now carries the session's background context as the extraction lifetime, so started extractions survive a keystroke cancel but stop on Session.Close. If an extraction gets aborted that way, its pending entry gets removed instead of caching a partial result, and any waiters retry or bail on their own ctx.expandAndFilterWatchEvents: dropping a delete there now sets DroppedWatchChanges too, same path as the bulk case. Test: deleted dependency directory in TestCancelledBuildTracksExtractionDependencies, fails without the fix.Fixed in e78087cb0.
<!-- ccr-overview-v2 -->
🔵 Needs a closer look
Cache ownership and cancellation interactions require human assessment because they can retain obsolete snapshot state and allow duplicate package extraction across builds.
<details open>
<summary><strong>2 open issues</strong></summary>
</details>
<sub>Review effort: Max</sub>
hood
Fixes #65410
While typing, the auto-import warm-up gets cancelled on every keystroke and used to throw away every package it had already extracted, so it kept re-reading and re-parsing
node_modulesfrom scratch and never finished if you type faster than one full build. This keeps per-package extraction results on the registry, shared from one clone to the next, so a cancelled build leaves its finished packages for the next one:node_moduleschanges, any file is created or deleted, apackage.jsonchanges, bucket build preferences or project-reference outputs change, and once a build completes, so memory goes back to what it was once the index is ready.| recharts
src/cartesian/Line.tsx, 120 keystrokes at 150 ms, diagnostics + semantic tokens per key |main(7 runs) | this PR (3 runs) ||---|---|---|
| process CPU over 18 s of typing | 42.6–44.8 s | 13.5–14.0 s (−68%), 13.7–13.8 s after review fixes |
| first completion after typing stops | 217–257 ms (index never got built) | 11–13 ms (index ready) |
|
textDocument/diagnosticmedian | 53–55 ms | 47.5–50 ms || completion-heavy typing (completion + diag + semantic tokens per key), CPU | ~17.9 s | ~17.5–17.9 s (no change) |
Measured with this harness: https://gist.github.com/hood/506e87027c83bbec1b44c1f687273349
Tests:
TestCancelledBuildKeepsExtractedPackages: a build cancelled mid-extraction doesn't extract that package again on the next build (fails onmain), and anode_moduleschange still re-extracts it.TestCancelledBuildTracksExtractionDependencies: a workspace package re-exporting../sharedgets re-extracted whensharedchanges after a cancelled build.TestPartialExtractionsInvalidation: deterministic interleavings (older build publishing after an edit, edits outside the package root, unrelated edits, sibling snapshots, replacement set after a prefs change).mainon the same session across 13 prefixes: 21,610 items, 6,335 of them auto-imports.go test ./...,npx hereby lintandnpx hereby check:formatpass.AI disclosure: I polished my solution, my breakdown of it and -most importantly- did most of the measurements with help from an AI agent. I've gone 2x through everything and I'll handle any follow-up myself ofc.