diff --git a/src/main/github/client/lookup/pr-branch-read-resources.ts b/src/main/github/client/lookup/pr-branch-read-resources.ts new file mode 100644 index 00000000000..3abe7c982f0 --- /dev/null +++ b/src/main/github/client/lookup/pr-branch-read-resources.ts @@ -0,0 +1,88 @@ +import type { CoalescedProbes } from '../../../git/remotes/coalesced-probe' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' + +/** + * One exact PR read (scope, branch, links, options) and what reads it: its coalesced timed and + * fresh probes, the provider reads running for it (including ones a fresh read replaced), the + * start of the newest one, and failures a retry still owes. It lives until none of those remain. + */ +export type PRBranchReadResource = { + probes: CoalescedProbes + running: number + latestStart: number + failures: number +} + +/** A failed provider read's claim on its resource while a retry owes it: current until a newer + * provider read of the same resource starts, or its scope changes. Released exactly once. */ +export type PRReadFailureHold = { current: () => boolean; release: () => void } + +const resources = new Map() + +export function prBranchReadResource(key: string): PRBranchReadResource { + let resource = resources.get(key) + if (!resource) { + resource = { probes: new Map(), running: 0, latestStart: 0, failures: 0 } + resources.set(key, resource) + } + return resource +} + +/** A probe still running for the resource, joinable while younger than two minutes. */ +export function pendingPRBranchRead( + key: string, + intent: 'fresh' | 'timed' +): Promise | null { + const pending = resources.get(key)?.probes.get(intent) + return pending && Date.now() - pending.startedAt < 2 * 60_000 ? pending.promise : null +} + +/** Drops the resource once no probe, provider read or owed retry refers to it. */ +export function retirePRBranchReadResource(key: string, resource: PRBranchReadResource): void { + if ( + resource.probes.size === 0 && + resource.running === 0 && + resource.failures === 0 && + resources.get(key) === resource + ) { + resources.delete(key) + } +} + +/** Marks an actual provider read of the resource as started; returns its end. */ +export function startPRBranchRead( + key: string, + resource: PRBranchReadResource, + sequence: number +): () => void { + resource.running += 1 + resource.latestStart = Math.max(resource.latestStart, sequence) + return () => { + resource.running -= 1 + retirePRBranchReadResource(key, resource) + } +} + +export function holdPRBranchReadFailure( + key: string, + resource: PRBranchReadResource, + sequence: number, + inScope: () => boolean +): PRReadFailureHold { + resource.failures += 1 + let held = true + return { + current: () => held && resource.latestStart === sequence && inScope(), + release: () => { + if (held) { + held = false + resource.failures -= 1 + retirePRBranchReadResource(key, resource) + } + } + } +} + +export function _prBranchReadResourceCountForTests(): number { + return resources.size +} diff --git a/src/main/github/client/lookup/pr-for-branch-outcome.ts b/src/main/github/client/lookup/pr-for-branch-outcome.ts index a3a59d4c9b7..8bfc231a4f4 100644 --- a/src/main/github/client/lookup/pr-for-branch-outcome.ts +++ b/src/main/github/client/lookup/pr-for-branch-outcome.ts @@ -3,7 +3,7 @@ import { captureGitHubRepoExecution, outsideGitHubRepoExecution } from '../../repositories/github-repository-identity' -import { runCoalescedProbe, type CoalescedProbes } from '../../../git/remotes/coalesced-probe' +import { runCoalescedProbe } from '../../../git/remotes/coalesced-probe' import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { acquire, release } from '../../execution/github-operation-slots' @@ -29,7 +29,14 @@ import { scopeGeneration } from '../../../source-control/hosted-review-scope-generations' import { getRepoExecutionHostId } from '../../../../shared/execution-host' -const reads: CoalescedProbes = new Map() +import { + holdPRBranchReadFailure, + pendingPRBranchRead, + prBranchReadResource, + retirePRBranchReadResource, + startPRBranchRead, + type PRReadFailureHold +} from './pr-branch-read-resources' class PRLookupRetentionRefused extends Error {} /** A phone read may take the last lookup's open PR; it was already observed when it was looked up. */ @@ -133,24 +140,26 @@ export async function preparePRBranchRead( scope ) const ownerKey = lastOutcomeKey(repoPath, branchName, scope) - const freshKey = `${key}::fresh` - const timedKey = `${key}::timed` - const coalescingKey = options.resetQuietBackoff || options.userRefresh ? freshKey : timedKey - const pendingAt = (key: string) => { - const pending = reads.get(key) - return pending && Date.now() - pending.startedAt < 2 * 60_000 ? pending.promise : null - } + const coalescingKey = options.resetQuietBackoff || options.userRefresh ? 'fresh' : 'timed' + const pendingAt = (intent: 'fresh' | 'timed') => pendingPRBranchRead(key, intent) + const isCurrent = () => + outsideGitHubRepoExecution( + () => + lastOutcomeKey(repoPath, branchName, prLookupScope(repoPath, connectionId, options)) === + ownerKey + ) const narrowed = options.checkPageLimit !== undefined || options.exactRepository || options.includeDerivedData === false let didRead = false const readCore = (requireRetention = false, settle?: PRReadSettlement) => - withExecution( - () => - (!options.userRefresh && coalescingKey === timedKey ? pendingAt(freshKey) : null) ?? + withExecution(() => { + const resource = prBranchReadResource(key) + return ( + (!options.userRefresh && coalescingKey === 'timed' ? pendingAt('fresh') : null) ?? runCoalescedProbe( - reads, + resource.probes, coalescingKey, async (ownsKey) => { const start = startPRLookup() @@ -165,6 +174,7 @@ export async function preparePRBranchRead( if (requireRetention && !retained) { throw new PRLookupRetentionRefused() } + const ended = startPRBranchRead(key, resource, start.sequence) didRead = true try { await acquire() @@ -205,20 +215,25 @@ export async function preparePRBranchRead( cached: () => readTimedPROutcome(ownerKey, key) }) } + const hold = narrowed + ? undefined + : () => holdPRBranchReadFailure(key, resource, start.sequence, isCurrent) return settle && (retained ? readTimedPROutcome(ownerKey, key)?.outcome === outcome : ownsKey()) - ? settle(outcome, { retained }) + ? settle(outcome, { retained, hold }) : outcome } finally { if (retained) { releaseExactPRLookup(key, start.sequence) } + ended() } }, 2 * 60_000, { userRefresh: options.userRefresh === true } - ) - ) + ).finally(() => retirePRBranchReadResource(key, resource)) + ) + }) const read = async (settle?: PRReadSettlement): Promise => { try { return await readCore(false, settle) @@ -243,15 +258,7 @@ export async function preparePRBranchRead( key, reprepare, cached: () => readTimedPROutcome(ownerKey, key), - isCurrent: () => - outsideGitHubRepoExecution( - () => - lastOutcomeKey( - repoPath, - branchName, - prLookupScope(repoPath, connectionId, options) - ) === ownerKey - ), + isCurrent, accepts: (outcome) => readTimedPROutcome(ownerKey, key)?.outcome === outcome, didRead: () => didRead, release: () => {}, @@ -259,7 +266,7 @@ export async function preparePRBranchRead( readRetained, canRetain: () => canRetainPROutcome(key), scheduleError: (expected, outcome) => scheduleExactPRError(key, expected, outcome), - pending: () => pendingAt(freshKey) ?? pendingAt(timedKey), + pending: () => pendingAt('fresh') ?? pendingAt('timed'), withExecution, read } @@ -267,9 +274,11 @@ export async function preparePRBranchRead( ) } +/** `hold`: for a full read, claims this provider read's failure for a retry it owes, whether or not + * the exact cache kept the outcome. */ export type PRReadSettlement = ( outcome: PRRefreshOutcome, - producer: { retained: boolean } + producer: { retained: boolean; hold?: () => PRReadFailureHold } ) => PRRefreshOutcome export type PreparedPRBranchRead = { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts index 12b2181249d..1640c54da93 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-candidate-policy.ts @@ -143,6 +143,15 @@ export function freshRetryAt(candidate: GitHubPRRefreshCandidate): number | null : candidate.cachedFetchedAt + refreshIntervalForCandidate(candidate) } +/** When a visible row's automatic follow-up is due under the current cadence: its validated + * interval after its data, now when it has none yet, or null when there is no timer for it (Off, + * or data even Default does not poll). Creation, retiming and the check before a start all use it. */ +export function automaticDueAt(candidate: GitHubPRRefreshCandidate): number | null { + return Number.isFinite(refreshIntervalForCandidate(candidate)) + ? (freshRetryAt(candidate) ?? Date.now()) + : null +} + /** How old data may be when a foreground return reads it again: its Default interval (the * validated quiet one where that applies), or the settled age for data Default runs no timer for. * The same age decides whether a return earns a read and whether a cached answer satisfies it. */ diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-auto-refresh-cadence.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-auto-refresh-cadence.test.ts index 3b8a5d905a0..9ca687d8fa7 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-auto-refresh-cadence.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-auto-refresh-cadence.test.ts @@ -172,14 +172,15 @@ describe('pr-refresh-coordinator auto-refresh cadence', () => { expect(getPRForBranchOutcomeMock.mock.calls.length).toBeGreaterThan(2) }) - it('restores a failed row’s own retry on Default, which the next Off retires again', async () => { + it('restores a failed row’s own retry from its failure time and count, which the next Off retires again', async () => { const { policy, coordinator } = await loadCoordinatorWithCadence('default') - getPRForBranchOutcomeMock.mockImplementation(async () => ({ + const failure = async () => ({ kind: 'upstream-error', errorType: 'unknown', message: 'offline', fetchedAt: Date.now() - })) + }) + getPRForBranchOutcomeMock.mockImplementation(failure) // Fails at 1 s; Default would retry it at 121 s. coordinator.reportVisiblePRRefreshCandidates([makeCandidate()], 1, 1) await vi.advanceTimersByTimeAsync(0) @@ -193,17 +194,24 @@ describe('pr-refresh-coordinator auto-refresh cadence', () => { await switchTo('off', 1_500) await switchTo('default', 2_000) await switchTo('off', 3_000) - await vi.advanceTimersByTimeAsync(130_000) + // Restored early: the retry still runs at 121 s, not later from the restoration. + await switchTo('default', 100_000) + await vi.advanceTimersByTimeAsync(120_999 - Date.now()) expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + // That retry fails as the second real failure, so the next one is due at 241 s; a count that + // restoration had raised would push it to 361 s or later. getPRForBranchOutcomeMock.mockImplementation(async () => ({ kind: 'found', pr: makePR({ checksStatus: 'pending' }), fetchedAt: Date.now() })) - await switchTo('default', Date.now()) - await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(240_999 - Date.now()) expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3) expect(coordinatorMocks.sendToTrustedUIRendererMock.mock.calls.at(-1)?.[1]).toMatchObject({ outcome: { kind: 'found' } }) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts index 8558e394e1c..b0f969a983f 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-foreground-cache.test.ts @@ -117,3 +117,54 @@ it.each([ expect(provider.resolve).toHaveBeenCalledTimes(2) } ) + +it('a settled PR shown again takes the answer another reader just fetched instead of reading again', async () => { + const coordinator = await import('./pr-refresh-coordinator') + const { getPRForBranchOutcome } = await import('../../client/lookup/pr-for-branch-outcome') + const { hostedReviewOptionArgs } = await import('./pr-refresh-candidate-policy') + const settled = (title: string) => async () => ({ + kind: 'found', + // ast-grep-ignore: test-no-wall-clock -- resetPRRefreshCoordinatorMocks installs fake timers + fetchedAt: Date.now(), + pr: makePR({ title, state: 'merged', checksStatus: 'success' }) + }) + provider.resolve.mockImplementation(settled('merged')) + const candidate = makeCandidate({ currentHeadOid: 'head-sha' }) + coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) + await vi.advanceTimersByTimeAsync(0) + coordinator.clearVisiblePRRefreshWindow(1) + await vi.advanceTimersByTimeAsync(20_000) + + // Another reader of the same request reads it just before the row is shown again. + provider.resolve.mockImplementation(settled('shared')) + await coordinator.runHostedPRRead(candidate, () => + getPRForBranchOutcome( + candidate.repoPath, + candidate.branch, + null, + null, + null, + hostedReviewOptionArgs(candidate, 'visible')[0] ?? {} + ) + ) + expect(provider.resolve).toHaveBeenCalledTimes(2) + coordinator.reportVisiblePRRefreshCandidates( + [ + { + ...candidate, + cachedFetchedAt: 1_000, + cachedHeadOid: 'head-sha', + cachedHasPR: true, + cachedPRState: 'merged', + cachedChecksStatus: 'success' + } + ], + 2, + 1 + ) + await vi.advanceTimersByTimeAsync(0) + expect(provider.resolve).toHaveBeenCalledTimes(2) + expect(coordinatorMocks.sendToTrustedUIRendererMock.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { pr: { title: 'shared' } } + }) +}) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator-restoration.test.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-restoration.test.ts new file mode 100644 index 00000000000..5385bed1af3 --- /dev/null +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator-restoration.test.ts @@ -0,0 +1,188 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { PRRefreshOutcome } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' +import { makeCandidate, makePR } from './pr-refresh-coordinator-test-harness' + +const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { + const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') + return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } +}) +// Only the provider and the rate-limit probe are faked: the lookup, its exact cache, the retry +// owner and the queue are the real ones. +const provider = vi.hoisted(() => ({ resolve: vi.fn(), gate: vi.fn() })) +vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) +vi.mock('./pr-refresh-rate-limit-gate', () => ({ + prRefreshRateLimitPausedUntil: provider.gate +})) +vi.mock('../../client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: provider.resolve +})) +vi.mock('../../execution/github-operation-slots', () => ({ + acquire: async () => {}, + release: () => {} +})) + +beforeEach(() => { + moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) + vi.setSystemTime(1_000) + provider.gate.mockReset().mockResolvedValue(null) + provider.resolve.mockReset().mockImplementation(async () => found('first')) +}) +afterEach(() => vi.useRealTimers()) + +function found(title: string): PRRefreshOutcome { + return { + kind: 'found', + fetchedAt: Date.now(), + pr: makePR({ title, checksStatus: 'pending' }) + } +} + +function failed(): PRRefreshOutcome { + return { kind: 'upstream-error', errorType: 'network', message: 'offline', fetchedAt: Date.now() } +} + +const readsOf = (branch: string) => + provider.resolve.mock.calls.filter(([read]) => read.branchName === branch).length + +async function load() { + const policy = await import('../../../../shared/review-refresh-policy') + const coordinator = await import('./pr-refresh-coordinator') + const lookup = await import('../../client/lookup/pr-for-branch-outcome') + const resources = await import('../../client/lookup/pr-branch-read-resources') + const switchTo = async (cadence: 'default' | 'off', at: number) => { + await vi.advanceTimersByTimeAsync(at - Date.now()) + policy.setPRAutoRefreshCadence(cadence) + coordinator.retimePRRefreshesForCadence() + } + return { coordinator, lookup, resources, switchTo } +} + +it('restores a failure the full exact cache could not keep as its own retry, which Off retires again', async () => { + const { coordinator, lookup, resources, switchTo } = await load() + // 256 other exact results, each held: the exact cache has no room for another. + const holds: (() => void)[] = [] + for (let other = 0; other < 256; other += 1) { + const prepared = await lookup.preparePRBranchRead('/repo', `other-${other}`, null, null, null, { + currentHeadOid: 'head-sha' + }) + await prepared.read() + holds.push(prepared.hold()) + } + provider.resolve.mockImplementation(async () => failed()) + const target = makeCandidate({ branch: 'target', currentHeadOid: 'head-sha' }) + // Fails at 1 s with no exact entry; Default would retry it at 121 s. + coordinator.reportVisiblePRRefreshCandidates([target], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(readsOf('target')).toBe(1) + for (const release of holds) { + release() + } + + await switchTo('off', 1_500) + await switchTo('default', 2_000) + await switchTo('off', 3_000) + await vi.advanceTimersByTimeAsync(130_000 - Date.now()) + expect(readsOf('target')).toBe(1) + + provider.resolve.mockImplementation(async () => found('recovered')) + await switchTo('default', Date.now()) + await vi.advanceTimersByTimeAsync(0) + expect(readsOf('target')).toBe(2) + expect(coordinatorMocks.sendToTrustedUIRendererMock.mock.calls.at(-1)?.[1]).toMatchObject({ + outcome: { pr: { title: 'recovered' } } + }) + // Recovery released the failure's claim on its request. + expect(resources._prBranchReadResourceCountForTests()).toBe(0) +}) + +it('owes no retry for a failure a newer read of the same request had already replaced', async () => { + const { coordinator, lookup } = await load() + const { hostedReviewOptionArgs } = await import('./pr-refresh-candidate-policy') + // The exact cache is full, so neither read below keeps its outcome there. + for (let other = 0; other < 256; other += 1) { + const prepared = await lookup.preparePRBranchRead('/repo', `other-${other}`, null, null, null, { + currentHeadOid: 'head-sha' + }) + await prepared.read() + prepared.hold() + } + const target = makeCandidate({ branch: 'target', currentHeadOid: 'head-sha' }) + const late = Promise.withResolvers() + provider.resolve.mockImplementationOnce(() => late.promise) + coordinator.reportVisiblePRRefreshCandidates([target], 1, 1) + await vi.advanceTimersByTimeAsync(0) + // A fresh read of the same request through the direct caller path, as a paired client's + // foreground read does, starts after it and succeeds first. + const options = hostedReviewOptionArgs(target, 'active')[0] ?? {} + await coordinator.runHostedPRRead(target, () => + lookup.getPRForBranchOutcome('/repo', 'target', null, null, null, options) + ) + late.resolve(failed()) + await vi.advanceTimersByTimeAsync(10 * 60_000) + expect(readsOf('target')).toBe(2) +}) + +it.each(['automatic', 'shown again'] as const)( + 'Off retires a restored follow-up waiting its turn, but not one a return upgraded (%s)', + async (kind) => { + const { coordinator, lookup, switchTo } = await load() + const x = makeCandidate({ branch: 'x', currentHeadOid: 'head-sha' }) + coordinator.reportVisiblePRRefreshCandidates([x], 1, 1) + await vi.advanceTimersByTimeAsync(0) + expect(readsOf('x')).toBe(1) + const shownX = { + ...x, + cachedFetchedAt: 1_000, + cachedHeadOid: 'head-sha', + cachedHasPR: true, + cachedPRState: 'open' as const, + cachedChecksStatus: 'pending' as const + } + await switchTo('off', 2_000) + // Other reads push X's exact answer out of the bounded cache while X stays visible. + for (let other = 0; other < 256; other += 1) { + await lookup.getPRForBranchOutcome('/repo', `other-${other}`, null, null, null, { + currentHeadOid: 'head-sha' + }) + } + // A newly shown Y reads under Off, and its budgeted start spaces the next one by 10 s. + await vi.advanceTimersByTimeAsync(199_000 - Date.now()) + const y = makeCandidate({ branch: 'y', worktreeId: 'wt-y', cacheKey: '/repo::y' }) + coordinator.reportVisiblePRRefreshCandidates([shownX, y], 2, 1) + await vi.advanceTimersByTimeAsync(0) + expect(readsOf('y')).toBe(1) + + await switchTo('default', 200_000) + if (kind === 'shown again') { + coordinator.clearVisiblePRRefreshWindow(1) + coordinator.reportVisiblePRRefreshCandidates([shownX, y], 3, 1) + } + await switchTo('off', 201_000) + await vi.advanceTimersByTimeAsync(30_000) + expect(readsOf('x')).toBe(kind === 'shown again' ? 2 : 1) + + provider.resolve.mockImplementation(async () => found('changed')) + await switchTo('default', Date.now()) + await vi.advanceTimersByTimeAsync(15_000) + // The automatic one is restored and reads now; the shown-again one already read under Off. + expect(readsOf('x')).toBe(2) + } +) + +it('a restored follow-up that waited for quota does not start once Off arrives', async () => { + const { coordinator, switchTo } = await load() + const x = makeCandidate({ branch: 'x', currentHeadOid: 'head-sha' }) + coordinator.reportVisiblePRRefreshCandidates([x], 1, 1) + await vi.advanceTimersByTimeAsync(0) + await switchTo('off', 2_000) + await vi.advanceTimersByTimeAsync(200_000 - Date.now()) + const quota = Promise.withResolvers() + provider.gate.mockReturnValueOnce(quota.promise) + await switchTo('default', 200_000) + await vi.advanceTimersByTimeAsync(0) + expect(provider.gate).toHaveBeenCalled() + await switchTo('off', 201_000) + quota.resolve(null) + await vi.advanceTimersByTimeAsync(60 * 60_000) + expect(readsOf('x')).toBe(1) +}) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts index f9d23b5eb49..5eefdb5a4ff 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-coordinator.ts @@ -32,7 +32,12 @@ import { refreshPRPolicyContext } from '../../client/lookup/pr-quiet-policy-evid import { getPRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' const retry = new PRRefreshRetryState() -const queue = new PRRefreshQueue((key) => retry.reset(key)) +// Dropping an old gate index entry must not forget a visible row's current failure. +const queue = new PRRefreshQueue((key) => { + if (!visibility.has(key)) { + retry.reset(key) + } +}) const pacing = new PRRefreshPacing() const visibility = new PRRefreshVisibility() const events = new PRRefreshEventPublisher() @@ -116,8 +121,23 @@ function removeInvisibleVisibleRefreshes(): void { } } +// A row no longer shown owes no retry for its failure; only its rate-limit gate stays. +function releaseHiddenFailures(shown: ReadonlySet): void { + for (const key of shown) { + if (!visibility.has(key)) { + retry.releaseFailure(key) + } + } +} + +function shownKeys(): Set { + return new Set(Array.from(visibility.reported(), ([, candidate]) => refreshKey(candidate))) +} + export function clearVisiblePRRefreshWindow(windowId: number): void { + const shown = shownKeys() const hadVisibleRefreshes = visibility.clearWindow(windowId) + releaseHiddenFailures(shown) pacing.clearActiveBurstWindow(windowId) if (hadVisibleRefreshes) { removeInvisibleVisibleRefreshes() @@ -128,9 +148,9 @@ export function clearVisiblePRRefreshWindow(windowId: number): void { /** A cadence change moves queued visible follow-ups, error retries and their shared schedules to * the new interval, and the gates of queued host jobs with them; "off" drops them. Under a timed - * cadence visible rows then get the next read it gives them, so Off back to Default resumes without - * waiting for the windows to report again: a row whose failure is still current gets that - * failure's own retry back, still an error retry the next Off retires; others their next read. */ + * cadence visible rows then get their automatic work back without waiting for the windows to + * report again: a row whose failure is still current gets that failure's own retry, others the + * follow-up the cadence gives them. Either stays automatic, so the next Off retires it. */ export function retimePRRefreshesForCadence(): void { const failureRetries = retry.retimeErrors(queue) queue.retimeVisible((key, candidate) => visibility.candidate(key, candidate)) @@ -140,22 +160,21 @@ export function retimePRRefreshesForCadence(): void { for (const [windowId, reported] of timed ? visibility.reported() : []) { const key = refreshKey(reported) const candidate = visibility.candidate(key, reported) - const retryAt = failureRetries.get(key) if (validateCandidate(candidate)) { continue } + const failed = failureRetries.get(key) + const retryAt = + failed !== undefined && retry.failureMatches(key, candidate) ? failed : undefined // Work already queued for the row (its retry, a return or an action) keeps its own reason. - if (retryAt !== undefined && !queue.get(key)) { - drainer.scheduleErrorRetry( - key, - candidate, - retryAt, - 40, - [aliasFromCandidate(candidate)], - windowId - ) - } else if (retryAt === undefined) { - queue.enqueue(candidate, 'visible', 40, windowId) + if (queue.get(key)) { + continue + } + const aliases = [aliasFromCandidate(candidate)] + if (retryAt === undefined) { + drainer.restoreFollowUp(key, candidate, 40, aliases, windowId) + } else { + drainer.scheduleErrorRetry(key, candidate, retryAt, 40, aliases, windowId) } } drainer.schedule() @@ -201,9 +220,11 @@ export function reportVisiblePRRefreshCandidates( ): void { refreshPRPolicyContext() const newlyExposed = new Set(candidates.map(refreshKey).filter((key) => !visibility.has(key))) + const shown = shownKeys() if (!visibility.report(candidates, generation, windowId)) { return } + releaseHiddenFailures(shown) removeInvisibleVisibleRefreshes() queue.retimeVisible((key, candidate) => visibility.candidate(key, candidate)) for (const candidate of candidates) { diff --git a/src/main/github/pull-requests/refresh/pr-refresh-error-retry-retiming.ts b/src/main/github/pull-requests/refresh/pr-refresh-error-retry-retiming.ts index 5b3495e5b68..23e5ef124fa 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-error-retry-retiming.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-error-retry-retiming.ts @@ -20,7 +20,9 @@ export function retimeQueuedErrorRetries( entry.key, candidateFor(entry.key, entry.candidate) ) + // No current failure owes it a retry (replaced, or its demand ended): it is not owed. if (planned === null) { + queue.delete(entry.key) continue } const retryAt = Math.max(planned, retry.manualGateUntil(entry.key)) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts b/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts index dcbff0e1ac8..a061619805a 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-immediate-read.ts @@ -119,16 +119,15 @@ export async function runImmediatePRRefresh( if (!prepared.isCurrent()) { return outcome } - const settled = - producer.retained && outcome.kind === 'upstream-error' && visibility.has(key) - ? retry.settleProducerError( - outcome, - key, - visibility.candidate(key, candidate), - prepared, - queue - ) - : outcome + const settled = retry.settleProducerError( + outcome, + key, + visibility.candidate(key, candidate), + prepared, + queue, + producer, + visibility.has(key) + ) events.observe(candidate, settled, aliases) return settled }) diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts index fb9df44d7de..98a9bb0b950 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-drainer.ts @@ -34,6 +34,7 @@ export class PRRefreshQueueDrainer { private readonly scheduler: PRRefreshQueueScheduler readonly scheduleVisibleFollowUp: PRRefreshQueueScheduler['scheduleVisibleFollowUp'] readonly scheduleErrorRetry: PRRefreshQueueScheduler['scheduleErrorRetry'] + readonly restoreFollowUp: PRRefreshQueueScheduler['restoreFollowUp'] constructor( private readonly queue: PRRefreshQueue, @@ -54,6 +55,7 @@ export class PRRefreshQueueDrainer { ) this.scheduleVisibleFollowUp = this.scheduler.scheduleVisibleFollowUp.bind(this.scheduler) this.scheduleErrorRetry = this.scheduler.scheduleErrorRetry.bind(this.scheduler) + this.restoreFollowUp = this.scheduler.restoreFollowUp.bind(this.scheduler) this.hostedJobs = new HostedPRReadJobs( queue, pacing, @@ -173,8 +175,9 @@ export class PRRefreshQueueDrainer { next.hosted?.finish(null) continue } - // A job retired or replaced while quota was checked never starts; the pause still holds. - if (this.hostedJobs.completeFromCache(next)) { + // A job retired or replaced, or automatic work the cadence no longer gives, while quota + // was checked never starts; the pause it learned still holds. + if (this.hostedJobs.completeFromCache(next) || this.scheduler.retired(next)) { if (pausedUntil !== null) { this.queue.protectBackgroundUntil(next.key, pausedUntil) } @@ -230,20 +233,18 @@ export class PRRefreshQueueDrainer { if (!prepared.isCurrent()) { return outcome } - const settled = - producer.retained && - outcome.kind === 'upstream-error' && - (next.hosted || this.visibility.has(next.key)) - ? this.retry.settleProducerError( - outcome, - next.key, - next.hosted - ? { ...next.candidate, isSelected: false } - : this.visibility.candidate(next.key, next.candidate), - prepared, - this.queue - ) - : outcome + // A host job's failure keeps its job's own finite lifetime, so it takes no retry claim. + const settled = this.retry.settleProducerError( + outcome, + next.key, + next.hosted + ? { ...next.candidate, isSelected: false } + : this.visibility.candidate(next.key, next.candidate), + prepared, + this.queue, + next.hosted ? { retained: producer.retained } : producer, + Boolean(next.hosted) || this.visibility.has(next.key) + ) this.events.observe(next.candidate, settled, aliases) return settled } diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts index b3a7f69abb6..e2cfbb22dfd 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue-scheduler.ts @@ -5,7 +5,7 @@ import type { } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { aliasFromCandidate, - freshRetryAt, + automaticDueAt, isBudgetedBackground, isMergeabilityPendingOutcome, sameAliasRequestIdentity, @@ -52,6 +52,9 @@ export class PRRefreshQueueScheduler { options?: { pendingMergeabilityDelayMs?: number; plannedRetryAt?: number } ): void { if (outcome.kind === 'upstream-error') { + if (this.retry.replacedFailure(outcome)) { + return + } const retryCandidate = this.visibility.candidate(key, candidate) const retryAt = Math.max( options?.plannedRetryAt ?? this.retry.nextVisibleErrorRetryAt(key, retryCandidate), @@ -77,7 +80,7 @@ export class PRRefreshQueueScheduler { return } const followUpCandidate = this.visibility.candidate(key, refreshed) - const regularDueAt = freshRetryAt(followUpCandidate) ?? Date.now() + const regularDueAt = automaticDueAt(followUpCandidate) ?? Number.POSITIVE_INFINITY const pendingDueAt = options?.pendingMergeabilityDelayMs !== undefined && isMergeabilityPendingOutcome(outcome) ? outcome.fetchedAt + options.pendingMergeabilityDelayMs @@ -111,6 +114,49 @@ export class PRRefreshQueueScheduler { this.schedule(Math.max(0, dueAt - Date.now())) } + /** Queues the automatic follow-up the current cadence gives a visible row whose timed work came + * back, due now if its data is already stale; none when the cadence gives it no timer. It stays + * an automatic follow-up while it waits, so the next Off retires it. */ + restoreFollowUp( + key: string, + candidate: GitHubPRRefreshCandidate, + priority: number, + aliases: GitHubPRRefreshAlias[], + windowId?: number + ): void { + const dueAt = automaticDueAt(candidate) + if (dueAt === null || !this.visibility.has(key)) { + return + } + this.queue.setVisibleFollowUp({ + key, + candidate, + aliases: new Map(aliases.map((alias) => [alias.cacheKey, alias])), + reason: 'visible', + priority: visibleFollowUpPriority(candidate, priority), + dueAt: Math.max(dueAt, this.queue.backgroundGateUntil(key)), + queuedAt: this.queue.nextOrder(), + followUp: true, + windowId + }) + this.schedule(Math.max(0, dueAt - Date.now())) + } + + /** Whether an automatic attempt still in its own reason (a follow-up or a failure's retry, not a + * return, an action or a forced reread) is no longer given by the current cadence; checked again + * once it has waited for quota, before it may start. */ + retired(entry: PRRefreshQueueEntry): boolean { + if (entry.reason !== 'visible' || entry.hosted || entry.watch || entry.bypassBackgroundBudget) { + return false + } + const candidate = this.visibility.candidate(entry.key, entry.candidate) + if (entry.errorRetry) { + const retryAt = this.retry.retimedVisibleErrorRetryAt(entry.key, candidate) + return retryAt === null || !Number.isFinite(retryAt) + } + return entry.followUp === true && automaticDueAt(candidate) === null + } + /** Queues the automatic retry a failure earned; it stays an error retry until it runs, is * replaced or a cadence change retires it. */ scheduleErrorRetry( diff --git a/src/main/github/pull-requests/refresh/pr-refresh-queue.ts b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts index 3339660b9c8..356673a959c 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-queue.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-queue.ts @@ -7,6 +7,7 @@ import type { } from '../../../../shared/github/pull-requests/refresh/pull-request-refresh-types' import { aliasFromCandidate, + automaticDueAt, bypassesFreshnessDelay, freshRetryAt, POST_PUSH_DELAY_MS, @@ -128,7 +129,7 @@ export class PRRefreshQueue { entry.candidate = candidateFor(entry.key, entry.candidate) entry.priority = visibleFollowUpPriority(entry.candidate, entry.priority) entry.dueAt = Math.max( - freshRetryAt(entry.candidate) ?? Date.now(), + automaticDueAt(entry.candidate) ?? Number.POSITIVE_INFINITY, this.backgroundNotBefore.get(entry.key)?.until ?? 0 ) if (!Number.isFinite(entry.dueAt)) { @@ -186,6 +187,7 @@ export class PRRefreshQueue { ) { existing.dueAt = Math.min(existing.dueAt, dueAt) existing.followUp = false + existing.errorRetry = false existing.foreground ||= exposureDueAt !== null } const shouldPromote = diff --git a/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts index 73d532aee45..e17a8c78ce1 100644 --- a/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts +++ b/src/main/github/pull-requests/refresh/pr-refresh-retry-state.ts @@ -7,8 +7,16 @@ import { getPRAutoRefreshCadence, type PRAutoRefreshCadence } from '../../../../shared/review-refresh-policy' -import { refreshIntervalForCandidate } from './pr-refresh-candidate-policy' -import type { PreparedPRBranchRead } from '../../client/lookup/pr-for-branch-outcome' +import { + aliasFromCandidate, + refreshIntervalForCandidate, + sameAliasRequestIdentity +} from './pr-refresh-candidate-policy' +import type { + PRReadSettlement, + PreparedPRBranchRead +} from '../../client/lookup/pr-for-branch-outcome' +import type { PRReadFailureHold } from '../../client/lookup/pr-branch-read-resources' import type { PRRefreshQueue } from './pr-refresh-queue' type ErrorBackoff = { @@ -18,8 +26,17 @@ type ErrorBackoff = { * that holds its key and whether a timed retry is planned; null once a newer read replaced it. */ settled?: PRRefreshOutcome retime?: () => { gate: number; timed: boolean } | null + /** The failed provider read's claim, current until a newer read of its resource starts. */ + hold?: PRReadFailureHold + /** A newer read or a scope change replaced this failure; it owes no automatic retry. */ + revoked?: boolean + /** The row as it failed; a row now reported with another HEAD or links is another request. */ + candidate?: GitHubPRRefreshCandidate } +// Failures a newer provider read of the same request had already replaced when they settled. +const superseded = new WeakSet() + export class PRRefreshRetryState { private readonly errorBackoff = new Map() private readonly manualRetryGates = new Map() @@ -29,10 +46,17 @@ export class PRRefreshRetryState { } reset(key: string): void { - this.errorBackoff.delete(key) + this.releaseFailure(key) this.manualRetryGates.delete(key) } + /** The row's demand ended (no longer visible): its failure owes nothing, though a manual + * rate-limit gate still holds. */ + releaseFailure(key: string): void { + this.errorBackoff.get(key)?.hold?.release() + this.errorBackoff.delete(key) + } + noteManualGate(key: string, outcome: PRRefreshOutcome): void { if (outcome.kind === 'upstream-error' && outcome.retryDisabledUntil !== undefined) { this.manualRetryGates.set(key, outcome.retryDisabledUntil) @@ -52,7 +76,9 @@ export class PRRefreshRetryState { candidate: GitHubPRRefreshCandidate, cadence: PRAutoRefreshCadence = getPRAutoRefreshCadence() ): number { - const failures = (this.errorBackoff.get(key)?.failures ?? 0) + 1 + const previous = this.errorBackoff.get(key) + previous?.hold?.release() + const failures = (previous?.failures ?? 0) + 1 const failedAt = Date.now() this.errorBackoff.set(key, { failures, failedAt }) return planErrorRetry(candidate, failures, failedAt, cadence) @@ -67,7 +93,9 @@ export class PRRefreshRetryState { cadence: PRAutoRefreshCadence = getPRAutoRefreshCadence() ): number | null { const state = this.errorBackoff.get(key) - return state ? planErrorRetry(candidate, state.failures, state.failedAt, cadence) : null + return state && !state.revoked + ? planErrorRetry(candidate, state.failures, state.failedAt, cadence) + : null } /** How long a failed key stays closed to background reads. Off plans no retry, yet holds the key @@ -80,6 +108,25 @@ export class PRRefreshRetryState { return state ? planErrorRetry(candidate, state.failures, state.failedAt, 'default') : Date.now() } + /** A failure a newer read of the same request had already replaced when it settled. */ + replacedFailure(outcome: PRRefreshOutcome): boolean { + return superseded.has(outcome) + } + + /** Whether the recorded failure belongs to the row as it is reported now (same HEAD and links); + * a failure of another request is released rather than restored for this one. */ + failureMatches(key: string, candidate: GitHubPRRefreshCandidate): boolean { + const failed = this.errorBackoff.get(key)?.candidate + if ( + failed && + sameAliasRequestIdentity(aliasFromCandidate(failed), aliasFromCandidate(candidate)) + ) { + return true + } + this.releaseFailure(key) + return false + } + /** Moves every retained error's shared schedule and gate to the current cadence, and returns * when each still-current failure retries under it (none under Off), from its own failure. */ retimeErrors(queue: PRRefreshQueue): Map { @@ -88,6 +135,8 @@ export class PRRefreshRetryState { const plan = state.retime?.() if (plan === null) { state.retime = undefined + state.revoked = true + state.hold?.release() } else if (plan !== undefined) { const gate = Math.max(plan.gate, this.manualGateUntil(key)) queue.protectBackgroundUntil(key, gate) @@ -127,28 +176,52 @@ export class PRRefreshRetryState { if (this.errorBackoff.get(key)?.settled === outcome) { return outcome.nextAutoRetryAt ?? Number.POSITIVE_INFINITY } + if (superseded.has(outcome)) { + return undefined + } const scheduled = getPRAutoRefreshCadence() === 'off' ? undefined : outcome.nextAutoRetryAt return scheduled ?? (visible ? this.nextVisibleErrorRetryAt(key, candidate) : undefined) } + /** + * Settles the actual provider read's failure once, before its callers continue: plans the retry + * it owes and keeps how to re-plan it. A read the exact cache kept also schedules the shared + * error there; a full read the cache refused still owes its retry through its own claim. Other + * outcomes, and reads with no demand, pass through. + */ settleProducerError( outcome: PRRefreshOutcome, key: string, candidate: GitHubPRRefreshCandidate, prepared: PreparedPRBranchRead, - queue: PRRefreshQueue + queue: PRRefreshQueue, + producer: Parameters[1] = { retained: true }, + demand = true ): PRRefreshOutcome { - const rateLimitedUntil = - outcome.kind === 'upstream-error' ? (outcome.retryDisabledUntil ?? 0) : 0 + if (outcome.kind !== 'upstream-error' || !demand || (!producer.retained && !producer.hold)) { + return outcome + } + const hold = producer.hold?.() + if (hold && !hold.current()) { + // A newer read already owns the request: this late failure owes it no retry. + hold.release() + superseded.add(outcome) + return outcome + } + const rateLimitedUntil = outcome.retryDisabledUntil ?? 0 const retryAt = this.nextVisibleErrorRetryAt(key, candidate) const state = this.errorBackoff.get(key)! const result = this.withErrorSchedule(outcome, retryAt) - prepared.scheduleError(outcome, result) + if (producer.retained) { + prepared.scheduleError(outcome, result) + } state.settled = result + state.hold = hold + state.candidate = candidate let scheduled = result // Replaces only the error this settlement scheduled; a newer read's result stays. state.retime = () => { - if (!prepared.accepts(scheduled)) { + if ((hold && !hold.current()) || (producer.retained && !prepared.accepts(scheduled))) { return null } const planned = planErrorRetry( @@ -157,10 +230,12 @@ export class PRRefreshRetryState { state.failedAt, getPRAutoRefreshCadence() ) - const next = this.withErrorSchedule(outcome, planned) - prepared.scheduleError(scheduled, next) - if (prepared.accepts(next)) { - scheduled = next + if (producer.retained) { + const next = this.withErrorSchedule(outcome, planned) + prepared.scheduleError(scheduled, next) + if (prepared.accepts(next)) { + scheduled = next + } } return { gate: Math.max(this.errorGateAt(key, candidate, planned), rateLimitedUntil),