compacted-full-history-cold-hydration.perf.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { createHash } from "node:crypto";
  2. import { performance } from "node:perf_hooks";
  3. import { describe, expect, it } from "vitest";
  4. import {
  5. CompactTimelineStatus,
  6. CompactTrigger,
  7. SessionEventType,
  8. type EventId,
  9. type MessagePart,
  10. type MessageWithParts,
  11. type SessionEvent,
  12. type SessionId,
  13. type TraceId,
  14. type TurnId,
  15. } from "@zcode/contracts";
  16. import { activeSessionMessages } from "@zcode/core";
  17. import { conversationTopicFrameSchema } from "@zcode/shared/zcode-protocol-v4";
  18. import { mergeColdConversationEvents } from "../src/zcode-protocol-v4/cold-event-merge.js";
  19. import { ConversationTopicPublisher } from "../src/zcode-protocol-v4/conversation-topic-publisher.js";
  20. const SESSION_ID = "perf03-compacted-full-history-cold-hydration";
  21. const PRECOMPACT_TURN_COUNT = 4_842;
  22. const PRECOMPACT_REASONING_PART_COUNT = 3_236;
  23. const PERSISTED_MESSAGE_COUNT = 10_623;
  24. const PERSISTED_PART_COUNT = 35_811;
  25. const ACTIVE_MESSAGE_COUNT = 939;
  26. const ACTIVE_PART_COUNT = 3_523;
  27. const ACTIVE_TURN_COUNT = 469;
  28. const ACTIVE_TOOL_PART_COUNT = 1_163;
  29. const ACTIVE_EXTRA_TEXT_PART_COUNT = 14;
  30. const CHECKPOINT_COUNT = 1_805;
  31. const TOOL_NAMES = ["Read", "Grep", "Bash", "Edit"] as const;
  32. describe.skipIf(process.env.ZCODE_PERF_REPRO !== "1")(
  33. "PERF03-E compacted full-history cold hydration repro",
  34. () => {
  35. it("replays the full branch even though runtime history uses the compact tail", () => {
  36. const messages = ticketMessages();
  37. const activeMessages = activeSessionMessages(messages);
  38. const checkpoints = ticketCheckpoints();
  39. expect(messages).toHaveLength(PERSISTED_MESSAGE_COUNT);
  40. expect(messages.reduce((total, message) => total + message.parts.length, 0)).toBe(
  41. PERSISTED_PART_COUNT,
  42. );
  43. expect(activeMessages).toHaveLength(ACTIVE_MESSAGE_COUNT);
  44. expect(activeMessages[0]?.info.id).toBe("perf03-compact-boundary");
  45. expect(activeMessages.reduce((total, message) => total + message.parts.length, 0)).toBe(
  46. ACTIVE_PART_COUNT,
  47. );
  48. expect(
  49. activeMessages.flatMap((message) => message.parts).filter((part) => part.type === "tool"),
  50. ).toHaveLength(ACTIVE_TOOL_PART_COUNT);
  51. expect(checkpoints).toHaveLength(CHECKPOINT_COUNT);
  52. const totalStartedAt = performance.now();
  53. const mergeStartedAt = performance.now();
  54. const merged = mergeColdConversationEvents({
  55. memoryEvents: checkpoints,
  56. messages,
  57. sessionId: SESSION_ID,
  58. });
  59. const mergeMs = performance.now() - mergeStartedAt;
  60. const checkpointDiagnostic = merged.diagnostics.find(
  61. (diagnostic) => diagnostic.code === "cold_merge.unclassified_event_preserved",
  62. );
  63. expect(checkpointDiagnostic).toMatchObject({
  64. count: CHECKPOINT_COUNT,
  65. eventTypes: { [SessionEventType.CheckpointCreated]: CHECKPOINT_COUNT },
  66. });
  67. expect(
  68. merged.events.filter((event) => event.type === SessionEventType.CheckpointCreated),
  69. ).toHaveLength(CHECKPOINT_COUNT);
  70. const publisher = new ConversationTopicPublisher(SESSION_ID, "perf03-e", {
  71. now: () => 0,
  72. });
  73. const rehydrateStartedAt = performance.now();
  74. publisher.rehydrate(merged.events);
  75. const rehydrateMs = performance.now() - rehydrateStartedAt;
  76. const subscribeStartedAt = performance.now();
  77. const subscribed = publisher.subscribe({
  78. connectionId: "perf03-e-desktop",
  79. deliveryProfile: "continuous",
  80. });
  81. const subscribeMs = performance.now() - subscribeStartedAt;
  82. const totalMs = performance.now() - totalStartedAt;
  83. expect(subscribed.frame?.payload.kind).toBe("snapshot");
  84. expect(() => conversationTopicFrameSchema.parse(subscribed.frame)).not.toThrow();
  85. const snapshot =
  86. subscribed.frame?.payload.kind === "snapshot"
  87. ? subscribed.frame.payload.snapshot
  88. : undefined;
  89. expect(snapshot).toBeDefined();
  90. expect(snapshot?.rows.window.some((row) => row.kind === "subagent")).toBe(false);
  91. expect(snapshot?.subagents).toMatchObject({
  92. childSessionIds: [],
  93. endedTotal: 0,
  94. running: [],
  95. });
  96. const frameJson = JSON.stringify(subscribed.frame);
  97. process.stdout.write(
  98. `${JSON.stringify({
  99. caseId: "PERF03-E",
  100. checkpointCount: CHECKPOINT_COUNT,
  101. initialFrameBytes: Buffer.byteLength(frameJson, "utf8"),
  102. initialFrameHash: createHash("sha256").update(frameJson).digest("hex"),
  103. activeMessageCount: activeMessages.length,
  104. activePartCount: activeMessages.reduce(
  105. (total, message) => total + message.parts.length,
  106. 0,
  107. ),
  108. mergeMs: roundMs(mergeMs),
  109. mergedEventCount: merged.events.length,
  110. persistedMessageCount: messages.length,
  111. persistedPartCount: messages.reduce((total, message) => total + message.parts.length, 0),
  112. rehydrateMs: roundMs(rehydrateMs),
  113. rowCount: snapshot?.rows.totalCount ?? 0,
  114. subscribeMs: roundMs(subscribeMs),
  115. totalMs: roundMs(totalMs),
  116. })}\n`,
  117. );
  118. }, 120_000);
  119. },
  120. );
  121. function ticketMessages(): MessageWithParts[] {
  122. const messages: MessageWithParts[] = [];
  123. for (let turn = 0; turn < PRECOMPACT_TURN_COUNT; turn += 1) {
  124. const userId = `perf03-pre-user-${turn}`;
  125. const turnId = `perf03-pre-turn-${turn}`;
  126. const createdAt = 1_700_000_000_000 + turn * 1_000;
  127. messages.push(userMessage(userId, turnId, createdAt));
  128. const assistantId = `perf03-pre-assistant-${turn}`;
  129. messages.push(precompactAssistantMessage(assistantId, userId, turnId, createdAt + 100, turn));
  130. }
  131. const lastPrecompactTurn = PRECOMPACT_TURN_COUNT - 1;
  132. const lastPrecompactUserId = `perf03-pre-user-${lastPrecompactTurn}`;
  133. const lastSummarizedMessageId = `perf03-pre-assistant-${lastPrecompactTurn}`;
  134. messages.push(compactionBoundaryMessage(lastPrecompactUserId, lastSummarizedMessageId));
  135. for (let turn = 0; turn < ACTIVE_TURN_COUNT; turn += 1) {
  136. const userId = `perf03-active-user-${turn}`;
  137. const turnId = `perf03-active-turn-${turn}`;
  138. const createdAt = 1_700_010_000_000 + turn * 1_000;
  139. messages.push(userMessage(userId, turnId, createdAt));
  140. messages.push(activeAssistantMessage(userId, turnId, createdAt + 100, turn));
  141. }
  142. return messages;
  143. }
  144. function precompactAssistantMessage(
  145. id: string,
  146. parentId: string,
  147. turnId: string,
  148. createdAt: number,
  149. turn: number,
  150. ): MessageWithParts {
  151. const parts: MessagePart[] = [
  152. textPart(`${id}-text`, id, `ticket precompact assistant response ${turn}`, createdAt),
  153. ];
  154. if (turn < PRECOMPACT_REASONING_PART_COUNT) {
  155. parts.push({
  156. id: `${id}-reasoning` as never,
  157. sessionID: SESSION_ID as never,
  158. messageID: id as never,
  159. type: "reasoning",
  160. text: `ticket precompact reasoning ${turn}`,
  161. time: { start: createdAt + 1, end: createdAt + 2 },
  162. });
  163. }
  164. parts.push(
  165. {
  166. id: `${id}-step-start` as never,
  167. sessionID: SESSION_ID as never,
  168. messageID: id as never,
  169. type: "step-start",
  170. },
  171. completedToolPart(id, turn, "Read", 0, createdAt + 10),
  172. completedToolPart(id, turn, "Grep", 1, createdAt + 11),
  173. {
  174. id: `${id}-step-finish` as never,
  175. sessionID: SESSION_ID as never,
  176. messageID: id as never,
  177. type: "step-finish",
  178. reason: "stop",
  179. cost: 0,
  180. tokens: { input: 1, output: 1, reasoning: 1, cache: { read: 0, write: 0 } },
  181. },
  182. );
  183. return assistantMessage(id, parentId, turnId, createdAt, parts);
  184. }
  185. function userMessage(id: string, turnId: string, createdAt: number): MessageWithParts {
  186. return {
  187. info: {
  188. id: id as never,
  189. sessionID: SESSION_ID as never,
  190. role: "user",
  191. time: { created: createdAt },
  192. agent: "zcode-agent",
  193. model: { providerID: "perf-provider" as never, modelID: "perf-model" as never },
  194. anchor: { turnId: turnId as never, origin: "realUser" },
  195. },
  196. parts: [textPart(`${id}-text`, id, `ticket-shaped user prompt ${id}`, createdAt)],
  197. };
  198. }
  199. function assistantMessage(
  200. id: string,
  201. parentId: string,
  202. turnId: string,
  203. createdAt: number,
  204. parts: MessagePart[],
  205. ): MessageWithParts {
  206. const completedAt = createdAt + 500;
  207. return {
  208. info: {
  209. id: id as never,
  210. sessionID: SESSION_ID as never,
  211. role: "assistant",
  212. time: { created: createdAt, completed: completedAt },
  213. parentID: parentId as never,
  214. modelID: "perf-model" as never,
  215. providerID: "perf-provider" as never,
  216. mode: "build",
  217. agent: "zcode-agent",
  218. path: { cwd: "/perf03-e", root: "/perf03-e" },
  219. cost: 0,
  220. tokens: { input: 1, output: 1, reasoning: 1, cache: { read: 0, write: 0 } },
  221. anchor: { turnId: turnId as never },
  222. },
  223. parts,
  224. };
  225. }
  226. function activeAssistantMessage(
  227. parentId: string,
  228. turnId: string,
  229. createdAt: number,
  230. turn: number,
  231. ): MessageWithParts {
  232. const id = `perf03-active-assistant-${turn}`;
  233. const threeToolTurnCount = ACTIVE_TOOL_PART_COUNT - ACTIVE_TURN_COUNT * 2;
  234. const toolCount = turn < threeToolTurnCount ? 3 : 2;
  235. const parts: MessagePart[] = [
  236. textPart(`${id}-text`, id, `ticket active assistant response ${turn}`, createdAt),
  237. {
  238. id: `${id}-reasoning` as never,
  239. sessionID: SESSION_ID as never,
  240. messageID: id as never,
  241. type: "reasoning",
  242. text: `ticket active reasoning ${turn}`,
  243. time: { start: createdAt + 1, end: createdAt + 2 },
  244. },
  245. {
  246. id: `${id}-step-start` as never,
  247. sessionID: SESSION_ID as never,
  248. messageID: id as never,
  249. type: "step-start",
  250. },
  251. ...Array.from({ length: toolCount }, (_, toolIndex) =>
  252. completedToolPart(
  253. id,
  254. turn,
  255. TOOL_NAMES[toolIndex % TOOL_NAMES.length]!,
  256. toolIndex,
  257. createdAt + 10 + toolIndex,
  258. ),
  259. ),
  260. {
  261. id: `${id}-step-finish` as never,
  262. sessionID: SESSION_ID as never,
  263. messageID: id as never,
  264. type: "step-finish",
  265. reason: "stop",
  266. cost: 0,
  267. tokens: { input: 1, output: 1, reasoning: 1, cache: { read: 0, write: 0 } },
  268. },
  269. ];
  270. if (turn < ACTIVE_EXTRA_TEXT_PART_COUNT) {
  271. parts.push(
  272. textPart(
  273. `${id}-text-extra`,
  274. id,
  275. `ticket active assistant continuation ${turn}`,
  276. createdAt + 20,
  277. ),
  278. );
  279. }
  280. return assistantMessage(id, parentId, turnId, createdAt, parts);
  281. }
  282. function compactionBoundaryMessage(
  283. parentId: string,
  284. lastSummarizedMessageId: string,
  285. ): MessageWithParts {
  286. const id = "perf03-compact-boundary";
  287. const createdAt = 1_700_009_999_000;
  288. return assistantMessage(id, parentId, `perf03-pre-turn-${PRECOMPACT_TURN_COUNT - 1}`, createdAt, [
  289. {
  290. id: `${id}-part` as never,
  291. sessionID: SESSION_ID as never,
  292. messageID: id as never,
  293. type: "compaction",
  294. auto: true,
  295. trigger: CompactTrigger.Auto,
  296. operationId: "perf03-compact-operation",
  297. timelineStatus: CompactTimelineStatus.Completed,
  298. tail_start_id: lastSummarizedMessageId as never,
  299. compactBoundary: {
  300. boundaryId: "perf03-compact-boundary",
  301. trigger: CompactTrigger.Auto,
  302. preCompactTokenCount: 180_000,
  303. postCompactTokenCount: 42_000,
  304. summarizedMessageCount: PRECOMPACT_TURN_COUNT * 2,
  305. lastSummarizedMessageId: lastSummarizedMessageId as never,
  306. summaryMessageIds: [],
  307. traceId: "perf03-trace" as TraceId,
  308. },
  309. },
  310. ]);
  311. }
  312. function textPart(
  313. id: string,
  314. messageId: string,
  315. text: string,
  316. createdAt: number,
  317. ): Extract<MessagePart, { type: "text" }> {
  318. return {
  319. id: id as never,
  320. sessionID: SESSION_ID as never,
  321. messageID: messageId as never,
  322. type: "text",
  323. text,
  324. time: { start: createdAt, end: createdAt },
  325. };
  326. }
  327. function completedToolPart(
  328. messageId: string,
  329. turn: number,
  330. toolName: (typeof TOOL_NAMES)[number],
  331. toolIndex: number,
  332. startedAt: number,
  333. ): Extract<MessagePart, { type: "tool" }> {
  334. return {
  335. id: `${messageId}-tool-${toolIndex}` as never,
  336. sessionID: SESSION_ID as never,
  337. messageID: messageId as never,
  338. type: "tool",
  339. callID: `perf03-call-${messageId}-${turn}-${toolIndex}`,
  340. tool: toolName,
  341. state: {
  342. status: "completed",
  343. input: { path: `/perf03-e/file-${turn}-${toolIndex}.ts` },
  344. output: `ticket active ${toolName} output ${turn}/${toolIndex}`,
  345. title: toolName,
  346. time: { start: startedAt, end: startedAt + 1 },
  347. metadata: { fixture: "PERF03-E" },
  348. },
  349. };
  350. }
  351. function ticketCheckpoints(): SessionEvent[] {
  352. return Array.from({ length: CHECKPOINT_COUNT }, (_, index) => {
  353. const turn = index % (PRECOMPACT_TURN_COUNT + ACTIVE_TURN_COUNT);
  354. const inPrecompactHistory = turn < PRECOMPACT_TURN_COUNT;
  355. const localTurn = inPrecompactHistory ? turn : turn - PRECOMPACT_TURN_COUNT;
  356. const messageId = inPrecompactHistory
  357. ? `perf03-pre-user-${localTurn}`
  358. : `perf03-active-user-${localTurn}`;
  359. const turnId = inPrecompactHistory
  360. ? `perf03-pre-turn-${localTurn}`
  361. : `perf03-active-turn-${localTurn}`;
  362. return {
  363. id: `perf03-checkpoint-event-${index}` as EventId,
  364. sessionId: SESSION_ID as SessionId,
  365. turnId: turnId as TurnId,
  366. type: SessionEventType.CheckpointCreated,
  367. timestamp: new Date(1_700_001_000_000 + index),
  368. traceId: "perf03-trace" as TraceId,
  369. sequenceNumber: index + 1,
  370. payload: {
  371. checkpointId: `perf03-checkpoint-${index}`,
  372. messageId,
  373. targetMessageId: messageId,
  374. scope: "workspace",
  375. snapshotRef: `zcode-artifact://${SESSION_ID}/perf03-checkpoint-${index}`,
  376. fileCount: 1,
  377. },
  378. };
  379. });
  380. }
  381. function roundMs(value: number): number {
  382. return Math.round(value * 10) / 10;
  383. }