From 04c89c3131d6f0c2eb0183ed5f099c8ec670ddf9 Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 2 Nov 2026 20:29:37 -0500 Subject: [PATCH 1/3] server/orchestration-v2: wait for the report of awaited work before auto-settle Providers drop finished background work from the provider thread's roster shortly before the turn that reports its result is requested (about 100ms for Claude). Auto-settle reacted to the empty roster inside that gap, detached the session, and the agent never received the result. Remember when holding work leaves a provider thread's roster and keep the thread out of auto-settlement until a turn is requested after that moment, for at most the queued-turn grace. --- .../ThreadSettlementService.test.ts | 153 ++++++++++++++++++ .../ThreadSettlementService.ts | 43 ++++- 2 files changed, 191 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index f118cd13a62dc..f52366f4eed5c 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -5,7 +5,9 @@ import { DEFAULT_SERVER_SETTINGS, ProjectId, EventId, + ProviderDriverKind, ProviderInstanceId, + ProviderThreadId, RunId, ThreadId, TurnItemId, @@ -13,6 +15,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2Command, type OrchestrationV2DomainEvent, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type PullRequestSummary, @@ -735,6 +738,44 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: }; }); +function rosterUpdated( + threadId: ThreadId, + pendingBackgroundTasks: ReadonlyArray, + occurredAt: DateTime.Utc, +): OrchestrationV2DomainEvent { + return { + type: "provider-thread.updated", + id: EventId.make(`event:roster:${threadId}:${pendingBackgroundTasks.length}`), + threadId, + occurredAt, + payload: { + id: ProviderThreadId.make(`provider-thread:${threadId}`), + appThreadId: threadId, + ownerNodeId: null, + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + providerSessionId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: occurredAt, + updatedAt: occurredAt, + pendingBackgroundTasks, + }, + }; +} + +const awaitedCommand: OrchestrationV2PendingBackgroundTask = { + taskId: "tests", + kind: "command", + description: "Run the tests", + awaited: true, +}; + const startHarness = Effect.fn("startThreadSettlementHarness")(function* ( reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"], activation: Deferred.Deferred, @@ -1113,6 +1154,118 @@ describe("ThreadSettlementServiceV2 worker", () => { ), ); + it.effect("waits for the turn that reports awaited work before settling on merge", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const settled = yield* Deferred.make(); + const thread = makeThread("awaited-work", { + pullRequests: [ + { + ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), + snapshot: { + state: "merged", + title: "Pull request", + headBranch: "feature", + baseBranch: "main", + isDraft: false, + updatedAt: NOW, + syncedAt: NOW, + mergedAt: NOW, + }, + }, + ], + pendingBackgroundTasks: [awaitedCommand], + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([thread]), + onDispatch: () => Deferred.succeed(settled, undefined), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishEvent( + rosterUpdated(thread.id, [awaitedCommand], DateTime.makeUnsafe(NOW)), + ); + yield* Ref.set( + fixture.snapshots, + makeSnapshot([{ ...thread, pendingBackgroundTasks: [] }]), + ); + yield* fixture.publishEvent(rosterUpdated(thread.id, [], DateTime.makeUnsafe(NOW))); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.deepStrictEqual(yield* Ref.get(fixture.commands), []); + + const reportAt = DateTime.makeUnsafe(Date.parse(NOW) + 1_000); + yield* Ref.set( + fixture.snapshots, + makeSnapshot([ + { + ...thread, + pendingBackgroundTasks: [], + latestRunId: RunId.make("run:report"), + latestUserMessageAt: reportAt, + latestRunRequestedAt: reportAt, + latestRunStartedAt: reportAt, + latestRunCompletedAt: DateTime.makeUnsafe(Date.parse(NOW) + 20_000), + }, + ]), + ); + // The next full sweep is within the hold's grace, so only the report turn releases it. + yield* TestClock.adjust("1 minute"); + yield* Deferred.await(settled); + assert.deepStrictEqual( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId), + [thread.id], + ); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + + it.effect("settles an idle thread whose awaited work ended once no report turn came", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const settled = yield* Deferred.make(); + const thread = makeThread("awaited-work-idle", { + pendingBackgroundTasks: [awaitedCommand], + }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([thread]), + settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 }, + onDispatch: () => Deferred.succeed(settled, undefined), + }); + + yield* Effect.gen(function* () { + const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); + yield* fixture.publishEvent( + rosterUpdated(thread.id, [awaitedCommand], DateTime.makeUnsafe(NOW)), + ); + yield* Ref.set( + fixture.snapshots, + makeSnapshot([{ ...thread, pendingBackgroundTasks: [] }]), + ); + // Ended 90s ago, so the next full sweep, a minute later, falls past the hold's grace. + const endedAt = DateTime.makeUnsafe(Date.parse(NOW) - 90_000); + yield* fixture.publishEvent(rosterUpdated(thread.id, [], endedAt)); + yield* Queue.take(fixture.snapshotReads); + yield* reactor.drain; + assert.deepStrictEqual(yield* Ref.get(fixture.commands), []); + + yield* TestClock.adjust("1 minute"); + yield* Deferred.await(settled); + assert.deepStrictEqual( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId), + [thread.id], + ); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 99fcb077aa718..8bd95d554369c 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -7,6 +7,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, isOrchestrationV2WorkActive, + type ProviderThreadId, type ThreadId, type OrchestrationV2DomainEvent, type OrchestrationV2ThreadShell, @@ -119,6 +120,21 @@ export function threadHasQueuedTurnStart( ].every((value) => value === null || value < messageAtMs); } +function awaitsHeldWorkReport( + thread: Pick< + ProjectionStore.ProjectionSettlementCandidate, + "latestUserMessageAt" | "latestRunRequestedAt" + >, + heldWorkEndedAtMs: number | undefined, +): boolean { + if (heldWorkEndedAtMs === undefined) return false; + const turnRequestedAtMs = latestMillis([ + toMillis(thread.latestUserMessageAt), + toMillis(thread.latestRunRequestedAt), + ]); + return turnRequestedAtMs === null || turnRequestedAtMs < heldWorkEndedAtMs; +} + function pullRequestSettles( thread: Pick< ProjectionStore.ProjectionSettlementCandidate, @@ -304,11 +320,20 @@ export const make = Effect.gen(function* () { const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; // Repeated thread.settled retains settledAt; run the action only once per settlement. const settleActionRunAt = new Map(); + // Providers drop finished work from the roster before the turn that reports it is requested + // (Claude: about 100ms). Settling in that gap detaches the session, so the report never arrives. + const providerThreadsHoldingWork = new Set(); + const heldWorkEndedAtMs = new Map(); const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* ( mergedPullRequest: PullRequestService.PullRequestMergeEvent | null, threadId?: ThreadId, ) { + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); + // Bounds the hold when no report turn comes, as when the run was stopped. + for (const [id, endedAtMs] of heldWorkEndedAtMs) { + if (Math.abs(nowMs - endedAtMs) > QUEUED_TURN_START_GRACE_MS) heldWorkEndedAtMs.delete(id); + } const settings = yield* settingsService.getSettings; if (!autoSettlementConfigured(settings)) { return; @@ -316,10 +341,13 @@ export const make = Effect.gen(function* () { const threads = yield* projections.getSettlementCandidates(threadId); if (threads.length === 0) return; const projectShells = yield* projectStore.listShells(); - const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const projects = new Map(projectShells.map((project) => [project.id, project])); // Merge events resweep all candidates because unlinked threads settle through branch lookup. - const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs)); + const candidates = threads.filter( + (thread) => + isAutoSettlementCandidate(thread, nowMs) && + !awaitsHeldWorkReport(thread, heldWorkEndedAtMs.get(thread.id)), + ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. const settleThread = Effect.fnUntraced( @@ -636,9 +664,14 @@ export const make = Effect.gen(function* () { ? Effect.void : enqueueThread(event.threadId); case "provider-thread.updated": - return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []) - ? Effect.void - : enqueueThread(event.threadId); + if (backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])) { + providerThreadsHoldingWork.add(event.payload.id); + return Effect.void; + } + if (providerThreadsHoldingWork.delete(event.payload.id)) { + heldWorkEndedAtMs.set(event.threadId, DateTime.toEpochMillis(event.occurredAt)); + } + return enqueueThread(event.threadId); case "turn-item.updated": { const item = event.payload; if ( From 1baceba1f2f31ce3303e99fc1350c242e9adc396 Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 2 Nov 2026 23:25:14 -0500 Subject: [PATCH 2/3] server/orchestration-v2: store when held work ended in the projection The hold was recorded in memory from the domain event stream, but full and merge sweeps read the projection, which can already show the empty roster while the event consumer lags. The provider thread projection now records when its roster stops holding work, in the same transaction as the roster update, and every sweep reads that time from the settlement candidates. The in-memory tracking is gone. --- .../ProjectionSettlement.test.ts | 61 ++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 34 +++++- .../ThreadSettlementService.test.ts | 111 ++++++------------ .../ThreadSettlementService.ts | 48 ++++---- apps/server/src/persistence/Migrations.ts | 2 + .../079_ProviderThreadHeldWorkEndedAt.ts | 9 ++ .../reconcileV2PreviewMigration.test.ts | 2 + 7 files changed, 159 insertions(+), 108 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/079_ProviderThreadHeldWorkEndedAt.ts diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 1352e17585bfd..e72906c8dcf30 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -276,6 +276,7 @@ it.effect( thread: { ...expected, latestUserAuthoredMessageAt: candidate.latestUserAuthoredMessageAt, + heldWorkEndedAt: candidate.heldWorkEndedAt, }, }), ); @@ -291,6 +292,66 @@ it.effect( }).pipe(Effect.provide(layerSql)), ); +it.effect("sql: records when a provider thread's roster stops holding work", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* createThread("held-work"); + yield* createRun(threadId); + const roster = ( + name: string, + at: DateTime.Utc, + pendingBackgroundTasks: ReadonlyArray<{ + readonly taskId: string; + readonly kind: "command"; + readonly awaited?: true; + }>, + ) => + store.apply({ + id: EventId.make(`event:settlement:held-work:${name}`), + type: "provider-thread.updated", + threadId, + occurredAt: at, + payload: { + id: ProviderThreadId.make("provider-thread:settlement:held-work"), + appThreadId: threadId, + ownerNodeId: null, + driver: ProviderDriverKind.make("claudeAgent"), + providerInstanceId, + providerSessionId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: old, + updatedAt: at, + pendingBackgroundTasks, + }, + }); + const heldWorkEndedAt = Effect.map(store.getSettlementCandidates(threadId), ([candidate]) => + candidate?.heldWorkEndedAt == null ? null : DateTime.formatIso(candidate.heldWorkEndedAt), + ); + const ended = DateTime.subtract(now, { minutes: 1 }); + + yield* roster("created", DateTime.subtract(now, { minutes: 5 }), []); + assert.isNull(yield* heldWorkEndedAt); + // A command nobody waits on, such as a dev server, never held the thread. + yield* roster("dev-server", DateTime.subtract(now, { minutes: 4 }), [ + { taskId: "dev", kind: "command" }, + ]); + yield* roster("dev-server-ended", DateTime.subtract(now, { minutes: 3 }), []); + assert.isNull(yield* heldWorkEndedAt); + yield* roster("awaited", DateTime.subtract(now, { minutes: 2 }), [ + { taskId: "tests", kind: "command", awaited: true }, + ]); + yield* roster("awaited-ended", ended, []); + yield* roster("idle-again", now, []); + assert.equal(yield* heldWorkEndedAt, DateTime.formatIso(ended)); + }).pipe(Effect.provide(layerSql)), +); + it.effect("sql: the user-authored message time ignores agent notifications", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 3cffce15b70d6..8fde27b14cee3 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -81,6 +81,7 @@ import { isOrchestrationV2SupersededInterrupt, } from "@t3tools/shared/orchestrationV2Timeline"; import { + backgroundWorkHoldsCompletion, deriveBlockedOnThreadWait, derivePendingBackgroundWork, } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; @@ -222,6 +223,8 @@ export type ProjectionSettlementCandidate = Pick< > & Pick & { readonly latestUserAuthoredMessageAt: DateTime.Utc | null; + /** When work last stopped holding one of the thread's provider threads. */ + readonly heldWorkEndedAt: DateTime.Utc | null; }; const ProjectionCheckpointContext = Schema.Struct({ @@ -1016,7 +1019,7 @@ type SettlementThreadRow = Pick< | "latest_run_completed_at" | "latest_user_message_at" | "latest_user_authored_message_at" ->; +> & { readonly held_work_ended_at: string | null }; type ShellRunItemCountRow = { readonly thread_id: string; @@ -2281,6 +2284,9 @@ export const layer: Layer.Layer = case "provider-thread.updated": { const payloadJson = yield* encodeProviderThreadPayload(event.payload); const payload = parseEncodedPayload(payloadJson); + const occurredAt = yield* encodePayloadTimestamp(event.occurredAt); + // Settlement waits for the turn that reports work which just stopped holding the + // thread; recording that here commits it with the roster that dropped the work. yield* sql` INSERT INTO orchestration_v2_projection_provider_threads ( provider_thread_id, @@ -2294,7 +2300,8 @@ export const layer: Layer.Layer = first_run_ordinal, last_run_ordinal, updated_at, - payload_json + payload_json, + holds_completion ) VALUES ( ${event.payload.id}, @@ -2308,7 +2315,8 @@ export const layer: Layer.Layer = ${event.payload.firstRunOrdinal}, ${event.payload.lastRunOrdinal}, ${stringField(payload, "updatedAt")}, - ${payloadJson} + ${payloadJson}, + ${booleanInt(backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []))} ) ON CONFLICT(provider_thread_id) DO UPDATE SET @@ -2322,7 +2330,14 @@ export const layer: Layer.Layer = first_run_ordinal = excluded.first_run_ordinal, last_run_ordinal = excluded.last_run_ordinal, updated_at = excluded.updated_at, - payload_json = excluded.payload_json + payload_json = excluded.payload_json, + held_work_ended_at = CASE + WHEN orchestration_v2_projection_provider_threads.holds_completion = 1 + AND excluded.holds_completion = 0 + THEN ${occurredAt} + ELSE orchestration_v2_projection_provider_threads.held_work_ended_at + END, + holds_completion = excluded.holds_completion `; if ( event.payload.appThreadId !== null && @@ -6400,7 +6415,12 @@ export const layer: Layer.Layer = AND NOT ${isIdleCompactionMessage("message")} ORDER BY message.updated_at DESC, message.message_id DESC LIMIT 1 - ) AS latest_user_authored_message_at + ) AS latest_user_authored_message_at, + ( + SELECT MAX(provider_thread.held_work_ended_at) + FROM orchestration_v2_projection_provider_threads provider_thread + WHERE provider_thread.thread_id = t.thread_id + ) AS held_work_ended_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 @@ -6473,6 +6493,10 @@ export const layer: Layer.Layer = row.latest_user_authored_message_at === null ? null : DateTime.makeUnsafe(row.latest_user_authored_message_at), + heldWorkEndedAt: + row.held_work_ended_at === null + ? null + : DateTime.makeUnsafe(row.held_work_ended_at), activityRunStatus: null, activityRunStartedAt: null, pendingRuntimeRequest: null, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b4a882b057e6f..247be5ffdb0e3 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -5,9 +5,7 @@ import { DEFAULT_SERVER_SETTINGS, ProjectId, EventId, - ProviderDriverKind, ProviderInstanceId, - ProviderThreadId, RunId, ThreadId, TurnItemId, @@ -15,7 +13,6 @@ import { type OrchestrationV2AppThread, type OrchestrationV2Command, type OrchestrationV2DomainEvent, - type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type PullRequestSummary, @@ -55,7 +52,10 @@ function at(offsetMs: number): DateTime.Utc { } type SettlementShell = OrchestrationV2ThreadShell & - Pick; + Pick< + ProjectionStore.ProjectionSettlementCandidate, + "latestUserAuthoredMessageAt" | "heldWorkEndedAt" + >; function shell(overrides: Partial = {}): SettlementShell { return { @@ -95,6 +95,7 @@ function shell(overrides: Partial = {}): SettlementShell { latestRunCompletedAt: null, latestUserMessageAt: null, latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null, + heldWorkEndedAt: null, createdAt: at(-30 * DAY_MS), updatedAt: at(-10 * DAY_MS), archivedAt: null, @@ -752,44 +753,6 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: }; }); -function rosterUpdated( - threadId: ThreadId, - pendingBackgroundTasks: ReadonlyArray, - occurredAt: DateTime.Utc, -): OrchestrationV2DomainEvent { - return { - type: "provider-thread.updated", - id: EventId.make(`event:roster:${threadId}:${pendingBackgroundTasks.length}`), - threadId, - occurredAt, - payload: { - id: ProviderThreadId.make(`provider-thread:${threadId}`), - appThreadId: threadId, - ownerNodeId: null, - driver: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - providerSessionId: null, - nativeThreadRef: null, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: 1, - lastRunOrdinal: 1, - handoffIds: [], - forkedFrom: null, - createdAt: occurredAt, - updatedAt: occurredAt, - pendingBackgroundTasks, - }, - }; -} - -const awaitedCommand: OrchestrationV2PendingBackgroundTask = { - taskId: "tests", - kind: "command", - description: "Run the tests", - awaited: true, -}; - const startHarness = Effect.fn("startThreadSettlementHarness")(function* ( reactor: ThreadSettlementService.ThreadSettlementServiceV2["Service"], activation: Deferred.Deferred, @@ -1279,12 +1242,13 @@ describe("ThreadSettlementServiceV2 worker", () => { ), ); - it.effect("waits for the turn that reports awaited work before settling on merge", () => + it.effect("full and merge sweeps wait for the turn that reports awaited work", () => Effect.scoped( Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); - const settled = yield* Deferred.make(); - const thread = makeThread("awaited-work", { + const dispatched = yield* Queue.unbounded(); + // The roster that dropped the work committed, but its event has not reached this worker. + const held = makeThread("awaited-work", { pullRequests: [ { ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")), @@ -1300,35 +1264,41 @@ describe("ThreadSettlementServiceV2 worker", () => { }, }, ], - pendingBackgroundTasks: [awaitedCommand], + heldWorkEndedAt: DateTime.makeUnsafe(NOW), + }); + // Only the merge event settles this one, so its dispatch marks that sweep's decisions. + const mergedInApp = makeThread("merged-in-app", { + latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"), + linkedPullRequest: { + projectId: PROJECT_ID, + repository: "owner/repository", + number: 42, + url: "https://example.test/owner/repository/pull/42", + }, }); const fixture = yield* makeHarness({ - snapshot: makeSnapshot([thread]), - onDispatch: () => Deferred.succeed(settled, undefined), + snapshot: makeSnapshot([held, mergedInApp]), + onDispatch: (command) => Queue.offer(dispatched, command.threadId).pipe(Effect.asVoid), }); yield* Effect.gen(function* () { const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); - yield* fixture.publishEvent( - rosterUpdated(thread.id, [awaitedCommand], DateTime.makeUnsafe(NOW)), - ); - yield* Ref.set( - fixture.snapshots, - makeSnapshot([{ ...thread, pendingBackgroundTasks: [] }]), - ); - yield* fixture.publishEvent(rosterUpdated(thread.id, [], DateTime.makeUnsafe(NOW))); - yield* Queue.take(fixture.snapshotReads); - yield* reactor.drain; assert.deepStrictEqual(yield* Ref.get(fixture.commands), []); + yield* fixture.publishMerge; + assert.strictEqual(yield* Queue.take(dispatched), mergedInApp.id); + assert.deepStrictEqual( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId), + [mergedInApp.id], + ); + const reportAt = DateTime.makeUnsafe(Date.parse(NOW) + 1_000); yield* Ref.set( fixture.snapshots, makeSnapshot([ { - ...thread, - pendingBackgroundTasks: [], + ...held, latestRunId: RunId.make("run:report"), latestUserMessageAt: reportAt, latestRunRequestedAt: reportAt, @@ -1339,11 +1309,7 @@ describe("ThreadSettlementServiceV2 worker", () => { ); // The next full sweep is within the hold's grace, so only the report turn releases it. yield* TestClock.adjust("1 minute"); - yield* Deferred.await(settled); - assert.deepStrictEqual( - (yield* Ref.get(fixture.commands)).map((command) => command.threadId), - [thread.id], - ); + assert.strictEqual(yield* Queue.take(dispatched), held.id); }).pipe(Effect.provide(fixture.layer)); }), ), @@ -1354,8 +1320,9 @@ describe("ThreadSettlementServiceV2 worker", () => { Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); const settled = yield* Deferred.make(); + // Ended 90s ago, so the next full sweep, a minute later, falls past the hold's grace. const thread = makeThread("awaited-work-idle", { - pendingBackgroundTasks: [awaitedCommand], + heldWorkEndedAt: DateTime.makeUnsafe(Date.parse(NOW) - 90_000), }); const fixture = yield* makeHarness({ snapshot: makeSnapshot([thread]), @@ -1366,18 +1333,6 @@ describe("ThreadSettlementServiceV2 worker", () => { yield* Effect.gen(function* () { const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2; yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); - yield* fixture.publishEvent( - rosterUpdated(thread.id, [awaitedCommand], DateTime.makeUnsafe(NOW)), - ); - yield* Ref.set( - fixture.snapshots, - makeSnapshot([{ ...thread, pendingBackgroundTasks: [] }]), - ); - // Ended 90s ago, so the next full sweep, a minute later, falls past the hold's grace. - const endedAt = DateTime.makeUnsafe(Date.parse(NOW) - 90_000); - yield* fixture.publishEvent(rosterUpdated(thread.id, [], endedAt)); - yield* Queue.take(fixture.snapshotReads); - yield* reactor.drain; assert.deepStrictEqual(yield* Ref.get(fixture.commands), []); yield* TestClock.adjust("1 minute"); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index f7bb14e3e2ad4..c1c5bfa636280 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -7,7 +7,6 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, isOrchestrationV2WorkActive, - type ProviderThreadId, type ThreadId, type OrchestrationV2DomainEvent, type OrchestrationV2ThreadShell, @@ -121,14 +120,25 @@ export function threadHasQueuedTurnStart( ].every((value) => value === null || value < messageAtMs); } +/** + * Providers drop finished work from the roster before the turn that reports it is requested + * (Claude: about 100ms). Settling in that gap detaches the session, so the report never arrives. + */ function awaitsHeldWorkReport( thread: Pick< ProjectionStore.ProjectionSettlementCandidate, - "latestUserMessageAt" | "latestRunRequestedAt" + "heldWorkEndedAt" | "latestUserMessageAt" | "latestRunRequestedAt" >, - heldWorkEndedAtMs: number | undefined, + nowMs: number, ): boolean { - if (heldWorkEndedAtMs === undefined) return false; + const heldWorkEndedAtMs = toMillis(thread.heldWorkEndedAt); + // The grace bounds the hold when no report turn comes, as when the run was stopped. + if ( + heldWorkEndedAtMs === null || + Math.abs(nowMs - heldWorkEndedAtMs) > QUEUED_TURN_START_GRACE_MS + ) { + return false; + } const turnRequestedAtMs = latestMillis([ toMillis(thread.latestUserMessageAt), toMillis(thread.latestRunRequestedAt), @@ -160,7 +170,10 @@ function pullRequestSettles( } export function isAutoSettlementCandidate( - thread: Omit, + thread: Omit< + ProjectionStore.ProjectionSettlementCandidate, + "latestUserAuthoredMessageAt" | "heldWorkEndedAt" + >, nowMs: number, ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; @@ -322,20 +335,11 @@ export const make = Effect.gen(function* () { const projectScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; // Repeated thread.settled retains settledAt; run the action only once per settlement. const settleActionRunAt = new Map(); - // Providers drop finished work from the roster before the turn that reports it is requested - // (Claude: about 100ms). Settling in that gap detaches the session, so the report never arrives. - const providerThreadsHoldingWork = new Set(); - const heldWorkEndedAtMs = new Map(); const sweep = Effect.fn("ThreadSettlementServiceV2.sweep")(function* ( mergedPullRequest: PullRequestService.PullRequestMergeEvent | null, threadId?: ThreadId, ) { - const nowMs = DateTime.toEpochMillis(yield* DateTime.now); - // Bounds the hold when no report turn comes, as when the run was stopped. - for (const [id, endedAtMs] of heldWorkEndedAtMs) { - if (Math.abs(nowMs - endedAtMs) > QUEUED_TURN_START_GRACE_MS) heldWorkEndedAtMs.delete(id); - } const settings = yield* settingsService.getSettings; if (!autoSettlementConfigured(settings)) { return; @@ -343,12 +347,11 @@ export const make = Effect.gen(function* () { const threads = yield* projections.getSettlementCandidates(threadId); if (threads.length === 0) return; const projectShells = yield* projectStore.listShells(); + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const projects = new Map(projectShells.map((project) => [project.id, project])); // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter( - (thread) => - isAutoSettlementCandidate(thread, nowMs) && - !awaitsHeldWorkReport(thread, heldWorkEndedAtMs.get(thread.id)), + (thread) => isAutoSettlementCandidate(thread, nowMs) && !awaitsHeldWorkReport(thread, nowMs), ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. @@ -668,14 +671,9 @@ export const make = Effect.gen(function* () { ? Effect.void : enqueueThread(event.threadId); case "provider-thread.updated": - if (backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? [])) { - providerThreadsHoldingWork.add(event.payload.id); - return Effect.void; - } - if (providerThreadsHoldingWork.delete(event.payload.id)) { - heldWorkEndedAtMs.set(event.threadId, DateTime.toEpochMillis(event.occurredAt)); - } - return enqueueThread(event.threadId); + return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []) + ? Effect.void + : enqueueThread(event.threadId); case "turn-item.updated": { const item = event.payload; if ( diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 3ee83e5fe01bf..17ead6a6d16a4 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -81,6 +81,7 @@ import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts"; import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts"; import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts"; import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts"; +import Migration0079 from "./Migrations/079_ProviderThreadHeldWorkEndedAt.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -162,6 +163,7 @@ const migrationEntries = [ [76, "ProjectionProjectsPinArchive", Migration0076], [77, "RepairBooleanSettledOverride", Migration0077], [78, "DropOrchestrationEventCorrelationIndex", Migration0078], + [79, "ProviderThreadHeldWorkEndedAt", Migration0079], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/079_ProviderThreadHeldWorkEndedAt.ts b/apps/server/src/persistence/Migrations/079_ProviderThreadHeldWorkEndedAt.ts new file mode 100644 index 0000000000000..5a56f21839cc2 --- /dev/null +++ b/apps/server/src/persistence/Migrations/079_ProviderThreadHeldWorkEndedAt.ts @@ -0,0 +1,9 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Rows start out holding nothing: restart recovery clears every roster before new turns run. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN holds_completion INTEGER NOT NULL DEFAULT 0`; + yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN held_work_ended_at TEXT`; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index d062961b3af57..b55baf8f8075b 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -58,6 +58,7 @@ describe("V2 preview upgrade", () => { [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], [78, "DropOrchestrationEventCorrelationIndex"], + [79, "ProviderThreadHeldWorkEndedAt"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -159,6 +160,7 @@ describe("V2 preview upgrade", () => { [76, "ProjectionProjectsPinArchive"], [77, "RepairBooleanSettledOverride"], [78, "DropOrchestrationEventCorrelationIndex"], + [79, "ProviderThreadHeldWorkEndedAt"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 2c5988ea3fe2dc9d158c6f9ccea7a4b96e72268c Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 2 Nov 2026 23:49:31 -0500 Subject: [PATCH 3/3] server/orchestration-v2: keep the held-work hold while the report run is queued A report requested behind another run stays queued until that run ends, so its request time alone does not mean the report has started. A full or merge sweep in that window could still settle the thread. --- .../ThreadSettlementService.test.ts | 19 ++++++++++++++----- .../ThreadSettlementService.ts | 4 +++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 247be5ffdb0e3..f63edcbbf0cf7 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -1286,6 +1286,18 @@ describe("ThreadSettlementServiceV2 worker", () => { yield* startHarness(reactor, fixture.activation, fixture.snapshotReads); assert.deepStrictEqual(yield* Ref.get(fixture.commands), []); + // The report turn was requested but waits behind another run. + const reportAt = DateTime.makeUnsafe(Date.parse(NOW) + 1_000); + const report = { + ...held, + latestRunId: RunId.make("run:report"), + latestUserMessageAt: reportAt, + latestRunRequestedAt: reportAt, + }; + yield* Ref.set( + fixture.snapshots, + makeSnapshot([{ ...report, status: "queued" }, mergedInApp]), + ); yield* fixture.publishMerge; assert.strictEqual(yield* Queue.take(dispatched), mergedInApp.id); assert.deepStrictEqual( @@ -1293,15 +1305,12 @@ describe("ThreadSettlementServiceV2 worker", () => { [mergedInApp.id], ); - const reportAt = DateTime.makeUnsafe(Date.parse(NOW) + 1_000); yield* Ref.set( fixture.snapshots, makeSnapshot([ { - ...held, - latestRunId: RunId.make("run:report"), - latestUserMessageAt: reportAt, - latestRunRequestedAt: reportAt, + ...report, + status: "completed", latestRunStartedAt: reportAt, latestRunCompletedAt: DateTime.makeUnsafe(Date.parse(NOW) + 20_000), }, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index c1c5bfa636280..bb832b77b8deb 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -127,7 +127,7 @@ export function threadHasQueuedTurnStart( function awaitsHeldWorkReport( thread: Pick< ProjectionStore.ProjectionSettlementCandidate, - "heldWorkEndedAt" | "latestUserMessageAt" | "latestRunRequestedAt" + "heldWorkEndedAt" | "latestUserMessageAt" | "latestRunRequestedAt" | "status" >, nowMs: number, ): boolean { @@ -139,6 +139,8 @@ function awaitsHeldWorkReport( ) { return false; } + // A report requested behind another run stays queued until that run ends. + if (thread.status === "queued") return true; const turnRequestedAtMs = latestMillis([ toMillis(thread.latestUserMessageAt), toMillis(thread.latestRunRequestedAt),