Files
orca/src/main/git/command-runner/git-admission-span.test.ts
T
Brennan BensonandMerge Sim b5a85890ac perf(git): bound git subprocess execution with an atomic admission scheduler (#16874)
* perf(git): bound git subprocess execution with an atomic admission scheduler

Field traces (#16038, #11363) show Windows freeze storms driven by unbounded
concurrent git children (12+ at once, 50-65s status convoys for 25+ minutes).
Admit every main-process git child against atomic per-budget base+headroom
counters (general / network / per-route), with reserved interactive capacity,
ordering-only aging, close-bound permit release, a 120s fail-safe read timeout
that feeds scheduler backoff, tier plumbing through every option carrier, and
coalesced+jittered visibility pollers. Killswitch: ORCA_GIT_ADMISSION_DISABLED=1.

Storm harness A/B: max concurrent children 65 -> 6, interactive p95 791ms -> 88ms;
output-parity battery byte-identical with admission on vs off.

* test(git): run the admission output-parity battery on every platform

Parity needs real git, not the storm harness's PATH stub, so it must not share
that file's POSIX gate - Windows is the platform where parity evidence matters.

* fix(git): preserve interactive admission invariants

* perf(git): keep admission queue drains linear

* fix(git): close final admission gaps

* perf(git): bound eligible route selection

* fix(merge): remove unrelated stale snapshot changes

* fix(git): preserve refresh lifecycle authority

* test(git): align admission lifetime contracts

* fix(git): harden admission across runtime paths

* fix(git): restore freshness for bulk status reads

* test(git): repoint delete-dialog source pins after admission plumbing

The hydration effect now orders its targets through
orderDeleteWorktreeStatusHydrationTargets and passes includeLineStats
alongside the abort signal, so both literal anchors stopped matching.
The invariants are unchanged and still pinned: dropping the signal, the
main-worktree/folder filter, or getState-instead-of-subscribe each
still reddens this test.

* Fix git admission tier propagation and lock ordering

Decode optional Git status tiers permissively and default runtime RPC status reads to the status lane while preserving renderer caller intent.

Acquire the FETCH_HEAD mutex before atomic admission so same-repository fetch waiters hold no global or route permits.

Preserve automatic pull-request refresh reasons, keep explicit hosted-review refreshes interactive, remove the dead candidate tier, and keep relay scheduling unchanged.

Use tier-aware status lease keys because a shared lease cannot be safely promoted after its admission request is queued or granted.

* test: align expectations with admission plumbing

* refactor(child-process): move the process contract types to process-spec

run-process.ts crossed its line cap after gaining the termination observer;
the public types and defaults move out with re-exports so no caller changes.

* chore: restore pnpm-lock.yaml to main (unintended local drift)

---------

Co-authored-by: Merge Sim <sim@local>
2026-08-30 14:19:05 -07:00

169 lines
5.5 KiB
TypeScript

import { EventEmitter } from 'node:events'
import type { ChildProcess } from 'node:child_process'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { execFileMock, spawnMock, span, withGitSpanMock, startGitSpanMock } = vi.hoisted(() => {
const span = {
setAttribute: vi.fn(),
end: vi.fn(),
fail: vi.fn()
}
return {
execFileMock: vi.fn(),
spawnMock: vi.fn(),
span,
withGitSpanMock: vi.fn(async (_attributes: unknown, run: (value: typeof span) => unknown) => {
try {
const result = await run(span)
span.end()
return result
} catch (error) {
span.fail(error)
throw error
}
}),
startGitSpanMock: vi.fn(() => span)
}
})
vi.mock('node:child_process', async (importOriginal) => ({
...(await importOriginal()),
execFile: execFileMock,
spawn: spawnMock
}))
vi.mock('../../observability/instrumentation', () => ({
withGitSpan: withGitSpanMock,
startGitSpan: startGitSpanMock
}))
import { gitExecFileAsync, gitExecFileAsyncBuffer } from './git-exec-file'
import { withGitAdmission } from './git-spawn'
import { gitStreamStdout } from './git-stream-stdout'
import {
GitAdmissionScheduler,
_gitAdmissionSnapshotForTests,
_resetGitAdmissionForTests
} from './git-subprocess-admission'
type ExecCallback = (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void
function mockChild(): ChildProcess {
const child = new EventEmitter() as EventEmitter & Record<string, unknown>
child.pid = 1234
child.kill = vi.fn(() => true)
child.stdin = Object.assign(new EventEmitter(), { end: vi.fn() })
child.stdout = new EventEmitter()
child.stderr = new EventEmitter()
return child as unknown as ChildProcess
}
async function queueBehindBlocker(): Promise<{
release: () => void
advance: () => void
}> {
let now = 0
const scheduler = new GitAdmissionScheduler({
generalCap: 1,
generalHeadroom: 0,
now: () => now
})
_resetGitAdmissionForTests(scheduler)
const blocker = await scheduler.acquire({ args: ['status'], cwd: '/blocker' })
return {
release: blocker.release,
advance: () => {
now = 37
}
}
}
async function releaseQueued(blocker: { release: () => void; advance: () => void }): Promise<void> {
await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1))
blocker.advance()
blocker.release()
}
describe('git admission span coverage', () => {
beforeEach(() => {
execFileMock.mockReset()
spawnMock.mockReset()
span.setAttribute.mockReset()
span.end.mockReset()
span.fail.mockReset()
withGitSpanMock.mockClear()
startGitSpanMock.mockClear()
})
afterEach(() => _resetGitAdmissionForTests())
it('records queue wait for string exec inside its span', async () => {
const blocker = await queueBehindBlocker()
const child = mockChild()
let callback: ExecCallback | undefined
execFileMock.mockImplementation(
(_command: string, _args: string[], _options: unknown, received: ExecCallback) => {
callback = received
return child
}
)
const pending = gitExecFileAsync(['status'], { cwd: '/repo' })
await releaseQueued(blocker)
await vi.waitFor(() => expect(callback).toBeTypeOf('function'))
child.emit('close', 0, null)
callback?.(null, 'ok', '')
await expect(pending).resolves.toEqual({ stdout: 'ok', stderr: '' })
expect(span.setAttribute).toHaveBeenCalledWith('git.queue_wait_ms', 37)
expect(span.end).toHaveBeenCalledOnce()
})
it('records queue wait for buffer exec inside its span', async () => {
const blocker = await queueBehindBlocker()
const child = mockChild()
let callback: ExecCallback | undefined
execFileMock.mockImplementation(
(_command: string, _args: string[], _options: unknown, received: ExecCallback) => {
callback = received
return child
}
)
const pending = gitExecFileAsyncBuffer(['show', 'HEAD:file'], { cwd: '/repo' })
await releaseQueued(blocker)
await vi.waitFor(() => expect(callback).toBeTypeOf('function'))
child.emit('close', 0, null)
callback?.(null, Buffer.from('blob'), Buffer.alloc(0))
await expect(pending).resolves.toEqual({ stdout: Buffer.from('blob') })
expect(span.setAttribute).toHaveBeenCalledWith('git.queue_wait_ms', 37)
expect(span.end).toHaveBeenCalledOnce()
})
it('records queue wait for stream exec inside its span', async () => {
const blocker = await queueBehindBlocker()
const child = mockChild()
spawnMock.mockReturnValue(child)
const pending = gitStreamStdout(['status'], { cwd: '/repo', onStdout: () => {} })
await releaseQueued(blocker)
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledOnce())
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({ stoppedEarly: false })
expect(span.setAttribute).toHaveBeenCalledWith('git.queue_wait_ms', 37)
expect(span.end).toHaveBeenCalledOnce()
})
it('keeps the manual spawn span open through queue wait and child close', async () => {
const blocker = await queueBehindBlocker()
const child = mockChild()
const pending = withGitAdmission(['status'], { cwd: '/repo' }, () => child)
await releaseQueued(blocker)
await expect(pending).resolves.toBe(child)
expect(span.setAttribute).toHaveBeenCalledWith('git.queue_wait_ms', 37)
expect(span.end).not.toHaveBeenCalled()
child.emit('close', 0, null)
expect(span.end).toHaveBeenCalledOnce()
expect(span.fail).not.toHaveBeenCalled()
})
})