dynamic-workflow-run-elapsed.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * lineage 活动时长的求和(完成卡的「时间」格,
  3. * docs/dynamic-workflow/transcript-and-notifications.md「How long it took」)。
  4. *
  5. * 回归的缺陷:时长曾只算「结算它的那个进程自己的那一世」,于是一个跑了四小时、被修订过一次的
  6. * run 在完成卡上报几秒——resume 与修订各自重开一次进程内时钟,而那一世大半是缓存重放。
  7. */
  8. import { mkdtemp, rm } from "node:fs/promises";
  9. import { tmpdir } from "node:os";
  10. import { join } from "node:path";
  11. import { afterEach, describe, expect, it, vi } from "vitest";
  12. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  13. import type { JournalStorePort, RunRecord } from "@zcode/dynamic-workflow";
  14. import type { DwfRunLifeSpan } from "@zcode/adapters/storage";
  15. import { runLineageActiveMs } from "../src/app/dynamic-workflow-run-elapsed.js";
  16. import { resolveDynamicWorkflowJournalStore } from "../src/app/dynamic-workflow-run-journal.js";
  17. /** 只实现被读到的两条:一条读世、一条读 lineage 指针。其余方法一律不该被这条求和碰到。 */
  18. function fakeJournal(input: {
  19. lives: Record<string, DwfRunLifeSpan[]>;
  20. resumedFrom?: Record<string, string>;
  21. omitLifeSpans?: boolean;
  22. }): JournalStorePort & { calls: string[] } {
  23. const calls: string[] = [];
  24. const base = {
  25. calls,
  26. getRun(runId: string): RunRecord | undefined {
  27. if (input.lives[runId] === undefined && input.resumedFrom?.[runId] === undefined) {
  28. return undefined;
  29. }
  30. const resumedFrom = input.resumedFrom?.[runId];
  31. return {
  32. runId,
  33. caps: { maxConcurrency: 4 },
  34. spentTokens: 0,
  35. status: "completed",
  36. ...(resumedFrom === undefined ? {} : { resumedFrom }),
  37. } satisfies RunRecord;
  38. },
  39. } as unknown as JournalStorePort & { calls: string[] };
  40. if (input.omitLifeSpans === true) return base;
  41. return Object.assign(base, {
  42. listRunLifeSpans(runId: string): DwfRunLifeSpan[] {
  43. calls.push(runId);
  44. return input.lives[runId] ?? [];
  45. },
  46. });
  47. }
  48. const HOUR = 3_600_000;
  49. describe("runLineageActiveMs", () => {
  50. it("单世 run:就是那一世的墙钟", () => {
  51. const journal = fakeJournal({ lives: { a: [{ startedAt: 1_000, lastActivityAt: 61_000 }] } });
  52. expect(runLineageActiveMs(journal, "a")).toBe(60_000);
  53. });
  54. it("多世 run(resume):逐世相加,世与世之间的死时间不计", () => {
  55. const journal = fakeJournal({
  56. lives: {
  57. a: [
  58. { startedAt: 0, lastActivityAt: HOUR },
  59. // 周末之后才 resume,两分钟后完成。
  60. { startedAt: 200 * HOUR, lastActivityAt: 200 * HOUR + 120_000 },
  61. ],
  62. },
  63. });
  64. expect(runLineageActiveMs(journal, "a")).toBe(HOUR + 120_000);
  65. });
  66. it("修订链:沿 resumedFrom 上溯,前驱的每一世都算进来", () => {
  67. // c 修订自 b,b 修订自 a:用户眼里是同一件工作的第三版。
  68. const journal = fakeJournal({
  69. lives: {
  70. a: [{ startedAt: 0, lastActivityAt: 4 * HOUR }],
  71. b: [{ startedAt: 10 * HOUR, lastActivityAt: 10 * HOUR + HOUR }],
  72. // 修订出来的这一世几乎全是缓存重放——12 秒。
  73. c: [{ startedAt: 20 * HOUR, lastActivityAt: 20 * HOUR + 12_000 }],
  74. },
  75. resumedFrom: { c: "b", b: "a" },
  76. });
  77. expect(runLineageActiveMs(journal, "c")).toBe(4 * HOUR + HOUR + 12_000);
  78. // 前驱自己的卡不受影响:它只报到自己为止。
  79. expect(runLineageActiveMs(journal, "b")).toBe(4 * HOUR + HOUR);
  80. expect(runLineageActiveMs(journal, "a")).toBe(4 * HOUR);
  81. });
  82. it("读面不在场(引擎的内存 journal):undefined,让调用方退回本世", () => {
  83. const journal = fakeJournal({
  84. lives: { a: [{ startedAt: 0, lastActivityAt: HOUR }] },
  85. omitLifeSpans: true,
  86. });
  87. expect(runLineageActiveMs(journal, "a")).toBeUndefined();
  88. });
  89. it("一世都没有(老 run / 行已清理):undefined,不是 0", () => {
  90. const journal = fakeJournal({ lives: {} });
  91. expect(runLineageActiveMs(journal, "a")).toBeUndefined();
  92. // 但确有一世、时长不足 1 毫秒时报的是 0——与「说不出」是两件事。
  93. expect(
  94. runLineageActiveMs(fakeJournal({ lives: { a: [{ startedAt: 5, lastActivityAt: 5 }] } }), "a"),
  95. ).toBe(0);
  96. });
  97. it("前驱行已被清理:本 run 的世照样算,链在读不到的那一跳自然停下", () => {
  98. const journal = fakeJournal({
  99. lives: { c: [{ startedAt: 0, lastActivityAt: 12_000 }] },
  100. resumedFrom: { c: "gone" },
  101. });
  102. expect(runLineageActiveMs(journal, "c")).toBe(12_000);
  103. });
  104. it("墙钟倒退的一世钳到 0,不从别的世里减时间", () => {
  105. const journal = fakeJournal({
  106. lives: {
  107. a: [
  108. { startedAt: 1_000, lastActivityAt: 500 },
  109. { startedAt: 10_000, lastActivityAt: 70_000 },
  110. ],
  111. },
  112. });
  113. expect(runLineageActiveMs(journal, "a")).toBe(60_000);
  114. });
  115. it("自指与成环的 resumedFrom 不会转不出来,每个 run 只读一次", () => {
  116. const selfRef = fakeJournal({
  117. lives: { a: [{ startedAt: 0, lastActivityAt: 1_000 }] },
  118. resumedFrom: { a: "a" },
  119. });
  120. expect(runLineageActiveMs(selfRef, "a")).toBe(1_000);
  121. expect(selfRef.calls).toEqual(["a"]);
  122. const cycle = fakeJournal({
  123. lives: {
  124. a: [{ startedAt: 0, lastActivityAt: 1_000 }],
  125. b: [{ startedAt: 0, lastActivityAt: 2_000 }],
  126. },
  127. resumedFrom: { a: "b", b: "a" },
  128. });
  129. expect(runLineageActiveMs(cycle, "a")).toBe(3_000);
  130. expect(cycle.calls).toEqual(["a", "b"]);
  131. });
  132. it("长链在跳数上限处停下(读一个时长不该扫过任意多行)", () => {
  133. const lives: Record<string, DwfRunLifeSpan[]> = {};
  134. const resumedFrom: Record<string, string> = {};
  135. // 200 跳的链:上限 64,所以求和到第 64 跳为止。
  136. for (let index = 0; index < 200; index += 1) {
  137. lives[`r${index}`] = [{ startedAt: 0, lastActivityAt: 1_000 }];
  138. resumedFrom[`r${index}`] = `r${index + 1}`;
  139. }
  140. const journal = fakeJournal({ lives, resumedFrom });
  141. expect(runLineageActiveMs(journal, "r0")).toBe(64_000);
  142. expect(journal.calls).toHaveLength(64);
  143. });
  144. });
  145. /**
  146. * 生产接线的绊线(与本文件上方的单测互补):走真实的 sqlite session store,即生产那条
  147. * `resolveDynamicWorkflowJournalStore` 路径。
  148. *
  149. * 读面是**能力探测**出来的(它不在引擎的 `JournalStorePort` 上),所以方法名或签名一旦漂移,
  150. * 不会有任何编译错误——只会让时长静默退回「本世」,也就是退回被修的那个 bug。
  151. *
  152. * 时刻由 `appendEvent` 打 `Date.now()`,所以这里只假 `Date`(不动定时器:store 自己可能排程),
  153. * 让一条「跑一小时 → 被重启打断 → 两天后 resume → 两分钟后完成」的 run 在毫秒上完全确定。
  154. */
  155. describe("runLineageActiveMs — 对着真实 sqlite journal", () => {
  156. const CAPS = { maxConcurrency: 4 };
  157. const T0 = Date.UTC(2026, 8, 18, 9, 0, 0);
  158. afterEach(() => {
  159. vi.useRealTimers();
  160. });
  161. /** 在给定时刻追加一条事件。 */
  162. function appendAt(
  163. journal: JournalStorePort,
  164. runId: string,
  165. at: number,
  166. event: "start" | "log" | "settle",
  167. ): void {
  168. vi.setSystemTime(at);
  169. journal.appendEvent(
  170. runId,
  171. event === "start"
  172. ? { type: "run-started", runId, caps: CAPS }
  173. : event === "log"
  174. ? { type: "log", message: "工作中" }
  175. : { type: "run-settled", status: "completed" },
  176. );
  177. }
  178. it("多世 + 修订链:真库上的求和只算活着的那几段", async () => {
  179. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-elapsed-"));
  180. const store = await createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  181. try {
  182. const journal = resolveDynamicWorkflowJournalStore(store as never);
  183. expect(journal).toBeDefined();
  184. vi.useFakeTimers({ toFake: ["Date"] });
  185. // 前驱:第一世跑满一小时后进程死掉(没有 run-settled),两天后 resume,两分钟后完成。
  186. journal!.createRun({ runId: "dwfrun-pred", caps: CAPS, spentTokens: 0, status: "running" });
  187. appendAt(journal!, "dwfrun-pred", T0, "start");
  188. appendAt(journal!, "dwfrun-pred", T0 + 3_600_000, "log");
  189. appendAt(journal!, "dwfrun-pred", T0 + 48 * 3_600_000, "start");
  190. appendAt(journal!, "dwfrun-pred", T0 + 48 * 3_600_000 + 120_000, "settle");
  191. // 修订:新 runId、resumedFrom 指向前驱,这一世 12 秒(几乎全是缓存重放)。
  192. journal!.createRun({
  193. runId: "dwfrun-amended",
  194. caps: CAPS,
  195. spentTokens: 0,
  196. status: "running",
  197. resumedFrom: "dwfrun-pred",
  198. });
  199. appendAt(journal!, "dwfrun-amended", T0 + 72 * 3_600_000, "start");
  200. appendAt(journal!, "dwfrun-amended", T0 + 72 * 3_600_000 + 12_000, "settle");
  201. // 前驱自己:一小时 + 两分钟(两世之间那 47 小时死时间不计)。
  202. expect(runLineageActiveMs(journal!, "dwfrun-pred")).toBe(3_600_000 + 120_000);
  203. // 修订:整条 lineage。被修的 bug 会在这里报 12_000。
  204. expect(runLineageActiveMs(journal!, "dwfrun-amended")).toBe(3_600_000 + 120_000 + 12_000);
  205. } finally {
  206. vi.useRealTimers();
  207. store.close();
  208. await rm(tempRoot, { force: true, recursive: true });
  209. }
  210. });
  211. });