diff --git a/src/main/git/status-upstream-probe-churn.test.ts b/src/main/git/status-upstream-probe-churn.test.ts index 7cb3d9d99..effe5302d 100644 --- a/src/main/git/status-upstream-probe-churn.test.ts +++ b/src/main/git/status-upstream-probe-churn.test.ts @@ -77,6 +77,42 @@ describe('getStatus missing-upstream polling churn', () => { expect(sameNameOriginProbeCalls).toHaveLength(1) }) + it('coalesces concurrent effective-upstream probes for a branch with no upstream', async () => { + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args.includes('status')) { + return { + stdout: '# branch.oid abcdef1234567890\n# branch.head Initi-Project\n' + } + } + if (args[0] === 'symbolic-ref' && args.includes('HEAD')) { + return { stdout: 'Initi-Project\n' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + await Promise.resolve() + throw new Error("fatal: no upstream configured for branch 'Initi-Project'") + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/Initi-Project')) { + await Promise.resolve() + throw new Error('missing remote branch') + } + throw new Error(`unexpected git command: ${args.join(' ')}`) + }) + + await Promise.all([getStatus('/repo'), getStatus('/repo'), getStatus('/repo')]) + + const upstreamProbeCalls = gitExecFileAsyncMock.mock.calls.filter((call) => { + const args = getGitArgs(call) + return args[0] === 'rev-parse' && args.includes('HEAD@{u}') + }) + const sameNameOriginProbeCalls = gitExecFileAsyncMock.mock.calls.filter((call) => { + const args = getGitArgs(call) + return args[0] === 'rev-parse' && args.includes('refs/remotes/origin/Initi-Project') + }) + + expect(upstreamProbeCalls).toHaveLength(1) + expect(sameNameOriginProbeCalls).toHaveLength(1) + }) + it('rechecks failed effective-upstream probes after the branch identity changes', async () => { let nextBranch = 'Second-Project' let currentStatusBranch = nextBranch diff --git a/src/main/git/status.ts b/src/main/git/status.ts index 8861c90b6..1a5675e94 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -46,9 +46,11 @@ type EffectiveUpstreamStatusCacheEntry = { } const effectiveUpstreamStatusCache = new Map() +const effectiveUpstreamStatusInFlight = new Map>() export function clearEffectiveUpstreamStatusCacheForTests(): void { effectiveUpstreamStatusCache.clear() + effectiveUpstreamStatusInFlight.clear() } export type GetStatusOptions = { @@ -184,38 +186,19 @@ export async function getStatus( if (shouldProbeEffectiveUpstreamStatus(branch, upstreamName)) { const branchName = getShortBranchName(branch) - const cacheKey = branchName - ? getEffectiveUpstreamStatusCacheKey(worktreePath, branchName, upstreamName) - : null - effectiveUpstreamStatus = cacheKey - ? readCachedEffectiveUpstreamStatus(cacheKey, Date.now()) - : undefined - let probedSameNameOriginRef = false - try { - if (!effectiveUpstreamStatus) { - effectiveUpstreamStatus = await getEffectiveGitUpstreamStatus((args) => { - if ( - branchName && - args[0] === 'rev-parse' && - args.includes(`refs/remotes/origin/${branchName}`) - ) { - probedSameNameOriginRef = true - } - return gitExecFileAsync(args, { cwd: worktreePath }) - }) - if (cacheKey) { - rememberEffectiveUpstreamStatus( - cacheKey, - effectiveUpstreamStatus, - Date.now(), - probedSameNameOriginRef - ) - } + if (branchName) { + const cacheKey = getEffectiveUpstreamStatusCacheKey(worktreePath, branchName, upstreamName) + try { + effectiveUpstreamStatus = await readOrProbeEffectiveUpstreamStatus( + cacheKey, + worktreePath, + branchName + ) + } catch { + // Why: git status polling should not fail just because the richer + // upstream probe hit a transient ref/read error; the explicit + // upstream-status path will surface those failures when invoked. } - } catch { - // Why: git status polling should not fail just because the richer - // upstream probe hit a transient ref/read error; the explicit - // upstream-status path will surface those failures when invoked. } } } catch { @@ -353,6 +336,56 @@ function rememberEffectiveUpstreamStatus( }) } +async function readOrProbeEffectiveUpstreamStatus( + cacheKey: string, + worktreePath: string, + branchName: string +): Promise { + const cached = readCachedEffectiveUpstreamStatus(cacheKey, Date.now()) + if (cached) { + return cached + } + + const inFlight = effectiveUpstreamStatusInFlight.get(cacheKey) + if (inFlight) { + return inFlight + } + + // Why: source-control mount and root git refresh can overlap during startup. + // Coalesce the richer upstream probe so a stable missing ref fails once. + const probe = probeEffectiveUpstreamStatus(worktreePath, branchName).then((result) => { + rememberEffectiveUpstreamStatus( + cacheKey, + result.status, + Date.now(), + result.probedSameNameOriginRef + ) + return result.status + }) + effectiveUpstreamStatusInFlight.set(cacheKey, probe) + try { + return await probe + } finally { + if (effectiveUpstreamStatusInFlight.get(cacheKey) === probe) { + effectiveUpstreamStatusInFlight.delete(cacheKey) + } + } +} + +async function probeEffectiveUpstreamStatus( + worktreePath: string, + branchName: string +): Promise<{ status: GitUpstreamStatus; probedSameNameOriginRef: boolean }> { + let probedSameNameOriginRef = false + const status = await getEffectiveGitUpstreamStatus((args) => { + if (args[0] === 'rev-parse' && args.includes(`refs/remotes/origin/${branchName}`)) { + probedSameNameOriginRef = true + } + return gitExecFileAsync(args, { cwd: worktreePath }) + }) + return { status, probedSameNameOriginRef } +} + function shouldProbeEffectiveUpstreamStatus( branch: string | undefined, upstreamName: string | undefined diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts index 8a2a313f6..61d3318f8 100644 --- a/src/main/github/gh-utils.test.ts +++ b/src/main/github/gh-utils.test.ts @@ -137,6 +137,30 @@ describe('github owner/repo resolution', () => { await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' }) }) + it('coalesces concurrent missing remote probes for the same repo and remote', async () => { + gitExecFileAsyncMock.mockImplementation(async () => { + await Promise.resolve() + throw new Error("error: No such remote 'upstream'") + }) + + await expect( + Promise.all([ + getOwnerRepoForRemote('/repo', 'upstream'), + getOwnerRepoForRemote('/repo', 'upstream'), + getOwnerRepoForRemote('/repo', 'upstream'), + getOwnerRepoForRemote('/repo', 'upstream') + ]) + ).resolves.toEqual([null, null, null, null]) + + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { + cwd: '/repo' + }) + + await expect(getOwnerRepoForRemote('/repo', 'upstream')).resolves.toBeNull() + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + it('resolves SSH repo remotes through the registered SSH git provider', async () => { const sshProvider = { exec: vi.fn().mockResolvedValue({ stdout: 'git@github.com:stablyai/orca.git\n', stderr: '' }) diff --git a/src/main/github/gh-utils.ts b/src/main/github/gh-utils.ts index 5bb3572a4..944436241 100644 --- a/src/main/github/gh-utils.ts +++ b/src/main/github/gh-utils.ts @@ -146,10 +146,12 @@ type OwnerRepoCacheEntry = { } const ownerRepoCache = new Map() +const ownerRepoInFlight = new Map>() /** @internal — exposed for tests only */ export function _resetOwnerRepoCache(): void { ownerRepoCache.clear() + ownerRepoInFlight.clear() } /** @internal — exposed for tests only */ @@ -249,6 +251,32 @@ export async function getOwnerRepoForRemote( if (cached && cached.expiresAt > now) { return cached.value } + + const inFlight = ownerRepoInFlight.get(cacheKey) + if (inFlight) { + return inFlight + } + + // Why: startup can resolve issue sources, PR candidates, and repo metadata + // for the same repo concurrently. Coalesce missing-remote probes so a stable + // absent upstream does not spawn identical `git remote get-url` processes. + const probe = resolveOwnerRepoForRemote(context, remoteName, cacheKey) + ownerRepoInFlight.set(cacheKey, probe) + try { + return await probe + } finally { + if (ownerRepoInFlight.get(cacheKey) === probe) { + ownerRepoInFlight.delete(cacheKey) + } + } +} + +async function resolveOwnerRepoForRemote( + context: GitHubRepoContext, + remoteName: string, + cacheKey: string +): Promise { + const now = Date.now() try { const remoteUrl = await getRemoteUrlForRepo(context, remoteName) const result = remoteUrl ? parseGitHubOwnerRepo(remoteUrl) : null diff --git a/src/main/gitlab/gl-utils.test.ts b/src/main/gitlab/gl-utils.test.ts index b2c253c19..6a3a57beb 100644 --- a/src/main/gitlab/gl-utils.test.ts +++ b/src/main/gitlab/gl-utils.test.ts @@ -178,6 +178,30 @@ describe('gitlab project ref resolution', () => { }) }) + it('coalesces concurrent missing remote probes for the same repo and remote', async () => { + gitExecFileAsyncMock.mockImplementation(async () => { + await Promise.resolve() + throw new Error("error: No such remote 'upstream'") + }) + + await expect( + Promise.all([ + getProjectRefForRemote('/repo', 'upstream'), + getProjectRefForRemote('/repo', 'upstream'), + getProjectRefForRemote('/repo', 'upstream'), + getProjectRefForRemote('/repo', 'upstream') + ]) + ).resolves.toEqual([null, null, null, null]) + + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { + cwd: '/repo' + }) + + await expect(getProjectRefForRemote('/repo', 'upstream')).resolves.toBeNull() + expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + it('resolves project refs through the SSH git provider for connected repos', async () => { sshExecMock.mockResolvedValueOnce({ stdout: 'git@gitlab.com:remote/orca.git\n', stderr: '' }) registerSshGitProvider('conn-1', { exec: sshExecMock } as never) diff --git a/src/main/gitlab/gl-utils.ts b/src/main/gitlab/gl-utils.ts index ad109985b..9ae15ef23 100644 --- a/src/main/gitlab/gl-utils.ts +++ b/src/main/gitlab/gl-utils.ts @@ -3,6 +3,7 @@ import { promisify } from 'util' import { gitExecFileAsync, glabExecFileAsync } from '../git/runner' import type { ClassifiedError, GitLabProjectRef, IssueSourcePreference } from '../../shared/types' import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { clearProjectRefInFlight, runProjectRefProbeOnce } from './project-ref-inflight' // Why: legacy generic execFile wrapper — only used by callers that don't need // WSL-aware routing. Repo-scoped callers should use glabExecFileAsync from @@ -109,6 +110,7 @@ const projectRefCache = new Map() /** @internal — exposed for tests only */ export function _resetProjectRefCache(): void { projectRefCache.clear() + clearProjectRefInFlight() } /** @internal — exposed for tests only */ @@ -192,6 +194,21 @@ export async function getProjectRefForRemote( if (projectRefCache.has(cacheKey)) { return projectRefCache.get(cacheKey)! } + + // Why: issue/PR refresh and repo metadata can ask for the same missing + // upstream concurrently. Coalesce the subprocess before caching the result. + return runProjectRefProbeOnce(cacheKey, () => + resolveProjectRefForRemote(repoPath, remoteName, knownHosts, connectionId, cacheKey) + ) +} + +async function resolveProjectRefForRemote( + repoPath: string, + remoteName: string, + knownHosts: readonly string[], + connectionId: string | null | undefined, + cacheKey: string +): Promise { try { const sshGitProvider = connectionId ? getSshGitProvider(connectionId) : null if (connectionId && !sshGitProvider) { diff --git a/src/main/gitlab/project-ref-inflight.ts b/src/main/gitlab/project-ref-inflight.ts new file mode 100644 index 000000000..8df88f63a --- /dev/null +++ b/src/main/gitlab/project-ref-inflight.ts @@ -0,0 +1,26 @@ +import type { ProjectRef } from './gl-utils' + +const projectRefInFlight = new Map>() + +export function clearProjectRefInFlight(): void { + projectRefInFlight.clear() +} + +export async function runProjectRefProbeOnce( + cacheKey: string, + createProbe: () => Promise +): Promise { + const inFlight = projectRefInFlight.get(cacheKey) + if (inFlight) { + return inFlight + } + const probe = createProbe() + projectRefInFlight.set(cacheKey, probe) + try { + return await probe + } finally { + if (projectRefInFlight.get(cacheKey) === probe) { + projectRefInFlight.delete(cacheKey) + } + } +}