diff --git a/.gitignore b/.gitignore index 7cdf33740..24595e4c7 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,7 @@ coverage/ # Benchmark run output /tools/benchmarks/results/*.json +/.bench-fixtures/ # Temp tmp/ diff --git a/package.json b/package.json index 812acb357..ca14f3fdb 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/main/diagnostics/main-thread-churn-probe.test.ts b/src/main/diagnostics/main-thread-churn-probe.test.ts new file mode 100644 index 000000000..cfc159fc1 --- /dev/null +++ b/src/main/diagnostics/main-thread-churn-probe.test.ts @@ -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({}) + }) +}) diff --git a/src/main/diagnostics/main-thread-churn-probe.ts b/src/main/diagnostics/main-thread-churn-probe.ts new file mode 100644 index 000000000..f4fe900cf --- /dev/null +++ b/src/main/diagnostics/main-thread-churn-probe.ts @@ -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 " " 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 -- 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() + +/** + * 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 { + const drained: Record = {} + 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?.() +} diff --git a/src/main/git/gh-rate-limit-breaker.test.ts b/src/main/git/gh-rate-limit-breaker.test.ts new file mode 100644 index 000000000..0975dd325 --- /dev/null +++ b/src/main/git/gh-rate-limit-breaker.test.ts @@ -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) + }) +}) diff --git a/src/main/git/gh-rate-limit-breaker.ts b/src/main/git/gh-rate-limit-breaker.ts new file mode 100644 index 000000000..94bef46ff --- /dev/null +++ b/src/main/git/gh-rate-limit-breaker.ts @@ -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 = { + search: 70_000, + core: 5 * 60_000, + graphql: 5 * 60_000 +} + +const blockedUntilMsByBucket = new Map() +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 +} diff --git a/src/main/git/runner-gh-rate-limit-breaker.test.ts b/src/main/git/runner-gh-rate-limit-breaker.test.ts new file mode 100644 index 000000000..dc22bb54f --- /dev/null +++ b/src/main/git/runner-gh-rate-limit-breaker.test.ts @@ -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: '' + }) + }) +}) diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index ec0d1d7b8..c90098453 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -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 ─────────────────────────────────────── diff --git a/src/main/git/status-upstream-probe-churn.test.ts b/src/main/git/status-upstream-probe-churn.test.ts index f5e8f06c3..49f6913e0 100644 --- a/src/main/git/status-upstream-probe-churn.test.ts +++ b/src/main/git/status-upstream-probe-churn.test.ts @@ -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')) { diff --git a/src/main/git/status.ts b/src/main/git/status.ts index e7b0d95b2..862c8c9b7 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -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() +// 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() + const effectiveUpstreamStatusCache = new Map() const effectiveUpstreamStatusInFlight = new Map>() const retiredEffectiveUpstreamStatusInFlight = new Map>() @@ -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, diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts index 3daf66943..531234322 100644 --- a/src/main/github/client-issue-source.test.ts +++ b/src/main/github/client-issue-source.test.ts @@ -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' diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index 5a281ddfc..66e728908 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -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) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 8d0030dfe..3a308a3ad 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -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 { - 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 { - 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[]).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[]).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)) { diff --git a/src/main/github/gh-cwd-repo-negative-cache.test.ts b/src/main/github/gh-cwd-repo-negative-cache.test.ts new file mode 100644 index 000000000..240711143 --- /dev/null +++ b/src/main/github/gh-cwd-repo-negative-cache.test.ts @@ -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() + }) +}) diff --git a/src/main/github/gh-cwd-repo-negative-cache.ts b/src/main/github/gh-cwd-repo-negative-cache.ts new file mode 100644 index 000000000..97a810f5e --- /dev/null +++ b/src/main/github/gh-cwd-repo-negative-cache.ts @@ -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() + +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 { + 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 { + 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() +} diff --git a/src/main/github/gh-error-classification.ts b/src/main/github/gh-error-classification.ts index b7064ef0f..2de37919d 100644 --- a/src/main/github/gh-error-classification.ts +++ b/src/main/github/gh-error-classification.ts @@ -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') || diff --git a/src/main/github/rate-limit.ts b/src/main/github/rate-limit.ts index 1108b6bd2..ad1404224 100644 --- a/src/main/github/rate-limit.ts +++ b/src/main/github/rate-limit.ts @@ -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 | 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 | null = null + export async function getRateLimit(options?: { force?: boolean }): Promise { 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 { await acquire() try { const { stdout } = await ghExecFileAsync(['api', 'rate_limit'], { encoding: 'utf-8' }) diff --git a/src/main/index.ts b/src/main/index.ts index 7d599f8df..251ea69e6 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -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({ diff --git a/src/main/updater.check-failure.test.ts b/src/main/updater.check-failure.test.ts index 2ecf0c855..1b5c1dfc7 100644 --- a/src/main/updater.check-failure.test.ts +++ b/src/main/updater.check-failure.test.ts @@ -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) + }) }) diff --git a/src/main/updater.ts b/src/main/updater.ts index 99553eadf..bc9c9d9b6 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -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()) } diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index bc935dcba..7f980ac6a 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -2839,6 +2839,10 @@ export const createGitHubSlice: StateCreator = (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 = (s return await countGitHubWorkItemsForRepo(requestContext, { query: query || undefined }) } catch { return 0 + } finally { + releaseWorkItemSlot() } }) ) diff --git a/src/shared/git-effective-upstream.ts b/src/shared/git-effective-upstream.ts index 2b99a951f..8292a9299 100644 --- a/src/shared/git-effective-upstream.ts +++ b/src/shared/git-effective-upstream.ts @@ -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 +): Promise { + 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 } : {}) diff --git a/tools/benchmarks/main-thread-jank-bench.mjs b/tools/benchmarks/main-thread-jank-bench.mjs new file mode 100644 index 000000000..4b2aeebd0 --- /dev/null +++ b/tools/benchmarks/main-thread-jank-bench.mjs @@ -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 ] + * [--exe ] [--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-