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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 { 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. ] as const;
  39. class EventLog {
  40. private seq = 0;
  41. readonly events: SessionEvent[] = [];
  42. push(type: SessionEventTypeUnion, payload: unknown, turnId?: string): void {
  43. this.seq += 1;
  44. this.events.push({
  45. id: `event-${this.seq}` as EventId,
  46. sessionId: "session-1" as SessionId,
  47. turnId: turnId as TurnId | undefined,
  48. type,
  49. timestamp: new Date(BASE_TIMESTAMP_MS + this.seq * 1000),
  50. traceId: "trace-1" as TraceId,
  51. sequenceNumber: this.seq,
  52. payload,
  53. });
  54. }
  55. }
  56. function stream(log: EventLog, turnId: string, payload: Record<string, unknown>): void {
  57. log.push(SessionEventType.ModelStreaming, { delta: "", done: false, ...payload }, turnId);
  58. }
  59. function pushTextTurn(log: EventLog, turn: number, withFiles: boolean): void {
  60. const turnId = `turn-${turn}`;
  61. log.push(
  62. SessionEventType.TurnStarted,
  63. { turnNumber: turn, input: `问题 ${turn}`, messageId: `message-user-${turn}` },
  64. turnId,
  65. );
  66. stream(log, turnId, { kind: "reasoning_start", assistantMessageId: `message-assistant-${turn}` });
  67. stream(log, turnId, { kind: "reasoning_delta", delta: `思考 ${turn}` });
  68. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}` });
  69. stream(log, turnId, { kind: "text_delta", delta: `回答 ${turn}` });
  70. stream(log, turnId, { kind: "text_end" });
  71. log.push(
  72. SessionEventType.ModelComplete,
  73. {
  74. content: `回答 ${turn}`,
  75. stopReason: "end_turn",
  76. querySource: "main_turn",
  77. contextWindow: 200_000,
  78. usage: USAGE,
  79. ...(withFiles
  80. ? {
  81. fileChanges: {
  82. files: 1,
  83. additions: 2,
  84. deletions: 1,
  85. items: [{ path: `/work/${turn}.ts`, additions: 2, deletions: 1, writeCount: 1 }],
  86. },
  87. }
  88. : {}),
  89. },
  90. turnId,
  91. );
  92. log.push(
  93. SessionEventType.TurnComplete,
  94. {
  95. response: `回答 ${turn}`,
  96. tokenCount: 1,
  97. toolCallCount: 0,
  98. duration: 1,
  99. resultType: "success",
  100. },
  101. turnId,
  102. );
  103. }
  104. function pushToolTurn(log: EventLog, turn: number): void {
  105. const turnId = `turn-${turn}`;
  106. const toolCallId = `tool-write-${turn}`;
  107. log.push(
  108. SessionEventType.TurnStarted,
  109. { turnNumber: turn, input: `改文件 ${turn}`, messageId: `message-user-${turn}` },
  110. turnId,
  111. );
  112. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}` });
  113. stream(log, turnId, { kind: "text_delta", delta: "先改文件。" });
  114. stream(log, turnId, { kind: "tool_input_start", toolCallId, toolName: "Write" });
  115. stream(log, turnId, {
  116. kind: "tool_input_delta",
  117. toolCallId,
  118. delta: '{"file_path":"/work/a.ts",',
  119. });
  120. stream(log, turnId, { kind: "tool_input_delta", toolCallId, delta: '"content":"a"}' });
  121. log.push(
  122. SessionEventType.ToolCallScheduled,
  123. {
  124. toolCallId,
  125. toolName: "Write",
  126. input: { file_path: "/work/a.ts", content: "a" },
  127. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  128. },
  129. turnId,
  130. );
  131. log.push(
  132. SessionEventType.PermissionRequested,
  133. {
  134. requestId: `request-${turn}`,
  135. toolCallId,
  136. toolName: "Write",
  137. riskLevel: "medium",
  138. reason: "Write file",
  139. input: { file_path: "/work/a.ts", content: "a" },
  140. },
  141. turnId,
  142. );
  143. log.push(
  144. SessionEventType.PermissionResolved,
  145. { requestId: `request-${turn}`, toolCallId, decision: "allow" },
  146. turnId,
  147. );
  148. log.push(
  149. SessionEventType.ToolCallStarted,
  150. { toolCallId, toolName: "Write", startedAt: new Date(BASE_TIMESTAMP_MS) },
  151. turnId,
  152. );
  153. log.push(
  154. SessionEventType.ToolCallResult,
  155. { toolCallId, result: { success: true, content: "ok" }, duration: 5 },
  156. turnId,
  157. );
  158. stream(log, turnId, { kind: "text_start", assistantMessageId: `message-assistant-${turn}-b` });
  159. stream(log, turnId, { kind: "text_delta", delta: "改好了。" });
  160. stream(log, turnId, { kind: "text_end" });
  161. log.push(
  162. SessionEventType.ModelComplete,
  163. {
  164. content: "改好了。",
  165. stopReason: "end_turn",
  166. querySource: "main_turn",
  167. contextWindow: 200_000,
  168. usage: USAGE,
  169. fileChanges: {
  170. files: 1,
  171. additions: 1,
  172. deletions: 0,
  173. items: [{ path: "/work/a.ts", additions: 1, deletions: 0, writeCount: 1 }],
  174. },
  175. },
  176. turnId,
  177. );
  178. log.push(
  179. SessionEventType.TurnComplete,
  180. { response: "改好了。", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  181. turnId,
  182. );
  183. }
  184. function sessionEvents(): SessionEvent[] {
  185. const log = new EventLog();
  186. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  187. pushTextTurn(log, 1, true);
  188. pushToolTurn(log, 2);
  189. pushTextTurn(log, 3, false);
  190. log.push(SessionEventType.CompactStarted, {
  191. operationId: "compact-1",
  192. messageId: "message-compact-1",
  193. status: "started",
  194. trigger: "manual",
  195. display: "separator",
  196. });
  197. log.push(SessionEventType.CompactCompleted, {
  198. operationId: "compact-1",
  199. messageId: "message-compact-1",
  200. status: "completed",
  201. trigger: "manual",
  202. display: "separator",
  203. preCompactTokenCount: 150,
  204. postCompactTokenCount: 50,
  205. // 覆盖边界落在第 3 轮:已登记的 edit target 被整体替换为 coveredByStableCompact(改写已有键)。
  206. tailStartMessageId: "message-user-3",
  207. });
  208. pushTextTurn(log, 4, true);
  209. // rewind 删除第 2 轮起的行,以及大侧表里这些行已有的键(含工具索引)。
  210. log.push(SessionEventType.RewindTriggered, {
  211. targetMessageId: "message-assistant-2",
  212. scope: "conversation",
  213. createdMessageId: "message-rewind-notice",
  214. });
  215. pushTextTurn(log, 5, false);
  216. return log.events;
  217. }
  218. /** 投影全部字段的结构化快照:Map / Set 按迭代顺序展开,对象保留键序。 */
  219. function stateOf(projection: ProductProjection): string {
  220. return JSON.stringify(projection, (_key, value: unknown) => {
  221. if (value instanceof Map) return { map: [...value.entries()] };
  222. if (value instanceof Set) return { set: [...value.values()] };
  223. return value;
  224. });
  225. }
  226. function injectReducerFailureOnce(): void {
  227. // 归约已写完大侧表之后才抛错,用来证明中途失败也会整体回滚。
  228. vi.spyOn(
  229. ProductProjection.prototype as unknown as { updateToolIndexesAfterDeltas: () => void },
  230. "updateToolIndexesAfterDeltas",
  231. ).mockImplementationOnce(() => {
  232. throw new Error(INJECTED_FAILURE);
  233. });
  234. }
  235. const originalRollback = TransactionalMap.prototype.rollbackTransaction;
  236. function injectRollbackFailureOnce(): void {
  237. // 第一张共享表(rowIndexById)照常回滚后再抛错:其余表必须仍被回滚、事务全部关闭。
  238. vi.spyOn(TransactionalMap.prototype, "rollbackTransaction").mockImplementationOnce(
  239. function (this: TransactionalMap<unknown, unknown>) {
  240. originalRollback.call(this);
  241. throw new Error(INJECTED_ROLLBACK_FAILURE);
  242. },
  243. );
  244. }
  245. /** 错误本身及 AggregateError 里各子错误的 message。 */
  246. function errorMessages(error: unknown): string[] {
  247. if (error instanceof AggregateError) {
  248. return [error.message, ...error.errors.flatMap((inner: unknown) => errorMessages(inner))];
  249. }
  250. return error instanceof Error ? [error.message] : [String(error)];
  251. }
  252. /** 八张共享大侧表都是 TransactionalMap,且没有残留事务(还开着时 beginTransaction 会抛错)。 */
  253. function expectSharedSideTablesReady(projection: ProductProjection, label: string): void {
  254. const fields = projection as unknown as Record<string, unknown>;
  255. for (const name of SHARED_SIDE_TABLES) {
  256. const table = fields[name];
  257. expect(table, `${label}:${name}`).toBeInstanceOf(TransactionalMap);
  258. const map = table as TransactionalMap<unknown, unknown>;
  259. expect(() => map.beginTransaction(), `${label}:${name} 有残留事务`).not.toThrow();
  260. map.rollbackTransaction();
  261. }
  262. }
  263. /** 对一个事件依次拒绝、accept 抛错、归约抛错、回滚抛错,最后接受,并与直接 applyEvent 的参考投影比较。 */
  264. function assertAtomicEvent(
  265. projection: ProductProjection,
  266. reference: ProductProjection,
  267. event: SessionEvent,
  268. ): void {
  269. const label = `${event.sequenceNumber} ${event.type}`;
  270. const before = stateOf(projection);
  271. expect(
  272. projection.applyEventAtomically(event, () => false),
  273. label,
  274. ).toBeNull();
  275. expect(stateOf(projection), `${label} 拒绝后`).toBe(before);
  276. expectSharedSideTablesReady(projection, `${label} 拒绝后`);
  277. expect(
  278. () =>
  279. projection.applyEventAtomically(event, () => {
  280. throw new Error("accept failure");
  281. }),
  282. label,
  283. ).toThrow("accept failure");
  284. expect(stateOf(projection), `${label} accept 抛错后`).toBe(before);
  285. expectSharedSideTablesReady(projection, `${label} accept 抛错后`);
  286. injectReducerFailureOnce();
  287. expect(() => projection.applyEventAtomically(event, () => true), label).toThrow(INJECTED_FAILURE);
  288. expect(stateOf(projection), `${label} 归约抛错后`).toBe(before);
  289. expectSharedSideTablesReady(projection, `${label} 归约抛错后`);
  290. injectRollbackFailureOnce();
  291. let rollbackFailure: unknown;
  292. try {
  293. projection.applyEventAtomically(event, () => false);
  294. } catch (error) {
  295. rollbackFailure = error;
  296. }
  297. expect(errorMessages(rollbackFailure), `${label} 回滚抛错`).toContain(INJECTED_ROLLBACK_FAILURE);
  298. expect(stateOf(projection), `${label} 回滚抛错后`).toBe(before);
  299. expectSharedSideTablesReady(projection, `${label} 回滚抛错后`);
  300. const accepted = projection.applyEventAtomically(event, () => true);
  301. const direct = reference.applyEvent(event);
  302. expect(accepted, label).toEqual(direct);
  303. expect(stateOf(projection), `${label} 接受后`).toBe(stateOf(reference));
  304. expectSharedSideTablesReady(projection, `${label} 接受后`);
  305. }
  306. function hydrate(projection: ProductProjection, events: readonly SessionEvent[]): void {
  307. projection.beginHydrationReplay();
  308. for (const event of events) projection.applyHydrationEvent(event);
  309. projection.completeHydrationReplay();
  310. }
  311. describe("ProductProjection 原子事件事务", () => {
  312. afterEach(() => {
  313. vi.restoreAllMocks();
  314. });
  315. it("拒绝、accept 抛错、归约抛错、回滚抛错都不留下任何痕迹;接受时与直接 applyEvent 相同", () => {
  316. const events = sessionEvents();
  317. const projection = new ProductProjection("session-1", "epoch-1");
  318. const reference = new ProductProjection("session-1", "epoch-1");
  319. expectSharedSideTablesReady(projection, "初始");
  320. for (const event of events) assertAtomicEvent(projection, reference, event);
  321. // 序列确实走到了 compact 覆盖与 rewind:有 edit target 被改写为已覆盖,第 2、3、4 轮的行已被移除。
  322. const editTargets = (
  323. projection as unknown as {
  324. editTargetByEntityId: Map<string, { coveredByStableCompact?: boolean }>;
  325. }
  326. ).editTargetByEntityId;
  327. expect([...editTargets.values()].some((target) => target.coveredByStableCompact)).toBe(true);
  328. const turnIds = new Set(projection.getSnapshot().rows.window.map((row) => row.turnId));
  329. expect(turnIds.has("message-user-1")).toBe(true);
  330. expect(turnIds.has("message-user-2")).toBe(false);
  331. expect(turnIds.has("message-user-3")).toBe(false);
  332. expect(turnIds.has("message-user-4")).toBe(false);
  333. expect(turnIds.has("message-user-5")).toBe(true);
  334. });
  335. it("冷恢复之后的原子事件同样满足事务契约", () => {
  336. const events = sessionEvents();
  337. // 冷恢复前两轮,其余(第 3 轮起,含 compact、rewind)走 live 原子路径。
  338. const split = events.findIndex(
  339. (event) =>
  340. event.type === SessionEventType.TurnStarted &&
  341. (event.payload as { turnNumber?: number }).turnNumber === 3,
  342. );
  343. expect(split).toBeGreaterThan(0);
  344. const projection = new ProductProjection("session-1", "epoch-1");
  345. const reference = new ProductProjection("session-1", "epoch-1");
  346. hydrate(projection, events.slice(0, split));
  347. hydrate(reference, events.slice(0, split));
  348. expect(stateOf(projection)).toBe(stateOf(reference));
  349. expectSharedSideTablesReady(projection, "冷恢复完成后");
  350. for (const event of events.slice(split)) assertAtomicEvent(projection, reference, event);
  351. });
  352. });