Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/3803-turn-boundary-hold.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`, `packages/ui-server/src/brain/turn-journal.ts:279-300`),
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/session-handoff.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
2 changes: 2 additions & 0 deletions packages/ui-server/src/ws/bridge-capabilities/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
5 changes: 3 additions & 2 deletions packages/ui-server/src/ws/bridge-capabilities/emission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MakeBridgeOptions, "promptText" | "onSessionNamed" | "onTerminalFailure" | "promptLabel" | "pricingContext">): BridgeSlice<"emit"> {
options: Pick<MakeBridgeOptions, "promptText" | "onSessionNamed" | "onTerminalFailure" | "onTurnResult" | "promptLabel" | "pricingContext">): 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;
Expand Down Expand Up @@ -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);
};

Expand Down
2 changes: 2 additions & 0 deletions packages/ui-server/src/ws/session-run/backend-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
35 changes: 29 additions & 6 deletions packages/ui-server/src/ws/turn-failures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Set<Promise<void>>>();
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<void> {
for (;;) {
Expand Down Expand Up @@ -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<never>((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), BOUNDARY_READ_MS); }),
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("history read timed out")), this.boundaryReadMs); }),
]);
this.catalog.recordScratchPins?.(sessionId, backend.id, messages);
const count = assistantCount(messages);
Expand All @@ -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<void>;
}> {
Expand All @@ -143,6 +146,9 @@ export class FailureReplay {
const settled = new Promise<void>((resolve) => { release = resolve; });
let write: Promise<void> | undefined;
let closed = false;
let end!: () => void;
const ended = new Promise<void>((resolve) => { end = resolve; });
let held = false;
return {
observe: (sid, failure) => {
if (closed || before === null || write) return;
Expand All @@ -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<typeof setTimeout> | undefined;
const hold = Promise.race([ended, new Promise<void>((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(); }
},
};
}
Expand Down
56 changes: 56 additions & 0 deletions packages/ui-server/tests/turn-boundary-hold.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, Set<Promise<void>>> }).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<unknown>): Promise<boolean> {
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([]);
});
29 changes: 29 additions & 0 deletions packages/ui-server/tests/ws-turn-failure-replay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ function harness(id: "claude" | "pi") {
let turns = 0;
let persist = true;
let historyHold: Promise<void> | undefined;
let endHold: Promise<void> | undefined;
let reads = 0;
const bridges: BackendBridge[] = [];
let lateFailure: TurnFailure | undefined;
Expand All @@ -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++;
Expand All @@ -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<void>((resolve) => { release = () => { endHold = undefined; resolve(); }; });
return release;
},
holdHistory() {
let release!: () => void;
historyHold = new Promise<void>((resolve) => { release = () => { historyHold = undefined; resolve(); }; });
Expand Down Expand Up @@ -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<ServerMessage, { type: "result" }> & { 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; }
});
});
Loading