Bound Windows PR refresh crash storms (#6203)

Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-24 00:21:56 -07:00
committed by GitHub
co-authored by Neil
parent 0c0367ea88
commit 6574e764d7
6 changed files with 644 additions and 64 deletions
@@ -184,6 +184,326 @@ describe('pr-refresh-coordinator', () => {
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2)
})
it('paces a burst of distinct active refreshes', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
await vi.advanceTimersByTimeAsync(0)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3)
expect(
getPRForBranchOutcomeMock.mock.calls.map(([repoPath, branch]) => [repoPath, branch])
).toEqual([
['/repo', 'feature/9'],
['/repo', 'feature/8'],
['/repo', 'feature/7']
])
await vi.advanceTimersByTimeAsync(29_999)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(3)
expect(
sendMock.mock.calls
.map(([, event]) => event)
.some((event) => event.reason === 'active' && event.status === 'queued')
).toBe(true)
await vi.advanceTimersByTimeAsync(1)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(6)
})
it('treats a same-key active reactivation as the latest active signal', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
await vi.advanceTimersByTimeAsync(0)
enqueuePRRefresh(
makeCandidate({
cacheKey: '/repo::feature/0',
branch: 'feature/0',
worktreeId: 'wt-0'
}),
'active',
80,
1
)
await vi.advanceTimersByTimeAsync(30_000)
expect(getPRForBranchOutcomeMock.mock.calls[3]?.[1]).toBe('feature/0')
})
it('does not let one capped active window block another window', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
enqueuePRRefresh(
makeCandidate({
cacheKey: '/repo::feature/other-window',
branch: 'feature/other-window',
worktreeId: 'wt-other-window'
}),
'active',
80,
2
)
await vi.advanceTimersByTimeAsync(0)
expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain(
'feature/other-window'
)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4)
})
it('does not let capped host active work block WSL or SSH active scopes', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
enqueuePRRefresh(
makeCandidate({
cacheKey: 'wsl::repo-1::feature/wsl',
branch: 'feature/wsl',
localGitOptions: { wslDistro: 'Ubuntu' },
worktreeId: 'wt-wsl'
}),
'active',
80,
1
)
enqueuePRRefresh(
makeCandidate({
cacheKey: 'ssh:ssh-1::repo-1::feature/ssh',
branch: 'feature/ssh',
connectionId: 'ssh-1',
worktreeId: 'wt-ssh'
}),
'active',
80,
1
)
await vi.advanceTimersByTimeAsync(0)
const startedBranches = getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])
expect(startedBranches).toContain('feature/wsl')
expect(startedBranches).toContain('feature/ssh')
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5)
})
it('does not let a capped active scope block ready visible work', async () => {
const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } =
await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
reportVisiblePRRefreshCandidates(
[
makeCandidate({
cacheKey: '/repo::feature/visible',
branch: 'feature/visible',
worktreeId: 'wt-visible'
})
],
1,
1
)
await vi.advanceTimersByTimeAsync(0)
expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain('feature/visible')
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4)
})
it('wakes for visible budget spacing before a capped active burst opens', async () => {
const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } =
await import('./pr-refresh-coordinator')
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
reportVisiblePRRefreshCandidates(
[
makeCandidate({
cacheKey: '/repo::feature/visible-first',
branch: 'feature/visible-first',
worktreeId: 'wt-visible-first'
})
],
1,
1
)
await vi.advanceTimersByTimeAsync(0)
for (let index = 0; index < 10; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
reportVisiblePRRefreshCandidates(
[
makeCandidate({
cacheKey: '/repo::feature/visible-second',
branch: 'feature/visible-second',
worktreeId: 'wt-visible-second'
})
],
2,
1
)
await vi.advanceTimersByTimeAsync(0)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4)
await vi.advanceTimersByTimeAsync(9_999)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(4)
await vi.advanceTimersByTimeAsync(1)
expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toContain(
'feature/visible-second'
)
expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(5)
})
it('does not consume active burst slots for rate-limit pauses', async () => {
const { enqueuePRRefresh } = await import('./pr-refresh-coordinator')
getRateLimitMock
.mockResolvedValueOnce({ ok: false })
.mockResolvedValueOnce({ ok: false })
.mockResolvedValueOnce({ ok: false })
.mockResolvedValue({ ok: true })
getPRForBranchOutcomeMock.mockResolvedValue({
kind: 'upstream-error',
errorType: 'unknown',
message: 'missing upstream',
fetchedAt: Date.now()
})
for (let index = 0; index < 6; index += 1) {
enqueuePRRefresh(
makeCandidate({
cacheKey: `/repo::feature/${index}`,
branch: `feature/${index}`,
worktreeId: `wt-${index}`
}),
'active',
80,
1
)
}
await vi.advanceTimersByTimeAsync(0)
const pausedEvents = sendMock.mock.calls
.map(([, event]) => event)
.filter((event) => event.status === 'paused' && event.skippedReason === 'rate-limit')
expect(pausedEvents).toHaveLength(3)
expect(getPRForBranchOutcomeMock.mock.calls.map((call) => call[1])).toEqual([
'feature/2',
'feature/1',
'feature/0'
])
})
it('preserves an active refresh queued while a visible refresh is in flight', async () => {
const { enqueuePRRefresh, reportVisiblePRRefreshCandidates } =
await import('./pr-refresh-coordinator')
+138 -14
View File
@@ -21,7 +21,9 @@ type QueueEntry = {
reason: GitHubPRRefreshReason
priority: number
dueAt: number
queuedAt: number
bypassBackgroundBudget?: boolean
activeDelayNotified?: boolean
windowId?: number
}
@@ -66,12 +68,16 @@ const POST_PUSH_DELAY_MS = 2_500
const BACKOFF_BASE_MS = 60_000
const BACKOFF_MAX_MS = 15 * 60_000
const DIAGNOSTIC_BREADCRUMB_MIN_INTERVAL_MS = 30_000
const ACTIVE_BURST_WINDOW_MS = 30_000
const ACTIVE_BURST_MAX = 3
let sequence = 0
let queueOrder = 0
let draining = false
let drainTimer: ReturnType<typeof setTimeout> | null = null
const queue = new Map<string, QueueEntry>()
const backgroundStarts: number[] = []
const activeStartsByScope = new Map<string, number[]>()
const errorBackoff = new Map<string, { failures: number; retryAt: number }>()
let lastBackgroundStartAt = 0
const visibleByWindow = new Map<number, { generation: number; keys: Set<string> }>()
@@ -123,13 +129,23 @@ function recordPRRefreshQueueDiagnostic(
})
}
export function clearVisiblePRRefreshWindow(windowId: number): void {
if (!visibleByWindow.delete(windowId)) {
return
function clearActiveBurstWindow(windowId: number): void {
const windowPrefix = `${windowId}::`
for (const scope of Array.from(activeStartsByScope.keys())) {
if (scope.startsWith(windowPrefix)) {
activeStartsByScope.delete(scope)
}
}
}
export function clearVisiblePRRefreshWindow(windowId: number): void {
const hadVisibleRefreshes = visibleByWindow.delete(windowId)
clearActiveBurstWindow(windowId)
if (hadVisibleRefreshes) {
// Why: visible follow-ups are owned by the renderer that reported them.
// If that WebContents is destroyed, no later visibility report may arrive.
removeInvisibleVisibleRefreshes()
}
// Why: visible follow-ups are owned by the renderer that reported them.
// If that WebContents is destroyed, no later visibility report may arrive.
removeInvisibleVisibleRefreshes()
}
function nextSequence(): number {
@@ -137,6 +153,11 @@ function nextSequence(): number {
return sequence
}
function nextQueueOrder(): number {
queueOrder += 1
return queueOrder
}
function broadcast(event: Omit<GitHubPRRefreshEvent, 'sequence'>, sequenceOverride?: number): void {
const payload = { ...event, sequence: sequenceOverride ?? nextSequence() } as GitHubPRRefreshEvent
for (const wc of webContents.getAllWebContents()) {
@@ -358,6 +379,7 @@ function scheduleVisibleFollowUp(
reason: 'visible',
priority,
dueAt: retryAt,
queuedAt: nextQueueOrder(),
windowId
})
// Why: this is a delayed retry, not active work; showing it as a spinner
@@ -386,6 +408,7 @@ function scheduleVisibleFollowUp(
reason: 'visible',
priority,
dueAt,
queuedAt: nextQueueOrder(),
// Why: this manual one-shot fixes GitHub's transient UNKNOWN state; visible
// spacing would otherwise delay it past the intended prompt retry window.
bypassBackgroundBudget: pendingMergeabilityDueAt !== null,
@@ -468,6 +491,80 @@ function nextBudgetDelay(): number {
return Math.max(spacingDelay, windowDelay)
}
function activeBurstScope(entry: QueueEntry): string {
const runtimeScope = entry.candidate.connectionId
? `ssh:${entry.candidate.connectionId}`
: `local:${entry.candidate.localGitOptions?.wslDistro ?? 'host'}`
return `${entry.windowId ?? 'global'}::${runtimeScope}`
}
function pruneActiveStarts(scope: string, now: number): number[] {
const activeStarts = activeStartsByScope.get(scope) ?? []
while (activeStarts.length > 0 && now - activeStarts[0] >= ACTIVE_BURST_WINDOW_MS) {
activeStarts.shift()
}
if (activeStarts.length === 0) {
activeStartsByScope.delete(scope)
} else {
activeStartsByScope.set(scope, activeStarts)
}
return activeStarts
}
function nextActiveBurstDelay(entry: QueueEntry): number {
const now = Date.now()
const activeStarts = pruneActiveStarts(activeBurstScope(entry), now)
if (activeStarts.length < ACTIVE_BURST_MAX) {
return 0
}
return Math.max(1, ACTIVE_BURST_WINDOW_MS - (now - activeStarts[0]))
}
function noteActiveStart(entry: QueueEntry): void {
const now = Date.now()
const scope = activeBurstScope(entry)
const activeStarts = pruneActiveStarts(scope, now)
activeStarts.push(now)
activeStartsByScope.set(scope, activeStarts)
}
function activeOrder(a: QueueEntry, b: QueueEntry): number {
if (a.reason !== 'active' || b.reason !== 'active') {
return 0
}
if (activeBurstScope(a) !== activeBurstScope(b)) {
return 0
}
// Why: activation churn should refresh the worktree the user lands on before
// stale transient selections from the same window/runtime scope.
return b.queuedAt - a.queuedAt
}
function entryDelay(entry: QueueEntry): number {
const activeBurstDelay = entry.reason === 'active' ? nextActiveBurstDelay(entry) : 0
if (activeBurstDelay > 0) {
return activeBurstDelay
}
return isBudgetedQueueEntry(entry) ? nextBudgetDelay() : 0
}
function isActiveBurstDelayed(entry: QueueEntry): boolean {
return entry.reason === 'active' && nextActiveBurstDelay(entry) > 0
}
function nextQueuedWakeDelay(excludedKey: string): number | null {
const now = Date.now()
let nextDelay = Number.POSITIVE_INFINITY
for (const entry of queue.values()) {
if (entry.key === excludedKey) {
continue
}
const delay = entry.dueAt > now ? entry.dueAt - now : entryDelay(entry)
nextDelay = Math.min(nextDelay, delay)
}
return Number.isFinite(nextDelay) ? Math.max(0, nextDelay) : null
}
function scheduleDrain(delay = 0): void {
if (drainTimer) {
clearTimeout(drainTimer)
@@ -484,7 +581,7 @@ function queuedEntriesByPriority(): QueueEntry[] {
const aReady = a.dueAt <= now
const bReady = b.dueAt <= now
if (aReady && bReady) {
return b.priority - a.priority || a.dueAt - b.dueAt
return b.priority - a.priority || activeOrder(a, b) || a.dueAt - b.dueAt
}
if (aReady !== bReady) {
return aReady ? -1 : 1
@@ -500,19 +597,37 @@ async function drainQueue(): Promise<void> {
draining = true
try {
while (queue.size > 0) {
const next = queuedEntriesByPriority()[0]
let next = queuedEntriesByPriority()[0]
const waitMs = next.dueAt - Date.now()
if (waitMs > 0) {
scheduleDrain(waitMs)
return
}
const budgetDelay = isBudgetedQueueEntry(next) ? nextBudgetDelay() : 0
if (budgetDelay > 0) {
diagnosticsCounters.backgroundPauses += 1
recordPRRefreshQueueDiagnostic('background-pause', next.reason)
scheduleDrain(budgetDelay)
return
let delay = entryDelay(next)
if (delay > 0) {
const runnable = queuedEntriesByPriority().find(
(entry) => entry.dueAt <= Date.now() && entryDelay(entry) === 0
)
if (runnable && runnable.key !== next.key) {
next = runnable
delay = 0
} else {
if (isActiveBurstDelayed(next) && !next.activeDelayNotified) {
next.activeDelayNotified = true
broadcast({
aliases: Array.from(next.aliases.values()),
reason: next.reason,
status: 'queued'
})
}
if (isBudgetedQueueEntry(next) && nextBudgetDelay() > 0) {
diagnosticsCounters.backgroundPauses += 1
recordPRRefreshQueueDiagnostic('background-pause', next.reason)
}
scheduleDrain(Math.min(delay, nextQueuedWakeDelay(next.key) ?? delay))
return
}
}
queue.delete(next.key)
@@ -571,6 +686,11 @@ async function drainQueue(): Promise<void> {
if (isBudgetedQueueEntry(next)) {
noteBackgroundStart()
}
if (next.reason === 'active') {
// Why: activation is high priority, but tab/worktree churn can enqueue
// many distinct active refreshes that each probe local Git.
noteActiveStart(next)
}
for (const bucket of buckets) {
noteRateLimitSpend(bucket)
}
@@ -632,11 +752,14 @@ export function enqueuePRRefresh(
const shouldPromoteExisting =
priority > existing.priority ||
isManual(reason) ||
(reason === 'active' && existing.reason === 'active') ||
(priority >= existing.priority && dueAt < existing.dueAt && bypassesFreshnessDelay(reason))
if (shouldPromoteExisting) {
existing.priority = priority
existing.reason = reason
existing.dueAt = Math.min(existing.dueAt, dueAt)
existing.queuedAt = nextQueueOrder()
existing.activeDelayNotified = false
existing.candidate = candidate
existing.windowId = windowId ?? existing.windowId
}
@@ -650,6 +773,7 @@ export function enqueuePRRefresh(
reason,
priority,
dueAt,
queuedAt: nextQueueOrder(),
windowId
})
}