Skip to content

Commit f72a7e2

Browse files
fix(server): worktree cleanup no longer runs sweeps back to back
Every thread.deleted and provider-session.updated event queued another full sweep, and the worker never merged them. Each eligible worktree also re-read the full active and archived thread snapshot under its lease, before and after measuring its size, so one sweep cost up to 2 + 4N snapshot reads for N eligible worktrees. - At most one automatic sweep waits at a time. The hourly schedule, settings changes and domain events all request it; later requests join it. Each manual run still gets its own sweep and report. - Request a sweep only for session updates that reach "stopped" or "error". Moves between live statuses cannot free a worktree. - The under-lease recheck reads the project list, the threads that use this path (new ProjectionStore.getThreadWorktreePaths), this thread's shell and the live sessions. The snapshot is read once per sweep, and recheck skips report the same reasons as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent febe1b2 commit f72a7e2

6 files changed

Lines changed: 571 additions & 24 deletions

File tree

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,71 @@ const restartCancelledWorkSurvivesStaleRunUpdate = Effect.gen(function* () {
327327
assert.deepEqual(updated?.restartCancelledBackgroundWork, work);
328328
});
329329

330+
const threadWorktreePathsSkipDeletedThreads = Effect.gen(function* () {
331+
const store = yield* ProjectionStore.ProjectionStoreV2;
332+
const now = yield* DateTime.now;
333+
const create = (id: string, input: { worktreePath: string | null; archived?: boolean }) => {
334+
const threadId = ThreadId.make(id);
335+
const thread = {
336+
createdBy: "user" as const,
337+
creationSource: "web" as const,
338+
id: threadId,
339+
projectId: ProjectId.make("project:worktree-paths"),
340+
title: id,
341+
providerInstanceId,
342+
modelSelection,
343+
runtimeMode: "full-access" as const,
344+
interactionMode: "default" as const,
345+
branch: input.worktreePath === null ? null : id,
346+
worktreePath: input.worktreePath,
347+
activeProviderThreadId: null,
348+
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
349+
forkedFrom: null,
350+
createdAt: now,
351+
updatedAt: now,
352+
archivedAt: input.archived === true ? now : null,
353+
settledOverride: null,
354+
settledAt: null,
355+
lastVisitedAt: null,
356+
deletedAt: null,
357+
};
358+
return store
359+
.apply({
360+
id: EventId.make(`event:${id}:created`),
361+
type: "thread.created",
362+
threadId,
363+
occurredAt: now,
364+
payload: thread,
365+
})
366+
.pipe(Effect.as(thread));
367+
};
368+
yield* create("thread:active", { worktreePath: "/worktrees/active" });
369+
yield* create("thread:archived", { worktreePath: "/worktrees/archived", archived: true });
370+
yield* create("thread:local", { worktreePath: null });
371+
const deleted = yield* create("thread:deleted", { worktreePath: "/worktrees/deleted" });
372+
yield* store.apply({
373+
id: EventId.make("event:thread:deleted:deleted"),
374+
type: "thread.deleted",
375+
threadId: deleted.id,
376+
occurredAt: now,
377+
payload: { ...deleted, deletedAt: now },
378+
});
379+
380+
assert.deepEqual(
381+
(yield* store.getThreadWorktreePaths()).toSorted((left, right) =>
382+
left.threadId.localeCompare(right.threadId),
383+
),
384+
[
385+
{ threadId: ThreadId.make("thread:active"), worktreePath: "/worktrees/active" },
386+
{ threadId: ThreadId.make("thread:archived"), worktreePath: "/worktrees/archived" },
387+
],
388+
);
389+
});
390+
391+
it.effect("memory worktree path lookup skips deleted threads and keeps archived ones", () =>
392+
threadWorktreePathsSkipDeletedThreads.pipe(Effect.provide(ProjectionStore.layerMemory)),
393+
);
394+
330395
it.effect("memory projection keeps restart-cancelled work through a stale run.updated", () =>
331396
restartCancelledWorkSurvivesStaleRunUpdate.pipe(Effect.provide(ProjectionStore.layerMemory)),
332397
);
@@ -501,6 +566,10 @@ it.effect("memory shell snapshots scope to one project", () =>
501566
);
502567

503568
it.layer(layerTest)("ProjectionStoreV2", (it) => {
569+
it.effect(
570+
"worktree path lookup skips deleted threads and keeps archived ones",
571+
() => threadWorktreePathsSkipDeletedThreads,
572+
);
504573
it.effect(
505574
"keeps restart-cancelled work through a stale run.updated",
506575
() => restartCancelledWorkSurvivesStaleRunUpdate,

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,15 @@ export interface ProjectionStoreV2Shape {
414414
readonly getThreadsWithPullRequests: (
415415
threadId?: ThreadId,
416416
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequests>, ProjectionStoreV2Error>;
417+
/**
418+
* Every non-deleted thread, archived or not, that has a worktree path. Reads
419+
* only the thread rows, so callers can check who uses a path without a shell
420+
* snapshot.
421+
*/
422+
readonly getThreadWorktreePaths: () => Effect.Effect<
423+
ReadonlyArray<{ readonly threadId: ThreadId; readonly worktreePath: string }>,
424+
ProjectionStoreV2Error
425+
>;
417426
readonly getTurnStartContext: (
418427
threadId: ThreadId,
419428
runId: RunId,
@@ -5610,6 +5619,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
56105619
);
56115620
}).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));
56125621

5622+
const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = () =>
5623+
sql<{ readonly thread_id: string; readonly worktree_path: string }>`
5624+
SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_path
5625+
FROM orchestration_v2_projection_threads
5626+
WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
5627+
`.pipe(
5628+
Effect.map((rows) =>
5629+
rows.map((row) => ({
5630+
threadId: ThreadId.make(row.thread_id),
5631+
worktreePath: row.worktree_path,
5632+
})),
5633+
),
5634+
Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
5635+
);
5636+
56135637
const shellThreadStateFromRow = (input: {
56145638
readonly row: ShellThreadRow;
56155639
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
@@ -5946,6 +5970,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
59465970
getThread,
59475971
getSettlementCandidates,
59485972
getThreadsWithPullRequests,
5973+
getThreadWorktreePaths,
59495974
getThreadProjection,
59505975
getTurnStartContext,
59515976
getTurnStartHistory,
@@ -6094,6 +6119,16 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
60946119
left.id.localeCompare(right.id),
60956120
);
60966121
}),
6122+
getThreadWorktreePaths: () =>
6123+
Ref.get(replayState).pipe(
6124+
Effect.map((state) =>
6125+
[...state.projections.values()].flatMap(({ thread }) =>
6126+
thread.deletedAt === null && thread.worktreePath !== null
6127+
? [{ threadId: thread.id, worktreePath: thread.worktreePath }]
6128+
: [],
6129+
),
6130+
),
6131+
),
60976132
getThreadsWithPullRequests: (threadId) =>
60986133
Ref.get(replayState).pipe(
60996134
Effect.map((state) =>

‎apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ it.effect(
218218
getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
219219
getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
220220
getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
221+
getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
221222
getThreadProjection: () => Effect.die("control effects must not load transcript"),
222223
getTurnStartContext: () => Effect.die("unused"),
223224
getTurnStartHistory: () => Effect.die("unused"),

0 commit comments

Comments
 (0)