product-projection-streaming-actions.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // 流式追加不重算命令 actions(docs/v4-refactor/02-projection.md「命令 actions 的物化时机」)。
  2. //
  3. // 钉住两件事:
  4. // 1. 哪些事件跳过 materializeCommandRowActions:对已打开流式行的追加,且本事件归约结果只有
  5. // row.delta 或为空;附带其他增量(如清除 apiRetry 的 state.updated)的追加照常物化。
  6. // 由“是否调用物化”的逐事件断言锁定。
  7. // 2. 跳过不改变输出:与每个事件都物化的参考投影逐事件比较 delta、snapshot 与 edit target。
  8. // 它能抓到“只产 row.delta 却改写侧表”而让 canEdit 或历史轮 canFork 变化的回归;运行中的
  9. // 轮次里 canRetry、canRewindFiles 和本轮 canFork 本来就关闭,判据宽窄由第 1 条锁定。
  10. import { describe, expect, it, vi } from "vitest";
  11. import {
  12. SessionEventType,
  13. type EventId,
  14. type SessionEvent,
  15. type SessionEventType as SessionEventTypeUnion,
  16. type SessionId,
  17. type TraceId,
  18. type TurnId,
  19. } from "@zcode/contracts";
  20. import type { ConversationDelta, ConversationSnapshot } from "@zcode/shared/zcode-protocol-v4";
  21. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  22. const BASE_TIMESTAMP_MS = 1_700_000_000_000;
  23. const USAGE = { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 };
  24. const HISTORY_TURNS = 3;
  25. const LIVE_TURN_ID = "turn-live";
  26. const ACTION_KEYS = ["canEdit", "canRetry", "canFork", "canRewindFiles"];
  27. const STREAMING_APPEND_KINDS = ["reasoning_delta", "text_delta", "tool_input_delta"];
  28. /** 归约结果为空的追加的成因:工具输入已定稿后迟到,或文件工具预览被节流。 */
  29. type EmptyAppendReason = "finalized" | "throttled";
  30. const EMPTY_APPEND_REASONS: EmptyAppendReason[] = ["finalized", "throttled"];
  31. class EventLog {
  32. private seq = 0;
  33. readonly events: SessionEvent[] = [];
  34. push(
  35. type: SessionEventTypeUnion,
  36. payload: unknown,
  37. opts: { turnId?: string; timestampMs?: number } = {},
  38. ): SessionEvent {
  39. this.seq += 1;
  40. const event: SessionEvent = {
  41. id: `event-${this.seq}` as EventId,
  42. sessionId: "session-1" as SessionId,
  43. turnId: opts.turnId as TurnId | undefined,
  44. type,
  45. timestamp: new Date(opts.timestampMs ?? BASE_TIMESTAMP_MS + this.seq * 1000),
  46. traceId: "trace-1" as TraceId,
  47. sequenceNumber: this.seq,
  48. payload,
  49. };
  50. this.events.push(event);
  51. return event;
  52. }
  53. }
  54. /** 测试只通过这两个私有方法观察与控制物化;不依赖其他内部状态。 */
  55. type ActionMaterialization = {
  56. materializeCommandRowActions: (...args: unknown[]) => unknown;
  57. shouldMaterializeCommandRowActions: (...args: unknown[]) => boolean;
  58. };
  59. function internals(projection: ProductProjection): ActionMaterialization {
  60. return projection as unknown as ActionMaterialization;
  61. }
  62. function userMessageId(turn: number | string): string {
  63. return `message-user-${turn}`;
  64. }
  65. /**
  66. * 逐事件比较跳过物化的投影与总是物化的参考投影,并断言只有 skipped 中的事件不调用物化。
  67. * 返回被测投影每个事件后的 delta 与 snapshot,以及出现过的 action 键,供用例补充断言。
  68. */
  69. function replayAgainstReference(
  70. events: readonly SessionEvent[],
  71. skipped: ReadonlySet<string>,
  72. userEntityIds: readonly string[],
  73. ): {
  74. deltasByEventId: Map<string, ConversationDelta[]>;
  75. snapshotByEventId: Map<string, ConversationSnapshot>;
  76. seenActions: Set<string>;
  77. } {
  78. const subject = new ProductProjection("session-1", "epoch-1");
  79. const reference = new ProductProjection("session-1", "epoch-1");
  80. vi.spyOn(internals(reference), "shouldMaterializeCommandRowActions").mockReturnValue(true);
  81. const materialize = vi.spyOn(internals(subject), "materializeCommandRowActions");
  82. const deltasByEventId = new Map<string, ConversationDelta[]>();
  83. const snapshotByEventId = new Map<string, ConversationSnapshot>();
  84. const seenActions = new Set<string>();
  85. for (const event of events) {
  86. const callsBefore = materialize.mock.calls.length;
  87. const deltas = subject.applyEvent(event);
  88. deltasByEventId.set(event.id, deltas);
  89. snapshotByEventId.set(event.id, subject.getSnapshot());
  90. expect(deltas, event.id).toEqual(reference.applyEvent(event));
  91. expect(subject.getSnapshot(), event.id).toEqual(reference.getSnapshot());
  92. for (const entityId of userEntityIds) {
  93. expect(subject.resolveEditTargetByEntityId(entityId), `${event.id} ${entityId}`).toEqual(
  94. reference.resolveEditTargetByEntityId(entityId),
  95. );
  96. }
  97. const materialized = materialize.mock.calls.length > callsBefore;
  98. expect(materialized, event.id).toBe(!skipped.has(event.id));
  99. for (const row of subject.getSnapshot().rows.window) {
  100. for (const key of Object.keys(row.actions ?? {})) seenActions.add(key);
  101. }
  102. }
  103. return { deltasByEventId, snapshotByEventId, seenActions };
  104. }
  105. /** 已完成的历史轮:真实用户输入、带 messageId 的正文、文件改动,使四种 actions 都有输入。 */
  106. function pushHistoryTurn(log: EventLog, turn: number, skipped: Set<string>): void {
  107. const turnId = `turn-${turn}`;
  108. log.push(
  109. SessionEventType.TurnStarted,
  110. { turnNumber: turn, input: `问题 ${turn}`, messageId: userMessageId(turn) },
  111. { turnId },
  112. );
  113. log.push(
  114. SessionEventType.ModelStreaming,
  115. { kind: "text_start", delta: "", done: false, assistantMessageId: `message-assistant-${turn}` },
  116. { turnId },
  117. );
  118. const textDelta = log.push(
  119. SessionEventType.ModelStreaming,
  120. { kind: "text_delta", delta: `回答 ${turn}`, done: false },
  121. { turnId },
  122. );
  123. skipped.add(textDelta.id);
  124. log.push(
  125. SessionEventType.ModelStreaming,
  126. { kind: "text_end", delta: "", done: false },
  127. { turnId },
  128. );
  129. log.push(
  130. SessionEventType.ModelComplete,
  131. {
  132. content: `回答 ${turn}`,
  133. stopReason: "stop",
  134. querySource: "main_turn",
  135. contextWindow: 200_000,
  136. usage: USAGE,
  137. fileChanges: {
  138. files: 1,
  139. additions: 2,
  140. deletions: 1,
  141. items: [{ path: `/work/${turn}.ts`, additions: 2, deletions: 1, writeCount: 1 }],
  142. },
  143. },
  144. { turnId },
  145. );
  146. log.push(
  147. SessionEventType.TurnComplete,
  148. {
  149. response: `回答 ${turn}`,
  150. tokenCount: 2,
  151. toolCallCount: 0,
  152. duration: 1,
  153. resultType: "success",
  154. },
  155. { turnId },
  156. );
  157. }
  158. /**
  159. * 运行中的一轮:reasoning、正文、普通工具与文件工具的流式输入,夹着各种边界事件。
  160. * 应跳过物化的事件记入 skipped;其中归约结果为空的再按成因记入 emptyAppends。
  161. */
  162. function pushLiveTurn(
  163. log: EventLog,
  164. skipped: Set<string>,
  165. emptyAppends: Map<string, EmptyAppendReason>,
  166. ): void {
  167. const turnId = LIVE_TURN_ID;
  168. const stream = (payload: Record<string, unknown>, timestampMs?: number) =>
  169. log.push(
  170. SessionEventType.ModelStreaming,
  171. { delta: "", done: false, ...payload },
  172. { turnId, timestampMs },
  173. );
  174. const skip = (payload: Record<string, unknown>, timestampMs?: number) => {
  175. const event = stream(payload, timestampMs);
  176. skipped.add(event.id);
  177. return event;
  178. };
  179. const skipEmpty = (
  180. reason: EmptyAppendReason,
  181. payload: Record<string, unknown>,
  182. timestampMs?: number,
  183. ) => {
  184. emptyAppends.set(skip(payload, timestampMs).id, reason);
  185. };
  186. log.push(
  187. SessionEventType.TurnStarted,
  188. { turnNumber: HISTORY_TURNS + 1, input: "当前问题", messageId: userMessageId("live") },
  189. { turnId },
  190. );
  191. stream({ kind: "reasoning_start" });
  192. skip({ kind: "reasoning_delta", delta: "先想" });
  193. skip({ kind: "reasoning_delta", delta: "再想" });
  194. stream({ kind: "reasoning_end" });
  195. stream({ kind: "text_start", assistantMessageId: "message-assistant-live-1" });
  196. skip({ kind: "text_delta", delta: "正在" });
  197. skip({ kind: "text_delta", delta: "处理" });
  198. skip({ kind: "text_delta", delta: "。" });
  199. stream({ kind: "text_end" });
  200. stream({ kind: "tool_input_start", toolCallId: "tc-bash", toolName: "Bash" });
  201. skip({ kind: "tool_input_delta", delta: '{"command":', toolCallId: "tc-bash" });
  202. skip({ kind: "tool_input_delta", delta: '"ls"}', toolCallId: "tc-bash" });
  203. stream({
  204. kind: "tool_call",
  205. done: true,
  206. input: { command: "ls" },
  207. toolCallId: "tc-bash",
  208. toolName: "Bash",
  209. });
  210. // 工具输入已定稿后迟到的原始流:仍是已登记工具行的追加,归约结果为空。
  211. skipEmpty("finalized", { kind: "tool_input_delta", delta: " ", toolCallId: "tc-bash" });
  212. log.push(
  213. SessionEventType.ToolCallScheduled,
  214. {
  215. toolCallId: "tc-bash",
  216. toolName: "Bash",
  217. input: { command: "ls" },
  218. schedule: { parallelGroups: [["tc-bash"]], executionOrder: ["tc-bash"] },
  219. },
  220. { turnId },
  221. );
  222. log.push(
  223. SessionEventType.ToolCallStarted,
  224. { toolCallId: "tc-bash", toolName: "Bash", startedAt: new Date(BASE_TIMESTAMP_MS) },
  225. { turnId },
  226. );
  227. log.push(
  228. SessionEventType.ToolCallResult,
  229. { toolCallId: "tc-bash", result: { success: true, content: "ok" }, duration: 10 },
  230. { turnId },
  231. );
  232. // 文件工具预览按时间节流:后两条与首条同一时刻,落在节流间隔内,归约结果为空。
  233. stream({ kind: "tool_input_start", toolCallId: "tc-write", toolName: "Write" });
  234. const firstWriteDelta = skip({
  235. kind: "tool_input_delta",
  236. delta: '{"file_path":"/work/b.ts",',
  237. toolCallId: "tc-write",
  238. });
  239. const throttledAt = firstWriteDelta.timestamp.getTime();
  240. skipEmpty(
  241. "throttled",
  242. { kind: "tool_input_delta", delta: '"content":', toolCallId: "tc-write" },
  243. throttledAt,
  244. );
  245. skipEmpty(
  246. "throttled",
  247. { kind: "tool_input_delta", delta: '"x"}', toolCallId: "tc-write" },
  248. throttledAt,
  249. );
  250. stream({ kind: "tool_input_end", toolCallId: "tc-write" });
  251. stream({
  252. kind: "tool_call",
  253. done: true,
  254. input: { file_path: "/work/b.ts", content: "x" },
  255. toolCallId: "tc-write",
  256. toolName: "Write",
  257. });
  258. // 没有 text_start 的 text_delta 会新开一行,不是已打开行的追加。
  259. stream({ kind: "text_delta", delta: "完成" });
  260. stream({ kind: "text_end" });
  261. log.push(
  262. SessionEventType.ModelComplete,
  263. {
  264. content: "完成",
  265. stopReason: "stop",
  266. querySource: "main_turn",
  267. contextWindow: 200_000,
  268. usage: USAGE,
  269. fileChanges: {
  270. files: 1,
  271. additions: 1,
  272. deletions: 0,
  273. items: [{ path: "/work/b.ts", additions: 1, deletions: 0, writeCount: 1 }],
  274. },
  275. },
  276. { turnId },
  277. );
  278. log.push(
  279. SessionEventType.TurnComplete,
  280. { response: "完成", tokenCount: 2, toolCallCount: 2, duration: 1, resultType: "success" },
  281. { turnId },
  282. );
  283. // 轮结束后迟到的 delta 被拒收,不是已打开行的追加。
  284. stream({ kind: "text_delta", delta: "迟到" });
  285. }
  286. function pushCompact(log: EventLog): void {
  287. log.push(SessionEventType.CompactStarted, {
  288. operationId: "compact-1",
  289. messageId: "compact-message",
  290. status: "started",
  291. trigger: "manual",
  292. display: "separator",
  293. });
  294. log.push(SessionEventType.CompactCompleted, {
  295. operationId: "compact-1",
  296. messageId: "compact-message",
  297. status: "completed",
  298. trigger: "manual",
  299. display: "separator",
  300. });
  301. }
  302. function streamingKind(event: SessionEvent): string {
  303. return String((event.payload as { kind?: unknown }).kind);
  304. }
  305. describe("命令 actions 的物化时机", () => {
  306. it("只跳过对已打开流式行的追加,逐事件输出与总是物化的参考投影相同", () => {
  307. const log = new EventLog();
  308. const skipped = new Set<string>();
  309. const emptyAppends = new Map<string, EmptyAppendReason>();
  310. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  311. for (let turn = 1; turn <= HISTORY_TURNS; turn += 1) pushHistoryTurn(log, turn, skipped);
  312. pushLiveTurn(log, skipped, emptyAppends);
  313. pushCompact(log);
  314. const userEntityIds = [
  315. ...Array.from({ length: HISTORY_TURNS }, (_, index) => userMessageId(index + 1)),
  316. userMessageId("live"),
  317. ];
  318. const { deltasByEventId, seenActions } = replayAgainstReference(
  319. log.events,
  320. skipped,
  321. userEntityIds,
  322. );
  323. // 归约结果为空的追加确实为空,且两种成因都在:节流间隔或迟到处理变化时,这条覆盖不会悄悄丢失。
  324. for (const eventId of emptyAppends.keys()) {
  325. expect(deltasByEventId.get(eventId), eventId).toEqual([]);
  326. }
  327. expect([...new Set(emptyAppends.values())].sort()).toEqual(EMPTY_APPEND_REASONS);
  328. // 三种流式追加都被跳过过。
  329. const skippedKinds = new Set(
  330. log.events.filter((event) => skipped.has(event.id)).map(streamingKind),
  331. );
  332. expect([...skippedKinds].sort()).toEqual(STREAMING_APPEND_KINDS);
  333. // 语料确实让四种 actions 都出现过,比较不是在全空的 actions 上通过。
  334. expect([...seenActions]).toEqual(expect.arrayContaining(ACTION_KEYS));
  335. });
  336. it("流式追加附带 state.updated(清除 apiRetry)时照常物化", () => {
  337. const log = new EventLog();
  338. const turnId = "turn-retry";
  339. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  340. log.push(
  341. SessionEventType.TurnStarted,
  342. { turnNumber: 1, input: "触发模型请求", messageId: userMessageId("retry") },
  343. { turnId },
  344. );
  345. log.push(
  346. SessionEventType.ModelStreaming,
  347. { kind: "text_start", delta: "", done: false, assistantMessageId: "message-assistant-retry" },
  348. { turnId },
  349. );
  350. const beforeRetry = log.push(
  351. SessionEventType.ModelStreaming,
  352. { kind: "text_delta", delta: "部分", done: false },
  353. { turnId },
  354. );
  355. const scheduled = log.push(
  356. SessionEventType.ModelNetworkStatus,
  357. {
  358. timestamp: "2026-10-29T00:00:00.000Z",
  359. traceId: "trace-1",
  360. requestId: "request-retry",
  361. model: { providerId: "bigmodel", modelId: "glm-5.2" },
  362. transport: "sse",
  363. attempt: 1,
  364. maxAttempts: 11,
  365. type: "model_retry_scheduled",
  366. delayMs: 2_000,
  367. nextAttempt: 2,
  368. reason: "rate_limited",
  369. message: "rate limited",
  370. statusCode: 429,
  371. },
  372. { turnId },
  373. );
  374. const recovered = log.push(
  375. SessionEventType.ModelStreaming,
  376. { kind: "text_delta", delta: "恢复", done: false },
  377. { turnId },
  378. );
  379. const { deltasByEventId, snapshotByEventId } = replayAgainstReference(
  380. log.events,
  381. new Set([beforeRetry.id]),
  382. [userMessageId("retry")],
  383. );
  384. // 重试排期后 apiRetry 有值,这条追加把它清除:归约结果不只有 row.delta,所以必须物化
  385. // (由比较内的调用断言检查)。
  386. expect(snapshotByEventId.get(scheduled.id)?.control.apiRetry).toMatchObject({
  387. reasonCode: "fault.provider.rateLimited",
  388. });
  389. expect(snapshotByEventId.get(recovered.id)?.control.apiRetry).toBeNull();
  390. const recoveredOps = (deltasByEventId.get(recovered.id) ?? []).map((delta) => delta.op);
  391. expect(recoveredOps).toEqual(expect.arrayContaining(["row.delta", "state.updated"]));
  392. });
  393. });