dynamic-workflow-run-replay.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // dwf run 冷回放的结算来源(docs/dynamic-workflow/presentation.md「Cold replay」):
  2. // 行是终态时,回放的尾部 `run-settled` 一律按行铸造——journal 里存着的那条(无论新旧词表)让位;
  3. // 尾部没有结算(进程死亡 / 孤儿收敛只改行)时追加。
  4. //
  5. // 修复原因(2026-09-15,桌面实测):2026-09-14 终态词表重构之前写下的 `run-settled` 带旧词
  6. // cancelled / failed,事件载荷原样回放,reducer 认不出,run 被留在 running。这里用真实 SQLite
  7. // journal 落下一模一样的字节(appendEvent 原样存 JSON),钉住回放 + reducer 之后 run 必须是终态。
  8. import { mkdtemp, rm } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  12. import { createSqliteSessionStore, type DwfRunSessionListItem } from "@zcode/adapters/storage";
  13. import type { JournalStorePort, RunEvent } from "@zcode/dynamic-workflow";
  14. import { reduceWorkflowRunsState, type WorkflowRunsState } from "@zcode/shared/zcode-protocol-v4";
  15. import { toProgressPayload } from "../src/app/dynamic-workflow-run-launch.js";
  16. import { replayRunProgress } from "../src/app/dynamic-workflow-run-replay.js";
  17. import { mintActorSessionId } from "../src/app/workflow-driver.js";
  18. import { resolveDynamicWorkflowJournalStore } from "../src/app/dynamic-workflow-run-service.js";
  19. const PARENT = "sess_replay_parent";
  20. // 冷回放的第三个参数:本进程的并发天花板,只落在 `run-started` 载荷上(docs/dynamic-workflow/concurrency.md「Two bounds on a run」)。
  21. // 这里的用例只看结算,取一个固定值即可;live 侧(toProgressPayload)传同一个值,逐字节契约才成立。
  22. const CEILING = 6;
  23. type Journal = JournalStorePort & {
  24. listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[];
  25. };
  26. let tempRoot: string;
  27. let store: ReturnType<typeof createSqliteSessionStore>;
  28. let journal: Journal;
  29. beforeEach(async () => {
  30. tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-replay-"));
  31. store = createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  32. const resolved = resolveDynamicWorkflowJournalStore(store as never);
  33. if (resolved === undefined) throw new Error("sqlite store must expose the dwf journal");
  34. journal = resolved as Journal;
  35. });
  36. afterEach(async () => {
  37. await store.close?.();
  38. await rm(tempRoot, { force: true, recursive: true });
  39. });
  40. function createRun(runId: string): void {
  41. journal.createRun({
  42. runId,
  43. parentSessionId: PARENT,
  44. cwd: "/repo",
  45. toolCallId: `call-${runId}`,
  46. scriptText: "const a = agent('a');",
  47. scriptHash: "sha-a",
  48. caps: { maxConcurrency: 4 },
  49. spentTokens: 0,
  50. status: "running",
  51. });
  52. journal.appendEvent(runId, {
  53. type: "run-started",
  54. runId,
  55. caps: { maxConcurrency: 4 },
  56. } as RunEvent);
  57. journal.appendEvent(runId, {
  58. type: "actor-created",
  59. actor: { siteId: "actor#1", ordinal: 1 },
  60. name: "a",
  61. } as RunEvent);
  62. }
  63. /** 旧词表的结算事件:`appendEvent` 原样存 JSON,落下的就是 2026-09-14 之前的字节。 */
  64. function appendLegacySettle(runId: string, status: "cancelled" | "failed", error?: unknown): void {
  65. journal.appendEvent(runId, {
  66. type: "run-settled",
  67. status,
  68. ...(error === undefined ? {} : { error }),
  69. } as unknown as RunEvent);
  70. }
  71. function rowOf(runId: string): DwfRunSessionListItem {
  72. const row = journal.listRunsByParentSession(PARENT, 8).find((item) => item.runId === runId);
  73. if (row === undefined) throw new Error(`row missing for ${runId}`);
  74. return row;
  75. }
  76. function reduce(runId: string): WorkflowRunsState["runs"][number] {
  77. let state: WorkflowRunsState | undefined;
  78. for (const payload of replayRunProgress(rowOf(runId), journal, CEILING)) {
  79. state = reduceWorkflowRunsState(state, payload) ?? state;
  80. }
  81. const run = state?.runs.find((item) => item.runId === runId);
  82. if (run === undefined) throw new Error("run not projected");
  83. return run;
  84. }
  85. describe("replayRunProgress — 结算按行铸造", () => {
  86. it("旧词表 run-settled{cancelled}(行已译成 stopped)→ 回放尾部是行铸的 stopped,reducer 落终态且可恢复", () => {
  87. createRun("dwfrun-legacy-cancelled");
  88. appendLegacySettle("dwfrun-legacy-cancelled", "cancelled");
  89. journal.updateRunStatus("dwfrun-legacy-cancelled", "stopped", { stopReason: "user" });
  90. const payloads = replayRunProgress(rowOf("dwfrun-legacy-cancelled"), journal, CEILING);
  91. const stored = journal.listEvents("dwfrun-legacy-cancelled", {
  92. types: "all",
  93. reportItems: "all",
  94. });
  95. // 一进一出:存着的结算被替换,不是追加——条数与 journal 一致,水位沿用被替换那条的 sequence。
  96. expect(payloads).toHaveLength(stored.length);
  97. const last = payloads.at(-1);
  98. expect(last).toMatchObject({
  99. eventType: "run-settled",
  100. sequence: stored.at(-1)?.sequence,
  101. payload: { status: "stopped", stopReason: "user", resumable: true },
  102. });
  103. expect(
  104. payloads.some((payload) => (payload.payload as { status?: unknown }).status === "cancelled"),
  105. ).toBe(false);
  106. const run = reduce("dwfrun-legacy-cancelled");
  107. expect(run.status).toBe("stopped");
  108. expect(run.stopReason).toBe("user");
  109. expect(run.resumable).toBe(true);
  110. });
  111. it("旧词表 run-settled{failed}(行是 errored)→ errored,失败文案来自行", () => {
  112. createRun("dwfrun-legacy-failed");
  113. appendLegacySettle("dwfrun-legacy-failed", "failed", { code: "DriverError", message: "boom" });
  114. journal.updateRunStatus("dwfrun-legacy-failed", "errored", {
  115. failure: { code: "DriverError", message: "boom" },
  116. });
  117. const run = reduce("dwfrun-legacy-failed");
  118. expect(run.status).toBe("errored");
  119. expect(run.error).toBe("boom");
  120. expect(run.resumable).toBeUndefined();
  121. });
  122. it("当前词表:行铸的结算与存着的那条逐字节相同(live 与冷回放同一份字节的契约不变)", () => {
  123. createRun("dwfrun-current");
  124. journal.updateRunStatus("dwfrun-current", "stopped", { stopReason: "model" });
  125. journal.appendEvent("dwfrun-current", {
  126. type: "run-settled",
  127. status: "stopped",
  128. stopReason: "model",
  129. } as RunEvent);
  130. const row = rowOf("dwfrun-current");
  131. const live = journal
  132. .listEvents("dwfrun-current", { types: "all", reportItems: "all" })
  133. .map((entry) =>
  134. toProgressPayload({
  135. event: entry.event,
  136. runId: row.runId,
  137. sequence: entry.sequence,
  138. toolCallId: row.toolCallId!,
  139. concurrencyCeiling: CEILING,
  140. }),
  141. );
  142. expect(JSON.stringify(replayRunProgress(row, journal, CEILING))).toBe(JSON.stringify(live));
  143. });
  144. it("行是终态而事件流没有结算(孤儿收敛只改了行)→ 追加一条 interrupted 结算,sequence = 最后一条 + 1", () => {
  145. createRun("dwfrun-orphan");
  146. journal.updateRunStatus("dwfrun-orphan", "stopped", {
  147. stopReason: "interrupted",
  148. failure: { code: "Interrupted", message: "owner exited" },
  149. });
  150. const stored = journal.listEvents("dwfrun-orphan", { types: "all", reportItems: "all" });
  151. const payloads = replayRunProgress(rowOf("dwfrun-orphan"), journal, CEILING);
  152. expect(payloads).toHaveLength(stored.length + 1);
  153. expect(payloads.at(-1)).toMatchObject({
  154. eventType: "run-settled",
  155. sequence: (stored.at(-1)?.sequence ?? 0) + 1,
  156. payload: { status: "stopped", stopReason: "interrupted", resumable: true },
  157. });
  158. expect(reduce("dwfrun-orphan").status).toBe("stopped");
  159. });
  160. it("中途的上一世结算(cancel → resume)原样保留,只替换尾部那条", () => {
  161. createRun("dwfrun-resumed");
  162. appendLegacySettle("dwfrun-resumed", "cancelled");
  163. journal.appendEvent("dwfrun-resumed", {
  164. type: "run-started",
  165. runId: "dwfrun-resumed",
  166. caps: { maxConcurrency: 4 },
  167. } as RunEvent);
  168. journal.updateRunStatus("dwfrun-resumed", "completed");
  169. journal.appendEvent("dwfrun-resumed", { type: "run-settled", status: "completed" } as RunEvent);
  170. const payloads = replayRunProgress(rowOf("dwfrun-resumed"), journal, CEILING);
  171. const settles = payloads.filter((payload) => payload.eventType === "run-settled");
  172. expect(settles.map((payload) => (payload.payload as { status: string }).status)).toEqual([
  173. "cancelled",
  174. "completed",
  175. ]);
  176. expect(reduce("dwfrun-resumed").status).toBe("completed");
  177. });
  178. // ── 本 run 的子代理模型(docs/dynamic-workflow/launch.md)───────────────────
  179. // 它与发起锚点同住 `run-launched`(零 SQL,dwf_run 上没有这一列):live 侧从 launch 入参拿到
  180. // 规范串并挂在 `run-started` 载荷上,冷回放从同一条事件读回。两侧必须给出同一个键,
  181. // 否则重启前后的投影就不再逐字节一致。
  182. it("run-launched 上的 subagentModel 进 run-started 载荷;冷回放与 live 逐字节相等", () => {
  183. const SUBAGENT = "zhipu/glm-5.3-flash$high";
  184. createRun("dwfrun-subagent");
  185. journal.appendEvent("dwfrun-subagent", {
  186. type: "run-launched",
  187. inputId: "input-origin",
  188. subagentModel: SUBAGENT,
  189. } as RunEvent);
  190. journal.updateRunStatus("dwfrun-subagent", "completed");
  191. journal.appendEvent("dwfrun-subagent", {
  192. type: "run-settled",
  193. status: "completed",
  194. } as RunEvent);
  195. const row = rowOf("dwfrun-subagent");
  196. const payloads = replayRunProgress(row, journal, CEILING);
  197. const started = payloads.find((payload) => payload.eventType === "run-started");
  198. expect(started?.payload).toMatchObject({
  199. subagentModel: SUBAGENT,
  200. concurrencyCeiling: CEILING,
  201. });
  202. // 派生字段只挂在 run-started 上:其余事件带着它只会让每一条载荷都重复同一条 run 级事实。
  203. // `run-launched` 自己不算——那条载荷是事件的原样内容,模型串本来就写在里面。
  204. for (const payload of payloads) {
  205. if (payload.eventType === "run-started" || payload.eventType === "run-launched") continue;
  206. expect("subagentModel" in payload.payload).toBe(false);
  207. }
  208. // live 侧同一条铸造链、同一个值 → 逐字节相等(本模块唯一的契约)。
  209. const live = journal
  210. .listEvents("dwfrun-subagent", { types: "all", reportItems: "all" })
  211. .map((entry) =>
  212. toProgressPayload({
  213. event: entry.event,
  214. runId: row.runId,
  215. sequence: entry.sequence,
  216. toolCallId: row.toolCallId!,
  217. launchInputId: "input-origin",
  218. concurrencyCeiling: CEILING,
  219. subagentModel: SUBAGENT,
  220. }),
  221. );
  222. expect(JSON.stringify(payloads)).toBe(JSON.stringify(live));
  223. });
  224. it("run-launched 没带子代理模型:run-started 载荷整个不带这个键", () => {
  225. createRun("dwfrun-no-subagent");
  226. journal.appendEvent("dwfrun-no-subagent", {
  227. type: "run-launched",
  228. inputId: "input-origin",
  229. } as RunEvent);
  230. const started = replayRunProgress(rowOf("dwfrun-no-subagent"), journal, CEILING).find(
  231. (payload) => payload.eventType === "run-started",
  232. );
  233. // 缺席而不是空串:读侧据此判断这个 run 有没有设过子代理模型。
  234. expect("subagentModel" in started!.payload).toBe(false);
  235. });
  236. // ── 脚本点名的模型(docs/dynamic-workflow/launch.md「Models the script names」)──────────
  237. // 绑定表同住 `run-launched`;actor-created 的派生 `model` 据它把 persona 的名字映射成规范串。
  238. // 冷回放从同一条事件读回同一张表,两侧载荷逐字节相等。
  239. it("actor-created 载荷的派生 model 来自 run-launched 的绑定表;冷回放与 live 逐字节相等", () => {
  240. const BINDINGS = { "GLM-5.3-Flash": "zhipu/GLM-5.3-Flash" };
  241. createRun("dwfrun-bindings");
  242. journal.appendEvent("dwfrun-bindings", {
  243. type: "run-launched",
  244. inputId: "input-origin",
  245. modelBindings: BINDINGS,
  246. } as RunEvent);
  247. journal.appendEvent("dwfrun-bindings", {
  248. type: "actor-created",
  249. actor: { siteId: "actor#7", ordinal: 1 },
  250. name: "评审员",
  251. persona: { name: "评审员", model: "GLM-5.3-Flash" },
  252. } as RunEvent);
  253. journal.appendEvent("dwfrun-bindings", {
  254. type: "actor-created",
  255. actor: { siteId: "actor#8", ordinal: 1 },
  256. name: "旁观者",
  257. persona: { name: "旁观者" },
  258. } as RunEvent);
  259. const row = rowOf("dwfrun-bindings");
  260. const payloads = replayRunProgress(row, journal, CEILING);
  261. // createRun 自己也建了一个子代理(无模型);这里只看本用例加的两个。
  262. const created = payloads.filter(
  263. (payload) =>
  264. payload.eventType === "actor-created" &&
  265. ["评审员", "旁观者"].includes(String(payload.payload.name)),
  266. );
  267. expect(created[0]?.payload).toMatchObject({ model: "zhipu/GLM-5.3-Flash" });
  268. expect("model" in created[1]!.payload).toBe(false);
  269. const live = journal
  270. .listEvents("dwfrun-bindings", { types: "all", reportItems: "all" })
  271. .map((entry) =>
  272. toProgressPayload({
  273. event: entry.event,
  274. runId: row.runId,
  275. sequence: entry.sequence,
  276. toolCallId: row.toolCallId!,
  277. launchInputId: "input-origin",
  278. concurrencyCeiling: CEILING,
  279. modelBindings: BINDINGS,
  280. }),
  281. );
  282. expect(JSON.stringify(payloads)).toBe(JSON.stringify(live));
  283. });
  284. // ── ask 的 node-dispatched(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Events」)─────
  285. // 它重复实例的出生事实并点名子代理,所以与 actor-created 一样在接缝上补 `actorSessionId`。
  286. // 冷回放走的是同一条铸造链,envelope 必须一字不差——否则重启前后投影就能收不同的实例进表。
  287. it("ask 的 node-dispatched 带出生事实与 actorSessionId;冷回放与 live 逐字节相等", () => {
  288. const actor = { siteId: "actor#1", ordinal: 1 };
  289. createRun("dwfrun-dispatch");
  290. journal.appendEvent("dwfrun-dispatch", {
  291. type: "node-dispatched",
  292. instance: { siteId: "ask#1", ordinal: 1 },
  293. kind: "ask",
  294. actor,
  295. actorName: "planner",
  296. actorPhaseName: "Prepare",
  297. phaseName: "Work",
  298. instructionsHead: "写一份调研大纲",
  299. } as RunEvent);
  300. // 同一条 journal 上的 world-read 派发:没有 actor,就不该长出会话 id。
  301. journal.appendEvent("dwfrun-dispatch", {
  302. type: "node-dispatched",
  303. instance: { siteId: "world-read#1", ordinal: 1 },
  304. } as RunEvent);
  305. const row = rowOf("dwfrun-dispatch");
  306. const payloads = replayRunProgress(row, journal, CEILING);
  307. const [ask, world] = payloads.filter((payload) => payload.eventType === "node-dispatched");
  308. expect(ask).toMatchObject({
  309. actorSessionId: mintActorSessionId("dwfrun-dispatch", actor),
  310. payload: {
  311. instance: { siteId: "ask#1", ordinal: 1 },
  312. kind: "ask",
  313. actor,
  314. actorName: "planner",
  315. actorPhaseName: "Prepare",
  316. phaseName: "Work",
  317. instructionsHead: "写一份调研大纲",
  318. },
  319. });
  320. // 铸的是与 actor-created 同一个 id:两条事件说的是同一个子代理的同一份转录。
  321. const created = payloads.find((payload) => payload.eventType === "actor-created");
  322. expect(ask?.actorSessionId).toBe(created?.actorSessionId);
  323. expect(world).toMatchObject({ payload: { instance: { siteId: "world-read#1", ordinal: 1 } } });
  324. expect("actorSessionId" in world!).toBe(false);
  325. const live = journal
  326. .listEvents("dwfrun-dispatch", { types: "all", reportItems: "all" })
  327. .map((entry) =>
  328. toProgressPayload({
  329. event: entry.event,
  330. runId: row.runId,
  331. sequence: entry.sequence,
  332. toolCallId: row.toolCallId!,
  333. concurrencyCeiling: CEILING,
  334. }),
  335. );
  336. expect(JSON.stringify(payloads)).toBe(JSON.stringify(live));
  337. });
  338. it("ask 的缓存结算带出生事实与 actorSessionId;world 与 live 的结算不补;冷回放与 live 逐字节相等", () => {
  339. const actor = { siteId: "actor#1", ordinal: 1 };
  340. createRun("dwfrun-cached");
  341. // 导入命中:答案读自前驱的会话。
  342. journal.appendEvent("dwfrun-cached", {
  343. type: "node-settled",
  344. instance: { siteId: "ask#1", ordinal: 1 },
  345. outcome: "ok",
  346. cached: true,
  347. kind: "ask",
  348. actor,
  349. actorSeq: 0,
  350. instructionsHead: "调研",
  351. sourceSessionId: "sess-predecessor",
  352. } as RunEvent);
  353. // 重放命中:答案是本 run 自己跑出来的。
  354. journal.appendEvent("dwfrun-cached", {
  355. type: "node-settled",
  356. instance: { siteId: "ask#2", ordinal: 1 },
  357. outcome: "ok",
  358. cached: true,
  359. kind: "ask",
  360. actor,
  361. actorSeq: 1,
  362. } as RunEvent);
  363. // 没有子代理的两条:world-read 的缓存结算,以及 live 的结算(不是出生事件,不点名子代理)。
  364. journal.appendEvent("dwfrun-cached", {
  365. type: "node-settled",
  366. instance: { siteId: "world-read#1", ordinal: 1 },
  367. outcome: "ok",
  368. cached: true,
  369. } as RunEvent);
  370. journal.appendEvent("dwfrun-cached", {
  371. type: "node-settled",
  372. instance: { siteId: "ask#3", ordinal: 1 },
  373. outcome: "ok",
  374. } as RunEvent);
  375. const row = rowOf("dwfrun-cached");
  376. const payloads = replayRunProgress(row, journal, CEILING);
  377. const settles = payloads.filter((payload) => payload.eventType === "node-settled");
  378. const own = mintActorSessionId("dwfrun-cached", actor);
  379. expect(settles.map((payload) => payload.actorSessionId)).toEqual([
  380. own,
  381. own,
  382. undefined,
  383. undefined,
  384. ]);
  385. // 载荷原样:前驱会话留在载荷里(引擎发了什么),派生字段在载荷之外。
  386. expect(settles[0]).toMatchObject({
  387. payload: { kind: "ask", actor, actorSeq: 0, sourceSessionId: "sess-predecessor" },
  388. });
  389. expect("actorSessionId" in settles[2]!).toBe(false);
  390. expect("actorSessionId" in settles[3]!).toBe(false);
  391. const live = journal
  392. .listEvents("dwfrun-cached", { types: "all", reportItems: "all" })
  393. .map((entry) =>
  394. toProgressPayload({
  395. event: entry.event,
  396. runId: row.runId,
  397. sequence: entry.sequence,
  398. toolCallId: row.toolCallId!,
  399. concurrencyCeiling: CEILING,
  400. }),
  401. );
  402. expect(JSON.stringify(payloads)).toBe(JSON.stringify(live));
  403. // 归约面:两条缓存结算都归到子代理名下;最后一条是本 run 的重放命中,sessionId 指回本 run。
  404. const run = reduce("dwfrun-cached");
  405. expect(run.nodes.filter((node) => node.actorSiteId === "actor#1").map((node) => node.siteId)).toEqual([
  406. "ask#1",
  407. "ask#2",
  408. ]);
  409. expect(run.actors[0]?.sessionId).toBe(own);
  410. });
  411. it("行不是终态(本会话真在飞的 run 由调用方排除;这里是另一进程的)→ 事件原样回放,不追加结算", () => {
  412. createRun("dwfrun-live");
  413. const stored = journal.listEvents("dwfrun-live", { types: "all", reportItems: "all" });
  414. const payloads = replayRunProgress(rowOf("dwfrun-live"), journal, CEILING);
  415. expect(payloads).toHaveLength(stored.length);
  416. expect(payloads.some((payload) => payload.eventType === "run-settled")).toBe(false);
  417. expect(reduce("dwfrun-live").status).toBe("running");
  418. });
  419. });