diff --git a/.changeset/3803-turn-boundary-hold.md b/.changeset/3803-turn-boundary-hold.md new file mode 100644 index 0000000000..d03264b534 --- /dev/null +++ b/.changeset/3803-turn-boundary-hold.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +A session's history read between a turn's result and the end of its teardown now waits for that turn's boundary. Before, it could replay the answer without its turn id, so a tracked session could never clear as seen. The wait is per session and bounded by the existing boundary deadline. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 8696cf4ed9..b65fde19a1 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1466,7 +1466,7 @@ from worker transcripts, and no extension of the observed-shell guarantee. **Where the next request waited.** The bridge never awaits an observation: it starts one per result and carries on -(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:272`). +(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture (`function held`, `packages/ui-server/src/brain/turn-journal.ts:279-300`), diff --git a/docs/decisions/session-handoff.md b/docs/decisions/session-handoff.md index 28c2f27b22..8603089495 100644 --- a/docs/decisions/session-handoff.md +++ b/docs/decisions/session-handoff.md @@ -160,7 +160,7 @@ its distinct retry treatment. Nothing archives, purges or automatically sends. The notice's presentation and actions are (`StateRoomNotice`, `packages/ui-react/src/components/chat/state-room-notice.tsx:22-100`); the host keeps the measurement and first quiet event (`const onResult`, -`packages/ui-server/src/ws/bridge-capabilities/emission.ts:203-228`). +`packages/ui-server/src/ws/bridge-capabilities/emission.ts:203-229`). ### Historical state directories remain untouched diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index b0931cdd97..3d23055b15 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -290,7 +290,7 @@ restore, resend, draft autosave and answer-delivery callbacks. Activity/Inbox/ journal APIs remain independent retained surfaces under the selected exclusion. Concrete entry points include `readSessionRecovery` (`readSessionRecovery`, `packages/ui-server/src/ws/recovery.ts:209-222`), -`FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:67-93`), +`FailureReplay` (`FailureReplay`, `packages/ui-server/src/ws/turn-failures.ts:67-94`), and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:100-110`; `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave belongs to `createDraftClient` (`createDraftClient`, diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index 7f0e062029..0f3d2c7722 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -21,6 +21,8 @@ export interface MakeBridgeOptions { */ onSessionNamed?: ((sessionId: string) => void) | undefined; onTerminalFailure?: ((sessionId: string, failure: TurnFailure) => void) | undefined; + /** Called before this turn's own result frame goes out. */ + onTurnResult?: ((sessionId: string) => void) | undefined; /** The pill label the request already has, read when the session is named (#1004). */ promptLabel?: (() => string | undefined) | undefined; applicationPolicy?: BrainApplicationPolicy | undefined; diff --git a/packages/ui-server/src/ws/bridge-capabilities/emission.ts b/packages/ui-server/src/ws/bridge-capabilities/emission.ts index 7b9a8d0748..5feabeef86 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/emission.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/emission.ts @@ -112,10 +112,10 @@ function offerRetry(ctx: BridgeContext, msg: ResultFrame): ResultFrame { /** Frame emission: stamps, persists and forwards every frame the backend emits. */ export function createEmission(ctx: BridgeContext, transcript: TurnTranscript, - options: Pick): BridgeSlice<"emit"> { + options: Pick): BridgeSlice<"emit"> { const { host, turn, turnId, requestId, backendId, principalId, authorization, work, recorder, mainModel, workerProfile } = ctx; const { coordinator, catalog } = host; - const { promptText, onTerminalFailure, promptLabel, pricingContext } = options; + const { promptText, onTerminalFailure, onTurnResult, promptLabel, pricingContext } = options; const { thinkingLevel, draftRef, attachmentFileIds, draftPrincipalId, resumedSession } = captureFrameFields(ctx); let profileBound = false; let draftSettled = false; @@ -224,6 +224,7 @@ export function createEmission(ctx: BridgeContext, transcript: TurnTranscript, if (turn.turnId === turnId && msg.failure && (msg.outcome === "error" || (msg.outcome === undefined && msg.isError))) { onTerminalFailure?.(msg.sessionId, msg.failure); } + if (turn.turnId === turnId) onTurnResult?.(msg.sessionId); return offerRetry(ctx, msg); }; diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 9ad4ca335b..833f245598 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -91,6 +91,8 @@ export async function openTurnBridge( }, // A terminal failure is recorded against the session it ended. onTerminalFailure: failureRecording.observe, + // History read after the result waits for the turn's boundary (#3155). + onTurnResult: failureRecording.resulted, // A follow-up's pill label is its turn's request label (#1004). promptLabel: () => current.label, applicationPolicy: backend.brainApplicationPolicy?.({ profileId, diff --git a/packages/ui-server/src/ws/turn-failures.ts b/packages/ui-server/src/ws/turn-failures.ts index 00be94a7e6..0fc799fdbb 100644 --- a/packages/ui-server/src/ws/turn-failures.ts +++ b/packages/ui-server/src/ws/turn-failures.ts @@ -66,7 +66,8 @@ const BOUNDARY_READ_MS = 10_000; /** One concrete host's in-flight writes; never shared across apps or sessions. */ export class FailureReplay { private readonly pending = new Map>>(); - constructor(private readonly catalog: SessionCatalog, private readonly log: Logger) {} + /** `boundaryReadMs` bounds a boundary read and a result-to-finish hold; tests shorten it. */ + constructor(private readonly catalog: SessionCatalog, private readonly log: Logger, private readonly boundaryReadMs = BOUNDARY_READ_MS) {} async wait(sessionId: string): Promise { for (;;) { @@ -111,7 +112,7 @@ export class FailureReplay { // so the read is bounded by its own timer instead. const messages = await Promise.race([ backend.getHistory(sessionId), - new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), BOUNDARY_READ_MS); }), + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), this.boundaryReadMs); }), ]); this.catalog.recordScratchPins?.(sessionId, backend.id, messages); const count = assistantCount(messages); @@ -129,6 +130,8 @@ export class FailureReplay { async begin(backend: AgentBackend, sessionId: string | undefined, turnId: string, signal: AbortSignal): Promise<{ observe: (sessionId: string, failure: TurnFailure) => void; + /** The turn's own result went out: history reads of its session wait for its end (`finish`). */ + resulted: (sessionId: string) => void; /** `sessionId` is the session the turn ran in, when it ran; boundaries are recorded only then. */ finish: (sessionId?: string | null) => Promise; }> { @@ -143,6 +146,9 @@ export class FailureReplay { const settled = new Promise((resolve) => { release = resolve; }); let write: Promise | undefined; let closed = false; + let end!: () => void; + const ended = new Promise((resolve) => { end = resolve; }); + let held = false; return { observe: (sid, failure) => { if (closed || before === null || write) return; @@ -162,12 +168,29 @@ export class FailureReplay { })(); this.track(sid, write); }, + resulted: (sid) => { + // A client may read the history again the moment the result + // arrives, while host teardown still runs. Its replay must wait for + // this turn's boundary, or the answer it ends replays without its + // turn id and nothing replays it again (#3155). Bounded like the + // boundary read, so a teardown that never finishes cannot hold + // the session's history. + if (closed || held || before === null || !this.catalog.recordTurnBoundary) return; + held = true; + let timer: ReturnType | undefined; + const hold = Promise.race([ended, new Promise((resolve) => { timer = setTimeout(resolve, this.boundaryReadMs); })]) + .finally(() => clearTimeout(timer)); + this.track(sid, hold); + }, finish: async (sid) => { const first = !closed; - closed = true; release(); await write; - if (first && sid && ((before !== null && this.catalog.recordTurnBoundary) || this.catalog.recordScratchPins)) { - await this.boundary(backend, sid, turnId, before); - } + closed = true; release(); + try { + await write; + if (first && sid && ((before !== null && this.catalog.recordTurnBoundary) || this.catalog.recordScratchPins)) { + await this.boundary(backend, sid, turnId, before); + } + } finally { end(); } }, }; } diff --git a/packages/ui-server/tests/turn-boundary-hold.test.ts b/packages/ui-server/tests/turn-boundary-hold.test.ts new file mode 100644 index 0000000000..1835f554d3 --- /dev/null +++ b/packages/ui-server/tests/turn-boundary-hold.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; +import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; +import { createRecordingObservability } from "../src/observability/index"; +import type { SessionCatalog } from "../src/ws/session-catalog"; +import { FailureReplay } from "../src/ws/turn-failures"; + +// The result-to-finish hold (#3803): a history read of a session waits for +// its turn's boundary, never for another session's, and never for longer +// than the boundary deadline. + +const answer = (content: string): SessionHistoryMessage => ({ role: "assistant", content, toolCalls: [] } as unknown as SessionHistoryMessage); + +function setup(boundaryReadMs?: number) { + const recorded: string[] = []; + const catalog = { recordTurnBoundary: (_sessionId: string, _backendId: string, boundary: { turnId: string }) => { recorded.push(boundary.turnId); } } as unknown as SessionCatalog; + let history: SessionHistoryMessage[] = []; + const backend = { id: "claude", getHistory: async () => structuredClone(history) } as unknown as AgentBackend; + const replay = new FailureReplay(catalog, createRecordingObservability().logger("turn"), boundaryReadMs); + const pending = () => (replay as unknown as { pending: Map>> }).pending; + return { replay, backend, recorded, pending, answer: (content: string) => { history = [...history, answer(content)]; } }; +} + +/** Whether `promise` settles within a few event-loop turns. */ +async function settlesSoon(promise: Promise): Promise { + let done = false; + void promise.then(() => { done = true; }); + for (let i = 0; i < 20 && !done; i++) await Bun.sleep(1); + return done; +} + +test("a held session's reads wait for its boundary; an unrelated session's do not", async () => { + const h = setup(); + const turn = await h.replay.begin(h.backend, "ithaca", "turn-ithaca", new AbortController().signal); + h.answer("The ship is rostered."); + turn.resulted("ithaca"); + expect(await settlesSoon(h.replay.wait("aeaea")), "another session reads at once").toBe(true); + const held = h.replay.wait("ithaca"); + expect(await settlesSoon(held), "this session waits for its turn's end").toBe(false); + await turn.finish("ithaca"); + expect(await settlesSoon(held), "and reads once the boundary is recorded").toBe(true); + expect(h.recorded).toEqual(["turn-ithaca"]); + expect(h.pending().size, "no pending entry is left").toBe(0); +}); + +test("a teardown that never finishes releases the hold at the boundary deadline", async () => { + const h = setup(50); + const turn = await h.replay.begin(h.backend, "ithaca", "turn-ithaca", new AbortController().signal); + turn.resulted("ithaca"); + const held = h.replay.wait("ithaca"); + expect(await settlesSoon(held), "held before the deadline").toBe(false); + await Bun.sleep(80); + expect(await settlesSoon(held), "released by the deadline without a finish").toBe(true); + expect(h.pending().size, "no pending entry is left").toBe(0); + expect(h.recorded, "no boundary is made up").toEqual([]); +}); diff --git a/packages/ui-server/tests/ws-turn-failure-replay.test.ts b/packages/ui-server/tests/ws-turn-failure-replay.test.ts index 5b4e428921..7ef9d318e5 100644 --- a/packages/ui-server/tests/ws-turn-failure-replay.test.ts +++ b/packages/ui-server/tests/ws-turn-failure-replay.test.ts @@ -43,6 +43,7 @@ function harness(id: "claude" | "pi") { let turns = 0; let persist = true; let historyHold: Promise | undefined; + let endHold: Promise | undefined; let reads = 0; const bridges: BackendBridge[] = []; let lateFailure: TurnFailure | undefined; @@ -67,6 +68,8 @@ function harness(id: "claude" | "pi") { isError: true, outcome: "error", failure: lateFailure }); req.bridge.emit({ type: "result", sessionId: "s1", numTurns: 1, durationMs: 1, isError: !!failure, outcome: failure ? "error" : "success", ...(failure ? { failure } : {}) }); + // A backend may still be settling after its result: the turn ends later. + await endHold; }, async getHistory() { reads++; @@ -85,6 +88,11 @@ function harness(id: "claude" | "pi") { get reads() { return reads; }, withholdTranscript() { persist = false; }, emitLateFailure(next: TurnFailure) { lateFailure = next; }, + holdEnd() { + let release!: () => void; + endHold = new Promise((resolve) => { release = () => { endHold = undefined; resolve(); }; }); + return release; + }, holdHistory() { let release!: () => void; historyHold = new Promise((resolve) => { release = () => { historyHold = undefined; resolve(); }; }); @@ -313,4 +321,25 @@ for (const id of ["claude", "pi"] as const) describe(`${id}: live failure surviv expect(replay?.type === "session_history" && replay.messages.at(-1)?.failure).toEqual(live); } finally { release(); await sending; } }); + + test("a resume between a turn's result and its end waits for the turn's boundary", async () => { + const h = harness(id); + const release = h.holdEnd(); + const sending = h.send(); + try { + for (let i = 0; i < 200 && !h.frames.some((frame) => frame.type === "result"); i++) await Bun.sleep(5); + // Servers stamp the turn id on every frame (protocol.ts, RESERVED). + const result = h.frames.find((frame): frame is Extract & { turnId?: string } => frame.type === "result"); + expect(result?.turnId).toBeString(); + // A client reads the history again on the result, as a started + // follow-up carrying composer originals does (#3155). + const frames: ServerMessage[] = []; + const loading = handleClientMessage({ send: (data) => frames.push(JSON.parse(data)) }, { type: "session_resume", sessionId: "s1" }); + for (let i = 0; i < 20 && !frames.some((frame) => frame.type === "session_history"); i++) await Bun.sleep(5); + release(); + await sending; await loading; + const replay = frames.find((frame) => frame.type === "session_history"); + expect(replay?.type === "session_history" && replay.messages.at(-1)?.turnId, "the answer carries its turn").toBe(result?.turnId); + } finally { release(); await sending; } + }); });