perf(source-control): stop gh rate-limit storms and idle git-status spawn churn (#7595)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -62,6 +62,7 @@ coverage/
|
||||
|
||||
# Benchmark run output
|
||||
/tools/benchmarks/results/*.json
|
||||
/.bench-fixtures/
|
||||
|
||||
# Temp
|
||||
tmp/
|
||||
|
||||
@@ -86,6 +86,7 @@
|
||||
"bench:idle-cpu": "pnpm run ensure:electron-runtime && node config/scripts/run-idle-cpu-benchmark.mjs",
|
||||
"bench:startup": "pnpm run ensure:electron-runtime && node tools/benchmarks/startup-time-bench.mjs",
|
||||
"bench:daemon-coldstart": "pnpm run ensure:electron-runtime && node tools/benchmarks/daemon-coldstart-bench.mjs",
|
||||
"bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tools/benchmarks/main-thread-jank-bench.mjs",
|
||||
"bench:compare": "node config/scripts/compare-benchmark-artifacts.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
MAIN_THREAD_DIAGNOSTICS_ENV,
|
||||
classifySubprocessCommand,
|
||||
drainSubprocessSpawnStats,
|
||||
isMainThreadDiagnosticsEnabled,
|
||||
recordSubprocessSpawn
|
||||
} from './main-thread-churn-probe'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
drainSubprocessSpawnStats()
|
||||
})
|
||||
|
||||
describe('classifySubprocessCommand', () => {
|
||||
it('uses the git subcommand, skipping global value flags', () => {
|
||||
expect(classifySubprocessCommand('git', ['-C', '/repo', 'status', '--porcelain=v2'])).toBe(
|
||||
'git status'
|
||||
)
|
||||
expect(
|
||||
classifySubprocessCommand('git', ['-c', 'core.quotepath=off', 'rev-list', '--count'])
|
||||
).toBe('git rev-list')
|
||||
expect(classifySubprocessCommand('git', ['--git-dir=/repo/.git', 'log', '--oneline'])).toBe(
|
||||
'git log'
|
||||
)
|
||||
})
|
||||
|
||||
it('normalizes absolute paths and .exe suffixes', () => {
|
||||
expect(classifySubprocessCommand('/usr/bin/git', ['status'])).toBe('git status')
|
||||
expect(classifySubprocessCommand('C:\\Program Files\\Git\\git.exe', ['fetch'])).toBe(
|
||||
'git fetch'
|
||||
)
|
||||
expect(classifySubprocessCommand('gh', ['api', 'rate_limit'])).toBe('gh api')
|
||||
})
|
||||
|
||||
it('unwraps wsl.exe-routed commands', () => {
|
||||
expect(
|
||||
classifySubprocessCommand('wsl.exe', ['-d', 'Ubuntu', '--', 'git', 'status', '--porcelain'])
|
||||
).toBe('git status')
|
||||
expect(classifySubprocessCommand('wsl.exe', ['-d', 'Ubuntu'])).toBe('wsl')
|
||||
})
|
||||
|
||||
it('falls back to the binary name when no subcommand exists', () => {
|
||||
expect(classifySubprocessCommand('rg', ['--files'])).toBe('rg')
|
||||
})
|
||||
|
||||
it('never treats positionals or git-flag values as subcommands for non-subcommand CLIs', () => {
|
||||
// rg's -C takes a number; it must not be consumed as a git-style flag
|
||||
// value, and "3"/"pattern" must not become fake subcommand buckets.
|
||||
expect(classifySubprocessCommand('rg', ['-C', '3', 'pattern'])).toBe('rg')
|
||||
expect(classifySubprocessCommand('node', ['script.js'])).toBe('node')
|
||||
})
|
||||
})
|
||||
|
||||
describe('recordSubprocessSpawn', () => {
|
||||
it('is a no-op when the diagnostics env var is unset', () => {
|
||||
vi.stubEnv(MAIN_THREAD_DIAGNOSTICS_ENV, '')
|
||||
expect(isMainThreadDiagnosticsEnabled()).toBe(false)
|
||||
recordSubprocessSpawn('git', ['status'], 1)
|
||||
expect(drainSubprocessSpawnStats()).toEqual({})
|
||||
})
|
||||
|
||||
it('aggregates count and block time per command, and drain resets', () => {
|
||||
vi.stubEnv(MAIN_THREAD_DIAGNOSTICS_ENV, '1')
|
||||
recordSubprocessSpawn('git', ['-C', '/repo', 'status'], 2)
|
||||
recordSubprocessSpawn('/usr/bin/git', ['status', '--porcelain=v2'], 4)
|
||||
recordSubprocessSpawn('git', ['rev-list', '--count'], 1.5)
|
||||
expect(drainSubprocessSpawnStats()).toEqual({
|
||||
'git status': { count: 2, blockMsTotal: 6, blockMsMax: 4 },
|
||||
'git rev-list': { count: 1, blockMsTotal: 1.5, blockMsMax: 1.5 }
|
||||
})
|
||||
expect(drainSubprocessSpawnStats()).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
import { writeStartupDiagnosticLine } from '../startup/startup-diagnostics'
|
||||
|
||||
export const MAIN_THREAD_DIAGNOSTICS_ENV = 'ORCA_MAIN_THREAD_DIAGNOSTICS'
|
||||
|
||||
// Why: 25ms mirrors event-loop-stall-probe — a timer that fires late by N ms
|
||||
// proves the main thread was blocked for N ms, which is the direct in-process
|
||||
// measurement of the macOS "Performance Diagnostics" main-thread warnings
|
||||
// reported in issue #7576.
|
||||
const TICK_MS = 25
|
||||
const REPORT_EVERY_MS = 5_000
|
||||
|
||||
export function isMainThreadDiagnosticsEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return env[MAIN_THREAD_DIAGNOSTICS_ENV] === '1'
|
||||
}
|
||||
|
||||
// Git global options that precede the subcommand. Value-taking flags must be
|
||||
// skipped together with their value to find the real subcommand.
|
||||
const GIT_VALUE_FLAGS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--exec-path'])
|
||||
|
||||
// Why: only subcommand-style CLIs get a "<binary> <subcommand>" bucket; for
|
||||
// anything else (rg, node, …) the first positional is an operand, not a
|
||||
// subcommand, and would fragment the aggregation.
|
||||
const SUBCOMMAND_BINARIES = new Set(['git', 'gh', 'glab'])
|
||||
|
||||
/**
|
||||
* Reduce a resolved spawn to a stable aggregation key like "git status" or
|
||||
* "gh api". Handles WSL wrapping (`wsl.exe -d <distro> -- git …`), absolute
|
||||
* binary paths, `.exe` suffixes, and git global flags before the subcommand.
|
||||
*/
|
||||
// Split on both separators so Windows-style paths classify correctly even
|
||||
// when the classifier itself runs in a posix test environment.
|
||||
function binaryName(command: string): string {
|
||||
const leaf = command.split(/[\\/]/).pop() ?? command
|
||||
return leaf.replace(/\.exe$/i, '').toLowerCase()
|
||||
}
|
||||
|
||||
export function classifySubprocessCommand(command: string, args: readonly string[]): string {
|
||||
let binary = binaryName(command)
|
||||
const rest = [...args]
|
||||
if (binary === 'wsl') {
|
||||
while (rest.length > 0) {
|
||||
const arg = rest.shift()
|
||||
if (arg === '--') {
|
||||
break
|
||||
}
|
||||
}
|
||||
const unwrapped = rest.shift()
|
||||
if (!unwrapped) {
|
||||
return 'wsl'
|
||||
}
|
||||
binary = binaryName(unwrapped)
|
||||
}
|
||||
if (!SUBCOMMAND_BINARIES.has(binary)) {
|
||||
return binary
|
||||
}
|
||||
let subcommand: string | null = null
|
||||
for (let i = 0; i < rest.length; i++) {
|
||||
const arg = rest[i]
|
||||
if (!arg.startsWith('-')) {
|
||||
subcommand = arg
|
||||
break
|
||||
}
|
||||
// Why: only git's global flags take a separate value; e.g. rg's -C takes
|
||||
// a number that must not be consumed as if it were a flag value.
|
||||
if (binary === 'git' && GIT_VALUE_FLAGS.has(arg)) {
|
||||
i++
|
||||
}
|
||||
}
|
||||
if (!subcommand) {
|
||||
return binary
|
||||
}
|
||||
return `${binary} ${subcommand.slice(0, 40)}`
|
||||
}
|
||||
|
||||
export type SubprocessSpawnStats = {
|
||||
count: number
|
||||
// Cumulative and worst synchronous cost of initiating the spawn (the
|
||||
// uv_spawn → posix_spawn call runs on the main thread before returning).
|
||||
blockMsTotal: number
|
||||
blockMsMax: number
|
||||
}
|
||||
|
||||
const spawnStatsByCommand = new Map<string, SubprocessSpawnStats>()
|
||||
|
||||
/**
|
||||
* Record one subprocess spawn from the main process. `blockMs` is how long
|
||||
* the synchronous spawn/execFile initiation call held the main thread.
|
||||
* No-op unless ORCA_MAIN_THREAD_DIAGNOSTICS=1.
|
||||
*/
|
||||
export function recordSubprocessSpawn(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
blockMs: number
|
||||
): void {
|
||||
if (!isMainThreadDiagnosticsEnabled()) {
|
||||
return
|
||||
}
|
||||
const key = classifySubprocessCommand(command, args)
|
||||
const stats = spawnStatsByCommand.get(key)
|
||||
if (stats) {
|
||||
stats.count++
|
||||
stats.blockMsTotal += blockMs
|
||||
stats.blockMsMax = Math.max(stats.blockMsMax, blockMs)
|
||||
} else {
|
||||
spawnStatsByCommand.set(key, { count: 1, blockMsTotal: blockMs, blockMsMax: blockMs })
|
||||
}
|
||||
}
|
||||
|
||||
export function drainSubprocessSpawnStats(): Record<string, SubprocessSpawnStats> {
|
||||
const drained: Record<string, SubprocessSpawnStats> = {}
|
||||
for (const [key, stats] of spawnStatsByCommand) {
|
||||
drained[key] = {
|
||||
count: stats.count,
|
||||
blockMsTotal: Math.round(stats.blockMsTotal * 100) / 100,
|
||||
blockMsMax: Math.round(stats.blockMsMax * 100) / 100
|
||||
}
|
||||
}
|
||||
spawnStatsByCommand.clear()
|
||||
return drained
|
||||
}
|
||||
|
||||
/**
|
||||
* Timestamped marker line for correlating a specific main-process activity
|
||||
* (e.g. an updater check) with the probe's stall windows and with macOS
|
||||
* Performance Diagnostics log entries in field captures. No-op unless
|
||||
* ORCA_MAIN_THREAD_DIAGNOSTICS=1.
|
||||
*/
|
||||
export function writeMainThreadDiagnosticMarker(marker: string): void {
|
||||
if (!isMainThreadDiagnosticsEnabled()) {
|
||||
return
|
||||
}
|
||||
writeStartupDiagnosticLine(
|
||||
`[main-thread] ${JSON.stringify({ marker, t: Math.round(performance.now()) })}`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Long-running main-process jank probe for benchmarks and field diagnosis of
|
||||
* issue #7576. Every 5s emits one `[main-thread] {json}` stderr line with the
|
||||
* window's worst event-loop stall, stall counts over 50/250ms, and drained
|
||||
* subprocess spawn stats. Unlike the startup stall probe this never stops:
|
||||
* the churn it measures (git status polling, updater retries) is steady-state.
|
||||
*/
|
||||
export function startMainThreadChurnProbe(): void {
|
||||
if (!isMainThreadDiagnosticsEnabled()) {
|
||||
return
|
||||
}
|
||||
let last = performance.now()
|
||||
let lastReport = last
|
||||
let windowMaxGapMs = 0
|
||||
let gapsOver50Ms = 0
|
||||
let gapsOver250Ms = 0
|
||||
const timer = setInterval(() => {
|
||||
const now = performance.now()
|
||||
const gap = now - last - TICK_MS
|
||||
last = now
|
||||
if (gap > windowMaxGapMs) {
|
||||
windowMaxGapMs = gap
|
||||
}
|
||||
if (gap > 50) {
|
||||
gapsOver50Ms++
|
||||
}
|
||||
if (gap > 250) {
|
||||
gapsOver250Ms++
|
||||
}
|
||||
if (now - lastReport < REPORT_EVERY_MS) {
|
||||
return
|
||||
}
|
||||
lastReport = now
|
||||
const spawns = drainSubprocessSpawnStats()
|
||||
const report = {
|
||||
t: Math.round(now),
|
||||
maxGapMs: Math.max(0, Math.round(windowMaxGapMs)),
|
||||
gapsOver50Ms,
|
||||
gapsOver250Ms,
|
||||
spawnCount: Object.values(spawns).reduce((sum, s) => sum + s.count, 0),
|
||||
spawns
|
||||
}
|
||||
windowMaxGapMs = 0
|
||||
gapsOver50Ms = 0
|
||||
gapsOver250Ms = 0
|
||||
writeStartupDiagnosticLine(`[main-thread] ${JSON.stringify(report)}`)
|
||||
}, TICK_MS)
|
||||
timer.unref?.()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
_resetGhRateLimitBreaker,
|
||||
classifyGhRateLimitBucket,
|
||||
createGhRateLimitBlockedError,
|
||||
getGhRateLimitBlockedUntilMs,
|
||||
isGhPrimaryRateLimitStderr,
|
||||
isGhRateLimitProbe,
|
||||
notifyGhPrimaryRateLimit,
|
||||
recordGhPrimaryRateLimit,
|
||||
registerGhRateLimitResetProbe
|
||||
} from './gh-rate-limit-breaker'
|
||||
|
||||
afterEach(() => {
|
||||
_resetGhRateLimitBreaker()
|
||||
})
|
||||
|
||||
describe('classifyGhRateLimitBucket', () => {
|
||||
it('classifies search API endpoints, skipping flag values', () => {
|
||||
expect(
|
||||
classifyGhRateLimitBucket([
|
||||
'api',
|
||||
'--cache',
|
||||
'120s',
|
||||
'search/issues?q=repo:a/b is:issue is:open&per_page=1',
|
||||
'--jq',
|
||||
'.total_count'
|
||||
])
|
||||
).toBe('search')
|
||||
expect(classifyGhRateLimitBucket(['search', 'prs', '--author', 'x'])).toBe('search')
|
||||
})
|
||||
|
||||
it('classifies graphql and defaults everything else to core', () => {
|
||||
expect(classifyGhRateLimitBucket(['api', 'graphql', '-f', 'query=…'])).toBe('graphql')
|
||||
expect(classifyGhRateLimitBucket(['api', 'repos/a/b/pulls?per_page=36'])).toBe('core')
|
||||
expect(classifyGhRateLimitBucket(['pr', 'list', '--limit', '36'])).toBe('core')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isGhRateLimitProbe', () => {
|
||||
it('recognizes the exempt rate_limit endpoint only', () => {
|
||||
expect(isGhRateLimitProbe(['api', 'rate_limit'])).toBe(true)
|
||||
expect(isGhRateLimitProbe(['api', '/rate_limit'])).toBe(true)
|
||||
expect(isGhRateLimitProbe(['api', 'search/issues?q=x'])).toBe(false)
|
||||
expect(isGhRateLimitProbe(['pr', 'list'])).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isGhPrimaryRateLimitStderr', () => {
|
||||
it('matches primary rate-limit 403s but not secondary limits', () => {
|
||||
expect(
|
||||
isGhPrimaryRateLimitStderr(
|
||||
'gh: API rate limit exceeded for user ID 1775218. If you reach out to GitHub Support… (HTTP 403)'
|
||||
)
|
||||
).toBe(true)
|
||||
expect(isGhPrimaryRateLimitStderr('You have exceeded a secondary rate limit.')).toBe(false)
|
||||
expect(isGhPrimaryRateLimitStderr('gh: Not Found (HTTP 404)')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('breaker state', () => {
|
||||
it('blocks until the recorded time, then expires', () => {
|
||||
const now = 1_000_000
|
||||
recordGhPrimaryRateLimit('search', now + 5_000)
|
||||
expect(getGhRateLimitBlockedUntilMs('search', now)).toBe(now + 5_000)
|
||||
expect(getGhRateLimitBlockedUntilMs('core', now)).toBeNull()
|
||||
expect(getGhRateLimitBlockedUntilMs('search', now + 5_001)).toBeNull()
|
||||
// Expiry is sticky — the entry was removed on the expired read.
|
||||
expect(getGhRateLimitBlockedUntilMs('search', now)).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the later of two recorded reset times', () => {
|
||||
const now = 1_000_000
|
||||
recordGhPrimaryRateLimit('core', now + 60_000)
|
||||
recordGhPrimaryRateLimit('core', now + 10_000)
|
||||
expect(getGhRateLimitBlockedUntilMs('core', now)).toBe(now + 60_000)
|
||||
})
|
||||
|
||||
it('notifyGhPrimaryRateLimit applies a fallback block and fires the reset probe', () => {
|
||||
const probe = vi.fn()
|
||||
registerGhRateLimitResetProbe(probe)
|
||||
notifyGhPrimaryRateLimit('search')
|
||||
expect(probe).toHaveBeenCalledWith('search')
|
||||
expect(getGhRateLimitBlockedUntilMs('search')).toBeGreaterThan(Date.now())
|
||||
})
|
||||
|
||||
it('creates an error that classifies as rate_limited, not permission_denied', () => {
|
||||
const error = createGhRateLimitBlockedError('search', Date.now() + 30_000)
|
||||
expect(error.stderr.toLowerCase()).toContain('rate limit')
|
||||
expect(error.stderr.toLowerCase()).not.toContain('403')
|
||||
expect(error.ghRateLimitBlocked).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Global circuit breaker for gh CLI primary rate limits.
|
||||
*
|
||||
* Why: a primary rate-limit 403 means every further request in that bucket
|
||||
* will fail until GitHub's reset time. Without shared state, a 90-repo
|
||||
* Tasks-page fan-out keeps spawning gh subprocesses that each take a fresh
|
||||
* 403 — burning main-thread spawn time and log noise while returning nothing
|
||||
* (the Discord "countWorkItems failed ×90" storm). This module holds
|
||||
* blocked-until state consulted by the runner before every gh spawn.
|
||||
*
|
||||
* Lives under git/ (not github/) with zero imports so both the runner and
|
||||
* the github rate-limit prober can use it without an import cycle.
|
||||
*/
|
||||
|
||||
export type GhRateLimitBucket = 'core' | 'search' | 'graphql'
|
||||
|
||||
// Why: a primary 403 does not carry the reset time. The search window resets
|
||||
// every minute; core/graphql reset hourly but blocking a full hour on a guess
|
||||
// would be too punishing, so pick a modest re-probe interval. The registered
|
||||
// reset probe (gh api rate_limit — exempt from limits) refines these to the
|
||||
// real reset time right after the breaker trips.
|
||||
const FALLBACK_BLOCK_MS: Record<GhRateLimitBucket, number> = {
|
||||
search: 70_000,
|
||||
core: 5 * 60_000,
|
||||
graphql: 5 * 60_000
|
||||
}
|
||||
|
||||
const blockedUntilMsByBucket = new Map<GhRateLimitBucket, number>()
|
||||
let resetProbe: ((bucket: GhRateLimitBucket) => void) | null = null
|
||||
|
||||
// gh api flags that take a separate value, so the endpoint arg can be found.
|
||||
const GH_API_VALUE_FLAGS = new Set([
|
||||
'--cache',
|
||||
'--jq',
|
||||
'-q',
|
||||
'--method',
|
||||
'-X',
|
||||
'--field',
|
||||
'-F',
|
||||
'--raw-field',
|
||||
'-f',
|
||||
'--header',
|
||||
'-H',
|
||||
'--hostname',
|
||||
'--input',
|
||||
'--template',
|
||||
'-t',
|
||||
'--preview',
|
||||
'-p'
|
||||
])
|
||||
|
||||
function findGhApiEndpoint(args: readonly string[]): string | null {
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const arg = args[i]
|
||||
if (!arg.startsWith('-')) {
|
||||
return arg
|
||||
}
|
||||
if (GH_API_VALUE_FLAGS.has(arg)) {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function classifyGhRateLimitBucket(args: readonly string[]): GhRateLimitBucket {
|
||||
const command = args[0]
|
||||
if (command === 'search') {
|
||||
return 'search'
|
||||
}
|
||||
if (command !== 'api') {
|
||||
return 'core'
|
||||
}
|
||||
const endpoint = findGhApiEndpoint(args)
|
||||
if (!endpoint) {
|
||||
return 'core'
|
||||
}
|
||||
const path = endpoint.replace(/^\//, '')
|
||||
if (path.startsWith('search/')) {
|
||||
return 'search'
|
||||
}
|
||||
if (path === 'graphql' || path.startsWith('graphql?')) {
|
||||
return 'graphql'
|
||||
}
|
||||
return 'core'
|
||||
}
|
||||
|
||||
/** `gh api rate_limit` is exempt from rate limits and must never be blocked —
|
||||
* it is the probe that refines the breaker's reset time. */
|
||||
export function isGhRateLimitProbe(args: readonly string[]): boolean {
|
||||
if (args[0] !== 'api') {
|
||||
return false
|
||||
}
|
||||
const endpoint = findGhApiEndpoint(args)
|
||||
return endpoint === 'rate_limit' || endpoint === '/rate_limit'
|
||||
}
|
||||
|
||||
/**
|
||||
* Primary rate-limit detection. Secondary limits ("secondary rate limit")
|
||||
* carry Retry-After and are handled by the runner's transient retry logic.
|
||||
*/
|
||||
export function isGhPrimaryRateLimitStderr(stderr: string): boolean {
|
||||
const s = stderr.toLowerCase()
|
||||
return s.includes('api rate limit exceeded') && !s.includes('secondary rate limit')
|
||||
}
|
||||
|
||||
export function recordGhPrimaryRateLimit(bucket: GhRateLimitBucket, blockedUntilMs: number): void {
|
||||
const existing = blockedUntilMsByBucket.get(bucket) ?? 0
|
||||
blockedUntilMsByBucket.set(bucket, Math.max(existing, blockedUntilMs))
|
||||
}
|
||||
|
||||
export function clearGhRateLimitBlock(bucket: GhRateLimitBucket): void {
|
||||
blockedUntilMsByBucket.delete(bucket)
|
||||
}
|
||||
|
||||
export function getGhRateLimitBlockedUntilMs(
|
||||
bucket: GhRateLimitBucket,
|
||||
nowMs: number = Date.now()
|
||||
): number | null {
|
||||
const blockedUntil = blockedUntilMsByBucket.get(bucket)
|
||||
if (blockedUntil === undefined) {
|
||||
return null
|
||||
}
|
||||
if (blockedUntil <= nowMs) {
|
||||
blockedUntilMsByBucket.delete(bucket)
|
||||
return null
|
||||
}
|
||||
return blockedUntil
|
||||
}
|
||||
|
||||
/** Register the (single) callback that refreshes precise reset times after a
|
||||
* breaker trip. Registered by the github rate-limit prober at module load. */
|
||||
export function registerGhRateLimitResetProbe(
|
||||
probe: ((bucket: GhRateLimitBucket) => void) | null
|
||||
): void {
|
||||
resetProbe = probe
|
||||
}
|
||||
|
||||
/** Called by the runner when a gh spawn came back with a primary 403. */
|
||||
export function notifyGhPrimaryRateLimit(bucket: GhRateLimitBucket): void {
|
||||
recordGhPrimaryRateLimit(bucket, Date.now() + FALLBACK_BLOCK_MS[bucket])
|
||||
try {
|
||||
resetProbe?.(bucket)
|
||||
} catch {
|
||||
// best-effort refinement; the fallback block stands
|
||||
}
|
||||
}
|
||||
|
||||
export function createGhRateLimitBlockedError(
|
||||
bucket: GhRateLimitBucket,
|
||||
blockedUntilMs: number
|
||||
): Error & { stderr: string; ghRateLimitBlocked: true } {
|
||||
const resetsIn = Math.max(1, Math.ceil((blockedUntilMs - Date.now()) / 1000))
|
||||
// Why: "rate limit" (and no "HTTP 403") so classifyGhError maps this to
|
||||
// rate_limited instead of permission_denied, matching a real gh failure.
|
||||
const message = `GitHub API rate limit exceeded (${bucket}); retrying in ~${resetsIn}s without spawning gh.`
|
||||
return Object.assign(new Error(message), {
|
||||
stderr: message,
|
||||
ghRateLimitBlocked: true as const
|
||||
})
|
||||
}
|
||||
|
||||
/** @internal — test-only */
|
||||
export function _resetGhRateLimitBreaker(): void {
|
||||
blockedUntilMsByBucket.clear()
|
||||
resetProbe = null
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { execFileMock, execFileSyncMock, spawnMock } = vi.hoisted(() => ({
|
||||
execFileMock: vi.fn(),
|
||||
execFileSyncMock: vi.fn(),
|
||||
spawnMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execFile: execFileMock,
|
||||
execFileSync: execFileSyncMock,
|
||||
spawn: spawnMock
|
||||
}))
|
||||
|
||||
import { ghExecFileAsync } from './runner'
|
||||
import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker'
|
||||
|
||||
const PRIMARY_RATE_LIMIT_STDERR =
|
||||
'gh: API rate limit exceeded for user ID 1775218. Please wait. (HTTP 403)'
|
||||
|
||||
function mockGhFailure(stderr: string): void {
|
||||
execFileMock.mockImplementation((_binary, _args, options, callback) => {
|
||||
const done = typeof options === 'function' ? options : callback
|
||||
queueMicrotask(() =>
|
||||
done(Object.assign(new Error(`Command failed: gh\n${stderr}`), { stderr }), '', stderr)
|
||||
)
|
||||
return { once: vi.fn() }
|
||||
})
|
||||
}
|
||||
|
||||
function mockGhSuccess(stdout: string): void {
|
||||
execFileMock.mockImplementation((_binary, _args, options, callback) => {
|
||||
const done = typeof options === 'function' ? options : callback
|
||||
queueMicrotask(() => done(null, stdout, ''))
|
||||
return { once: vi.fn() }
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
execFileMock.mockReset()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
_resetGhRateLimitBreaker()
|
||||
})
|
||||
|
||||
describe('ghExecFileAsync rate-limit breaker', () => {
|
||||
it('spawns once for a primary 403, then short-circuits same-bucket calls', async () => {
|
||||
mockGhFailure(PRIMARY_RATE_LIMIT_STDERR)
|
||||
await expect(
|
||||
ghExecFileAsync(['api', '--cache', '120s', 'search/issues?q=repo:a/b&per_page=1'])
|
||||
).rejects.toThrow('rate limit')
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
// The 90-repo storm case: every further search-bucket call must fail fast
|
||||
// without a subprocess.
|
||||
await expect(
|
||||
ghExecFileAsync(['api', '--cache', '120s', 'search/issues?q=repo:c/d&per_page=1'])
|
||||
).rejects.toMatchObject({ ghRateLimitBlocked: true })
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps other buckets working while one bucket is blocked', async () => {
|
||||
mockGhFailure(PRIMARY_RATE_LIMIT_STDERR)
|
||||
await expect(ghExecFileAsync(['api', 'search/issues?q=x'])).rejects.toThrow()
|
||||
mockGhSuccess('[]')
|
||||
await expect(ghExecFileAsync(['pr', 'list', '--limit', '36'])).resolves.toEqual({
|
||||
stdout: '[]',
|
||||
stderr: ''
|
||||
})
|
||||
expect(execFileMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('never blocks the exempt rate_limit probe', async () => {
|
||||
mockGhFailure(PRIMARY_RATE_LIMIT_STDERR)
|
||||
await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).rejects.toThrow()
|
||||
mockGhSuccess('{"resources":{}}')
|
||||
await expect(ghExecFileAsync(['api', 'rate_limit'])).resolves.toMatchObject({
|
||||
stdout: '{"resources":{}}'
|
||||
})
|
||||
expect(execFileMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not trip the breaker on secondary rate limits', async () => {
|
||||
mockGhFailure('gh: You have exceeded a secondary rate limit. (HTTP 403)')
|
||||
await expect(
|
||||
ghExecFileAsync(['api', 'repos/a/b/pulls'], { idempotent: false })
|
||||
).rejects.toThrow()
|
||||
mockGhSuccess('[]')
|
||||
await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).resolves.toEqual({
|
||||
stdout: '[]',
|
||||
stderr: ''
|
||||
})
|
||||
})
|
||||
})
|
||||
+47
-8
@@ -19,6 +19,15 @@ import {
|
||||
} from 'node:child_process'
|
||||
import { StringDecoder } from 'node:string_decoder'
|
||||
import { withGitSpan } from '../observability/instrumentation'
|
||||
import { recordSubprocessSpawn } from '../diagnostics/main-thread-churn-probe'
|
||||
import {
|
||||
classifyGhRateLimitBucket,
|
||||
createGhRateLimitBlockedError,
|
||||
getGhRateLimitBlockedUntilMs,
|
||||
isGhPrimaryRateLimitStderr,
|
||||
isGhRateLimitProbe,
|
||||
notifyGhPrimaryRateLimit
|
||||
} from './gh-rate-limit-breaker'
|
||||
import { getDefaultWslDistro, parseWslPath, toWindowsWslPath, type WslPathInfo } from '../wsl'
|
||||
import { getSpawnArgsForWindows, isWindowsBatchScript, resolveWindowsCommand } from '../win32-utils'
|
||||
import {
|
||||
@@ -381,6 +390,7 @@ function execFileCapture(
|
||||
}
|
||||
|
||||
try {
|
||||
const spawnStartedAt = performance.now()
|
||||
child = execFile(
|
||||
command,
|
||||
args,
|
||||
@@ -399,6 +409,7 @@ function execFileCapture(
|
||||
finish(error, stdout, stderr)
|
||||
}
|
||||
)
|
||||
recordSubprocessSpawn(command, args, performance.now() - spawnStartedAt)
|
||||
} catch (error) {
|
||||
finish(error instanceof Error ? error : new Error(String(error)))
|
||||
return
|
||||
@@ -441,12 +452,14 @@ async function spawnCommandCapture(
|
||||
let stderr = ''
|
||||
let stdoutBytes = 0
|
||||
let stderrBytes = 0
|
||||
const spawnStartedAt = performance.now()
|
||||
const child = spawn(spawnCmd, spawnArgs, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
windowsHide: true
|
||||
})
|
||||
recordSubprocessSpawn(spawnCmd, spawnArgs, performance.now() - spawnStartedAt)
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
const onAbort = (): void => {
|
||||
killSpawnedCommandTree(child)
|
||||
@@ -1033,12 +1046,19 @@ export function gitExecFileSync(
|
||||
}
|
||||
): string {
|
||||
const resolved = resolveCommand('git', args, options.cwd)
|
||||
return execFileSync(resolved.binary, resolved.args, {
|
||||
cwd: resolved.cwd,
|
||||
encoding: options.encoding ?? 'utf-8',
|
||||
stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'],
|
||||
timeout: options.timeout ?? GIT_EXEC_SYNC_TIMEOUT_MS
|
||||
}) as string
|
||||
const spawnStartedAt = performance.now()
|
||||
try {
|
||||
return execFileSync(resolved.binary, resolved.args, {
|
||||
cwd: resolved.cwd,
|
||||
encoding: options.encoding ?? 'utf-8',
|
||||
stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'],
|
||||
timeout: options.timeout ?? GIT_EXEC_SYNC_TIMEOUT_MS
|
||||
}) as string
|
||||
} finally {
|
||||
// Sync exec holds the main thread for its whole duration, so the entire
|
||||
// call is main-thread block time — the cost issue #7576 flags.
|
||||
recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1053,10 +1073,13 @@ export function gitSpawn(
|
||||
const resolved = resolveCommand('git', args, options.cwd, wslDistro, {
|
||||
useWslLoginShell: Boolean(wslDistro)
|
||||
})
|
||||
return spawn(resolved.binary, resolved.args, {
|
||||
const spawnStartedAt = performance.now()
|
||||
const child = spawn(resolved.binary, resolved.args, {
|
||||
...spawnOptions,
|
||||
cwd: resolved.cwd
|
||||
})
|
||||
recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt)
|
||||
return child
|
||||
}
|
||||
|
||||
// ─── gh CLI runners ─────────────────────────────────────────────────
|
||||
@@ -1356,6 +1379,16 @@ export async function ghExecFileAsync(
|
||||
args: string[],
|
||||
options: GhExecOptions = {}
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
// Why: while a bucket's primary rate limit is exhausted, every spawn would
|
||||
// return the same 403 — fail fast without paying the subprocess cost. The
|
||||
// rate_limit probe itself is exempt so the breaker can learn the reset time.
|
||||
const rateLimitBucket = classifyGhRateLimitBucket(args)
|
||||
if (!isGhRateLimitProbe(args)) {
|
||||
const blockedUntilMs = getGhRateLimitBlockedUntilMs(rateLimitBucket)
|
||||
if (blockedUntilMs !== null) {
|
||||
throw createGhRateLimitBlockedError(rateLimitBucket, blockedUntilMs)
|
||||
}
|
||||
}
|
||||
let resolved = resolveCommand('gh', args, options.cwd, options.wslDistro)
|
||||
let lastError: unknown
|
||||
let attemptedHostFallback = false
|
||||
@@ -1375,6 +1408,9 @@ export async function ghExecFileAsync(
|
||||
} catch (err) {
|
||||
lastError = err
|
||||
const { stderr } = extractExecError(err)
|
||||
if (isGhPrimaryRateLimitStderr(stderr)) {
|
||||
notifyGhPrimaryRateLimit(rateLimitBucket)
|
||||
}
|
||||
if (
|
||||
process.platform === 'win32' &&
|
||||
!attemptedDefaultWslFallback &&
|
||||
@@ -1554,10 +1590,13 @@ export function wslAwareSpawn(
|
||||
const resolved = resolveCommand(command, args, options.cwd, wslDistro, {
|
||||
useWslLoginShell
|
||||
})
|
||||
return spawn(resolved.binary, resolved.args, {
|
||||
const spawnStartedAt = performance.now()
|
||||
const child = spawn(resolved.binary, resolved.args, {
|
||||
...spawnOptions,
|
||||
cwd: resolved.cwd
|
||||
})
|
||||
recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt)
|
||||
return child
|
||||
}
|
||||
|
||||
// ─── Path translation helpers ───────────────────────────────────────
|
||||
|
||||
@@ -186,6 +186,90 @@ describe('getStatus missing-upstream polling churn', () => {
|
||||
expect(sameNameOriginProbeCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
// The pushed-but-untracked branch shape (issue #7576): the effective
|
||||
// upstream resolves to the same-name origin ref, and before the resolved-name
|
||||
// cache each 3s poll re-ran the whole resolution chain (~5 spawns/tick).
|
||||
function mockResolvedSameNameOrigin(revList: { failOnCall?: number } = {}): void {
|
||||
let revListCalls = 0
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('status')) {
|
||||
return {
|
||||
stdout: '# branch.oid abcdef1234567890\n# branch.head bench/feature\n'
|
||||
}
|
||||
}
|
||||
if (args[0] === 'symbolic-ref' && args.includes('HEAD')) {
|
||||
return { stdout: 'bench/feature\n' }
|
||||
}
|
||||
if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) {
|
||||
throw new Error("fatal: no upstream configured for branch 'bench/feature'")
|
||||
}
|
||||
if (isConfigListSnapshotCommand(args)) {
|
||||
return emptyGitConfigSnapshot()
|
||||
}
|
||||
if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/bench/feature')) {
|
||||
return { stdout: 'abcdef1234567890\n' }
|
||||
}
|
||||
if (args[0] === 'rev-list') {
|
||||
revListCalls++
|
||||
if (revList.failOnCall === revListCalls) {
|
||||
throw new Error('fatal: bad revision')
|
||||
}
|
||||
return { stdout: '1\t0\n' }
|
||||
}
|
||||
throw new Error(`unexpected git command: ${args.join(' ')}`)
|
||||
})
|
||||
}
|
||||
|
||||
function countCalls(predicate: (args: string[]) => boolean): number {
|
||||
return gitExecFileAsyncMock.mock.calls.filter((call) => predicate(getGitArgs(call))).length
|
||||
}
|
||||
|
||||
it('revalidates a resolved same-name upstream with a single rev-list per poll', async () => {
|
||||
mockResolvedSameNameOrigin()
|
||||
|
||||
await getStatus('/repo')
|
||||
await getStatus('/repo')
|
||||
await getStatus('/repo')
|
||||
|
||||
// Resolution chain ran once; the two later polls paid one rev-list each.
|
||||
expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(1)
|
||||
expect(countCalls((args) => args[0] === 'rev-parse' && args.includes('HEAD@{u}'))).toBe(1)
|
||||
expect(countCalls(isConfigListSnapshotCommand)).toBe(1)
|
||||
expect(
|
||||
countCalls(
|
||||
(args) => args[0] === 'rev-parse' && args.includes('refs/remotes/origin/bench/feature')
|
||||
)
|
||||
).toBe(1)
|
||||
expect(countCalls((args) => args[0] === 'rev-list')).toBe(3)
|
||||
})
|
||||
|
||||
it('re-resolves the upstream after the resolved-name cache TTL lapses', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(0)
|
||||
mockResolvedSameNameOrigin()
|
||||
|
||||
await getStatus('/repo')
|
||||
vi.setSystemTime(61_000)
|
||||
await getStatus('/repo')
|
||||
|
||||
expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(2)
|
||||
expect(countCalls((args) => args[0] === 'rev-list')).toBe(2)
|
||||
})
|
||||
|
||||
it('falls back to a full re-resolve when the cached upstream rev-list fails', async () => {
|
||||
// Second rev-list (the first revalidation attempt) fails, e.g. deleted ref.
|
||||
mockResolvedSameNameOrigin({ failOnCall: 2 })
|
||||
|
||||
await getStatus('/repo')
|
||||
const status = await getStatus('/repo')
|
||||
|
||||
// Full chain ran twice: initial resolve + the fallback after the failure.
|
||||
expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(2)
|
||||
// rev-list: initial + failed revalidate + fallback's own rev-list.
|
||||
expect(countCalls((args) => args[0] === 'rev-list')).toBe(3)
|
||||
expect(status.upstreamStatus?.hasUpstream).toBe(true)
|
||||
})
|
||||
|
||||
it('does not cache a positive configured push target signal', async () => {
|
||||
gitExecFileAsyncMock.mockImplementation(async (args: string[]) => {
|
||||
if (args.includes('status')) {
|
||||
|
||||
+65
-1
@@ -19,6 +19,7 @@ import type {
|
||||
import type { CommitMessageDraftContext } from '../../shared/commit-message-generation'
|
||||
import {
|
||||
getEffectiveGitUpstreamStatus,
|
||||
getGitUpstreamStatusForUpstreamName,
|
||||
splitRemoteBranchName
|
||||
} from '../../shared/git-effective-upstream'
|
||||
import { createGitConfigSnapshotRunner } from '../../shared/git-config-snapshot-runner'
|
||||
@@ -66,6 +67,21 @@ const SUBMODULE_PATHS_CACHE_TTL_MS = 5_000
|
||||
type SubmodulePathsCacheEntry = { paths: string[]; expiresAt: number }
|
||||
const submodulePathsCache = new Map<string, SubmodulePathsCacheEntry>()
|
||||
|
||||
// Why: the effective-upstream resolution chain (symbolic-ref + rev-parse ×2-3
|
||||
// + config snapshot) costs 4-5 subprocess spawns and only changes when branch
|
||||
// or git config changes. Ahead/behind is a pure function of the two rev-list
|
||||
// endpoints, so a recently-resolved name can be revalidated with one rev-list
|
||||
// spawn per poll tick; a failed rev-list (deleted ref) falls back to a full
|
||||
// re-resolve. Issue #7576: this path dominated idle main-process spawn churn.
|
||||
const RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS = 60_000
|
||||
|
||||
type ResolvedUpstreamNameCacheEntry = {
|
||||
upstreamName: string
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const resolvedUpstreamNameCache = new Map<string, ResolvedUpstreamNameCacheEntry>()
|
||||
|
||||
const effectiveUpstreamStatusCache = new Map<string, EffectiveUpstreamStatusCacheEntry>()
|
||||
const effectiveUpstreamStatusInFlight = new Map<string, Promise<GitUpstreamStatus>>()
|
||||
const retiredEffectiveUpstreamStatusInFlight = new Map<string, Promise<GitUpstreamStatus>>()
|
||||
@@ -80,6 +96,7 @@ function clearGitReadInvalidationState(): void {
|
||||
gitDiffReadDedupe.clear()
|
||||
statusReadsInFlight.clear()
|
||||
submodulePathsCache.clear()
|
||||
resolvedUpstreamNameCache.clear()
|
||||
}
|
||||
|
||||
export function clearSubmodulePathsCacheForTests(): void {
|
||||
@@ -508,6 +525,7 @@ export function clearEffectiveUpstreamNegativeStatusCache(identity: {
|
||||
retireEffectiveUpstreamStatusProbe(cacheKey)
|
||||
effectiveUpstreamStatusCache.delete(cacheKey)
|
||||
effectiveUpstreamStatusInFlight.delete(cacheKey)
|
||||
resolvedUpstreamNameCache.delete(cacheKey)
|
||||
effectiveUpstreamStatusWriteGeneration.set(
|
||||
cacheKey,
|
||||
(effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0) + 1
|
||||
@@ -626,7 +644,13 @@ async function readOrProbeEffectiveUpstreamStatus(
|
||||
// Why: source-control mount and root git refresh can overlap during startup.
|
||||
// Coalesce the richer upstream probe so a stable missing ref fails once.
|
||||
const writeGeneration = effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0
|
||||
const probe = probeEffectiveUpstreamStatus(worktreePath, branchName, options).then((result) => {
|
||||
const probe = probeOrRevalidateEffectiveUpstreamStatus(
|
||||
cacheKey,
|
||||
worktreePath,
|
||||
branchName,
|
||||
options,
|
||||
bypassCache
|
||||
).then((result) => {
|
||||
rememberEffectiveUpstreamStatus(
|
||||
cacheKey,
|
||||
result.status,
|
||||
@@ -649,6 +673,46 @@ async function readOrProbeEffectiveUpstreamStatus(
|
||||
}
|
||||
}
|
||||
|
||||
async function probeOrRevalidateEffectiveUpstreamStatus(
|
||||
cacheKey: string,
|
||||
worktreePath: string,
|
||||
branchName: string,
|
||||
options: GitRuntimeOptions = {},
|
||||
bypassCache = false
|
||||
): Promise<{ status: GitUpstreamStatus; probedSameNameOriginRef: boolean }> {
|
||||
const now = Date.now()
|
||||
const cached = resolvedUpstreamNameCache.get(cacheKey)
|
||||
if (cached && (bypassCache || cached.expiresAt <= now)) {
|
||||
resolvedUpstreamNameCache.delete(cacheKey)
|
||||
} else if (cached) {
|
||||
try {
|
||||
const status = await getGitUpstreamStatusForUpstreamName(
|
||||
(args) => gitExecFileAsync(args, gitOptionsForWorktree(worktreePath, options)),
|
||||
cached.upstreamName
|
||||
)
|
||||
return { status, probedSameNameOriginRef: false }
|
||||
} catch {
|
||||
// Ref deleted or repo state changed — fall through to a full re-resolve.
|
||||
resolvedUpstreamNameCache.delete(cacheKey)
|
||||
}
|
||||
}
|
||||
const result = await probeEffectiveUpstreamStatus(worktreePath, branchName, options)
|
||||
if (result.status.hasUpstream && result.status.upstreamName) {
|
||||
resolvedUpstreamNameCache.set(cacheKey, {
|
||||
upstreamName: result.status.upstreamName,
|
||||
expiresAt: Date.now() + RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS
|
||||
})
|
||||
while (resolvedUpstreamNameCache.size > MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES) {
|
||||
const oldest = resolvedUpstreamNameCache.keys().next()
|
||||
if (oldest.done) {
|
||||
break
|
||||
}
|
||||
resolvedUpstreamNameCache.delete(oldest.value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function probeEffectiveUpstreamStatus(
|
||||
worktreePath: string,
|
||||
branchName: string,
|
||||
|
||||
@@ -43,7 +43,8 @@ vi.mock('./gh-utils', async () => {
|
||||
|
||||
vi.mock('./rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: noteRateLimitSpendMock
|
||||
noteRateLimitSpend: noteRateLimitSpendMock,
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' }))
|
||||
}))
|
||||
|
||||
import { countWorkItems, getWorkItem, listWorkItems, _resetOwnerRepoCache } from './client'
|
||||
|
||||
@@ -63,7 +63,8 @@ vi.mock('../git/runner', () => ({
|
||||
|
||||
vi.mock('./rate-limit', () => ({
|
||||
rateLimitGuard: rateLimitGuardMock,
|
||||
noteRateLimitSpend: noteRateLimitSpendMock
|
||||
noteRateLimitSpend: noteRateLimitSpendMock,
|
||||
getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' }))
|
||||
}))
|
||||
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ import {
|
||||
_resetMergeQueueCacheForTests,
|
||||
_resetOwnerRepoCache
|
||||
} from './client'
|
||||
import { _resetGhCwdRepoNegativeCache } from './gh-cwd-repo-negative-cache'
|
||||
import { GITHUB_WORK_ITEMS_QUERY_MAX_BYTES } from '../../shared/github-work-items-query-bounds'
|
||||
|
||||
describe('listWorkItems', () => {
|
||||
@@ -99,6 +101,25 @@ describe('listWorkItems', () => {
|
||||
getOwnerRepoForRemoteMock.mockResolvedValue(null)
|
||||
_resetOwnerRepoCache()
|
||||
_resetMergeQueueCacheForTests()
|
||||
_resetGhCwdRepoNegativeCache()
|
||||
})
|
||||
|
||||
it('stops re-spawning gh for a repo whose cwd resolution already failed with no remotes', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValue(null)
|
||||
getOwnerRepoMock.mockResolvedValue(null)
|
||||
ghExecFileAsyncMock.mockRejectedValue(
|
||||
Object.assign(new Error('Command failed: gh pr list\nno git remotes found'), {
|
||||
stderr: 'no git remotes found'
|
||||
})
|
||||
)
|
||||
|
||||
await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found')
|
||||
// The first refresh pays the two cwd-fallback spawns (issue + pr list).
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
|
||||
await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found')
|
||||
// The second refresh is served from the negative cache — zero new spawns.
|
||||
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('runs both issue and PR GitHub searches for a mixed query and merges the results by recency', async () => {
|
||||
@@ -537,6 +558,22 @@ describe('listWorkItems', () => {
|
||||
expect(apiPath).not.toContain('-is:merged')
|
||||
})
|
||||
|
||||
it('returns zero without spawning gh when the search bucket is rate-limit blocked', async () => {
|
||||
getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' })
|
||||
rateLimitGuardMock.mockReturnValue({
|
||||
blocked: true,
|
||||
remaining: 0,
|
||||
limit: 30,
|
||||
resetAt: Math.floor(Date.now() / 1000) + 60
|
||||
} as unknown as { blocked: boolean })
|
||||
|
||||
await expect(countWorkItems('/repo-root', 'is:issue is:open')).resolves.toBe(0)
|
||||
|
||||
expect(rateLimitGuardMock).toHaveBeenCalledWith('search')
|
||||
expect(ghExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns zero for oversized count queries before resolving repo sources', async () => {
|
||||
const secret = 'main-github-work-items-secret'
|
||||
const oversizedQuery = secret + 'x'.repeat(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES)
|
||||
|
||||
@@ -73,6 +73,12 @@ import {
|
||||
type HostedReviewExecutionOptions
|
||||
} from '../source-control/hosted-review-git-options'
|
||||
import { readLocalGitConfigSignature } from './local-git-config-signature'
|
||||
import {
|
||||
getRememberedGhCwdResolutionFailure,
|
||||
isGhCwdRepoResolutionFailure,
|
||||
rememberGhCwdResolutionFailure
|
||||
} from './gh-cwd-repo-negative-cache'
|
||||
import type { GitHubRepoContext } from './github-repository-identity'
|
||||
export { _resetOwnerRepoCache } from './gh-utils'
|
||||
export {
|
||||
getIssue,
|
||||
@@ -1005,6 +1011,32 @@ async function resolvePrWorkItemSource(
|
||||
return { source, originCandidate, upstreamCandidate }
|
||||
}
|
||||
|
||||
/**
|
||||
* gh exec for calls that rely on gh's own cwd→repo resolution (no explicit
|
||||
* owner/repo). Serves a remembered deterministic resolution failure without
|
||||
* spawning, so a remote-less repo costs one gh spawn per config change/TTL
|
||||
* instead of two per Tasks refresh.
|
||||
*/
|
||||
async function ghCwdResolvedExec(
|
||||
context: GitHubRepoContext,
|
||||
args: string[],
|
||||
ghOptions: GhExecOptions
|
||||
): Promise<{ stdout: string; stderr: string }> {
|
||||
const remembered = await getRememberedGhCwdResolutionFailure(context)
|
||||
if (remembered !== null) {
|
||||
throw new Error(remembered)
|
||||
}
|
||||
try {
|
||||
return await ghExecFileAsync(args, ghOptions)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
if (isGhCwdRepoResolutionFailure(message)) {
|
||||
await rememberGhCwdResolutionFailure(context, message)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function listRecentWorkItems(
|
||||
repoPath: string,
|
||||
issueOwnerRepo: OwnerRepo | null,
|
||||
@@ -1014,7 +1046,8 @@ async function listRecentWorkItems(
|
||||
noCache?: boolean,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<PartialWorkItemsResult> {
|
||||
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
|
||||
const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions)
|
||||
const ghOptions = ghRepoExecOptions(repoContext)
|
||||
const requiresExplicitRepo = Boolean(connectionId)
|
||||
const restCacheArgs = noCache ? [] : ['--cache', '120s']
|
||||
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
|
||||
@@ -1034,7 +1067,8 @@ async function listRecentWorkItems(
|
||||
)
|
||||
: requiresExplicitRepo
|
||||
? Promise.resolve({ stdout: '[]' })
|
||||
: ghExecFileAsync(
|
||||
: ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'issue',
|
||||
'list',
|
||||
@@ -1058,7 +1092,8 @@ async function listRecentWorkItems(
|
||||
)
|
||||
: requiresExplicitRepo
|
||||
? Promise.resolve({ stdout: '[]' })
|
||||
: ghExecFileAsync(
|
||||
: ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
@@ -1130,7 +1165,8 @@ async function listRecentWorkItems(
|
||||
// effectively unusable for the feature — reject-all matches reality. If
|
||||
// non-GitHub remotes ever grow source metadata, revisit this symmetry.
|
||||
const [issuesResult, prsResult] = await Promise.all([
|
||||
ghExecFileAsync(
|
||||
ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'issue',
|
||||
'list',
|
||||
@@ -1143,7 +1179,8 @@ async function listRecentWorkItems(
|
||||
],
|
||||
ghOptions
|
||||
),
|
||||
ghExecFileAsync(
|
||||
ghCwdResolvedExec(
|
||||
repoContext,
|
||||
[
|
||||
'pr',
|
||||
'list',
|
||||
@@ -1180,7 +1217,8 @@ async function listQueriedWorkItems(
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): Promise<PartialWorkItemsResult> {
|
||||
const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
|
||||
const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions)
|
||||
const ghOptions = ghRepoExecOptions(repoContext)
|
||||
const requiresExplicitRepo = Boolean(connectionId)
|
||||
assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo })
|
||||
const hasPrOnlyFilter =
|
||||
@@ -1209,7 +1247,9 @@ async function listQueriedWorkItems(
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, ghOptions)
|
||||
const { stdout } = issueOwnerRepo
|
||||
? await ghExecFileAsync(args, ghOptions)
|
||||
: await ghCwdResolvedExec(repoContext, args, ghOptions)
|
||||
return {
|
||||
items: (JSON.parse(stdout) as Record<string, unknown>[]).map(mapIssueWorkItem)
|
||||
}
|
||||
@@ -1234,7 +1274,9 @@ async function listQueriedWorkItems(
|
||||
before
|
||||
})
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(args, ghOptions)
|
||||
const { stdout } = prOwnerRepo
|
||||
? await ghExecFileAsync(args, ghOptions)
|
||||
: await ghCwdResolvedExec(repoContext, args, ghOptions)
|
||||
const mapped = (JSON.parse(stdout) as Record<string, unknown>[]).map((item) =>
|
||||
mapPullRequestWorkItem(item, prOwnerRepo)
|
||||
)
|
||||
@@ -1398,6 +1440,9 @@ async function countWorkItemsForQuery(
|
||||
],
|
||||
ghOptions
|
||||
)
|
||||
// Why: over-counts gh cache hits, which is the safe direction — the search
|
||||
// bucket is only 30/min and the next probe corrects the estimate.
|
||||
noteRateLimitSpend('search')
|
||||
return Number.parseInt(stdout.trim(), 10) || 0
|
||||
}
|
||||
|
||||
@@ -1453,6 +1498,15 @@ export async function countWorkItems(
|
||||
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
|
||||
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
|
||||
|
||||
// Why: counts are decorative (pagination totals). The search bucket is only
|
||||
// 30/min, so a multi-repo Tasks page must stop counting when the budget is
|
||||
// gone instead of converting the remaining repos into 403 spawns. getRateLimit
|
||||
// is 30s-cached and single-flight, so priming here is one spawn per window.
|
||||
await getRateLimit()
|
||||
if (rateLimitGuard('search').blocked) {
|
||||
return 0
|
||||
}
|
||||
|
||||
await acquire()
|
||||
try {
|
||||
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { readLocalGitConfigSignatureMock } = vi.hoisted(() => ({
|
||||
readLocalGitConfigSignatureMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./local-git-config-signature', () => ({
|
||||
readLocalGitConfigSignature: readLocalGitConfigSignatureMock
|
||||
}))
|
||||
|
||||
import {
|
||||
_resetGhCwdRepoNegativeCache,
|
||||
getRememberedGhCwdResolutionFailure,
|
||||
isGhCwdRepoResolutionFailure,
|
||||
rememberGhCwdResolutionFailure
|
||||
} from './gh-cwd-repo-negative-cache'
|
||||
|
||||
const context = { repoPath: '/repo', connectionId: null }
|
||||
|
||||
afterEach(() => {
|
||||
_resetGhCwdRepoNegativeCache()
|
||||
readLocalGitConfigSignatureMock.mockReset()
|
||||
})
|
||||
|
||||
describe('isGhCwdRepoResolutionFailure', () => {
|
||||
it('matches gh cwd-resolution failures only', () => {
|
||||
expect(isGhCwdRepoResolutionFailure('Command failed: gh\nno git remotes found')).toBe(true)
|
||||
expect(
|
||||
isGhCwdRepoResolutionFailure(
|
||||
'none of the git remotes configured for this repository point to a known GitHub host'
|
||||
)
|
||||
).toBe(true)
|
||||
expect(isGhCwdRepoResolutionFailure('gh: API rate limit exceeded (HTTP 403)')).toBe(false)
|
||||
expect(isGhCwdRepoResolutionFailure('gh: Not Found (HTTP 404)')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('remembered failures', () => {
|
||||
it('serves the remembered failure while the config signature is unchanged', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-1')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBe('no git remotes found')
|
||||
})
|
||||
|
||||
it('invalidates when the git config signature changes (remote added)', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValueOnce('sig-1')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-2')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull()
|
||||
// The stale entry is gone, not just skipped.
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig-1')
|
||||
await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('separates repos and runtimes by cache key', async () => {
|
||||
readLocalGitConfigSignatureMock.mockResolvedValue('sig')
|
||||
await rememberGhCwdResolutionFailure(context, 'no git remotes found')
|
||||
await expect(
|
||||
getRememberedGhCwdResolutionFailure({ repoPath: '/other-repo', connectionId: null })
|
||||
).resolves.toBeNull()
|
||||
await expect(
|
||||
getRememberedGhCwdResolutionFailure({ repoPath: '/repo', connectionId: 'ssh-1' })
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { readLocalGitConfigSignature } from './local-git-config-signature'
|
||||
import type { GitHubRepoContext } from './github-repository-identity'
|
||||
|
||||
/**
|
||||
* Negative cache for repos where gh's cwd-based repo resolution fails
|
||||
* ("no git remotes found" etc). Orca only falls back to cwd resolution when
|
||||
* it could not resolve an owner/repo itself, so for a remote-less repo the
|
||||
* failure is deterministic — yet the Tasks page re-spawned gh for every such
|
||||
* repo on every refresh (×90 repos in the reported storm). Remember the
|
||||
* failure and re-throw it without a subprocess until the repo's git config
|
||||
* changes (signature check) or the TTL lapses.
|
||||
*/
|
||||
const NEGATIVE_CACHE_TTL_MS = 5 * 60_000
|
||||
const MAX_ENTRIES = 512
|
||||
|
||||
type NegativeCacheEntry = {
|
||||
message: string
|
||||
configSignature: string | undefined
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
const entries = new Map<string, NegativeCacheEntry>()
|
||||
|
||||
function negativeCacheKey(context: GitHubRepoContext): string {
|
||||
const runtimeKey = context.connectionId ?? `local:${context.wslDistro ?? 'host'}`
|
||||
return `${runtimeKey}\0${context.repoPath}`
|
||||
}
|
||||
|
||||
export function isGhCwdRepoResolutionFailure(text: string): boolean {
|
||||
const s = text.toLowerCase()
|
||||
return (
|
||||
s.includes('no git remotes found') ||
|
||||
s.includes('not a git repository') ||
|
||||
s.includes('unable to determine base repository') ||
|
||||
s.includes('none of the git remotes configured')
|
||||
)
|
||||
}
|
||||
|
||||
export async function getRememberedGhCwdResolutionFailure(
|
||||
context: GitHubRepoContext
|
||||
): Promise<string | null> {
|
||||
const key = negativeCacheKey(context)
|
||||
const entry = entries.get(key)
|
||||
if (!entry) {
|
||||
return null
|
||||
}
|
||||
if (entry.expiresAt <= Date.now()) {
|
||||
entries.delete(key)
|
||||
return null
|
||||
}
|
||||
// Why: adding a remote is the way out of this failure; the config signature
|
||||
// (mtime/size of the repo's git config chain) changes when that happens.
|
||||
const signature = await readLocalGitConfigSignature(context)
|
||||
if (signature !== entry.configSignature) {
|
||||
entries.delete(key)
|
||||
return null
|
||||
}
|
||||
return entry.message
|
||||
}
|
||||
|
||||
export async function rememberGhCwdResolutionFailure(
|
||||
context: GitHubRepoContext,
|
||||
message: string
|
||||
): Promise<void> {
|
||||
const configSignature = await readLocalGitConfigSignature(context)
|
||||
entries.set(negativeCacheKey(context), {
|
||||
message,
|
||||
configSignature,
|
||||
expiresAt: Date.now() + NEGATIVE_CACHE_TTL_MS
|
||||
})
|
||||
while (entries.size > MAX_ENTRIES) {
|
||||
const oldest = entries.keys().next()
|
||||
if (oldest.done) {
|
||||
break
|
||||
}
|
||||
entries.delete(oldest.value)
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal — test-only */
|
||||
export function _resetGhCwdRepoNegativeCache(): void {
|
||||
entries.clear()
|
||||
}
|
||||
@@ -4,6 +4,14 @@ import type { ClassifiedError } from '../../shared/types'
|
||||
// patterns to typed errors so callers can show user-friendly messages.
|
||||
export function classifyGhError(stderr: string): ClassifiedError {
|
||||
const s = stderr.toLowerCase()
|
||||
// Why: primary rate-limit errors also carry "HTTP 403" — check rate limit
|
||||
// first so they don't misclassify as a token-scope problem.
|
||||
if (s.includes('rate limit')) {
|
||||
return {
|
||||
type: 'rate_limited',
|
||||
message: 'GitHub rate limit hit. Try again in a few minutes.'
|
||||
}
|
||||
}
|
||||
if (s.includes('http 403') || s.includes('resource not accessible')) {
|
||||
return {
|
||||
type: 'permission_denied',
|
||||
@@ -19,12 +27,6 @@ export function classifyGhError(stderr: string): ClassifiedError {
|
||||
if (s.includes('http 422') || s.includes('validation failed')) {
|
||||
return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` }
|
||||
}
|
||||
if (s.includes('rate limit')) {
|
||||
return {
|
||||
type: 'rate_limited',
|
||||
message: 'GitHub rate limit hit. Try again in a few minutes.'
|
||||
}
|
||||
}
|
||||
if (
|
||||
s.includes('timeout') ||
|
||||
s.includes('no such host') ||
|
||||
|
||||
@@ -20,6 +20,13 @@ import type {
|
||||
} from '../../shared/types'
|
||||
import { acquire, release } from './gh-utils'
|
||||
import { ghExecFileAsync } from '../git/runner'
|
||||
import {
|
||||
clearGhRateLimitBlock,
|
||||
getGhRateLimitBlockedUntilMs,
|
||||
recordGhPrimaryRateLimit,
|
||||
registerGhRateLimitResetProbe,
|
||||
type GhRateLimitBucket
|
||||
} from '../git/gh-rate-limit-breaker'
|
||||
|
||||
// Why: GitHub explicitly states `GET /rate_limit` does NOT count against
|
||||
// any bucket, so the only reason to cache is to avoid spawning a `gh`
|
||||
@@ -93,6 +100,18 @@ export function rateLimitGuard(bucket: RateLimitBucketKind):
|
||||
limit: number
|
||||
resetAt: number
|
||||
} {
|
||||
// Why: the runner-level breaker learns about exhaustion from actual 403s,
|
||||
// which can happen long before (or without) a snapshot probe — e.g. quota
|
||||
// burned by another tool on the same account.
|
||||
const breakerBlockedUntilMs = getGhRateLimitBlockedUntilMs(bucket)
|
||||
if (breakerBlockedUntilMs !== null) {
|
||||
return {
|
||||
blocked: true,
|
||||
remaining: 0,
|
||||
limit: cached?.[bucket].limit ?? 0,
|
||||
resetAt: Math.ceil(breakerBlockedUntilMs / 1000)
|
||||
}
|
||||
}
|
||||
if (!cached) {
|
||||
return { blocked: false }
|
||||
}
|
||||
@@ -103,6 +122,11 @@ export function rateLimitGuard(bucket: RateLimitBucketKind):
|
||||
: bucket === 'graphql'
|
||||
? MIN_REMAINING_GRAPHQL
|
||||
: MIN_REMAINING_SEARCH
|
||||
// Why: a snapshot from before the bucket's reset time describes a window
|
||||
// that has already ended — fail open rather than blocking on stale data.
|
||||
if (b.resetAt * 1000 <= Date.now()) {
|
||||
return { blocked: false }
|
||||
}
|
||||
// Why: only block when we have a positive limit (limit:0 means "unknown" per
|
||||
// parseBucket fallback — don't block on missing data, that would brick the
|
||||
// app on a single bad rate_limit response).
|
||||
@@ -130,10 +154,63 @@ export function noteRateLimitSpend(bucket: RateLimitBucketKind, cost = 1): void
|
||||
}
|
||||
}
|
||||
|
||||
// Why: when the runner's breaker trips it only knows "blocked", not for how
|
||||
// long. `gh api rate_limit` is exempt from limits, so one forced probe turns
|
||||
// the fallback block into the bucket's real reset time (or clears a block
|
||||
// that a stale fallback would otherwise keep alive). Single-flight: a 90-repo
|
||||
// 403 burst must refine once, not 90 times.
|
||||
let resetRefinementInFlight: Promise<void> | null = null
|
||||
|
||||
function refineBreakerFromSnapshot(): void {
|
||||
if (resetRefinementInFlight) {
|
||||
return
|
||||
}
|
||||
resetRefinementInFlight = (async () => {
|
||||
try {
|
||||
const result = await getRateLimit({ force: true })
|
||||
if (!result.ok) {
|
||||
return
|
||||
}
|
||||
for (const bucket of ['core', 'search', 'graphql'] as GhRateLimitBucket[]) {
|
||||
const b = result.snapshot[bucket]
|
||||
if (b.limit > 0 && b.remaining <= 0) {
|
||||
recordGhPrimaryRateLimit(bucket, b.resetAt * 1000)
|
||||
} else if (b.limit > 0) {
|
||||
clearGhRateLimitBlock(bucket)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
resetRefinementInFlight = null
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
registerGhRateLimitResetProbe(() => refineBreakerFromSnapshot())
|
||||
|
||||
// Why: a 90-repo fan-out that primes the guard concurrently must resolve to
|
||||
// one `gh api rate_limit` spawn, not one per repo — the TTL cache alone can't
|
||||
// dedupe calls that all start before the first probe lands.
|
||||
let probeInFlight: Promise<GetRateLimitResult> | null = null
|
||||
|
||||
export async function getRateLimit(options?: { force?: boolean }): Promise<GetRateLimitResult> {
|
||||
if (!options?.force && cached && Date.now() - cached.fetchedAt < RATE_LIMIT_CACHE_TTL_MS) {
|
||||
return { ok: true, snapshot: cached }
|
||||
}
|
||||
if (!options?.force && probeInFlight) {
|
||||
return probeInFlight
|
||||
}
|
||||
const probe = fetchRateLimitSnapshot()
|
||||
probeInFlight = probe
|
||||
try {
|
||||
return await probe
|
||||
} finally {
|
||||
if (probeInFlight === probe) {
|
||||
probeInFlight = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRateLimitSnapshot(): Promise<GetRateLimitResult> {
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(['api', 'rate_limit'], { encoding: 'utf-8' })
|
||||
|
||||
@@ -92,6 +92,7 @@ import {
|
||||
shouldBypassSingleInstanceLock
|
||||
} from './startup/single-instance-lock'
|
||||
import { startEventLoopStallProbe } from './startup/event-loop-stall-probe'
|
||||
import { startMainThreadChurnProbe } from './diagnostics/main-thread-churn-probe'
|
||||
import {
|
||||
isStartupDiagnosticsEnabled,
|
||||
logStartupDiagnostic,
|
||||
@@ -432,6 +433,9 @@ if (startupDiagnosticsEnabled) {
|
||||
})
|
||||
startEventLoopStallProbe()
|
||||
}
|
||||
// Self-gated on ORCA_MAIN_THREAD_DIAGNOSTICS; unlike the startup probe it
|
||||
// runs for the whole session to catch steady-state churn (issue #7576).
|
||||
startMainThreadChurnProbe()
|
||||
|
||||
function focusExistingWindow(): void {
|
||||
focusExistingMainWindow({
|
||||
|
||||
@@ -217,4 +217,54 @@ describe('updater check failure handling', () => {
|
||||
await vi.advanceTimersByTimeAsync(ONE_HOUR_MS - THIRTY_SECONDS_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('backs off consecutive failing background retries instead of re-checking hourly forever', async () => {
|
||||
vi.useFakeTimers()
|
||||
makeBenignCheckFailure('Unable to find latest version on GitHub')
|
||||
|
||||
const sendMock = vi.fn()
|
||||
const mainWindow = { webContents: { send: sendMock } }
|
||||
|
||||
const { setupAutoUpdater, checkForUpdates } = await import('./updater')
|
||||
|
||||
setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() })
|
||||
checkForUpdates()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1)
|
||||
|
||||
// First retry keeps the fast 1h cadence (release-publishing windows).
|
||||
await vi.advanceTimersByTimeAsync(ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
|
||||
|
||||
// Second retry doubles to 2h: nothing at +1h, fires by +2h.
|
||||
await vi.advanceTimersByTimeAsync(ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2)
|
||||
await vi.advanceTimersByTimeAsync(ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3)
|
||||
|
||||
// Third retry doubles to 4h.
|
||||
await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3)
|
||||
await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(4)
|
||||
|
||||
// A completed check resets the backoff to the fast retry.
|
||||
autoUpdaterMock.checkForUpdates.mockImplementation(() => {
|
||||
autoUpdaterMock.emit('checking-for-update')
|
||||
queueMicrotask(() => {
|
||||
autoUpdaterMock.emit('update-not-available', { version: '1.0.51' })
|
||||
})
|
||||
return Promise.resolve(null)
|
||||
})
|
||||
checkForUpdates()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(5)
|
||||
|
||||
makeBenignCheckFailure('Unable to find latest version on GitHub')
|
||||
checkForUpdates()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(6)
|
||||
await vi.advanceTimersByTimeAsync(ONE_HOUR_MS)
|
||||
expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(7)
|
||||
})
|
||||
})
|
||||
|
||||
+25
-1
@@ -6,6 +6,7 @@ import type { UpdateCheckOptions, UpdateStatus } from '../shared/types'
|
||||
import { killAllPty } from './ipc/pty'
|
||||
import { withUpdaterSpan } from './observability/instrumentation'
|
||||
import { loadElectronAutoUpdater, type ElectronAutoUpdater } from './electron-updater-loader'
|
||||
import { writeMainThreadDiagnosticMarker } from './diagnostics/main-thread-churn-probe'
|
||||
import {
|
||||
beginMacUpdateDownload,
|
||||
deferMacQuitUntilInstallerReady,
|
||||
@@ -34,6 +35,12 @@ type ReleaseFeedPreflightResult = 'ready' | 'not-available'
|
||||
|
||||
const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000
|
||||
const AUTO_UPDATE_RETRY_INTERVAL_MS = 60 * 60 * 1000
|
||||
// Why: a persistently-failing feed (blocked domain, proxy, GHE mirror) used
|
||||
// to re-arm the retry at an exact 1h cadence forever — the recurring hourly
|
||||
// macOS Performance Diagnostics signature in issue #7576. Double the retry
|
||||
// delay per consecutive failure up to this cap; any completed check resets.
|
||||
// Release-publishing windows resolve within the first (still 1h) retry.
|
||||
const MAX_AUTO_UPDATE_RETRY_INTERVAL_MS = 6 * 60 * 60 * 1000
|
||||
const NUDGE_POLL_INTERVAL_MS = 30 * 60 * 1000
|
||||
const NUDGE_ACTIVATION_COOLDOWN_MS = 5 * 60 * 1000
|
||||
const QUIT_AND_INSTALL_DELAY_MS = 100
|
||||
@@ -384,6 +391,9 @@ function beginUpdateCheckAttempt(): number {
|
||||
updateCheckAttemptSequence += 1
|
||||
activeUpdateCheckAttemptId = updateCheckAttemptSequence
|
||||
armUpdateCheckStallTimer(activeUpdateCheckAttemptId)
|
||||
// Why: issue #7576's warnings recurred at the retry cadence; field captures
|
||||
// need a timestamp for each check attempt to confirm or rule the updater out.
|
||||
writeMainThreadDiagnosticMarker('updater-check-attempt')
|
||||
return activeUpdateCheckAttemptId
|
||||
}
|
||||
|
||||
@@ -690,7 +700,20 @@ export function getUpdateStatus(): UpdateStatus {
|
||||
return currentStatus
|
||||
}
|
||||
|
||||
let consecutiveAutomaticRetrySchedules = 0
|
||||
|
||||
function scheduleAutomaticUpdateCheck(delayMs: number): void {
|
||||
let effectiveDelayMs = delayMs
|
||||
// All retry-cadence callers (here and updater-events) pass exactly this
|
||||
// constant, so keying the backoff on it keeps one choke point instead of
|
||||
// threading a flag through seven schedule sites.
|
||||
if (delayMs === AUTO_UPDATE_RETRY_INTERVAL_MS) {
|
||||
effectiveDelayMs = Math.min(
|
||||
AUTO_UPDATE_RETRY_INTERVAL_MS * 2 ** consecutiveAutomaticRetrySchedules,
|
||||
MAX_AUTO_UPDATE_RETRY_INTERVAL_MS
|
||||
)
|
||||
consecutiveAutomaticRetrySchedules += 1
|
||||
}
|
||||
if (autoUpdateCheckTimer) {
|
||||
clearTimeout(autoUpdateCheckTimer)
|
||||
}
|
||||
@@ -700,10 +723,11 @@ function scheduleAutomaticUpdateCheck(delayMs: number): void {
|
||||
// background attempt scheduled in the main process instead of tying checks
|
||||
// to relaunches or renderer lifetime.
|
||||
runBackgroundUpdateCheck()
|
||||
}, delayMs)
|
||||
}, effectiveDelayMs)
|
||||
}
|
||||
|
||||
function recordCompletedUpdateCheck(): void {
|
||||
consecutiveAutomaticRetrySchedules = 0
|
||||
persistLastUpdateCheckAt?.(Date.now())
|
||||
}
|
||||
|
||||
|
||||
@@ -2839,6 +2839,10 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
|
||||
}
|
||||
const counts = await Promise.all(
|
||||
repos.map(async (r) => {
|
||||
// Why: same stampede cap as the item-fetch paths — without a slot,
|
||||
// a 90-repo selection dispatches 90 concurrent count IPCs before the
|
||||
// main-side rate-limit guard can see the first 403.
|
||||
await acquireWorkItemSlot()
|
||||
try {
|
||||
const requestState = get()
|
||||
const repo = findRepoForGitHubOwner(requestState, r.repoId, r.path)
|
||||
@@ -2857,6 +2861,8 @@ export const createGitHubSlice: StateCreator<AppState, [], [], GitHubSlice> = (s
|
||||
return await countGitHubWorkItemsForRepo(requestContext, { query: query || undefined })
|
||||
} catch {
|
||||
return 0
|
||||
} finally {
|
||||
releaseWorkItemSlot()
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
@@ -206,12 +206,25 @@ export async function getEffectiveGitUpstreamStatus(
|
||||
}
|
||||
}
|
||||
|
||||
const { stdout } = await runGit([
|
||||
'rev-list',
|
||||
'--left-right',
|
||||
'--count',
|
||||
`HEAD...${upstream.upstreamName}`
|
||||
])
|
||||
return getGitUpstreamStatusForUpstreamName(
|
||||
runGit,
|
||||
upstream.upstreamName,
|
||||
getBehindCommitsArePatchEquivalent
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ahead/behind status for an already-resolved upstream name. Split out so
|
||||
* callers that cached the resolution (a pure function of branch/config state)
|
||||
* can refresh the counts with a single rev-list spawn instead of re-running
|
||||
* the whole resolution chain.
|
||||
*/
|
||||
export async function getGitUpstreamStatusForUpstreamName(
|
||||
runGit: GitCommandRunner,
|
||||
upstreamName: string,
|
||||
getBehindCommitsArePatchEquivalent?: (upstreamName: string) => Promise<boolean>
|
||||
): Promise<GitUpstreamStatus> {
|
||||
const { stdout } = await runGit(['rev-list', '--left-right', '--count', `HEAD...${upstreamName}`])
|
||||
const counts = parseGitRevListAheadBehindCounts(stdout)
|
||||
if (counts.status === 'unexpected-field-count') {
|
||||
throw new Error(`Unexpected git rev-list output: ${JSON.stringify(stdout)}`)
|
||||
@@ -222,12 +235,12 @@ export async function getEffectiveGitUpstreamStatus(
|
||||
|
||||
const behindCommitsArePatchEquivalent =
|
||||
counts.ahead > 0 && counts.behind > 0 && getBehindCommitsArePatchEquivalent
|
||||
? await getBehindCommitsArePatchEquivalent(upstream.upstreamName)
|
||||
? await getBehindCommitsArePatchEquivalent(upstreamName)
|
||||
: undefined
|
||||
|
||||
return {
|
||||
hasUpstream: true,
|
||||
upstreamName: upstream.upstreamName,
|
||||
upstreamName,
|
||||
ahead: counts.ahead,
|
||||
behind: counts.behind,
|
||||
...(behindCommitsArePatchEquivalent !== undefined ? { behindCommitsArePatchEquivalent } : {})
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Orca main-thread jank / subprocess-churn benchmark (issue #7576).
|
||||
*
|
||||
* Reproduces the reporter's setup: a running app with an active git worktree
|
||||
* and the Source Control sidebar open, measured at steady state. The app is
|
||||
* launched with ORCA_MAIN_THREAD_DIAGNOSTICS=1 so the main process emits one
|
||||
* `[main-thread] {json}` stderr line every 5s containing:
|
||||
* - worst event-loop stall in the window (maxGapMs) and stall counts
|
||||
* - subprocess spawns since the last report, keyed by command
|
||||
* ("git status", "gh api", …) with the synchronous spawn-initiation cost
|
||||
* that held the main thread (blockMsTotal/blockMsMax)
|
||||
* On macOS the bench also tails the unified log for the exact
|
||||
* "Performance Diagnostics" warnings from the issue and records which process
|
||||
* emitted them, so spawn churn and OS warnings can be correlated by timestamp.
|
||||
*
|
||||
* Usage:
|
||||
* node tools/benchmarks/main-thread-jank-bench.mjs --label baseline
|
||||
* [--duration-s 120] [--warmup-s 20] [--fixture-dir <path>]
|
||||
* [--exe <path-to-packaged-Orca>] [--headless] [--no-log-stream]
|
||||
*
|
||||
* The window must stay VISIBLE during the run: git-status polling is gated on
|
||||
* document visibility, so a hidden/minimized window measures nothing.
|
||||
* --headless exists only for smoke-testing the harness itself.
|
||||
*
|
||||
* Prereq (when not using --exe): `pnpm build:electron-vite` so out/ exists.
|
||||
* Results: tools/benchmarks/results/main-thread-jank-<label>-<timestamp>.json
|
||||
*/
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { join, resolve } from 'node:path'
|
||||
|
||||
const scriptDir = import.meta.dirname
|
||||
const repoRoot = resolve(scriptDir, '..', '..')
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
label: 'run',
|
||||
durationS: 120,
|
||||
warmupS: 20,
|
||||
fixtureDir: null,
|
||||
exe: null,
|
||||
headless: false,
|
||||
logStream: process.platform === 'darwin'
|
||||
}
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const next = () => argv[++i]
|
||||
switch (argv[i]) {
|
||||
case '--label':
|
||||
args.label = next()
|
||||
break
|
||||
case '--duration-s':
|
||||
args.durationS = Number(next())
|
||||
break
|
||||
case '--warmup-s':
|
||||
args.warmupS = Number(next())
|
||||
break
|
||||
case '--fixture-dir':
|
||||
args.fixtureDir = next()
|
||||
break
|
||||
case '--exe':
|
||||
args.exe = next()
|
||||
break
|
||||
case '--headless':
|
||||
args.headless = true
|
||||
break
|
||||
case '--no-log-stream':
|
||||
args.logStream = false
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unknown argument: ${argv[i]}`)
|
||||
}
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed a userData fixture whose persisted state restores straight into the
|
||||
* churn-producing configuration: one git repo as the active worktree with the
|
||||
* Source Control sidebar open (engages the 3s interactive git-status poll).
|
||||
* The branch is pushed to a local `origin` but has NO configured upstream —
|
||||
* the shape Orca worktrees commonly have, which forces the effective-upstream
|
||||
* probe (the most spawn-heavy status path) on every poll tick.
|
||||
*/
|
||||
function ensureFixture(fixtureDir) {
|
||||
mkdirSync(fixtureDir, { recursive: true })
|
||||
const repoPath = join(fixtureDir, 'bench-repo')
|
||||
if (!existsSync(join(repoPath, '.git'))) {
|
||||
mkdirSync(repoPath, { recursive: true })
|
||||
run('git', ['init', repoPath])
|
||||
run('git', ['-C', repoPath, 'config', 'user.email', 'bench@example.com'])
|
||||
run('git', ['-C', repoPath, 'config', 'user.name', 'Bench'])
|
||||
writeFileSync(join(repoPath, 'README.md'), '# bench\n')
|
||||
run('git', ['-C', repoPath, 'add', '.'])
|
||||
run('git', ['-C', repoPath, 'commit', '-m', 'init', '--no-gpg-sign'])
|
||||
}
|
||||
const originPath = join(fixtureDir, 'bench-origin.git')
|
||||
if (!existsSync(originPath)) {
|
||||
run('git', ['init', '--bare', originPath])
|
||||
run('git', ['-C', repoPath, 'remote', 'add', 'origin', originPath])
|
||||
run('git', ['-C', repoPath, 'checkout', '-b', 'bench/feature'])
|
||||
// Push WITHOUT -u: same-name origin ref exists but no tracking config.
|
||||
run('git', ['-C', repoPath, 'push', 'origin', 'bench/feature'])
|
||||
}
|
||||
// A dirty file so every status poll parses a non-empty porcelain diff.
|
||||
writeFileSync(join(repoPath, 'dirty.txt'), `${Date.now()}\n`)
|
||||
|
||||
const repoId = 'bench-repo'
|
||||
const worktreeId = `${repoId}::${repoPath}`
|
||||
const tabId = 'bench-tab-00000'
|
||||
const state = {
|
||||
schemaVersion: 1,
|
||||
repos: [
|
||||
{
|
||||
id: repoId,
|
||||
path: repoPath,
|
||||
displayName: 'Bench Repo',
|
||||
badgeColor: '#000000',
|
||||
addedAt: 1,
|
||||
externalWorktreeVisibility: 'show'
|
||||
}
|
||||
],
|
||||
settings: {
|
||||
telemetry: {
|
||||
installId: 'main-thread-jank-bench',
|
||||
optedIn: false,
|
||||
existedBeforeTelemetryRelease: true
|
||||
}
|
||||
},
|
||||
ui: {
|
||||
lastActiveRepoId: repoId,
|
||||
lastActiveWorktreeId: worktreeId,
|
||||
rightSidebarOpen: true,
|
||||
rightSidebarTab: 'source-control'
|
||||
},
|
||||
workspaceSession: {
|
||||
activeRepoId: repoId,
|
||||
activeWorktreeId: worktreeId,
|
||||
activeTabId: tabId,
|
||||
tabsByWorktree: {
|
||||
[worktreeId]: [
|
||||
{
|
||||
id: tabId,
|
||||
ptyId: 'bench-pty-00000',
|
||||
worktreeId,
|
||||
title: 'Terminal 1',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
[tabId]: { root: null, activeLeafId: null, expandedLeafId: null }
|
||||
},
|
||||
activeTabIdByWorktree: { [worktreeId]: tabId },
|
||||
activeWorktreeIdsOnShutdown: [worktreeId],
|
||||
defaultTerminalTabsAppliedByWorktreeId: { [worktreeId]: true }
|
||||
}
|
||||
}
|
||||
writeFileSync(join(fixtureDir, 'orca-data.json'), JSON.stringify(state, null, 2))
|
||||
return repoPath
|
||||
}
|
||||
|
||||
function run(command, args) {
|
||||
const result = spawnSync(command, args, { stdio: 'ignore' })
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${command} ${args.join(' ')} failed with ${result.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
function parseMainThreadLine(line) {
|
||||
const match = /^\[main-thread\] (\{.*\})$/.exec(line)
|
||||
if (!match) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return JSON.parse(match[1])
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tail the macOS unified log for the exact warning from issue #7576. Events
|
||||
* are kept with process identity + wall-clock timestamp so they can be lined
|
||||
* up against the probe's report windows.
|
||||
*/
|
||||
function startPerfDiagnosticsLogStream(events) {
|
||||
const child = spawn(
|
||||
'log',
|
||||
[
|
||||
'stream',
|
||||
'--style',
|
||||
'ndjson',
|
||||
'--predicate',
|
||||
// The issue's "Performance Diagnostics:" prefix is the log category as
|
||||
// rendered by the CLI; the message body carries the actual warning.
|
||||
'eventMessage CONTAINS "should not be called on the main thread" OR eventMessage CONTAINS "Performance Diagnostics"'
|
||||
],
|
||||
{ stdio: ['ignore', 'pipe', 'ignore'] }
|
||||
)
|
||||
let buffer = ''
|
||||
child.stdout.setEncoding('utf-8')
|
||||
child.stdout.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
let newlineIndex = buffer.indexOf('\n')
|
||||
while (newlineIndex !== -1) {
|
||||
const line = buffer.slice(0, newlineIndex)
|
||||
buffer = buffer.slice(newlineIndex + 1)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
if (!line.startsWith('{')) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const entry = JSON.parse(line)
|
||||
events.push({
|
||||
timestamp: entry.timestamp ?? null,
|
||||
process: entry.processImagePath ?? entry.process ?? null,
|
||||
pid: entry.processID ?? null,
|
||||
message: String(entry.eventMessage ?? '').slice(0, 200)
|
||||
})
|
||||
} catch {
|
||||
// ignore malformed ndjson lines
|
||||
}
|
||||
}
|
||||
})
|
||||
child.on('error', () => {
|
||||
console.warn('[log-stream] failed to start `log stream`; continuing without it')
|
||||
})
|
||||
return child
|
||||
}
|
||||
|
||||
function killProcessTree(proc) {
|
||||
if (proc.exitCode !== null || proc.signalCode !== null) {
|
||||
return
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
spawnSync('taskkill', ['/PID', String(proc.pid), '/T', '/F'], { stdio: 'ignore' })
|
||||
} else {
|
||||
try {
|
||||
proc.kill('SIGKILL')
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function aggregate(reports) {
|
||||
const perCommand = {}
|
||||
let spawnCount = 0
|
||||
let maxGapMs = 0
|
||||
let gapsOver50Ms = 0
|
||||
let gapsOver250Ms = 0
|
||||
for (const report of reports) {
|
||||
spawnCount += report.spawnCount ?? 0
|
||||
maxGapMs = Math.max(maxGapMs, report.maxGapMs ?? 0)
|
||||
gapsOver50Ms += report.gapsOver50Ms ?? 0
|
||||
gapsOver250Ms += report.gapsOver250Ms ?? 0
|
||||
for (const [command, stats] of Object.entries(report.spawns ?? {})) {
|
||||
const entry = (perCommand[command] ??= { count: 0, blockMsTotal: 0, blockMsMax: 0 })
|
||||
entry.count += stats.count
|
||||
entry.blockMsTotal = Math.round((entry.blockMsTotal + stats.blockMsTotal) * 100) / 100
|
||||
entry.blockMsMax = Math.max(entry.blockMsMax, stats.blockMsMax)
|
||||
}
|
||||
}
|
||||
return { spawnCount, maxGapMs, gapsOver50Ms, gapsOver250Ms, perCommand }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv)
|
||||
const fixtureDir = resolve(
|
||||
args.fixtureDir ?? join(repoRoot, '.bench-fixtures', 'main-thread-jank')
|
||||
)
|
||||
const repoPath = ensureFixture(fixtureDir)
|
||||
console.log(`[fixture] userData=${fixtureDir} repo=${repoPath}`)
|
||||
|
||||
const env = {
|
||||
...process.env,
|
||||
ORCA_STARTUP_DIAGNOSTICS: '1',
|
||||
ORCA_MAIN_THREAD_DIAGNOSTICS: '1',
|
||||
ORCA_E2E_USER_DATA_DIR: fixtureDir
|
||||
}
|
||||
if (args.headless) {
|
||||
env.ORCA_E2E_HEADLESS = '1'
|
||||
console.warn(
|
||||
'[bench] --headless: visibility-gated polling will NOT engage; harness smoke test only'
|
||||
)
|
||||
}
|
||||
|
||||
const command = args.exe ?? require('electron')
|
||||
const commandArgs = args.exe ? [] : [repoRoot]
|
||||
const startedAtWallMs = Date.now()
|
||||
const child = spawn(command, commandArgs, { env, stdio: ['ignore', 'ignore', 'pipe'] })
|
||||
|
||||
const perfDiagnosticsEvents = []
|
||||
const logStreamChild = args.logStream
|
||||
? startPerfDiagnosticsLogStream(perfDiagnosticsEvents)
|
||||
: null
|
||||
|
||||
const allReports = []
|
||||
const markers = []
|
||||
const startupEvents = []
|
||||
let buffer = ''
|
||||
child.stderr.setEncoding('utf-8')
|
||||
child.stderr.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
let newlineIndex = buffer.indexOf('\n')
|
||||
while (newlineIndex !== -1) {
|
||||
const line = buffer.slice(0, newlineIndex).trimEnd()
|
||||
buffer = buffer.slice(newlineIndex + 1)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
const report = parseMainThreadLine(line)
|
||||
if (report) {
|
||||
// Marker lines (e.g. updater-check-attempt) timestamp one-off
|
||||
// activities for correlation; they are not 5s report windows.
|
||||
if (report.marker) {
|
||||
markers.push({ ...report, wallMs: Date.now() })
|
||||
} else {
|
||||
allReports.push({ ...report, wallMs: Date.now() })
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (line.startsWith('[startup] ')) {
|
||||
startupEvents.push({ line, wallMs: Date.now() })
|
||||
}
|
||||
}
|
||||
})
|
||||
let exitedEarly = false
|
||||
child.on('exit', () => {
|
||||
exitedEarly = true
|
||||
})
|
||||
|
||||
const totalMs = (args.warmupS + args.durationS) * 1000
|
||||
console.log(
|
||||
`[bench] pid=${child.pid} warming up ${args.warmupS}s, then measuring ${args.durationS}s…`
|
||||
)
|
||||
await new Promise((resolvePromise) => setTimeout(resolvePromise, totalMs))
|
||||
|
||||
const measureStartWallMs = startedAtWallMs + args.warmupS * 1000
|
||||
const reports = allReports.filter((report) => report.wallMs >= measureStartWallMs)
|
||||
killProcessTree(child)
|
||||
if (logStreamChild) {
|
||||
killProcessTree(logStreamChild)
|
||||
}
|
||||
if (exitedEarly) {
|
||||
console.error('[bench] app exited before the measurement window completed')
|
||||
}
|
||||
|
||||
const totals = aggregate(reports)
|
||||
const measuredMinutes = args.durationS / 60
|
||||
const result = {
|
||||
label: args.label,
|
||||
capturedAt: new Date(startedAtWallMs).toISOString(),
|
||||
platform: process.platform,
|
||||
config: { ...args, fixtureDir },
|
||||
outcome: exitedEarly ? 'early-exit' : 'ok',
|
||||
measuredDurationS: args.durationS,
|
||||
reportCount: reports.length,
|
||||
totals: {
|
||||
...totals,
|
||||
spawnsPerMinute: Math.round((totals.spawnCount / Math.max(measuredMinutes, 0.01)) * 10) / 10
|
||||
},
|
||||
perfDiagnostics: {
|
||||
enabled: Boolean(logStreamChild),
|
||||
totalCount: perfDiagnosticsEvents.length,
|
||||
byProcess: perfDiagnosticsEvents.reduce((acc, event) => {
|
||||
const key = event.process ?? 'unknown'
|
||||
acc[key] = (acc[key] ?? 0) + 1
|
||||
return acc
|
||||
}, {}),
|
||||
events: perfDiagnosticsEvents.slice(0, 200)
|
||||
},
|
||||
reports,
|
||||
markers,
|
||||
startupEvents: startupEvents.map((event) => event.line)
|
||||
}
|
||||
|
||||
const resultsDir = join(scriptDir, 'results')
|
||||
mkdirSync(resultsDir, { recursive: true })
|
||||
const outPath = join(
|
||||
resultsDir,
|
||||
`main-thread-jank-${args.label}-${new Date(startedAtWallMs).toISOString().replace(/[:.]/g, '-')}.json`
|
||||
)
|
||||
writeFileSync(outPath, JSON.stringify(result, null, 2))
|
||||
|
||||
console.log(`\n[bench] label=${args.label} outcome=${result.outcome}`)
|
||||
console.log(` reports: ${reports.length} (5s windows over ${args.durationS}s)`)
|
||||
console.log(
|
||||
` spawns: ${totals.spawnCount} total, ${result.totals.spawnsPerMinute}/min` +
|
||||
` worst event-loop stall: ${totals.maxGapMs}ms` +
|
||||
` stalls >50ms: ${totals.gapsOver50Ms}, >250ms: ${totals.gapsOver250Ms}`
|
||||
)
|
||||
const topCommands = Object.entries(totals.perCommand).sort((a, b) => b[1].count - a[1].count)
|
||||
for (const [commandKey, stats] of topCommands.slice(0, 10)) {
|
||||
console.log(
|
||||
` ${commandKey}: ${stats.count} spawns, block ${stats.blockMsTotal}ms total / ${stats.blockMsMax}ms max`
|
||||
)
|
||||
}
|
||||
if (logStreamChild) {
|
||||
const byProcessSummary = perfDiagnosticsEvents.length
|
||||
? ` (${Object.entries(result.perfDiagnostics.byProcess)
|
||||
.map(([proc, count]) => `${proc.split('/').pop()}: ${count}`)
|
||||
.join(', ')})`
|
||||
: ''
|
||||
console.log(
|
||||
` macOS Performance Diagnostics log entries: ${perfDiagnosticsEvents.length}${byProcessSummary}`
|
||||
)
|
||||
}
|
||||
console.log(` results: ${outPath}`)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error)
|
||||
process.exit(1)
|
||||
})
|
||||
Reference in New Issue
Block a user