Skip to content

The open-source app everyone uses to manage agents at work

fix: describe unexpected git expiration failures in the result (#17341)

Devin Foley62c78e56e533
diff --git a/server/src/__tests__/git-workspace-expiration.test.ts b/server/src/__tests__/git-workspace-expiration.test.ts
index 8e9db5c0b8..9e470c3de5 100644
--- a/server/src/__tests__/git-workspace-expiration.test.ts
+++ b/server/src/__tests__/git-workspace-expiration.test.ts
@@ -1,7 +1,8 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
-import { execFileSync, spawnSync } from "node:child_process";
+import { execFile, execFileSync, spawnSync } from "node:child_process";
+import { promisify } from "node:util";
import { randomUUID } from "node:crypto";
import { pathToFileURL } from "node:url";
import { createRequire } from "node:module";
@@ -18,7 +19,7 @@ import { materializeIsolatedRemoteWorkspaceSource } from "../services/isolated-r
import { realizeExecutionWorkspace, ensurePersistedExecutionWorkspaceAvailable } from "../services/workspace-runtime.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { prepareProjectRepositoryWorkspaces, mergeExecutionWorkspaceMetadataForPersistence } from "../services/heartbeat/workspaces.js";
-import { expireReconstructableGitWorkspace } from "../services/git-workspace-expiration.js";
+import { describeGitExpirationFailure, expireReconstructableGitWorkspace } from "../services/git-workspace-expiration.js";
import * as activityLog from "../services/activity-log.js";
import { readGitCacheRestoration } from "../services/git-workspace-restoration.js";
import { gitCacheExpirationLockLocations, readGitCacheExpiration } from "../services/git-workspace-restoration.js";
@@ -821,6 +822,47 @@ describeEmbeddedPostgres("reconstructable Git expiration", () => {
expect(await exists(f.cwd)).toBe(true);
});
+ it("describes an unexpected inspection failure without the command or credentials", async () => {
+ const f = await fixture();
+ await fs.writeFile(path.join(f.cwd, ".git"), `gitdir: ${path.join(f.cwd, "missing-admin")}\n`);
+ const result = await f.expire();
+ expect(result).toMatchObject({ expired: false, skipReason: "inspection_failed",
+ failure: { name: "Error", code: expect.any(String), at: expect.stringMatching(/^at /), stderr: expect.stringContaining("not a git repository") } });
+ expect(await exists(f.cwd)).toBe(true);
+ });
+
+ it.skipIf(process.getuid?.() === 0)("describes an unexpected failure while inspecting the base", async () => {
+ const f = await fixture();
+ const locked = path.join(f.baseCwd, "locked-dir");
+ const result = await f.expire({ beforeDelete: async () => {
+ await fs.mkdir(locked);
+ await fs.writeFile(path.join(locked, "file"), "x");
+ await fs.chmod(locked, 0o000);
+ } });
+ await fs.chmod(locked, 0o755);
+ expect(result).toMatchObject({ expired: true, baseExpired: false, skipReason: "inspection_failed",
+ failure: { code: "EACCES", at: expect.stringMatching(/^at /) } });
+ });
+
+ it("redacts credentials from a described git failure", async () => {
+ const error = await promisify(execFile)("git", ["-c", "http.extraHeader=Authorization: Bearer sk-secret-header",
+ "ls-remote", "https://user:[email protected]:9/repo.git"], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } })
+ .then(() => { throw new Error("expected git to fail"); }, (error: Error) => error);
+ const described = describeGitExpirationFailure(error);
+ expect(JSON.stringify(described)).not.toContain("sk-secret");
+ expect(JSON.stringify(described)).not.toContain("ls-remote");
+ expect(described).toMatchObject({ name: "Error", code: expect.any(String), stderr: expect.any(String) });
+ });
+
+ it("redacts credentials that git echoes on stderr", () => {
+ const error = Object.assign(new Error("Command failed: git fetch https://user:[email protected]/repo.git"), {
+ code: 128, stderr: "fatal: unable to access 'https://user:[email protected]/repo.git/'\nheader Authorization: Bearer sk-secret-header\n" });
+ const described = describeGitExpirationFailure(error);
+ expect(JSON.stringify(described)).not.toContain("sk-secret");
+ expect(described.stderr).toContain("https://<redacted>@example.test/repo.git");
+ expect(described.code).toBe("128");
+ });
+
it("retries after interruption with the restoration recipe already committed", async () => {
const f = await fixture();
expect((await f.expire({ beforeDelete: async () => { throw new Error("interrupted_fixture"); } })).expired).toBe(false);
diff --git a/server/src/services/git-workspace-expiration.ts b/server/src/services/git-workspace-expiration.ts
index 0d9684f5e9..d60583d9c2 100644
--- a/server/src/services/git-workspace-expiration.ts
+++ b/server/src/services/git-workspace-expiration.ts
@@ -43,8 +43,33 @@ const DAY_MS = 24 * 60 * 60 * 1000;
type Workspace = typeof executionWorkspaces.$inferSelect;
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
type Expiration = GitCacheExpiration;
+export type GitExpirationFailure = { name: string; code: string | null; at: string | null; stderr: string | null };
+
export type GitExpirationResult = { candidate: boolean; expired: boolean; reclaimedBytes: number;
- candidateBytes: number; baseExpired: boolean; skipReason: string | null; restorePoint: boolean };
+ candidateBytes: number; baseExpired: boolean; skipReason: string | null; restorePoint: boolean; failure?: GitExpirationFailure };
+
+function redactGitOutput(text: string) {
+ return text.replace(/:\/\/[^@\s/]+@/g, "://<redacted>@")
+ .replace(/(authorization|token|password|secret)(\s*[:=]\s*)[^\n]*/gi, "$1$2<redacted>");
+}
+
+function recordSkip(result: GitExpirationResult, error: unknown) {
+ result.skipReason = error instanceof RestorePointSkip ? error.reason : skipReason(error);
+ if (result.skipReason === "inspection_failed") result.failure = describeGitExpirationFailure(error);
+}
+
+export function describeGitExpirationFailure(error: unknown): GitExpirationFailure {
+ if (!(error instanceof Error)) return { name: typeof error, code: null, at: null, stderr: null };
+ const details = error as Error & { code?: unknown; stderr?: unknown };
+ const frame = error.stack?.split("\n").slice(1).map(line => line.trim()).find(line => line.startsWith("at ")) ?? null;
+ const stderr = typeof details.stderr === "string" ? details.stderr : Buffer.isBuffer(details.stderr) ? details.stderr.toString("utf8") : "";
+ return {
+ name: error.name,
+ code: details.code === undefined || details.code === null ? null : String(details.code),
+ at: frame ? frame.slice(0, 300) : null,
+ stderr: stderr.trim() ? redactGitOutput(stderr.trim()).slice(0, 500) : null,
+ };
+}
export type GitRestorePointExpirationOptions = {
storage: StorageService;
@@ -271,7 +296,7 @@ export async function expireReconstructableGitWorkspace(db: Db, snapshot: Worksp
if (options.expireBase) {
try { result.candidateBytes += await inspectBase(db, { ...workspace,
metadata: { ...workspace.metadata, [GIT_CACHE_RESTORATION_KEY]: recipe } }, options.signal, present); }
- catch (error) { result.skipReason = skipReason(error); }
+ catch (error) { recordSkip(result, error); }
}
return result;
}
@@ -416,7 +441,7 @@ export async function expireReconstructableGitWorkspace(db: Db, snapshot: Worksp
result.reclaimedBytes += bytes;
result.baseExpired = true;
}
- } catch (error) { result.skipReason = skipReason(error); }
+ } catch (error) { recordSkip(result, error); }
}
state.completed = recipe.sourceKind !== "isolated_remote" || !options.expireBase || (result.baseExpired || !await exists(recipe.sourcePath)) && (!state.baseTrash || !await exists(state.baseTrash));
await persist();
@@ -425,7 +450,7 @@ export async function expireReconstructableGitWorkspace(db: Db, snapshot: Worksp
} catch (error) {
for (const ledgerId of pendingRestorePoints) await abandonGitRestorePoint(db, ledgerId).catch(() => undefined);
options.signal?.throwIfAborted();
- result.skipReason = error instanceof RestorePointSkip ? error.reason : skipReason(error);
+ recordSkip(result, error);
return result;
}
}