conversation-topic-publisher-hydration-bound.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import { Buffer } from "node:buffer";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. SessionEventType,
  5. type EventId,
  6. type SessionEvent,
  7. type SessionEventType as SessionEventTypeUnion,
  8. type SessionId,
  9. type TraceId,
  10. type TurnId,
  11. } from "@zcode/contracts";
  12. import { PROTOCOL_V4_LIMITS, utf8JsonByteLength } from "@zcode/shared/zcode-protocol-v4";
  13. import {
  14. coldHydrationJsonByteLength,
  15. ConversationTopicPublisher,
  16. PROJECTION_TERMINAL_RESERVE_BYTES,
  17. } from "../src/zcode-protocol-v4/conversation-topic-publisher.js";
  18. const wireByteProbe = vi.hoisted(() => ({
  19. snapshotBytesOverride: null as ((value: unknown) => number | null) | null,
  20. inputs: [] as unknown[],
  21. snapshotSequences: [] as number[],
  22. }));
  23. vi.mock("@zcode/shared/zcode-protocol-v4", async (importOriginal) => {
  24. const actual = await importOriginal<typeof import("@zcode/shared/zcode-protocol-v4")>();
  25. return {
  26. ...actual,
  27. utf8JsonByteLength(value: unknown): number {
  28. wireByteProbe.inputs.push(value);
  29. if (
  30. typeof value === "object" &&
  31. value !== null &&
  32. "payload" in value &&
  33. typeof value.payload === "object" &&
  34. value.payload !== null &&
  35. "kind" in value.payload &&
  36. value.payload.kind === "snapshot" &&
  37. "snapshot" in value.payload &&
  38. typeof value.payload.snapshot === "object" &&
  39. value.payload.snapshot !== null &&
  40. "seq" in value.payload.snapshot &&
  41. typeof value.payload.snapshot.seq === "number"
  42. ) {
  43. wireByteProbe.snapshotSequences.push(value.payload.snapshot.seq);
  44. }
  45. const snapshotBytesOverride = wireByteProbe.snapshotBytesOverride?.(value);
  46. if (snapshotBytesOverride !== null && snapshotBytesOverride !== undefined) {
  47. return snapshotBytesOverride;
  48. }
  49. return actual.utf8JsonByteLength(value);
  50. },
  51. };
  52. });
  53. function sessionEvent(
  54. sequenceNumber: number,
  55. type: SessionEventTypeUnion,
  56. payload: unknown,
  57. turnId?: string,
  58. ): SessionEvent {
  59. return {
  60. id: `event-${sequenceNumber}` as EventId,
  61. sessionId: "session-1" as SessionId,
  62. ...(turnId ? { turnId: turnId as TurnId } : {}),
  63. type,
  64. timestamp: new Date(1_700_000_000_000 + sequenceNumber),
  65. traceId: "trace-1" as TraceId,
  66. sequenceNumber,
  67. payload,
  68. };
  69. }
  70. function checkpoint(sequenceNumber: number): SessionEvent {
  71. return sessionEvent(sequenceNumber, SessionEventType.CheckpointCreated, {
  72. checkpointId: `checkpoint-${sequenceNumber}`,
  73. messageId: `message-${sequenceNumber}`,
  74. targetMessageId: `message-${sequenceNumber}`,
  75. scope: "workspace",
  76. snapshotRef: `zcode-artifact://session-1/checkpoint-${sequenceNumber}`,
  77. fileCount: 1,
  78. });
  79. }
  80. function isRecord(value: unknown): value is Record<string, unknown> {
  81. return typeof value === "object" && value !== null && !Array.isArray(value);
  82. }
  83. function snapshotMeasurementCount(): number {
  84. return wireByteProbe.inputs.filter((value) => {
  85. if (!isRecord(value) || !isRecord(value.payload)) return false;
  86. return value.payload.kind === "snapshot";
  87. }).length;
  88. }
  89. function snapshotSequence(value: unknown): number | null {
  90. if (!isRecord(value) || !isRecord(value.payload) || value.payload.kind !== "snapshot") {
  91. return null;
  92. }
  93. if (!isRecord(value.payload.snapshot) || typeof value.payload.snapshot.seq !== "number") {
  94. return null;
  95. }
  96. return value.payload.snapshot.seq;
  97. }
  98. describe("cold hydration wire payload upper bound", () => {
  99. it.each([
  100. ["顶层 undefined", undefined],
  101. ["ASCII", { kind: "deltas", deltas: [{ text: "plain text" }] }],
  102. ["中文", { text: "冷启动恢复" }],
  103. ["emoji", { text: "ready 🚀" }],
  104. ["JSON 转义", { text: "quote: \\\" slash: \\\\ newline:\n tab:\t" }],
  105. ["未配对 surrogate", { text: "\ud800" }],
  106. ])("cold-only byte length 对 %s 保持 shared 精确结果", (_name, value) => {
  107. expect(coldHydrationJsonByteLength(value)).toBe(utf8JsonByteLength(value));
  108. });
  109. it("no-delta checkpoint 只在 candidate 初始化和最终事件精确测量", () => {
  110. const events = [
  111. sessionEvent(1, SessionEventType.SessionCreated, {
  112. mode: "default",
  113. contextWindow: 200_000,
  114. }),
  115. ...Array.from({ length: 100 }, (_, index) => checkpoint(index + 2)),
  116. ];
  117. const strict = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  118. for (const event of events) strict.ingest(event);
  119. const cold = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  120. const byteLengthSpy = vi.spyOn(Buffer, "byteLength");
  121. const emptyDeltaJson = JSON.stringify({ kind: "deltas", deltas: [] });
  122. try {
  123. wireByteProbe.inputs.length = 0;
  124. cold.rehydrate(events);
  125. expect(cold.getSnapshot()).toEqual(strict.getSnapshot());
  126. expect(byteLengthSpy.mock.calls.some(([value]) => value === emptyDeltaJson)).toBe(false);
  127. expect(snapshotMeasurementCount()).toBe(2);
  128. } finally {
  129. byteLengthSpy.mockRestore();
  130. }
  131. });
  132. it("保守增长触及限额时先按当前 snapshot 精确重测,不误回退 strict replay", () => {
  133. const titleBody = "x".repeat(4 * 1024 * 1024);
  134. const events = [
  135. sessionEvent(1, SessionEventType.SessionCreated, {
  136. mode: "default",
  137. contextWindow: 200_000,
  138. }),
  139. ...Array.from({ length: 5 }, (_, index) =>
  140. sessionEvent(index + 2, SessionEventType.SessionTitleUpdated, {
  141. previousTitle: index === 0 ? "" : `${index - 1}${titleBody}`,
  142. title: `${index}${titleBody}`,
  143. source: "custom",
  144. }),
  145. ),
  146. ];
  147. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  148. wireByteProbe.inputs.length = 0;
  149. publisher.rehydrate(events);
  150. expect(snapshotMeasurementCount()).toBeGreaterThan(2);
  151. const resumed = publisher.subscribe({
  152. connectionId: "mobile",
  153. deliveryProfile: "replayable",
  154. base: { logEpoch: "epoch-1", seq: 1 },
  155. });
  156. expect(resumed.ack.mode).toBe("snapshot");
  157. expect(resumed.frame?.payload.kind).toBe("snapshot");
  158. expect(utf8JsonByteLength(resumed.frame)).toBeLessThan(
  159. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  160. );
  161. });
  162. it.each([
  163. { from: 9, to: 10, headroomBytes: 1 },
  164. { from: 99, to: 100, headroomBytes: 3 },
  165. ])("sequence $from→$to 位数增长计入上界,并在越界前精确重测", ({ from, to, headroomBytes }) => {
  166. const events = [checkpoint(from), checkpoint(to), checkpoint(to + 1)];
  167. const strict = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  168. for (const event of events) strict.ingest(event);
  169. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  170. const runtimeLimit =
  171. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes - PROJECTION_TERMINAL_RESERVE_BYTES;
  172. wireByteProbe.inputs.length = 0;
  173. wireByteProbe.snapshotSequences.length = 0;
  174. wireByteProbe.snapshotBytesOverride = () => runtimeLimit - headroomBytes;
  175. try {
  176. publisher.rehydrate(events);
  177. } finally {
  178. wireByteProbe.snapshotBytesOverride = null;
  179. }
  180. expect(wireByteProbe.snapshotSequences).toEqual([0, to, to + 1]);
  181. expect(publisher.getSnapshot()).toEqual(strict.getSnapshot());
  182. expect(
  183. publisher.subscribe({
  184. connectionId: "mobile",
  185. deliveryProfile: "replayable",
  186. base: { logEpoch: "epoch-1", seq: from },
  187. }).ack.mode,
  188. ).toBe("snapshot");
  189. });
  190. it.each([
  191. {
  192. name: "TurnComplete",
  193. type: SessionEventType.TurnComplete,
  194. payload: {
  195. response: "",
  196. tokenCount: 0,
  197. toolCallCount: 0,
  198. duration: 1,
  199. resultType: "success",
  200. },
  201. },
  202. {
  203. name: "TurnError",
  204. type: SessionEventType.TurnError,
  205. payload: {
  206. error: { type: "test.error", message: "failed" },
  207. turnPhase: "model",
  208. },
  209. },
  210. ])("普通事件后紧接 $name 时可使用 terminal reserve", ({ type, payload }) => {
  211. const events = [
  212. sessionEvent(1, SessionEventType.SessionCreated, {
  213. mode: "default",
  214. contextWindow: 200_000,
  215. }),
  216. sessionEvent(
  217. 2,
  218. SessionEventType.TurnStarted,
  219. { turnNumber: 1, input: "第一问", messageId: "user-1" },
  220. "turn-1",
  221. ),
  222. sessionEvent(
  223. 3,
  224. SessionEventType.ModelStreaming,
  225. {
  226. kind: "text_start",
  227. delta: "",
  228. done: false,
  229. assistantMessageId: "assistant-1",
  230. },
  231. "turn-1",
  232. ),
  233. sessionEvent(
  234. 4,
  235. SessionEventType.ModelStreaming,
  236. { kind: "text_delta", delta: "第一答", done: false },
  237. "turn-1",
  238. ),
  239. checkpoint(5),
  240. sessionEvent(6, type, payload, "turn-1"),
  241. ];
  242. const strict = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  243. for (const event of events) strict.ingest(event);
  244. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  245. const fullLimit = PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes;
  246. const runtimeLimit = fullLimit - PROJECTION_TERMINAL_RESERVE_BYTES;
  247. wireByteProbe.snapshotSequences.length = 0;
  248. wireByteProbe.snapshotBytesOverride = (value) => {
  249. const sequenceNumber = snapshotSequence(value);
  250. if (sequenceNumber === null) return null;
  251. return sequenceNumber === 6 ? fullLimit : runtimeLimit - 1024 * 1024;
  252. };
  253. try {
  254. publisher.rehydrate(events);
  255. } finally {
  256. wireByteProbe.snapshotBytesOverride = null;
  257. }
  258. expect(wireByteProbe.snapshotSequences).toEqual([0, 6]);
  259. expect(publisher.getSnapshot()).toEqual(strict.getSnapshot());
  260. expect(
  261. publisher.subscribe({
  262. connectionId: "mobile",
  263. deliveryProfile: "replayable",
  264. base: { logEpoch: "epoch-1", seq: 1 },
  265. }).ack.mode,
  266. ).toBe("snapshot");
  267. });
  268. it("row.removed 立即重测,最终事件在 actions 收敛后再次重测", () => {
  269. const events = [
  270. sessionEvent(1, SessionEventType.SessionCreated, { mode: "default" }),
  271. sessionEvent(
  272. 2,
  273. SessionEventType.TurnStarted,
  274. { turnNumber: 1, input: "第一问", messageId: "user-1" },
  275. "turn-1",
  276. ),
  277. sessionEvent(
  278. 3,
  279. SessionEventType.ModelStreaming,
  280. {
  281. kind: "text_start",
  282. delta: "",
  283. done: false,
  284. assistantMessageId: "assistant-1",
  285. },
  286. "turn-1",
  287. ),
  288. sessionEvent(
  289. 4,
  290. SessionEventType.ModelStreaming,
  291. { kind: "text_delta", delta: "第一答", done: false },
  292. "turn-1",
  293. ),
  294. sessionEvent(
  295. 5,
  296. SessionEventType.TurnComplete,
  297. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1, resultType: "success" },
  298. "turn-1",
  299. ),
  300. sessionEvent(
  301. 6,
  302. SessionEventType.TurnStarted,
  303. { turnNumber: 2, input: "第二问", messageId: "user-2" },
  304. "turn-2",
  305. ),
  306. sessionEvent(
  307. 7,
  308. SessionEventType.ModelStreaming,
  309. {
  310. kind: "text_start",
  311. delta: "",
  312. done: false,
  313. assistantMessageId: "assistant-2",
  314. },
  315. "turn-2",
  316. ),
  317. sessionEvent(
  318. 8,
  319. SessionEventType.ModelStreaming,
  320. { kind: "text_delta", delta: "第二答", done: false },
  321. "turn-2",
  322. ),
  323. sessionEvent(
  324. 9,
  325. SessionEventType.TurnComplete,
  326. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1, resultType: "success" },
  327. "turn-2",
  328. ),
  329. sessionEvent(10, SessionEventType.RewindTriggered, {
  330. targetMessageId: "assistant-2",
  331. scope: "conversation",
  332. createdMessageId: "rewind-notice",
  333. }),
  334. checkpoint(11),
  335. ];
  336. const strict = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  337. for (const event of events) strict.ingest(event);
  338. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  339. wireByteProbe.inputs.length = 0;
  340. wireByteProbe.snapshotSequences.length = 0;
  341. publisher.rehydrate(events);
  342. expect(snapshotMeasurementCount()).toBe(3);
  343. expect(wireByteProbe.snapshotSequences).toEqual([0, 10, 11]);
  344. expect(publisher.getSnapshot()).toEqual(strict.getSnapshot());
  345. expect(
  346. publisher
  347. .getSnapshot()
  348. .rows.window.filter((row) => row.kind === "userInput")
  349. .map((row) => row.text),
  350. ).toEqual(["第一问"]);
  351. });
  352. });