TypeScript
fix(server): a rollback blocked by Git's index lock says so instead of a generic error (#11340)
shivam9448aa572a75
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.tsindex abacb6d666a..6e408e512ff 100644--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts@@ -5,6 +5,7 @@ import {type OrchestrationV2DomainEvent,ProviderThreadId,ThreadId,+ VcsProcessExitError,} from "@t3tools/contracts";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -24,10 +25,11 @@ import {isCheckpointRestoreIsolated,SHARED_WORKSPACE_RESTORE_MESSAGE,} from "./CheckpointRestoreSafety.ts";-import { CheckpointServiceV2 } from "./CheckpointService.ts";+import { CheckpointRestoreError, CheckpointServiceV2 } from "./CheckpointService.ts";import { EventSinkV2 } from "./EventSink.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import { ProjectionStoreV2 } from "./ProjectionStore.ts";+import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";import * as ProjectStore from "./ProjectStore.ts";import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";@@ -70,6 +72,20 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo}const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);+const isVcsProcessExitError = Schema.is(VcsProcessExitError);+const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);++/**+ * The message clients see when a rollback fails. Only a held Git index lock+ * gets its own explanation; other reasons carry internal ids or raw Git+ * output, so they fall back to the generic message.+ */+export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {+ const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;+ return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL+ ? GIT_INDEX_LOCKED_DETAIL+ : ROLLBACK_FAILED_MESSAGE;+}export interface CheckpointRollbackServiceV2Shape {readonly execute: (input: {diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.tsindex 99676e6613a..77e9a263ddb 100644--- a/apps/server/src/orchestration-v2/EffectWorker.test.ts+++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts@@ -1,5 +1,7 @@import { assert, it } from "@effect/vitest";import {+ CheckpointId,+ CheckpointScopeId,CommandId,NodeId,ProviderSessionId,@@ -8,6 +10,7 @@ import {RunAttemptId,RunId,ThreadId,+ VcsProcessExitError,} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as DateTime from "effect/DateTime";@@ -21,6 +24,7 @@ import * as Ref from "effect/Ref";import * as TestClock from "effect/testing/TestClock";import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";+import * as CheckpointService from "./CheckpointService.ts";import * as EffectOutbox from "./EffectOutbox.ts";import * as EffectWorker from "./EffectWorker.ts";import * as RunFinalizationService from "./RunFinalizationService.ts";@@ -83,6 +87,7 @@ function layerExecutorFor(input: {readonly threads?: Partial<ThreadManagementService.ThreadManagementService["Service"]>;readonly continueAfterRestart?: boolean;readonly interrupt?: ProviderTurnControlService.ProviderTurnControlServiceV2Shape["interrupt"];+ readonly rollback?: CheckpointRollbackService.CheckpointRollbackServiceV2Shape["execute"];}) {const record = (event: string) => Ref.update(input.events, (events) => [...events, event]);const layerDependencies = Layer.mergeAll(@@ -136,7 +141,9 @@ function layerExecutorFor(input: {),Layer.succeed(CheckpointRollbackService.CheckpointRollbackServiceV2,- CheckpointRollbackService.CheckpointRollbackServiceV2.of({ execute: () => Effect.void }),+ CheckpointRollbackService.CheckpointRollbackServiceV2.of({+ execute: input.rollback ?? (() => Effect.void),+ }),),Layer.succeed(RuntimeRequestService.RuntimeRequestServiceV2,@@ -231,6 +238,75 @@ it.effect("settles a stopped run when its adapter has already lost the native tu}),);+const lockedIndexMessage =+ "Git's index is locked. Wait for other Git operations to finish, then try again.";+const rollbackCheckpointId = CheckpointId.make("checkpoint:effect-worker-rollback");+const rollbackScopeId = CheckpointScopeId.make("checkpoint-scope:effect-worker-rollback");+const restoreFailure = (detail: string) =>+ new CheckpointRollbackService.CheckpointRollbackExecutionError({+ reason: "unexpected-failure",+ threadId,+ providerThreadId,+ checkpointId: rollbackCheckpointId,+ cause: new CheckpointService.CheckpointRestoreError({+ scopeId: rollbackScopeId,+ checkpointId: rollbackCheckpointId,+ cause: new VcsProcessExitError({+ operation: "GitVcsDriverCore.restoreCheckpoint",+ command: "git",+ cwd: "/private/repo",+ exitCode: 128,+ detail,+ failureKind: "command-failed",+ }),+ }),+ });++it.effect.each([+ {+ name: "a held Git index lock",+ failure: restoreFailure(lockedIndexMessage),+ message: lockedIndexMessage,+ },+ {+ name: "raw Git output",+ failure: restoreFailure("error: could not clean /private/repo/secret.txt"),+ message: CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,+ },+])("reports a rollback blocked by $name only after the last attempt", ({ failure, message }) =>+ Effect.gen(function* () {+ const now = yield* DateTime.now;+ const failures = yield* Ref.make<ReadonlyArray<string>>([]);+ const layer = layerExecutorFor({+ events: yield* Ref.make<ReadonlyArray<string>>([]),+ rollback: () => Effect.fail(failure),+ threads: {+ dispatch: (command) =>+ Ref.update(failures, (current) =>+ command.type === "checkpoint.rollback.fail" ? [...current, command.message] : current,+ ).pipe(Effect.as({ sequence: 1, storedEvents: [] })),+ },+ });+ yield* Effect.gen(function* () {+ const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;+ const rollback: EffectOutbox.OrchestrationEffectV2 = {+ ...restartEffect(now, { type: "detach" }),+ request: {+ type: "provider-thread.rollback",+ providerThreadId,+ checkpointId: rollbackCheckpointId,+ scopeId: rollbackScopeId,+ restoreFiles: true,+ },+ };+ yield* Effect.flip(executor.execute(rollback, { willRetry: true }));+ assert.deepEqual(yield* Ref.get(failures), []);+ yield* Effect.flip(executor.execute(rollback, { willRetry: false }));+ }).pipe(Effect.provide(layer));+ assert.deepEqual(yield* Ref.get(failures), [message]);+ }),+);+it.effect("requeues a claim when a pre-execution worker check fails", () =>Effect.gen(function* () {const now = DateTime.formatIso(yield* DateTime.now);diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.tsindex 6227e3a5df2..a44b60c2498 100644--- a/apps/server/src/orchestration-v2/EffectWorker.ts+++ b/apps/server/src/orchestration-v2/EffectWorker.ts@@ -422,7 +422,10 @@ export const layerExecutor: Layer.Layer<commandId: CommandId.make(`${effect.commandId}:rollback-failed`),threadId: effect.threadId,requestId: effect.commandId,- message: CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,+ message: Option.match(Cause.findErrorOption(cause), {+ onNone: () => CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,+ onSome: CheckpointRollbackService.rollbackFailureClientMessage,+ }),}).pipe(Effect.catchCause((recordCause) =>diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.tsindex e5fcd758cc4..e6de543c124 100644--- a/apps/server/src/vcs/VcsProcess.test.ts+++ b/apps/server/src/vcs/VcsProcess.test.ts@@ -57,8 +57,63 @@ const captureProcessResult = ();describe("VcsProcess.run", () => {+ it.effect("explains a locked Git index and allows restore after the lock is released", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" });+ const git = (args: readonly string[]) =>+ run({ operation: "test.checkpoint.restore", command: "git", cwd, args });+ yield* git(["init"]);+ const file = path.join(cwd, "README.md");+ yield* fs.writeFileString(file, "before\n");+ yield* git(["add", "README.md"]);+ yield* git([+ "-c",+ "user.name=Test",+ "-c",+ "[email protected]",+ "commit",+ "-m",+ "initial",+ ]);+ yield* fs.writeFileString(file, "after\n");+ const lock = path.join(cwd, ".git", "index.lock");+ yield* fs.writeFileString(lock, "held by another process\n");+ const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"];++ const error = yield* Effect.flip(git(restore));+ expect(error).toBeInstanceOf(VcsProcessExitError);+ expect(error).toMatchObject({+ exitCode: 128,+ failureKind: "command-failed",+ detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",+ });+ expect(error.message).not.toContain("index.lock");+ expect(yield* fs.readFileString(file)).toBe("after\n");+ expect(yield* fs.readFileString(lock)).toBe("held by another process\n");++ yield* fs.remove(lock);+ yield* git(restore);+ expect(yield* fs.readFileString(file)).toBe("before\n");+ }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),+ );+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': File exists",+ retryable: true,+ detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",+ },+ {+ stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.",+ retryable: true,+ detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",+ },+ {+ stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.",+ retryable: true,+ },{stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",retryable: false,@@ -75,8 +130,8 @@ describe("VcsProcess.run", () => {},{ stderr: "fatal: index file corrupt", retryable: false },])(- "classifies Git exit retryability without retaining stderr: $stderr",- ({ stderr, retryable }) =>+ "classifies Git exit retryability and safe detail without retaining stderr: $stderr",+ ({ stderr, retryable, detail = "Process exited with a non-zero status." }) =>Effect.gen(function* () {const error = yield* captureProcessResult(Effect.succeed({@@ -92,8 +147,9 @@ describe("VcsProcess.run", () => {);assert.instanceOf(error, VcsProcessExitError);expect(error.retryable === true).toBe(retryable);+ expect(error.detail).toBe(detail);const encoded = yield* encodeExitError(error);- expect(encoded).not.toContain("/private/repo");+ expect(encoded).not.toContain("private");}),);diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.tsindex e4eba5f0fb2..42ca8d28370 100644--- a/apps/server/src/vcs/VcsProcess.ts+++ b/apps/server/src/vcs/VcsProcess.ts@@ -62,6 +62,10 @@ const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";const VCS_PROCESS_CONCURRENCY = 8;const GITHUB_PROCESS_CONCURRENCY = 4;+/** Shown to users when a Git command fails because another process holds the index lock. */+export const GIT_INDEX_LOCKED_DETAIL =+ "Git's index is locked. Wait for other Git operations to finish, then try again.";+export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";/**@@ -263,7 +267,7 @@ export const make = Effect.gen(function* () {if (!input.allowNonZeroExit && result.code !== 0) {const failureKind = classifyNonZeroExit(input.command, result.stderr);- return yield* VcsProcessExitError.fromProcessExit(+ const error = VcsProcessExitError.fromProcessExit(baseError,{exitCode: result.code,@@ -275,6 +279,18 @@ export const make = Effect.gen(function* () {failureKind === "command-failed" &&isTransientGitExit(result.stderr),);+ if (+ input.command === "git" &&+ /^fatal: unable to create ['"][^\r\n]*[/\\]index\.lock['"]: file exists\.?$/im.test(+ result.stderr,+ )+ ) {+ return yield* new VcsProcessExitError({+ ...error,+ detail: GIT_INDEX_LOCKED_DETAIL,+ });+ }+ return yield* error;}return {