Skip to content
TypeScript

fix(server): clean up worktrees shared by subagents (#19748)

mariae733a40295f3
diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts
index a29e5d2a051..daab7cceff8 100644
--- a/apps/server/src/storageCleanup.test.ts
+++ b/apps/server/src/storageCleanup.test.ts
@@ -463,6 +463,199 @@ const runCleanupTest = <A, E>(
>,
) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped);
+describe("subagent worktree ownership", () => {
+ it.effect.each([
+ "idle",
+ "grandchild",
+ "null-branch",
+ "stale-branch",
+ "isolated-owner",
+ "fork-owner",
+ "missing-parent",
+ "cycle",
+ "two-tops",
+ "wrong-root",
+ "running",
+ "pending",
+ "unrelated",
+ "fork",
+ "recent-activity",
+ "recent-inactive",
+ "recent-grace",
+ "recent-settle",
+ "child-settled-now",
+ "child-settled-only",
+ ] as const)("checks the whole owner group (%s)", (scenario) =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(NOW_MS);
+ const fixture = yield* cleanupFixture();
+ fixture.setSettings({
+ storageCleanup: {
+ ...DEFAULT_SERVER_SETTINGS.storageCleanup,
+ worktreeSettledAfterDays: scenario === "recent-inactive" ? null : 8,
+ worktreeAfterDays: scenario === "recent-inactive" ? 8 : null,
+ },
+ });
+ const root = shell({
+ branch: "feature",
+ worktreePath: fixture.worktree,
+ settledAt: scenario === "child-settled-only" ? null : at(-20 * DAY_MS),
+ ...(scenario === "isolated-owner" || scenario === "fork-owner"
+ ? {
+ lineage: {
+ parentThreadId: ThreadId.make("ancestor"),
+ rootThreadId: ThreadId.make("ancestor"),
+ relationshipToParent:
+ scenario === "fork-owner" ? ("fork" as const) : ("subagent" as const),
+ },
+ }
+ : {}),
+ });
+ const child = shell({
+ id: ThreadId.make("child"),
+ branch:
+ scenario === "null-branch"
+ ? null
+ : scenario === "stale-branch"
+ ? "t3/15a6e5ae"
+ : "feature",
+ worktreePath: fixture.worktree,
+ lineage: {
+ parentThreadId:
+ scenario === "missing-parent"
+ ? ThreadId.make("missing")
+ : scenario === "cycle"
+ ? ThreadId.make("child")
+ : scenario === "two-tops"
+ ? null
+ : root.id,
+ rootThreadId:
+ scenario === "wrong-root" ? ThreadId.make("other-root") : root.lineage.rootThreadId,
+ relationshipToParent:
+ scenario === "fork" ? "fork" : scenario === "unrelated" ? null : "subagent",
+ },
+ status: scenario === "running" ? "running" : "completed",
+ pendingBackgroundTasks: scenario === "pending" ? [{ taskId: "task", kind: "command" }] : [],
+ latestRunCompletedAt:
+ scenario === "recent-activity" || scenario === "recent-inactive"
+ ? at(-2 * DAY_MS)
+ : scenario === "recent-grace"
+ ? at(-30_000)
+ : null,
+ settledAt: scenario === "child-settled-only" ? at(-20 * DAY_MS) : null,
+ });
+ const grandchild = {
+ ...child,
+ id: ThreadId.make("grandchild"),
+ lineage: { ...child.lineage, parentThreadId: child.id },
+ };
+ // The worktree owner can follow its children in the snapshot.
+ fixture.setThreads(
+ scenario === "grandchild"
+ ? [grandchild, child, root]
+ : scenario === "isolated-owner" || scenario === "fork-owner"
+ ? [child, root, shell({ id: ThreadId.make("ancestor") })]
+ : [child, root],
+ );
+ if (scenario === "recent-settle" || scenario === "child-settled-now")
+ fixture.setThreads([
+ {
+ ...child,
+ settledAt: scenario === "recent-settle" ? at(0) : at(-20 * DAY_MS),
+ updatedAt: at(0),
+ },
+ root,
+ ]);
+ const report = yield* fixture.service.runNow;
+ const removed = ["idle", "grandchild", "isolated-owner", "fork-owner"].includes(scenario);
+ const shared = [
+ "unrelated",
+ "fork",
+ "missing-parent",
+ "cycle",
+ "two-tops",
+ "wrong-root",
+ ].includes(scenario);
+ expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed);
+ expect(report.entries[0]).toMatchObject({
+ threadId: shared ? child.id : root.id,
+ outcome: removed ? "removed" : "kept",
+ reason: removed
+ ? "Settled for 20 days"
+ : scenario === "running" || scenario === "pending"
+ ? "Thread is running or has pending work"
+ : shared
+ ? "Shared by 2 threads"
+ : scenario === "null-branch" || scenario === "stale-branch"
+ ? "A subagent thread's branch differs from this worktree's branch"
+ : scenario === "recent-activity"
+ ? "Settled for 2 of 8 days"
+ : scenario === "recent-inactive"
+ ? "Inactive for 2 of 8 days"
+ : ["recent-grace", "recent-settle", "child-settled-now"].includes(scenario)
+ ? "Settled moments ago"
+ : "Not settled",
+ });
+ }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
+ );
+
+ it.live.each([
+ "running",
+ "pending",
+ "activity",
+ "unrelated",
+ "settled",
+ "resettled",
+ "null-branch",
+ "stale-branch",
+ ] as const)("cancels removal when a child changes during measurement (%s)", (change) =>
+ runCleanupTest(
+ Effect.gen(function* () {
+ const fixture = yield* pausedMeasurementFixture();
+ const root = shell({ branch: "feature", worktreePath: fixture.worktree });
+ const child = {
+ ...root,
+ id: ThreadId.make("child"),
+ settledAt: change === "resettled" ? at(-20 * DAY_MS) : null,
+ lineage: {
+ parentThreadId: root.id,
+ rootThreadId: root.id,
+ relationshipToParent: "subagent" as const,
+ },
+ };
+ fixture.setThreads([child, root]);
+ const run = yield* fixture.service.runNow.pipe(Effect.forkChild);
+ yield* Deferred.await(fixture.measuring);
+ fixture.setThreads([
+ root,
+ {
+ ...child,
+ branch:
+ change === "null-branch"
+ ? null
+ : change === "stale-branch"
+ ? "t3/15a6e5ae"
+ : child.branch,
+ settledAt: change === "settled" ? at(-20 * DAY_MS) : child.settledAt,
+ updatedAt: change === "settled" || change === "resettled" ? at(0) : child.updatedAt,
+ status: change === "running" ? "running" : "idle",
+ pendingBackgroundTasks:
+ change === "pending" ? [{ taskId: "task", kind: "command" }] : [],
+ latestRunCompletedAt: change === "activity" ? at(-DAY_MS) : null,
+ },
+ ...(change === "unrelated" ? [shell({ ...root, id: ThreadId.make("other") })] : []),
+ ]);
+ yield* Deferred.succeed(fixture.resume, undefined);
+ expect((yield* Fiber.join(run)).entries[0]).toMatchObject({
+ outcome: "kept",
+ reason: "Thread activity or shared worktree changed since check",
+ });
+ expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
+ }),
+ ),
+ );
+});
+
describe("storage cleanup reports and local file policies", () => {
it.live("measures nested regular files without following symlinks", () =>
runCleanupTest(
@@ -505,6 +698,14 @@ describe("storage cleanup reports and local file policies", () => {
),
);
it.live.each([
+ [
+ "its owner's branch is cleared",
+ (worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })],
+ ],
+ [
+ "its owner's branch changes",
+ (worktree: string) => [shell({ branch: "other", worktreePath: worktree, updatedAt: at(0) })],
+ ],
[
"its thread starts",
(worktree: string) => [
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index 627bc410c52..2c5fece9e15 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -107,7 +107,6 @@ function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings
/** Live sessions keep their cwd even when no turn is currently running. */
export function storageCleanupThreadIdle(thread: OrchestrationV2ThreadShell, now: number): boolean {
return (
- thread.branch !== null &&
thread.worktreePath !== null &&
thread.activeRunId === null &&
(thread.status === "idle" ||
@@ -135,6 +134,32 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu
);
}
+/** Only a complete subagent chain within this worktree shares ownership. */
+function worktreeOwner(threads: ReadonlyArray<OrchestrationV2ThreadShell>) {
+ if (threads.length === 1) return threads[0];
+ const byId = new Map(threads.map((thread) => [thread.id, thread]));
+ const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!));
+ if (tops.length !== 1) return undefined;
+ const owner = tops[0]!;
+ for (const thread of threads) {
+ let current = thread;
+ const seen = new Set<string>();
+ while (current.id !== owner.id) {
+ if (
+ seen.has(current.id) ||
+ current.lineage.relationshipToParent !== "subagent" ||
+ current.lineage.rootThreadId !== owner.lineage.rootThreadId
+ )
+ return undefined;
+ seen.add(current.id);
+ const parent = byId.get(current.lineage.parentThreadId!);
+ if (parent === undefined) return undefined;
+ current = parent;
+ }
+ }
+ return owner;
+}
+
/**
* Whether the host's pull request proves this worktree's head was merged. A
* squash or rebase merge leaves the head outside the default branch, so the
@@ -441,13 +466,15 @@ const make = Effect.gen(function* () {
(thread) => path.resolve(thread.worktreePath!),
);
const candidates = [
- ...[...groups.values()].map((group) => group[0]!),
+ ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!),
...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))),
];
for (const thread of candidates) {
const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
if (!worktreeCleanupEnabled(settings)) continue;
const worktreePath = path.resolve(thread.worktreePath!);
+ const group = groups.get(worktreePath) ?? [];
+ const activityAt = Math.max(...group.map(storageCleanupActivityAt));
const deleted = "workspaceRoot" in thread;
const project = deleted
? { workspaceRoot: thread.workspaceRoot }
@@ -466,11 +493,16 @@ const make = Effect.gen(function* () {
yield* Effect.gen(function* () {
if (!(yield* fs.exists(worktreePath))) return;
if (deleted && !settings.worktreeOnDelete) return keep("no rules apply");
- const shared = groups.get(worktreePath)?.length ?? 0;
- if (shared > 1) return keep(`shared by ${shared} threads`);
+ if (group.length > 1 && worktreeOwner(group) === undefined)
+ return keep(`shared by ${group.length} threads`);
if (project === undefined) return keep("project is unavailable");
- if (!deleted && !storageCleanupThreadIdle(thread, now))
+ if (
+ thread.branch === null ||
+ (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now)))
+ )
return keep("thread is running or has pending work");
+ if (group.some((member) => member.branch !== thread.branch))
+ return keep("a subagent thread's branch differs from this worktree's branch");
if (hasTerminal(worktreePath)) return keep("open terminal");
// Roots are canonical, so compare canonical paths. A symlinked parent
// (a linked drive) is fine; a symlinked worktree directory is not.
@@ -494,19 +526,23 @@ const make = Effect.gen(function* () {
// settlement backdates settledAt to the thread's last activity.
if (
!deleted &&
- thread.settledAt !== null &&
- now - DateTime.toEpochMillis(thread.updatedAt) < SETTLE_SCRIPT_GRACE_MS
+ group.some(
+ (member) =>
+ member.settledAt !== null &&
+ now - Math.max(DateTime.toEpochMillis(member.updatedAt), activityAt) <
+ SETTLE_SCRIPT_GRACE_MS,
+ )
)
return keep("settled moments ago");
const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
const old =
!deleted &&
settings.worktreeAfterDays !== null &&
- storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
+ activityAt < now - settings.worktreeAfterDays * DAY_MS;
const settledFor =
deleted || thread.settledAt === null
? null
- : now - DateTime.toEpochMillis(thread.settledAt);
+ : now - Math.max(DateTime.toEpochMillis(thread.settledAt), activityAt);
const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS);
const settled =
settledFor !== null &&
@@ -516,7 +552,7 @@ const make = Effect.gen(function* () {
let removalReason = deleted
? "thread was deleted"
: old
- ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`
+ ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days`
: `settled for ${settledDays} days`;
if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
const repositoryCwd = path.resolve(project.workspaceRoot);
@@ -564,7 +600,7 @@ const make = Effect.gen(function* () {
if (!eligible)
return keep(
!deleted && settings.worktreeAfterDays !== null
- ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days`
+ ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days`
: settings.worktreeSettledAfterDays !== null
? settledFor === null
? "not settled"
@@ -575,7 +611,7 @@ const make = Effect.gen(function* () {
);
// Threads, queued deletion work and provider sessions as they are now, so a
// queued turn, resumed session or new thread sharing this path cancels
- // the removal. Read only this path and this thread: a full snapshot per
+ // the removal. Read only this path's threads: a full snapshot per
// worktree takes seconds on large databases.
const blockedSinceCheck = Effect.fnUntraced(function* () {
const latestProjects = yield* projectStore.listShells();
@@ -600,15 +636,28 @@ const make = Effect.gen(function* () {
`;
if (pendingCleanup.length > 0) return "thread deletion is still pending";
} else {
- const latestShell =
- latest.length === 1 && latest[0]!.threadId === thread.id
- ? yield* projections.getThreadShell(thread.id)
- : null;
+ const latestShells = yield* Effect.forEach(latest, (entry) =>
+ projections.getThreadShell(entry.threadId),
+ );
+ const latestGroup = latestShells.filter((shell) => shell !== null);
+ const latestOwner = worktreeOwner(latestGroup);
if (
- latestShell === null ||
- !storageCleanupThreadIdle(latestShell, now) ||
- storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) ||
- !Equal.equals(latestShell.settledAt, thread.settledAt)
+ latestGroup.length !== group.length ||
+ latestOwner?.id !== thread.id ||
+ latestOwner?.branch !== thread.branch ||
+ latestGroup.some((shell) => {
+ const previous = group.find((member) => member.id === shell.id);
+ return (
+ previous === undefined ||
+ shell.branch !== thread.branch ||
+ !Equal.equals(shell.settledAt, previous.settledAt) ||
+ (shell.settledAt !== null &&
+ !Equal.equals(shell.updatedAt, previous.updatedAt)) ||
+ !storageCleanupThreadIdle(shell, now) ||
+ path.resolve(shell.worktreePath!) !== worktreePath ||
+ storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous)
+ );
+ })
)
return "thread activity or shared worktree changed since check";
}