fix(P1-D): bound hosted-review in-flight lookups so a wedged provider cannot pin a branch (#12030)
* fix(P1-D): bound hosted-review lookups with a detachable deadline The `inflight` map in the hosted-review branch cache was only ever cleared when the lookup settled, and nothing bounded how long that took. One wedged provider call pinned its branch for the life of the process: every later poll joined the same dead promise, so the card loaded forever with no in-session recovery. Each lookup now runs under a 120s deadline. Nothing below the funnel can be cancelled, so the deadline detaches instead: the record is released, the callers get the last known review (or a timeout error), and the branch enters the existing failure backoff. The lookup keeps running and its answer is still adopted if it lands, so a slow-but-alive host converges rather than failing forever. A token identity keeps a detached lookup from evicting the record that replaced it, and a wall-clock sweep expires records whose timer never fired — main's timers are suspended across system sleep. `inflight` is capped independently of the completed cache. The failure backoff moves to its own module: it has a different lifetime from the answer cache and is what a deadline records against. * fix(P1-D): bound `git remote get-url` on the local/WSL path `getRemoteUrlForRepo` ran the git child with no timeout, which is the one unbounded step under the hosted-review lookup funnel: `git/runner.ts` only arms its kill path when a timeout is passed, so a dead network mount or a stalled WSL interop hangs the call and everything above it. The SSH branch is already bounded by the relay mux's 30s request timeout, so it is unchanged. * rm review doc * rm review doc * test(P1-D): add probe tests and transient-failure recovery verification Add tests for coalesced-probe and remote-url-probe infrastructure. Add integration test verifying that transient Bitbucket API failures don't cache as a definitive no-review result, allowing recovery after cache TTL expiration. * fix(P1-D): track lookups from start, prevent stale scope adoption - Count unsettled lookups when they start, not after deadline expires: prevents multiple concurrent lookups for the same branch. - Add evicted generation floor: prevents adopting stale results when scope is invalidated and evicted from the map. - Consolidate duplicate repository reference cache logic into createRemoteRefProbeCache utility. - Fix deadline wrapper in git config signature lookup: bound the caller's deadline only, not the coalesced probe itself. * feat(P1-D): add remote-ref-probe-cache utility Cache successful remote URL probes per repo/runtime to avoid duplicate work. Skip caching transient errors and SSH failures so providers can retry on reconnect, preventing stale scope adoption during the session.
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runCoalescedProbe, type CoalescedProbes } from './coalesced-probe'
|
||||
|
||||
function deferred<T>(): {
|
||||
promise: Promise<T>
|
||||
resolve: (value: T) => void
|
||||
reject: (error: unknown) => void
|
||||
} {
|
||||
let resolve: (value: T) => void = () => {}
|
||||
let reject: (error: unknown) => void = () => {}
|
||||
const promise = new Promise<T>((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<string> = new Map()
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const createProbe = vi
|
||||
.fn<() => Promise<string>>()
|
||||
.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<string> = new Map()
|
||||
const first = deferred<string>()
|
||||
const second = deferred<string>()
|
||||
const createProbe = vi
|
||||
.fn<() => Promise<string>>()
|
||||
.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')
|
||||
})
|
||||
})
|
||||
@@ -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<T> = { startedAt: number; promise: Promise<T> }
|
||||
export type CoalescedProbes<T> = Map<string, CoalescedProbe<T>>
|
||||
|
||||
/** 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<T>(
|
||||
probes: CoalescedProbes<T>,
|
||||
key: string,
|
||||
createProbe: () => Promise<T>,
|
||||
staleAfterMs: number = PROBE_COALESCE_STALE_MS
|
||||
): Promise<T> {
|
||||
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<T> = { startedAt: now, promise: createProbe() }
|
||||
probes.set(key, entry)
|
||||
try {
|
||||
return await entry.promise
|
||||
} finally {
|
||||
if (probes.get(key) === entry) {
|
||||
probes.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Ref> = {
|
||||
get(
|
||||
repoPath: string,
|
||||
remoteName: string,
|
||||
connectionId?: string | null,
|
||||
localGitOptions?: RemoteRefLocalGitOptions
|
||||
): Promise<Ref | null>
|
||||
clear(): void
|
||||
size(): number
|
||||
}
|
||||
|
||||
export function createRemoteRefProbeCache<Ref>(
|
||||
parseRemoteUrl: (remoteUrl: string) => Ref | null
|
||||
): RemoteRefProbeCache<Ref> {
|
||||
const repoRefCache = new Map<string, Ref | null>()
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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<string | null> {
|
||||
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<void> {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user