review round 4: release pendingTurnStart on turn end, harden steer guard, hydrate detail snapshot

- Clear pendingTurnStart on every settled session status (including
  ready), in both the in-memory projector and the SQL projection. A
  mid-turn steer re-arms the flag with the session already running, so
  only terminal-status clearing left it stuck after natural completion,
  permanently rejecting queue drains. Ready-with-genuinely-pending
  starts never project as ready — ingestion maps that shape to starting.
- Reject steer while a turn start awaits adoption whenever the session
  tracks no active turn, including running with a null activeTurnId.
- Hydrate pendingTurnStart in getThreadDetailById so thread-detail
  snapshots agree with the command read model after a refresh.
- Decider test covers the steer-then-complete-then-drain lifecycle.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-07-23 03:15:10 -07:00
1 parent 2218b91213
commit 6be48eb238
5 files changed
+114 -20

No files matched your search

@@ -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;
}
@@ -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 = {
@@ -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);
+6 -5
View File
@@ -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,
+7 -6
View File
@@ -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 {