From 18df7e1e36fddcfa98566efd560e066ad2454e20 Mon Sep 17 00:00:00 2001 From: doublesharp Date: Thu, 29 Oct 2026 11:09:14 -0700 Subject: [PATCH 1/4] fix(server): keep failed threads out of automatic settlement --- .../ProjectionSettlement.test.ts | 36 ++++++++++++++--- .../ThreadSettlementService.test.ts | 40 ++++++++++++++++--- .../ThreadSettlementService.ts | 1 + docs/user/thread-sidebar.md | 2 +- 4 files changed, 67 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..e4d9772d8ca35 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -77,6 +77,7 @@ const createRun = Effect.fn(function* ( threadId: ThreadId, status: OrchestrationV2Run["status"] = "completed", ordinal = 1, + at = old, ) { const store = yield* ProjectionStore.ProjectionStoreV2; const runId = RunId.make(`run:${threadId}:${ordinal}`); @@ -84,7 +85,7 @@ const createRun = Effect.fn(function* ( id: EventId.make(`event:${runId}`), type: "run.created", threadId, - occurredAt: old, + occurredAt: at, payload: { id: runId, threadId, @@ -96,9 +97,9 @@ const createRun = Effect.fn(function* ( rootNodeId: null, activeAttemptId: null, status, - requestedAt: old, - startedAt: status === "queued" ? null : old, - completedAt: ["completed", "rolled_back", "failed"].includes(status) ? old : null, + requestedAt: at, + startedAt: status === "queued" ? null : at, + completedAt: ["completed", "rolled_back", "failed"].includes(status) ? at : null, checkpointId: null, contextHandoffId: null, }, @@ -210,6 +211,31 @@ it.effect.each([["sql", layerSql]] as const)( }).pipe(Effect.provide(testLayer)), ); +it.effect("sql: a failed latest run blocks merge settlement until a successful follow-up", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* createThread("failed-after-merge"); + yield* createRun(threadId, "failed", 1, DateTime.subtract(now, { minutes: 1 })); + const resolve = Effect.gen(function* () { + const candidates = yield* store.getSettlementCandidates(threadId); + assert.equal(candidates.length, 1); + return resolveAutoSettlementAt({ + thread: candidates[0]!, + pullRequest: { + state: "merged", + mergedAt: DateTime.formatIso(DateTime.subtract(now, { minutes: 5 })), + }, + nowMs: DateTime.toEpochMillis(now), + autoSettleAfterDays: null, + autoSettleOnMerge: true, + }); + }); + assert.isNull(yield* resolve); + yield* createRun(threadId, "completed", 2, now); + assert.deepEqual(yield* resolve, now); + }).pipe(Effect.provide(layerSql)), +); + it.effect( "sql: discovers settlement work with the same activity and background semantics as the shell", () => @@ -324,7 +350,7 @@ it.effect( ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), - new Set([idle, completed, queued, woke, background, persistent, rolledBack]), + new Set([idle, completed, queued, background, persistent, rolledBack]), ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index a17dde47c20b3..1b114c61700ce 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -181,12 +181,13 @@ describe("isAutoSettlementCandidate", () => { snoozedAt: at(-60 * 60 * 1_000), }); expect(ThreadSettlementService.isAutoSettlementCandidate(snoozed, NOW_MS)).toBe(false); - expect( - ThreadSettlementService.isAutoSettlementCandidate( - shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-30 * 60 * 1_000) }), - NOW_MS, - ), - ).toBe(true); + const failed = shell({ + ...snoozed, + status: "failed", + latestRunCompletedAt: at(-30 * 60 * 1_000), + }); + expect(ThreadSettlementService.isSnoozed(failed, NOW_MS)).toBe(false); + expect(ThreadSettlementService.isAutoSettlementCandidate(failed, NOW_MS)).toBe(false); expect( ThreadSettlementService.isAutoSettlementCandidate( shell({ ...snoozed, status: "failed", latestRunCompletedAt: at(-2 * 60 * 60 * 1_000) }), @@ -215,6 +216,33 @@ describe("isAutoSettlementCandidate", () => { }); describe("resolveAutoSettlementAt", () => { + it.each(["merged", "closed", "inactivity"] as const)( + "keeps a failed run visible instead of settling on %s", + (reason) => { + const input = { + thread: shell({ status: "failed", latestRunCompletedAt: at(-4 * DAY_MS) }), + pullRequest: + reason === "inactivity" + ? null + : { + state: reason, + mergedAt: DateTime.formatIso(at(-1)), + closedAt: DateTime.formatIso(at(-1)), + }, + nowMs: NOW_MS, + autoSettleAfterDays: reason === "inactivity" ? 3 : null, + autoSettleOnMerge: true, + }; + expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull(); + expect( + ThreadSettlementService.resolveAutoSettlementAt({ + ...input, + thread: { ...input.thread, status: "completed" }, + }), + ).toEqual(at(-4 * DAY_MS)); + }, + ); + it("keeps threads with a PR from inactivity settlement only when asked", () => { const input = { thread: shell({ diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 5c49dcddbf404..702896a5e9201 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -164,6 +164,7 @@ export function isAutoSettlementCandidate( ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; + if (thread.status === "failed") return false; if (thread.pendingRuntimeRequest !== null) return false; // A guest is waiting on the owner; settling would hide the Request. if ((thread.pendingGuestMessageCount ?? 0) > 0) return false; diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 905f3a5bfbe9c..bb772cf04fb29 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -189,7 +189,7 @@ Press `Escape` while dragging to cancel. By default, environments settle inactive threads after seven days and settle threads whose pull request merged. A closed pull request can also settle an idle thread. An empty thread's inactivity counts from when it was created. -Work in progress, pending questions or approvals, and background work the agent +Failed runs, work in progress, pending questions or approvals, and background work the agent is waiting on prevent automatic settlement. An open pull request does not prevent inactivity settlement unless you turn on **Keep threads with a PR** in **Settings → Threads**, but an old closed or merged pull request does not settle work you From 9c347457e753649d9320fb643f8111ddf436bc2b Mon Sep 17 00:00:00 2001 From: doublesharp Date: Thu, 29 Oct 2026 12:48:57 -0700 Subject: [PATCH 2/4] fix(server): ignore held queued runs during settlement --- .../ProjectionSettlement.test.ts | 16 ++++++++++++++-- .../src/orchestration-v2/ProjectionStore.ts | 4 ++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index e4d9772d8ca35..b784264b605d0 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -78,6 +78,7 @@ const createRun = Effect.fn(function* ( status: OrchestrationV2Run["status"] = "completed", ordinal = 1, at = old, + queueHeld = false, ) { const store = yield* ProjectionStore.ProjectionStoreV2; const runId = RunId.make(`run:${threadId}:${ordinal}`); @@ -97,6 +98,7 @@ const createRun = Effect.fn(function* ( rootNodeId: null, activeAttemptId: null, status, + queueHeld, requestedAt: at, startedAt: status === "queued" ? null : at, completedAt: ["completed", "rolled_back", "failed"].includes(status) ? at : null, @@ -215,7 +217,12 @@ it.effect("sql: a failed latest run blocks merge settlement until a successful f Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; const threadId = yield* createThread("failed-after-merge"); - yield* createRun(threadId, "failed", 1, DateTime.subtract(now, { minutes: 1 })); + const failedRunId = yield* createRun( + threadId, + "failed", + 1, + DateTime.subtract(now, { minutes: 1 }), + ); const resolve = Effect.gen(function* () { const candidates = yield* store.getSettlementCandidates(threadId); assert.equal(candidates.length, 1); @@ -231,7 +238,12 @@ it.effect("sql: a failed latest run blocks merge settlement until a successful f }); }); assert.isNull(yield* resolve); - yield* createRun(threadId, "completed", 2, now); + yield* createRun(threadId, "queued", 2, now, true); + const [heldCandidate] = yield* store.getSettlementCandidates(threadId); + assert.equal(heldCandidate?.latestRunId, failedRunId); + assert.equal(heldCandidate?.status, "failed"); + assert.isNull(yield* resolve); + yield* createRun(threadId, "completed", 3, now); assert.deepEqual(yield* resolve, now); }).pipe(Effect.provide(layerSql)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 289bdce2276c0..616de887537c1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8358,6 +8358,10 @@ export const layer: Layer.Layer = LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = ( SELECT latest.run_id FROM orchestration_v2_projection_runs latest WHERE latest.thread_id = t.thread_id + AND NOT ( + latest.status = 'queued' + AND json_extract(latest.payload_json, '$.queueHeld') IS 1 + ) AND NOT ${isSilentShellRun("latest")} ORDER BY latest.ordinal DESC, latest.run_id DESC LIMIT 1 From fdfde03f2fe2035665155d9f0805c10d45512c18 Mon Sep 17 00:00:00 2001 From: doublesharp Date: Fri, 30 Oct 2026 20:00:36 -0700 Subject: [PATCH 3/4] fix(server): keep queued threads out of automatic settlement --- .../ProjectionSettlement.test.ts | 5 +- .../ThreadSettlementService.test.ts | 60 +++++++++++-------- .../ThreadSettlementService.ts | 2 +- docs/user/thread-sidebar.md | 2 +- 4 files changed, 38 insertions(+), 31 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index b784264b605d0..4c41e50fba01d 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -269,8 +269,7 @@ it.effect( for (const status of ["preparing", "starting", "running", "waiting"] as const) { yield* createRun(yield* createThread(status), status); } - const queued = yield* createThread("queued"); - yield* createRun(queued, "queued"); + yield* createRun(yield* createThread("queued"), "queued"); const blocked = yield* createThread("blocked"); yield* store.apply({ id: EventId.make("event:settlement:request"), @@ -362,7 +361,7 @@ it.effect( ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), - new Set([idle, completed, queued, background, persistent, rolledBack]), + new Set([idle, completed, background, persistent, rolledBack]), ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 1b114c61700ce..0c68aa8350bad 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -216,32 +216,40 @@ describe("isAutoSettlementCandidate", () => { }); describe("resolveAutoSettlementAt", () => { - it.each(["merged", "closed", "inactivity"] as const)( - "keeps a failed run visible instead of settling on %s", - (reason) => { - const input = { - thread: shell({ status: "failed", latestRunCompletedAt: at(-4 * DAY_MS) }), - pullRequest: - reason === "inactivity" - ? null - : { - state: reason, - mergedAt: DateTime.formatIso(at(-1)), - closedAt: DateTime.formatIso(at(-1)), - }, - nowMs: NOW_MS, - autoSettleAfterDays: reason === "inactivity" ? 3 : null, - autoSettleOnMerge: true, - }; - expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull(); - expect( - ThreadSettlementService.resolveAutoSettlementAt({ - ...input, - thread: { ...input.thread, status: "completed" }, - }), - ).toEqual(at(-4 * DAY_MS)); - }, - ); + it.each( + (["failed", "queued"] as const).flatMap((status) => + (["merged", "closed", "inactivity"] as const).map((reason) => ({ status, reason })), + ), + )("keeps a $status run visible instead of settling on $reason", ({ status, reason }) => { + const input = { + thread: shell({ + status, + latestRunId: RunId.make("run-1"), + latestRunRequestedAt: at(-4 * DAY_MS), + latestRunCompletedAt: status === "failed" ? at(-4 * DAY_MS) : null, + latestUserMessageAt: at(-4 * DAY_MS), + latestUserAuthoredMessageAt: at(-4 * DAY_MS), + }), + pullRequest: + reason === "inactivity" + ? null + : { + state: reason, + mergedAt: DateTime.formatIso(at(-1)), + closedAt: DateTime.formatIso(at(-1)), + }, + nowMs: NOW_MS, + autoSettleAfterDays: reason === "inactivity" ? 3 : null, + autoSettleOnMerge: true, + }; + expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull(); + expect( + ThreadSettlementService.resolveAutoSettlementAt({ + ...input, + thread: { ...input.thread, status: "completed", latestRunCompletedAt: at(-4 * DAY_MS) }, + }), + ).toEqual(at(-4 * DAY_MS)); + }); it("keeps threads with a PR from inactivity settlement only when asked", () => { const input = { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 702896a5e9201..f6ff753fd2950 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -164,7 +164,7 @@ export function isAutoSettlementCandidate( ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; - if (thread.status === "failed") return false; + if (thread.status === "failed" || thread.status === "queued") return false; if (thread.pendingRuntimeRequest !== null) return false; // A guest is waiting on the owner; settling would hide the Request. if ((thread.pendingGuestMessageCount ?? 0) > 0) return false; diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index bb772cf04fb29..f5e9ce72c5099 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -189,7 +189,7 @@ Press `Escape` while dragging to cancel. By default, environments settle inactive threads after seven days and settle threads whose pull request merged. A closed pull request can also settle an idle thread. An empty thread's inactivity counts from when it was created. -Failed runs, work in progress, pending questions or approvals, and background work the agent +Failed or queued runs, work in progress, pending questions or approvals, and background work the agent is waiting on prevent automatic settlement. An open pull request does not prevent inactivity settlement unless you turn on **Keep threads with a PR** in **Settings → Threads**, but an old closed or merged pull request does not settle work you From 9f5cb6eb710213b70d28b753dee266b4b56e7a26 Mon Sep 17 00:00:00 2001 From: doublesharp Date: Mon, 16 Nov 2026 21:24:57 -0800 Subject: [PATCH 4/4] fix(server): reuse shell run selection for settlement --- .../ProjectionSettlement.test.ts | 22 ++++++++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 13 ++--------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 4c41e50fba01d..c48018532c415 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -238,11 +238,31 @@ it.effect("sql: a failed latest run blocks merge settlement until a successful f }); }); assert.isNull(yield* resolve); - yield* createRun(threadId, "queued", 2, now, true); + const queuedRunId = yield* createRun(threadId, "queued", 2, now, true); const [heldCandidate] = yield* store.getSettlementCandidates(threadId); assert.equal(heldCandidate?.latestRunId, failedRunId); assert.equal(heldCandidate?.status, "failed"); assert.isNull(yield* resolve); + const queuedRun = yield* store.getRun(threadId, queuedRunId); + assert.isDefined(queuedRun); + const cancelledAt = DateTime.subtract(now, { minutes: 1 }); + yield* store.apply({ + id: EventId.make("event:failed-after-merge:queued-cancelled"), + type: "run.updated", + threadId, + occurredAt: cancelledAt, + payload: { + ...queuedRun!, + status: "cancelled", + queueHeld: false, + requestedAt: DateTime.subtract(cancelledAt, { minutes: 1 }), + completedAt: cancelledAt, + }, + }); + const [cancelledCandidate] = yield* store.getSettlementCandidates(threadId); + assert.equal(cancelledCandidate?.latestRunId, failedRunId); + assert.equal(cancelledCandidate?.status, "failed"); + assert.isNull(yield* resolve); yield* createRun(threadId, "completed", 3, now); assert.deepEqual(yield* resolve, now); }).pipe(Effect.provide(layerSql)), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 616de887537c1..40d2603186f9c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8355,17 +8355,8 @@ export const layer: Layer.Layer = LIMIT 1 ) AS latest_user_authored_message_at FROM orchestration_v2_projection_threads t - LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = ( - SELECT latest.run_id FROM orchestration_v2_projection_runs latest - WHERE latest.thread_id = t.thread_id - AND NOT ( - latest.status = 'queued' - AND json_extract(latest.payload_json, '$.queueHeld') IS 1 - ) - AND NOT ${isSilentShellRun("latest")} - ORDER BY latest.ordinal DESC, latest.run_id DESC - LIMIT 1 - ) + LEFT JOIN orchestration_v2_projection_runs r + ON r.run_id = ${presentedShellRunId(sql.literal("t.thread_id"))} WHERE t.deleted_at IS NULL${threadId === undefined ? sql`` : sql` AND t.thread_id = ${threadId}`} AND json_extract(t.payload_json, '$.archivedAt') IS NULL AND json_extract(t.payload_json, '$.settledOverride') IS NULL