diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 4dc0cf8083..ffd65459e5 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1134,19 +1134,22 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.session-set": { const turnId = event.payload.session.activeTurnId; if (turnId === null || event.payload.session.status !== "running") { - if ( - event.payload.session.status === "error" || - event.payload.session.status === "stopped" || - event.payload.session.status === "interrupted" - ) { - yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ - threadId: event.payload.threadId, - }); - } // Leaving the "running" session status is the turn-end signal: // settle still-running turns so their duration reflects the whole // turn rather than the last assistant message. const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status); + // Any settled status abandons an unadopted pending turn start — + // including "ready": a mid-turn steer re-arms the pending row + // without a fresh adoption, and a stale row would block queue + // drains (and re-arm the read model's pendingTurnStart flag on + // restart hydration). Ready-with-genuinely-pending starts never + // reach this projection: ingestion maps that shape to + // "starting" before dispatching the session set. + if (settledTurnState !== null) { + yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }); + } if (settledTurnState === null) { return; } diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 5a00c9d5cb..1bc2ff1c37 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -661,6 +661,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { requestedAt: IsoDateTime, }); + const getPendingTurnStartRowByThread = SqlSchema.findOneOption({ + Request: ThreadIdLookupInput, + Result: PendingTurnStartDbRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + pending_message_id AS "messageId", + requested_at AS "requestedAt" + FROM projection_turns + WHERE thread_id = ${threadId} + AND turn_id IS NULL + AND state = 'pending' + AND pending_message_id IS NOT NULL + AND checkpoint_turn_count IS NULL + ORDER BY requested_at DESC + LIMIT 1 + `, + }); + const listPendingTurnStartRows = SqlSchema.findAll({ Request: Schema.Void, Result: PendingTurnStartDbRowSchema, @@ -2104,6 +2124,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { messageRows, proposedPlanRows, queuedMessageRows, + pendingTurnStartRow, activityRows, checkpointRows, latestTurnRow, @@ -2141,6 +2162,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), + getPendingTurnStartRowByThread({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadDetailById:getPendingTurnStart:query", + "ProjectionSnapshotQuery.getThreadDetailById:getPendingTurnStart:decodeRow", + ), + ), + ), listThreadActivityRowsByThread({ threadId }).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -2211,6 +2240,12 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { return message; }), queuedMessages: queuedMessageRows.map(mapQueuedMessageRow), + pendingTurnStart: Option.isSome(pendingTurnStartRow) + ? { + messageId: pendingTurnStartRow.value.messageId, + requestedAt: pendingTurnStartRow.value.requestedAt, + } + : null, proposedPlans: proposedPlanRows.map(mapProposedPlanRow), activities: activityRows.map((row) => { const activity = { diff --git a/apps/server/src/orchestration/decider.queue.test.ts b/apps/server/src/orchestration/decider.queue.test.ts index 5aabf54ddc..1fe7ac9f6b 100644 --- a/apps/server/src/orchestration/decider.queue.test.ts +++ b/apps/server/src/orchestration/decider.queue.test.ts @@ -212,6 +212,60 @@ it.layer(NodeServices.layer)("decider queue flows", (it) => { }), ); + it.effect("drains after a mid-turn steer once the turn settles to ready", () => + Effect.gen(function* () { + // Two messages queue while running; the first is steered mid-turn + // (re-arming pendingTurnStart), then the turn completes → ready. + let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3); + readModel = yield* applyPlanned( + readModel, + yield* decideOrchestrationCommand({ command: turnStartCommand("settle-1"), readModel }), + ); + readModel = yield* applyPlanned( + readModel, + yield* decideOrchestrationCommand({ command: turnStartCommand("settle-2"), readModel }), + ); + readModel = yield* applyPlanned( + readModel, + yield* decideOrchestrationCommand({ + command: { + type: "thread.queue.steer", + commandId: asCommandId("cmd-steer-settle"), + threadId: THREAD_ID, + messageId: asMessageId("message-settle-1"), + createdAt: NOW, + }, + readModel, + }), + ); + // The steer left pendingTurnStart armed with the session still running. + let thread = readModel.threads.find((entry) => entry.id === THREAD_ID); + expect(thread?.pendingTurnStart?.messageId).toEqual(asMessageId("message-settle-1")); + + // Turn end: session settles to ready, which must release the pending + // flag so the queued follow-up can drain. + readModel = yield* withSessionStatus(readModel, "ready", readModel.snapshotSequence + 1); + thread = readModel.threads.find((entry) => entry.id === THREAD_ID); + expect(thread?.pendingTurnStart).toBeNull(); + + const planned = yield* decideOrchestrationCommand({ + command: { + type: "thread.queue.drain", + commandId: asCommandId("cmd-drain-settle"), + threadId: THREAD_ID, + createdAt: NOW, + }, + readModel, + }); + const events = Array.isArray(planned) ? planned : [planned]; + expect(events.map((event) => event.type)).toEqual([ + "thread.queued-message-removed", + "thread.message-sent", + "thread.turn-start-requested", + ]); + }), + ); + it.effect("rejects queueing past the per-thread cap", () => Effect.gen(function* () { let readModel = yield* withSessionStatus(yield* seedReadModel, "running", 3); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index ed83947bf1..bf22a7a1db 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -877,13 +877,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // While a turn start is still pending there is no provider turn to // steer into — dispatching now would race the pending turn/start with // a second one. The message stays queued; steer again once running. - // A `starting` session that already tracks an active turn (provider - // reconnect mid-turn) is steerable. Rejected shapes: starting with no - // active turn, and a seemingly-idle session whose just-dispatched - // turn start the provider has not adopted yet. + // A session that already tracks an active turn (running, or a + // provider reconnect mid-turn) is steerable. Rejected shapes: starting + // with no active turn, and any session without an active turn while a + // just-dispatched turn start is still awaiting adoption — including + // "running" with a null activeTurnId (provider waiting). const steerRacesPendingStart = (thread.session?.status === "starting" && thread.session.activeTurnId === null) || - (thread.session?.status !== "running" && thread.pendingTurnStart !== null); + (thread.pendingTurnStart !== null && (thread.session?.activeTurnId ?? null) === null); if (steerRacesPendingStart) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 080de70d82..7e14c6d4f6 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -589,14 +589,15 @@ export function projectEvent( // a still-running latest turn so its duration reflects the whole turn. const settledTurnState = settledTurnStateForSessionStatus(session.status); // Mirrors the SQL pipeline's pending-turn-start clearing: a running - // session with an active turn adopts the pending start, and terminal - // statuses (error/stopped/interrupted) abandon it. "starting" and - // idle-ish statuses leave it pending. + // session with an active turn adopts the pending start; every settled + // or terminal status (ready/idle/error/stopped/interrupted) clears it + // — a mid-turn steer re-arms the flag without any adopting session + // transition, so the turn-end ready must release it or drains would + // be rejected forever. Only "starting" (and running while waiting on + // a turn id) keeps it pending. const pendingTurnStart = (session.status === "running" && session.activeTurnId !== null) || - session.status === "error" || - session.status === "stopped" || - session.status === "interrupted" + settledTurnStateForSessionStatus(session.status) !== null ? null : thread.pendingTurnStart; return {