Files
orca/src/main/ipc/filesystem-search-git.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

227 lines
7.1 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from 'vitest'
const { gitSpawnMock } = vi.hoisted(() => ({
gitSpawnMock: vi.fn()
}))
vi.mock('../git/runner', () => ({
gitSpawnAfterWindowsEnvironmentReady: gitSpawnMock
}))
import { searchWithGitGrep } from './filesystem-search-git'
import { EventEmitter } from 'node:events'
import type { ChildProcess } from 'node:child_process'
function createMockProcess(): ChildProcess {
const p = new EventEmitter() as unknown as ChildProcess
;(p as unknown as Record<string, unknown>).stdout = new EventEmitter()
;(
(p as unknown as Record<string, unknown>).stdout as EventEmitter & {
setEncoding: () => void
}
).setEncoding = vi.fn()
;(p as unknown as Record<string, unknown>).stderr = new EventEmitter()
;(p as unknown as Record<string, unknown>).kill = vi.fn()
return p
}
describe('filesystem-search-git', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('parses git grep output and finds matches', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'hello', rootPath: '/mock/root' }, 100)
setTimeout(() => {
;(proc.stdout as unknown as EventEmitter).emit(
'data',
'src/index.ts\x005\x00 console.log("hello world")\n'
)
;(proc.stdout as unknown as EventEmitter).emit(
'data',
'src/main.ts\x0012\x00 return "hello"\n'
)
proc.emit('close')
}, 10)
const result = await promise
expect(result.files).toHaveLength(2)
expect(result.totalMatches).toBe(2)
expect(result.truncated).toBe(false)
expect(result.files[0].relativePath).toBe('src/index.ts')
expect(result.files[0].matchCount).toBe(1)
expect(result.files[0].matches[0]).toEqual({
line: 5,
column: 16,
matchLength: 5,
lineContent: ' console.log("hello world")'
})
expect(result.files[1].relativePath).toBe('src/main.ts')
expect(result.files[1].matchCount).toBe(1)
expect(result.files[1].matches[0].line).toBe(12)
})
it('finds multiple matches per line', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'ab', rootPath: '/mock/root' }, 100)
setTimeout(() => {
;(proc.stdout as unknown as EventEmitter).emit('data', 'file.txt\x001\x00ab cd ab ef ab\n')
proc.emit('close')
}, 10)
const result = await promise
expect(result.files).toHaveLength(1)
expect(result.totalMatches).toBe(3)
expect(result.files[0].matchCount).toBe(3)
expect(result.files[0].matches).toEqual([
{ line: 1, column: 1, matchLength: 2, lineContent: 'ab cd ab ef ab' },
{ line: 1, column: 7, matchLength: 2, lineContent: 'ab cd ab ef ab' },
{ line: 1, column: 13, matchLength: 2, lineContent: 'ab cd ab ef ab' }
])
})
it('respects maxResults and sets truncated', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'x', rootPath: '/mock/root' }, 2)
setTimeout(() => {
;(proc.stdout as unknown as EventEmitter).emit(
'data',
'a.ts\x001\x00x\n' + 'b.ts\x001\x00x\n' + 'c.ts\x001\x00x\n'
)
proc.emit('close')
}, 10)
const result = await promise
expect(result.totalMatches).toBe(2)
expect(result.truncated).toBe(true)
expect(result.files.map((file) => file.matchCount)).toEqual([1, 1])
})
it('passes correct flags for case-insensitive fixed-string search', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep(
'/mock/root',
{ query: 'test', rootPath: '/mock/root', caseSensitive: false, useRegex: false },
100,
{ wslDistro: 'Ubuntu' }
)
setTimeout(() => proc.emit('close'), 10)
await promise
const gitArgs = gitSpawnMock.mock.calls[0][0] as string[]
expect(gitArgs).toContain('-i')
expect(gitArgs).toContain('--fixed-strings')
expect(gitArgs).not.toContain('--extended-regexp')
expect(gitSpawnMock.mock.calls[0][1]).toEqual(
expect.objectContaining({ admissionTier: 'interactive', wslDistro: 'Ubuntu' })
)
})
it('passes correct flags for regex whole-word search', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep(
'/mock/root',
{
query: 'foo',
rootPath: '/mock/root',
caseSensitive: true,
useRegex: true,
wholeWord: true
},
100
)
setTimeout(() => proc.emit('close'), 10)
await promise
const gitArgs = gitSpawnMock.mock.calls[0][0] as string[]
expect(gitArgs).toContain('-w')
expect(gitArgs).toContain('--extended-regexp')
expect(gitArgs).not.toContain('-i')
expect(gitArgs).not.toContain('--fixed-strings')
})
it('returns empty result when git grep spawn fails', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'test', rootPath: '/mock/root' }, 100)
setTimeout(() => proc.emit('error', new Error('spawn git ENOENT')), 10)
const result = await promise
expect(result.files).toHaveLength(0)
expect(result.totalMatches).toBe(0)
})
it('settles and detaches when git grep ignores the timeout kill', async () => {
vi.useFakeTimers()
try {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'ok', rootPath: '/mock/root' }, 100)
await vi.waitFor(() =>
expect((proc.stdout as unknown as EventEmitter).listenerCount('data')).toBeGreaterThan(0)
)
;(proc.stdout as unknown as EventEmitter).emit('data', 'valid.ts\x001\x00ok\npartial')
await vi.runOnlyPendingTimersAsync()
const result = await promise
expect(result.truncated).toBe(true)
expect(result.files).toHaveLength(1)
expect(result.files[0].matchCount).toBe(1)
expect(proc.kill).toHaveBeenCalled()
expect((proc.stdout as unknown as EventEmitter).listenerCount('data')).toBe(0)
expect((proc.stderr as unknown as EventEmitter).listenerCount('data')).toBe(0)
expect(proc.listenerCount('error')).toBe(0)
expect(proc.listenerCount('close')).toBe(0)
} finally {
vi.useRealTimers()
}
})
it('skips lines without null separator', async () => {
const proc = createMockProcess()
gitSpawnMock.mockReturnValue(proc)
const promise = searchWithGitGrep('/mock/root', { query: 'ok', rootPath: '/mock/root' }, 100)
setTimeout(() => {
// A line without \0 should be skipped (e.g. git header output)
;(proc.stdout as unknown as EventEmitter).emit('data', 'no-null-here:1:ok\n')
;(proc.stdout as unknown as EventEmitter).emit('data', 'valid.ts\x003\x00ok\n')
proc.emit('close')
}, 10)
const result = await promise
expect(result.files).toHaveLength(1)
expect(result.files[0].relativePath).toBe('valid.ts')
})
})