Files
orca/src/main/git/worktree-base-refresh-lock-real-git.test.ts
T
Brennan Benson 12b8ef8c0b fix(worktree): update local main safely, once per branch, alongside the checkout (#23698)
* fix(worktree): retry local main refresh through git lock contention and skip false alarms

* fix(worktree): overlap the local main refresh with the checkout and run one refresh per repo at a time

* fix(worktree): skip the local base refresh when the create makes that branch itself

Creating a workspace named feature-x from origin/feature-x runs `worktree add -b feature-x`,
which now overlaps the refresh. The refresh's drift probe could see refs/heads/feature-x
missing and its presence probe then see it (the add just wrote it), which reported
"not fast-forward" and showed a sticky "Local feature-x was not refreshed" warning.
`-b` refuses an existing branch, so there is nothing to refresh in that case: skip it on
the local, prepared-checkout and SSH create paths.

The SSH overlap tests move to their own file so the existing suite stays under the line limit.

* fix(worktree): say plainly what happens after the local base refresh queue wait expires

* test(worktree): prove SSH local base refreshes of one repo run one at a time

* test(worktree): drop type assertions from the SSH refresh overlap test mocks

* fix(worktree): fast-forward local main with one host-owned merge --ff-only per branch

Moves the whole local base refresh into one shared routine that runs on the
execution host (main process for local and WSL repos, the relay for SSH), so
the app no longer keeps a second copy of the checks, queue and retry.

A checked-out branch now moves with merge --ff-only (hooks, auto-gc and
autostash off) instead of status-then-reset --hard, which silently overwrote an
untracked file the new commit adds and could discard an edit or a commit made
after the check. A free branch moves with a compare-and-swap update-ref that
writes a reflog message. Status reads no longer take index.lock.

Creates of one branch share one run plus at most one trailing run; a create
waits at most 30 s and never starts a competing mutation. The failure toast is
keyed by repo and branch because every create that joined a run reports the
same fact.

* fix(worktree): fast-forward local main even when the repo requires signed merges

With merge.verifySignatures=true, the owner-checkout fast-forward refused an
unsigned origin/main tip, so every create warned "Local main was not
refreshed" where the old reset moved main. The new workspace is already
created from that same unsigned commit, and a branch that is not checked out
moves without a signature check, so the refusal protected nothing. Turn the
setting off for this one merge, like the hooks, gc and autostash overrides.

* fix(worktree): clear git read caches when a shared local main update lands late

The update of local main can finish after a create stopped waiting for it, so
the shared run now invalidates git read caches itself. The index.lock real-git
test also no longer reads the developer's global git config.

* fix(worktree): never overwrite an ignored file when fast-forwarding local main

A plain `git merge --ff-only` silently replaces an ignored file (for example a
local `.env`) at a path the new commit starts tracking. Pass
`--no-overwrite-ignore` so git refuses instead and the create reports the
checkout as having local changes. Supported on the fast-forward path since
well before Git 2.25.

Also make the relay test for one-refresh-per-branch hold the first merge until
the second request has reached the relay, so it fails without the coalescing.

* fix(worktree): keep the local main update a plain fast-forward whatever the user's merge settings say

A per-branch mergeOptions such as '-s ours' or '--squash', or pull.twohead=ours,
made the update create a merge commit that dropped upstream, or stage upstream
without moving main, while reporting success. The command now clears the
branch's mergeOptions and passes the strategy and signature choice on the
command line, which beats any config. After the move Orca confirms local main
is exactly the target before reporting it updated. The exact command also runs
in the Git 2.25 compatibility suite.

* fix(worktree): make the Git 2.25 fast-forward contract pass in CI and rerun on every change to it

The new real-Git contract for the local main fast-forward wrote a post-merge hook into .git/hooks, which does not exist when the repo is created by the uninstalled Git 2.25.5 build CI uses (no templates), so the Git compatibility check failed. Create the directory first.

The Git compatibility check also did not run when only the fast-forward module changed, so a later edit to its merge arguments (for example a flag Git 2.25 lacks) would skip the one check that tests them. Add the module to the check's paths.

* fix(worktree): answer every create from a local main update toward its own base

Creates from different remotes' main (origin/main and upstream/main) shared one queued update
per repo and branch, which ran only the latest caller's target: a create could get no result
for its own base, or a false "not refreshed" warning computed for another remote's main.

The per-branch runner now queues one run per distinct target, still one at a time per branch,
and only callers toward the same target share a queued run. Applied in the app and the relay.

* test(worktree): record the third create's result in the mixed-remote burst tests and update the toast id rationale

* chore(worktree): correct the toast id rationale
2026-09-30 18:30:22 -07:00

213 lines
8.3 KiB
TypeScript

import { execFileSync } from 'node:child_process'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as gitRunner from './runner'
import { refreshLocalBaseRefForWorktreeCreate } from './worktree-base-refresh'
const tempRoots: string[] = []
function git(cwd: string, args: string[]): string {
return execFileSync('git', args, {
cwd,
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe']
}).trim()
}
// Primary checkout on `main` one commit behind `refs/remotes/origin/main`, with its index locked.
async function createBehindRepoWithIndexLock(): Promise<{
repoPath: string
lockPath: string
localOid: string
remoteOid: string
}> {
const root = await mkdtemp(join(tmpdir(), 'orca-base-refresh-lock-'))
tempRoots.push(root)
const repoPath = join(root, 'repo')
execFileSync('git', ['init', '--quiet', repoPath])
git(repoPath, ['symbolic-ref', 'HEAD', 'refs/heads/main'])
git(repoPath, ['config', 'user.email', 'test@example.com'])
git(repoPath, ['config', 'user.name', 'Test User'])
git(repoPath, ['config', 'core.autocrlf', 'false'])
await writeFile(join(repoPath, 'version.txt'), 'one\n')
git(repoPath, ['add', 'version.txt'])
git(repoPath, ['commit', '--quiet', '-m', 'one'])
const localOid = git(repoPath, ['rev-parse', 'HEAD'])
git(repoPath, ['checkout', '--quiet', '-b', 'upstream'])
await writeFile(join(repoPath, 'version.txt'), 'two\n')
git(repoPath, ['commit', '--quiet', '-am', 'two'])
const remoteOid = git(repoPath, ['rev-parse', 'HEAD'])
git(repoPath, ['checkout', '--quiet', 'main'])
git(repoPath, ['update-ref', 'refs/remotes/origin/main', remoteOid])
git(repoPath, ['branch', '--quiet', '-D', 'upstream'])
const lockPath = join(repoPath, '.git', 'index.lock')
await writeFile(lockPath, '')
return { repoPath, lockPath, localOid, remoteOid }
}
function isOwnerFastForward(args: readonly string[]): boolean {
return args.includes('merge') && args.includes('--ff-only')
}
/** Counts owner fast-forwards; `onFailure` runs after each failed one, before it is reported. */
function spyOnFastForwards(onFailure: () => Promise<void> | void = () => {}): {
merges: () => number
maxConcurrent: () => number
} {
const original = gitRunner.gitExecFileAsync
let merges = 0
let active = 0
let maxConcurrent = 0
vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => {
if (!isOwnerFastForward(args)) {
return original(args, options)
}
merges += 1
active += 1
maxConcurrent = Math.max(maxConcurrent, active)
try {
return await original(args, options)
} catch (error) {
await onFailure()
throw error
} finally {
active -= 1
}
})
return { merges: () => merges, maxConcurrent: () => maxConcurrent }
}
function refresh(repoPath: string, remote: 'origin' | 'upstream' = 'origin') {
return refreshLocalBaseRefForWorktreeCreate(
repoPath,
`${remote}/main`,
`refs/remotes/${remote}/main`
)
}
// A fork: checked-out `main` behind `origin/main`, which is one commit behind `upstream/main`.
async function createForkRepo(): Promise<{
repoPath: string
originOid: string
upstreamOid: string
}> {
const { repoPath, lockPath, remoteOid: originOid } = await createBehindRepoWithIndexLock()
await rm(lockPath, { force: true })
git(repoPath, ['checkout', '--quiet', '-b', 'fork-upstream', originOid])
await writeFile(join(repoPath, 'version.txt'), 'three\n')
git(repoPath, ['commit', '--quiet', '-am', 'three'])
const upstreamOid = git(repoPath, ['rev-parse', 'HEAD'])
git(repoPath, ['checkout', '--quiet', 'main'])
git(repoPath, ['update-ref', 'refs/remotes/upstream/main', upstreamOid])
git(repoPath, ['branch', '--quiet', '-D', 'fork-upstream'])
return { repoPath, originOid, upstreamOid }
}
beforeEach(() => {
// Why: a developer's global config (e.g. merge.verifySignatures) must not change what these repos do.
vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1')
vi.stubEnv('GIT_CONFIG_GLOBAL', join(tmpdir(), `orca-no-global-gitconfig-${process.pid}`))
})
afterEach(async () => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('local base refresh against a held index.lock with real Git', () => {
it('retries once the other git process releases the lock', async () => {
const { repoPath, lockPath, remoteOid } = await createBehindRepoWithIndexLock()
const spy = spyOnFastForwards(() => rm(lockPath, { force: true }))
const result = await refresh(repoPath)
expect(result).toMatchObject({ status: 'updated' })
expect(spy.merges()).toBe(2)
expect(git(repoPath, ['rev-parse', 'main'])).toBe(remoteOid)
expect(await readFile(join(repoPath, 'version.txt'), 'utf8')).toBe('two\n')
})
it('reports updated when another process fast-forwarded local while holding the lock', async () => {
const { repoPath, remoteOid } = await createBehindRepoWithIndexLock()
spyOnFastForwards(() => {
git(repoPath, ['update-ref', 'refs/heads/main', remoteOid])
})
const result = await refresh(repoPath)
expect(result).toMatchObject({ status: 'updated' })
expect(git(repoPath, ['rev-parse', 'main'])).toBe(remoteOid)
})
it('reports skipped_error when the lock outlives every retry', async () => {
const { repoPath, localOid } = await createBehindRepoWithIndexLock()
const spy = spyOnFastForwards()
const result = await refresh(repoPath)
expect(result).toMatchObject({ status: 'skipped_error' })
expect(spy.merges()).toBe(4)
expect(git(repoPath, ['rev-parse', 'main'])).toBe(localOid)
})
})
describe('concurrent local base refreshes of one repo with real Git', () => {
it('runs one fast-forward and resolves every create without a warning', async () => {
const { repoPath, lockPath, remoteOid } = await createBehindRepoWithIndexLock()
await rm(lockPath, { force: true })
const spy = spyOnFastForwards()
const warn = vi.spyOn(console, 'warn')
const results = await Promise.all([refresh(repoPath), refresh(repoPath), refresh(repoPath)])
expect(results[0]).toMatchObject({ status: 'updated', ownerWorktreePath: expect.any(String) })
// The joiners share one follow-up run, which finds local already current.
expect(results.slice(1)).toEqual([undefined, undefined])
expect(spy.merges()).toBe(1)
expect(warn).not.toHaveBeenCalled()
expect(git(repoPath, ['rev-parse', 'main'])).toBe(remoteOid)
})
})
describe('concurrent local base refreshes toward different remotes with real Git', () => {
it('moves local to a target a later create from another remote asked for', async () => {
const { repoPath, upstreamOid } = await createForkRepo()
const spy = spyOnFastForwards()
const results = await Promise.all([
refresh(repoPath, 'origin'),
refresh(repoPath, 'upstream'),
refresh(repoPath, 'origin')
])
expect(results[0]).toMatchObject({ baseRef: 'origin/main', status: 'updated' })
expect(results[1]).toMatchObject({ baseRef: 'upstream/main', status: 'updated' })
// Local is now ahead of origin/main: the existing ahead-of-requested-remote rule, not a sharing artifact.
expect(results[2]).toMatchObject({ baseRef: 'origin/main', status: 'skipped_not_fast_forward' })
expect(git(repoPath, ['rev-parse', 'main'])).toBe(upstreamOid)
expect(spy.maxConcurrent()).toBe(1)
})
it('never answers a create with the outcome of another remote target', async () => {
const { repoPath, upstreamOid } = await createForkRepo()
const spy = spyOnFastForwards()
const results = await Promise.all([
refresh(repoPath, 'upstream'),
refresh(repoPath, 'upstream'),
refresh(repoPath, 'origin')
])
expect(results[0]).toMatchObject({ baseRef: 'upstream/main', status: 'updated' })
// Local already equals upstream/main, so the second upstream create has nothing to report.
expect(results[1]).toBeUndefined()
// Local is now ahead of origin/main: the existing ahead-of-requested-remote rule, not a sharing artifact.
expect(results[2]).toMatchObject({ baseRef: 'origin/main', status: 'skipped_not_fast_forward' })
expect(git(repoPath, ['rev-parse', 'main'])).toBe(upstreamOid)
expect(spy.maxConcurrent()).toBe(1)
})
})