Skip to content

Commit eac6d35

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, so one sweep cost 2 + 2N 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. - Under the worktree lease, recheck 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 0caa95d commit eac6d35

6 files changed

Lines changed: 582 additions & 23 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
);
@@ -350,6 +415,10 @@ it.effect("memory recovery selection includes unfinished items from missing runs
350415
);
351416

352417
it.layer(layerTest)("ProjectionStoreV2", (it) => {
418+
it.effect(
419+
"worktree path lookup skips deleted threads and keeps archived ones",
420+
() => threadWorktreePathsSkipDeletedThreads,
421+
);
353422
it.effect(
354423
"keeps restart-cancelled work through a stale run.updated",
355424
() => restartCancelledWorkSurvivesStaleRunUpdate,

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,15 @@ export interface ProjectionStoreV2Shape {
408408
readonly getThreadsWithPullRequests: (
409409
threadId?: ThreadId,
410410
) => Effect.Effect<ReadonlyArray<ProjectionThreadPullRequests>, ProjectionStoreV2Error>;
411+
/**
412+
* Every non-deleted thread, archived or not, that has a worktree path. Reads
413+
* only the thread rows, so callers can check who uses a path without a shell
414+
* snapshot.
415+
*/
416+
readonly getThreadWorktreePaths: () => Effect.Effect<
417+
ReadonlyArray<{ readonly threadId: ThreadId; readonly worktreePath: string }>,
418+
ProjectionStoreV2Error
419+
>;
411420
readonly getTurnStartContext: (
412421
threadId: ThreadId,
413422
runId: RunId,
@@ -5566,6 +5575,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
55665575
);
55675576
}).pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));
55685577

5578+
const getThreadWorktreePaths: ProjectionStoreV2Shape["getThreadWorktreePaths"] = () =>
5579+
sql<{ readonly thread_id: string; readonly worktree_path: string }>`
5580+
SELECT thread_id, json_extract(payload_json, '$.worktreePath') AS worktree_path
5581+
FROM orchestration_v2_projection_threads
5582+
WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL
5583+
`.pipe(
5584+
Effect.map((rows) =>
5585+
rows.map((row) => ({
5586+
threadId: ThreadId.make(row.thread_id),
5587+
worktreePath: row.worktree_path,
5588+
})),
5589+
),
5590+
Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
5591+
);
5592+
55695593
const shellThreadStateFromRow = (input: {
55705594
readonly row: ShellThreadRow;
55715595
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
@@ -5906,6 +5930,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
59065930
getThread,
59075931
getSettlementCandidates,
59085932
getThreadsWithPullRequests,
5933+
getThreadWorktreePaths,
59095934
getThreadProjection,
59105935
getTurnStartContext,
59115936
getTurnStartHistory,
@@ -6048,6 +6073,16 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
60486073
left.id.localeCompare(right.id),
60496074
);
60506075
}),
6076+
getThreadWorktreePaths: () =>
6077+
Ref.get(replayState).pipe(
6078+
Effect.map((state) =>
6079+
[...state.projections.values()].flatMap(({ thread }) =>
6080+
thread.deletedAt === null && thread.worktreePath !== null
6081+
? [{ threadId: thread.id, worktreePath: thread.worktreePath }]
6082+
: [],
6083+
),
6084+
),
6085+
),
60516086
getThreadsWithPullRequests: (threadId) =>
60526087
Ref.get(replayState).pipe(
60536088
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)