Skip to content

Commit 32855a9

Browse files
fix(server): serialize local PR checkout with branch changes
Use the existing workspace lease for the local checkout transaction and competing server branch operations. Canonicalize checkout roots consistently and guard the captured branch before refreshing. Verified with 165 focused tests, server typecheck, targeted lint/formatting and precommit. Frozen-tree review: GPT-6.1 Sol high, Codex through T3 Code.
1 parent cb474b0 commit 32855a9

4 files changed

Lines changed: 208 additions & 24 deletions

File tree

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5382,6 +5382,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
53825382
const setUpLocalCheckoutPullRequest = Effect.fnUntraced(function* (
53835383
reportedHead: (pullHead: string) => string | undefined = (pullHead) => pullHead,
53845384
syncCheckoutWithPullHead = true,
5385+
gitSpawnGate?: NonNullable<Parameters<typeof makeManager>[0]>["gitSpawnGate"],
53855386
) {
53865387
const repoDir = yield* makeTempDir("t3code-git-manager-");
53875388
yield* initRepo(repoDir);
@@ -5399,6 +5400,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
53995400
yield* runGit(repoDir, ["push", "origin", "HEAD:refs/pull/91/head"]);
54005401
yield* runGit(repoDir, ["reset", "--hard", firstCommit]);
54015402
const { manager, ghCalls } = yield* makeManager({
5403+
...(gitSpawnGate ? { gitSpawnGate } : {}),
54025404
ghScenario: {
54035405
pullRequest: {
54045406
number: 91,
@@ -5415,6 +5417,139 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
54155417
return { repoDir, manager, ghCalls, firstCommit, pullHead };
54165418
});
54175419

5420+
it.effect.each([
5421+
["switch", "before-refresh", false],
5422+
["switch", "during-refresh", false],
5423+
["create-and-switch", "before-refresh", false],
5424+
["create-and-switch", "during-refresh", false],
5425+
["switch", "during-refresh", true],
5426+
["create-and-switch", "during-refresh", true],
5427+
["feature-branch", "during-refresh", true],
5428+
] as const)(
5429+
"local PR checkout excludes a concurrent %s from another client (%s, alternate root: %s)",
5430+
([operation, phase, alternateRoot]) =>
5431+
Effect.gen(function* () {
5432+
const gate = {
5433+
matches: (args: ReadonlyArray<string>) =>
5434+
args[0] === "rev-parse" &&
5435+
args[1] === "--verify" &&
5436+
(phase === "before-refresh"
5437+
? /^[0-9a-f]{40}\^\{commit\}$/.test(args[2] ?? "")
5438+
: args[2] === "HEAD^{commit}"),
5439+
reached: yield* Deferred.make<void>(),
5440+
release: yield* Deferred.make<void>(),
5441+
};
5442+
const { repoDir, manager, pullHead } = yield* setUpLocalCheckoutPullRequest(
5443+
(head) => head,
5444+
false,
5445+
gate,
5446+
);
5447+
const nestedCwd = NodePath.join(repoDir, "nested-project");
5448+
yield* makeDirectory(nestedCwd);
5449+
const mainCommit = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
5450+
yield* runGit(repoDir, ["checkout", "main"]);
5451+
const registry = yield* Layer.build(
5452+
VcsDriverRegistry.layer.pipe(
5453+
Layer.provide(VcsProjectConfig.layer),
5454+
Layer.provide(VcsProcess.layer),
5455+
),
5456+
);
5457+
const handle = yield* Context.get(registry, VcsDriverRegistry.VcsDriverRegistry).resolve({
5458+
cwd: repoDir,
5459+
});
5460+
const resolvedHandle = alternateRoot
5461+
? {
5462+
...handle,
5463+
repository: { ...handle.repository, rootPath: `${handle.repository.rootPath}/.` },
5464+
}
5465+
: handle;
5466+
const fileSystem = yield* FileSystem.FileSystem;
5467+
const canonicalRoot = yield* fileSystem.realPath(resolvedHandle.repository.rootPath);
5468+
const git = yield* GitVcsDriver.GitVcsDriver;
5469+
const events: string[] = [];
5470+
const workflows = yield* Effect.forEach([0, 1], () =>
5471+
GitWorkflowService.make.pipe(
5472+
// Cache the real filesystem result so startImmediately reaches lease acquisition.
5473+
Effect.provideService(FileSystem.FileSystem, {
5474+
...fileSystem,
5475+
realPath: (root) =>
5476+
root === resolvedHandle.repository.rootPath
5477+
? Effect.succeed(canonicalRoot)
5478+
: fileSystem.realPath(root),
5479+
}),
5480+
Effect.provideService(GitManager.GitManager, {
5481+
...manager,
5482+
runStackedAction: (input, options) =>
5483+
Effect.sync(() => {
5484+
events.push("feature-branch");
5485+
NodeFS.writeFileSync(
5486+
NodePath.join(repoDir, "second-client.txt"),
5487+
"second client\n",
5488+
);
5489+
}).pipe(Effect.andThen(manager.runStackedAction(input, options))),
5490+
}),
5491+
Effect.provideService(VcsDriverRegistry.VcsDriverRegistry, {
5492+
...Context.get(registry, VcsDriverRegistry.VcsDriverRegistry),
5493+
resolve: () => Effect.succeed(resolvedHandle),
5494+
}),
5495+
Effect.provideService(GitVcsDriver.GitVcsDriver, {
5496+
...git,
5497+
switchRef: (input) =>
5498+
Effect.sync(() => events.push("switch")).pipe(Effect.andThen(git.switchRef(input))),
5499+
createRef: (input) =>
5500+
Effect.sync(() => events.push("create-and-switch")).pipe(
5501+
Effect.andThen(git.createRef(input)),
5502+
),
5503+
}),
5504+
),
5505+
);
5506+
const preparing = yield* Effect.forkChild(
5507+
workflows[0]!.preparePullRequestThread({ cwd: repoDir, reference: "91", mode: "local" }),
5508+
);
5509+
yield* Deferred.await(gate.reached);
5510+
const switching = yield* Effect.forkChild(
5511+
operation === "switch"
5512+
? workflows[1]!.switchRef({ cwd: nestedCwd, refName: "main" })
5513+
: operation === "create-and-switch"
5514+
? workflows[1]!.createRef({
5515+
cwd: nestedCwd,
5516+
refName: "second-client",
5517+
switchRef: true,
5518+
})
5519+
: workflows[1]!.runStackedAction({
5520+
cwd: nestedCwd,
5521+
actionId: "second-client-feature-branch",
5522+
action: "commit",
5523+
featureBranch: true,
5524+
commitMessage: "Second client commit",
5525+
}),
5526+
{ startImmediately: true },
5527+
);
5528+
// Both independent server workflows have started, but the second cannot touch Git yet.
5529+
expect(events).toEqual([]);
5530+
yield* Deferred.succeed(gate.release, undefined);
5531+
const prepared = yield* Fiber.join(preparing);
5532+
const switched = yield* Fiber.join(switching);
5533+
expect(events).toEqual([operation]);
5534+
expect(prepared).toMatchObject({ branch: "feature/pr-safe", isOnPullRequestHead: true });
5535+
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(mainCommit);
5536+
expect((yield* runGit(repoDir, ["rev-parse", "feature/pr-safe"])).stdout.trim()).toBe(
5537+
pullHead,
5538+
);
5539+
expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe(
5540+
operation === "switch"
5541+
? "main"
5542+
: "branch" in switched
5543+
? switched.branch.name
5544+
: "second-client",
5545+
);
5546+
if ("commit" in switched) {
5547+
expect(switched.commit.status).toBe("created");
5548+
expect((yield* runGit(repoDir, ["rev-parse", "HEAD^"])).stdout.trim()).toBe(pullHead);
5549+
}
5550+
}),
5551+
);
5552+
54185553
it.effect.each([false, true])(
54195554
"local PR checkout refuses and preserves tracked edits (staged: %s)",
54205555
(staged) =>

‎apps/server/src/git/GitManager.ts‎

Lines changed: 44 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ import { detachStackFrame } from "./detachStackFrame.ts";
8383
import * as ServerSettings from "../serverSettings.ts";
8484
import type { GitManagerServiceError } from "@t3tools/contracts";
8585
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
86+
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
8687
import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
8788
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
8889
import type { ChangeRequest } from "@t3tools/contracts";
@@ -2641,28 +2642,52 @@ export const make = Effect.gen(function* () {
26412642
const pullRequest = toResolvedPullRequest(pullRequestSummary);
26422643

26432644
if (input.mode === "local") {
2644-
yield* ensureNoTrackedChanges(input.cwd, pullRequest.number);
2645-
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
2645+
const root = yield* gitCore.execute({
2646+
operation: "GitManager.preparePullRequestThread.root",
26462647
cwd: input.cwd,
2647-
reference: normalizedReference,
2648+
args: ["rev-parse", "--show-toplevel"],
26482649
});
2649-
const details = yield* gitCore.statusDetails(input.cwd);
2650-
yield* configurePullRequestHeadUpstream(
2651-
input.cwd,
2652-
{
2653-
...pullRequest,
2654-
...toPullRequestHeadRemoteInfo(pullRequestSummary),
2655-
},
2656-
details.branch ?? pullRequest.headBranch,
2650+
// All projects in this checkout share the lease, including ones rooted in a subdirectory.
2651+
return yield* withWorkspaceLease(
2652+
yield* canonicalizeExistingPath(root.stdout.trim()),
2653+
Effect.gen(function* () {
2654+
yield* ensureNoTrackedChanges(input.cwd, pullRequest.number);
2655+
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
2656+
cwd: input.cwd,
2657+
reference: normalizedReference,
2658+
});
2659+
const details = yield* gitCore.statusDetails(input.cwd);
2660+
yield* configurePullRequestHeadUpstream(
2661+
input.cwd,
2662+
{
2663+
...pullRequest,
2664+
...toPullRequestHeadRemoteInfo(pullRequestSummary),
2665+
},
2666+
details.branch ?? pullRequest.headBranch,
2667+
);
2668+
return {
2669+
pullRequest,
2670+
branch: details.branch ?? pullRequest.headBranch,
2671+
worktreePath: null,
2672+
// Unforced checkout leaves a branch that is ahead of, or could not be advanced to, the
2673+
// pull request where it is, so only the resulting HEAD says whether this is its head.
2674+
isOnPullRequestHead: yield* gitCore
2675+
.execute({
2676+
operation: "GitManager.preparePullRequestThread.currentBranch",
2677+
cwd: input.cwd,
2678+
args: ["symbolic-ref", "--quiet", "--short", "HEAD"],
2679+
allowNonZeroExit: true,
2680+
})
2681+
.pipe(
2682+
Effect.flatMap((current) =>
2683+
current.stdout.trim() === details.branch
2684+
? moveToPullRequestHead(input.cwd, pullRequestSummary.headSha)
2685+
: Effect.succeed(false),
2686+
),
2687+
),
2688+
};
2689+
}),
26572690
);
2658-
return {
2659-
pullRequest,
2660-
branch: details.branch ?? pullRequest.headBranch,
2661-
worktreePath: null,
2662-
// Unforced checkout leaves a branch that is ahead of, or could not be advanced to, the
2663-
// pull request where it is, so only the resulting HEAD says whether this is its head.
2664-
isOnPullRequestHead: yield* moveToPullRequestHead(input.cwd, pullRequestSummary.headSha),
2665-
};
26662691
}
26672692

26682693
const ensureExistingWorktreeUpstream = Effect.fn("ensureExistingWorktreeUpstream")(function* (

‎apps/server/src/git/GitWorkflowService.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { assert, describe, expect, it, vi } from "@effect/vitest";
1+
import { assert, expect, it, vi } from "@effect/vitest";
22
import * as DateTime from "effect/DateTime";
33
import * as Effect from "effect/Effect";
44
import * as Layer from "effect/Layer";
@@ -30,7 +30,7 @@ function layer(input: {
3030
);
3131
}
3232

33-
describe("GitWorkflowService", () => {
33+
it.layer(NodeServices.layer)("GitWorkflowService", (it) => {
3434
it.effect("reports a non-Git VCS repository as not a Git repository", () =>
3535
Effect.gen(function* () {
3636
const workflow = yield* GitWorkflowService.GitWorkflowService;

‎apps/server/src/git/GitWorkflowService.ts‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Context from "effect/Context";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
4+
import * as FileSystem from "effect/FileSystem";
45

56
import {
67
GitManagerError,
@@ -31,6 +32,7 @@ import {
3132
import * as GitManager from "./GitManager.ts";
3233
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
3334
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
35+
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
3436

3537
export class GitWorkflowService extends Context.Service<
3638
GitWorkflowService,
@@ -163,6 +165,13 @@ export const make = Effect.gen(function* () {
163165
const registry = yield* VcsDriverRegistry.VcsDriverRegistry;
164166
const git = yield* GitVcsDriver.GitVcsDriver;
165167
const gitManager = yield* GitManager.GitManager;
168+
const fileSystem = yield* FileSystem.FileSystem;
169+
170+
const withCheckoutLease = <A, E, R>(rootPath: string, effect: Effect.Effect<A, E, R>) =>
171+
fileSystem.realPath(rootPath).pipe(
172+
Effect.orElseSucceed(() => rootPath),
173+
Effect.flatMap((cwd) => withWorkspaceLease(cwd, effect)),
174+
);
166175

167176
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
168177
operation: string,
@@ -186,6 +195,7 @@ export const make = Effect.gen(function* () {
186195
detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,
187196
});
188197
}
198+
return handle;
189199
});
190200

191201
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
@@ -212,6 +222,7 @@ export const make = Effect.gen(function* () {
212222
detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
213223
});
214224
}
225+
return handle;
215226
});
216227

217228
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
@@ -352,7 +363,14 @@ export const make = Effect.gen(function* () {
352363
),
353364
runStackedAction: (input, options) =>
354365
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
355-
Effect.andThen(gitManager.runStackedAction(input, options)),
366+
Effect.flatMap((handle) =>
367+
input.featureBranch
368+
? withCheckoutLease(
369+
handle.repository.rootPath,
370+
gitManager.runStackedAction(input, options),
371+
)
372+
: gitManager.runStackedAction(input, options),
373+
),
356374
),
357375
resolvePullRequest: routeGitManager(
358376
"GitWorkflowService.resolvePullRequest",
@@ -406,11 +424,17 @@ export const make = Effect.gen(function* () {
406424
),
407425
createRef: (input) =>
408426
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
409-
Effect.andThen(git.createRef(input)),
427+
Effect.flatMap((handle) =>
428+
input.switchRef
429+
? withCheckoutLease(handle.repository.rootPath, git.createRef(input))
430+
: git.createRef(input),
431+
),
410432
),
411433
switchRef: (input) =>
412434
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
413-
Effect.andThen(Effect.scoped(git.switchRef(input))),
435+
Effect.flatMap((handle) =>
436+
withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))),
437+
),
414438
),
415439
renameBranch: (input) =>
416440
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(

0 commit comments

Comments
 (0)