perf(runtime): limit status-read invalidation to the checkouts an outside change touched

This commit is contained in:
Kelvin Amoaba
2026-11-08 18:02:18 +00:00
parent 5f54c93dae
commit 04b0a4bdc0
6 changed files with 109 additions and 33 deletions
@@ -1,12 +1,16 @@
import type { GitDiffResult } from '../../../shared/git/diff/git-diff-compare-types'
import type { GitStatusResult } from '../../../shared/git/status/git-status-types'
import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe'
import { clearGitStatusLineStatsCache } from '../../../shared/git/status/git-status-line-stats-cache'
import {
clearGitStatusLineStatsCache,
clearGitStatusLineStatsCacheKey
} from '../../../shared/git/status/git-status-line-stats-cache'
import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total'
import { GitStatusReadLeaseOwner } from '../../../shared/git/status/git-status-read-lease-owner'
import { invalidateGitUpstreamStatusReads } from './upstream'
import { clearSubmodulePathsCache } from './submodule-paths'
import { resolvedUpstreamNameCache } from './resolved-upstream-name-cache'
import { getStatusLineStatsCacheKey } from './status-branch-line-total-input'
import {
FILE_DIFF_CACHE_LIMITS,
NUMSTAT_CACHE_LIMITS,
@@ -37,9 +41,19 @@ export function invalidateGitReadCaches(): void {
}
// A change made outside Orca: later status reads must neither join a read begun before it nor reuse its line counts.
export function invalidateGitStatusReads(): void {
statusReadLeaseOwner.invalidate()
clearGitStatusLineStatsCache()
// `null` means the changed checkouts are unknown.
export function invalidateGitStatusReads(worktreePaths: readonly string[] | null): void {
if (worktreePaths === null) {
statusReadLeaseOwner.invalidate()
clearGitStatusLineStatsCache()
return
}
for (const worktreePath of worktreePaths) {
// Status-read keys start with this one (getStatusReadKey).
const scope = getStatusLineStatsCacheKey(worktreePath)
statusReadLeaseOwner.invalidateWhere((key) => key.startsWith(`${scope}\0`))
clearGitStatusLineStatsCacheKey(scope)
}
}
export async function runWithGitReadCacheInvalidation<T>(run: () => Promise<T>): Promise<T> {
+3 -4
View File
@@ -48,11 +48,10 @@ export async function getStatus(
)
}
// Led by the worktree's line-stats key so an outside change can detach just that checkout's reads.
function getStatusReadKey(worktreePath: string, options: GetStatusOptions): string {
const limit = resolveGitStatusLimit(options.limit)
return stableInFlightKey([
worktreePath,
options.wslDistro ?? '',
return `${getStatusLineStatsCacheKey(worktreePath, options)}\0${stableInFlightKey([
options.admissionTier ?? 'status',
options.includeIgnored === true,
options.includeLineStats !== false,
@@ -63,7 +62,7 @@ function getStatusReadKey(worktreePath: string, options: GetStatusOptions): stri
limit,
// Filtering options affect which rows survive and must participate in the cache key.
options.sharedLinkPaths ?? []
])
])}`
}
/** Hide only configured, real, untracked shared symlinks; directory-only Git ignore rules cannot hide them. */
@@ -4,10 +4,15 @@ import { BrowserWindow } from 'electron'
import { afterEach, expect, it, vi } from 'vitest'
import { listWorktrees } from '../../../git/worktrees/catalog/worktree-scan-cache'
import { listWorktreesStrict } from '../../../git/worktrees/catalog/worktree-listing'
import { getStatusLineStatsCacheKey } from '../../../git/source-control/status-branch-line-total-input'
import { OrcaRuntimeService } from '../../../runtime/orca-runtime'
import { partialRuntimeStore } from '../../../runtime/orca-runtime-tests/runtime-store-partial-fixture'
import { makeStore } from '../../../runtime/paired-client-navigation-test-harness'
import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events'
import {
applyCachedGitStatusLineStats,
storeGitStatusLineStats
} from '../../../../shared/git/status/git-status-line-stats-cache'
import { setWorktreeCatalogRemoteClientNotifier } from '../../watched-worktree-catalog-notification'
import {
scheduleWorktreeBaseNotification,
@@ -38,6 +43,31 @@ vi.mock('../../../git/worktrees/catalog/worktree-listing', async (importOriginal
listWorktreesStrict: vi.fn()
}))
// A watched common dir whose memo knows the linked checkout /tmp/feature.
function watchWithFeatureCheckout(): WorktreeBaseNotificationWatch {
const headIdentityRefresh = createWorktreeHeadIdentityRefreshState()
headIdentityRefresh.cache.entries.set('feature', {
worktreePath: '/tmp/feature',
head: 'b',
branch: 'refs/heads/feature'
})
return {
key: 'git-common:/tmp/repo/.git',
kind: 'git-common',
path: '/tmp/repo/.git',
repos: new Map(),
mainWindow: new BrowserWindow(),
notifyTimer: null,
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
pendingHeadIdentityRepoIds: new Set(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh,
disposed: false
}
}
afterEach(() => {
vi.useRealTimers()
setWorktreeCatalogRemoteClientNotifier(null)
@@ -69,27 +99,7 @@ it('tells paired clients which worktree an index change touched', async () => {
const events: RuntimeClientEvent[] = []
runtime.onClientEvent((event) => events.push(event))
const headIdentityRefresh = createWorktreeHeadIdentityRefreshState()
headIdentityRefresh.cache.entries.set('feature', {
worktreePath: '/tmp/feature',
head: 'b',
branch: 'refs/heads/feature'
})
const watch: WorktreeBaseNotificationWatch = {
key: 'git-common:/tmp/repo/.git',
kind: 'git-common',
path: '/tmp/repo/.git',
repos: new Map(),
mainWindow: new BrowserWindow(),
notifyTimer: null,
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
pendingHeadIdentityRepoIds: new Set(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh,
disposed: false
}
const watch = watchWithFeatureCheckout()
vi.useFakeTimers()
scheduleWorktreeBaseNotification(watch, {
gitStatusRepoIds: ['repo-1'],
@@ -101,3 +111,31 @@ it('tells paired clients which worktree an index change touched', async () => {
{ type: 'gitStatusChanged', repoId: 'repo-1', worktreeIds: ['repo-1::/tmp/feature'] }
])
})
it("drops reused line counts for the checkout an index change touched, not another repo's", async () => {
const counted = [{ path: 'a.txt', status: 'modified', area: 'staged', added: 3, removed: 1 }]
const touched = getStatusLineStatsCacheKey('/tmp/feature')
const otherRepo = getStatusLineStatsCacheKey('/tmp/other-repo')
for (const cacheKey of [touched, otherRepo]) {
storeGitStatusLineStats({ cacheKey, head: 'h', entries: counted, now: 0 })
}
const reusable = (cacheKey: string): boolean =>
applyCachedGitStatusLineStats({
cacheKey,
head: 'h',
entries: [{ path: 'a.txt', status: 'modified', area: 'staged' }],
now: 0
})
vi.useFakeTimers()
scheduleWorktreeBaseNotification(watchWithFeatureCheckout(), {
gitStatusRepoIds: ['repo-1'],
gitStatusScope: headIdentityScopeForEntry('feature')
})
await vi.advanceTimersByTimeAsync(250)
expect({ touched: reusable(touched), otherRepo: reusable(otherRepo) }).toEqual({
touched: false,
otherRepo: true
})
})
@@ -11,7 +11,10 @@ import {
mergeHeadIdentityScopes,
type WorktreeHeadIdentityScope
} from './worktree-head-identity-scope'
import { cachedWorktreePathsForScope } from './worktree-head-identity-cached-paths'
import {
allCachedWorktreePaths,
cachedWorktreePathsForScope
} from './worktree-head-identity-cached-paths'
import { invalidateGitStatusReads } from '../../../git/source-control/git-read-cache-invalidation'
import { notifyWorktreeGitStatusMetadataChanged } from '../../worktree-remote'
import {
@@ -94,10 +97,17 @@ export function scheduleWorktreeBaseNotification(
const gitStatusWorktreePaths = supportsWorktreeHeadIdentityRefresh(watch)
? cachedWorktreePathsForScope(watch.headIdentityRefresh.cache, watch.pendingGitStatusScope)
: null
// Structural and unattributed bursts may touch any checkout of this common dir, but no other repo's.
const changedWorktreePaths =
pendingStructure.length === 0 && gitStatusWorktreePaths
? gitStatusWorktreePaths
: supportsWorktreeHeadIdentityRefresh(watch)
? allCachedWorktreePaths(watch.headIdentityRefresh.cache)
: null
clearPendingWorktreeBaseNotifications(watch)
if (pendingStructure.length > 0 || sourceControlRepoIds.size > 0) {
// Staging can keep a file's status letters, and a phone's re-read must not join a read begun before the change.
invalidateGitStatusReads()
invalidateGitStatusReads(changedWorktreePaths)
}
for (const repoId of pendingStructure) {
notifyWatchedWorktreeCatalogChanged(watch.mainWindow, repoId)
@@ -34,3 +34,12 @@ export function cachedWorktreePathsForScope(
}
return paths
}
/** Every checkout of the common dir, or null while the memo hasn't listed them all. */
export function allCachedWorktreePaths(cache: WorktreeHeadIdentityCache): string[] | null {
if (cache.entryNames === null || cache.primaryUnverified) {
return null
}
const linked = [...cache.entries.values()].map((identity) => identity.worktreePath)
return cache.primary ? [cache.primary.worktreePath, ...linked] : linked
}
@@ -64,10 +64,16 @@ export class GitStatusReadLeaseOwner<T> {
}
invalidate(): void {
this.invalidateWhere(() => true)
}
// Later leases start fresh; callers already holding a detached read keep it.
invalidateWhere(matches: (key: string) => boolean): void {
for (const [key, entry] of this.entries) {
this.detach(key, entry)
if (matches(key)) {
this.detach(key, entry)
}
}
this.entries.clear()
}
private createLease(