product-projection-atomic-transaction.test.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. // 原子事件事务的回归契约(docs/v4-refactor/02-projection.md「原子事件事务」)。
  2. //
  3. // 钉住四件事,前两条对投影的全部字段通用(新增字段自动纳入比较):
  4. // 1. 拒绝、accept 抛错、归约中途抛错、某张共享表回滚抛错时,投影的每个字段(含 Map / Set 的迭代顺序)
  5. // 与调用前完全相同。rowIdForMessageId 等按插入顺序取第一个匹配,顺序变化也是行为变化。
  6. // 2. 接受时,状态与 delta 和直接 applyEvent 完全相同。
  7. // 3. 每一步之后,十一张共享大侧表都仍是 TransactionalMap,且没有残留的事务(JSON 比较看不出这两点:
  8. // 表悄悄退回整份复制只是变慢,残留事务会让之后每个事件都失败)。
  9. // 4. 冷恢复(批量 hydration)之后的第一个原子事件同样满足以上三条。
  10. // 事件序列覆盖大侧表的新增、改写已有键(compact 覆盖边界)与删除(rewind):开轮、文本/推理/工具流、
  11. // 权限、文件改动、compact、rewind。
  12. import { afterEach, describe, expect, it, vi } from "vitest";
  13. import {
  14. SessionEventType,
  15. type EventId,
  16. type SessionEvent,
  17. type SessionEventType as SessionEventTypeUnion,
  18. type SessionId,
  19. type TraceId,
  20. type TurnId,
  21. } from "@zcode/contracts";
  22. import { ConversationTopicPublisher, ProductProjection } from "../src/zcode-protocol-v4/index.js";
  23. import { TransactionalMap } from "../src/zcode-protocol-v4/product-projection.js";
  24. const BASE_TIMESTAMP_MS = 1_700_000_000_000;
  25. const USAGE = { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 };
  26. const INJECTED_FAILURE = "injected reducer failure";
  27. const INJECTED_ROLLBACK_FAILURE = "injected rollback failure";
  28. // 与 cloneProjection 里共享的字段一一对应(docs/v4-refactor/02-projection.md「原子事件事务」)。
  29. const SHARED_SIDE_TABLES = [
  30. "rowIndexById",
  31. "toolRowIdByCallId",
  32. "messageIdByRowId",
  33. "entityIdByRowId",
  34. "editTargetByEntityId",
  35. "turnHeaderRowIdByTurnId",
  36. "productTurnIdByRuntimeTurnId",
  37. "runtimeTurnIdByProductTurnId",
  38. "subagentOutcomeByChildId",
  39. "workflowOutcomeByRunId",
  40. "workflowChildSessionIds",
  41. ] as const;
  42. class EventLog {
  43. private seq = 0;
  44. readonly events: SessionEvent[] = [];
  45. push(type: SessionEventTypeUnion, payload: unknown, turnId?: string): void {
  46. this.seq += 1;
  47. this.events.push({
  48. id: `event-${this.seq}` as EventId,
  49. sessionId: "session-1" as SessionId,
  50. turnId: turnId as TurnId | undefined,
  51. type,
  52. timestamp: new Date(BASE_TIMESTAMP_MS + this.seq * 1000),
  53. traceId: "trace-1" as TraceId,
  54. sequenceNumber: this.seq,
  55. payload,
  56. });
  57. }
  58. }
  59. function stream(log: EventLog, turnId: string, payload: Record<string, unknown>): void {
  60. log.push(SessionEventType.ModelStreaming, { delta: "", done: false, ...payload }, turnId);
  61. }
  62. function pushTextTurn(log: EventLog, turn: number, withFiles: boolean): void {
  63. const turnId = `turn-${turn}`;
  64. log.push(
  65. SessionEventType.TurnStarted,
  66. { turnNumber: turn, input: `问题 ${turn}`, messageId: `message-user-${turn}` },
  67. turnId,
  68. );
  69. stream(log, turnId, { kind: "reasoning_start", assistantMessageId: `message-assistant-${turn}` });
  70. stream(log, turnId, { kind: "reasoning_delta", delta: `思考 ${turn}` });
  71. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}` });
  72. stream(log, turnId, { kind: "text_delta", delta: `回答 ${turn}` });
  73. stream(log, turnId, { kind: "text_end" });
  74. log.push(
  75. SessionEventType.ModelComplete,
  76. {
  77. content: `回答 ${turn}`,
  78. stopReason: "end_turn",
  79. querySource: "main_turn",
  80. contextWindow: 200_000,
  81. usage: USAGE,
  82. ...(withFiles
  83. ? {
  84. fileChanges: {
  85. files: 1,
  86. additions: 2,
  87. deletions: 1,
  88. items: [{ path: `/work/${turn}.ts`, additions: 2, deletions: 1, writeCount: 1 }],
  89. },
  90. }
  91. : {}),
  92. },
  93. turnId,
  94. );
  95. log.push(
  96. SessionEventType.TurnComplete,
  97. {
  98. response: `回答 ${turn}`,
  99. tokenCount: 1,
  100. toolCallCount: 0,
  101. duration: 1,
  102. resultType: "success",
  103. },
  104. turnId,
  105. );
  106. }
  107. function pushToolTurn(log: EventLog, turn: number): void {
  108. const turnId = `turn-${turn}`;
  109. const toolCallId = `tool-write-${turn}`;
  110. log.push(
  111. SessionEventType.TurnStarted,
  112. { turnNumber: turn, input: `改文件 ${turn}`, messageId: `message-user-${turn}` },
  113. turnId,
  114. );
  115. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}` });
  116. stream(log, turnId, { kind: "text_delta", delta: "先改文件。" });
  117. stream(log, turnId, { kind: "tool_input_start", toolCallId, toolName: "Write" });
  118. stream(log, turnId, {
  119. kind: "tool_input_delta",
  120. toolCallId,
  121. delta: '{"file_path":"/work/a.ts",',
  122. });
  123. stream(log, turnId, { kind: "tool_input_delta", toolCallId, delta: '"content":"a"}' });
  124. log.push(
  125. SessionEventType.ToolCallScheduled,
  126. {
  127. toolCallId,
  128. toolName: "Write",
  129. input: { file_path: "/work/a.ts", content: "a" },
  130. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  131. },
  132. turnId,
  133. );
  134. log.push(
  135. SessionEventType.PermissionRequested,
  136. {
  137. requestId: `request-${turn}`,
  138. toolCallId,
  139. toolName: "Write",
  140. riskLevel: "medium",
  141. reason: "Write file",
  142. input: { file_path: "/work/a.ts", content: "a" },
  143. },
  144. turnId,
  145. );
  146. log.push(
  147. SessionEventType.PermissionResolved,
  148. { requestId: `request-${turn}`, toolCallId, decision: "allow" },
  149. turnId,
  150. );
  151. log.push(
  152. SessionEventType.ToolCallStarted,
  153. { toolCallId, toolName: "Write", startedAt: new Date(BASE_TIMESTAMP_MS) },
  154. turnId,
  155. );
  156. log.push(
  157. SessionEventType.ToolCallResult,
  158. { toolCallId, result: { success: true, content: "ok" }, duration: 5 },
  159. turnId,
  160. );
  161. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}-b` });
  162. stream(log, turnId, { kind: "text_delta", delta: "改好了。" });
  163. stream(log, turnId, { kind: "text_end" });
  164. log.push(
  165. SessionEventType.ModelComplete,
  166. {
  167. content: "改好了。",
  168. stopReason: "end_turn",
  169. querySource: "main_turn",
  170. contextWindow: 200_000,
  171. usage: USAGE,
  172. fileChanges: {
  173. files: 1,
  174. additions: 1,
  175. deletions: 0,
  176. items: [{ path: "/work/a.ts", additions: 1, deletions: 0, writeCount: 1 }],
  177. },
  178. },
  179. turnId,
  180. );
  181. log.push(
  182. SessionEventType.TurnComplete,
  183. { response: "改好了。", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  184. turnId,
  185. );
  186. }
  187. function sessionEvents(): SessionEvent[] {
  188. const log = new EventLog();
  189. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  190. pushTextTurn(log, 1, true);
  191. pushToolTurn(log, 2);
  192. pushTextTurn(log, 3, false);
  193. log.push(SessionEventType.CompactStarted, {
  194. operationId: "compact-1",
  195. messageId: "message-compact-1",
  196. status: "started",
  197. trigger: "manual",
  198. display: "separator",
  199. });
  200. log.push(SessionEventType.CompactCompleted, {
  201. operationId: "compact-1",
  202. messageId: "message-compact-1",
  203. status: "completed",
  204. trigger: "manual",
  205. display: "separator",
  206. preCompactTokenCount: 150,
  207. postCompactTokenCount: 50,
  208. // 覆盖边界落在第 3 轮:已登记的 edit target 被整体替换为 coveredByStableCompact(改写已有键)。
  209. tailStartMessageId: "message-user-3",
  210. });
  211. pushTextTurn(log, 4, true);
  212. // rewind 删除第 2 轮起的行,以及大侧表里这些行已有的键(含工具索引)。
  213. log.push(SessionEventType.RewindTriggered, {
  214. targetMessageId: "message-assistant-2",
  215. scope: "conversation",
  216. createdMessageId: "message-rewind-notice",
  217. });
  218. pushTextTurn(log, 5, false);
  219. return log.events;
  220. }
  221. /** 投影全部字段的结构化快照:Map / Set 按迭代顺序展开,对象保留键序。 */
  222. function stateOf(projection: ProductProjection): string {
  223. return JSON.stringify(projection, (_key, value: unknown) => {
  224. if (value instanceof Map) return { map: [...value.entries()] };
  225. if (value instanceof Set) return { set: [...value.values()] };
  226. return value;
  227. });
  228. }
  229. function injectReducerFailureOnce(): void {
  230. // 归约已写完大侧表之后才抛错,用来证明中途失败也会整体回滚。
  231. vi.spyOn(
  232. ProductProjection.prototype as unknown as { updateToolIndexesAfterDeltas: () => void },
  233. "updateToolIndexesAfterDeltas",
  234. ).mockImplementationOnce(() => {
  235. throw new Error(INJECTED_FAILURE);
  236. });
  237. }
  238. const originalRollback = TransactionalMap.prototype.rollbackTransaction;
  239. function injectRollbackFailureOnce(): void {
  240. // 第一张共享表(rowIndexById)照常回滚后再抛错:其余表必须仍被回滚、事务全部关闭。
  241. vi.spyOn(TransactionalMap.prototype, "rollbackTransaction").mockImplementationOnce(
  242. function (this: TransactionalMap<unknown, unknown>) {
  243. originalRollback.call(this);
  244. throw new Error(INJECTED_ROLLBACK_FAILURE);
  245. },
  246. );
  247. }
  248. /** 错误本身及 AggregateError 里各子错误的 message。 */
  249. function errorMessages(error: unknown): string[] {
  250. if (error instanceof AggregateError) {
  251. return [error.message, ...error.errors.flatMap((inner: unknown) => errorMessages(inner))];
  252. }
  253. return error instanceof Error ? [error.message] : [String(error)];
  254. }
  255. /** 十一张共享大侧表都是 TransactionalMap,且没有残留事务(还开着时 beginTransaction 会抛错)。 */
  256. function expectSharedSideTablesReady(projection: ProductProjection, label: string): void {
  257. const fields = projection as unknown as Record<string, unknown>;
  258. for (const name of SHARED_SIDE_TABLES) {
  259. const table = fields[name];
  260. expect(table, `${label}:${name}`).toBeInstanceOf(TransactionalMap);
  261. const map = table as TransactionalMap<unknown, unknown>;
  262. expect(() => map.beginTransaction(), `${label}:${name} 有残留事务`).not.toThrow();
  263. map.rollbackTransaction();
  264. }
  265. }
  266. /** 对一个事件依次拒绝、accept 抛错、归约抛错、回滚抛错,最后接受,并与直接 applyEvent 的参考投影比较。 */
  267. function assertAtomicEvent(
  268. projection: ProductProjection,
  269. reference: ProductProjection,
  270. event: SessionEvent,
  271. ): void {
  272. const label = `${event.sequenceNumber} ${event.type}`;
  273. const before = stateOf(projection);
  274. expect(
  275. projection.applyEventAtomically(event, () => false),
  276. label,
  277. ).toBeNull();
  278. expect(stateOf(projection), `${label} 拒绝后`).toBe(before);
  279. expectSharedSideTablesReady(projection, `${label} 拒绝后`);
  280. expect(
  281. () =>
  282. projection.applyEventAtomically(event, () => {
  283. throw new Error("accept failure");
  284. }),
  285. label,
  286. ).toThrow("accept failure");
  287. expect(stateOf(projection), `${label} accept 抛错后`).toBe(before);
  288. expectSharedSideTablesReady(projection, `${label} accept 抛错后`);
  289. injectReducerFailureOnce();
  290. expect(() => projection.applyEventAtomically(event, () => true), label).toThrow(INJECTED_FAILURE);
  291. expect(stateOf(projection), `${label} 归约抛错后`).toBe(before);
  292. expectSharedSideTablesReady(projection, `${label} 归约抛错后`);
  293. injectRollbackFailureOnce();
  294. let rollbackFailure: unknown;
  295. try {
  296. projection.applyEventAtomically(event, () => false);
  297. } catch (error) {
  298. rollbackFailure = error;
  299. }
  300. expect(errorMessages(rollbackFailure), `${label} 回滚抛错`).toContain(INJECTED_ROLLBACK_FAILURE);
  301. expect(stateOf(projection), `${label} 回滚抛错后`).toBe(before);
  302. expectSharedSideTablesReady(projection, `${label} 回滚抛错后`);
  303. const accepted = projection.applyEventAtomically(event, () => true);
  304. const direct = reference.applyEvent(event);
  305. expect(accepted, label).toEqual(direct);
  306. expect(stateOf(projection), `${label} 接受后`).toBe(stateOf(reference));
  307. expectSharedSideTablesReady(projection, `${label} 接受后`);
  308. }
  309. function hydrate(projection: ProductProjection, events: readonly SessionEvent[]): void {
  310. projection.beginHydrationReplay();
  311. for (const event of events) projection.applyHydrationEvent(event);
  312. projection.completeHydrationReplay();
  313. }
  314. describe("ProductProjection 原子事件事务", () => {
  315. afterEach(() => {
  316. vi.restoreAllMocks();
  317. });
  318. it("拒绝、accept 抛错、归约抛错、回滚抛错都不留下任何痕迹;接受时与直接 applyEvent 相同", () => {
  319. const events = sessionEvents();
  320. const projection = new ProductProjection("session-1", "epoch-1");
  321. const reference = new ProductProjection("session-1", "epoch-1");
  322. expectSharedSideTablesReady(projection, "初始");
  323. for (const event of events) assertAtomicEvent(projection, reference, event);
  324. // 序列确实走到了 compact 覆盖与 rewind:有 edit target 被改写为已覆盖,第 2、3、4 轮的行已被移除。
  325. const editTargets = (
  326. projection as unknown as {
  327. editTargetByEntityId: Map<string, { coveredByStableCompact?: boolean }>;
  328. }
  329. ).editTargetByEntityId;
  330. expect([...editTargets.values()].some((target) => target.coveredByStableCompact)).toBe(true);
  331. const turnIds = new Set(projection.getSnapshot().rows.window.map((row) => row.turnId));
  332. expect(turnIds.has("message-user-1")).toBe(true);
  333. expect(turnIds.has("message-user-2")).toBe(false);
  334. expect(turnIds.has("message-user-3")).toBe(false);
  335. expect(turnIds.has("message-user-4")).toBe(false);
  336. expect(turnIds.has("message-user-5")).toBe(true);
  337. });
  338. it("冷恢复之后的原子事件同样满足事务契约", () => {
  339. const events = sessionEvents();
  340. // 冷恢复前两轮,其余(第 3 轮起,含 compact、rewind)走 live 原子路径。
  341. const split = events.findIndex(
  342. (event) =>
  343. event.type === SessionEventType.TurnStarted &&
  344. (event.payload as { turnNumber?: number }).turnNumber === 3,
  345. );
  346. expect(split).toBeGreaterThan(0);
  347. const projection = new ProductProjection("session-1", "epoch-1");
  348. const reference = new ProductProjection("session-1", "epoch-1");
  349. hydrate(projection, events.slice(0, split));
  350. hydrate(reference, events.slice(0, split));
  351. expect(stateOf(projection)).toBe(stateOf(reference));
  352. expectSharedSideTablesReady(projection, "冷恢复完成后");
  353. for (const event of events.slice(split)) assertAtomicEvent(projection, reference, event);
  354. });
  355. });
  356. // 万级历史只作为计数种子,不制造万行 UI;锁定真实原子路径的索引访问成本。
  357. describe("Activity 完整历史事务", () => {
  358. afterEach(() => vi.restoreAllMocks());
  359. function seed(projection: ProductProjection, size: number) {
  360. projection.seedSubagents({
  361. revision: 1,
  362. childSessionIds: Array.from({ length: size }, (_, i) => `child-${i}`),
  363. running: [],
  364. ended: Array.from({ length: size }, (_, i) => ({
  365. childSessionId: `child-${i}`,
  366. subagentType: "Explore",
  367. title: "done",
  368. status: "success" as const,
  369. endedAt: 1,
  370. })),
  371. });
  372. projection.seedWorkflowActivityHistory({
  373. runs: Array.from({ length: size }, (_, i) => ({
  374. runId: `run-${i}`,
  375. status: "completed" as const,
  376. sequence: 2,
  377. })),
  378. childSessionIds: Array.from({ length: size / 2 }, (_, i) => `child-${i}`),
  379. });
  380. }
  381. function progress(
  382. sequence: number,
  383. eventType: string,
  384. payload: unknown = {},
  385. actorSessionId?: string,
  386. ): SessionEvent {
  387. return {
  388. id: `progress-${sequence}`,
  389. sessionId: "session-1",
  390. traceId: "trace-1",
  391. timestamp: new Date(BASE_TIMESTAMP_MS + sequence),
  392. sequenceNumber: sequence,
  393. type: SessionEventType.DynamicWorkflowRunProgress,
  394. payload: {
  395. runId: "run-0",
  396. sequence,
  397. eventType,
  398. payload,
  399. ...(actorSessionId ? { actorSessionId } : {}),
  400. },
  401. } as SessionEvent;
  402. }
  403. it.each(["continuous", "replayable"] as const)(
  404. "%s publisher 的文本和工具流不扫描或重写完整历史",
  405. (deliveryProfile) => {
  406. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  407. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  408. seed(projection, 10_000);
  409. publisher.seedSubagents();
  410. publisher.subscribe({ connectionId: "live", deliveryProfile });
  411. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  412. .subagentOutcomeByChildId;
  413. for (const method of [
  414. Symbol.iterator,
  415. "entries",
  416. "values",
  417. "keys",
  418. "forEach",
  419. "set",
  420. ] as const) {
  421. vi.spyOn(table, method).mockImplementation(() => {
  422. throw new Error(`无关流访问历史: ${String(method)}`);
  423. });
  424. }
  425. const log = new EventLog();
  426. pushTextTurn(log, 1, false);
  427. pushToolTurn(log, 2);
  428. for (const event of log.events.filter(
  429. (event) =>
  430. event.type !== SessionEventType.PermissionRequested &&
  431. event.type !== SessionEventType.PermissionResolved,
  432. ))
  433. publisher.ingest(event);
  434. const { frame } = publisher.subscribe({ connectionId: "reconnect", deliveryProfile });
  435. if (frame?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  436. expect(frame.payload.snapshot.completedActivityCount).toBe(15_000);
  437. expect(frame.payload.snapshot.rows.window.some((row) => row.kind === "assistantText")).toBe(
  438. true,
  439. );
  440. },
  441. );
  442. it.each(["continuous", "replayable"] as const)(
  443. "%s 预览外结果变化发布完整数量,拒绝候选不污染重连",
  444. (deliveryProfile) => {
  445. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  446. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  447. const log = new EventLog();
  448. for (let i = 0; i < 101; i++) {
  449. log.push(SessionEventType.SubagentSpawned, {
  450. agentId: `agent-${i}`,
  451. childSessionId: `child-${i}`,
  452. agentType: "Explore",
  453. description: "inspect",
  454. });
  455. log.push(SessionEventType.SubagentStopped, {
  456. agentId: `agent-${i}`,
  457. childSessionId: `child-${i}`,
  458. status: i === 0 ? "failed" : "success",
  459. summaryText: "done",
  460. });
  461. }
  462. for (const event of log.events) publisher.ingest(event);
  463. const subscription = publisher.subscribe({ connectionId: "live", deliveryProfile });
  464. expect(subscription.frame?.payload.kind).toBe("snapshot");
  465. const before = projection.getSnapshot();
  466. expect(before.completedActivityCount).toBe(100);
  467. log.push(SessionEventType.SubagentStopped, {
  468. agentId: "agent-0",
  469. childSessionId: "child-0",
  470. status: "success",
  471. summaryText: "done",
  472. });
  473. // 合法更正仍早于第二项,保证更新对象留在最近 100 条之外。
  474. const event = { ...log.events.at(-1)!, timestamp: new Date(BASE_TIMESTAMP_MS + 2500) };
  475. expect(projection.applyEventAtomically(event, () => false)).toBeNull();
  476. expect(projection.getSnapshot()).toEqual(before);
  477. expect(() =>
  478. projection.applyEventAtomically(event, () => {
  479. throw new Error("reject");
  480. }),
  481. ).toThrow("reject");
  482. expect(projection.getSnapshot()).toEqual(before);
  483. publisher.ingest(event);
  484. expect(projection.getSnapshot().subagents).toEqual(before.subagents);
  485. const frame = publisher.flush(subscription.ack.subscriptionId);
  486. if (frame?.payload.kind !== "deltas") throw new Error("expected deltas");
  487. expect(frame.payload.deltas).toContainEqual(
  488. expect.objectContaining({
  489. op: "state.updated",
  490. patch: expect.objectContaining({ completedActivityCount: 101 }),
  491. }),
  492. );
  493. const reconnect = publisher.subscribe({ connectionId: "reconnect", deliveryProfile }).frame;
  494. if (reconnect?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  495. expect(reconnect.payload.snapshot.completedActivityCount).toBe(101);
  496. },
  497. );
  498. it.each(["continuous", "replayable"] as const)(
  499. "%s 普通 Bash 生命周期不读取完整 child 历史",
  500. (deliveryProfile) => {
  501. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  502. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  503. seed(projection, 10_000);
  504. publisher.seedSubagents();
  505. const subscription = publisher.subscribe({ connectionId: "live", deliveryProfile });
  506. expect(subscription.frame?.payload.kind).toBe("snapshot");
  507. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  508. .subagentOutcomeByChildId;
  509. for (const method of [
  510. Symbol.iterator,
  511. "entries",
  512. "keys",
  513. "values",
  514. "forEach",
  515. "set",
  516. ] as const)
  517. vi.spyOn(table, method).mockImplementation(() => {
  518. throw new Error("Bash 扫描 child 历史");
  519. });
  520. const log = new EventLog();
  521. log.push(SessionEventType.BackgroundTaskStarted, {
  522. taskId: "bash",
  523. toolName: "Bash",
  524. status: "running",
  525. });
  526. log.push(SessionEventType.BackgroundTaskCompleted, {
  527. taskId: "bash",
  528. toolName: "Bash",
  529. status: "completed",
  530. });
  531. for (const event of log.events) publisher.ingest(event);
  532. const reconnect = publisher.subscribe({ connectionId: "reconnect", deliveryProfile }).frame;
  533. if (reconnect?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  534. expect(reconnect.payload.snapshot.backgroundWorks[0]?.status).toBe("resultPending");
  535. expect(reconnect.payload.snapshot.completedActivityCount).toBe(15_000);
  536. },
  537. );
  538. it("真实 child 阻塞与解除仍更新摘要,同身份其他后台任务不误解除", () => {
  539. const projection = new ProductProjection("session-1", "epoch-1");
  540. const log = new EventLog();
  541. const send = (type: SessionEventTypeUnion, payload: unknown) => {
  542. log.push(type, payload);
  543. projection.applyEventAtomically(log.events.at(-1)!, () => true);
  544. };
  545. send(SessionEventType.SubagentSpawned, {
  546. agentId: "agent",
  547. childSessionId: "child",
  548. agentType: "Explore",
  549. description: "inspect",
  550. });
  551. for (const taskId of ["a", "b"])
  552. send(SessionEventType.BackgroundTaskStarted, {
  553. taskId,
  554. toolName: "Agent",
  555. taskKind: "subagent",
  556. childSessionId: "child",
  557. status: "running",
  558. blocked: true,
  559. });
  560. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("blocked");
  561. send(SessionEventType.BackgroundTaskCompleted, {
  562. taskId: "a",
  563. toolName: "Agent",
  564. status: "completed",
  565. });
  566. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("blocked");
  567. send(SessionEventType.BackgroundTaskUpdated, {
  568. taskId: "b",
  569. toolName: "Agent",
  570. status: "running",
  571. blocked: false,
  572. });
  573. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("running");
  574. });
  575. it("一万项历史下普通节点、结算与 actor 归属变化不遍历完整索引", () => {
  576. const projection = new ProductProjection("session-1", "epoch-1");
  577. seed(projection, 10_000);
  578. expect(projection.getSnapshot().completedActivityCount).toBe(15_000);
  579. const tables = projection as unknown as Record<string, Map<unknown, unknown>>;
  580. for (const name of SHARED_SIDE_TABLES.slice(-3)) {
  581. const table = tables[name]!;
  582. for (const method of [Symbol.iterator, "entries", "values", "keys", "forEach"] as const) {
  583. vi.spyOn(table, method).mockImplementation(() => {
  584. throw new Error(`完整索引被遍历: ${name}`);
  585. });
  586. }
  587. }
  588. for (let seq = 3; seq < 1003; seq++) {
  589. projection.applyEventAtomically(
  590. progress(seq, "node-queued", { instance: { siteId: "ask", ordinal: 1 }, kind: "ask" }),
  591. () => true,
  592. );
  593. }
  594. expect(projection.getSnapshot().completedActivityCount).toBe(15_000);
  595. projection.applyEventAtomically(progress(1003, "run-started"), () => true);
  596. expect(projection.getSnapshot().completedActivityCount).toBe(14_999);
  597. projection.applyEventAtomically(
  598. progress(
  599. 1004,
  600. "node-queued",
  601. { instance: { siteId: "ask", ordinal: 1 }, kind: "ask" },
  602. "child-9999",
  603. ),
  604. () => true,
  605. );
  606. expect(projection.getSnapshot().completedActivityCount).toBe(14_998);
  607. projection.applyEventAtomically(
  608. progress(1005, "run-settled", { status: "completed" }),
  609. () => true,
  610. );
  611. expect(projection.getSnapshot().completedActivityCount).toBe(14_999);
  612. });
  613. it.each(["continuous", "replayable"] as const)(
  614. "%s 主代理审批不扫描历史,child 多审批仅按等待身份变化物化",
  615. (deliveryProfile) => {
  616. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  617. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  618. seed(projection, 10_000);
  619. publisher.seedSubagents();
  620. const log = new EventLog();
  621. log.push(SessionEventType.SubagentSpawned, {
  622. agentId: "active",
  623. childSessionId: "active",
  624. agentType: "Explore",
  625. description: "Active",
  626. });
  627. publisher.ingest(log.events.at(-1)!);
  628. const subscriber = publisher.subscribe({ connectionId: "live", deliveryProfile });
  629. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  630. .subagentOutcomeByChildId;
  631. const keys = vi.spyOn(table, "keys");
  632. const entries = vi.spyOn(table, Symbol.iterator);
  633. const request = (requestId: string, child = false) => {
  634. log.push(SessionEventType.PermissionRequested, {
  635. requestId,
  636. toolCallId: requestId,
  637. toolName: "Write",
  638. riskLevel: "medium",
  639. reason: "Write",
  640. input: {},
  641. ...(child ? { origin: { kind: "subagent", childSessionId: "active" } } : {}),
  642. });
  643. publisher.ingest(log.events.at(-1)!);
  644. };
  645. const resolve = (requestId: string) => {
  646. log.push(SessionEventType.PermissionResolved, {
  647. requestId,
  648. toolCallId: requestId,
  649. decision: "allow",
  650. });
  651. publisher.ingest(log.events.at(-1)!);
  652. };
  653. request("main");
  654. resolve("main");
  655. expect(keys).not.toHaveBeenCalled();
  656. expect(entries).not.toHaveBeenCalled();
  657. request("child-1", true);
  658. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("waiting");
  659. keys.mockClear();
  660. entries.mockClear();
  661. request("child-2", true);
  662. resolve("child-1");
  663. expect(keys).not.toHaveBeenCalled();
  664. expect(entries).not.toHaveBeenCalled();
  665. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("waiting");
  666. resolve("child-2");
  667. expect(projection.getSnapshot().subagents?.running[0]?.status).toBe("running");
  668. expect(publisher.flush(subscriber.ack.subscriptionId)?.payload.kind).toBe("deltas");
  669. const reconnect = publisher.subscribe({ connectionId: "reconnect", deliveryProfile }).frame;
  670. if (reconnect?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  671. expect(reconnect.payload.snapshot.completedActivityCount).toBe(15_000);
  672. expect(reconnect.payload.snapshot.subagents?.running[0]?.status).toBe("running");
  673. },
  674. );
  675. it("相关权限状态要求重建摘要时不重写未变化的 child outcome", () => {
  676. const projection = new ProductProjection("session-1", "epoch-1");
  677. const log = new EventLog();
  678. for (let i = 0; i < 4; i++) {
  679. log.push(SessionEventType.SubagentSpawned, {
  680. agentId: `agent-${i}`,
  681. childSessionId: `child-${i}`,
  682. agentType: "Explore",
  683. description: "Inspect",
  684. });
  685. log.push(SessionEventType.SubagentStopped, {
  686. agentId: `agent-${i}`,
  687. childSessionId: `child-${i}`,
  688. status: "success",
  689. summaryText: "done",
  690. });
  691. }
  692. for (const event of log.events) projection.applyEvent(event);
  693. expect(projection.getSnapshot().completedActivityCount).toBe(4);
  694. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  695. .subagentOutcomeByChildId;
  696. const write = vi.spyOn(table, "set");
  697. log.push(SessionEventType.PermissionRequested, {
  698. requestId: "request",
  699. toolCallId: "write",
  700. toolName: "Write",
  701. riskLevel: "medium",
  702. reason: "Write file",
  703. input: {},
  704. });
  705. projection.applyEventAtomically(log.events.at(-1)!, () => true);
  706. expect(write).not.toHaveBeenCalled();
  707. expect(projection.getSnapshot().completedActivityCount).toBe(4);
  708. });
  709. it.each(["continuous", "replayable"] as const)(
  710. "%s 万级 child 成功→恢复→结算只点更新,拒绝和异常不污染状态",
  711. (deliveryProfile) => {
  712. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  713. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  714. seed(projection, 10_000);
  715. publisher.seedSubagents();
  716. const subscriber = publisher.subscribe({ connectionId: "live", deliveryProfile });
  717. expect(subscriber.frame?.payload.kind).toBe("snapshot");
  718. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  719. .subagentOutcomeByChildId;
  720. const iterate = table[Symbol.iterator];
  721. let copiedEntries = 0;
  722. vi.spyOn(table, Symbol.iterator).mockImplementation(function* () {
  723. for (const entry of iterate.call(table)) {
  724. copiedEntries++;
  725. yield entry;
  726. }
  727. });
  728. const log = new EventLog();
  729. log.push(SessionEventType.SubagentSpawned, {
  730. agentId: "agent-9999",
  731. childSessionId: "child-9999",
  732. agentType: "Explore",
  733. description: "Resume",
  734. });
  735. log.push(SessionEventType.SubagentStopped, {
  736. agentId: "agent-9999",
  737. childSessionId: "child-9999",
  738. status: "success",
  739. summaryText: "done",
  740. });
  741. for (const [index, event] of log.events.entries()) {
  742. const before = stateOf(projection);
  743. copiedEntries = 0;
  744. expect(projection.applyEventAtomically(event, () => false)).toBeNull();
  745. expect(copiedEntries).toBe(0);
  746. expect(stateOf(projection)).toBe(before);
  747. copiedEntries = 0;
  748. expect(() =>
  749. projection.applyEventAtomically(event, () => {
  750. throw new Error(INJECTED_FAILURE);
  751. }),
  752. ).toThrow(INJECTED_FAILURE);
  753. expect(copiedEntries).toBe(0);
  754. expect(stateOf(projection)).toBe(before);
  755. copiedEntries = 0;
  756. publisher.ingest(event);
  757. expect(copiedEntries).toBe(0);
  758. const expectedCount = index === 0 ? 14_999 : 15_000;
  759. const frame = publisher.flush(subscriber.ack.subscriptionId);
  760. if (frame?.payload.kind !== "deltas") throw new Error("expected deltas");
  761. expect(frame.payload.deltas).toContainEqual(
  762. expect.objectContaining({
  763. op: "state.updated",
  764. patch: expect.objectContaining({ completedActivityCount: expectedCount }),
  765. }),
  766. );
  767. const reconnect = publisher.subscribe({
  768. connectionId: `reconnect-${index}`,
  769. deliveryProfile,
  770. }).frame;
  771. if (reconnect?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  772. expect(reconnect.payload.snapshot.completedActivityCount).toBe(expectedCount);
  773. expect(table.get("child-9999")).toMatchObject({
  774. status: index === 0 ? "running" : "success",
  775. });
  776. }
  777. },
  778. );
  779. it.each(["continuous", "replayable"] as const)(
  780. "%s 回退只撤销当前分支后缀,保留无行旧 child 与多来源身份",
  781. (deliveryProfile) => {
  782. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  783. const projection = (publisher as unknown as { projection: ProductProjection }).projection;
  784. const log = new EventLog();
  785. log.push(
  786. SessionEventType.TurnStarted,
  787. { turnNumber: 1, input: "old", messageId: "old-user" },
  788. "old-turn",
  789. );
  790. publisher.ingest(log.events.at(-1)!);
  791. const childSessionIds = ["old-seed", "new-seed", "shared-seed"];
  792. publisher.seedSubagents({
  793. revision: 1,
  794. childSessionIds,
  795. running: [],
  796. ended: childSessionIds.map((childSessionId) => ({
  797. childSessionId,
  798. status: "success",
  799. title: childSessionId,
  800. subagentType: "Explore",
  801. endedAt: 1,
  802. })),
  803. parentMessageIdsByChildId: {
  804. "old-seed": ["old-message"],
  805. "new-seed": ["new-message"],
  806. "shared-seed": ["old-message", "new-message"],
  807. },
  808. });
  809. log.push(
  810. SessionEventType.TurnStarted,
  811. { turnNumber: 2, input: "new", messageId: "new-user" },
  812. "new-turn",
  813. );
  814. log.push(
  815. SessionEventType.SubagentSpawned,
  816. {
  817. agentId: "new-live",
  818. childSessionId: "new-live",
  819. agentType: "Explore",
  820. description: "New",
  821. },
  822. "new-turn",
  823. );
  824. log.push(
  825. SessionEventType.SubagentStopped,
  826. { agentId: "new-live", childSessionId: "new-live", status: "success", summaryText: "done" },
  827. "new-turn",
  828. );
  829. for (const event of log.events.slice(1)) publisher.ingest(event);
  830. const subscriber = publisher.subscribe({ connectionId: "live", deliveryProfile });
  831. expect(projection.getSnapshot().completedActivityCount).toBe(4);
  832. log.push(SessionEventType.RewindTriggered, {
  833. targetMessageId: "new-user",
  834. scope: "conversation",
  835. branchGeneration: 1,
  836. branchCutAfterMessageId: "new-message",
  837. removedMessageIds: ["new-user", "new-message"],
  838. });
  839. const rewind = log.events.at(-1)!;
  840. const before = stateOf(projection);
  841. expect(projection.applyEventAtomically(rewind, () => false)).toBeNull();
  842. expect(stateOf(projection)).toBe(before);
  843. expect(() =>
  844. projection.applyEventAtomically(rewind, () => {
  845. throw new Error(INJECTED_FAILURE);
  846. }),
  847. ).toThrow(INJECTED_FAILURE);
  848. expect(stateOf(projection)).toBe(before);
  849. publisher.ingest(rewind);
  850. expect([...(projection.getSnapshot().subagents?.childSessionIds ?? [])].sort()).toEqual([
  851. "old-seed",
  852. "shared-seed",
  853. ]);
  854. const frame = publisher.flush(subscriber.ack.subscriptionId);
  855. if (frame?.payload.kind !== "deltas") throw new Error("expected deltas");
  856. expect(frame.payload.deltas).toContainEqual(
  857. expect.objectContaining({
  858. op: "state.updated",
  859. patch: expect.objectContaining({ completedActivityCount: 2 }),
  860. }),
  861. );
  862. const reconnect = publisher.subscribe({ connectionId: "reconnect", deliveryProfile }).frame;
  863. if (reconnect?.payload.kind !== "snapshot") throw new Error("expected snapshot");
  864. expect(reconnect.payload.snapshot.completedActivityCount).toBe(2);
  865. const cold = new ProductProjection("session-1", "cold");
  866. cold.seedSubagents({
  867. revision: 1,
  868. childSessionIds: ["old-seed", "shared-seed"],
  869. running: [],
  870. ended: ["old-seed", "shared-seed"].map((childSessionId) => ({
  871. childSessionId,
  872. status: "success",
  873. title: childSessionId,
  874. subagentType: "Explore",
  875. endedAt: 1,
  876. })),
  877. parentMessageIdsByChildId: { "old-seed": ["old-message"], "shared-seed": ["old-message"] },
  878. });
  879. expect(projection.getSnapshot().completedActivityCount).toBe(
  880. cold.getSnapshot().completedActivityCount,
  881. );
  882. log.push(SessionEventType.RewindTriggered, {
  883. targetMessageId: "old-user",
  884. scope: "conversation",
  885. branchGeneration: 2,
  886. branchCutAfterMessageId: "new-message",
  887. removedMessageIds: ["old-user", "old-message"],
  888. });
  889. publisher.ingest(log.events.at(-1)!);
  890. expect(projection.getSnapshot().completedActivityCount).toBe(0);
  891. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([]);
  892. },
  893. );
  894. it.each(["running", "success"] as const)(
  895. "真实回退仍清除 %s child 身份,拒绝回退保留索引",
  896. (status) => {
  897. const projection = new ProductProjection("session-1", "epoch-1");
  898. const log = new EventLog();
  899. log.push(
  900. SessionEventType.TurnStarted,
  901. { turnNumber: 1, input: "inspect", messageId: "user" },
  902. "turn",
  903. );
  904. const spawn = {
  905. agentId: "agent",
  906. childSessionId: "child",
  907. agentType: "Explore",
  908. description: "Inspect",
  909. };
  910. const stop = {
  911. agentId: "agent",
  912. childSessionId: "child",
  913. status: "success",
  914. summaryText: "done",
  915. };
  916. log.push(SessionEventType.SubagentSpawned, spawn, "turn");
  917. log.push(SessionEventType.SubagentStopped, stop, "turn");
  918. log.push(SessionEventType.SubagentSpawned, spawn, "turn");
  919. if (status === "success") log.push(SessionEventType.SubagentStopped, stop, "turn");
  920. for (const event of log.events) projection.applyEventAtomically(event, () => true);
  921. const table = (projection as unknown as { subagentOutcomeByChildId: Map<string, unknown> })
  922. .subagentOutcomeByChildId;
  923. expect(table.get("child")).toMatchObject({ status });
  924. const before = stateOf(projection);
  925. log.push(SessionEventType.RewindTriggered, {
  926. targetMessageId: "user",
  927. scope: "conversation",
  928. branchGeneration: 1,
  929. branchCutAfterMessageId: "user",
  930. });
  931. expect(projection.applyEventAtomically(log.events.at(-1)!, () => false)).toBeNull();
  932. expect(stateOf(projection)).toBe(before);
  933. projection.applyEventAtomically(log.events.at(-1)!, () => true);
  934. expect(table.size).toBe(0);
  935. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([]);
  936. expect(projection.getSnapshot().completedActivityCount).toBe(0);
  937. },
  938. );
  939. it("恢复、actor 去重、重复和旧事件的拒绝与异常不污染索引、水位和计数", () => {
  940. const projection = new ProductProjection("session-1", "epoch-1");
  941. const reference = new ProductProjection("session-1", "epoch-1");
  942. seed(projection, 4);
  943. seed(reference, 4);
  944. for (const event of [
  945. progress(3, "run-started"),
  946. progress(
  947. 4,
  948. "node-queued",
  949. { instance: { siteId: "ask", ordinal: 1 }, kind: "ask" },
  950. "child-3",
  951. ),
  952. progress(5, "run-settled", { status: "completed" }),
  953. progress(5, "run-settled", { status: "completed" }),
  954. progress(2, "run-started"),
  955. ])
  956. assertAtomicEvent(projection, reference, event);
  957. const childLog = new EventLog();
  958. childLog.push(SessionEventType.SubagentSpawned, {
  959. agentId: "agent-2",
  960. childSessionId: "child-2",
  961. agentType: "Explore",
  962. description: "Resume",
  963. });
  964. childLog.push(SessionEventType.SubagentStopped, {
  965. agentId: "agent-2",
  966. childSessionId: "child-2",
  967. status: "success",
  968. summaryText: "done",
  969. });
  970. for (const event of childLog.events) assertAtomicEvent(projection, reference, event);
  971. expect(projection.getSnapshot().completedActivityCount).toBe(5);
  972. });
  973. });