TypeScript
fix(server): storage cleanup reaches archived threads' worktrees (#16473)
Info-Cado034b50616165
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 74377160a82..34fc75a64d2 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -512,7 +512,7 @@ const restartCancelledWorkSurvivesStaleRunUpdate = Effect.gen(function* () {assert.deepEqual(updated?.restartCancelledBackgroundWork, work);});-const threadWorktreePathsReadActiveThreads = Effect.gen(function* () {+const threadWorktreePathsIncludeArchivedOnRequest = Effect.gen(function* () {const store = yield* ProjectionStore.ProjectionStoreV2;const now = yield* DateTime.now;const create = (id: string, input: { worktreePath: string | null; archived?: boolean }) => {@@ -565,6 +565,10 @@ const threadWorktreePathsReadActiveThreads = Effect.gen(function* () {assert.deepEqual(yield* store.getThreadWorktreePaths(), [{ threadId: ThreadId.make("thread:active"), worktreePath: "/worktrees/active" },]);+ assert.deepEqual(yield* store.getThreadWorktreePaths({ includeArchived: true }), [+ { threadId: ThreadId.make("thread:active"), worktreePath: "/worktrees/active" },+ { threadId: ThreadId.make("thread:archived"), worktreePath: "/worktrees/archived" },+ ]);});const commandReadsSkipSettledLeafNodes = Effect.gen(function* () {@@ -650,8 +654,10 @@ it.effect("memory command reads skip finished leaf nodes of finished runs", () =commandReadsSkipSettledLeafNodes.pipe(Effect.provide(ProjectionStore.layerMemory)),);-it.effect("memory worktree path lookup reads only active threads", () =>- threadWorktreePathsReadActiveThreads.pipe(Effect.provide(ProjectionStore.layerMemory)),+it.effect(+ "memory worktree path lookup defaults to active threads and can include archived threads",+ () =>+ threadWorktreePathsIncludeArchivedOnRequest.pipe(Effect.provide(ProjectionStore.layerMemory)),);it.effect("memory projection keeps restart-cancelled work through a stale run.updated", () =>@@ -878,8 +884,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {() => runlessNativeSubagentNeedsRecovery,);it.effect(- "worktree path lookup reads only active threads",- () => threadWorktreePathsReadActiveThreads,+ "worktree path lookup defaults to active threads and can include archived threads",+ () => threadWorktreePathsIncludeArchivedOnRequest,);it.effect(diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 002ef7bafa9..fedd86a4841 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -422,7 +422,9 @@ export interface ProjectionStoreV2Shape {readonly getThreadsWithPullRequests: (threadId?: ThreadId,) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequests>, ProjectionStoreV2Error>;- readonly getThreadWorktreePaths: () => Effect.Effect<+ readonly getThreadWorktreePaths: (options?: {+ readonly includeArchived?: boolean;+ }) => Effect.Effect<ReadonlyArray<{ readonly threadId: ThreadId; readonly worktreePath: string }>,ProjectionStoreV2Error>;@@ -5739,12 +5741,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =);}).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));- const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = () =>+ const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = (options) =>sql<{ readonly thread_id: string; readonly worktree_path: string }>`SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_pathFROM orchestration_v2_projection_threadsWHERE deleted_at IS NULL- AND json_extract(payload_json, '$.archivedAt') IS NULL+ ${options?.includeArchived === true ? sql`` : sql`AND json_extract(payload_json, '$.archivedAt') IS NULL`}AND json_extract(payload_json, '$.worktreePath') IS NOT NULL`.pipe(Effect.map((rows) =>@@ -6240,12 +6242,12 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(left.id.localeCompare(right.id),);}),- getThreadWorktreePaths: () =>+ getThreadWorktreePaths: (options) =>Ref.get(replayState).pipe(Effect.map((state) =>[...state.projections.values()].flatMap(({ thread }) =>thread.deletedAt === null &&- thread.archivedAt === null &&+ (options?.includeArchived === true || thread.archivedAt === null) &&thread.worktreePath !== null? [{ threadId: thread.id, worktreePath: thread.worktreePath }]: [],diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.tsindex e3870f8af0c..6ef6f5b3f01 100644--- a/apps/server/src/storageCleanup.test.ts+++ b/apps/server/src/storageCleanup.test.ts@@ -306,14 +306,26 @@ const cleanupFixture = (getShellSnapshot: (input?: { location?: string }) =>Effect.sync(() => {snapshotReads++;- return { threads: input?.location === "archive" ? [] : threads };+ const visible = threads.filter((thread) => thread.deletedAt === null);+ return {+ threads:+ input?.location === "archive"+ ? []+ : visible.filter((thread) => thread.archivedAt === null),+ archivedThreads:+ input?.location === "active"+ ? []+ : visible.filter((thread) => thread.archivedAt !== null),+ };}),- getThreadWorktreePaths: () =>+ getThreadWorktreePaths: (input?: { includeArchived?: boolean }) =>Effect.sync(() =>threads.flatMap((thread) =>- thread.worktreePath === null- ? []- : [{ threadId: thread.id, worktreePath: thread.worktreePath }],+ thread.deletedAt === null &&+ (input?.includeArchived === true || thread.archivedAt === null) &&+ thread.worktreePath !== null+ ? [{ threadId: thread.id, worktreePath: thread.worktreePath }]+ : [],),),getThreadShell: (threadId: ThreadId) =>@@ -1176,6 +1188,41 @@ describe("orphan worktree reports", () => {});describe("storage cleanup reports and local file policies", () => {+ it.effect("automatically removes an eligible archived thread checkout", () =>+ runCleanupTest(+ Effect.gen(function* () {+ yield* TestClock.setTime(NOW_MS);+ const fixture = yield* cleanupFixture();+ fixture.setThreads([+ shell({+ branch: "feature",+ worktreePath: fixture.worktree,+ archivedAt: at(-DAY_MS),+ }),+ ]);+ yield* fixture.activate(Stream.empty);+ const [report] = yield* fixture.service.reports.pipe(+ Stream.filter((report) => report !== null),+ Stream.take(1),+ Stream.runCollect,+ );+ yield* fixture.service.drain;+ expect(report).toMatchObject({+ trigger: "automatic",+ counts: { removed: 1, kept: 0, failed: 0 },+ entries: [+ {+ threadId: "thread-1",+ path: fixture.worktree,+ outcome: "removed",+ reason: "Inactive for 30 days",+ },+ ],+ });+ expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);+ }),+ ),+ );it.live.each(["before-check", "while-measuring"] as const)("keeps a worktree protected by a missing project root (%s)",(timing) =>@@ -1264,6 +1311,18 @@ describe("storage cleanup reports and local file policies", () => {shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }),],],+ [+ "an archived thread starts using it",+ (worktree: string) => [+ shell({ branch: "feature", worktreePath: worktree }),+ shell({+ id: ThreadId.make("thread-2"),+ branch: "feature",+ worktreePath: worktree,+ archivedAt: at(-DAY_MS),+ }),+ ],+ ],] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) =>runCleanupTest(Effect.gen(function* () {@@ -1542,6 +1601,17 @@ describe("storage cleanup reports and local file policies", () => {shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }),]);expect((yield* service.runNow).entries[0]?.reason).toBe("Shared by 2 threads");+ setThreads([+ shell({ branch: "feature", worktreePath: worktree }),+ shell({+ id: ThreadId.make("thread-2"),+ branch: "feature",+ worktreePath: worktree,+ archivedAt: at(-DAY_MS),+ }),+ ]);+ expect((yield* service.runNow).entries[0]?.reason).toBe("Shared by 2 threads");+ expect(yield* fs.exists(worktree)).toBe(true);fixture.disable();expect((yield* service.runNow).entries).toEqual([]);yield* fs.remove(worktree, { recursive: true });diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.tsindex d6844486742..697811409da 100644--- a/apps/server/src/storageCleanup.ts+++ b/apps/server/src/storageCleanup.ts@@ -291,11 +291,9 @@ const make = Effect.gen(function* () {// The snapshot takes seconds on large databases, so it runs on the reader// worker instead of the event loop.const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {- const { threads } = yield* projections- .getShellSnapshot({ location: "active" })- .pipe(NodeSqliteClient.readOnly);+ const snapshot = yield* projections.getShellSnapshot().pipe(NodeSqliteClient.readOnly);const projects = yield* projectStore.listShells();- return { projects, threads };+ return { projects, threads: [...snapshot.threads, ...snapshot.archivedThreads] };});const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (@@ -740,9 +738,9 @@ const make = Effect.gen(function* () {const latestProjects = yield* projectStore.listShells();if (yield* containsProjectRoot(worktreePath, [project, ...latestProjects]))return "contains a project checkout";- const latest = (yield* projections.getThreadWorktreePaths()).filter(- (entry) => path.resolve(entry.worktreePath) === worktreePath,- );+ const latest = (yield* projections.getThreadWorktreePaths({+ includeArchived: true,+ })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath);if (hasTerminal(worktreePath)) return "open terminal";if (deleted) {if (