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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. MessageId,
  20. ModelId,
  21. ModelProviderId,
  22. MessagePart,
  23. ProjectId,
  24. SessionEvent,
  25. SessionEventStorePort,
  26. SessionId,
  27. TraceId,
  28. } from "@zcode/contracts";
  29. import { SessionEventType } from "@zcode/contracts";
  30. import { createConversationV4Gateway } from "../src/zcode-protocol/v4-bridge.js";
  31. import type {
  32. ZCodeProtocolAgentServerContext,
  33. ZCodeProtocolSessionRecord,
  34. } from "../src/zcode-protocol/server-types.js";
  35. type TestSessionStore = Awaited<ReturnType<typeof createSqliteSessionStore>>;
  36. const WORKSPACE_PATH = "/tmp/zcode-workflow-cold-replay";
  37. const PARENT_SESSION_ID = "sess_parent_replay" as SessionId;
  38. const CHILD_SESSION_ID = "sess_actor_replay" as SessionId;
  39. function progress(
  40. runId: string,
  41. sequence: number,
  42. eventType: string,
  43. payload: Record<string, unknown> = {},
  44. ): DynamicWorkflowRunProgressPayload {
  45. return { runId, toolCallId: `call-${runId}`, sequence, eventType, payload };
  46. }
  47. /** 一条 run 从 journal 回放出来的载荷:started → 一个 ask 结算 → 用量 → settle。 */
  48. function replayedRun(
  49. runId: string,
  50. status: "completed" | "stopped",
  51. ): DynamicWorkflowRunProgressPayload[] {
  52. return [
  53. progress(runId, 0, "run-started", { caps: { maxConcurrency: 4 } }),
  54. progress(runId, 1, "actor-created", {
  55. actor: { siteId: "actor#1", ordinal: 1 },
  56. name: "worker",
  57. }),
  58. progress(runId, 2, "node-queued", {
  59. instance: { siteId: "ask#1", ordinal: 1 },
  60. kind: "ask",
  61. actor: { siteId: "actor#1", ordinal: 1 },
  62. }),
  63. progress(runId, 3, "node-settled", {
  64. instance: { siteId: "ask#1", ordinal: 1 },
  65. outcome: "ok",
  66. }),
  67. progress(runId, 4, "usage-updated", { spentTokens: 4200 }),
  68. progress(runId, 5, "run-settled", {
  69. status,
  70. ...(status === "stopped" ? { stopReason: "user", resumable: true } : {}),
  71. }),
  72. ];
  73. }
  74. function memoryProgressEvent(
  75. sessionId: SessionId,
  76. seq: number,
  77. payload: DynamicWorkflowRunProgressPayload,
  78. ): SessionEvent {
  79. return {
  80. id: `${sessionId}-event-${seq}` as EventId,
  81. sessionId,
  82. type: SessionEventType.DynamicWorkflowRunProgress,
  83. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  84. traceId: "trace-replay" as TraceId,
  85. sequenceNumber: seq,
  86. payload,
  87. } as SessionEvent;
  88. }
  89. function makeRecord(
  90. eventStore: SessionEventStorePort,
  91. replay?: (input: {
  92. excludeRunIds: ReadonlySet<string>;
  93. }) => Promise<DynamicWorkflowRunProgressPayload[]>,
  94. ): ZCodeProtocolSessionRecord {
  95. return {
  96. app: {
  97. readToolResultArtifact: async () => ({ content: "" }),
  98. ...(replay === undefined ? {} : { replayDynamicWorkflowRuns: replay }),
  99. runtime: {
  100. getSessionModelSelection: () => ({ providerId: "glm", modelId: "glm-4-air" }),
  101. // readSessionContextUsage(staging 6d4c3cc571 起在 loadPersistedEvents 里同步读容量种子)要读
  102. // projection.contextWindow / contextUsed;给一份最小投影即可,子代理投影本就为空。
  103. getProjection: async () => ({ contextUsed: 0, contextWindow: 200_000 }) as never,
  104. },
  105. sessionId: PARENT_SESSION_ID,
  106. },
  107. createdAt: 0,
  108. eventStore,
  109. persistence: "immediate",
  110. stateRevision: 1,
  111. updatedAt: 0,
  112. workspace: { workspaceKey: `local:${WORKSPACE_PATH}`, workspacePath: WORKSPACE_PATH },
  113. } as unknown as ZCodeProtocolSessionRecord;
  114. }
  115. function makeContext(input: {
  116. sessions: Map<string, ZCodeProtocolSessionRecord>;
  117. store: TestSessionStore;
  118. warnings: string[];
  119. }): ZCodeProtocolAgentServerContext {
  120. return {
  121. appRuntimePreferences: {
  122. askUserQuestionAutoResolutionEnabled: false,
  123. modelIoFullRetentionEnabled: false,
  124. },
  125. deps: { sessionStore: input.store },
  126. logger: {
  127. debug: () => {},
  128. error: () => {},
  129. info: () => {},
  130. warn: (message: string, context?: Record<string, unknown>) => {
  131. input.warnings.push(`${message} ${JSON.stringify(context ?? {})}`);
  132. },
  133. },
  134. notify: () => {},
  135. requestClient: async () => {
  136. throw new Error("cold replay test does not issue reverse requests");
  137. },
  138. sessions: input.sessions,
  139. v4Interactions: { resolve: () => false },
  140. workspaceModelCatalogs: new Map(),
  141. } as unknown as ZCodeProtocolAgentServerContext;
  142. }
  143. async function subscribeWorkflowRuns(
  144. gateway: ReturnType<typeof createConversationV4Gateway>,
  145. sessionId: string,
  146. ): Promise<WorkflowRunsState | undefined> {
  147. const result = await gateway.subscribe({
  148. topic: conversationTopic(sessionId),
  149. connectionId: `conn-${sessionId}`,
  150. clientMode: "desktop-continuous",
  151. });
  152. const payload = result.initialFrame?.payload;
  153. if (payload?.kind !== "snapshot") throw new Error("Expected snapshot initial frame");
  154. return payload.snapshot.workflowRuns;
  155. }
  156. describe("v4 冷物化 · dwf run 的冷回放", () => {
  157. let tempRoot: string;
  158. let store: TestSessionStore;
  159. let warnings: string[];
  160. beforeEach(async () => {
  161. tempRoot = await mkdtemp(join(tmpdir(), "zcode-workflow-cold-replay-"));
  162. store = await createSqliteSessionStore({ dbPath: join(tempRoot, "sessions.db") });
  163. warnings = [];
  164. });
  165. afterEach(async () => {
  166. store.close();
  167. await rm(tempRoot, { force: true, recursive: true });
  168. });
  169. async function createSessionRow(sessionId: SessionId, parentId?: SessionId): Promise<void> {
  170. await store.createSession({
  171. id: sessionId,
  172. ...(parentId ? { parentID: parentId } : {}),
  173. projectID: "project_cold_replay" as ProjectId,
  174. slug: `slug-${sessionId}`,
  175. directory: WORKSPACE_PATH,
  176. path: WORKSPACE_PATH,
  177. title: `session ${sessionId}`,
  178. version: "test-version",
  179. time: { created: 1, updated: 4 },
  180. });
  181. }
  182. it("父会话:回放载荷经同一个 reducer 落进 workflowRuns;内存里已有的 runId 交给 CLI 排除", async () => {
  183. await createSessionRow(PARENT_SESSION_ID);
  184. const eventStore = createInMemorySessionEventStore();
  185. // 本进程已收到过 dwfrun-live 的事件(暖物化):它必须出现在排除集里、且不被回放覆盖。
  186. const liveEvents = replayedRun("dwfrun-live", "completed").slice(0, 2);
  187. let seq = 0;
  188. for (const payload of liveEvents) {
  189. seq += 1;
  190. await eventStore.append(memoryProgressEvent(PARENT_SESSION_ID, seq, payload));
  191. }
  192. const excludeSeen: string[][] = [];
  193. const record = makeRecord(eventStore, async ({ excludeRunIds }) => {
  194. excludeSeen.push([...excludeRunIds]);
  195. return [...replayedRun("dwfrun-old", "stopped"), ...replayedRun("dwfrun-done", "completed")];
  196. });
  197. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  198. const context = makeContext({ sessions, store, warnings });
  199. const gateway = createConversationV4Gateway(context);
  200. context.v4Gateway = gateway;
  201. const workflowRuns = await subscribeWorkflowRuns(gateway, PARENT_SESSION_ID);
  202. expect(excludeSeen).toEqual([["dwfrun-live"]]);
  203. const byId = new Map(workflowRuns?.runs.map((run) => [run.runId, run]));
  204. // 回放出来的 run 与 live 归约同形:状态、步数、用量、resumable 位一个不少。
  205. expect(byId.get("dwfrun-old")).toMatchObject({
  206. status: "stopped",
  207. stopReason: "user",
  208. resumable: true,
  209. toolCallId: "call-dwfrun-old",
  210. usage: { spentTokens: 4200, nodesUsed: 0 },
  211. });
  212. expect(byId.get("dwfrun-old")?.nodes).toHaveLength(1);
  213. expect(byId.get("dwfrun-old")?.actors).toHaveLength(1);
  214. expect(byId.get("dwfrun-done")).toMatchObject({ status: "completed" });
  215. expect(byId.get("dwfrun-done")?.resumable).toBeUndefined();
  216. // 回放在前、内存事件在后:live run 仍是内存事件归约出的形态(running,只有 actor)。
  217. expect(byId.get("dwfrun-live")).toMatchObject({ status: "running" });
  218. expect([...byId.keys()]).toEqual(["dwfrun-old", "dwfrun-done", "dwfrun-live"]);
  219. expect(warnings.some((line) => line.includes("dynamic workflow replay failed"))).toBe(false);
  220. });
  221. it("完整历史种子不受八条预览限制,保留更新的 live run 状态", async () => {
  222. await createSessionRow(PARENT_SESSION_ID);
  223. const eventStore = createInMemorySessionEventStore();
  224. const record = makeRecord(eventStore, async () => replayedRun("recent", "completed"));
  225. record.app.getWorkflowActivityHistory = async () => ({
  226. runs: Array.from({ length: 10 }, (_, i) => ({
  227. runId: `old-${i}`,
  228. status: "completed",
  229. sequence: 20,
  230. })),
  231. childSessionIds: [],
  232. });
  233. const context = makeContext({
  234. sessions: new Map([[PARENT_SESSION_ID, record]]),
  235. store,
  236. warnings,
  237. });
  238. const gateway = createConversationV4Gateway(context);
  239. context.v4Gateway = gateway;
  240. const result = await gateway.subscribe({
  241. topic: conversationTopic(PARENT_SESSION_ID),
  242. connectionId: "complete-history",
  243. clientMode: "desktop-continuous",
  244. });
  245. const payload = result.initialFrame?.payload;
  246. if (payload?.kind !== "snapshot") throw new Error("Expected snapshot");
  247. expect(payload.snapshot.workflowRuns?.runs).toHaveLength(1);
  248. expect(payload.snapshot.completedActivityCount).toBe(11);
  249. });
  250. it.each(["desktop-continuous", "web-remote-replayable"] as const)(
  251. "完整计数读取失败保留可用历史、实时事件及未知计数,并记录告警 (%s)",
  252. async (clientMode) => {
  253. await createSessionRow(PARENT_SESSION_ID);
  254. const eventStore = createInMemorySessionEventStore();
  255. const messageId = "persisted-user" as MessageId;
  256. await store.saveMessage({
  257. id: messageId,
  258. sessionID: PARENT_SESSION_ID,
  259. role: "user",
  260. time: { created: 1 },
  261. agent: "zcode-agent",
  262. tools: {},
  263. model: { providerID: "glm" as ModelProviderId, modelID: "glm-4-air" as ModelId },
  264. });
  265. await store.savePart({
  266. id: "persisted-text" as MessagePart["id"],
  267. sessionID: PARENT_SESSION_ID,
  268. messageID: messageId,
  269. type: "text",
  270. text: "retained history message",
  271. time: { start: 1, end: 1 },
  272. });
  273. const record = makeRecord(eventStore, async () => replayedRun("history", "completed"));
  274. record.app.getWorkflowActivityHistory = async () => {
  275. for (const [index, payload] of replayedRun("live-tail", "completed").entries()) {
  276. const event = memoryProgressEvent(PARENT_SESSION_ID, index + 1, payload);
  277. await eventStore.append(event);
  278. gateway.ingest(PARENT_SESSION_ID, event);
  279. }
  280. throw new Error("injected activity summary failure");
  281. };
  282. const context = makeContext({
  283. sessions: new Map([[PARENT_SESSION_ID, record]]),
  284. store,
  285. warnings,
  286. });
  287. const gateway = createConversationV4Gateway(context);
  288. context.v4Gateway = gateway;
  289. const result = await gateway.subscribe({
  290. topic: conversationTopic(PARENT_SESSION_ID),
  291. connectionId: "summary-failure",
  292. clientMode,
  293. historyFirst: true,
  294. });
  295. const payload = result.initialFrame?.payload;
  296. if (payload?.kind !== "snapshot") throw new Error("Expected snapshot");
  297. expect(payload.snapshot.workflowRuns?.runs.map((run) => run.runId)).toEqual([
  298. "history",
  299. "live-tail",
  300. ]);
  301. expect(payload.snapshot.completedActivityCount).toBeNull();
  302. expect(JSON.stringify(payload.snapshot.rows)).toContain("retained history message");
  303. expect(
  304. warnings.some(
  305. (line) =>
  306. line.includes("activity history read failed") && line.includes(PARENT_SESSION_ID),
  307. ),
  308. ).toBe(true);
  309. },
  310. );
  311. it("子会话经 parentID 回落到父 record:不补种", async () => {
  312. await createSessionRow(PARENT_SESSION_ID);
  313. await createSessionRow(CHILD_SESSION_ID, PARENT_SESSION_ID);
  314. const eventStore = createInMemorySessionEventStore();
  315. let replayCalls = 0;
  316. const record = makeRecord(eventStore, async () => {
  317. replayCalls += 1;
  318. return replayedRun("dwfrun-old", "completed");
  319. });
  320. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  321. const context = makeContext({ sessions, store, warnings });
  322. const gateway = createConversationV4Gateway(context);
  323. context.v4Gateway = gateway;
  324. // 生产形态(与 v4-detached-child-hydration 同):子会话没有自己的 record,事件按子 sessionId
  325. // 归档进父的 event store,另经父 record 的 sink 路由到 gateway 的 detached live 通道。
  326. let seq = 0;
  327. for (const [type, payload, turnId] of [
  328. [SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 }, undefined],
  329. [SessionEventType.TurnStarted, { turnNumber: 1, input: "actor 提问" }, "actor-turn-live"],
  330. ] as const) {
  331. seq += 1;
  332. const event = {
  333. id: `${CHILD_SESSION_ID}-event-${seq}` as EventId,
  334. sessionId: CHILD_SESSION_ID,
  335. ...(turnId === undefined ? {} : { turnId }),
  336. type,
  337. timestamp: new Date(1_700_000_000_000 + seq * 1000),
  338. traceId: "trace-replay" as TraceId,
  339. sequenceNumber: seq,
  340. payload,
  341. } as SessionEvent;
  342. await eventStore.append(event);
  343. gateway.ingestDetachedLiveSession(CHILD_SESSION_ID, event);
  344. }
  345. const workflowRuns = await subscribeWorkflowRuns(gateway, CHILD_SESSION_ID);
  346. expect(replayCalls).toBe(0);
  347. expect(workflowRuns?.runs ?? []).toEqual([]);
  348. });
  349. it("回放抛错:记 warn、冷开照常完成、投影为空而不是失败", async () => {
  350. await createSessionRow(PARENT_SESSION_ID);
  351. const eventStore = createInMemorySessionEventStore();
  352. const record = makeRecord(eventStore, async () => {
  353. throw new Error("journal exploded");
  354. });
  355. const sessions = new Map<string, ZCodeProtocolSessionRecord>([[PARENT_SESSION_ID, record]]);
  356. const context = makeContext({ sessions, store, warnings });
  357. const gateway = createConversationV4Gateway(context);
  358. context.v4Gateway = gateway;
  359. const workflowRuns = await subscribeWorkflowRuns(gateway, PARENT_SESSION_ID);
  360. expect(workflowRuns?.runs ?? []).toEqual([]);
  361. expect(
  362. warnings.some((line) => line.includes("v4 hydrate dynamic workflow replay failed")),
  363. ).toBe(true);
  364. });
  365. });