Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode };
const reconnectShell = { ...resumedShell.recorder.totals(), mode: shellMode };
const reconnectSqlStatements = counter.count() - reconnectSqlStart;
assert.equal(threadMode, "snapshot");
assert.equal(threadMode, "replay");

const get = (path: string) =>
measureHttpGet({
Expand Down
110 changes: 2 additions & 108 deletions apps/server/src/orchestration-v2/ThreadStream.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
ContextHandoffId,
ContextTransferId,
EventId,
OrchestrationV2ThreadStreamItem,
ProviderThreadId,
RunId,
Expand All @@ -17,22 +16,10 @@ import * as DateTime from "effect/DateTime";
import * as Schema from "effect/Schema";
import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot";

import {
buildBoundedThreadStreamSnapshot,
decideThreadResume,
isThreadReplayRawPayloadSafe,
threadReplayEncodedBytes,
THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES,
THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
THREAD_RESUME_MAX_REPLAY_EVENTS,
} from "./ThreadStream.ts";
import { projectDomainEventForWire } from "./WireProjection.ts";
import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts";

const NOW = DateTime.makeUnsafe("2026-09-08T00:00:00.000Z");
const THREAD_ID = ThreadId.make("thread-stream-test");
const LARGE_PROJECTABLE_OUTPUT_BYTES = 10 * 1_048_576;
const LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES = 10_486_214;
const MAX_PROJECTED_DYNAMIC_REPLAY_BYTES = 2_048;

function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection {
const visibleTurnItems: OrchestrationV2ProjectedTurnItem[] = Array.from(
Expand Down Expand Up @@ -115,44 +102,7 @@ function timelineProjection(itemCount: number): OrchestrationV2ThreadProjection
} as unknown as OrchestrationV2ThreadProjection;
}

describe("decideThreadResume", () => {
it("replays when the event count is within the bound", () => {
expect(
decideThreadResume({
afterSequence: 10,
highWater: 20_000,
replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS,
replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
}),
).toEqual({
mode: "replay",
afterSequence: 10,
throughSequence: 20_000,
});
});

it("falls back to a snapshot when encoded replay bytes exceed the bound", () => {
expect(
decideThreadResume({
afterSequence: 10,
highWater: 11,
replayEventCount: 1,
replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1,
}),
).toEqual({ mode: "snapshot" });
});

it("falls back to a snapshot when the client cursor is ahead of the store", () => {
expect(
decideThreadResume({
afterSequence: 50,
highWater: 40,
replayEventCount: 0,
replayEncodedBytes: 0,
}),
).toEqual({ mode: "snapshot" });
});

describe("buildBoundedThreadStreamSnapshot", () => {
it("builds socket fallback snapshots with a bounded timeline and history cursor", () => {
const projection = timelineProjection(80);
// A delivered side chat digest stays "ready", which bounded snapshots keep.
Expand Down Expand Up @@ -187,62 +137,6 @@ describe("decideThreadResume", () => {
expect(snapshot.hasMoreHistory).toBe(true);
expect(snapshot.latestLocalTurnOrdinal).toBe(80);
});

it("rejects a 10 MiB raw replay even when its projected form fits the wire budget", () => {
const item = {
id: TurnItemId.make("large-dynamic-tool"),
type: "dynamic_tool",
threadId: THREAD_ID,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "completed",
title: "Large result",
toolName: "mcp__test__large_result",
input: { query: "small" },
output: { text: "x".repeat(LARGE_PROJECTABLE_OUTPUT_BYTES) },
startedAt: NOW,
completedAt: NOW,
updatedAt: NOW,
} satisfies OrchestrationV2TurnItem;
const event = {
id: EventId.make("large-dynamic-tool-event"),
type: "turn-item.updated" as const,
threadId: THREAD_ID,
occurredAt: NOW,
payload: item,
};
const rawReplay = [{ kind: "event" as const, sequence: 10, event }];
const projectedReplay = [
{
kind: "event" as const,
sequence: 10,
event: projectDomainEventForWire(event),
},
];

const rawPayloadBytes = Buffer.byteLength(JSON.stringify(event.payload), "utf8");
expect(rawPayloadBytes).toBe(LARGE_PROJECTABLE_RAW_PAYLOAD_BYTES);
expect(rawPayloadBytes).toBeGreaterThan(THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES);
expect(isThreadReplayRawPayloadSafe(rawPayloadBytes)).toBe(false);
expect(threadReplayEncodedBytes(rawReplay)).toBeGreaterThan(
THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES,
);
const projectedBytes = threadReplayEncodedBytes(projectedReplay);
expect(projectedBytes).toBeLessThanOrEqual(MAX_PROJECTED_DYNAMIC_REPLAY_BYTES);
expect(
decideThreadResume({
afterSequence: 9,
highWater: 10,
replayEventCount: projectedReplay.length,
replayEncodedBytes: projectedBytes,
}),
).toEqual({ mode: "replay", afterSequence: 9, throughSequence: 10 });
});
});

describe("compact bounded snapshots", () => {
Expand Down
38 changes: 1 addition & 37 deletions apps/server/src/orchestration-v2/ThreadStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,7 @@ import {

export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128;

export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576;

/** Decoded objects and temporary strings exceed stored JSON size, even before wire slimming. */
export const THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES = 1_048_576;

export function isThreadReplayRawPayloadSafe(rawPayloadBytes: number): boolean {
return rawPayloadBytes <= THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES;
}
const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576;

export function threadReplayEncodedBytes(
items: ReadonlyArray<unknown>,
Expand Down Expand Up @@ -87,32 +80,3 @@ export function buildBoundedThreadStreamSnapshot(input: {
}),
};
}

export type ThreadResumePlan =
| {
readonly mode: "replay";
readonly afterSequence: number;
readonly throughSequence: number;
}
| { readonly mode: "snapshot" };

/** Bound event count and encoded bytes; replace excessive replay with one current snapshot. */
export function decideThreadResume(input: {
readonly afterSequence: number;
readonly highWater: number;
readonly replayEventCount: number;
readonly replayEncodedBytes: number;
}): ThreadResumePlan {
if (
input.afterSequence > input.highWater ||
input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS ||
input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES
) {
return { mode: "snapshot" };
}
return {
mode: "replay",
afterSequence: input.afterSequence,
throughSequence: input.highWater,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,72 @@ const seedEvents = Effect.fn("test.seedSequenceEvents")(function* (
`;
});

it.effect("checks creation ranges without restoring or decoding payloads", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
const threadId = ThreadId.make("creation-existence");
const inserted = yield* seedEvents([
{ ...eventRow(1, "thread", 2, threadId), event_type: "thread.created", payload_json: "{" },
eventRow(2, "thread", 2, threadId),
{ ...eventRow(3, "thread", 2, "other"), event_type: "thread.created", payload_json: "{" },
{ ...eventRow(4, "thread", 1, threadId), event_type: "thread.created", payload_json: "{" },
]);
const range = {
threadId,
afterSequence: 0,
throughSequence: inserted[3]!.sequence,
eventType: "thread.created" as const,
};
assert.isTrue(yield* store.hasAgentEvent(range));
assert.isFalse(yield* store.hasAgentEvent({ ...range, afterSequence: inserted[0]!.sequence }));
assert.isFalse(yield* store.hasAgentEvent({ ...range, throughSequence: 0 }));
assert.isTrue(yield* store.hasAgentEvent({ ...range, throughSequence: inserted[0]!.sequence }));
}).pipe(Effect.provide(layerEventStore)),
);

it.effect("fetches the next byte-bounded replay page after delivering the previous page", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("byte-paged-replay");
const rows = Arr.map([1, 2] as const, (ordinal) => ({
...eventRow(ordinal, "thread", 2, threadId),
payload_json: encodeJson({
providerSessionId: `session:${ordinal}:${"x".repeat(180_000)}`,
detachedAt: occurredAt,
}),
}));
const inserted = yield* seedEvents(rows);
const updatedPayload = {
providerSessionId: ProviderSessionId.make("session:updated"),
detachedAt: occurredAt,
};
const items = yield* store
.readAgentEvents({
threadId,
throughSequence: inserted[1]!.sequence,
maxPageBytes: 256 * 1024,
})
.pipe(
Stream.tap((item) =>
item.sequence === inserted[0]!.sequence
? sql`UPDATE orchestration_events SET payload_json = ${encodeJson(updatedPayload)}
WHERE sequence = ${inserted[1]!.sequence}`
: Effect.void,
),
Stream.runCollect,
);
assert.deepEqual(
items.map((item) => item.sequence),
inserted.map((item) => item.sequence),
);
assert.deepEqual(items[1]!.event.payload, {
...updatedPayload,
detachedAt: DateTime.makeUnsafe(occurredAt),
});
}).pipe(Effect.provide(layerEventStore)),
);

it.effect("keeps application and scoped agent high-water marks separate from legacy history", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
Expand Down
61 changes: 27 additions & 34 deletions apps/server/src/persistence/OrchestrationEventStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ layer("OrchestrationEventStore", (it) => {
const id = NodeId.make("node:subagent-prompt");
const driver = ProviderDriverKind.make("claudeAgent");
const providerInstanceId = ProviderInstanceId.make("claudeAgent");
const prompt = "Audit the repository. ".repeat(200);
const prompt = 'Audit "repo"\n漢字 '.repeat(9_000);
const subagent = (index: number, progress: string, nextPrompt = prompt) =>
({
id: EventId.make(`event:subagent-prompt:subagent:${index}`),
Expand Down Expand Up @@ -183,14 +183,14 @@ layer("OrchestrationEventStore", (it) => {
subagent(3, "Retrying", "Audit again."),
item(3, "Retrying", "Audit again."),
];
yield* store.appendAgentEvents({ events });
const appended = yield* store.appendAgentEvents({ events });

const stored = yield* sql<{ readonly payload_json: string }>`
SELECT payload_json FROM orchestration_events
WHERE stream_id = ${threadId} ORDER BY sequence ASC
`;
assert.deepEqual(
stored.map((row) => row.payload_json.includes(prompt)),
stored.map((row) => row.payload_json.includes(JSON.stringify(prompt).slice(1, -1))),
[true, true, false, false, false, false, false, false],
);
const replayed = yield* store
Expand All @@ -200,18 +200,33 @@ layer("OrchestrationEventStore", (it) => {
replayed.map((entry) => entry.event),
events,
);
const stats = yield* store.getAgentReplayStats({
threadId,
afterSequence,
throughSequence: yield* store.latestApplicationSequence,
maxEvents: events.length,
});
assert.isAbove(stats.rawPayloadBytes, prompt.length * 6);
const applicationStats = yield* store.getReplayStats({
afterSequence,
throughSequence: yield* store.latestApplicationSequence,
});
assert.isAbove(applicationStats.rawPayloadBytes, prompt.length * 6);
const paged = yield* store
.readAgentEvents({ threadId, afterSequence, maxPageBytes: 256 * 1024 })
.pipe(Stream.runCollect);
assert.deepEqual(
paged.map((entry) => entry.event),
events,
);
// The first two updates here reference prompts in earlier anchor rows.
// Sizing must stop before touching a later page's malformed payload.
yield* sql`UPDATE orchestration_events SET payload_json = '{' WHERE sequence = ${appended[4]!.sequence}`;
const firstPage = yield* store
.readAgentEvents({
threadId,
afterSequence: appended[1]!.sequence,
throughSequence: appended[4]!.sequence,
maxPageBytes: 256 * 1024,
})
.pipe(Stream.take(1), Stream.runCollect);
assert.deepEqual(
firstPage.map((entry) => entry.event),
[events[2]!],
);
}),
);

Expand Down Expand Up @@ -392,7 +407,7 @@ layer("OrchestrationEventStore", (it) => {
);
}),
);
it.effect("measures only a bounded thread replay before decoding its payloads", () =>
it.effect("measures replay payloads before decoding them", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
Expand Down Expand Up @@ -420,7 +435,7 @@ layer("OrchestrationEventStore", (it) => {
`;
return rows[0]!.sequence;
});
const first = yield* insert({
yield* insert({
id: "measured-replay-1",
payload: unicodePayload,
type: "thread.created",
Expand All @@ -432,28 +447,6 @@ layer("OrchestrationEventStore", (it) => {
});
yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 });
const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload });
const later = yield* insert({ id: "measured-replay-003", payload: "{}" });
const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 };
assert.deepEqual(yield* store.getAgentReplayStats(range), {
eventCount: 2,
rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload),
hasCreateEvent: true,
});
assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), {
eventCount: 1,
rawPayloadBytes: Buffer.byteLength(oversizedPayload),
hasCreateEvent: false,
});
assert.equal(
(yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 }))
.eventCount,
2,
);
assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), {
eventCount: 0,
rawPayloadBytes: 0,
hasCreateEvent: false,
});
assert.deepEqual(
yield* store.getReplayStats({ afterSequence: baseline, throughSequence: head }),
{
Expand Down
Loading
Loading