Files
orca/src/main/git/worktrees/creation/worktree-base-refresh.ts
T
Brennan BensonandNeil 3bb91aaf36 Keep Git reads responsive during worktree creation bursts (#41927)
* Isolate worktree checkout admission and bound default workers

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>

* Prove checkout admission survives caller timeout

* Keep checkout admission coverage compatible with older Git

* Keep aged Git work below interactive priority

---------

Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
2026-11-13 10:31:03 -08:00

148 lines
5.7 KiB
TypeScript

import type {
LocalBaseRefRefreshResult,
LocalBaseRefUpdateSuggestion
} from '../../../../shared/worktree/base-ref-drift-types'
import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path'
import { createCoalescingKeyedRunner } from '../../../../shared/coalescing-keyed-runner'
import { parseWorktreeList } from '../../../../shared/git/worktrees/git-worktree-porcelain-parser'
import {
fastForwardLocalBaseBranch,
inspectLocalBaseBranch,
toLocalBaseRefRefreshResult,
type LocalBaseBranchFastForwardOutcome,
type LocalBaseBranchGit
} from '../../../../shared/worktree/local-base-branch-fast-forward'
import { gitExecFileAsync } from '../../command-runner/git-exec-file'
import { findGitSubcommandIndex } from '../../../../shared/git/commands/git-command-classification'
import { translateWslOutputPaths } from '../../command-runner/host-routing/wsl-path-translation'
import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation'
import type { AddWorktreeOptions, GitWorktreeExecOptions } from '../worktree-operation-options'
// Bound the create's wait without cancelling the mutating refresh that still owns its checkout.
export const LOCAL_BASE_REF_REFRESH_WAIT_MS = 30_000
// Serialize per branch to avoid index.lock races; coalesce only matching targets.
const runPerLocalBaseBranch = createCoalescingKeyedRunner<LocalBaseBranchFastForwardOutcome>()
export function parseRemoteTrackingLocalBaseRef(
baseBranch: string,
remoteTrackingRef: string,
remoteTrackingBase?: AddWorktreeOptions['remoteTrackingBase']
): { baseRef: string; localBranch: string; fullRef: string } | undefined {
if (remoteTrackingBase?.ref === remoteTrackingRef) {
return {
baseRef: remoteTrackingBase.base,
localBranch: remoteTrackingBase.branch,
fullRef: `refs/heads/${remoteTrackingBase.branch}`
}
}
const remoteRefPrefix = 'refs/remotes/'
if (!remoteTrackingRef.startsWith(remoteRefPrefix)) {
return undefined
}
// Only proven remote-tracking refs warrant refresh warnings, not slash-named local branches.
const shortRemoteRef = remoteTrackingRef.slice(remoteRefPrefix.length)
const slashIndex = shortRemoteRef.indexOf('/')
if (slashIndex <= 0) {
return undefined
}
const localBranch = shortRemoteRef.slice(slashIndex + 1)
return {
baseRef: baseBranch,
localBranch,
fullRef: `refs/heads/${localBranch}`
}
}
export async function refreshLocalBaseRefForWorktreeCreate(
repoPath: string,
baseBranch: string,
remoteTrackingRef: string,
remoteTrackingBase?: AddWorktreeOptions['remoteTrackingBase'],
options: GitWorktreeExecOptions = {}
): Promise<LocalBaseRefRefreshResult | undefined> {
const parsed = parseRemoteTrackingLocalBaseRef(baseBranch, remoteTrackingRef, remoteTrackingBase)
if (!parsed) {
return undefined
}
const key = `${options.wslDistro ?? ''}\0${normalizeRuntimePathForComparison(repoPath)}\0${parsed.fullRef}`
const git = localBaseBranchGit(options)
const outcome = await waitAtMost(
// The shared run may outlive its create, so it owns cache invalidation.
runPerLocalBaseBranch(key, remoteTrackingRef, () =>
runWithGitReadCacheInvalidation(() =>
fastForwardLocalBaseBranch(git, { repoPath, fullRef: parsed.fullRef, remoteTrackingRef })
)
),
LOCAL_BASE_REF_REFRESH_WAIT_MS
)
if (!outcome) {
console.warn(
`addWorktree: stopped waiting for the local ${parsed.localBranch} refresh after ${LOCAL_BASE_REF_REFRESH_WAIT_MS}ms`
)
}
return toLocalBaseRefRefreshResult(parsed, outcome)
}
export async function getLocalBaseRefUpdateSuggestionForWorktreeCreate(
repoPath: string,
baseBranch: string,
remoteTrackingRef: string,
remoteTrackingBase?: AddWorktreeOptions['remoteTrackingBase'],
options: GitWorktreeExecOptions = {}
): Promise<LocalBaseRefUpdateSuggestion | undefined> {
const parsed = parseRemoteTrackingLocalBaseRef(baseBranch, remoteTrackingRef, remoteTrackingBase)
if (!parsed) {
return undefined
}
const inspection = await inspectLocalBaseBranch(localBaseBranchGit(options), {
repoPath,
fullRef: parsed.fullRef,
remoteTrackingRef
})
return inspection.status === 'behind'
? { baseRef: parsed.baseRef, localBranch: parsed.localBranch, behind: inspection.behind }
: undefined
}
function localBaseBranchGit(options: GitWorktreeExecOptions): LocalBaseBranchGit {
// Shared refreshes cannot use any individual create's cancellation signal or timeout.
const execOptions = (cwd: string) => ({
cwd,
...(options.wslDistro ? { wslDistro: options.wslDistro } : {}),
...(options.admissionTier ? { admissionTier: options.admissionTier } : {})
})
return {
exec: (args, cwd) =>
gitExecFileAsync(args, {
...execOptions(cwd),
...(args[findGitSubcommandIndex(args)] === 'merge'
? { admissionClass: 'checkout' as const }
: {})
}),
listWorktrees: async (repoPath) => {
const { stdout } = await withRepositoryGitCause(
repoPath,
options,
{ family: 'catalog', reason: 'creation-base-refresh', cache: 'uncached' },
() => gitExecFileAsync(['worktree', 'list', '--porcelain'], execOptions(repoPath))
)
return parseWorktreeList(translateWslOutputPaths(stdout, repoPath, options))
}
}
}
function waitAtMost<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
return Promise.race([
promise,
new Promise<undefined>((resolve) => {
timer = setTimeout(() => resolve(undefined), timeoutMs)
})
]).finally(() => clearTimeout(timer))
}
import { withRepositoryGitCause } from '../../repository-git-cause'