Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 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
10 changes: 8 additions & 2 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,8 @@ jobs:
- uses: ./.github/actions/prepare-git-compatibility

- name: Verify Git binary compatibility matrix
env:
ORCA_BACKGROUND_LAUNCH: '1'
run: |
specs=(
"alpine/git:edge-2.38.1|2.38.1"
Expand All @@ -433,7 +435,9 @@ 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 \
src/relay/git-review-draft-binary-compatibility.test.ts
) &
pids+=("$!")

Expand All @@ -444,7 +448,9 @@ 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 \
src/relay/git-review-draft-binary-compatibility.test.ts
) &
pids+=("$!")
done
Expand Down
2 changes: 2 additions & 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,8 @@ 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('src/relay/git-review-draft-binary-compatibility.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
189 changes: 189 additions & 0 deletions src/main/git/local-repo-ref-maintenance-probe-retry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as GitRunner from './runner'
import { RepoRefMaintenance } from '../../shared/repo-ref-maintenance'
import {
REF_MAINTENANCE_ATTEMPT_DEADLINE_MS,
REF_MAINTENANCE_CLEAN_COOLDOWN_MS
} from '../../shared/repo-ref-maintenance-policy'

const gitExecFileAsyncMock = vi.hoisted(() => vi.fn())
vi.mock('./runner', async (importOriginal) => ({
...(await importOriginal<typeof GitRunner>()),
gitExecFileAsync: gitExecFileAsyncMock
}))

import { createLocalRepoRefMaintenanceTarget } from './local-repo-ref-maintenance'

const QUIET_MS = 1000
const engines: RepoRefMaintenance[] = []

function createHarness() {
const spans: Record<string, unknown>[] = []
const onError = vi.fn()
const maintenance = new RepoRefMaintenance({
quietPeriodMs: QUIET_MS,
onError,
observe: (attempt) => {
const attributes: Record<string, unknown> = {}
spans.push(attributes)
return attempt({
setAttribute: (key, value) => {
attributes[key] = value
}
})
}
})
engines.push(maintenance)
const maintainPackIndex = vi.fn(async () => {})
const resolveRefsDirectory = vi.fn(async () => undefined)
const packRefs = vi.fn(async () => {})
const target = {
...createLocalRepoRefMaintenanceTarget({ key: 'local::/repo/.git', repoPath: '/repo' }),
maintainPackIndex,
resolveRefsDirectory,
packRefs
}
return { maintenance, target, spans, onError, maintainPackIndex, resolveRefsDirectory, packRefs }
}

async function elapse(maintenance: RepoRefMaintenance, milliseconds: number) {
await vi.advanceTimersByTimeAsync(milliseconds)
await maintenance.whenAttemptSettled()
}

beforeEach(() => {
vi.useFakeTimers()
gitExecFileAsyncMock.mockReset().mockResolvedValue({ stdout: '', stderr: '' })
})

afterEach(() => {
for (const engine of engines.splice(0)) {
engine.dispose()
}
vi.useRealTimers()
})

describe('local maintenance config probe recovery', () => {
it('retries a transient config failure before admitting either maintenance phase', async () => {
const error = new Error('temporary Git spawn failure')
gitExecFileAsyncMock.mockRejectedValueOnce(error)
const h = createHarness()
h.maintenance.arm(h.target)
await elapse(h.maintenance, QUIET_MS)
expect(h.spans[0]).toMatchObject({
'repo.maintenance_outcome': 'failed',
'repo.maintenance_error': String(error)
})
expect(h.onError).toHaveBeenCalledExactlyOnceWith(error)
expect(h.maintainPackIndex).not.toHaveBeenCalled()
expect(h.resolveRefsDirectory).not.toHaveBeenCalled()
expect(h.packRefs).not.toHaveBeenCalled()
await elapse(h.maintenance, 2 * QUIET_MS - 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
await elapse(h.maintenance, 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(h.maintainPackIndex).toHaveBeenCalledTimes(1)
expect(h.resolveRefsDirectory).toHaveBeenCalledTimes(1)
expect(vi.getTimerCount()).toBe(0)
})

it('retains the clean cooldown only for an explicit user opt-out', async () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'maintenance.auto false\n', stderr: '' })
const h = createHarness()
h.maintenance.arm(h.target)
await elapse(h.maintenance, QUIET_MS)
expect(h.spans[0]['repo.maintenance_outcome']).toBe('opted_out')
h.maintenance.arm(h.target)
await elapse(h.maintenance, REF_MAINTENANCE_CLEAN_COOLDOWN_MS - 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
await elapse(h.maintenance, 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(h.onError).not.toHaveBeenCalled()
expect(h.maintainPackIndex).not.toHaveBeenCalled()
expect(h.resolveRefsDirectory).not.toHaveBeenCalled()
expect(h.packRefs).not.toHaveBeenCalled()
})

it('caps a persistent config failure at seven probes and six backed-off retries', async () => {
gitExecFileAsyncMock.mockRejectedValue(new Error('invalid config'))
const h = createHarness()
h.maintenance.arm(h.target)
for (const [index, multiplier] of [1, 2, 4, 8, 8, 8, 8].entries()) {
await elapse(h.maintenance, QUIET_MS * multiplier - 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(index)
await elapse(h.maintenance, 1)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(index + 1)
}
await elapse(h.maintenance, REF_MAINTENANCE_CLEAN_COOLDOWN_MS)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(7)
expect(h.onError).toHaveBeenCalledTimes(7)
expect(h.spans.every((span) => span['repo.maintenance_outcome'] === 'failed')).toBe(true)
expect(h.maintainPackIndex).not.toHaveBeenCalled()
expect(h.resolveRefsDirectory).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})

it('keeps a newer arm when a stale probe fails', async () => {
let rejectProbe: (error: Error) => void = () => {}
gitExecFileAsyncMock.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectProbe = reject
})
)
const h = createHarness()
h.maintenance.arm(h.target)
await vi.advanceTimersByTimeAsync(QUIET_MS)
const newIndex = vi.fn(async () => {})
h.maintenance.arm({ ...h.target, maintainPackIndex: newIndex })
rejectProbe(new Error('stale failure'))
await h.maintenance.whenAttemptSettled()
await elapse(h.maintenance, QUIET_MS)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(newIndex).toHaveBeenCalledOnce()
expect(h.maintainPackIndex).not.toHaveBeenCalled()
})

it.each(['failure', 'opt_out'])('does not re-arm a disposed probe after %s', async (result) => {
let settle: () => void = () => {}
gitExecFileAsyncMock.mockImplementationOnce(
() =>
new Promise((resolve, reject) => {
settle = () =>
result === 'failure'
? reject(new Error('disposed probe'))
: resolve({ stdout: 'maintenance.auto false\n', stderr: '' })
})
)
const h = createHarness()
h.maintenance.arm(h.target)
await vi.advanceTimersByTimeAsync(QUIET_MS)
h.maintenance.dispose()
settle()
await h.maintenance.whenAttemptSettled()
expect(h.spans[0]['repo.maintenance_outcome']).toBe('interrupted')
expect(vi.getTimerCount()).toBe(0)
expect(h.maintainPackIndex).not.toHaveBeenCalled()
expect(h.resolveRefsDirectory).not.toHaveBeenCalled()
})

it('treats a canceled deadline probe as timed out without scheduling retries', async () => {
gitExecFileAsyncMock.mockImplementationOnce(
(_argv, options) =>
new Promise((_resolve, reject) => {
options.signal.addEventListener('abort', () => reject(options.signal.reason), {
once: true
})
})
)
const h = createHarness()
h.maintenance.arm(h.target)
await vi.advanceTimersByTimeAsync(QUIET_MS)
await elapse(h.maintenance, REF_MAINTENANCE_ATTEMPT_DEADLINE_MS)
expect(h.spans[0]['repo.maintenance_outcome']).toBe('timed_out')
expect(gitExecFileAsyncMock).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
expect(h.maintainPackIndex).not.toHaveBeenCalled()
expect(h.resolveRefsDirectory).not.toHaveBeenCalled()
})
})
4 changes: 2 additions & 2 deletions src/main/git/local-repo-ref-maintenance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,13 @@ describe('local repo ref maintenance target', () => {
await expect(target().isOptedOut?.(NO_ABORT)).resolves.toBe(false)
})

it('fails closed when the auto-maintenance config cannot be read', async () => {
it('reports unreadable auto-maintenance config without claiming a user opt-out', async () => {
for (const error of [
new Error('spawn failed'),
Object.assign(new Error('bad config'), { code: 128 })
]) {
gitExecFileAsyncMock.mockRejectedValue(error)
await expect(target().isOptedOut?.(NO_ABORT)).resolves.toBe(true)
await expect(target().isOptedOut?.(NO_ABORT)).rejects.toBe(error)
}
})

Expand Down
19 changes: 14 additions & 5 deletions src/main/git/local-repo-ref-maintenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,11 @@ export function createLocalRepoRefMaintenanceTarget(
)
return isGitAutoMaintenanceDisabled(stdout)
} catch (error) {
// An unset key is consent; unreadable or invalid config must fail closed.
return !isUnsetGitConfigError(error)
if (isUnsetGitConfigError(error)) {
return false
}
// A failed probe blocks writers and retries without claiming a user opt-out.
throw error
}
},
async maintainPackIndex(signal, span, canWrite) {
Expand All @@ -266,7 +269,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 +282,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 +291,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
Loading
Loading