fix(server): retry transient git failures during checkpoint capture (#11665)

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-18 11:42:28 -07:00
1 parent e84f23a97d
commit 869347bc26
5 files changed
+348 -4

No files matched your search

+140 -2
View File
@@ -1,5 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Exit from "effect/Exit";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -14,7 +16,11 @@ import { assert, it } from "@effect/vitest";
import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts";
import * as ServerConfig from "../config.ts";
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import type * as VcsDriver from "./VcsDriver.ts";
import * as VcsDriverRegistry from "./VcsDriverRegistry.ts";
import * as VcsProcess from "./VcsProcess.ts";
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
@@ -26,6 +32,10 @@ const GitContractLayer = Layer.mergeAll(GitVcsDriver.vcsLayer, GitVcsDriver.laye
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
const GitCaptureContractLayer = Layer.merge(
GitContractLayer,
ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)),
);
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
@@ -38,6 +48,22 @@ const runGit = (cwd: string, args: ReadonlyArray<string>) =>
});
});
const makeCaptureStore = Effect.fn("test.makeCaptureStore")(function* (
driver: VcsDriver.VcsDriver["Service"],
cwd: string,
) {
const repository = yield* driver.detectRepository(cwd);
if (repository === null) return yield* Effect.die("Expected a test Git repository");
const handle = { kind: repository.kind, repository, driver };
return yield* CheckpointStore.make.pipe(
Effect.provideService(VcsDriverRegistry.VcsDriverRegistry, {
get: () => Effect.succeed(driver),
detect: () => Effect.succeed(handle),
resolve: () => Effect.succeed(handle),
}),
);
});
type GitContractError = GitCommandError | PlatformError.PlatformError;
runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
@@ -260,6 +286,112 @@ it.effect("checkpoint recovery refuses excessive candidates before probing", ()
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
it.effect.each([
{ phase: "add", nestedRecovery: false, expireRecovery: false },
{ phase: "update-ref", nestedRecovery: false, expireRecovery: false },
{ phase: "update-ref", nestedRecovery: true, expireRecovery: false },
{ phase: "add", nestedRecovery: true, expireRecovery: false },
{ phase: "add", nestedRecovery: true, expireRecovery: true },
])(
"checkpoint handles a $phase lock with nestedRecovery=$nestedRecovery, expireRecovery=$expireRecovery",
({ phase, nestedRecovery, expireRecovery }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const liveRunner = yield* ProcessRunner.ProcessRunner;
const driver = yield* GitVcsDriver.makeVcsDriverShape();
const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ref-race-" });
const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
if (nestedRecovery) yield* git(["init", "empty"]);
const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index"));
const refLockPath = path.join(cwd, ".git", `${checkpointRef}.lock`);
const failed = yield* Deferred.make<void>();
const retryReached = yield* Deferred.make<void>();
const allowRetry = yield* Deferred.make<void>();
const clock = yield* Clock.Clock;
const privateIndexes = new Set<string>();
let racedAttempts = 0;
let discoveries = 0;
let stageError: VcsProcessExitError | undefined;
const captureProcess = yield* VcsProcess.make.pipe(
Effect.provideService(ProcessRunner.ProcessRunner, {
run: (input) => {
if (input.args.includes("--others")) discoveries += 1;
if (input.env?.GIT_INDEX_FILE) privateIndexes.add(input.env.GIT_INDEX_FILE);
const initialStage =
phase === "add" &&
nestedRecovery &&
!input.args.some((arg) => arg.startsWith(":(exclude,literal)"));
if (!input.args.includes(phase) || initialStage || ++racedAttempts !== 1) {
return liveRunner.run(input);
}
const lockPath = phase === "add" ? `${input.env!.GIT_INDEX_FILE!}.lock` : refLockPath;
return Effect.gen(function* () {
yield* fs
.makeDirectory(path.dirname(lockPath), { recursive: true })
.pipe(Effect.orDie);
yield* fs.writeFileString(lockPath, "concurrent ref writer").pipe(Effect.orDie);
return yield* liveRunner.run(input).pipe(
Effect.ensuring(fs.remove(lockPath).pipe(Effect.orDie)),
Effect.tap(() => Deferred.succeed(failed, undefined)),
);
});
},
}),
);
const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
Effect.provideService(VcsProcess.VcsProcess, {
run: (input) =>
captureProcess.run(input).pipe(
Effect.tapError((error) => {
if (input.args.includes("add") && error._tag === "VcsProcessExitError")
stageError = error;
return Effect.void;
}),
),
}),
);
const captureStore = yield* makeCaptureStore(captureDriver, cwd);
const fiber = yield* captureStore.captureCheckpoint({ cwd, checkpointRef }).pipe(
Effect.provideService(Clock.Clock, {
...clock,
sleep: (duration) =>
Duration.toMillis(duration) === 75
? Deferred.succeed(retryReached, undefined).pipe(
Effect.andThen(Deferred.await(allowRetry)),
)
: clock.sleep(duration),
}),
Effect.exit,
Effect.forkScoped,
);
yield* Deferred.await(failed);
yield* Deferred.await(retryReached);
if (expireRecovery) yield* TestClock.adjust("5 seconds");
else yield* Deferred.succeed(allowRetry, undefined);
const result = yield* Fiber.join(fiber);
if (expireRecovery) {
if (Exit.isSuccess(result))
return yield* Effect.die("Expected the recovery deadline to expire");
const error = Cause.findErrorOption(result.cause);
assert.isTrue(error._tag === "Some");
if (error._tag === "Some") assert.strictEqual(error.value, stageError);
} else assert.isTrue(Exit.isSuccess(result));
assert.strictEqual(racedAttempts, expireRecovery ? 1 : 2);
assert.strictEqual(discoveries, nestedRecovery ? 1 : 0);
assert.strictEqual(privateIndexes.size, 1);
assert.strictEqual(
yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }),
!expireRecovery,
);
for (const index of privateIndexes) {
assert.isFalse(yield* fs.exists(index));
assert.isFalse(yield* fs.exists(`${index}.lock`));
}
assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
}).pipe(Effect.scoped, Effect.provide(GitCaptureContractLayer)),
);
for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
it.effect(`checkpoint recovery has one deadline including ${blockedPhase}`, () =>
Effect.gen(function* () {
@@ -276,11 +408,15 @@ for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
let stageError: VcsProcessExitError | undefined;
let privateIndex: string | undefined;
let interrupted = false;
let stagingAttempts = 0;
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;
if (staging) {
privateIndex = input.env?.GIT_INDEX_FILE;
stagingAttempts += 1;
}
const block =
(blockedPhase === "discovery" && input.args.includes("--others")) ||
(blockedPhase === "probe" && input.cwd !== cwd && input.args.includes("rev-parse")) ||
@@ -322,7 +458,8 @@ for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
},
}),
);
const fiber = yield* captureDriver.checkpoints
const captureStore = yield* makeCaptureStore(captureDriver, cwd);
const fiber = yield* captureStore
.captureCheckpoint({ cwd, checkpointRef })
.pipe(Effect.flip, Effect.forkScoped);
if (blockedPhase === "probe") {
@@ -333,6 +470,7 @@ for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
yield* TestClock.adjust(blockedPhase === "probe" ? "2 seconds" : "5 seconds");
const error = yield* Fiber.join(fiber);
assert.strictEqual(error, stageError);
assert.strictEqual(stagingAttempts, blockedPhase === "retry" ? 2 : 1);
assert.isTrue(interrupted);
assert.isDefined(privateIndex);
assert.isFalse(yield* fs.exists(privateIndex!));
+1 -1
View File
@@ -766,7 +766,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (
const checkpoints: VcsDriver.VcsCheckpointOps = {
captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) {
const operation = "GitVcsDriver.checkpoints.captureCheckpoint";
const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION;
const indexConfig = [
"-c",
"core.fsmonitor=false",
+169
View File
@@ -4,10 +4,13 @@ import { HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
import * as Duration from "effect/Duration";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Cause from "effect/Cause";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import { TestClock } from "effect/testing";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -19,6 +22,8 @@ import {
import * as ProcessRunner from "../processRunner.ts";
import * as VcsProcess from "./VcsProcess.ts";
const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
const run = (input: VcsProcess.VcsProcessInput) =>
Effect.gen(function* () {
const process = yield* VcsProcess.VcsProcess;
@@ -50,6 +55,170 @@ const captureProcessResult = (
);
describe("VcsProcess.run", () => {
it.effect.each([
{ stderr: "fatal: Unable to create '/private/repo/index.lock': File exists", retryable: true },
{
stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
retryable: false,
},
{ stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
{
stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
retryable: true,
},
{ stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
{
stderr: "error: '/private/repo/child/' does not have a commit checked out",
retryable: false,
},
{ stderr: "fatal: index file corrupt", retryable: false },
])(
"classifies Git exit retryability without retaining stderr: $stderr",
({ stderr, retryable }) =>
Effect.gen(function* () {
const error = yield* captureProcessResult(
Effect.succeed({
stdout: "",
stderr,
code: ChildProcessSpawner.ExitCode(128),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
}),
);
assert.instanceOf(error, VcsProcessExitError);
expect(error.retryable === true).toBe(retryable);
const encoded = yield* encodeExitError(error);
expect(encoded).not.toContain("/private/repo");
}),
);
it.effect.each(["timeout", "spawn"] as const)(
"checkpoint commands do not retry %s failures",
(kind) =>
Effect.gen(function* () {
let attempts = 0;
const fields = { command: "git", argumentCount: 2, cwd: "/workspace" };
const failure =
kind === "timeout"
? new ProcessRunner.ProcessTimeoutError({ ...fields, timeoutMs: 30_000 })
: new ProcessRunner.ProcessSpawnError({ ...fields, cause: new Error("spawn failed") });
const service = yield* VcsProcess.make.pipe(
Effect.provideService(ProcessRunner.ProcessRunner, {
run: () =>
Effect.sync(() => {
attempts += 1;
}).pipe(Effect.andThen(Effect.fail(failure))),
}),
);
const error = yield* service
.run({
...baseInput,
operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
})
.pipe(Effect.flip);
expect(attempts).toBe(1);
expect(error._tag).toBe(
kind === "timeout" ? "VcsProcessTimeoutError" : "VcsProcessSpawnError",
);
}),
);
it.effect.each([
{
name: "recovers after two lock failures",
failures: 2,
attempts: 3,
transient: true,
capture: true,
streaming: false,
},
{
name: "bounds persistent lock failures",
failures: Infinity,
attempts: 3,
transient: true,
capture: true,
streaming: false,
},
{
name: "does not retry unknown exits",
failures: Infinity,
attempts: 1,
transient: false,
capture: true,
streaming: false,
},
{
name: "leaves other operations unchanged",
failures: Infinity,
attempts: 1,
transient: true,
capture: false,
streaming: false,
},
{
name: "does not replay stdout callbacks",
failures: Infinity,
attempts: 1,
transient: true,
capture: true,
streaming: true,
},
])(
"checkpoint command retry $name",
({ failures, attempts: expectedAttempts, transient, capture, streaming }) =>
Effect.gen(function* () {
let attempts = 0;
const service = yield* VcsProcess.make.pipe(
Effect.provideService(ProcessRunner.ProcessRunner, {
run: () =>
Effect.sync(() => {
attempts += 1;
return {
stdout: "",
stderr:
attempts > failures
? ""
: transient
? "fatal: Unable to create '/repo/index.lock': File exists"
: "fatal: index file corrupt",
code: ChildProcessSpawner.ExitCode(attempts > failures ? 0 : attempts),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
stderrInvalidUtf8: false,
};
}),
}),
);
const fiber = yield* service
.run({
...baseInput,
operation: capture ? VcsProcess.CHECKPOINT_CAPTURE_OPERATION : baseInput.operation,
...(streaming ? { onStdoutChunk: () => {} } : {}),
})
.pipe(Effect.exit, Effect.forkScoped);
yield* TestClock.adjust("150 millis");
const result = yield* Fiber.join(fiber);
expect(attempts).toBe(expectedAttempts);
if (failures === Infinity) {
if (Exit.isSuccess(result))
return yield* Effect.die("Expected a capture command failure");
const error = Cause.findErrorOption(result.cause);
if (error._tag === "None" || error.value._tag !== "VcsProcessExitError") {
return yield* Effect.die("Expected a Git exit error");
}
expect(error.value.exitCode).toBe(expectedAttempts);
} else {
expect(Exit.isSuccess(result)).toBe(true);
}
}),
);
it.effect("bounds a synthetic burst of GitHub API processes", () =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
+34 -1
View File
@@ -1,7 +1,9 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Match from "effect/Match";
import * as Schedule from "effect/Schedule";
import * as Semaphore from "effect/Semaphore";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -58,6 +60,8 @@ const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
const VCS_PROCESS_CONCURRENCY = 8;
const GITHUB_PROCESS_CONCURRENCY = 4;
export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
const normalized = stderr.toLowerCase();
@@ -104,6 +108,11 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
return "command-failed";
};
// Classify before discarding stderr; keep paths and process output out of errors.
const isTransientGitExit = (stderr: string) =>
/unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) ||
/(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr);
export const make = Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
@@ -167,6 +176,7 @@ export const make = Effect.gen(function* () {
}
if (!input.allowNonZeroExit && result.code !== 0) {
const failureKind = classifyNonZeroExit(input.command, result.stderr);
return yield* VcsProcessExitError.fromProcessExit(
baseError,
{
@@ -174,7 +184,10 @@ export const make = Effect.gen(function* () {
stderr: result.stderr,
stderrTruncated: result.stderrTruncated,
},
classifyNonZeroExit(input.command, result.stderr),
failureKind,
input.command === "git" &&
failureKind === "command-failed" &&
isTransientGitExit(result.stderr),
);
}
@@ -191,6 +204,26 @@ export const make = Effect.gen(function* () {
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
if (
input.command === "git" &&
input.operation === CHECKPOINT_CAPTURE_OPERATION &&
input.onStdoutChunk === undefined
) {
// Retry the failed command, retaining the private index/tree and recovery's outer deadline.
return yield* bounded.pipe(
Effect.tapError((error) =>
Effect.logDebug("checkpoint Git command failed", {
operation: input.operation,
errorTag: error._tag,
}),
),
Effect.retry({
times: 2,
while: (error) => error._tag === "VcsProcessExitError" && error.retryable === true,
schedule: Schedule.spaced(Duration.millis(75)),
}),
);
}
return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
});
+4
View File
@@ -119,6 +119,8 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
exitCode: Schema.Number,
detail: Schema.String,
failureKind: Schema.optional(VcsProcessExitFailureKind),
/** Process-boundary hint for a recognized transient failure; absence is not retryable. */
retryable: Schema.optional(Schema.Boolean),
stderrLength: Schema.optional(NonNegativeInt),
stderrTruncated: Schema.optional(Schema.Boolean),
},
@@ -131,6 +133,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
context: VcsProcessErrorContext,
error: VcsProcessExitFailure,
failureKind: VcsProcessExitFailureKind,
retryable?: boolean,
) {
const detail =
failureKind === "authentication"
@@ -150,6 +153,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
exitCode: error.exitCode,
detail,
failureKind,
...(retryable === true ? { retryable: true } : {}),
stderrLength: error.stderr.length,
stderrTruncated: error.stderrTruncated,
});