fix(server): checkpoint workspaces with empty nested repositories (#12181)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-17 16:48:18 -07:00
1 parent fcfd9f911a
commit 1455cb5c35
2 files changed
+371 -20

No files matched your search

+292 -1
View File
@@ -1,5 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Cause from "effect/Cause";
import * as Exit from "effect/Exit";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -7,7 +12,7 @@ import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { assert, it } from "@effect/vitest";
import { CheckpointRef, GitCommandError } from "@t3tools/contracts";
import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";
@@ -86,6 +91,292 @@ const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* (
return { git, checkpointRef };
});
it.effect("checkpoint capture skips untracked nested repositories without a commit", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-unborn-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
const nested = "scratch/empty [repo]";
yield* git(["init", nested]);
yield* git(["init", "another empty"]);
yield* fileSystem.writeFileString(path.join(cwd, nested, "private.txt"), "nested\n");
yield* git(["init", "committed"]);
yield* git([
"-C",
"committed",
"-c",
"user.name=Test",
"-c",
"[email protected]",
"commit",
"--allow-empty",
"-m",
"initial",
]);
const nestedHead = (yield* git(["-C", "committed", "rev-parse", "HEAD"])).stdout.trim();
yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n");
const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n");
assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", nested])).stdout, "");
assert.strictEqual((yield* git(["ls-tree", checkpointRef, "--", "another empty"])).stdout, "");
assert.strictEqual(
(yield* git(["ls-tree", checkpointRef, "--", "committed"])).stdout,
`160000 commit ${nestedHead}\tcommitted\n`,
);
assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
assert.strictEqual(
yield* fileSystem.readFileString(path.join(cwd, nested, "private.txt")),
"nested\n",
);
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-git-dir-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* git(["init", "empty"]);
const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
yield* Effect.acquireUseRelease(
Effect.sync(() => {
const previous = process.env.GIT_DIR;
process.env.GIT_DIR = path.join(cwd, ".git");
return previous;
}),
() => driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
(previous) =>
Effect.sync(() => {
if (previous === undefined) delete process.env.GIT_DIR;
else process.env.GIT_DIR = previous;
}),
);
assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n");
assert.strictEqual((yield* git(["ls-tree", "-r", checkpointRef, "--", "empty"])).stdout, "");
assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect("checkpoint capture still fails when a clean filter rejects a file", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-checkpoint-filter-failure-",
});
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* fileSystem.writeFileString(path.join(cwd, ".gitattributes"), "file.txt filter=reject\n");
yield* git(["config", "filter.reject.clean", "false"]);
yield* git(["config", "filter.reject.required", "true"]);
const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
const result = yield* Effect.result(
driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
);
assert.strictEqual(result._tag, "Failure");
assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect("checkpoint capture refuses a truncated nested repository listing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const liveProcess = yield* VcsProcess.VcsProcess;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-truncated-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* git(["init", "empty"]);
const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
Effect.provideService(VcsProcess.VcsProcess, {
run: (input) =>
liveProcess
.run(input)
.pipe(
Effect.map((result) =>
input.args.includes("--others") ? { ...result, stdoutTruncated: true } : result,
),
),
}),
);
const result = yield* Effect.result(
captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
);
assert.strictEqual(result._tag, "Failure");
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect("checkpoint recovery refuses excessive candidates before probing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const liveProcess = yield* VcsProcess.VcsProcess;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-cap-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* git(["init", "empty0"]);
for (let i = 1; i < 65; i++)
yield* fs.copy(path.join(cwd, "empty0"), path.join(cwd, `empty${i}`));
const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
let stageError: VcsProcessExitError | undefined;
let nestedProbes = 0;
let stageAttempts = 0;
const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
Effect.provideService(VcsProcess.VcsProcess, {
run: (input) => {
if (input.cwd !== cwd && input.args.includes("rev-parse")) nestedProbes++;
if (input.args.includes("add") && input.args.includes("-A")) stageAttempts++;
return liveProcess.run(input).pipe(
Effect.tapError((error) => {
if (error._tag === "VcsProcessExitError") stageError = error;
return Effect.void;
}),
);
},
}),
);
const result = yield* Effect.result(
captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }),
);
assert.strictEqual(nestedProbes, 0);
assert.strictEqual(stageAttempts, 1);
assert.strictEqual(result._tag, "Failure");
if (result._tag === "Failure") assert.strictEqual(result.failure, stageError);
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
it.effect(`checkpoint recovery has one deadline including ${blockedPhase}`, () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const liveProcess = yield* VcsProcess.VcsProcess;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-timeout-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* git(["init", "empty"]);
const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
const entered = yield* Deferred.make<void>();
const discovered = yield* Deferred.make<void>();
let stageError: VcsProcessExitError | undefined;
let privateIndex: string | undefined;
let interrupted = false;
const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
Effect.provideService(VcsProcess.VcsProcess, {
run: (input) => {
const staging = input.args.includes("add") && input.args.includes("-A");
if (staging) privateIndex = input.env?.GIT_INDEX_FILE;
const block =
(blockedPhase === "discovery" && input.args.includes("--others")) ||
(blockedPhase === "probe" && input.cwd !== cwd && input.args.includes("rev-parse")) ||
(blockedPhase === "retry" &&
staging &&
input.args.some((arg) => arg.startsWith(":(exclude,literal)")));
if (block)
return (
blockedPhase === "retry"
? fs
.writeFileString(
`${input.env!.GIT_INDEX_FILE!}.lock`,
"interrupted index write",
)
.pipe(Effect.orDie)
: Effect.void
).pipe(
Effect.andThen(Deferred.succeed(entered, undefined)),
Effect.andThen(Effect.never),
Effect.onInterrupt(() =>
Effect.sync(() => {
interrupted = true;
}),
),
);
return liveProcess.run(input).pipe(
Effect.tap(() =>
blockedPhase === "probe" && input.args.includes("--others")
? Deferred.succeed(discovered, undefined).pipe(
Effect.andThen(Effect.sleep("3 seconds")),
)
: Effect.void,
),
Effect.tapError((error) => {
if (staging && error._tag === "VcsProcessExitError") stageError = error;
return Effect.void;
}),
);
},
}),
);
const fiber = yield* captureDriver.checkpoints
.captureCheckpoint({ cwd, checkpointRef })
.pipe(Effect.flip, Effect.forkScoped);
if (blockedPhase === "probe") {
yield* Deferred.await(discovered);
yield* TestClock.adjust("3 seconds");
}
yield* Deferred.await(entered);
yield* TestClock.adjust(blockedPhase === "probe" ? "2 seconds" : "5 seconds");
const error = yield* Fiber.join(fiber);
assert.strictEqual(error, stageError);
assert.isTrue(interrupted);
assert.isDefined(privateIndex);
assert.isFalse(yield* fs.exists(privateIndex!));
assert.isFalse(yield* fs.exists(`${privateIndex!}.lock`));
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
}
it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const liveProcess = yield* VcsProcess.VcsProcess;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-interrupt-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
yield* git(["init", "empty"]);
const entered = yield* Deferred.make<void>();
let privateIndex: string | undefined;
const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
Effect.provideService(VcsProcess.VcsProcess, {
run: (input) => {
if (input.args.includes("add") && input.args.includes("-A"))
privateIndex = input.env?.GIT_INDEX_FILE;
return input.args.includes("--others")
? Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never))
: liveProcess.run(input);
},
}),
);
const fiber = yield* captureDriver.checkpoints
.captureCheckpoint({ cwd, checkpointRef })
.pipe(Effect.forkScoped);
yield* Deferred.await(entered);
yield* Fiber.interrupt(fiber);
const exit = yield* Fiber.await(fiber);
assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause));
assert.isDefined(privateIndex);
assert.isFalse(yield* fs.exists(privateIndex!));
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect("checkpoint capture does not rerun clean filters for unchanged indexed files", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+79 -19
View File
@@ -379,6 +379,8 @@ export class GitVcsDriver extends Context.Service<
>()("t3/vcs/GitVcsDriver") {}
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64;
const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds";
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
@@ -715,12 +717,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
}),
);
const hasHeadCommit = (cwd: string) =>
const hasHeadCommit = (cwd: string, env?: NodeJS.ProcessEnv) =>
execute({
operation: "GitVcsDriver.checkpoints.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
...(env !== undefined ? { env } : {}),
}).pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>
@@ -784,9 +787,12 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
GIT_COMMITTER_EMAIL: "[email protected]",
};
const cleanupTempIndex = fileSystem
.remove(tempIndexPath, { force: true })
.pipe(Effect.ignore);
// Forced process termination can leave Git's private index lock behind.
const cleanupTempIndex = Effect.forEach(
[tempIndexPath, `${tempIndexPath}.lock`],
(indexFile) => fileSystem.remove(indexFile, { force: true }).pipe(Effect.ignore),
{ discard: true },
);
yield* Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
@@ -914,21 +920,75 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
}
}
yield* execute({
operation,
cwd: input.cwd,
// Preserve absent skipped entries, but capture present nonignored files outside the cone.
args: [
...indexConfig,
...durableWrite,
"add",
...(sparseCheckout ? ["--sparse"] : []),
"-A",
"--",
".",
],
env: commitEnv,
});
const stageFiles = (exclusions: ReadonlyArray<string>) =>
execute({
operation,
cwd: input.cwd,
// Preserve absent skipped entries, but capture present nonignored files outside the cone.
args: [
...indexConfig,
...durableWrite,
"add",
...(sparseCheckout ? ["--sparse"] : []),
"-A",
"--",
".",
...exclusions,
],
env: commitEnv,
});
yield* stageFiles([]).pipe(
Effect.catchTags({
VcsProcessExitError: (error) =>
Effect.gen(function* () {
// Git cannot stage an embedded repository until it has a commit. Discover these
// only after staging fails so ordinary checkpoints do not need another file scan.
const untracked = yield* execute({
operation,
cwd: input.cwd,
args: ["ls-files", "--others", "--exclude-standard", "-z", "--", "."],
env: commitEnv,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
});
if (untracked.stdoutTruncated) return yield* error;
const candidates = splitNullSeparatedGitStdoutPaths(untracked).filter((entry) =>
entry.endsWith("/"),
);
// Refuse excessive recovery work before probing any nested repositories.
if (candidates.length > CHECKPOINT_RECOVERY_MAX_CANDIDATES) return yield* error;
// Discover each child's repository instead of inheriting the server's Git bindings.
const nestedRepoEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_DIR: undefined,
GIT_WORK_TREE: undefined,
GIT_COMMON_DIR: undefined,
GIT_INDEX_FILE: undefined,
GIT_OBJECT_DIRECTORY: undefined,
GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,
};
const exclusions: Array<string> = [];
for (const entry of candidates) {
const nestedCwd = path.join(input.cwd, entry);
if (
(yield* fileSystem
.exists(path.join(nestedCwd, ".git"))
.pipe(Effect.mapError(() => error))) &&
!(yield* hasHeadCommit(nestedCwd, nestedRepoEnv))
) {
exclusions.push(`:(exclude,literal)${entry}`);
}
}
if (exclusions.length === 0) return yield* error;
return yield* stageFiles(exclusions);
}).pipe(
// One budget covers discovery, queued Git admission, probes, and the staging retry.
Effect.timeoutOrElse({
duration: CHECKPOINT_RECOVERY_TIMEOUT,
orElse: () => Effect.fail(error),
}),
),
}),
);
const writeTreeResult = yield* execute({
operation,