diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..c48018532c415 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -77,6 +77,8 @@ const createRun = Effect.fn(function* ( threadId: ThreadId, status: OrchestrationV2Run["status"] = "completed", ordinal = 1, + at = old, + queueHeld = false, ) { const store = yield* ProjectionStore.ProjectionStoreV2; const runId = RunId.make(`run:${threadId}:${ordinal}`); @@ -84,7 +86,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 +98,10 @@ 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, + queueHeld, + requestedAt: at, + startedAt: status === "queued" ? null : at, + completedAt: ["completed", "rolled_back", "failed"].includes(status) ? at : null, checkpointId: null, contextHandoffId: null, }, @@ -210,6 +213,61 @@ 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"); + 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); + 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); + 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)), +); + it.effect( "sql: discovers settlement work with the same activity and background semantics as the shell", () => @@ -231,8 +289,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"), @@ -324,7 +381,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, background, persistent, rolledBack]), ); assert.deepEqual( new Set(eligible.map((thread) => thread.id)), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 289bdce2276c0..40d2603186f9c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8355,13 +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 ${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 diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index a17dde47c20b3..0c68aa8350bad 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,41 @@ describe("isAutoSettlementCandidate", () => { }); describe("resolveAutoSettlementAt", () => { + 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 = { thread: shell({ diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 5c49dcddbf404..f6ff753fd2950 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" || 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 905f3a5bfbe9c..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. -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