Skip to content

Commit 1b8fe13

Browse files
fix(server): new branches survive a config lock held outside T3
Branch creation used to write a remote start point's upstream itself and fail outright when git outside T3 held .git/config.lock, leaving the branch behind. Branches are now created with --no-track, and the upstream is set afterwards by a write that retries. Lock contention is told apart from permission errors, which no longer retry. Plain local checkouts no longer take the repository's config lock. `remote add` runs with stable diagnostics. Retry tests wait on the real clock instead of counting attempts, and new tests cover a push whose upstream cannot be recorded and the GitHub provider's typed writes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7f6b015 commit 1b8fe13

3 files changed

Lines changed: 152 additions & 67 deletions

File tree

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 100 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,28 @@ const makeFailedHandle = (stderr: string) =>
8989
stderr: Stream.encodeText(Stream.make(stderr)),
9090
});
9191

92+
// Reports when matching git commands exit, so a test can act between a write's attempts.
93+
const makeDriverReportingExits = (matches: (args: ReadonlyArray<string>) => boolean) =>
94+
Effect.gen(function* () {
95+
const exits = yield* Queue.unbounded<ChildProcessSpawner.ExitCode>();
96+
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
97+
const spawner = ChildProcessSpawner.make((command) =>
98+
Effect.gen(function* () {
99+
const handle = yield* delegate.spawn(command);
100+
if (!ChildProcess.isStandardCommand(command) || !matches(command.args)) return handle;
101+
return ChildProcessSpawner.makeHandle({
102+
...handle,
103+
exitCode: handle.exitCode.pipe(Effect.tap((exitCode) => Queue.offer(exits, exitCode))),
104+
});
105+
}),
106+
);
107+
const driver = yield* makeGitVcsDriverCore().pipe(
108+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
109+
Effect.provide(layerServerConfig),
110+
);
111+
return { driver, exits };
112+
});
113+
92114
describe("Git output collection", () => {
93115
// Git writes in arbitrary chunk sizes; one byte per chunk splits every
94116
// multibyte character across reads.
@@ -3160,7 +3182,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
31603182
const args = ChildProcess.isStandardCommand(command) ? command.args : [];
31613183
const writesConfig =
31623184
(args.includes("worktree") && args.includes("add") && args.includes("-b")) ||
3163-
(args[0] === "branch" && (args[1] === "--" || args[1] === "-m")) ||
3185+
(args[0] === "branch" &&
3186+
(args[1] === "-m" || args[1]?.startsWith("--set-upstream-to"))) ||
31643187
(args[0] === "config" && !args[1]?.startsWith("-"));
31653188
if (!writesConfig) return yield* delegate.spawn(command);
31663189
configWriters += 1;
@@ -3526,49 +3549,26 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
35263549
}),
35273550
);
35283551

3529-
it.effect("still creates the worktree when the base-ref config is locked", () =>
3552+
it.effect("still creates the worktree when the base-ref config stays locked", () =>
35303553
Effect.gen(function* () {
35313554
const cwd = yield* makeTmpDir();
35323555
const { initialBranch } = yield* initRepoWithCommit(cwd);
35333556
const pathService = yield* Path.Path;
35343557
const fileSystem = yield* FileSystem.FileSystem;
35353558
const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "locked-config");
35363559
yield* writeTextFile(cwd, ".git/config.lock", "");
3537-
const configWritesFinished = yield* Queue.unbounded<void>();
3538-
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
3539-
const spawner = ChildProcessSpawner.make((command) =>
3540-
Effect.gen(function* () {
3541-
const handle = yield* delegate.spawn(command);
3542-
const args = ChildProcess.isStandardCommand(command) ? command.args : [];
3543-
if (args[0] !== "config" || !args[1]?.startsWith("branch.")) return handle;
3544-
return ChildProcessSpawner.makeHandle({
3545-
...handle,
3546-
exitCode: handle.exitCode.pipe(
3547-
Effect.tap(() => Queue.offer(configWritesFinished, undefined)),
3548-
),
3549-
});
3550-
}),
3551-
);
3552-
const driver = yield* makeGitVcsDriverCore().pipe(
3553-
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
3554-
Effect.provide(layerServerConfig),
3555-
);
3560+
const driver = yield* GitVcsDriver.GitVcsDriver;
35563561

3557-
const creating = yield* driver
3558-
.createWorktree({
3562+
// The base-ref write retries on the real clock before giving up.
3563+
const created = yield* TestClock.withLive(
3564+
driver.createWorktree({
35593565
cwd,
35603566
path: worktreePath,
35613567
refName: initialBranch,
35623568
newRefName: "feature/locked-config",
35633569
baseRefName: initialBranch,
3564-
})
3565-
.pipe(Effect.forkChild);
3566-
// The base-ref write tries once and retries ten times before giving up.
3567-
for (let attempt = 0; attempt < 11; attempt++) {
3568-
yield* Queue.take(configWritesFinished);
3569-
yield* TestClock.adjust("50 millis");
3570-
}
3571-
const created = yield* Fiber.join(creating);
3570+
}),
3571+
);
35723572

35733573
assert.deepEqual(created.worktree, {
35743574
path: worktreePath,
@@ -3858,40 +3858,60 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
38583858
const path = yield* Path.Path;
38593859
const lockPath = path.join(cwd, ".git", "config.lock");
38603860
yield* fileSystem.writeFileString(lockPath, "");
3861-
const writesFinished = yield* Queue.unbounded<number>();
3862-
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
3863-
const spawner = ChildProcessSpawner.make((command) =>
3864-
Effect.gen(function* () {
3865-
const handle = yield* delegate.spawn(command);
3866-
if (!ChildProcess.isStandardCommand(command) || command.args[1] !== "t3.test") {
3867-
return handle;
3868-
}
3869-
return ChildProcessSpawner.makeHandle({
3870-
...handle,
3871-
exitCode: handle.exitCode.pipe(
3872-
Effect.tap((exitCode) => Queue.offer(writesFinished, exitCode)),
3873-
),
3874-
});
3875-
}),
3876-
);
3877-
const driver = yield* makeGitVcsDriverCore().pipe(
3878-
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
3879-
Effect.provide(layerServerConfig),
3880-
);
3861+
const { driver, exits } = yield* makeDriverReportingExits((args) => args[1] === "t3.test");
38813862

3882-
const write = yield* driver
3883-
.writeConfigValue({ cwd, key: "t3.test", value: "written" })
3884-
.pipe(Effect.forkChild);
3885-
assert.notEqual(yield* Queue.take(writesFinished), 0);
3863+
// Retries wait on the real clock while the external lock is released.
3864+
const write = yield* TestClock.withLive(
3865+
driver.writeConfigValue({ cwd, key: "t3.test", value: "written" }),
3866+
).pipe(Effect.forkChild);
3867+
assert.notEqual(yield* Queue.take(exits), 0);
38863868
yield* fileSystem.remove(lockPath);
3887-
yield* TestClock.adjust("50 millis");
38883869
yield* Fiber.join(write);
38893870

3890-
assert.equal(yield* Queue.take(writesFinished), 0);
38913871
assert.equal(yield* git(cwd, ["config", "t3.test"]), "written");
38923872
}),
38933873
);
38943874

3875+
it.effect("tracks a remote start point once another process releases the config lock", () =>
3876+
Effect.gen(function* () {
3877+
const cwd = yield* makeTmpDir();
3878+
const { initialBranch } = yield* initRepoWithCommit(cwd);
3879+
const remote = yield* makeTmpDir("git-remote-");
3880+
yield* git(remote, ["init", "--bare"]);
3881+
yield* git(cwd, ["remote", "add", "origin", remote]);
3882+
yield* git(cwd, ["push", "origin", initialBranch]);
3883+
const fileSystem = yield* FileSystem.FileSystem;
3884+
const path = yield* Path.Path;
3885+
const lockPath = path.join(cwd, ".git", "config.lock");
3886+
yield* fileSystem.writeFileString(lockPath, "");
3887+
const { driver, exits } = yield* makeDriverReportingExits((args) =>
3888+
args.some((arg) => arg.startsWith("--set-upstream-to")),
3889+
);
3890+
3891+
// The upstream write retries on the real clock while the external lock is released.
3892+
const creating = yield* TestClock.withLive(
3893+
driver.createWorktree({
3894+
cwd,
3895+
path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"),
3896+
refName: `origin/${initialBranch}`,
3897+
newRefName: "feature/tracked",
3898+
}),
3899+
).pipe(Effect.forkChild);
3900+
// Raced with the launch so a branch step that fails under the lock fails the test.
3901+
assert.notEqual(
3902+
yield* Effect.raceFirst(Queue.take(exits), Fiber.join(creating)),
3903+
ChildProcessSpawner.ExitCode(0),
3904+
);
3905+
yield* fileSystem.remove(lockPath);
3906+
yield* Fiber.join(creating);
3907+
3908+
assert.equal(
3909+
yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]),
3910+
`origin/${initialBranch}`,
3911+
);
3912+
}),
3913+
);
3914+
38953915
// regression: #12485 explain fetch failures without exposing remote output
38963916
it.effect("explains a real fetch failure for a missing local remote", () =>
38973917
Effect.gen(function* () {
@@ -4405,6 +4425,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
44054425
}),
44064426
);
44074427

4428+
it.effect("reports a push whose upstream could not be recorded", () =>
4429+
Effect.gen(function* () {
4430+
const cwd = yield* makeTmpDir();
4431+
const remote = yield* makeTmpDir("git-remote-");
4432+
yield* initRepoWithCommit(cwd);
4433+
yield* git(remote, ["init", "--bare"]);
4434+
yield* git(cwd, ["remote", "add", "origin", remote]);
4435+
yield* git(cwd, ["checkout", "-q", "-b", "feature/locked"]);
4436+
yield* writeTextFile(cwd, ".git/config.lock", "");
4437+
const driver = yield* GitVcsDriver.GitVcsDriver;
4438+
4439+
// Recording the upstream retries on the real clock before giving up.
4440+
const pushed = yield* TestClock.withLive(driver.pushCurrentBranch(cwd, null));
4441+
4442+
assert.deepInclude(pushed, { status: "pushed", setUpstream: false });
4443+
assert.include(
4444+
yield* git(cwd, ["ls-remote", "origin", "refs/heads/feature/locked"]),
4445+
yield* git(cwd, ["rev-parse", "HEAD"]),
4446+
);
4447+
assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/locked.remote"), null);
4448+
}),
4449+
);
4450+
44084451
it.effect.each(["feature/push", "origin/feature/push"])(
44094452
"publishes %s when the configured diff base already contains HEAD",
44104453
(branch) =>

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai
437437
[/would clobber existing tag/i, "tag_would_be_clobbered"],
438438
[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
439439
[/a branch named .+ already exists/i, "branch_already_exists"],
440-
[/could not lock config file/i, "config_locked"],
440+
// The same prefix also reports permission errors, which retrying cannot fix.
441+
[/could not lock config file .+: File exists/i, "config_locked"],
441442
[
442443
/(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,
443444
"authentication_failed",
@@ -1744,7 +1745,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
17441745
suffix += 1;
17451746
}
17461747

1747-
return yield* runGit(
1748+
return yield* executeGitWithStableDiagnostics(
17481749
"GitVcsDriver.ensureRemote.add",
17491750
input.cwd,
17501751
["remote", "add", "--", remoteName, input.url],
@@ -3409,22 +3410,45 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
34093410
).pipe(retryWhileConfigLocked);
34103411
});
34113412

3412-
const createBranchAt = (
3413+
// `git branch` writes a remote start point's upstream itself and fails outright if the
3414+
// config is locked, so tracking is recorded afterwards by a write that retries.
3415+
const createBranchAt = Effect.fn("createBranchAt")(function* (
34133416
operation: string,
34143417
input: GitVcsDriver.GitCreateBranchInput,
34153418
fallbackErrorDetail: string,
3416-
) =>
3417-
executeGitWithStableDiagnostics(
3419+
) {
3420+
// `git branch` does not read a lone - as the previous checkout.
3421+
const startPoint = input.startPoint === "-" ? "@{-1}" : input.startPoint;
3422+
yield* executeGitWithStableDiagnostics(
34183423
operation,
34193424
input.cwd,
3420-
// `git branch` does not read a lone - as the previous checkout.
3421-
["branch", "--", input.branch, input.startPoint === "-" ? "@{-1}" : input.startPoint],
3422-
{ fallbackErrorDetail, writesSharedConfig: true },
3423-
).pipe(Effect.asVoid);
3425+
["branch", "--no-track", "--", input.branch, startPoint],
3426+
{ fallbackErrorDetail },
3427+
);
3428+
const startRef = yield* executeGit(
3429+
`${operation}.resolveStartPoint`,
3430+
input.cwd,
3431+
["rev-parse", "--symbolic-full-name", startPoint],
3432+
{ allowNonZeroExit: true },
3433+
).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : "")));
3434+
if (!startRef.startsWith("refs/remotes/")) return;
3435+
yield* executeGitWithStableDiagnostics(
3436+
`${operation}.track`,
3437+
input.cwd,
3438+
["branch", `--set-upstream-to=${startRef}`, "--", input.branch],
3439+
{ writesSharedConfig: true },
3440+
).pipe(
3441+
retryWhileConfigLocked,
3442+
Effect.catch((cause) =>
3443+
Effect.logWarning("created the branch without tracking its start point", { cause }),
3444+
),
3445+
);
3446+
});
34243447

34253448
const createBranch: GitVcsDriver.GitVcsDriver["Service"]["createBranch"] = Effect.fn(
34263449
"createBranch",
34273450
)(function* (input) {
3451+
yield* refuseOptionLikeRefName("GitVcsDriver.createBranch", input.cwd, input.startPoint);
34283452
yield* createBranchAt("GitVcsDriver.createBranch", input, "git branch create failed");
34293453
});
34303454

@@ -4474,7 +4498,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
44744498
timeoutMs: 10_000,
44754499
fallbackErrorDetail: "git checkout failed",
44764500
// Checking out a remote branch creates a local one that tracks it.
4477-
writesSharedConfig: true,
4501+
writesSharedConfig: !localInputExists,
44784502
},
44794503
);
44804504

‎packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,19 @@ describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {
528528
}).pipe(Effect.provide(layer));
529529
});
530530

531+
it.effect("records the branch base for gh through the host's config write", () => {
532+
const { layer, git } = harness({
533+
remotes: remotesOutput(["origin", "[email protected]:acme/web.git"]),
534+
});
535+
return Effect.gen(function* () {
536+
const gh = yield* GitHubSourceControlProvider.make;
537+
yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });
538+
assert.deepStrictEqual(git, [
539+
["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],
540+
]);
541+
}).pipe(Effect.provide(layer));
542+
});
543+
531544
it("names the local branch the way gh pr checkout does", () => {
532545
const name = (headRefName: string, isCrossRepository: boolean) =>
533546
GitHubSourceControlProvider.pullRequestCheckoutBranchName({
@@ -951,6 +964,11 @@ it.live.each([
951964
["github.com", "repos/team/explicit"],
952965
],
953966
);
967+
assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {
968+
cwd: "/repo",
969+
branch: "feature",
970+
startPoint: "refs/remotes/enterprise/feature",
971+
});
954972
assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {
955973
cwd: "/repo",
956974
remoteName: "enterprise",

0 commit comments

Comments
 (0)