Fix git submodule path cache retention (#7687)

This commit is contained in:
Neil
2026-07-11 01:30:19 -07:00
committed by GitHub
parent d912482752
commit acb35ee649
18 changed files with 807 additions and 112 deletions
+4 -1
View File
@@ -1,6 +1,7 @@
import type { GitRuntimeOptions } from './git-runtime-options'
import { gitOptionsForWorktree } from './git-runtime-options'
import { gitExecFileAsync } from './runner'
import { runWithGitReadCacheInvalidation } from './status'
/**
* Reject branch names git would parse as an option (`-`/`--…`) or that aren't a
@@ -27,7 +28,9 @@ export async function checkoutBranch(
options: GitRuntimeOptions = {}
): Promise<void> {
assertValidBranchName(branch)
await gitExecFileAsync(['checkout', branch, '--'], gitOptionsForWorktree(worktreePath, options))
await runWithGitReadCacheInvalidation(() =>
gitExecFileAsync(['checkout', branch, '--'], gitOptionsForWorktree(worktreePath, options))
)
}
/**
+21 -14
View File
@@ -7,6 +7,7 @@ import type { GitRuntimeOptions } from './git-runtime-options'
import { gitOptionsForWorktree } from './git-runtime-options'
import { validateGitPushTarget } from './push-target-validation'
import { gitExecFileAsync } from './runner'
import { runWithGitReadCacheInvalidation } from './status'
async function getConfiguredPushTarget(
worktreePath: string,
@@ -249,7 +250,9 @@ export async function gitPull(
// Why: plain `git pull` uses the user's configured pull strategy (merge by
// default) so diverged branches reconcile instead of erroring out. Conflicts
// surface through the existing conflict-resolution flow.
await gitPullWithArgs(worktreePath, [], pushTarget, options)
await runWithGitReadCacheInvalidation(() =>
gitPullWithArgs(worktreePath, [], pushTarget, options)
)
}
export async function gitFastForward(
@@ -257,7 +260,9 @@ export async function gitFastForward(
pushTarget?: GitPushTarget,
options: GitRuntimeOptions = {}
): Promise<void> {
await gitPullWithArgs(worktreePath, ['--ff-only'], pushTarget, options)
await runWithGitReadCacheInvalidation(() =>
gitPullWithArgs(worktreePath, ['--ff-only'], pushTarget, options)
)
}
export async function gitPullRebaseFromBase(
@@ -265,18 +270,20 @@ export async function gitPullRebaseFromBase(
baseRef: string,
options: GitRuntimeOptions = {}
): Promise<void> {
try {
const source = await resolveGitRemoteRebaseSource(
(args) => gitExecFileAsync(args, gitOptionsForWorktree(worktreePath, options)),
baseRef
)
await gitExecFileAsync(
['pull', '--rebase', source.remoteName, source.branchName],
gitOptionsForWorktree(worktreePath, options)
)
} catch (error) {
throw new Error(normalizeGitErrorMessage(error, 'pull'))
}
await runWithGitReadCacheInvalidation(async () => {
try {
const source = await resolveGitRemoteRebaseSource(
(args) => gitExecFileAsync(args, gitOptionsForWorktree(worktreePath, options)),
baseRef
)
await gitExecFileAsync(
['pull', '--rebase', source.remoteName, source.branchName],
gitOptionsForWorktree(worktreePath, options)
)
} catch (error) {
throw new Error(normalizeGitErrorMessage(error, 'pull'))
}
})
}
export async function gitFetch(
+2 -1
View File
@@ -24,7 +24,8 @@ vi.mock('./runner', () => ({
}))
vi.mock('./status', () => ({
resolveGitDir: resolveGitDirMock
resolveGitDir: resolveGitDirMock,
runWithGitReadCacheInvalidation: <T>(run: () => Promise<T>) => run()
}))
vi.mock('fs/promises', async () => {
@@ -0,0 +1,231 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { gitExecFileAsyncMock, gitExecFileAsyncBufferMock, gitStreamStdoutMock } = vi.hoisted(
() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileAsyncBufferMock: vi.fn(),
gitStreamStdoutMock: vi.fn()
})
)
vi.mock('./runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock,
gitExecFileAsyncBuffer: gitExecFileAsyncBufferMock,
gitStreamStdout: gitStreamStdoutMock,
gitOptionalLocksDisabledEnv: (env: NodeJS.ProcessEnv = process.env) => ({
...env,
GIT_OPTIONAL_LOCKS: '0'
})
}))
import {
MAX_SUBMODULE_PATHS_CACHE_ENTRIES,
abortMerge,
abortRebase,
clearSubmodulePathsCacheForTests,
getSubmodulePathsCacheCountForTests,
listSubmodulePaths
} from './status'
import { checkoutBranch } from './checkout'
import { gitPull, gitPullRebaseFromBase } from './remote'
import { addWorktree, removeWorktree } from './worktree'
describe('submodule path cache', () => {
beforeEach(() => {
clearSubmodulePathsCacheForTests()
gitExecFileAsyncMock.mockReset()
gitExecFileAsyncBufferMock.mockReset()
gitStreamStdoutMock.mockReset()
gitExecFileAsyncMock.mockImplementation((_args: string[], options?: { cwd?: string }) =>
Promise.resolve({
stdout: `submodule.lib.path ${String(options?.cwd ?? 'repo').replace(/^.*[/\\\\]/, '')}-lib\n`
})
)
})
afterEach(() => {
vi.useRealTimers()
clearSubmodulePathsCacheForTests()
})
it('prunes expired entries even when later reads use different worktrees', async () => {
vi.useFakeTimers()
vi.setSystemTime(0)
await listSubmodulePaths('/repo-a')
await listSubmodulePaths('/repo-b')
expect(getSubmodulePathsCacheCountForTests()).toBe(2)
vi.setSystemTime(5_001)
await expect(listSubmodulePaths('/repo-c')).resolves.toEqual(['repo-c-lib'])
expect(getSubmodulePathsCacheCountForTests()).toBe(1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(3)
})
it('stays bounded through prolonged worktree churn and keeps recently reused worktrees', async () => {
vi.useFakeTimers()
vi.setSystemTime(0)
for (let wave = 0; wave < 4; wave += 1) {
for (let i = 0; i < MAX_SUBMODULE_PATHS_CACHE_ENTRIES; i += 1) {
await listSubmodulePaths(`/wave-${wave}-repo-${i}`)
}
expect(getSubmodulePathsCacheCountForTests()).toBe(MAX_SUBMODULE_PATHS_CACHE_ENTRIES)
vi.advanceTimersByTime(5_001)
}
await expect(listSubmodulePaths('/retained-repo')).resolves.toEqual(['retained-repo-lib'])
for (let i = 0; i < MAX_SUBMODULE_PATHS_CACHE_ENTRIES - 1; i += 1) {
await listSubmodulePaths(`/final-repo-${i}`)
}
await expect(listSubmodulePaths('/retained-repo')).resolves.toEqual(['retained-repo-lib'])
await listSubmodulePaths(`/final-repo-${MAX_SUBMODULE_PATHS_CACHE_ENTRIES - 1}`)
await listSubmodulePaths('/overflow-repo')
expect(getSubmodulePathsCacheCountForTests()).toBe(MAX_SUBMODULE_PATHS_CACHE_ENTRIES)
const callsBeforeRetainedRead = gitExecFileAsyncMock.mock.calls.length
await expect(listSubmodulePaths('/retained-repo')).resolves.toEqual(['retained-repo-lib'])
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(callsBeforeRetainedRead)
await expect(listSubmodulePaths('/final-repo-0')).resolves.toEqual(['final-repo-0-lib'])
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(callsBeforeRetainedRead + 1)
})
it('does not let a pre-invalidation read repopulate the cache', async () => {
let resolveOldRead: ((value: { stdout: string }) => void) | undefined
gitExecFileAsyncMock.mockImplementationOnce(
() =>
new Promise<{ stdout: string }>((resolve) => {
resolveOldRead = resolve
})
)
const oldRead = listSubmodulePaths('/repo')
expect(resolveOldRead).toBeTypeOf('function')
clearSubmodulePathsCacheForTests()
resolveOldRead?.({ stdout: 'submodule.lib.path old-lib\n' })
await expect(oldRead).resolves.toEqual(['old-lib'])
expect(getSubmodulePathsCacheCountForTests()).toBe(0)
await expect(listSubmodulePaths('/repo')).resolves.toEqual(['repo-lib'])
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
it('does not reuse another branch\'s submodule paths after local or WSL checkout', async () => {
let modulePath = 'main-lib'
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'checkout') {
modulePath = 'feature-lib'
return Promise.resolve({ stdout: '' })
}
return Promise.resolve({ stdout: `submodule.lib.path ${modulePath}\n` })
})
const runtime = { wslDistro: 'Ubuntu' }
await expect(listSubmodulePaths('/repo', runtime)).resolves.toEqual(['main-lib'])
await checkoutBranch('/repo', 'feature', runtime)
await expect(listSubmodulePaths('/repo', runtime)).resolves.toEqual(['feature-lib'])
const configReads = gitExecFileAsyncMock.mock.calls.filter(
([args]) => args[0] === 'config' && args.includes('.gitmodules')
)
expect(configReads).toHaveLength(2)
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['checkout', 'feature', '--'], {
cwd: '/repo',
wslDistro: 'Ubuntu'
})
})
it.each([
['pull', () => gitPull('/repo')],
['rebase', () => gitPullRebaseFromBase('/repo', 'origin/main')]
])('invalidates submodule paths around local %s', async (_name, mutate) => {
let modulePath = 'old-lib'
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'remote') {
return Promise.resolve({ stdout: 'origin\n' })
}
if (args[0] === 'pull') {
modulePath = 'fresh-lib'
return Promise.resolve({ stdout: '' })
}
if (args[0] === 'config' && args.includes('.gitmodules')) {
return Promise.resolve({ stdout: `submodule.lib.path ${modulePath}\n` })
}
return Promise.resolve({ stdout: '' })
})
await expect(listSubmodulePaths('/repo')).resolves.toEqual(['old-lib'])
await mutate()
await expect(listSubmodulePaths('/repo')).resolves.toEqual(['fresh-lib'])
const configReads = gitExecFileAsyncMock.mock.calls.filter(
([args]) => args[0] === 'config' && args.includes('.gitmodules')
)
expect(configReads).toHaveLength(2)
})
it.each([
['merge', () => abortMerge('/repo', { wslDistro: 'Ubuntu' })],
['rebase', () => abortRebase('/repo', { wslDistro: 'Ubuntu' })]
])('drops a cached empty .gitmodules result when %s abort restores it', async (_name, abort) => {
let modulePath = ''
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[1] === '--abort') {
modulePath = 'restored-lib'
return Promise.resolve({ stdout: '' })
}
return Promise.resolve({
stdout: modulePath ? `submodule.lib.path ${modulePath}\n` : ''
})
})
await expect(listSubmodulePaths('/repo', { wslDistro: 'Ubuntu' })).resolves.toEqual([])
await abort()
await expect(listSubmodulePaths('/repo', { wslDistro: 'Ubuntu' })).resolves.toEqual([
'restored-lib'
])
const configReads = gitExecFileAsyncMock.mock.calls.filter(
([args]) => args[0] === 'config' && args.includes('.gitmodules')
)
expect(configReads).toHaveLength(2)
})
it('drops a same-path negative cache when a local or WSL worktree is recreated', async () => {
let recreated = false
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'worktree' && args[1] === 'add') {
recreated = true
}
if (args[0] === 'config' && args.includes('.gitmodules')) {
return Promise.resolve({
stdout: recreated ? 'submodule.lib.path recreated-lib\n' : ''
})
}
return Promise.resolve({ stdout: '' })
})
const runtime = { wslDistro: 'Ubuntu' }
await expect(listSubmodulePaths('/repo-feature', runtime)).resolves.toEqual([])
await removeWorktree('/repo', '/repo-feature', true, {
...runtime,
knownRemovedWorktree: { branch: '', head: '', locked: false }
})
await addWorktree('/repo', '/repo-feature', 'feature', undefined, false, false, {
...runtime,
checkoutExistingBranch: true
})
await expect(listSubmodulePaths('/repo-feature', runtime)).resolves.toEqual([
'recreated-lib'
])
const configReads = gitExecFileAsyncMock.mock.calls.filter(
([args]) => args[0] === 'config' && args.includes('.gitmodules')
)
expect(configReads).toHaveLength(2)
})
})
+95 -23
View File
@@ -64,8 +64,10 @@ type EffectiveUpstreamStatusCacheEntry = {
}
const SUBMODULE_PATHS_CACHE_TTL_MS = 5_000
export const MAX_SUBMODULE_PATHS_CACHE_ENTRIES = 512
type SubmodulePathsCacheEntry = { paths: string[]; expiresAt: number }
const submodulePathsCache = new Map<string, SubmodulePathsCacheEntry>()
let submodulePathsCacheGeneration = 0
// Why: the effective-upstream resolution chain (symbolic-ref + rev-parse ×2-3
// + config snapshot) costs 4-5 subprocess spawns and only changes when branch
@@ -92,15 +94,37 @@ const statusReadsInFlight = new Map<string, Promise<GitStatusResult>>()
// Why: a mutation invalidates both in-flight diff reads and in-flight status
// coalescing; clearing only the diff dedupe would let a post-mutation
// getStatus() join a pre-mutation read and return stale entries.
function clearGitReadInvalidationState(): void {
export function invalidateGitReadCaches(): void {
gitDiffReadDedupe.clear()
statusReadsInFlight.clear()
submodulePathsCache.clear()
clearSubmodulePathsCache()
resolvedUpstreamNameCache.clear()
}
export async function runWithGitReadCacheInvalidation<T>(run: () => Promise<T>): Promise<T> {
invalidateGitReadCaches()
try {
return await run()
} finally {
// Why: a read that started during the mutation can be stale too, so the
// post-mutation boundary retires both pre-existing and overlapping reads.
invalidateGitReadCaches()
}
}
export function clearSubmodulePathsCacheForTests(): void {
clearSubmodulePathsCache()
}
function clearSubmodulePathsCache(): void {
submodulePathsCache.clear()
// Why: a pre-mutation .gitmodules read must not repopulate the cache after
// the mutation invalidated it.
submodulePathsCacheGeneration += 1
}
export function getSubmodulePathsCacheCountForTests(): number {
return submodulePathsCache.size
}
function gitRuntimeOptionsKey(options: GitRuntimeOptions): readonly unknown[] {
@@ -113,6 +137,44 @@ function getSubmodulePathsCacheKey(worktreePath: string, options: GitRuntimeOpti
return [worktreePath, ...gitRuntimeOptionsKey(options)].join('\0')
}
function pruneExpiredSubmodulePathsCache(now: number): void {
for (const [cacheKey, entry] of submodulePathsCache) {
if (entry.expiresAt <= now) {
submodulePathsCache.delete(cacheKey)
}
}
}
function trimSubmodulePathsCache(): void {
while (submodulePathsCache.size > MAX_SUBMODULE_PATHS_CACHE_ENTRIES) {
const oldestKey = submodulePathsCache.keys().next().value
if (oldestKey === undefined) {
break
}
submodulePathsCache.delete(oldestKey)
}
}
function getCachedSubmodulePaths(cacheKey: string, now: number): string[] | null {
const cached = submodulePathsCache.get(cacheKey)
if (!cached) {
return null
}
if (cached.expiresAt <= now) {
submodulePathsCache.delete(cacheKey)
return null
}
submodulePathsCache.delete(cacheKey)
submodulePathsCache.set(cacheKey, cached)
return cached.paths
}
function rememberSubmodulePaths(cacheKey: string, paths: string[], now: number): void {
submodulePathsCache.delete(cacheKey)
submodulePathsCache.set(cacheKey, { paths, expiresAt: now + SUBMODULE_PATHS_CACHE_TTL_MS })
trimSubmodulePathsCache()
}
// Why: status tests reuse this reset hook, so every cross-call memoization layer
// must reset together even though the historical name mentions upstream only.
export function clearEffectiveUpstreamStatusCacheForTests(): void {
@@ -120,7 +182,7 @@ export function clearEffectiveUpstreamStatusCacheForTests(): void {
effectiveUpstreamStatusInFlight.clear()
retiredEffectiveUpstreamStatusInFlight.clear()
effectiveUpstreamStatusWriteGeneration.clear()
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
export function getEffectiveUpstreamStatusCacheCountForTests(): number {
@@ -908,14 +970,18 @@ export async function abortMerge(
worktreePath: string,
options: GitRuntimeOptions = {}
): Promise<void> {
await gitExecFileAsync(['merge', '--abort'], gitOptionsForWorktree(worktreePath, options))
await runWithGitReadCacheInvalidation(() =>
gitExecFileAsync(['merge', '--abort'], gitOptionsForWorktree(worktreePath, options))
)
}
export async function abortRebase(
worktreePath: string,
options: GitRuntimeOptions = {}
): Promise<void> {
await gitExecFileAsync(['rebase', '--abort'], gitOptionsForWorktree(worktreePath, options))
await runWithGitReadCacheInvalidation(() =>
gitExecFileAsync(['rebase', '--abort'], gitOptionsForWorktree(worktreePath, options))
)
}
export async function resolveGitDir(worktreePath: string): Promise<string> {
@@ -945,10 +1011,14 @@ export async function listSubmodulePaths(
): Promise<string[]> {
const now = Date.now()
const cacheKey = getSubmodulePathsCacheKey(worktreePath, options)
const cached = submodulePathsCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
return cached.paths
const cached = getCachedSubmodulePaths(cacheKey, now)
if (cached) {
return cached
}
// Why: prune on misses so removed worktrees do not accumulate while hot
// cache hits stay O(1).
pruneExpiredSubmodulePathsCache(now)
const cacheGeneration = submodulePathsCacheGeneration
let paths: string[] = []
try {
const { stdout } = await gitExecFileAsync(
@@ -971,7 +1041,9 @@ export async function listSubmodulePaths(
// No .gitmodules (or git config failure) — treat as a repo without submodules.
paths = []
}
submodulePathsCache.set(cacheKey, { paths, expiresAt: now + SUBMODULE_PATHS_CACHE_TTL_MS })
if (cacheGeneration === submodulePathsCacheGeneration) {
rememberSubmodulePaths(cacheKey, paths, Date.now())
}
return paths
}
@@ -1834,14 +1906,14 @@ export async function stageFile(
filePath: string,
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
try {
await gitExecFileAsync(
['add', '--', literalPathspec(filePath, options)],
gitOptionsForWorktree(worktreePath, options)
)
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -1853,13 +1925,13 @@ export async function unstageFile(
filePath: string,
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
try {
await gitExecFileAsync(['restore', '--staged', '--', literalPathspec(filePath, options)], {
...gitOptionsForWorktree(worktreePath, options)
})
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -1916,7 +1988,7 @@ export async function commitChanges(
message: string,
options: GitRuntimeOptions = {}
): Promise<{ success: boolean; error?: string }> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
try {
await gitExecFileAsync(['commit', '-m', message], gitOptionsForWorktree(worktreePath, options))
return { success: true }
@@ -1939,7 +2011,7 @@ export async function commitChanges(
(error instanceof Error ? error.message : 'Commit failed')
return { success: false, error: errorMessage }
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -1951,7 +2023,7 @@ export async function discardChanges(
filePath: string,
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
const resolvedWorktree = path.resolve(worktreePath)
const resolvedTarget = path.resolve(worktreePath, filePath)
try {
@@ -1986,7 +2058,7 @@ export async function discardChanges(
cleanUntrackedPaths(worktreePath, [targetPath], options)
)
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -2061,7 +2133,7 @@ export async function bulkDiscardChanges(
filePaths: string[],
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
if (filePaths.length === 0) {
return
}
@@ -2105,7 +2177,7 @@ export async function bulkDiscardChanges(
}
)
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -2131,7 +2203,7 @@ export async function bulkStageFiles(
filePaths: string[],
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
if (filePaths.length === 0) {
return
}
@@ -2144,7 +2216,7 @@ export async function bulkStageFiles(
)
}
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
@@ -2156,7 +2228,7 @@ export async function bulkUnstageFiles(
filePaths: string[],
options: GitRuntimeOptions = {}
): Promise<void> {
clearGitReadInvalidationState()
invalidateGitReadCaches()
if (filePaths.length === 0) {
return
}
@@ -2176,6 +2248,6 @@ export async function bulkUnstageFiles(
)
}
} finally {
clearGitReadInvalidationState()
invalidateGitReadCaches()
}
}
+17 -11
View File
@@ -24,7 +24,7 @@ import {
} from '../../shared/git-worktree-command-capabilities'
import { getLocalGitCapabilityCache } from './git-capability-state'
import { gitExecFileAsync, translateWslOutputPaths } from './runner'
import { resolveGitDir } from './status'
import { resolveGitDir, runWithGitReadCacheInvalidation } from './status'
import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe'
export type AddWorktreeResult = {
@@ -838,14 +838,16 @@ export async function addWorktree(
options: AddWorktreeOptions = {}
): Promise<AddWorktreeResult> {
try {
return await performAddWorktree(
repoPath,
worktreePath,
branch,
baseBranch,
refreshLocalBaseRef,
noCheckout,
options
return await runWithGitReadCacheInvalidation(() =>
performAddWorktree(
repoPath,
worktreePath,
branch,
baseBranch,
refreshLocalBaseRef,
noCheckout,
options
)
)
} finally {
bumpWorktreeScanGeneration(repoPath)
@@ -1056,7 +1058,9 @@ export async function moveWorktree(
newPath: string
): Promise<void> {
try {
await gitExecFileAsync(['worktree', 'move', oldPath, newPath], { cwd: repoPath })
await runWithGitReadCacheInvalidation(() =>
gitExecFileAsync(['worktree', 'move', oldPath, newPath], { cwd: repoPath })
)
} finally {
bumpWorktreeScanGeneration(repoPath)
}
@@ -1076,7 +1080,9 @@ export async function removeWorktree(
options: RemoveWorktreeOptions = {}
): Promise<RemoveWorktreeResult> {
try {
return await performRemoveWorktree(repoPath, worktreePath, force, options)
return await runWithGitReadCacheInvalidation(() =>
performRemoveWorktree(repoPath, worktreePath, force, options)
)
} finally {
bumpWorktreeScanGeneration(repoPath)
}