v4-workflow-cold-replay.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // dwf run 的冷回放接缝(docs/dynamic-workflow/presentation.md):
  2. // 父会话冷物化时,`app.replayDynamicWorkflowRuns` 交出的进度载荷被铸成 DynamicWorkflowRunProgress
  3. // 会话事件、前置到内存事件之前,经既有 cold merge(memory-only 权威)与同一个 reducer 落进
  4. // `workflowRuns`——重启后订阅拿到的快照里 run 与重启前一致。
  5. //
  6. // 覆盖面:
  7. // 1. 父会话直接命中 record:回放载荷进投影,内存里已有的 runId 被交给 CLI 排除;
  8. // 2. 子会话经 parentID 回落到父 record:**不**补种(journal 按父会话建键);
  9. // 3. 回放抛错:只记日志,冷开照常完成。
  10. import { mkdtemp, rm } from "node:fs/promises";
  11. import { tmpdir } from "node:os";
  12. import { join } from "node:path";
  13. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  14. import { createInMemorySessionEventStore, createSqliteSessionStore } from "@zcode/adapters/storage";
  15. import { conversationTopic, type WorkflowRunsState } from "@zcode/shared/zcode-protocol-v4";
  16. import type {
  17. DynamicWorkflowRunProgressPayload,
  18. EventId,
  19. ProjectId,
  20. SessionEvent,
  21. SessionEventStorePort,
  22. SessionId,
  23. TraceId,
  24. } from "@zcode/contracts";
  25. import { SessionEventType } from "@zcode/contracts";
  26. import { createConversationV4Gateway } from "../src/zcode-protocol/v4-bridge.js";
  27. import type {
  28. ZCodeProtocolAgentServerContext,
  29. ZCodeProtocolSessionRecord,
  30. } from "../src/zcode-protocol/server-types.js";
  31. type TestSessionStore = ReturnType<typeof createSqliteSessionStore>;
  32. const WORKSPACE_PATH = "/tmp/zcode-workflow-cold-replay";
  33. const PARENT_SESSION_ID = "sess_parent_replay" as SessionId;
  34. const CHILD_SESSION_ID = "sess_actor_replay" as SessionId;
  35. function progress(
  36. runId: string,
  37. sequence: number,
  38. eventType: string,
  39. payload: Record<string, unknown> = {},
  40. ): DynamicWorkflowRunProgressPayload {
  41. return { runId, toolCallId: `call-${runId}`, sequence, eventType, payload };
  42. }
  43. /** 一条 run 从 journal 回放出来的载荷:started → 一个 ask 结算 → 用量 → settle。 */
  44. function replayedRun(
  45. runId: string,
  46. status: "completed" | "stopped",
  47. ): DynamicWorkflowRunProgressPayload[] {
  48. return [
  49. progress(runId, 0, "run-started", { caps: { maxConcurrency: 4 } }),
  50. progress(runId, 1, "actor-created", {
  51. actor: { siteId: "actor#1", ordinal: 1 },
  52. name: "worker",
  53. }),
  54. progress(runId, 2, "node-queued", {
  55. instance: { siteId: "ask#1", ordinal: 1 },
  56. kind: "ask",
  57. actor: { siteId: "actor#1", ordinal: 1 },
  58. }),
  59. progress(runId, 3, "node-settled", {
  60. instance: { siteId: "ask#1", ordinal: 1 },
  61. outcome: "ok",
  62. }),
  63. progress(runId, 4, "usage-updated", { spentTokens: 4200 }),
  64. progress(runId, 5, "run-settled", {
  65. status,
  66. ...(status === "stopped" ? { stopReason: "user", resumable: true } : {}),
  67. }),
  68. ];
  69. }
  70. function memoryProgressEvent(
  71. sessionId: SessionId,
  72. seq: number,
  73. payload: DynamicWorkflowRunProgressPayload,
  74. ): SessionEvent {
  75. return {
  76. id: `${sessionId}-event-${seq}` as EventId,
  77. sessionId,
  78. type: SessionEventType.DynamicWorkflowRunProgress,
  79. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  80. traceId: "trace-replay" as TraceId,
  81. sequenceNumber: seq,
  82. payload,
  83. } as SessionEvent;
  84. }
  85. function makeRecord(
  86. eventStore: SessionEventStorePort,
  87. replay?: (input: {
  88. excludeRunIds: ReadonlySet<string>;
  89. }) => Promise<DynamicWorkflowRunProgressPayload[]>,
  90. ): ZCodeProtocolSessionRecord {
  91. return {
  92. app: {
  93. readToolResultArtifact: async () => ({ content: "" }),
  94. ...(replay === undefined ? {} : { replayDynamicWorkflowRuns: replay }),
  95. runtime: {
  96. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  97. // readSessionContextUsage(staging 6d4c3cc571 起在 loadPersistedEvents 里同步读容量种子)要读
  98. // projection.contextWindow / contextUsed;给一份最小投影即可,子代理投影本就为空。
  99. getProjection: async () => ({ contextUsed: 0, contextWindow: 200_000 }) as never,
  100. },
  101. sessionId: PARENT_SESSION_ID,
  102. },
  103. createdAt: 0,
  104. eventStore,
  105. persistence: "immediate",
  106. stateRevision: 1,
  107. updatedAt: 0,
  108. workspace: { workspaceKey: `local:${WORKSPACE_PATH}`, workspacePath: WORKSPACE_PATH },
  109. } as unknown as ZCodeProtocolSessionRecord;
  110. }
  111. function makeContext(input: {
  112. sessions: Map<string, ZCodeProtocolSessionRecord>;
  113. store: TestSessionStore;
  114. warnings: string[];
  115. }): ZCodeProtocolAgentServerContext {
  116. return {
  117. appRuntimePreferences: {
  118. askUserQuestionAutoResolutionEnabled: false,
  119. modelIoFullRetentionEnabled: false,
  120. },
  121. deps: { sessionStore: input.store },
  122. logger: {
  123. debug: () => {},
  124. error: () => {},
  125. info: () => {},
  126. warn: (message: string, context?: Record<string, unknown>) => {
  127. input.warnings.push(`${message} ${JSON.stringify(context ?? {})}`);
  128. },
  129. },
  130. notify: () => {},
  131. requestClient: async () => {
  132. throw new Error("cold replay test does not issue reverse requests");
  133. },
  134. sessions: input.sessions,
  135. v4Interactions: { resolve: () => false },
  136. workspaceModelCatalogs: new Map(),
  137. } as unknown as ZCodeProtocolAgentServerContext;
  138. }
  139. async function subscribeWorkflowRuns(
  140. gateway: ReturnType<typeof createConversationV4Gateway>,
  141. sessionId: string,
  142. ): Promise<WorkflowRunsState | undefined> {
  143. const result = await gateway.subscribe({
  144. topic: conversationTopic(sessionId),
  145. connectionId: `conn-${sessionId}`,
  146. clientMode: "desktop-continuous",
  147. });
  148. const payload = result.initialFrame?.payload;
  149. if (payload?.kind !== "snapshot") throw new Error("Expected snapshot initial frame");
  150. return payload.snapshot.workflowRuns;
  151. }
  152. describe("v4 冷物化 · dwf run 的冷回放", () => {
  153. let tempRoot: string;
  154. let store: TestSessionStore;
  155. let warnings: string[];
  156. beforeEach(async () => {
  157. tempRoot = await mkdtemp(join(tmpdir(), "zcode-workflow-cold-replay-"));
  158. store = createSqliteSessionStore({ dbPath: join(tempRoot, "sessions.db") });
  159. warnings = [];
  160. });
  161. afterEach(async () => {
  162. store.close();
  163. await rm(tempRoot, { force: true, recursive: true });
  164. });
  165. async function createSessionRow(sessionId: SessionId, parentId?: SessionId): Promise<void> {
  166. await store.createSession({
  167. id: sessionId,
  168. ...(parentId ? { parentID: parentId } : {}),
  169. projectID: "project_cold_replay" as ProjectId,
  170. slug: `slug-${sessionId}`,
  171. directory: WORKSPACE_PATH,
  172. path: WORKSPACE_PATH,
  173. title: `session ${sessionId}`,
  174. version: "test-version",
  175. time: { created: 1, updated: 4 },
  176. });
  177. }
  178. it("父会话:回放载荷经同一个 reducer 落进 workflowRuns;内存里已有的 runId 交给 CLI 排除", async () => {
  179. await createSessionRow(PARENT_SESSION_ID);
  180. const eventStore = createInMemorySessionEventStore();
  181. // 本进程已收到过 dwfrun-live 的事件(暖物化):它必须出现在排除集里、且不被回放覆盖。
  182. const liveEvents = replayedRun("dwfrun-live", "completed").slice(0, 2);
  183. let seq = 0;
  184. for (const payload of liveEvents) {
  185. seq += 1;
  186. await eventStore.append(memoryProgressEvent(PARENT_SESSION_ID, seq, payload));
  187. }
  188. const excludeSeen: string[][] = [];
  189. const record = makeRecord(eventStore, async ({ excludeRunIds }) => {
  190. excludeSeen.push([...excludeRunIds]);
  191. return [...replayedRun("dwfrun-old", "stopped"), ...replayedRun("dwfrun-done", "completed")];
  192. });
  193. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  194. const context = makeContext({ sessions, store, warnings });
  195. const gateway = createConversationV4Gateway(context);
  196. context.v4Gateway = gateway;
  197. const workflowRuns = await subscribeWorkflowRuns(gateway, PARENT_SESSION_ID);
  198. expect(excludeSeen).toEqual([["dwfrun-live"]]);
  199. const byId = new Map(workflowRuns?.runs.map((run) => [run.runId, run]));
  200. // 回放出来的 run 与 live 归约同形:状态、步数、用量、resumable 位一个不少。
  201. expect(byId.get("dwfrun-old")).toMatchObject({
  202. status: "stopped",
  203. stopReason: "user",
  204. resumable: true,
  205. toolCallId: "call-dwfrun-old",
  206. usage: { spentTokens: 4200, nodesUsed: 0 },
  207. });
  208. expect(byId.get("dwfrun-old")?.nodes).toHaveLength(1);
  209. expect(byId.get("dwfrun-old")?.actors).toHaveLength(1);
  210. expect(byId.get("dwfrun-done")).toMatchObject({ status: "completed" });
  211. expect(byId.get("dwfrun-done")?.resumable).toBeUndefined();
  212. // 回放在前、内存事件在后:live run 仍是内存事件归约出的形态(running,只有 actor)。
  213. expect(byId.get("dwfrun-live")).toMatchObject({ status: "running" });
  214. expect([...byId.keys()]).toEqual(["dwfrun-old", "dwfrun-done", "dwfrun-live"]);
  215. expect(warnings.some((line) => line.includes("dynamic workflow replay failed"))).toBe(false);
  216. });
  217. it("子会话经 parentID 回落到父 record:不补种", async () => {
  218. await createSessionRow(PARENT_SESSION_ID);
  219. await createSessionRow(CHILD_SESSION_ID, PARENT_SESSION_ID);
  220. const eventStore = createInMemorySessionEventStore();
  221. let replayCalls = 0;
  222. const record = makeRecord(eventStore, async () => {
  223. replayCalls += 1;
  224. return replayedRun("dwfrun-old", "completed");
  225. });
  226. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  227. const context = makeContext({ sessions, store, warnings });
  228. const gateway = createConversationV4Gateway(context);
  229. context.v4Gateway = gateway;
  230. // 生产形态(与 v4-detached-child-hydration 同):子会话没有自己的 record,事件按子 sessionId
  231. // 归档进父的 event store,另经父 record 的 sink 路由到 gateway 的 detached live 通道。
  232. let seq = 0;
  233. for (const [type, payload, turnId] of [
  234. [SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 }, undefined],
  235. [SessionEventType.TurnStarted, { turnNumber: 1, input: "actor 提问" }, "actor-turn-live"],
  236. ] as const) {
  237. seq += 1;
  238. const event = {
  239. id: `${CHILD_SESSION_ID}-event-${seq}` as EventId,
  240. sessionId: CHILD_SESSION_ID,
  241. ...(turnId === undefined ? {} : { turnId }),
  242. type,
  243. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  244. traceId: "trace-replay" as TraceId,
  245. sequenceNumber: seq,
  246. payload,
  247. } as SessionEvent;
  248. await eventStore.append(event);
  249. gateway.ingestDetachedLiveSession(CHILD_SESSION_ID, event);
  250. }
  251. const workflowRuns = await subscribeWorkflowRuns(gateway, CHILD_SESSION_ID);
  252. expect(replayCalls).toBe(0);
  253. expect(workflowRuns?.runs ?? []).toEqual([]);
  254. });
  255. it("回放抛错:记 warn、冷开照常完成、投影为空而不是失败", async () => {
  256. await createSessionRow(PARENT_SESSION_ID);
  257. const eventStore = createInMemorySessionEventStore();
  258. const record = makeRecord(eventStore, async () => {
  259. throw new Error("journal exploded");
  260. });
  261. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  262. const context = makeContext({ sessions, store, warnings });
  263. const gateway = createConversationV4Gateway(context);
  264. context.v4Gateway = gateway;
  265. const workflowRuns = await subscribeWorkflowRuns(gateway, PARENT_SESSION_ID);
  266. expect(workflowRuns?.runs ?? []).toEqual([]);
  267. expect(
  268. warnings.some((line) => line.includes("v4 hydrate dynamic workflow replay failed")),
  269. ).toBe(true);
  270. });
  271. });