diff --git a/src/main/azure-devops/pull-request-creation.test.ts b/src/main/azure-devops/pull-request-creation.test.ts index dfcb4c82b..2b3be3d9e 100644 --- a/src/main/azure-devops/pull-request-creation.test.ts +++ b/src/main/azure-devops/pull-request-creation.test.ts @@ -4,6 +4,7 @@ import { isAzureDevOpsReviewCreationAuthenticated } from './pull-request-creation' import { _resetAzureDevOpsRepoRefCache } from './repository-ref' +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' const { gitExecFileAsyncMock, getSshGitProviderMock } = vi.hoisted(() => ({ gitExecFileAsyncMock: vi.fn(), @@ -149,7 +150,8 @@ describe('Azure DevOps pull request creation', () => { code: 'auth_required' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) }) diff --git a/src/main/azure-devops/repository-ref.test.ts b/src/main/azure-devops/repository-ref.test.ts index 7eaed82a7..6d3e4e13b 100644 --- a/src/main/azure-devops/repository-ref.test.ts +++ b/src/main/azure-devops/repository-ref.test.ts @@ -16,6 +16,7 @@ import { parseAzureDevOpsRepoRef } from './repository-ref' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' describe('parseAzureDevOpsRepoRef', () => { beforeEach(() => { @@ -151,11 +152,13 @@ describe('parseAzureDevOpsRepoRef', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], { cwd: '/repo', - wslDistro: 'Ubuntu' + wslDistro: 'Ubuntu', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) diff --git a/src/main/azure-devops/repository-ref.ts b/src/main/azure-devops/repository-ref.ts index 868d0d8c9..3c014daa6 100644 --- a/src/main/azure-devops/repository-ref.ts +++ b/src/main/azure-devops/repository-ref.ts @@ -1,5 +1,4 @@ -import { gitExecFileAsync } from '../git/runner' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { createRemoteRefProbeCache } from '../git/remote-ref-probe-cache' export type AzureDevOpsRepoRef = { host: string @@ -14,28 +13,16 @@ type LocalGitExecOptions = { wslDistro?: string } -const REPO_REF_CACHE_MAX_ENTRIES = 512 -const repoRefCache = new Map() +const repoRefProbeCache = createRemoteRefProbeCache(parseAzureDevOpsRepoRef) /** @internal - exposed for tests only */ export function _resetAzureDevOpsRepoRefCache(): void { - repoRefCache.clear() + repoRefProbeCache.clear() } /** @internal - exposed for tests only */ export function _getAzureDevOpsRepoRefCacheSize(): number { - return repoRefCache.size -} - -function rememberRepoRefCacheEntry(cacheKey: string, value: AzureDevOpsRepoRef | null): void { - repoRefCache.set(cacheKey, value) - while (repoRefCache.size > REPO_REF_CACHE_MAX_ENTRIES) { - const oldestKey = repoRefCache.keys().next().value - if (oldestKey === undefined) { - return - } - repoRefCache.delete(oldestKey) - } + return repoRefProbeCache.size() } function decodeSegment(value: string): string { @@ -211,34 +198,7 @@ export async function getAzureDevOpsRepoRefForRemote( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { - const runtimeKey = connectionId ?? `local:${localGitOptions.wslDistro ?? 'host'}` - const cacheKey = `${runtimeKey}\0${repoPath}\0${remoteName}` - if (repoRefCache.has(cacheKey)) { - return repoRefCache.get(cacheKey)! - } - try { - const sshGitProvider = connectionId ? getSshGitProvider(connectionId) : null - if (connectionId && !sshGitProvider) { - return null - } - const { stdout } = sshGitProvider - ? await sshGitProvider.exec(['remote', 'get-url', remoteName], repoPath) - : await gitExecFileAsync(['remote', 'get-url', remoteName], { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }) - const result = parseAzureDevOpsRepoRef(stdout) - rememberRepoRefCacheEntry(cacheKey, result) - return result - } catch { - if (connectionId) { - // Why: SSH provider failures are often transient reconnect/tunnel states; - // caching them as "not Azure DevOps" would poison the repo for the session. - return null - } - rememberRepoRefCacheEntry(cacheKey, null) - return null - } + return repoRefProbeCache.get(repoPath, remoteName, connectionId, localGitOptions) } export async function getAzureDevOpsRepoRef( diff --git a/src/main/bitbucket/repository-ref.test.ts b/src/main/bitbucket/repository-ref.test.ts index c29b35399..0b900b213 100644 --- a/src/main/bitbucket/repository-ref.test.ts +++ b/src/main/bitbucket/repository-ref.test.ts @@ -17,6 +17,7 @@ import { parseBitbucketRepoRef } from './repository-ref' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' describe('Bitbucket repository refs', () => { beforeEach(() => { @@ -90,7 +91,8 @@ describe('Bitbucket repository refs', () => { }) expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) @@ -120,11 +122,13 @@ describe('Bitbucket repository refs', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], { cwd: '/repo', - wslDistro: 'Ubuntu' + wslDistro: 'Ubuntu', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) diff --git a/src/main/bitbucket/repository-ref.ts b/src/main/bitbucket/repository-ref.ts index fb07c32d4..8456b2d4a 100644 --- a/src/main/bitbucket/repository-ref.ts +++ b/src/main/bitbucket/repository-ref.ts @@ -1,5 +1,4 @@ -import { gitExecFileAsync } from '../git/runner' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { createRemoteRefProbeCache } from '../git/remote-ref-probe-cache' export type BitbucketRepoRef = { workspace: string @@ -10,28 +9,16 @@ type LocalGitExecOptions = { wslDistro?: string } -const REPO_REF_CACHE_MAX_ENTRIES = 512 -const repoRefCache = new Map() +const repoRefProbeCache = createRemoteRefProbeCache(parseBitbucketRepoRef) /** @internal - exposed for tests only */ export function _resetBitbucketRepoRefCache(): void { - repoRefCache.clear() + repoRefProbeCache.clear() } /** @internal - exposed for tests only */ export function _getBitbucketRepoRefCacheSize(): number { - return repoRefCache.size -} - -function rememberRepoRefCacheEntry(cacheKey: string, value: BitbucketRepoRef | null): void { - repoRefCache.set(cacheKey, value) - while (repoRefCache.size > REPO_REF_CACHE_MAX_ENTRIES) { - const oldestKey = repoRefCache.keys().next().value - if (oldestKey === undefined) { - return - } - repoRefCache.delete(oldestKey) - } + return repoRefProbeCache.size() } function decodeSegment(value: string): string { @@ -86,34 +73,7 @@ export async function getBitbucketRepoRefForRemote( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { - const runtimeKey = connectionId ?? `local:${localGitOptions.wslDistro ?? 'host'}` - const cacheKey = `${runtimeKey}\0${repoPath}\0${remoteName}` - if (repoRefCache.has(cacheKey)) { - return repoRefCache.get(cacheKey)! - } - try { - const sshGitProvider = connectionId ? getSshGitProvider(connectionId) : null - if (connectionId && !sshGitProvider) { - return null - } - const { stdout } = sshGitProvider - ? await sshGitProvider.exec(['remote', 'get-url', remoteName], repoPath) - : await gitExecFileAsync(['remote', 'get-url', remoteName], { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }) - const result = parseBitbucketRepoRef(stdout) - rememberRepoRefCacheEntry(cacheKey, result) - return result - } catch { - if (connectionId) { - // Why: SSH provider failures are often transient reconnect/tunnel states; - // caching them as "not Bitbucket" would poison the repo for the session. - return null - } - rememberRepoRefCacheEntry(cacheKey, null) - return null - } + return repoRefProbeCache.get(repoPath, remoteName, connectionId, localGitOptions) } export async function getBitbucketRepoRef( diff --git a/src/main/git/coalesced-probe.test.ts b/src/main/git/coalesced-probe.test.ts new file mode 100644 index 000000000..2b1eb3e73 --- /dev/null +++ b/src/main/git/coalesced-probe.test.ts @@ -0,0 +1,74 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { runCoalescedProbe, type CoalescedProbes } from './coalesced-probe' + +function deferred(): { + promise: Promise + resolve: (value: T) => void + reject: (error: unknown) => void +} { + let resolve: (value: T) => void = () => {} + let reject: (error: unknown) => void = () => {} + const promise = new Promise((settle, fail) => { + resolve = settle + reject = fail + }) + return { promise, resolve, reject } +} + +describe('runCoalescedProbe', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_000_000) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('replaces a stale probe without letting the older cleanup remove its successor', async () => { + const probes: CoalescedProbes = new Map() + const first = deferred() + const second = deferred() + const createProbe = vi + .fn<() => Promise>() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + + const firstRequest = runCoalescedProbe(probes, 'repo', createProbe, 60_000) + vi.setSystemTime(1_060_001) + const secondRequest = runCoalescedProbe(probes, 'repo', createProbe, 60_000) + + expect(createProbe).toHaveBeenCalledTimes(2) + first.resolve('old') + await expect(firstRequest).resolves.toBe('old') + + const joinedRequest = runCoalescedProbe(probes, 'repo', createProbe, 60_000) + expect(createProbe).toHaveBeenCalledTimes(2) + + second.resolve('new') + await expect(secondRequest).resolves.toBe('new') + await expect(joinedRequest).resolves.toBe('new') + expect(probes).toEqual(new Map()) + }) + + it('removes a settled probe only when it still owns the key', async () => { + const probes: CoalescedProbes = new Map() + const first = deferred() + const second = deferred() + const createProbe = vi + .fn<() => Promise>() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + + const firstRequest = runCoalescedProbe(probes, 'repo', createProbe, 1) + vi.advanceTimersByTime(2) + const secondRequest = runCoalescedProbe(probes, 'repo', createProbe, 1) + + first.reject(new Error('old probe failed')) + await expect(firstRequest).rejects.toThrow('old probe failed') + expect(probes.get('repo')?.promise).toBe(second.promise) + + second.resolve('new') + await expect(secondRequest).resolves.toBe('new') + }) +}) diff --git a/src/main/git/coalesced-probe.ts b/src/main/git/coalesced-probe.ts new file mode 100644 index 000000000..57bc70513 --- /dev/null +++ b/src/main/git/coalesced-probe.ts @@ -0,0 +1,41 @@ +/** + * Coalescing for repeated host probes (P1-D). + * + * Why: the in-flight maps under the hosted-review funnel only drop a probe when + * it settles, so one that never does pins every later retry for the life of the + * process — the outer deadline then unpins the UI without restoring any lookup + * progress. Joining a probe only while it is young enough to still be making + * progress is what lets a host recover in-session. + */ + +export type CoalescedProbe = { startedAt: number; promise: Promise } +export type CoalescedProbes = Map> + +/** Every step under a probe is bounded well inside this, so an older one is wedged, not slow. */ +export const PROBE_COALESCE_STALE_MS = 60_000 + +export async function runCoalescedProbe( + probes: CoalescedProbes, + key: string, + createProbe: () => Promise, + staleAfterMs: number = PROBE_COALESCE_STALE_MS +): Promise { + const now = Date.now() + const existing = probes.get(key) + if (existing && now - existing.startedAt < staleAfterMs) { + return existing.promise + } + if (existing) { + // The abandoned probe keeps running; nothing here will await it again. + void existing.promise.catch(() => {}) + } + const entry: CoalescedProbe = { startedAt: now, promise: createProbe() } + probes.set(key, entry) + try { + return await entry.promise + } finally { + if (probes.get(key) === entry) { + probes.delete(key) + } + } +} diff --git a/src/main/git/remote-ref-probe-cache.ts b/src/main/git/remote-ref-probe-cache.ts new file mode 100644 index 000000000..166e511ed --- /dev/null +++ b/src/main/git/remote-ref-probe-cache.ts @@ -0,0 +1,82 @@ +import { isTransientGitProbeError, readRemoteUrl } from './remote-url-probe' + +/** + * The "is this repo mine?" probe every forge integration runs: read the remote's + * URL once per repo/runtime, cache what the provider's parser made of it, and + * never cache an answer a failed probe never gave. + */ + +const REPO_REF_CACHE_MAX_ENTRIES = 512 + +export type RemoteRefLocalGitOptions = { + wslDistro?: string +} + +export type RemoteRefProbeCache = { + get( + repoPath: string, + remoteName: string, + connectionId?: string | null, + localGitOptions?: RemoteRefLocalGitOptions + ): Promise + clear(): void + size(): number +} + +export function createRemoteRefProbeCache( + parseRemoteUrl: (remoteUrl: string) => Ref | null +): RemoteRefProbeCache { + const repoRefCache = new Map() + + function remember(cacheKey: string, value: Ref | null): void { + repoRefCache.set(cacheKey, value) + while (repoRefCache.size > REPO_REF_CACHE_MAX_ENTRIES) { + const oldestKey = repoRefCache.keys().next().value + if (oldestKey === undefined) { + return + } + repoRefCache.delete(oldestKey) + } + } + + return { + async get(repoPath, remoteName, connectionId, localGitOptions = {}) { + const runtimeKey = connectionId ?? `local:${localGitOptions.wslDistro ?? 'host'}` + const cacheKey = `${runtimeKey}\0${repoPath}\0${remoteName}` + if (repoRefCache.has(cacheKey)) { + return repoRefCache.get(cacheKey)! + } + try { + const stdout = await readRemoteUrl( + { + repoPath, + connectionId, + ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) + }, + remoteName + ) + if (stdout === null) { + return null + } + const result = parseRemoteUrl(stdout) + remember(cacheKey, result) + return result + } catch (error) { + if (connectionId || isTransientGitProbeError(error)) { + // Why: SSH provider failures are often transient reconnect/tunnel states, + // and a probe killed on its deadline says nothing about the remote either; + // caching them as "not this provider" would poison the repo for the session. + return null + } + remember(cacheKey, null) + return null + } + }, + clear() { + repoRefCache.clear() + }, + size() { + return repoRefCache.size + } + } +} diff --git a/src/main/git/remote-url-probe.test.ts b/src/main/git/remote-url-probe.test.ts new file mode 100644 index 000000000..a2bd0c8f5 --- /dev/null +++ b/src/main/git/remote-url-probe.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { getSshGitProviderMock, gitExecFileAsyncMock } = vi.hoisted(() => ({ + getSshGitProviderMock: vi.fn(), + gitExecFileAsyncMock: vi.fn() +})) + +vi.mock('../providers/ssh-git-dispatch', () => ({ + getSshGitProvider: getSshGitProviderMock, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE: 'SSH Git provider unavailable' +})) + +vi.mock('./runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) + +import { + assertRemoteUrlReadable, + isTransientGitProbeError, + readRemoteUrl, + REMOTE_URL_PROBE_TIMEOUT_MS +} from './remote-url-probe' + +describe('remote URL probe', () => { + beforeEach(() => { + getSshGitProviderMock.mockReset() + gitExecFileAsyncMock.mockReset() + }) + + it('bounds local and WSL remote reads with the shared timeout', async () => { + gitExecFileAsyncMock.mockResolvedValue({ stdout: 'git@github.com:acme/orca.git\n' }) + + await expect( + readRemoteUrl({ repoPath: '/repo', wslDistro: 'Ubuntu' }, 'upstream') + ).resolves.toContain('github.com') + + expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS, + wslDistro: 'Ubuntu' + }) + + await expect(readRemoteUrl({ repoPath: '/repo' }, 'origin')).resolves.toContain('github.com') + + expect(gitExecFileAsyncMock).toHaveBeenLastCalledWith(['remote', 'get-url', 'origin'], { + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS + }) + expect(REMOTE_URL_PROBE_TIMEOUT_MS).toBe(30_000) + }) + + it('rethrows a timed-out local probe so callers can report unavailable', async () => { + const timeout = new Error('git timed out.') + gitExecFileAsyncMock.mockRejectedValue(timeout) + + expect(isTransientGitProbeError(timeout)).toBe(true) + await expect(assertRemoteUrlReadable({ repoPath: '/repo' })).rejects.toBe(timeout) + }) + + it('accepts a stable missing remote as a readable, empty repository state', async () => { + gitExecFileAsyncMock.mockRejectedValue(new Error("fatal: No such remote 'origin'")) + + await expect(assertRemoteUrlReadable({ repoPath: '/repo' })).resolves.toBeUndefined() + }) + + it('does not turn a missing SSH provider into a false readable result', async () => { + getSshGitProviderMock.mockReturnValue(null) + + await expect( + assertRemoteUrlReadable({ repoPath: '/repo', connectionId: 'ssh-1' }) + ).rejects.toThrow('SSH Git provider unavailable') + }) +}) diff --git a/src/main/git/remote-url-probe.ts b/src/main/git/remote-url-probe.ts new file mode 100644 index 000000000..4615e74e4 --- /dev/null +++ b/src/main/git/remote-url-probe.ts @@ -0,0 +1,101 @@ +import { + getSshGitProvider, + SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE +} from '../providers/ssh-git-dispatch' +import { gitExecFileAsync } from './runner' + +/** + * The `git remote get-url` probe every forge integration runs to decide whether + * a repo is theirs (P1-D). + * + * Why: it is a local config read, so the only way it outlasts this bound is a + * wedged host — a dead network mount or stalled WSL interop. Unbounded, the call + * never returns and every caller above it hangs with it. Passing a timeout is + * also what arms the runner's kill path; Node's own waits forever on a child + * that ignores signals. The SSH branch is bounded by the relay mux's own 30s + * request timeout. + */ +export const REMOTE_URL_PROBE_TIMEOUT_MS = 30_000 + +export type RemoteUrlProbeContext = { + repoPath: string + connectionId?: string | null + wslDistro?: string +} + +/** Reads a remote URL, or null when the repo's SSH runtime is not connected. */ +export async function readRemoteUrl( + context: RemoteUrlProbeContext, + remoteName: string +): Promise { + if (context.connectionId) { + const provider = getSshGitProvider(context.connectionId) + if (!provider) { + return null + } + const { stdout } = await provider.exec(['remote', 'get-url', remoteName], context.repoPath) + return stdout + } + const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], { + cwd: context.repoPath, + timeout: REMOTE_URL_PROBE_TIMEOUT_MS, + ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) + }) + return stdout +} + +const TRANSIENT_PROBE_PATTERNS = [ + /\btimed out\b/i, + /\bETIMEDOUT\b/, + /\bECONNRESET\b/, + /\bEPIPE\b/, + /connection (?:dropped|closed|refused|reset)/i +] + +/** + * A probe that was killed on its deadline, or died with its transport, says + * nothing about the remote. Callers must neither cache it as an answer nor + * report it as "no review": it is an unavailable result, not a negative one. + */ +export function isTransientGitProbeError(error: unknown): boolean { + const parts: string[] = [] + if (error instanceof Error) { + parts.push(error.message) + } + if (typeof error === 'object' && error !== null) { + const execLike = error as { stderr?: unknown; code?: unknown } + if (typeof execLike.stderr === 'string') { + parts.push(execLike.stderr) + } + if (typeof execLike.code === 'string') { + parts.push(execLike.code) + } + } + if (parts.length === 0) { + parts.push(String(error)) + } + const text = parts.join('\n') + return TRANSIENT_PROBE_PATTERNS.some((pattern) => pattern.test(text)) +} + +/** + * Throws when the remote could not be read because the probe was wedged or its + * transport was gone, and returns normally for every answer — including a repo + * with no remote at all. Lets a caller that treats "nothing found" as a cacheable + * answer tell that apart from a lookup that never got to ask. + */ +export async function assertRemoteUrlReadable( + context: RemoteUrlProbeContext, + remoteName = 'origin' +): Promise { + if (context.connectionId && !getSshGitProvider(context.connectionId)) { + throw new Error(SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE) + } + try { + await readRemoteUrl(context, remoteName) + } catch (error) { + if (isTransientGitProbeError(error)) { + throw error + } + } +} diff --git a/src/main/gitea/repository-ref.test.ts b/src/main/gitea/repository-ref.test.ts index 3964d3fda..7169bd69b 100644 --- a/src/main/gitea/repository-ref.test.ts +++ b/src/main/gitea/repository-ref.test.ts @@ -17,6 +17,7 @@ import { parseGiteaRepoRef } from './repository-ref' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' describe('Gitea repository ref parsing', () => { beforeEach(() => { @@ -121,7 +122,8 @@ describe('Gitea repository ref parsing', () => { }) expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) @@ -151,11 +153,13 @@ describe('Gitea repository ref parsing', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], { cwd: '/repo', - wslDistro: 'Ubuntu' + wslDistro: 'Ubuntu', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) diff --git a/src/main/gitea/repository-ref.ts b/src/main/gitea/repository-ref.ts index f5a9acc8e..ea12698f0 100644 --- a/src/main/gitea/repository-ref.ts +++ b/src/main/gitea/repository-ref.ts @@ -1,5 +1,4 @@ -import { gitExecFileAsync } from '../git/runner' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import { createRemoteRefProbeCache } from '../git/remote-ref-probe-cache' export type GiteaRepoRef = { host: string @@ -20,28 +19,16 @@ const KNOWN_NON_GITEA_HOSTS = new Set([ 'dev.azure.com', 'ssh.dev.azure.com' ]) -const REPO_REF_CACHE_MAX_ENTRIES = 512 -const repoRefCache = new Map() +const repoRefProbeCache = createRemoteRefProbeCache(parseGiteaRepoRef) /** @internal - exposed for tests only */ export function _resetGiteaRepoRefCache(): void { - repoRefCache.clear() + repoRefProbeCache.clear() } /** @internal - exposed for tests only */ export function _getGiteaRepoRefCacheSize(): number { - return repoRefCache.size -} - -function rememberRepoRefCacheEntry(cacheKey: string, value: GiteaRepoRef | null): void { - repoRefCache.set(cacheKey, value) - while (repoRefCache.size > REPO_REF_CACHE_MAX_ENTRIES) { - const oldestKey = repoRefCache.keys().next().value - if (oldestKey === undefined) { - return - } - repoRefCache.delete(oldestKey) - } + return repoRefProbeCache.size() } function decodeSegment(value: string): string { @@ -147,34 +134,7 @@ export async function getGiteaRepoRefForRemote( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { - const runtimeKey = connectionId ?? `local:${localGitOptions.wslDistro ?? 'host'}` - const cacheKey = `${runtimeKey}\0${repoPath}\0${remoteName}` - if (repoRefCache.has(cacheKey)) { - return repoRefCache.get(cacheKey)! - } - try { - const sshGitProvider = connectionId ? getSshGitProvider(connectionId) : null - if (connectionId && !sshGitProvider) { - return null - } - const { stdout } = sshGitProvider - ? await sshGitProvider.exec(['remote', 'get-url', remoteName], repoPath) - : await gitExecFileAsync(['remote', 'get-url', remoteName], { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }) - const result = parseGiteaRepoRef(stdout) - rememberRepoRefCacheEntry(cacheKey, result) - return result - } catch { - if (connectionId) { - // Why: SSH provider failures are often transient reconnect/tunnel states; - // caching them as "not Gitea" would poison the repo for the session. - return null - } - rememberRepoRefCacheEntry(cacheKey, null) - return null - } + return repoRefProbeCache.get(repoPath, remoteName, connectionId, localGitOptions) } export async function getGiteaRepoRef( diff --git a/src/main/github/gh-utils.test.ts b/src/main/github/gh-utils.test.ts index ae7b6c414..9c4461e5e 100644 --- a/src/main/github/gh-utils.test.ts +++ b/src/main/github/gh-utils.test.ts @@ -102,7 +102,8 @@ describe('github owner/repo resolution', () => { await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) }) @@ -115,7 +116,8 @@ describe('github owner/repo resolution', () => { await expect(getOwnerRepo('/repo')).resolves.toEqual({ owner: 'acme', repo: 'widgets' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) }) @@ -126,7 +128,8 @@ describe('github owner/repo resolution', () => { await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'stablyai', repo: 'orca' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) }) @@ -137,10 +140,12 @@ describe('github owner/repo resolution', () => { await expect(getIssueOwnerRepo('/repo')).resolves.toEqual({ owner: 'fork', repo: 'orca' }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) }) @@ -176,7 +181,8 @@ describe('github owner/repo resolution', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) await expect(getOwnerRepoForRemote('/repo', 'upstream')).resolves.toBeNull() @@ -245,10 +251,12 @@ describe('github owner/repo resolution', () => { // 2 runtimes x (1 upstream miss + 1 origin hit); repeat WSL call is cached. expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(4) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { cwd: '/repo', + timeout: 30_000, wslDistro: 'Ubuntu' }) }) @@ -750,7 +758,8 @@ describe('resolveIssueSource', () => { }) expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: 30_000 }) }) diff --git a/src/main/github/github-repository-identity.ts b/src/main/github/github-repository-identity.ts index f66b3dbe0..0490b19c5 100644 --- a/src/main/github/github-repository-identity.ts +++ b/src/main/github/github-repository-identity.ts @@ -1,6 +1,7 @@ -import { gitExecFileAsync } from '../git/runner' +import { runCoalescedProbe, type CoalescedProbes } from '../git/coalesced-probe' +import { readRemoteUrl } from '../git/remote-url-probe' import type { GitHubOwnerRepo } from '../../shared/types' -import { getSshGitProvider, getSshGitProviderGeneration } from '../providers/ssh-git-dispatch' +import { getSshGitProviderGeneration } from '../providers/ssh-git-dispatch' import { readLocalGitConfigSignature } from './local-git-config-signature' import { parseGitHubOwnerRepo, @@ -61,7 +62,7 @@ type OwnerRepoCacheEntry = { } const ownerRepoCache = new Map() -const ownerRepoInFlight = new Map>() +const ownerRepoInFlight: CoalescedProbes = new Map() /** @internal - exposed for tests only */ export function _resetOwnerRepoCache(): void { @@ -93,19 +94,7 @@ export async function getRemoteUrlForRepo( context: GitHubRepoContext, remoteName: string ): Promise { - if (context.connectionId) { - const provider = getSshGitProvider(context.connectionId) - if (!provider) { - return null - } - const { stdout } = await provider.exec(['remote', 'get-url', remoteName], context.repoPath) - return stdout - } - const { stdout } = await gitExecFileAsync(['remote', 'get-url', remoteName], { - cwd: context.repoPath, - ...(context.wslDistro ? { wslDistro: context.wslDistro } : {}) - }) - return stdout + return readRemoteUrl(context, remoteName) } function getOwnerRepoCacheTtl(value: OwnerRepo | null, configSignature?: string): number { @@ -152,22 +141,13 @@ export async function getOwnerRepoForRemote( return refreshedCached.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. - const probe = resolveOwnerRepoForRemote(context, remoteName, cacheKey, nextConfigSignature) - ownerRepoInFlight.set(cacheKey, probe) - try { - return await probe - } finally { - if (ownerRepoInFlight.get(cacheKey) === probe) { - ownerRepoInFlight.delete(cacheKey) - } - } + // for the same repo concurrently. Coalesce missing-remote probes — but only + // onto one young enough to still answer, so a wedged probe cannot pin the + // repo's identity for the life of the process (P1-D). + return runCoalescedProbe(ownerRepoInFlight, cacheKey, () => + resolveOwnerRepoForRemote(context, remoteName, cacheKey, nextConfigSignature) + ) } async function resolveOwnerRepoForRemote( diff --git a/src/main/github/local-git-config-signature.ts b/src/main/github/local-git-config-signature.ts index 1a3c297d5..79c9da1d3 100644 --- a/src/main/github/local-git-config-signature.ts +++ b/src/main/github/local-git-config-signature.ts @@ -1,6 +1,7 @@ import { readFile, stat } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, isAbsolute, join, resolve } from 'node:path' +import { runCoalescedProbe, type CoalescedProbes } from '../git/coalesced-probe' import type { GitHubRepoContext } from './github-repository-identity' type LocalGitConfigPaths = { @@ -8,7 +9,15 @@ type LocalGitConfigPaths = { worktreeConfigPath: string } -const localGitConfigSignatureInFlight = new Map>() +/** + * Why: `stat` on a dead network mount is uninterruptible, and this read runs + * *before* the bounded remote probe — unbounded, it reintroduces the hang that + * probe timeout removes (P1-D). Abandoning the read only costs the shorter + * negative-cache TTL that a missing signature already implies. + */ +const CONFIG_SIGNATURE_DEADLINE_MS = 2_000 + +const localGitConfigSignatureInFlight: CoalescedProbes = new Map() export async function readLocalGitConfigSignature( context: GitHubRepoContext @@ -18,21 +27,37 @@ export async function readLocalGitConfigSignature( // runtimes are already separated by cache key and probed through git. return undefined } - const cacheKey = context.repoPath - const inFlight = localGitConfigSignatureInFlight.get(cacheKey) - if (inFlight) { - return inFlight - } + // Why: the deadline is caller-facing only. Bounding the coalesced probe itself + // would drop its map entry after 2s while the read runs on, so every later + // call would start another unbounded read instead of joining the one already + // out — the coalescing that keeps a wedged mount to one read (P1-D). + return withConfigSignatureDeadline( + runCoalescedProbe(localGitConfigSignatureInFlight, context.repoPath, () => + readUncachedLocalGitConfigSignature(context.repoPath) + ) + ) +} - const read = readUncachedLocalGitConfigSignature(context.repoPath) - localGitConfigSignatureInFlight.set(cacheKey, read) - try { - return await read - } finally { - if (localGitConfigSignatureInFlight.get(cacheKey) === read) { - localGitConfigSignatureInFlight.delete(cacheKey) +/** Resolves undefined rather than waiting on a read the filesystem may never finish. */ +function withConfigSignatureDeadline( + read: Promise +): Promise { + return new Promise((settle) => { + const timer = setTimeout(() => settle(undefined), CONFIG_SIGNATURE_DEADLINE_MS) + if (typeof timer === 'object' && 'unref' in timer) { + timer.unref() } - } + void read.then( + (signature) => { + clearTimeout(timer) + settle(signature) + }, + () => { + clearTimeout(timer) + settle(undefined) + } + ) + }) } export function __resetLocalGitConfigSignatureCacheForTests(): void { diff --git a/src/main/gitlab/gitlab-known-host-probe.ts b/src/main/gitlab/gitlab-known-host-probe.ts index 5699030a4..cc4ecf5fa 100644 --- a/src/main/gitlab/gitlab-known-host-probe.ts +++ b/src/main/gitlab/gitlab-known-host-probe.ts @@ -1,3 +1,4 @@ +import { runCoalescedProbe, type CoalescedProbes } from '../git/coalesced-probe' import { glabExecFileAsync } from '../git/runner' import { getSshGitProviderGeneration } from '../providers/ssh-git-dispatch' import { DEFAULT_GITLAB_HOSTS, normalizeGitLabHost } from './project-ref-parser' @@ -8,7 +9,7 @@ export type LocalGitExecOptions = { const GLAB_KNOWN_HOSTS_TIMEOUT_MS = 10_000 const knownHostsCacheByExecutionContext = new Map() -const knownHostsInFlightByExecutionContext = new Map>() +const knownHostsInFlightByExecutionContext: CoalescedProbes = new Map() function knownHostsExecutionKey( connectionId?: string | null, @@ -67,19 +68,11 @@ export async function getGlabKnownHosts( if (cached) { return cached } - const inFlight = knownHostsInFlightByExecutionContext.get(key) - if (inFlight) { - return inFlight - } - const probe = probeGlabKnownHosts(key, connectionId, localGitOptions) - knownHostsInFlightByExecutionContext.set(key, probe) - try { - return await probe - } finally { - if (knownHostsInFlightByExecutionContext.get(key) === probe) { - knownHostsInFlightByExecutionContext.delete(key) - } - } + // Why: only join a probe still young enough to answer, so a wedged one cannot + // pin every later retry for the life of the process (P1-D). + return runCoalescedProbe(knownHostsInFlightByExecutionContext, key, () => + probeGlabKnownHosts(key, connectionId, localGitOptions) + ) } async function probeGlabKnownHosts( diff --git a/src/main/gitlab/gitlab-project-ref-resolution.ts b/src/main/gitlab/gitlab-project-ref-resolution.ts index 218a41869..4b33a4c43 100644 --- a/src/main/gitlab/gitlab-project-ref-resolution.ts +++ b/src/main/gitlab/gitlab-project-ref-resolution.ts @@ -1,6 +1,6 @@ -import { gitExecFileAsync, glabExecFileAsync } from '../git/runner' +import { glabExecFileAsync } from '../git/runner' +import { isTransientGitProbeError, readRemoteUrl } from '../git/remote-url-probe' import type { IssueSourcePreference } from '../../shared/types' -import { getSshGitProvider } from '../providers/ssh-git-dispatch' import { clearProjectRefInFlight, runProjectRefProbeOnce } from './project-ref-inflight' import { parseGlabAuthStatusHosts, @@ -83,16 +83,17 @@ async function resolveProjectRefForRemote( localGitOptions: LocalGitExecOptions ): Promise { try { - const sshGitProvider = connectionId ? getSshGitProvider(connectionId) : null - if (connectionId && !sshGitProvider) { + const stdout = await readRemoteUrl( + { + repoPath, + connectionId, + ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) + }, + remoteName + ) + if (stdout === null) { return null } - const { stdout } = sshGitProvider - ? await sshGitProvider.exec(['remote', 'get-url', remoteName], repoPath) - : await gitExecFileAsync(['remote', 'get-url', remoteName], { - cwd: repoPath, - ...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}) - }) const result = parseGitLabProjectRef(stdout, knownHosts) if (result) { rememberProjectRefCacheEntry(cacheKey, result) @@ -112,8 +113,10 @@ async function resolveProjectRefForRemote( rememberProjectRefCacheEntry(cacheKey, remoteCandidate) return remoteCandidate } - } catch { - if (connectionId) { + } catch (error) { + // Why: a wedged or killed probe is not evidence the remote is not GitLab — + // caching it would misdetect the forge for the life of the process (P1-D). + if (connectionId || isTransientGitProbeError(error)) { return null } } diff --git a/src/main/gitlab/gl-utils.test.ts b/src/main/gitlab/gl-utils.test.ts index 21f483ca0..1e1e3d0cc 100644 --- a/src/main/gitlab/gl-utils.test.ts +++ b/src/main/gitlab/gl-utils.test.ts @@ -27,6 +27,7 @@ import { } from './gl-utils' import { rememberGlabKnownHost, rememberGlabKnownHosts } from './gitlab-known-host-probe' import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch' +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' describe('gitlab project ref resolution', () => { beforeEach(() => { @@ -50,7 +51,8 @@ describe('gitlab project ref resolution', () => { path: 'fork/orca' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) @@ -64,7 +66,8 @@ describe('gitlab project ref resolution', () => { path: 'stablyai/orca' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) @@ -118,11 +121,13 @@ describe('gitlab project ref resolution', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote', 'get-url', 'origin'], { cwd: '/repo', - wslDistro: 'Ubuntu' + wslDistro: 'Ubuntu', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) @@ -143,7 +148,8 @@ describe('gitlab project ref resolution', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'upstream'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) await expect(getProjectRefForRemote('/repo', 'upstream')).resolves.toBeNull() @@ -255,7 +261,8 @@ describe('resolveIssueSource', () => { }) expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) }) diff --git a/src/main/gitlab/project-ref-inflight.ts b/src/main/gitlab/project-ref-inflight.ts index 8df88f63a..a9de9d757 100644 --- a/src/main/gitlab/project-ref-inflight.ts +++ b/src/main/gitlab/project-ref-inflight.ts @@ -1,6 +1,7 @@ +import { runCoalescedProbe, type CoalescedProbes } from '../git/coalesced-probe' import type { ProjectRef } from './gl-utils' -const projectRefInFlight = new Map>() +const projectRefInFlight: CoalescedProbes = new Map() export function clearProjectRefInFlight(): void { projectRefInFlight.clear() @@ -10,17 +11,7 @@ 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) - } - } + // Why: joining only a probe that is still young keeps a wedged host's dead + // promise from pinning every later retry for the process lifetime (P1-D). + return runCoalescedProbe(projectRefInFlight, cacheKey, createProbe) } diff --git a/src/main/source-control/hosted-review-active-branch-claims.ts b/src/main/source-control/hosted-review-active-branch-claims.ts new file mode 100644 index 000000000..ffcff78ac --- /dev/null +++ b/src/main/source-control/hosted-review-active-branch-claims.ts @@ -0,0 +1,45 @@ +import { ACTIVE_CLAIM_TTL_MS, MAX_ACTIVE_BRANCHES } from './hosted-review-refresh-pacing' + +/** + * The branches callers report as their current selection (#11532). + * + * Split from the answer cache because it is a different question: not "what is + * this branch's review" but "is anyone looking at it", which is what buys the + * per-minute tier. + */ +const activeClaims = new Map() + +/** + * Records the caller's current selection, reporting whether the branch was not + * already active. Claims are least-recently-used so the fast tier stays bounded + * no matter how many a client asserts. + */ +export function noteActiveClaim(key: string): boolean { + const now = Date.now() + for (const [candidate, claimedAt] of activeClaims) { + if (now - claimedAt > ACTIVE_CLAIM_TTL_MS) { + activeClaims.delete(candidate) + } + } + const wasActive = activeClaims.has(key) + activeClaims.delete(key) + activeClaims.set(key, now) + while (activeClaims.size > MAX_ACTIVE_BRANCHES) { + const oldest = activeClaims.keys().next().value + if (oldest === undefined) { + break + } + activeClaims.delete(oldest) + } + return !wasActive +} + +export function isActiveBranch(key: string): boolean { + const claimedAt = activeClaims.get(key) + return claimedAt !== undefined && Date.now() - claimedAt <= ACTIVE_CLAIM_TTL_MS +} + +/** @internal - exposed for tests only */ +export function __resetHostedReviewActiveClaimsForTests(): void { + activeClaims.clear() +} diff --git a/src/main/source-control/hosted-review-bitbucket.integration.test.ts b/src/main/source-control/hosted-review-bitbucket.integration.test.ts index 603ec231a..588d37d6b 100644 --- a/src/main/source-control/hosted-review-bitbucket.integration.test.ts +++ b/src/main/source-control/hosted-review-bitbucket.integration.test.ts @@ -4,9 +4,10 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { _resetBitbucketRepoRefCache } from '../bitbucket/repository-ref' import { getHostedReviewForBranch } from './hosted-review' +import { __resetHostedReviewBranchCacheForTests } from './hosted-review-branch-cache' const execFileAsync = promisify(execFile) const OLD_ENV = process.env @@ -28,11 +29,14 @@ describe('Bitbucket hosted review integration', () => { delete process.env.ORCA_BITBUCKET_EMAIL delete process.env.ORCA_BITBUCKET_API_TOKEN _resetBitbucketRepoRefCache() + __resetHostedReviewBranchCacheForTests() }) afterEach(() => { + vi.useRealTimers() process.env = OLD_ENV _resetBitbucketRepoRefCache() + __resetHostedReviewBranchCacheForTests() }) it('resolves a Bitbucket PR through real git remote parsing and HTTP API calls', async () => { @@ -118,4 +122,80 @@ describe('Bitbucket hosted review integration', () => { }) } }) + + it('does not cache a transient API failure as a definitive no-review result', async () => { + vi.useFakeTimers({ now: Date.now() }) + let pullRequestCalls = 0 + let buildStatusCalls = 0 + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) + if (url.pathname === '/2.0/repositories/team/repo/pullrequests') { + pullRequestCalls += 1 + if (pullRequestCalls === 1) { + res.writeHead(503, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ message: 'temporary outage' })) + return + } + sendJson(res, { + values: [ + { + id: 13, + title: 'Recovered Bitbucket branch', + state: 'OPEN', + updated_on: '2026-05-15T00:00:00Z', + links: { html: { href: 'https://bitbucket.org/team/repo/pull-requests/13' } }, + source: { branch: { name: 'feature/recovery' }, commit: { hash: 'def456' } } + } + ] + }) + return + } + + if (url.pathname === '/2.0/repositories/team/repo/commit/def456/statuses/build') { + buildStatusCalls += 1 + sendJson(res, { values: [{ state: 'SUCCESSFUL' }] }) + return + } + + res.writeHead(404, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ message: 'not found' })) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + + const repoPath = await mkdtemp(join(tmpdir(), 'orca-bitbucket-review-recovery-')) + try { + const address = server.address() + if (!address || typeof address === 'string') { + throw new Error('expected TCP server address') + } + + process.env.ORCA_BITBUCKET_API_BASE_URL = `http://127.0.0.1:${address.port}/2.0` + await execFileAsync('git', ['init'], { cwd: repoPath }) + await execFileAsync('git', ['remote', 'add', 'origin', 'git@bitbucket.org:team/repo.git'], { + cwd: repoPath + }) + + await expect( + getHostedReviewForBranch({ repoPath, branch: 'refs/heads/feature/recovery' }) + ).rejects.toThrow('HTTP 503') + + vi.advanceTimersByTime(60_001) + await expect( + getHostedReviewForBranch({ repoPath, branch: 'refs/heads/feature/recovery' }) + ).resolves.toMatchObject({ + provider: 'bitbucket', + number: 13, + title: 'Recovered Bitbucket branch', + state: 'open' + }) + expect(pullRequestCalls).toBe(2) + // The failed lookup never reaches build status, so the recovery owns this call. + expect(buildStatusCalls).toBe(1) + } finally { + await rm(repoPath, { recursive: true, force: true }) + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }) + } + }) }) diff --git a/src/main/source-control/hosted-review-branch-cache.test.ts b/src/main/source-control/hosted-review-branch-cache.test.ts index 80d9220aa..17c69038d 100644 --- a/src/main/source-control/hosted-review-branch-cache.test.ts +++ b/src/main/source-control/hosted-review-branch-cache.test.ts @@ -5,8 +5,57 @@ import { invalidateHostedReviewBranchCache, withHostedReviewBranchCache } from './hosted-review-branch-cache' +import { + HOSTED_REVIEW_LOOKUP_DEADLINE_MS, + LOOKUP_BACKOFF_MAX_MS, + MAX_BRANCH_MAP_ENTRIES, + MAX_INFLIGHT_LOOKUPS, + MAX_UNSETTLED_LOOKUPS_PER_KEY +} from './hosted-review-refresh-pacing' const identity = { repoPath: '/repo', connectionId: null, branch: 'feature/x' } +const START = 1_000_000 + +/** A lookup that never settles — the wedged provider this file's deadline exists for. */ +function stuckLookup() { + let resolve: (review: HostedReviewInfo | null) => void = () => {} + let reject: (error: unknown) => void = () => {} + const lookup = vi.fn( + () => + new Promise((settle, fail) => { + resolve = settle + reject = fail + }) + ) + return { lookup, resolve: (review) => resolve(review), reject: (error) => reject(error) } +} + +/** + * Runs `evictedLookup` for the shared identity, drops its in-flight record via + * the size cap alone — no deadline, so it is a straggler that never timed out — + * and leaves a fresh lookup owning the key. + */ +function evictInflightRecord(evictedLookup: () => Promise) { + const swallow = (promise: Promise): void => { + void promise.catch(() => {}) + } + swallow(withHostedReviewBranchCache(identity, { headOid: null }, evictedLookup)) + + const filler = stuckLookup() + for (let index = 0; index < MAX_INFLIGHT_LOOKUPS; index += 1) { + swallow( + withHostedReviewBranchCache( + { ...identity, branch: `feature/${index}` }, + { headOid: null }, + filler.lookup + ) + ) + } + + const successor = stuckLookup() + const request = withHostedReviewBranchCache(identity, { headOid: null }, successor.lookup) + return { request, resolve: successor.resolve, reject: successor.reject } +} const openReview: HostedReviewInfo = { provider: 'github', @@ -371,4 +420,423 @@ describe('hosted review branch cache (#11532)', () => { expect(lookup).toHaveBeenCalledTimes(2) }) }) + + describe('in-flight deadline (P1-D)', () => { + it('releases a stuck lookup at the deadline instead of pinning the branch', async () => { + const { lookup } = stuckLookup() + + const request = withHostedReviewBranchCache(identity, { headOid: null }, lookup) + const rejects = expect(request).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + // The dead lookup is no longer joinable, so the branch can recover in + // session rather than staying pinned for the life of the process. + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, lookup) + ).rejects.toThrow(/backing off/) + expect(lookup).toHaveBeenCalledTimes(1) + }) + + it('lets a later poll succeed after a lookup times out', async () => { + const { lookup } = stuckLookup() + + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + await vi.advanceTimersByTimeAsync(60_001) + const recovered = vi.fn(async () => openReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, recovered) + ).resolves.toEqual(openReview) + expect(recovered).toHaveBeenCalledTimes(1) + }) + + it('keeps the last known review when a refresh times out', async () => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + vi.setSystemTime(START + 60_001) + + const { lookup } = stuckLookup() + const request = withHostedReviewBranchCache(identity, { headOid: null }, lookup) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + + // A wedged refresh must not blank the card any more than a failing one does. + await expect(request).resolves.toEqual(openReview) + }) + + it('adopts a lookup that lands after its deadline', async () => { + const { lookup, resolve } = stuckLookup() + + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + resolve(openReview) + await vi.advanceTimersByTimeAsync(0) + + // The detached call still cost the quota, so its answer is worth keeping: + // a slow-but-alive host converges instead of failing on every poll. + const next = vi.fn(async () => null) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + openReview + ) + expect(next).not.toHaveBeenCalled() + }) + + it('keeps escalating when a lookup only ever answers past its deadline', async () => { + const first = stuckLookup() + const firstRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await firstRejects + + // A second timeout doubles the window to 120s, so the backoff outlives the + // found-review TTL — that is what makes the escalation observable. + await vi.advanceTimersByTimeAsync(60_001) + const second = stuckLookup() + const secondRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await secondRejects + + second.resolve(openReview) + await vi.advanceTimersByTimeAsync(0) + + // The answer is still adopted — the call cost the quota either way — but a + // host that only ever answers after the deadline is not healthy, so it must + // not restart its escalation and be re-asked at the base window forever. + await vi.advanceTimersByTimeAsync(60_001) + const recovered = vi.fn(async () => mergedReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, recovered) + ).resolves.toEqual(openReview) + expect(recovered).not.toHaveBeenCalled() + }) + + it('does not let a timed-out null wipe the open review it was refreshing', async () => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + await vi.advanceTimersByTimeAsync(60_001) + + const stale = stuckLookup() + const request = withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await expect(request).resolves.toEqual(openReview) + + stale.resolve(null) + await vi.advanceTimersByTimeAsync(0) + + // The refresh never outranked the answer its own callers were served, so a + // null from a wedged host must not blank the card for a no-review interval. + const next = vi.fn(async () => openReview) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + openReview + ) + expect(next).not.toHaveBeenCalled() + }) + + it('does not let a timed-out null short-circuit the lookup replacing it', async () => { + const stale = stuckLookup() + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + await vi.advanceTimersByTimeAsync(60_001) + const replacement = stuckLookup() + const pending = withHostedReviewBranchCache(identity, { headOid: null }, replacement.lookup) + + stale.resolve(null) + await vi.advanceTimersByTimeAsync(0) + + // A stored null reads as a fresh "no review" for the whole no-review + // interval, so it would answer callers ahead of the running lookup. + const joiner = vi.fn(async () => null) + const joined = withHostedReviewBranchCache(identity, { headOid: null }, joiner) + + replacement.resolve(openReview) + await expect(pending).resolves.toEqual(openReview) + await expect(joined).resolves.toEqual(openReview) + expect(joiner).not.toHaveBeenCalled() + }) + + it('lets a newer straggler supersede an older one that landed first', async () => { + const first = stuckLookup() + const firstRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await firstRejects + + await vi.advanceTimersByTimeAsync(60_001) + const second = stuckLookup() + const secondRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await secondRejects + + // The older attempt answers first, so landing order says nothing about which + // answer is current — only which lookup started later does. + first.resolve(null) + await vi.advanceTimersByTimeAsync(0) + second.resolve(openReview) + await vi.advanceTimersByTimeAsync(0) + + const next = vi.fn(async () => null) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + openReview + ) + expect(next).not.toHaveBeenCalled() + }) + + it('does not let an older straggler overwrite a newer one that landed first', async () => { + const first = stuckLookup() + const firstRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, first.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await firstRejects + + await vi.advanceTimersByTimeAsync(60_001) + const second = stuckLookup() + const secondRejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, second.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await secondRejects + + // Both are detached, so the one that stores last is whichever host unwedged + // last — the answer that has to survive is the one asked most recently. + second.resolve(openReview) + await vi.advanceTimersByTimeAsync(0) + first.resolve(null) + await vi.advanceTimersByTimeAsync(0) + + const next = vi.fn(async () => null) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + openReview + ) + expect(next).not.toHaveBeenCalled() + }) + + it('does not let a straggler overwrite an answer newer than itself', async () => { + const stale = stuckLookup() + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + await vi.advanceTimersByTimeAsync(60_001) + await withHostedReviewBranchCache(identity, { headOid: null }, async () => mergedReview) + + stale.resolve(openReview) + await vi.advanceTimersByTimeAsync(0) + + const next = vi.fn(async () => null) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + mergedReview + ) + expect(next).not.toHaveBeenCalled() + }) + + it('does not let a straggler evict the lookup that replaced it', async () => { + const stale = stuckLookup() + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + + await vi.advanceTimersByTimeAsync(60_001) + const replacement = stuckLookup() + const first = withHostedReviewBranchCache(identity, { headOid: null }, replacement.lookup) + + // The straggler settling must clear its own record, not the replacement's — + // otherwise the next caller starts a duplicate provider call. + stale.reject(new Error('late failure')) + await vi.advanceTimersByTimeAsync(0) + + const second = withHostedReviewBranchCache(identity, { headOid: null }, replacement.lookup) + replacement.resolve(openReview) + + await expect(first).resolves.toEqual(openReview) + await expect(second).resolves.toEqual(openReview) + expect(replacement.lookup).toHaveBeenCalledTimes(1) + }) + + it('releases a caller by wall clock when the deadline timer never fires', async () => { + const { lookup } = stuckLookup() + + const request = withHostedReviewBranchCache(identity, { headOid: null }, lookup) + const rejects = expect(request).rejects.toThrow(/timed out/) + // Why: main-process timers are suspended across a system sleep, so age — + // not setTimeout — is what has to bound the pin. + vi.setSystemTime(START + HOSTED_REVIEW_LOOKUP_DEADLINE_MS + 1) + + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, lookup) + ).rejects.toThrow(/backing off/) + await rejects + expect(lookup).toHaveBeenCalledTimes(1) + }) + + it('bounds the in-flight map independently of the completed cache', async () => { + const { lookup } = stuckLookup() + const branchAt = (index: number) => ({ ...identity, branch: `feature/${index}` }) + const swallow = (promise: Promise): void => { + void promise.catch(() => {}) + } + + for (let index = 0; index <= MAX_INFLIGHT_LOOKUPS; index += 1) { + swallow(withHostedReviewBranchCache(branchAt(index), { headOid: null }, lookup)) + } + expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 1) + + // The oldest stuck record was evicted, so its branch is no longer joinable. + swallow(withHostedReviewBranchCache(branchAt(0), { headOid: null }, lookup)) + expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 2) + + // The newest is still tracked, so concurrent callers still collapse onto it. + swallow( + withHostedReviewBranchCache(branchAt(MAX_INFLIGHT_LOOKUPS), { headOid: null }, lookup) + ) + expect(lookup).toHaveBeenCalledTimes(MAX_INFLIGHT_LOOKUPS + 2) + }) + + it('does not let a cap-evicted straggler clobber the answer that replaced it', async () => { + const evicted = stuckLookup() + const successor = evictInflightRecord(evicted.lookup) + + // The evicted lookup never timed out, so it is a straggler on the strength + // of the eviction alone — the successor still owns the key. + evicted.resolve(mergedReview) + await vi.advanceTimersByTimeAsync(0) + + // Stored, its stale answer would read as fresh and be served ahead of the + // lookup that actually owns the branch. + const joiner = vi.fn(async () => null) + const joined = withHostedReviewBranchCache(identity, { headOid: null }, joiner) + + successor.resolve(openReview) + await expect(successor.request).resolves.toEqual(openReview) + await expect(joined).resolves.toEqual(openReview) + expect(joiner).not.toHaveBeenCalled() + }) + + it('does not let a cap-evicted straggler double-count its successor failure', async () => { + const evicted = stuckLookup() + const successor = evictInflightRecord(evicted.lookup) + + evicted.reject(new Error('late failure')) + await vi.advanceTimersByTimeAsync(0) + + successor.reject(new Error('successor failure')) + await expect(successor.request).rejects.toThrow('successor failure') + + // One failure is one backoff doubling: the straggler's rejection must not + // stretch the window the live retry is waiting on. + await vi.advanceTimersByTimeAsync(60_001) + const recovered = vi.fn(async () => openReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, recovered) + ).resolves.toEqual(openReview) + expect(recovered).toHaveBeenCalledTimes(1) + }) + + it('stops asking once a branch has stranded its cap of unsettled lookups', async () => { + const wedged = stuckLookup() + for (let attempt = 0; attempt < MAX_UNSETTLED_LOOKUPS_PER_KEY; attempt += 1) { + const rejects = expect( + withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup) + ).rejects.toThrow(/timed out/) + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + await rejects + // Past the longest backoff, so only the detached cap can hold the branch. + await vi.advanceTimersByTimeAsync(LOOKUP_BACKOFF_MAX_MS + 1) + } + expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) + + // Nothing can cancel the stranded calls, so a third would leak another one + // for the life of the process rather than recover anything. + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup) + ).rejects.toThrow(/never answered/) + expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) + + // A settling lookup frees its slot, so a host that recovers is asked again. + wedged.resolve(openReview) + await vi.advanceTimersByTimeAsync(60_001) + const recovered = vi.fn(async () => mergedReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, recovered) + ).resolves.toEqual(mergedReview) + expect(recovered).toHaveBeenCalledTimes(1) + }) + + it('counts a lookup that is still running against the branch cap', async () => { + const swallow = (promise: Promise): void => { + void promise.catch(() => {}) + } + const filler = stuckLookup() + const wedged = stuckLookup() + /** Drops the branch's in-flight record without expiring it, so it runs on untracked. */ + const evictInflightRecords = (round: number): void => { + for (let index = 0; index < MAX_INFLIGHT_LOOKUPS; index += 1) { + swallow( + withHostedReviewBranchCache( + { ...identity, branch: `filler/${round}/${index}` }, + { headOid: null }, + filler.lookup + ) + ) + } + } + + for (let attempt = 0; attempt < MAX_UNSETTLED_LOOKUPS_PER_KEY; attempt += 1) { + swallow(withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup)) + evictInflightRecords(attempt) + } + expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) + + // Neither has reached its deadline, so nothing is counted as detached yet — + // but both are running with nothing able to stop them, and a third would + // strand another provider call the same way. + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, wedged.lookup) + ).rejects.toThrow(/never answered/) + expect(wedged.lookup).toHaveBeenCalledTimes(MAX_UNSETTLED_LOOKUPS_PER_KEY) + }) + + it('does not adopt a straggler whose invalidated scope was evicted', async () => { + const stale = stuckLookup() + const inflight = withHostedReviewBranchCache(identity, { headOid: null }, stale.lookup) + + invalidateHostedReviewBranchCache('/repo', null) + // Fill the generation map so the repo's own generation is evicted: read back + // as zero it would match what this lookup captured before the invalidation. + for (let index = 0; index < MAX_BRANCH_MAP_ENTRIES; index += 1) { + invalidateHostedReviewBranchCache(`/filler/${index}`, null) + } + + stale.resolve(null) + await expect(inflight).resolves.toBeNull() + + // Stored, that "no review" would hide the review Orca had just opened for + // the whole no-review interval. + const next = vi.fn(async () => openReview) + await expect(withHostedReviewBranchCache(identity, { headOid: null }, next)).resolves.toEqual( + openReview + ) + expect(next).toHaveBeenCalledTimes(1) + }) + }) }) diff --git a/src/main/source-control/hosted-review-branch-cache.ts b/src/main/source-control/hosted-review-branch-cache.ts index b1d54774c..b99943bda 100644 --- a/src/main/source-control/hosted-review-branch-cache.ts +++ b/src/main/source-control/hosted-review-branch-cache.ts @@ -1,10 +1,34 @@ import type { HostedReviewInfo } from '../../shared/hosted-review' import { - ACTIVE_CLAIM_TTL_MS, + __resetHostedReviewActiveClaimsForTests, + isActiveBranch, + noteActiveClaim +} from './hosted-review-active-branch-claims' +import { + __resetUnsettledHostedReviewLookupsForTests, + hasLookupCapacity, + noteDetachedLookup, + noteLookupStarted, + settleDetachedLookup, + settleLookup +} from './hosted-review-unsettled-lookups' +import { + __resetHostedReviewScopeGenerationsForTests, + bumpScopeGeneration, + scopeGeneration +} from './hosted-review-scope-generations' +import { + __resetHostedReviewLookupBackoffForTests, + backoffUntil, + clearFailures, + dropFailuresWithPrefix, + noteFailure +} from './hosted-review-lookup-backoff' +import { ACTIVE_REFRESH_INTERVAL_MS, - lookupBackoffDelayMs, - LOOKUP_BACKOFF_MAX_MS, - MAX_ACTIVE_BRANCHES, + HOSTED_REVIEW_LOOKUP_DEADLINE_MS, + MAX_BRANCH_MAP_ENTRIES, + MAX_INFLIGHT_LOOKUPS, NO_REVIEW_REFRESH_INTERVAL_MS } from './hosted-review-refresh-pacing' @@ -24,22 +48,27 @@ import { // Why: a found review still refreshes at the callers' poll cadence; the cache // exists to collapse concurrent clients, not to make review state go stale. const FOUND_REVIEW_TTL_MS = 60_000 -const MAX_ENTRIES = 500 +const MAX_ENTRIES = MAX_BRANCH_MAP_ENTRIES type CacheEntry = { review: HostedReviewInfo | null fetchedAt: number headOid: string | null + /** When the lookup that produced this answer began, for straggler ordering. */ + startedAt: number +} + +type InflightRecord = { + /** Identity, so a detached lookup can only ever clear its own entry. */ + token: object + startedAt: number + promise: Promise + /** Releases the callers and unpins the branch; idempotent. */ + expire: () => void } const entries = new Map() -const inflight = new Map>() -const failureBackoff = new Map() -/** Branches a caller reported as its current selection, least recent first. */ -const activeClaims = new Map() -/** Bumped per repo on invalidation so a lookup that predates it cannot store. */ -const scopeGenerations = new Map() - +const inflight = new Map() // Why: NUL is the one byte a repo path or branch name cannot contain, so a // scope prefix cannot straddle a component boundary — invalidating `/a/b` must // not also flush the unrelated repo at `/a/b c`. @@ -85,36 +114,6 @@ export function hostedReviewBranchCacheKey(identity: HostedReviewBranchCacheIden ].join(KEY_SEPARATOR) } -/** - * Records the caller's current selection, reporting whether the branch was not - * already active. Claims are least-recently-used so the fast tier stays bounded - * no matter how many a client asserts. - */ -function noteActiveClaim(key: string): boolean { - const now = Date.now() - for (const [candidate, claimedAt] of activeClaims) { - if (now - claimedAt > ACTIVE_CLAIM_TTL_MS) { - activeClaims.delete(candidate) - } - } - const wasActive = activeClaims.has(key) - activeClaims.delete(key) - activeClaims.set(key, now) - while (activeClaims.size > MAX_ACTIVE_BRANCHES) { - const oldest = activeClaims.keys().next().value - if (oldest === undefined) { - break - } - activeClaims.delete(oldest) - } - return !wasActive -} - -function isActiveBranch(key: string): boolean { - const claimedAt = activeClaims.get(key) - return claimedAt !== undefined && Date.now() - claimedAt <= ACTIVE_CLAIM_TTL_MS -} - // Why: a merged review is the one answer that depends on the inspected head — // the merged-at-head carve-out keeps it visible only while the head matches. // Negative answers are deliberately head-insensitive, so a branch under active @@ -151,50 +150,50 @@ function storeEntry(key: string, entry: CacheEntry): void { } } -function backoffUntil(key: string): number | null { - // Why: a lapsed window keeps its failure count, otherwise the very act of - // retrying resets the escalation and the backoff never grows past the base. - const entry = failureBackoff.get(key) - return entry !== undefined && entry.until > Date.now() ? entry.until : null +/** Clears the key's in-flight record only if it is still this lookup's. */ +function releaseInflight(key: string, token: object): boolean { + if (inflight.get(key)?.token !== token) { + return false + } + inflight.delete(key) + return true } -function noteFailure(key: string): void { - const now = Date.now() - for (const [candidate, entry] of failureBackoff) { - // Why: only counts that lapsed a full max window ago are stale enough to - // forget; anything more eager would undo the escalation above. - if (now - entry.until > LOOKUP_BACKOFF_MAX_MS) { - failureBackoff.delete(candidate) +/** + * Expires records that outlived the deadline without their timer firing. Main's + * timers are suspended across a system sleep, so wall-clock age — not + * `setTimeout` alone — is what actually bounds how long a branch stays pinned. + * + * The guarantee covers tracked records only: one the size cap evicted is no + * longer reachable here and falls back to its own suspended timer. + */ +function expireOverdueInflight(now: number): void { + let overdue: InflightRecord[] | undefined + for (const record of inflight.values()) { + if (now - record.startedAt >= HOSTED_REVIEW_LOOKUP_DEADLINE_MS) { + overdue ??= [] + overdue.push(record) } } - const failures = (failureBackoff.get(key)?.failures ?? 0) + 1 - failureBackoff.delete(key) - failureBackoff.set(key, { until: now + lookupBackoffDelayMs(failures), failures }) - while (failureBackoff.size > MAX_ENTRIES) { - const oldest = failureBackoff.keys().next().value - if (oldest === undefined) { - break - } - failureBackoff.delete(oldest) + // Expire after the walk: each one deletes its own entry from the map. + for (const record of overdue ?? []) { + record.expire() } } -function scopeGeneration(scope: string): number { - return scopeGenerations.get(scope) ?? 0 -} - -function bumpScopeGeneration(scope: string): void { - const next = scopeGeneration(scope) + 1 - scopeGenerations.delete(scope) - scopeGenerations.set(scope, next) - // Why: an evicted scope reads as generation 0, which only makes a lookup in - // flight at eviction discard its result — a wasted call, never a stale one. - while (scopeGenerations.size > MAX_ENTRIES) { - const oldest = scopeGenerations.keys().next().value +function trackInflight(key: string, record: InflightRecord): void { + inflight.set(key, record) + while (inflight.size > MAX_INFLIGHT_LOOKUPS) { + const oldest = inflight.keys().next().value if (oldest === undefined) { break } - scopeGenerations.delete(oldest) + // Why: drop the record without expiring it — its own deadline still + // releases its callers, and evicting is about memory, not about failing. + // It does forfeit the sweep's wall-clock release, so the cap must stay far + // above realistic concurrency: below it, sleep-suspended timers are all an + // evicted record's callers have left. + inflight.delete(oldest) } } @@ -214,20 +213,174 @@ export function invalidateHostedReviewBranchCache( entries.delete(key) } } - for (const key of failureBackoff.keys()) { - if (key.startsWith(prefix)) { - failureBackoff.delete(key) - } - } + dropFailuresWithPrefix(prefix) } /** @internal - exposed for tests only */ export function __resetHostedReviewBranchCacheForTests(): void { entries.clear() inflight.clear() - failureBackoff.clear() - activeClaims.clear() - scopeGenerations.clear() + __resetHostedReviewLookupBackoffForTests() + __resetHostedReviewActiveClaimsForTests() + __resetUnsettledHostedReviewLookupsForTests() + __resetHostedReviewScopeGenerationsForTests() +} + +/** + * Whether a lookup that no longer owns the key may still install its answer. + * Losing the record — to the deadline or to the size cap — costs it the branch, + * so it may only fill a gap or replace an answer a strictly older attempt stored + * after this one began. It must never overwrite the pre-refresh answer its own + * callers were served, and never beat a replacement to the key: a late `null` + * landing there reads as a fresh "no review" and short-circuits the lookup that + * was about to give the real one. + */ +function canAdoptDetachedAnswer(key: string, startedAt: number): boolean { + if (inflight.has(key)) { + return false + } + const current = entries.get(key) + return current === undefined || (current.startedAt < startedAt && current.fetchedAt >= startedAt) +} + +/** Why the branch must not be asked again yet, or null when a lookup may start. */ +function lookupUnavailableReason(key: string): string | null { + const until = backoffUntil(key) + if (until !== null) { + return `Hosted review lookup is backing off after repeated failures. Retrying after ${new Date( + until + ).toLocaleTimeString()}.` + } + if (!hasLookupCapacity(key)) { + return 'Hosted review lookup is still running from an earlier attempt that never answered. It will be retried once that attempt settles.' + } + return null +} + +/** + * Runs one lookup under a deadline. Nothing below this can be cancelled, so the + * deadline *detaches* instead: the branch is unpinned and the callers hear a + * failure, while the lookup keeps running and its answer is still adopted if it + * ever lands. That is what lets a wedged host recover in-session (P1-D). + */ +function startLookup( + key: string, + scope: string, + headOid: string | null, + lookup: () => Promise +): Promise { + const startedAt = Date.now() + const generation = scopeGeneration(scope) + const token = {} + /** The deadline released the callers; the lookup itself runs on, detached. */ + let timedOut = false + let completed = false + let release: (review: HostedReviewInfo | null) => void = () => {} + let fail: (error: unknown) => void = () => {} + const promise = new Promise((resolve, reject) => { + release = resolve + fail = reject + }) + let timer: ReturnType | undefined + + const expire = (): void => { + if (timedOut || completed) { + return + } + timedOut = true + if (timer !== undefined) { + clearTimeout(timer) + } + // Why: only the lookup still serving this key shapes the backoff. A record + // already replaced — or dropped by the size cap — has a live successor, and + // penalising the branch would slow down the retry that is already running. + if (releaseInflight(key, token)) { + noteFailure(key) + } + // Why: the lookup runs on with nothing able to stop it, so it is counted + // process-wide until it settles — that count is what stops a wedged host + // from stranding a lookup on every branch it serves. + noteDetachedLookup() + const stale = entries.get(key) + if (stale) { + release(stale.review) + return + } + fail( + new Error( + `Hosted review lookup timed out after ${Math.round( + HOSTED_REVIEW_LOOKUP_DEADLINE_MS / 1000 + )}s. It will be retried on a later poll.` + ) + ) + } + + // Why: the branch's slot is taken from the moment the lookup starts. Counting + // only from the deadline would let a first failure wave admit one lookup per + // branch with the cap still reading zero, and every one of them can wedge. + noteLookupStarted(key) + timer = setTimeout(expire, HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + if (typeof timer === 'object' && 'unref' in timer) { + timer.unref() + } + // Why: track before running, so a lookup that throws synchronously clears the + // record it would otherwise leave behind for a full deadline. + trackInflight(key, { token, startedAt, promise, expire }) + + void (async () => { + try { + const review = await lookup() + // Why: a review created while this lookup was out makes its answer older + // than the invalidation; storing it would re-pin the stale "no review". + // Owning the key is what licenses a store outright — anything else is a + // straggler and has to prove it still outranks what is there. + const stored = + generation === scopeGeneration(scope) && + (inflight.get(key)?.token === token || canAdoptDetachedAnswer(key, startedAt)) + if (stored) { + storeEntry(key, { review, fetchedAt: Date.now(), headOid, startedAt }) + } + // Why: only an answer that beat the deadline proves the provider is + // healthy. Clearing on a straggler leaves a chronically wedged host at the + // base window forever, re-asking as fast as the deadline expires. + if (stored && !timedOut) { + clearFailures(key) + } + release(review) + } catch (error) { + // Why: the deadline already counted this lookup as a failure and released + // its callers; counting the late rejection again would double-escalate. + if (timedOut) { + return + } + // Why: a record the size cap dropped has a live successor, and backing the + // branch off would slow the retry that is already running. + if (inflight.get(key)?.token === token) { + noteFailure(key) + } + // Why: the last good review beats an error card here just as it does on + // the backed-off path — otherwise it blinks out on the first failure. + // An invalidation drops the entry, so this cannot revive a retired answer. + const stale = entries.get(key) + if (stale) { + release(stale.review) + return + } + fail(error) + } finally { + completed = true + if (timer !== undefined) { + clearTimeout(timer) + } + if (timedOut) { + settleDetachedLookup() + } + settleLookup(key) + releaseInflight(key, token) + } + })() + + return promise } /** @@ -242,6 +395,9 @@ export async function withHostedReviewBranchCache( ): Promise { const key = hostedReviewBranchCacheKey(identity) const headOid = options.headOid + // Why: sweep first, so a lookup whose deadline never fired cannot be joined — + // that is the pin this cache used to hold until the process restarted. + expireOverdueInflight(Date.now()) if (options.active === true && noteActiveClaim(key) && entries.get(key)?.review === null) { // Why: switching to a worktree is the user asking whether a review exists // yet, so the long no-review interval must not answer on their behalf. This @@ -258,49 +414,18 @@ export async function withHostedReviewBranchCache( const pending = inflight.get(key) if (pending) { - return pending + return pending.promise } - const until = backoffUntil(key) - if (until !== null) { + const unavailable = lookupUnavailableReason(key) + if (unavailable !== null) { // Why: a stale answer beats an error card, but with nothing cached the // caller must hear the failure rather than read it as "no review". if (cached) { return cached.review } - throw new Error( - `Hosted review lookup is backing off after repeated failures. Retrying after ${new Date( - until - ).toLocaleTimeString()}.` - ) + throw new Error(unavailable) } - const scope = repoScope(identity.repoPath, identity.connectionId) - const request = (async () => { - const generation = scopeGeneration(scope) - try { - const review = await lookup() - // Why: a review created while this lookup was out makes its answer older - // than the invalidation; storing it would re-pin the stale "no review". - if (generation === scopeGeneration(scope)) { - storeEntry(key, { review, fetchedAt: Date.now(), headOid }) - failureBackoff.delete(key) - } - return review - } catch (error) { - noteFailure(key) - // Why: the last good review beats an error card here just as it does on - // the backed-off path — otherwise it blinks out on the first failure. - // An invalidation drops the entry, so this cannot revive a retired answer. - const stale = entries.get(key) - if (stale) { - return stale.review - } - throw error - } finally { - inflight.delete(key) - } - })() - inflight.set(key, request) - return request + return startLookup(key, repoScope(identity.repoPath, identity.connectionId), headOid, lookup) } diff --git a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts index 2bb808857..e0bb2e491 100644 --- a/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts +++ b/src/main/source-control/hosted-review-creation-gitlab-self-hosted.test.ts @@ -61,6 +61,7 @@ vi.mock('./hosted-review', () => ({ getHostedReviewForBranch: getHostedReviewForBranchMock })) +import { REMOTE_URL_PROBE_TIMEOUT_MS } from '../git/remote-url-probe' import { _resetKnownHostsCache, _resetProjectRefCache } from '../gitlab/gl-utils' import { diagnoseAuth } from '../gitlab/client' import { getHostedReviewCreationEligibility } from './hosted-review-creation' @@ -140,8 +141,11 @@ describe('GitLab self-hosted hosted review creation eligibility', () => { head: 'feature/self-hosted-mr' }) + // The probe is bounded: a dead mount must not pin the forge detection that + // every hosted-review lookup starts with (P1-D). expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], { - cwd: '/repo' + cwd: '/repo', + timeout: REMOTE_URL_PROBE_TIMEOUT_MS }) expect(glabExecFileAsyncMock).toHaveBeenCalledWith( ['auth', 'status', '--hostname', 'gitlab.internal'], diff --git a/src/main/source-control/hosted-review-lookup-backoff.ts b/src/main/source-control/hosted-review-lookup-backoff.ts new file mode 100644 index 000000000..d02b730f6 --- /dev/null +++ b/src/main/source-control/hosted-review-lookup-backoff.ts @@ -0,0 +1,64 @@ +import { + lookupBackoffDelayMs, + LOOKUP_BACKOFF_MAX_MS, + MAX_BRANCH_MAP_ENTRIES +} from './hosted-review-refresh-pacing' + +/** + * Per-branch failure escalation for hosted-review lookups (#11532). + * + * Split out of the branch cache so the cache file stays about caching: this map + * has its own lifetime — a branch stays backed off after its cached answer is + * invalidated, and it is what a lookup deadline records against (P1-D). + */ + +/** Bounded like the answer cache, so a churn of dead branches cannot grow it. */ +const MAX_BACKOFF_ENTRIES = MAX_BRANCH_MAP_ENTRIES + +const failureBackoff = new Map() + +export function backoffUntil(key: string): number | null { + // Why: a lapsed window keeps its failure count, otherwise the very act of + // retrying resets the escalation and the backoff never grows past the base. + const entry = failureBackoff.get(key) + return entry !== undefined && entry.until > Date.now() ? entry.until : null +} + +export function noteFailure(key: string): void { + const now = Date.now() + for (const [candidate, entry] of failureBackoff) { + // Why: only counts that lapsed a full max window ago are stale enough to + // forget; anything more eager would undo the escalation above. + if (now - entry.until > LOOKUP_BACKOFF_MAX_MS) { + failureBackoff.delete(candidate) + } + } + const failures = (failureBackoff.get(key)?.failures ?? 0) + 1 + failureBackoff.delete(key) + failureBackoff.set(key, { until: now + lookupBackoffDelayMs(failures), failures }) + while (failureBackoff.size > MAX_BACKOFF_ENTRIES) { + const oldest = failureBackoff.keys().next().value + if (oldest === undefined) { + break + } + failureBackoff.delete(oldest) + } +} + +/** A lookup answered, so the branch starts its next escalation from the base. */ +export function clearFailures(key: string): void { + failureBackoff.delete(key) +} + +export function dropFailuresWithPrefix(prefix: string): void { + for (const key of failureBackoff.keys()) { + if (key.startsWith(prefix)) { + failureBackoff.delete(key) + } + } +} + +/** @internal - exposed for tests only */ +export function __resetHostedReviewLookupBackoffForTests(): void { + failureBackoff.clear() +} diff --git a/src/main/source-control/hosted-review-refresh-pacing.ts b/src/main/source-control/hosted-review-refresh-pacing.ts index 7c2eaf3c6..ed36463af 100644 --- a/src/main/source-control/hosted-review-refresh-pacing.ts +++ b/src/main/source-control/hosted-review-refresh-pacing.ts @@ -29,6 +29,40 @@ export const ACTIVE_CLAIM_TTL_MS = NO_REVIEW_REFRESH_INTERVAL_MS export const LOOKUP_BACKOFF_BASE_MS = 60_000 export const LOOKUP_BACKOFF_MAX_MS = 15 * 60_000 +/** + * Hard deadline for a single lookup. The steps underneath are individually + * bounded (30s `gh` exec, HTTP timeouts) but they chain, so this is a hang + * detector rather than a latency budget: a lookup that outlives it is wedged on + * something that has no timeout of its own, not merely slow. + */ +export const HOSTED_REVIEW_LOOKUP_DEADLINE_MS = 2 * 60_000 + +/** + * Single bound for every branch-keyed map in this subsystem — cached answers, + * scope generations and failure backoff. One knob, so tuning one map cannot + * silently leave the others behind. + */ +export const MAX_BRANCH_MAP_ENTRIES = 500 + +/** + * Why: a memory backstop, not a concurrency limit. Evicting a live lookup costs + * a duplicate provider call — the quota problem this cache exists to prevent — + * so the cap must stay far above the branch count any client polls at once. + */ +export const MAX_INFLIGHT_LOOKUPS = MAX_BRANCH_MAP_ENTRIES + +/** + * A lookup cannot be cancelled, so one that never settles is stranded for the + * life of the process. Two per branch — counted from the moment a lookup starts, + * not from the deadline — leaves room for the retry that proves a host + * recovered; past that the branch is wedged, not slow, and asking again only + * strands another provider call. + */ +export const MAX_UNSETTLED_LOOKUPS_PER_KEY = 2 + +/** Process-wide backstop for the same leak when many branches wedge at once. */ +export const MAX_DETACHED_LOOKUPS = 64 + // Why: capped so a long-lived failure settles at LOOKUP_BACKOFF_MAX_MS rather // than overflowing the exponent. const MAX_BACKOFF_DOUBLINGS = 4 diff --git a/src/main/source-control/hosted-review-scope-generations.ts b/src/main/source-control/hosted-review-scope-generations.ts new file mode 100644 index 000000000..f96ed6548 --- /dev/null +++ b/src/main/source-control/hosted-review-scope-generations.ts @@ -0,0 +1,43 @@ +import { MAX_BRANCH_MAP_ENTRIES } from './hosted-review-refresh-pacing' + +/** + * Per-repo invalidation counter for hosted-review lookups (#11532). + * + * A lookup that was already out when Orca opened a review has an answer older + * than the invalidation, so it must not store. Comparing the generation it + * started at against the current one is what tells the two apart. + */ +const scopeGenerations = new Map() + +/** + * Floor for a scope the size cap dropped. Without it an eviction reads back as + * generation 0 — the same value a lookup that started before the first + * invalidation captured — and that lookup's pre-invalidation answer would be + * stored as current. Never decreasing is what keeps the comparison one-way: + * eviction can only make a lookup discard its result, never adopt a stale one. + */ +let evictedGeneration = 0 + +export function scopeGeneration(scope: string): number { + return scopeGenerations.get(scope) ?? evictedGeneration +} + +export function bumpScopeGeneration(scope: string): void { + const next = scopeGeneration(scope) + 1 + scopeGenerations.delete(scope) + scopeGenerations.set(scope, next) + while (scopeGenerations.size > MAX_BRANCH_MAP_ENTRIES) { + const oldest = scopeGenerations.keys().next().value + if (oldest === undefined) { + break + } + evictedGeneration = Math.max(evictedGeneration, scopeGenerations.get(oldest) ?? 0) + scopeGenerations.delete(oldest) + } +} + +/** @internal - exposed for tests only */ +export function __resetHostedReviewScopeGenerationsForTests(): void { + scopeGenerations.clear() + evictedGeneration = 0 +} diff --git a/src/main/source-control/hosted-review-unsettled-lookups.ts b/src/main/source-control/hosted-review-unsettled-lookups.ts new file mode 100644 index 000000000..96ed0eddf --- /dev/null +++ b/src/main/source-control/hosted-review-unsettled-lookups.ts @@ -0,0 +1,63 @@ +import { MAX_DETACHED_LOOKUPS, MAX_UNSETTLED_LOOKUPS_PER_KEY } from './hosted-review-refresh-pacing' + +/** + * Accounting for lookups that have not settled (P1-D). + * + * Nothing under the hosted-review funnel can be cancelled, so a lookup runs + * until it settles — or forever, on a wedged host. Counting them is what stops + * every deadline-plus-backoff cycle from stranding another one: past the cap the + * branch answers unavailable instead of spawning a duplicate zombie. + * + * A branch reserves its slot when the lookup *starts*, not when the deadline + * detaches it: an in-flight lookup the size cap dropped from the in-flight map is + * just as unstoppable as a detached one, and admitting another for the same + * branch alongside it would strand both. + */ +const unsettledByKey = new Map() + +/** + * Detached work is counted process-wide too, because a wedged host wedges every + * branch on it. In-flight lookups are deliberately left out of this total: they + * are the ordinary fan-out of a client polling its worktree list, and capping + * those at 64 would fail legitimate lookups on any machine with more branches. + */ +let detachedTotal = 0 + +/** Reserves the branch's slot for a lookup that is about to start. */ +export function noteLookupStarted(key: string): void { + unsettledByKey.set(key, (unsettledByKey.get(key) ?? 0) + 1) +} + +/** The deadline gave up on this lookup; it runs on, and stays counted. */ +export function noteDetachedLookup(): void { + detachedTotal += 1 +} + +/** Called when a lookup finally settles, freeing its branch slot. */ +export function settleLookup(key: string): void { + const remaining = (unsettledByKey.get(key) ?? 0) - 1 + if (remaining > 0) { + unsettledByKey.set(key, remaining) + } else { + unsettledByKey.delete(key) + } +} + +/** Called when a detached lookup settles, freeing its process-wide slot. */ +export function settleDetachedLookup(): void { + detachedTotal = Math.max(0, detachedTotal - 1) +} + +/** False once this branch — or the process — is holding too many unsettled lookups. */ +export function hasLookupCapacity(key: string): boolean { + return ( + (unsettledByKey.get(key) ?? 0) < MAX_UNSETTLED_LOOKUPS_PER_KEY && + detachedTotal < MAX_DETACHED_LOOKUPS + ) +} + +/** @internal - exposed for tests only */ +export function __resetUnsettledHostedReviewLookupsForTests(): void { + unsettledByKey.clear() + detachedTotal = 0 +} diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 50c68870b..c6fd3bd8f 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,7 +1,11 @@ import type { HostedReviewInfo } from '../../shared/hosted-review' +import { assertRemoteUrlReadable } from '../git/remote-url-probe' import { getForgeProviderForRepository, type ForgeProviderId } from './forge-provider' import { withHostedReviewBranchCache } from './hosted-review-branch-cache' -import type { HostedReviewExecutionOptions } from './hosted-review-git-options' +import { + getHostedReviewLocalGitOptions, + type HostedReviewExecutionOptions +} from './hosted-review-git-options' function reviewLinkForProvider( input: Parameters[0], @@ -71,6 +75,15 @@ export async function getHostedReviewForBranch( ...(input.localGitExecOptions ? { localGitExecOptions: input.localGitExecOptions } : {}) }) if (!provider) { + // Why: forge detection swallows probe failures, so a remote read that + // was killed on its deadline (or lost its relay) would otherwise be + // cached as a definitive "no review" for the whole no-review interval. + // Throwing keeps it on the cache's failure path instead (P1-D). + await assertRemoteUrlReadable({ + repoPath: input.repoPath, + connectionId: input.connectionId, + ...getHostedReviewLocalGitOptions(input) + }) return null } return provider.getReviewForBranch({