TypeScript
fix(server): parallel worktree launches no longer fail on .git/config lock (#25700)
Julius Marminge3b22620a5cbb
diff --git a/apps/server/src/sourceControl/ServerSourceControlHost.ts b/apps/server/src/sourceControl/ServerSourceControlHost.tsindex de62afef246..aed4011bf1a 100644--- a/apps/server/src/sourceControl/ServerSourceControlHost.ts+++ b/apps/server/src/sourceControl/ServerSourceControlHost.ts@@ -29,6 +29,8 @@ export const layer = Layer.effect(fetchRemoteBranch: git.fetchRemoteBranch,fetchRemoteTrackingBranch: git.fetchRemoteTrackingBranch,setBranchUpstream: git.setBranchUpstream,+ createBranch: git.createBranch,+ writeConfigValue: git.writeConfigValue,switchRef: git.switchRef,},});diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.tsindex aaa4c382ac7..78a195e4034 100644--- a/apps/server/src/vcs/GitVcsDriver.ts+++ b/apps/server/src/vcs/GitVcsDriver.ts@@ -57,6 +57,8 @@ export interface ExecuteGitInput {/** With appendTruncationMarker, line callbacks continue beyond the buffer cap for progress-only consumers. */readonly keepLineCallbacksAfterTruncation?: boolean;readonly progress?: ExecuteGitProgress;+ /** Writes .git/config, which every worktree shares and Git locks without waiting. */+ readonly writesSharedConfig?: boolean;}export interface ExecuteGitResult {@@ -269,6 +271,18 @@ export interface GitFetchWorktreeBaseCommitInput {refName: string;}+export interface GitCreateBranchInput {+ readonly cwd: string;+ readonly branch: string;+ readonly startPoint: string;+}++export interface GitWriteConfigValueInput {+ readonly cwd: string;+ readonly key: string;+ readonly value: string;+}+export interface GitSetBranchUpstreamInput {cwd: string;branch: string;@@ -387,6 +401,11 @@ export class GitVcsDriver extends Context.Service<readonly setBranchUpstream: (input: GitSetBranchUpstreamInput,) => Effect.Effect<void, GitCommandError>;+ /** Tracks the start point like `git branch` does. */+ readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;+ readonly writeConfigValue: (+ input: GitWriteConfigValueInput,+ ) => Effect.Effect<void, GitCommandError>;readonly removeWorktree: (input: VcsRemoveWorktreeInput,) => Effect.Effect<void, GitCommandError>;diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.tsindex f28fd36cf4e..18709ecf0e2 100644--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts@@ -16,6 +16,7 @@ import * as Scope from "effect/Scope";import * as Schema from "effect/Schema";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import { ChildProcess, ChildProcessSpawner } from "effect/process";import {@@ -87,6 +88,41 @@ const makeFailedHandle = (stderr: string) =>stderr: Stream.encodeText(Stream.make(stderr)),});+// Releases the lock as soon as a matching git command fails on it, before the driver retries.+const makeDriverReleasingLock = (+ matches: (args: ReadonlyArray<string>) => boolean,+ lockPath: string,+) =>+ Effect.gen(function* () {+ const failures = yield* Ref.make(0);+ const fileSystem = yield* FileSystem.FileSystem;+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ const handle = yield* delegate.spawn(command);+ if (!ChildProcess.isStandardCommand(command) || !matches(command.args)) return handle;+ return ChildProcessSpawner.makeHandle({+ ...handle,+ exitCode: handle.exitCode.pipe(+ Effect.tap((exitCode) =>+ exitCode === 0+ ? Effect.void+ : Ref.update(failures, (count) => count + 1).pipe(+ Effect.andThen(fileSystem.remove(lockPath, { force: true })),+ Effect.orDie,+ ),+ ),+ ),+ });+ }),+ );+ const driver = yield* makeGitVcsDriverCore().pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provide(layerServerConfig),+ );+ return { driver, failures };+ });+describe("Git output collection", () => {// Git writes in arbitrary chunk sizes; one byte per chunk splits every// multibyte character across reads.@@ -1057,6 +1093,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {it.effect.each([{ action: "worktree add", detail: "git worktree add failed" },+ { action: "worktree add -b", detail: "git worktree add failed" },{ action: "switch", detail: "git checkout failed" },])("reports a missing ref during $action with stable, redacted diagnostics",@@ -1071,7 +1108,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {const spawner = ChildProcessSpawner.make((command) => {if (ChildProcess.isStandardCommand(command) &&- (command.args.includes("worktree") || command.args[0] === "checkout")+ (command.args.includes("worktree") ||+ command.args[0] === "branch" ||+ command.args[0] === "checkout")) {locales.push(command.options.env?.LC_ALL);}@@ -1088,7 +1127,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {.createWorktree({cwd,refName,- newRefName: "t3/new-thread",+ ...(action === "worktree add -b" ? { newRefName: "t3/new-thread" } : {}),path: path.join(cwd, "worktree"),}).pipe(Effect.flip);@@ -3026,6 +3065,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {yield* git(previous.worktree.path, ["branch", "--show-current"]),initialBranch,);+ const fromPrevious = yield* driver.createWorktree({+ cwd,+ path: pathService.join(worktrees, "from-previous"),+ refName: "-",+ newRefName: "from-previous",+ });+ assert.equal(+ yield* git(fromPrevious.worktree.path, ["rev-parse", "HEAD"]),+ yield* git(cwd, ["rev-parse", initialBranch]),+ );}),);});@@ -3124,6 +3173,85 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect("creates parallel worktrees in one repository without racing on its config", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const { initialBranch } = yield* initRepoWithCommit(cwd);+ const remote = yield* makeTmpDir("git-remote-");+ yield* git(remote, ["init", "--bare"]);+ yield* git(cwd, ["remote", "add", "origin", remote]);+ yield* git(cwd, ["push", "origin", initialBranch]);+ const path = yield* Path.Path;+ const worktrees = yield* makeTmpDir("git-worktrees-");++ // Git has no lock timeout for .git/config, which every worktree shares: a writer that+ // overlaps another fails, and a branch can then be left without its worktree.+ let configWriters = 0;+ let peakConfigWriters = 0;+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;+ const countingSpawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ const args = ChildProcess.isStandardCommand(command) ? command.args : [];+ const writesConfig =+ (args.includes("worktree") && args.includes("add") && args.includes("-b")) ||+ (args[0] === "branch" &&+ (args[1] === "-m" || args[1]?.startsWith("--set-upstream-to"))) ||+ (args[0] === "config" && !args[1]?.startsWith("-"));+ if (!writesConfig) return yield* delegate.spawn(command);+ configWriters += 1;+ peakConfigWriters = Math.max(peakConfigWriters, configWriters);+ const handle = yield* delegate.spawn(command);+ return ChildProcessSpawner.makeHandle({+ ...handle,+ exitCode: handle.exitCode.pipe(+ Effect.ensuring(Effect.sync(() => (configWriters -= 1))),+ ),+ });+ }),+ );+ const driver = yield* makeGitVcsDriverCore().pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner),+ Effect.provide(layerServerConfig),+ );+ const branches = Array.from({ length: 8 }, (_, index) => `feature/parallel-${index}`);++ yield* Effect.forEach(+ branches,+ (branch) =>+ driver.createWorktree({+ cwd,+ path: path.join(worktrees, branch.replace("/", "-")),+ refName: `origin/${initialBranch}`,+ newRefName: branch,+ baseRefName: `origin/${initialBranch}`,+ }),+ { concurrency: "unbounded" },+ );+ // Launches rename their temporary branch from inside the new worktree.+ yield* Effect.forEach(+ branches,+ (branch) =>+ driver.renameBranch({+ cwd: path.join(worktrees, branch.replace("/", "-")),+ oldBranch: branch,+ newBranch: `${branch}-renamed`,+ exactName: true,+ }),+ { concurrency: "unbounded" },+ );++ assert.equal(peakConfigWriters, 1);+ for (const branch of branches) {+ const renamed = `${branch}-renamed`;+ assert.equal(yield* git(cwd, ["config", `branch.${renamed}.remote`]), "origin");+ assert.equal(+ yield* git(cwd, ["config", `branch.${renamed}.t3-merge-base-ref`]),+ `refs/remotes/origin/${initialBranch}`,+ );+ }+ }),+ );+it.effect.each(["release/v2", "refs/heads/release/v2", "deadbeef"])("records the branch name when creating a worktree from %s",(baseRef) =>@@ -3433,7 +3561,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);- it.effect("still creates the worktree when the base-ref config is locked", () =>+ it.effect("still creates the worktree when the base-ref config stays locked", () =>Effect.gen(function* () {const cwd = yield* makeTmpDir();const { initialBranch } = yield* initRepoWithCommit(cwd);@@ -3443,13 +3571,16 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {yield* writeTextFile(cwd, ".git/config.lock", "");const driver = yield* GitVcsDriver.GitVcsDriver;- const created = yield* driver.createWorktree({- cwd,- path: worktreePath,- refName: initialBranch,- newRefName: "feature/locked-config",- baseRefName: initialBranch,- });+ // The base-ref write retries on the real clock before giving up.+ const created = yield* TestClock.withLive(+ driver.createWorktree({+ cwd,+ path: worktreePath,+ refName: initialBranch,+ newRefName: "feature/locked-config",+ baseRefName: initialBranch,+ }),+ );assert.deepEqual(created.worktree, {path: worktreePath,@@ -3698,6 +3829,129 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect("ensureRemote returns the remote a parallel call added for the same URL", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ yield* git(cwd, ["init"]);+ // Hold the first add until both calls have listed remotes, so both decide to add.+ let listings = 0;+ const bothListed = yield* Deferred.make<void>();+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ const args = ChildProcess.isStandardCommand(command) ? command.args : [];+ if (args[0] === "remote" && args[1] === "-v") {+ listings += 1;+ if (listings === 2) yield* Deferred.succeed(bothListed, undefined);+ }+ if (args[0] === "remote" && args[1] === "add") yield* Deferred.await(bothListed);+ return yield* delegate.spawn(command);+ }),+ );+ const driver = yield* makeGitVcsDriverCore().pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provide(layerServerConfig),+ );+ const input = { cwd, preferredName: "fork", url: "https://github.com/fork/t3code.git" };++ const names = yield* Effect.all([driver.ensureRemote(input), driver.ensureRemote(input)], {+ concurrency: "unbounded",+ });++ assert.deepEqual(names, ["fork", "fork"]);+ }),+ );++ it.effect("retries a config write while another process holds the config lock", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ yield* initRepoWithCommit(cwd);+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const lockPath = path.join(cwd, ".git", "config.lock");+ yield* fileSystem.writeFileString(lockPath, "");+ const { driver, failures } = yield* makeDriverReleasingLock(+ (args) => args[1] === "t3.test",+ lockPath,+ );++ // The retry waits on the real clock; the lock is already gone by then.+ yield* TestClock.withLive(+ driver.writeConfigValue({ cwd, key: "t3.test", value: "written" }),+ );++ assert.equal(yield* Ref.get(failures), 1);+ assert.equal(yield* git(cwd, ["config", "t3.test"]), "written");+ }),+ );++ it.effect("tracks a remote start point once another process releases the config lock", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const { initialBranch } = yield* initRepoWithCommit(cwd);+ const remote = yield* makeTmpDir("git-remote-");+ yield* git(remote, ["init", "--bare"]);+ yield* git(cwd, ["remote", "add", "origin", remote]);+ yield* git(cwd, ["push", "origin", initialBranch]);+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const lockPath = path.join(cwd, ".git", "config.lock");+ yield* fileSystem.writeFileString(lockPath, "");+ const { driver, failures } = yield* makeDriverReleasingLock(+ (args) => args.some((arg) => arg.startsWith("--set-upstream-to")),+ lockPath,+ );++ // The upstream retry waits on the real clock; the lock is already gone by then.+ yield* TestClock.withLive(+ driver.createWorktree({+ cwd,+ path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"),+ refName: `origin/${initialBranch}`,+ newRefName: "feature/tracked",+ }),+ );++ assert.equal(yield* Ref.get(failures), 1);+ assert.equal(+ yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]),+ `origin/${initialBranch}`,+ );+ }),+ );++ it.effect("fetches a remote branch into a tracking branch past another process's lock", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const { initialBranch } = yield* initRepoWithCommit(cwd);+ const remote = yield* makeTmpDir("git-remote-");+ yield* git(remote, ["init", "--bare"]);+ yield* git(cwd, ["remote", "add", "origin", remote]);+ yield* git(cwd, ["push", "origin", `${initialBranch}:refs/heads/pr-head`]);+ const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock");+ yield* (yield* FileSystem.FileSystem).writeFileString(lockPath, "");+ const { driver, failures } = yield* makeDriverReleasingLock(+ (args) => args.some((arg) => arg.startsWith("--set-upstream-to")),+ lockPath,+ );++ yield* TestClock.withLive(+ driver.fetchRemoteBranch({+ cwd,+ remoteName: "origin",+ remoteBranch: "pr-head",+ localBranch: "review/pr-head",+ }),+ );++ assert.equal(yield* Ref.get(failures), 1);+ assert.equal(+ yield* git(cwd, ["rev-parse", "--abbrev-ref", "review/pr-head@{upstream}"]),+ "origin/pr-head",+ );+ }),+ );+// regression: #12485 explain fetch failures without exposing remote outputit.effect("explains a real fetch failure for a missing local remote", () =>Effect.gen(function* () {@@ -4211,6 +4465,45 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {}),);+ it.effect("rebases a pushed branch's pulls when branch.autoSetupRebase asks for it", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const remote = yield* makeTmpDir("git-remote-");+ yield* initRepoWithCommit(cwd);+ yield* git(remote, ["init", "--bare"]);+ yield* git(cwd, ["remote", "add", "origin", remote]);+ yield* git(cwd, ["config", "branch.autoSetupRebase", "always"]);+ yield* git(cwd, ["checkout", "-q", "-b", "feature/rebase"]);+ const driver = yield* GitVcsDriver.GitVcsDriver;++ assert.deepInclude(yield* driver.pushCurrentBranch(cwd, null), { setUpstream: true });+ assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/rebase.rebase"), "true");+ }),+ );++ it.effect("reports a push whose upstream could not be recorded", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ const remote = yield* makeTmpDir("git-remote-");+ yield* initRepoWithCommit(cwd);+ yield* git(remote, ["init", "--bare"]);+ yield* git(cwd, ["remote", "add", "origin", remote]);+ yield* git(cwd, ["checkout", "-q", "-b", "feature/locked"]);+ yield* writeTextFile(cwd, ".git/config.lock", "");+ const driver = yield* GitVcsDriver.GitVcsDriver;++ // Recording the upstream retries on the real clock before giving up.+ const pushed = yield* TestClock.withLive(driver.pushCurrentBranch(cwd, null));++ assert.deepInclude(pushed, { status: "pushed", setUpstream: false });+ assert.include(+ yield* git(cwd, ["ls-remote", "origin", "refs/heads/feature/locked"]),+ yield* git(cwd, ["rev-parse", "HEAD"]),+ );+ assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/locked.remote"), null);+ }),+ );+it.effect.each(["feature/push", "origin/feature/push"])("publishes %s when the configured diff base already contains HEAD",(branch) =>diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex 753ba03fca9..f0b78aa564f 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -16,6 +16,7 @@ import * as PlatformError from "effect/PlatformError";import * as Ref from "effect/Ref";import * as Result from "effect/Result";import * as Schema from "effect/Schema";+import * as Schedule from "effect/Schedule";import * as Scope from "effect/Scope";import * as Semaphore from "effect/Semaphore";import * as Stream from "effect/Stream";@@ -185,6 +186,7 @@ interface ExecuteGitOptions {maxOutputBytes?: number | undefined;appendTruncationMarker?: boolean | undefined;progress?: GitVcsDriver.ExecuteGitProgress | undefined;+ writesSharedConfig?: boolean | undefined;}function parseBranchAb(value: string): { ahead: number; behind: number } {@@ -435,6 +437,8 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFai[/would clobber existing tag/i, "tag_would_be_clobbered"],[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],[/a branch named .+ already exists/i, "branch_already_exists"],+ // The same prefix also reports permission errors, which retrying cannot fix.+ [/could not lock config file .+: File exists/i, "config_locked"],[/(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,"authentication_failed",@@ -469,6 +473,8 @@ const GIT_FAILURE_REASON_DETAILS: Partial<Record<GitCommandFailureReason, string"The remote rejected the push. Push this branch from a terminal to see the server's message.",push_rejected_non_fast_forward:"The remote has commits this branch doesn't have. Pull or rebase, then push again.",+ config_locked:+ "Another Git process kept the repository's config locked. Wait for it to finish, then retry.",};function gitFailureDetail(reason: GitCommandFailureReason | null): string {@@ -1072,6 +1078,21 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*},);+ const sharedConfigLocks = new Map<string, Semaphore.Semaphore>();+ const withSharedConfigLock = <A, E>(cwd: string, effect: Effect.Effect<A, E>) =>+ resolveRepositoryPaths(cwd).pipe(+ Effect.orElseSucceed(() => null),+ Effect.flatMap((repositoryPaths) => {+ if (repositoryPaths === null) return effect;+ let lock = sharedConfigLocks.get(repositoryPaths.gitCommonDir);+ if (lock === undefined) {+ lock = Semaphore.makeUnsafe(1);+ sharedConfigLocks.set(repositoryPaths.gitCommonDir, lock);+ }+ return lock.withPermit(effect);+ }),+ );+const execute: GitVcsDriver.GitVcsDriver["Service"]["execute"] = (input) =>executeRaw(input).pipe(withMetrics({@@ -1093,6 +1114,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*"git.args_count": input.args.length,},}),+ // Outside the process permit: resolving the repository may itself need one.+ (execution) =>+ input.writesSharedConfig ? withSharedConfigLock(input.cwd, execution) : execution,);const executeGit = (@@ -1117,6 +1141,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*? { appendTruncationMarker: options.appendTruncationMarker }: {}),...(options.progress ? { progress: options.progress } : {}),+ ...(options.writesSharedConfig ? { writesSharedConfig: true } : {}),}).pipe(Effect.flatMap((result) => {if (options.allowNonZeroExit || result.exitCode === 0) {@@ -1698,17 +1723,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*)(function* (input) {const preferredName = sanitizeRemoteName(input.preferredName);const normalizedTargetUrl = sourceControlDefinitions.repositoryKeyFromRemote(input.url);- const remoteFetchUrls = yield* runGitStdout(+ const listRemoteFetchUrls = runGitStdout("GitVcsDriver.ensureRemote.listRemoteUrls",input.cwd,["remote", "-v"],).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));+ const findMatchingRemote = (remoteFetchUrls: Map<string, string>) =>+ Array.from(remoteFetchUrls.entries()).find(+ ([, remoteUrl]) =>+ sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl,+ )?.[0];- for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {- if (sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl) {- return remoteName;- }- }+ const remoteFetchUrls = yield* listRemoteFetchUrls;+ const existing = findMatchingRemote(remoteFetchUrls);+ if (existing !== undefined) return existing;let remoteName = preferredName;let suffix = 1;@@ -1717,14 +1745,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*suffix += 1;}- yield* runGit("GitVcsDriver.ensureRemote.add", input.cwd, [- "remote",- "add",- "--",- remoteName,- input.url,- ]);- return remoteName;+ return yield* executeGitWithStableDiagnostics(+ "GitVcsDriver.ensureRemote.add",+ input.cwd,+ ["remote", "add", "--", remoteName, input.url],+ { writesSharedConfig: true },+ ).pipe(+ retryWhileConfigLocked,+ Effect.as(remoteName),+ // A parallel launch for the same fork may have added it since the listing above.+ Effect.catch((error) =>+ listRemoteFetchUrls.pipe(+ Effect.flatMap((current) => {+ const added = findMatchingRemote(current);+ return added === undefined ? Effect.fail(error) : Effect.succeed(added);+ }),+ ),+ ),+ );});const resolveComparisonBaseRef = Effect.fn("resolveComparisonBaseRef")(function* (@@ -2476,6 +2514,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*return { commitSha };});+ // `push -u` exits 0 without the upstream when another writer holds the config lock.+ const recordPushedUpstream = Effect.fn("recordPushedUpstream")(+ function* (cwd: string, branch: string, remoteName: string, publishBranch: string) {+ // Without a prior upstream, Git ignores a merge ref with no remote, so losing the second+ // write leaves none rather than a wrong one.+ yield* writeConfigValue({+ cwd,+ key: `branch.${branch}.merge`,+ value: `refs/heads/${publishBranch}`,+ });+ yield* writeConfigValue({ cwd, key: `branch.${branch}.remote`, value: remoteName });+ // Matches what `push -u` sets for a remote upstream.+ const autoSetupRebase = yield* readConfigValue(cwd, "branch.autoSetupRebase");+ if (autoSetupRebase === "always" || autoSetupRebase === "remote") {+ yield* writeConfigValue({ cwd, key: `branch.${branch}.rebase`, value: "true" });+ }+ return true;+ },+ Effect.catch((cause) =>+ Effect.logWarning("pushed, but could not record the branch upstream", { cause }).pipe(+ Effect.as(false),+ ),+ ),+ );+const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn("pushCurrentBranch",)(function* (cwd, fallbackBranch, options) {@@ -2498,14 +2561,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote",cwd,- ["push", "-u", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],+ ["push", "--", requestedRemoteName, `HEAD:refs/heads/${publishBranch}`],{ timeoutMs: null },);return {status: "pushed" as const,branch,upstreamBranch: `${requestedRemoteName}/${publishBranch}`,- setUpstream: true,+ setUpstream: yield* recordPushedUpstream(cwd, branch, requestedRemoteName, publishBranch),};}@@ -2574,14 +2637,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithUpstream",cwd,- ["push", "-u", "--", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],+ ["push", "--", publishRemoteName, `HEAD:refs/heads/${publishBranch}`],{ timeoutMs: null },);return {status: "pushed" as const,branch,upstreamBranch: `${publishRemoteName}/${publishBranch}`,- setUpstream: true,+ setUpstream: yield* recordPushedUpstream(cwd, branch, publishRemoteName, publishBranch),};}@@ -2602,30 +2665,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const publishBranch = yield* resolvePublishBranchName(cwd, branch);// Publishing retargets the upstream, so preserve its comparison base first.if ((yield* readBranchBase(cwd, branch)) === null) {- yield* runGit("GitVcsDriver.pushCurrentBranch.recordMergeBase", cwd, [- "config",- branchBaseConfigKey(branch),- currentUpstream.branchName,- ]);+ yield* writeConfigValue({+ cwd,+ key: branchBaseConfigKey(branch),+ value: currentUpstream.branchName,+ });if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {- yield* runGit("GitVcsDriver.pushCurrentBranch.recordComparisonRef", cwd, [- "config",- `branch.${branch}.t3-merge-base-ref`,- `refs/remotes/${currentUpstream.upstreamRef}`,- ]);+ yield* writeConfigValue({+ cwd,+ key: `branch.${branch}.t3-merge-base-ref`,+ value: `refs/remotes/${currentUpstream.upstreamRef}`,+ });}}yield* runGit("GitVcsDriver.pushCurrentBranch.pushOwnBranch",cwd,- ["push", "-u", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],+ ["push", "--", remoteName, `HEAD:refs/heads/${publishBranch}`],{ timeoutMs: null },);return {status: "pushed" as const,branch,upstreamBranch: `${remoteName}/${publishBranch}`,- setUpstream: true,+ setUpstream: yield* recordPushedUpstream(cwd, branch, remoteName, publishBranch),};}@@ -3325,6 +3388,70 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),);+ // Git never waits for .git/config.lock, and git run outside T3, such as an agent's, can hold it.+ // Only writes that are safe to repeat retry.+ const retryWhileConfigLocked = <A>(effect: Effect.Effect<A, GitCommandError>) =>+ effect.pipe(+ Effect.retry({+ while: (error) => error.reason === "config_locked",+ times: 10,+ schedule: Schedule.spaced("50 millis"),+ }),+ );++ const writeConfigValue: GitVcsDriver.GitVcsDriver["Service"]["writeConfigValue"] = Effect.fn(+ "writeConfigValue",+ )(function* (input) {+ yield* executeGitWithStableDiagnostics(+ "GitVcsDriver.writeConfigValue",+ input.cwd,+ ["config", input.key, input.value],+ { writesSharedConfig: true },+ ).pipe(retryWhileConfigLocked);+ });++ // `git branch` writes a remote start point's upstream itself and fails outright if the+ // config is locked, so tracking is recorded afterwards by a write that retries.+ const createBranchAt = Effect.fn("createBranchAt")(function* (+ operation: string,+ input: GitVcsDriver.GitCreateBranchInput,+ fallbackErrorDetail: string,+ ) {+ // `git branch` does not read a lone - as the previous checkout.+ const startPoint = input.startPoint === "-" ? "@{-1}" : input.startPoint;+ yield* executeGitWithStableDiagnostics(+ operation,+ input.cwd,+ ["branch", "--no-track", "--", input.branch, startPoint],+ { fallbackErrorDetail },+ );+ const startRef = yield* executeGit(+ `${operation}.resolveStartPoint`,+ input.cwd,+ ["rev-parse", "--symbolic-full-name", startPoint],+ { allowNonZeroExit: true },+ ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : "")));+ if (!startRef.startsWith("refs/remotes/")) return;+ yield* executeGitWithStableDiagnostics(+ `${operation}.track`,+ input.cwd,+ ["branch", `--set-upstream-to=${startRef}`, "--", input.branch],+ { writesSharedConfig: true },+ ).pipe(+ retryWhileConfigLocked,+ Effect.catch((cause) =>+ Effect.logWarning("created the branch without tracking its start point", { cause }),+ ),+ );+ });++ const createBranch: GitVcsDriver.GitVcsDriver["Service"]["createBranch"] = Effect.fn(+ "createBranch",+ )(function* (input) {+ yield* refuseOptionLikeRefName("GitVcsDriver.createBranch", input.cwd, input.startPoint);+ yield* createBranchAt("GitVcsDriver.createBranch", input, "git branch create failed");+ });+const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn("GitVcsDriver.readBranchBase",)(function* (cwd, branch) {@@ -3700,9 +3827,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*}worktreePath = path.join(parentDir, repoName, sanitizedBranch);}- const args = input.newRefName- ? ["worktree", "add", "-b", input.newRefName, "--", worktreePath, input.refName]- : ["worktree", "add", "--", worktreePath, input.refName];+ if (input.newRefName) {+ // Kept apart from the checkout so the shared-config lock only covers the tracking write.+ yield* createBranchAt(+ "GitVcsDriver.createWorktree.createBranch",+ { cwd: input.cwd, branch: input.newRefName, startPoint: input.refName },+ "git worktree add failed",+ );+ }+ const args = ["worktree", "add", "--", worktreePath, input.newRefName ?? input.refName];const progress = options?.progress;const onCheckoutProgress = progress?.onCheckoutProgress;@@ -3767,19 +3900,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* progress.onSubmodulesStarted();}const onSubmoduleLine = progress?.onSubmoduleLine;+ // Registering submodule URLs writes the shared config; the clones that follow do not.yield* runGit(- "GitVcsDriver.createWorktree.updateSubmodules",+ "GitVcsDriver.createWorktree.initSubmodules",worktreePath,- submoduleMode.value === "recursive"- ? ["submodule", "update", "--init", "--recursive"]- : ["submodule", "update", "--init"],- onSubmoduleLine- ? {- env: { LC_ALL: "C" },- progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine },- }- : {},+ ["submodule", "init"],+ { writesSharedConfig: true },).pipe(+ Effect.andThen(+ runGit(+ "GitVcsDriver.createWorktree.updateSubmodules",+ worktreePath,+ submoduleMode.value === "recursive"+ ? ["submodule", "update", "--init", "--recursive"]+ : ["submodule", "update", "--init"],+ onSubmoduleLine+ ? {+ env: { LC_ALL: "C" },+ progress: { onStdoutLine: onSubmoduleLine, onStderrLine: onSubmoduleLine },+ }+ : {},+ ),+ ),Effect.matchEffect({onFailure: (cause) =>Effect.logWarning("worktree submodule checkout failed; submodule paths are empty", {@@ -3805,18 +3947,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const base = yield* resolveBranchBase(input.cwd, input.baseRefName);if (base) {yield* Effect.gen(function* () {- yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [- "config",- branchBaseConfigKey(newRefName),- base.branchName,- ]);+ yield* writeConfigValue({+ cwd: input.cwd,+ key: branchBaseConfigKey(newRefName),+ value: base.branchName,+ });if (base.baseRef.startsWith("refs/remotes/")) {// The base key names a branch on the host; this one keeps the remote it came from.- yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [- "config",- `branch.${input.newRefName}.t3-merge-base-ref`,- base.baseRef,- ]);+ yield* writeConfigValue({+ cwd: input.cwd,+ key: `branch.${input.newRefName}.t3-merge-base-ref`,+ value: base.baseRef,+ });}}).pipe(Effect.catchTags({@@ -4103,12 +4245,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch);const targetRef = `${input.remoteName}/${input.remoteBranch}`;+ if (!localBranchAlreadyExists) {+ return yield* createBranchAt(+ "GitVcsDriver.fetchRemoteBranch.materialize",+ { cwd: input.cwd, branch: input.localBranch, startPoint: targetRef },+ "git branch create failed",+ );+ }yield* runGit("GitVcsDriver.fetchRemoteBranch.materialize",input.cwd,- localBranchAlreadyExists- ? ["branch", "--force", "--", input.localBranch, targetRef]- : ["branch", "--", input.localBranch, targetRef],+ ["branch", "--force", "--", input.localBranch, targetRef],+ { writesSharedConfig: true },);});@@ -4125,13 +4273,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*});const setBranchUpstream: GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"] = (input) =>- runGit("GitVcsDriver.setBranchUpstream", input.cwd, [- "branch",- "--set-upstream-to",- `${input.remoteName}/${input.remoteBranch}`,- "--",- input.branch,- ]);+ executeGitWithStableDiagnostics(+ "GitVcsDriver.setBranchUpstream",+ input.cwd,+ [+ "branch",+ "--set-upstream-to",+ `${input.remoteName}/${input.remoteBranch}`,+ "--",+ input.branch,+ ],+ { writesSharedConfig: true },+ ).pipe(retryWhileConfigLocked, Effect.asVoid);/*** Unlinks links under `target` without following them and removes the@@ -4240,6 +4393,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*{timeoutMs: 10_000,fallbackErrorDetail: "git branch delete failed",+ // Under contention Git deletes the ref but keeps its config section.+ writesSharedConfig: true,},);});@@ -4261,6 +4416,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*{timeoutMs: 10_000,fallbackErrorDetail: "git branch rename failed",+ writesSharedConfig: true,},);@@ -4346,6 +4502,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*{timeoutMs: 10_000,fallbackErrorDetail: "git checkout failed",+ // Checking out a remote branch creates a local one that tracks it.+ writesSharedConfig: !localInputExists,},);@@ -4363,6 +4521,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*yield* executeGit("GitVcsDriver.createRef", input.cwd, ["branch", "--", input.refName], {timeoutMs: 10_000,fallbackErrorDetail: "git branch create failed",+ // `branch.autoSetupMerge=always` records HEAD's branch as the upstream.+ writesSharedConfig: true,});if (input.switchRef) {yield* switchRef({ cwd: input.cwd, refName: input.refName });@@ -4507,6 +4667,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*setBranchUpstream: Effect.fnUntraced(function* (input) {return yield* withListRefsInvalidation(input.cwd, setBranchUpstream(input));}),+ createBranch: Effect.fnUntraced(function* (input) {+ return yield* withListRefsInvalidation(input.cwd, createBranch(input));+ }),+ writeConfigValue,removeWorktree: Effect.fnUntraced(function* (input) {return yield* withListRefsInvalidation(input.cwd, removeWorktree(input));}),diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.tsindex f69460d3311..0dc958f59c4 100644--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@ -354,6 +354,7 @@ export const GitCommandFailureReason = Schema.Literals(["authentication_failed","branch_already_exists","branch_checked_out_in_worktree",+ "config_locked","host_key_unverified","not_a_repository","path_already_exists",diff --git a/packages/source-control-core/src/server/SourceControlHost.ts b/packages/source-control-core/src/server/SourceControlHost.tsindex e04b602f1af..eb68cc4730c 100644--- a/packages/source-control-core/src/server/SourceControlHost.ts+++ b/packages/source-control-core/src/server/SourceControlHost.ts@@ -109,6 +109,20 @@ export class SourceControlHost extends Context.Service<readonly setBranchUpstream: (input: SourceControlGitRemoteBranch & { readonly branch: string },) => Effect.Effect<void, GitCommandError>;+ /**+ * Writes to .git/config, which every worktree shares, go through these rather than+ * `execute`: the host serializes them per repository.+ */+ readonly createBranch: (input: {+ readonly cwd: string;+ readonly branch: string;+ readonly startPoint: string;+ }) => Effect.Effect<void, GitCommandError>;+ readonly writeConfigValue: (input: {+ readonly cwd: string;+ readonly key: string;+ readonly value: string;+ }) => Effect.Effect<void, GitCommandError>;readonly switchRef: (input: VcsSwitchRefInput,) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;diff --git a/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts b/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.tsindex dc3bcf3a1ac..e02ebd0b455 100644--- a/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts@@ -492,8 +492,10 @@ export const make = Effect.gen(function* () {yield* git.execute({operation: "GitCafeSourceControlProvider.checkoutChangeRequest",cwd: input.cwd,+ // The upstream is recorded next, through the host's serialized config write.args: ["checkout",+ "--no-track","-B",localBranch,`refs/remotes/${remoteName}/${pull.headRefName}`,diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.tsindex b3885921b38..0bf7773aa0e 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts@@ -182,6 +182,8 @@ function harness(input: {}),fetchRemoteTrackingBranch: (args) => record("fetchRemoteTrackingBranch", undefined)(args),setBranchUpstream: (args) => record("setBranchUpstream", undefined)(args),+ createBranch: (args) => record("createBranch", undefined)(args),+ writeConfigValue: (args) => record("writeConfigValue", undefined)(args),switchRef: (args) => record("switchRef", { refName: args.refName })(args) as never,listLocalBranchNames: () =>input.gitFailure === undefined@@ -526,6 +528,19 @@ describe("GitHubSourceControlProvider.checkoutChangeRequest", () => {}).pipe(Effect.provide(layer));});+ it.effect("records the branch base for gh through the host's config write", () => {+ const { layer, git } = harness({+ remotes: remotesOutput(["origin", "[email protected]:acme/web.git"]),+ });+ return Effect.gen(function* () {+ const gh = yield* GitHubSourceControlProvider.make;+ yield* gh.recordBranchBase!({ cwd: "/repo", branch: "feature", baseBranch: "main" });+ assert.deepStrictEqual(git, [+ ["writeConfigValue", { cwd: "/repo", key: "branch.feature.gh-merge-base", value: "main" }],+ ]);+ }).pipe(Effect.provide(layer));+ });+it("names the local branch the way gh pr checkout does", () => {const name = (headRefName: string, isCrossRepository: boolean) =>GitHubSourceControlProvider.pullRequestCheckoutBranchName({@@ -949,6 +964,11 @@ it.live.each([["github.com", "repos/team/explicit"],],);+ assert.deepStrictEqual(git.find(([name]) => name === "createBranch")?.[1], {+ cwd: "/repo",+ branch: "feature",+ startPoint: "refs/remotes/enterprise/feature",+ });assert.deepStrictEqual(git.find(([name]) => name === "fetchRemoteTrackingBranch")?.[1], {cwd: "/repo",remoteName: "enterprise",diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex 60502a138ea..dda1c7c7527 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -750,7 +750,9 @@ export const make = Effect.gen(function* () {);yield* Effect.gen(function* () {- if (!exists) yield* runGit(input.cwd, "branch", ["branch", "--", localBranch, target.ref]);+ if (!exists) {+ yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });+ }yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));if (exists) {yield* runGit(@@ -891,13 +893,8 @@ export const make = Effect.gen(function* () {baseBranch,}) {return git- .execute({- operation: "GitHubSourceControlProvider.recordBranchBase",- cwd,- args: ["config", `branch.${branch}.gh-merge-base`, baseBranch],- })+ .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch }).pipe(- Effect.asVoid,Effect.catch((cause) =>Effect.logWarning("Could not record the branch base for gh", { cause }),),diff --git a/packages/source-control-testing/src/TestSourceControlHost.ts b/packages/source-control-testing/src/TestSourceControlHost.tsindex 632e9fd0848..d241f9f737f 100644--- a/packages/source-control-testing/src/TestSourceControlHost.ts+++ b/packages/source-control-testing/src/TestSourceControlHost.ts@@ -44,6 +44,8 @@ const failingGit: Git = {fetchRemoteBranch: unexpectedGit("fetchRemoteBranch"),fetchRemoteTrackingBranch: unexpectedGit("fetchRemoteTrackingBranch"),setBranchUpstream: unexpectedGit("setBranchUpstream"),+ createBranch: unexpectedGit("createBranch"),+ writeConfigValue: unexpectedGit("writeConfigValue"),switchRef: unexpectedGit("switchRef"),};