Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,8 @@ jobs:
ORCA_GIT_COMPAT_VERSION="2.25.5" \
pnpm exec vitest run --config config/vitest.config.ts \
src/shared/git-binary-compatibility.test.ts \
src/main/git/worktree-safety-real-git.test.ts
src/main/git/worktree-safety-real-git.test.ts \
src/main/git/worktree-rebase-update-refs-real-git.test.ts
) &
pids+=("$!")

Expand All @@ -444,7 +445,8 @@ jobs:
ORCA_GIT_COMPAT_IMAGE="$image" ORCA_GIT_COMPAT_VERSION="$version" \
pnpm exec vitest run --config config/vitest.config.ts \
src/shared/git-binary-compatibility.test.ts \
src/main/git/worktree-safety-real-git.test.ts
src/main/git/worktree-safety-real-git.test.ts \
src/main/git/worktree-rebase-update-refs-real-git.test.ts
) &
pids+=("$!")
done
Expand Down
1 change: 1 addition & 0 deletions config/scripts/git-binary-compatibility-workflow.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ describe('Git binary compatibility PR gate', () => {
expect(run).toContain('ORCA_GIT_COMPAT_IMAGE="$image"')
expect(run).toContain('src/shared/git-binary-compatibility.test.ts')
expect(run).toContain('src/main/git/worktree-safety-real-git.test.ts')
expect(run).toContain('src/main/git/worktree-rebase-update-refs-real-git.test.ts')
expect(run).toContain('pids+=("$!")')
expect(run).toContain('wait "$pid" || status=1')
})
Expand Down
2 changes: 1 addition & 1 deletion config/scripts/runtime-serve-terminal-smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function resolveLaunch(userDataDir) {
label: `electron (${serveEntry})`,
command: override ?? 'npx',
args: override ? serveArgs : ['electron', ...serveArgs],
env: {}
env: { ORCA_DEV_USER_DATA_PATH: userDataDir }
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/main/git/command-runner/git-exec-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { nonInteractiveGitEnv, untranslatedGitOutputEnv } from './git-process-en
import { acquireGitAdmission } from './git-subprocess-admission'
import { GitCommandTimeoutError, gitCommandTimeoutMs } from './git-command-timeout'
import { classifyGitCommand } from '../../../shared/git-command-classification'
import { createAbortError } from './abort-error'

/**
* Async git command execution. Drop-in replacement for
Expand Down Expand Up @@ -74,7 +75,7 @@ async function gitExecFileAsyncUnlocked(
cwd: options.cwd,
wslDistro: options.wslDistro,
tier: options.admissionTier,
signal: options.signal
signal: options.admissionSignal ?? options.signal
})
span?.setAttribute('git.queue_wait_ms', grant.queueWaitMs)
const timeoutMs = gitCommandTimeoutMs(args, options.timeout, options.timeoutMsForTest)
Expand Down Expand Up @@ -153,6 +154,10 @@ async function gitExecFileAsyncUnlocked(
}
}
try {
options.admissionSignal?.throwIfAborted()
if (options.canStart?.() === false) {
throw createAbortError()
}
return await runCapturedCommand()
} finally {
const termination = terminationState.current
Expand Down
4 changes: 4 additions & 0 deletions src/main/git/command-runner/git-exec-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export type GitExecOptions = {
stdin?: string
env?: NodeJS.ProcessEnv
signal?: AbortSignal
/** Cancels admission only; a running child still finishes. */
admissionSignal?: AbortSignal
/** Rechecks owner eligibility after admission, before starting the child. */
canStart?: () => boolean
wslDistro?: string
preferWslDirectGit?: boolean
useConfiguredSshCommandForNetwork?: boolean
Expand Down
12 changes: 9 additions & 3 deletions src/main/git/local-repo-ref-maintenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ export function createLocalRepoRefMaintenanceTarget(
}
return 'failed'
},
async packRefs(lock: PackedRefsLockReporter) {
async packRefs(
lock: PackedRefsLockReporter,
admissionSignal?: AbortSignal,
canStart?: () => boolean
) {
const resolved = await resolveCommonDir()
const owner = resolved
? new PackRefsLockOwnership(gitCommonDirForMainProcess(resolved, args.wslDistro))
Expand All @@ -275,7 +279,7 @@ export function createLocalRepoRefMaintenanceTarget(
if (!claim.ok) {
throw new RefMaintenanceRepoLocked(claim.reason)
}
// Report the rewrite window rather than accepting a signal. A pack that is
// Only admission is cancellable. A pack that is
// killed mid-prune strands a `refs/**` lock about one time in five, and
// Git never clears those; waiting out the window costs at most ~1.4s.
const watch = owner?.watchLock((held) => lock.setHeld(held))
Expand All @@ -284,7 +288,9 @@ export function createLocalRepoRefMaintenanceTarget(
cwd: args.repoPath,
...gitOptions,
admissionTier: 'background',
timeout: PACK_REFS_TIMEOUT_MS
timeout: PACK_REFS_TIMEOUT_MS,
admissionSignal,
canStart
})
} finally {
watch?.stop()
Expand Down
5 changes: 5 additions & 0 deletions src/main/git/remove-worktree-branch-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
// Ref mutation tests use fictitious repositories; administrative reservations have real-Git coverage.
vi.mock('../../shared/git-worktree-admin', () => ({
isBranchReservedByWorktreeOperation: vi.fn().mockResolvedValue(false)
}))

import type * as FsPromises from 'node:fs/promises'
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'

Expand Down
274 changes: 274 additions & 0 deletions src/main/git/repo-maintenance-admission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

type CaptureOptions = { signal?: AbortSignal; onChildTerminated?: () => void }
const { capture, probe, stamp, count, releaseOwner, stopWatch } = vi.hoisted(() => ({
capture:
vi.fn<
(
binary: string,
argv: string[],
options: CaptureOptions
) => Promise<{ stdout: string; stderr: string }>
>(),
probe: vi.fn(),
stamp: vi.fn(),
count: vi.fn(),
releaseOwner: vi.fn(),
stopWatch: vi.fn()
}))

vi.mock('../../shared/loose-ref-count', () => ({ countLooseRefs: count }))
vi.mock('./worktree-list-reader', () => ({
readRepoCommonDirFromGit: async () => '/repo/.git'
}))
vi.mock('./pack-refs-lock-ownership', () => ({
PackRefsLockOwnership: class {
claim = async () => ({ ok: true })
watchLock = () => ({ stop: stopWatch })
release = releaseOwner
}
}))
vi.mock('../observability/tracer', () => ({
withSpan: async (_name: string, run: (span: unknown) => unknown) =>
run({ setAttribute: () => {} })
}))
vi.mock('./repo-pack-index-state', () => ({
probeRepoPackIndexDirectory: probe,
readRepoPackDirectoryStamp: stamp
}))
vi.mock('./runner', async () => import('./command-runner/git-exec-file'))
vi.mock('./command-runner/exec-file-capture', () => ({
execFileCapture: capture,
execFileCaptureToTermination: capture
}))
vi.mock('../observability/instrumentation', () => ({
withGitSpan: async (_args: unknown, run: (span: unknown) => unknown) =>
run({ setAttribute: () => {} })
}))

import { RepoRefMaintenance } from '../../shared/repo-ref-maintenance'
import { createLocalRepoRefMaintenanceTarget } from './local-repo-ref-maintenance'
import { clearRepoPackIndexMaintenanceCache } from './repo-pack-index-maintenance'
import { gitExecFileAsync } from './command-runner/git-exec-file'
import {
GENERAL_CAP,
GitAdmissionScheduler,
acquireGitAdmission,
_gitAdmissionSnapshotForTests,
_resetGitAdmissionForTests
} from './command-runner/git-subprocess-admission'

beforeEach(() => {
vi.clearAllMocks()
clearRepoPackIndexMaintenanceCache()
_resetGitAdmissionForTests(new GitAdmissionScheduler())
stamp.mockResolvedValue('stable-directory')
probe.mockResolvedValue({ protected: false, packCountFloor: 64 })
count.mockResolvedValue({ count: 1001, saturated: true })
releaseOwner.mockResolvedValue(undefined)
capture.mockImplementation(async (_binary, argv, options) => {
options.onChildTerminated?.()
if (argv[0] === 'config') {
throw Object.assign(new Error('unset'), { code: 1 })
}
return { stdout: '', stderr: '' }
})
})

afterEach(() => _resetGitAdmissionForTests())

function arm(
writer: 'multi-pack-index' | 'pack-refs',
isBusy: () => boolean = () => false
): RepoRefMaintenance {
const maintenance = new RepoRefMaintenance({ quietPeriodMs: 1, isBusy })
const target = createLocalRepoRefMaintenanceTarget({
key: 'local::/repo/.git',
repoPath: '/repo'
})
maintenance.arm(writer === 'pack-refs' ? { ...target, maintainPackIndex: undefined } : target)
return maintenance
}

describe('maintenance writer admission cancellation', () => {
it.each(['multi-pack-index', 'pack-refs'] as const)(
'rechecks %s activity after admission and still writes on the next idle attempt',
async (writer) => {
const blockers: { release: () => void }[] = []
const saturate = async () => {
blockers.push(
...(await Promise.all(
Array.from({ length: GENERAL_CAP }, () =>
acquireGitAdmission({ args: ['status'], cwd: '/blocker', tier: 'background' })
)
))
)
}
count.mockResolvedValue({ count: 0, saturated: false })
if (writer === 'multi-pack-index') {
probe.mockImplementationOnce(async () => {
await saturate()
return { protected: false, packCountFloor: 64 }
})
} else {
count.mockImplementationOnce(async () => {
await saturate()
return { count: 1001, saturated: true }
})
}
let busy = false
const maintenance = arm(writer, () => busy)
try {
await vi.waitFor(() => expect(_gitAdmissionSnapshotForTests().queued).toBe(1))
busy = true
blockers.forEach((blocker) => blocker.release())
await maintenance.whenAttemptSettled()
expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(0)
expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0)
if (writer === 'multi-pack-index') {
expect(stamp).toHaveBeenCalledOnce()
} else {
expect(count).toHaveBeenCalledOnce()
}
busy = false
if (writer === 'pack-refs') {
count.mockResolvedValueOnce({ count: 1001, saturated: true })
}
const target = createLocalRepoRefMaintenanceTarget({
key: 'local::/repo/.git',
repoPath: '/repo'
})
maintenance.arm(
writer === 'pack-refs' ? { ...target, maintainPackIndex: undefined } : target
)
await vi.waitFor(() =>
expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(1)
)
await maintenance.whenAttemptSettled()
if (writer === 'multi-pack-index') {
expect(stamp).toHaveBeenCalledTimes(3)
} else {
expect(count).toHaveBeenCalledTimes(3)
}
} finally {
maintenance.dispose()
blockers.forEach((blocker) => blocker.release())
}
}
)

it('releases a grant canceled before the child starts', async () => {
const controller = new AbortController()
const reason = new Error('Owner disposed between grant and spawn')
_resetGitAdmissionForTests(
new GitAdmissionScheduler({
onAdmissionEvent: (event) => {
if (event.phase === 'grant') {
queueMicrotask(() => queueMicrotask(() => controller.abort(reason)))
}
}
})
)
await expect(
gitExecFileAsync(['multi-pack-index', 'write'], {
cwd: '/repo',
admissionTier: 'background',
admissionSignal: controller.signal
})
).rejects.toBe(reason)
expect(capture).not.toHaveBeenCalled()
expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0)
})

it.each(['multi-pack-index', 'pack-refs'] as const)(
'removes queued %s immediately on disposal and never starts it after slots reopen',
async (writer) => {
const blockers: { release: () => void }[] = []
const saturate = async () => {
blockers.push(
...(await Promise.all(
Array.from({ length: GENERAL_CAP }, () =>
acquireGitAdmission({ args: ['status'], cwd: '/blocker', tier: 'background' })
)
))
)
}
if (writer === 'multi-pack-index') {
probe.mockImplementationOnce(async () => {
await saturate()
return { protected: false, packCountFloor: 64 }
})
} else {
count.mockImplementationOnce(async () => {
await saturate()
return { count: 1001, saturated: true }
})
}
const maintenance = arm(writer)
try {
await vi.waitFor(() =>
expect(_gitAdmissionSnapshotForTests().queuedWaiters).toEqual([
expect.objectContaining({
args:
writer === 'pack-refs'
? ['pack-refs', '--all', '--prune']
: ['multi-pack-index', 'write']
})
])
)
maintenance.dispose()
expect(_gitAdmissionSnapshotForTests().queued).toBe(0)
blockers.forEach((blocker) => blocker.release())
await maintenance.whenAttemptSettled()
expect(capture.mock.calls.filter(([, argv]) => argv[0] === writer)).toHaveLength(0)
if (writer === 'pack-refs') {
expect(stopWatch).toHaveBeenCalledOnce()
expect(releaseOwner).toHaveBeenCalledOnce()
}
} finally {
maintenance.dispose()
blockers.forEach((blocker) => blocker.release())
}
}
)

it.each(['multi-pack-index', 'pack-refs'] as const)(
'lets live %s settle after owner disposal without sending a child abort signal',
async (writer) => {
let finishWriter: (() => void) | undefined
capture.mockImplementation(async (_binary, argv, options) => {
if (argv[0] === 'config') {
options.onChildTerminated?.()
throw Object.assign(new Error('unset'), { code: 1 })
}
await new Promise<void>((resolve) => {
finishWriter = resolve
})
options.onChildTerminated?.()
return { stdout: '', stderr: '' }
})
const maintenance = arm(writer)
try {
await vi.waitFor(() => expect(finishWriter).toBeTypeOf('function'))
maintenance.dispose()
const starts = capture.mock.calls.filter(([, argv]) => argv[0] === writer)
expect(starts).toHaveLength(1)
expect(starts[0]?.[2].signal).toBeUndefined()
expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(1)
if (writer === 'pack-refs') {
expect(releaseOwner).not.toHaveBeenCalled()
}
finishWriter?.()
await maintenance.whenAttemptSettled()
expect(_gitAdmissionSnapshotForTests().budgets.general?.baseUsed).toBe(0)
if (writer === 'pack-refs') {
expect(stopWatch).toHaveBeenCalledOnce()
expect(releaseOwner).toHaveBeenCalledOnce()
}
} finally {
maintenance.dispose()
finishWriter?.()
}
}
)
})
Loading
Loading