dynamic-workflow-report-reads.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // 宿主侧读 journal 的形状(docs/execution-engine.md「Reading the journal」):report item 只在
  2. // 要显示时才离开存储层,而且只取显示得下的那么多。
  3. //
  4. // - 冷回放:本 run 第 64 条之后的 report 事件不带 item 读回,归约结果与读全量逐字节相同
  5. // (docs/dynamic-workflow/presentation.md「Cold replay」);
  6. // - 修订导入:一条 report 行都不读,前驱报没报过、报了多少,导入表都一样;
  7. // - 规模:一个报满 65,536 条的 run,终态快照 / 产物清单 / 冷回放 / GetWorkflowRun / 修订导入
  8. // 加起来,交到 JS 手里的 report item 恰好是 256 + 64 + 64 条。
  9. import { mkdtemp, rm } from "node:fs/promises";
  10. import { tmpdir } from "node:os";
  11. import { join } from "node:path";
  12. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  13. import { createSqliteSessionStore, type DwfRunSessionListItem } from "@zcode/adapters/storage";
  14. import {
  15. ALL_EVENTS,
  16. InMemoryJournalStore,
  17. type JournalStorePort,
  18. type ListNodesOptions,
  19. type NodeRecord,
  20. type RunEvent,
  21. type StoredEvent,
  22. } from "@zcode/dynamic-workflow";
  23. import {
  24. readWorkflowArtifactField,
  25. reduceWorkflowRunsState,
  26. type WorkflowRunsState,
  27. } from "@zcode/shared/zcode-protocol-v4";
  28. import { buildImportedCache, preflightAmendImport } from "../src/app/dynamic-workflow-import.js";
  29. import { listArtifactItemsFrom } from "../src/app/dynamic-workflow-run-artifact-queries.js";
  30. import { artifactsOf, snapshotOf } from "../src/app/dynamic-workflow-run-observation.js";
  31. import {
  32. COLD_REPLAY_EVENT_READ,
  33. replayRunProgress,
  34. replayRunProgressFromEvents,
  35. } from "../src/app/dynamic-workflow-run-replay.js";
  36. import { createRunIntrospectionMethods } from "../src/app/dynamic-workflow-run-introspection.js";
  37. import type { DynamicWorkflowIntrospectableJournal } from "../src/app/dynamic-workflow-run-journal.js";
  38. import { resolveDynamicWorkflowJournalStore } from "../src/app/dynamic-workflow-run-service.js";
  39. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  40. const PARENT = "sess_report_reads";
  41. const CEILING = 6;
  42. type SqliteJournal = JournalStorePort & {
  43. listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[];
  44. };
  45. let tempRoot: string;
  46. let store: ReturnType<typeof createSqliteSessionStore>;
  47. let journal: SqliteJournal;
  48. beforeEach(async () => {
  49. tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-report-reads-"));
  50. store = createSqliteSessionStore({ dbPath: join(tempRoot, "session.sqlite") });
  51. const resolved = resolveDynamicWorkflowJournalStore(store as never);
  52. if (resolved === undefined) throw new Error("sqlite store must expose the dwf journal");
  53. journal = resolved as SqliteJournal;
  54. });
  55. afterEach(async () => {
  56. await store.close?.();
  57. await rm(tempRoot, { force: true, recursive: true });
  58. });
  59. function createRun(runId: string, status: "running" | "completed" = "running"): void {
  60. journal.createRun({
  61. runId,
  62. parentSessionId: PARENT,
  63. cwd: "/repo",
  64. toolCallId: `call-${runId}`,
  65. scriptText: "report(1);",
  66. scriptHash: "sha-r",
  67. caps: { maxConcurrency: 4 },
  68. spentTokens: 0,
  69. status,
  70. });
  71. }
  72. function started(runId: string): void {
  73. journal.appendEvent(runId, {
  74. type: "run-started",
  75. runId,
  76. caps: { maxConcurrency: 4 },
  77. } as RunEvent);
  78. }
  79. /** 一条 report:节点行 + 事件,与引擎的「一次写 + 一个事件」同形。 */
  80. function report(runId: string, ordinal: number, item: unknown, artifactId?: string): void {
  81. journal.putNode({
  82. runId,
  83. siteId: "report#1",
  84. ordinal,
  85. kind: "report",
  86. inputHash: `h-${ordinal}`,
  87. status: "completed",
  88. result: item,
  89. ...(artifactId === undefined ? {} : { artifactId }),
  90. });
  91. journal.appendEvent(runId, {
  92. type: "report",
  93. instance: { siteId: "report#1", ordinal },
  94. item,
  95. ...(artifactId === undefined ? {} : { artifactId }),
  96. });
  97. }
  98. function declareChart(runId: string): void {
  99. const artifact = { id: "perf", kind: "chart", version: 1, publishedAt: 1, spec: {} };
  100. journal.putNode({
  101. runId,
  102. siteId: "artifact#1",
  103. ordinal: 1,
  104. kind: "artifact",
  105. inputHash: "h-artifact",
  106. status: "completed",
  107. artifactId: "perf",
  108. result: artifact,
  109. });
  110. journal.appendEvent(runId, {
  111. type: "artifact-published",
  112. instance: { siteId: "artifact#1", ordinal: 1 },
  113. artifact,
  114. } as unknown as RunEvent);
  115. }
  116. function rowOf(runId: string): DwfRunSessionListItem {
  117. const row = journal.listRunsByParentSession(PARENT, 8).find((item) => item.runId === runId);
  118. if (row === undefined) throw new Error(`row missing for ${runId}`);
  119. return row;
  120. }
  121. function reduce(runId: string, stored: readonly StoredEvent[]): WorkflowRunsState["runs"][number] {
  122. let state: WorkflowRunsState | undefined;
  123. for (const payload of replayRunProgressFromEvents(rowOf(runId), stored, CEILING)) {
  124. state = reduceWorkflowRunsState(state, payload) ?? state;
  125. }
  126. const run = state?.runs.find((item) => item.runId === runId);
  127. if (run === undefined) throw new Error("run not projected");
  128. return run;
  129. }
  130. function hasItem(stored: StoredEvent): boolean {
  131. return stored.event.type === "report" && "item" in stored.event;
  132. }
  133. describe("cold replay reads report items only up to the projection's bound", () => {
  134. it("reduces to the same state from stripped events as from the full log, across two lives", () => {
  135. const runId = "dwfrun-many-reports";
  136. createRun(runId);
  137. started(runId);
  138. declareChart(runId);
  139. // 第一世 90 条(每三条一条打标签),停下;第二世再 60 条,结算。
  140. for (let ordinal = 1; ordinal <= 90; ordinal += 1) {
  141. report(
  142. runId,
  143. ordinal,
  144. { finding: ordinal, pad: "x".repeat(200) },
  145. ordinal % 3 === 0 ? "perf" : undefined,
  146. );
  147. }
  148. journal.appendEvent(runId, {
  149. type: "run-settled",
  150. status: "stopped",
  151. stopReason: "user",
  152. } as RunEvent);
  153. started(runId);
  154. for (let ordinal = 91; ordinal <= 150; ordinal += 1) {
  155. report(runId, ordinal, `line ${ordinal}`, ordinal % 3 === 0 ? "perf" : undefined);
  156. }
  157. journal.updateRunStatus(runId, "completed");
  158. const full = journal.listEvents(runId, ALL_EVENTS);
  159. const stripped = journal.listEvents(runId, COLD_REPLAY_EVENT_READ);
  160. // 这条用例确实走到了剥离:前 64 条 report 带 item,其余 86 条不带;事件条数不变。
  161. expect(stripped).toHaveLength(full.length);
  162. expect(stripped.filter(hasItem)).toHaveLength(64);
  163. expect(stripped.filter((stored) => stored.event.type === "report")).toHaveLength(150);
  164. const fromFull = reduce(runId, full);
  165. const fromStripped = reduce(runId, stripped);
  166. expect(fromStripped).toEqual(fromFull);
  167. // 归约结果本身说得通:64 条预览、被截断、看板数到了全部 50 条标签。
  168. expect(fromStripped.reports).toHaveLength(64);
  169. expect(fromStripped.truncated).toBe(true);
  170. expect(fromStripped.artifacts?.find((artifact) => artifact.id === "perf")?.itemCount).toBe(50);
  171. // 生产入口就是这条读。
  172. let viaEntry: WorkflowRunsState | undefined;
  173. for (const payload of replayRunProgress(rowOf(runId), journal, CEILING)) {
  174. viaEntry = reduceWorkflowRunsState(viaEntry, payload) ?? viaEntry;
  175. }
  176. expect(viaEntry?.runs.find((run) => run.runId === runId)).toEqual(fromFull);
  177. });
  178. });
  179. describe("amend import never reads report rows", () => {
  180. function seedPredecessor(target: JournalStorePort, reports: number): void {
  181. target.createRun({
  182. runId: "runA",
  183. caps: { maxConcurrency: 4 },
  184. spentTokens: 0,
  185. status: "completed",
  186. });
  187. target.putActor({
  188. runId: "runA",
  189. siteId: "actor#1",
  190. ordinal: 1,
  191. name: "worker",
  192. persona: { name: "worker", system: "you work" },
  193. sessionId: "ses_a",
  194. });
  195. for (let seq = 0; seq < 3; seq += 1) {
  196. target.putNode({
  197. runId: "runA",
  198. siteId: "ask#1",
  199. ordinal: seq + 1,
  200. kind: "ask",
  201. actorSiteId: "actor#1",
  202. actorOrdinal: 1,
  203. actorSeq: seq,
  204. inputHash: `ask-${seq}`,
  205. status: "completed",
  206. result: `answer ${seq}`,
  207. messageBoundary: (seq + 1) * 2,
  208. });
  209. }
  210. target.putNode({
  211. runId: "runA",
  212. siteId: "files.grep#1",
  213. ordinal: 1,
  214. kind: "world-read",
  215. inputHash: "grep-1",
  216. status: "completed",
  217. result: ["a.ts:1"],
  218. });
  219. for (let ordinal = 1; ordinal <= reports; ordinal += 1) {
  220. target.putNode({
  221. runId: "runA",
  222. siteId: "report#1",
  223. ordinal,
  224. kind: "report",
  225. inputHash: `r-${ordinal}`,
  226. status: "completed",
  227. result: { big: "x".repeat(512) },
  228. });
  229. }
  230. }
  231. class SpyJournal extends InMemoryJournalStore {
  232. readonly reads: ListNodesOptions[] = [];
  233. override listNodes(runId: string, opts: ListNodesOptions): NodeRecord[] {
  234. this.reads.push(opts);
  235. return super.listNodes(runId, opts);
  236. }
  237. }
  238. it("builds the same cache whether or not the predecessor reported, without touching report rows", async () => {
  239. const quiet = new SpyJournal();
  240. seedPredecessor(quiet, 0);
  241. const loud = new SpyJournal();
  242. seedPredecessor(loud, 300);
  243. expect(preflightAmendImport(loud, "runA")).toMatchObject({ ok: true });
  244. const a = await buildImportedCache({ journal: quiet }, "runA");
  245. const b = await buildImportedCache({ journal: loud }, "runA");
  246. expect(b).toEqual(a);
  247. expect(b.ok).toBe(true);
  248. for (const read of loud.reads) {
  249. expect(read.kinds).not.toBe("all");
  250. expect(read.kinds).not.toContain("report");
  251. }
  252. });
  253. });
  254. describe("a run that reported 65,536 items", () => {
  255. /** 包一层:数一数经这些读交到 JS 手里的 report item(节点行的 result、事件的 item)。 */
  256. function countingJournal(target: SqliteJournal): { journal: SqliteJournal; items: () => number } {
  257. let items = 0;
  258. const proxy = new Proxy(target, {
  259. get(obj, prop, receiver) {
  260. const value = Reflect.get(obj, prop, receiver) as unknown;
  261. if (typeof value !== "function") return value;
  262. const fn = value as (...args: unknown[]) => unknown;
  263. return (...args: unknown[]) => {
  264. const out = fn.apply(obj, args);
  265. if (prop === "listNodes" || prop === "getNode") {
  266. const rows = (
  267. Array.isArray(out) ? out : out === undefined ? [] : [out]
  268. ) as NodeRecord[];
  269. items += rows.filter((row) => row.kind === "report" && "result" in row).length;
  270. }
  271. if (prop === "listEvents") items += (out as StoredEvent[]).filter(hasItem).length;
  272. return out;
  273. };
  274. },
  275. });
  276. return { journal: proxy, items: () => items };
  277. }
  278. it("hands 256 + 64 + 64 items to the host across snapshot, artifacts, cold replay, GetWorkflowRun and amend", async () => {
  279. const runId = "dwfrun-65536";
  280. const total = 65_536;
  281. createRun(runId);
  282. started(runId);
  283. declareChart(runId);
  284. for (let ordinal = 1; ordinal <= total; ordinal += 1) {
  285. report(runId, ordinal, { n: ordinal }, ordinal % 2 === 0 ? "perf" : undefined);
  286. }
  287. journal.updateRunStatus(runId, "completed");
  288. const counted = countingJournal(journal);
  289. // 冷行(本进程注册表里没有条目):终态快照全部从 journal 读。
  290. const snapshot = snapshotOf(runId, new Map(), counted.journal);
  291. expect(snapshot?.reportCount).toBe(total);
  292. expect(snapshot?.reports).toHaveLength(256);
  293. expect(snapshot?.artifacts?.[0]?.itemCount).toBe(total / 2);
  294. expect(artifactsOf(runId, counted.journal).artifacts?.[0]?.itemCount).toBe(total / 2);
  295. let state: WorkflowRunsState | undefined;
  296. for (const payload of replayRunProgress(rowOf(runId), counted.journal, CEILING)) {
  297. state = reduceWorkflowRunsState(state, payload) ?? state;
  298. }
  299. const run = state?.runs.find((item) => item.runId === runId);
  300. expect(run?.reports).toHaveLength(64);
  301. expect(run?.artifacts?.find((artifact) => artifact.id === "perf")?.itemCount).toBe(total / 2);
  302. // GetWorkflowRun:与冷回放同一条事件读(64 条 item),节点行不带结果、不读 report。
  303. const { getRunDetail } = createRunIntrospectionMethods({
  304. introspection: counted.journal as unknown as DynamicWorkflowIntrospectableJournal,
  305. journal: counted.journal,
  306. parentSessionId: PARENT,
  307. runs: new Map(),
  308. escalations: createWorkflowEscalationRegistry(),
  309. defaultConcurrency: () => CEILING,
  310. });
  311. const detail = await getRunDetail(runId);
  312. expect(detail?.status).toBe("completed");
  313. expect(detail?.artifacts?.[0]?.itemCount).toBe(total / 2);
  314. expect(preflightAmendImport(counted.journal, runId)).toMatchObject({ ok: true });
  315. await buildImportedCache({ journal: counted.journal }, runId);
  316. // 快照 256 + 冷回放 64 + GetWorkflowRun 64;产物清单与修订导入一条不读。
  317. expect(counted.items()).toBe(256 + 64 + 64);
  318. }, 120_000);
  319. });
  320. describe("report item size: 1 MiB items stay out of JavaScript except where they are shown", () => {
  321. // docs/execution-engine.md「Progressive results: `report`」与「Reading the journal」:单条上限
  322. // 1 MiB 之后,「只读前 N 条」管不住字节——每个读者还得有字节界。这里数的是真正交到 JS 手里
  323. // 的 report 载荷字节(节点行的 result、事件的 item、看板条目的 item / fields)。
  324. const ITEM_PAD = 1_000_000;
  325. const TOTAL = 40;
  326. function payloadBytes(value: unknown): number {
  327. return value === undefined ? 0 : Buffer.byteLength(JSON.stringify(value));
  328. }
  329. function byteCountingJournal(target: SqliteJournal): {
  330. journal: SqliteJournal;
  331. bytes: () => number;
  332. reset: () => void;
  333. } {
  334. let bytes = 0;
  335. const proxy = new Proxy(target, {
  336. get(obj, prop, receiver) {
  337. const value = Reflect.get(obj, prop, receiver);
  338. if (typeof value !== "function") return value;
  339. return (...args: unknown[]) => {
  340. const out = (value as (...inner: unknown[]) => unknown).apply(obj, args);
  341. if (prop === "listNodes" || prop === "getNode") {
  342. const rows = (
  343. Array.isArray(out) ? out : out === undefined ? [] : [out]
  344. ) as NodeRecord[];
  345. for (const row of rows) if (row.kind === "report") bytes += payloadBytes(row.result);
  346. }
  347. if (prop === "listEvents" || prop === "listEventPage") {
  348. const events = (
  349. prop === "listEvents" ? out : (out as { events: StoredEvent[] }).events
  350. ) as StoredEvent[];
  351. for (const stored of events) {
  352. if (stored.event.type === "report")
  353. bytes += payloadBytes((stored.event as { item?: unknown }).item);
  354. }
  355. }
  356. if (prop === "listArtifactItems") {
  357. for (const entry of (out as { items: Array<{ item?: unknown; fields?: unknown }> })
  358. .items) {
  359. bytes += payloadBytes(entry.item) + payloadBytes(entry.fields);
  360. }
  361. }
  362. return out;
  363. };
  364. },
  365. });
  366. return { journal: proxy, bytes: () => bytes, reset: () => (bytes = 0) };
  367. }
  368. it("bounds the snapshot at 8 MiB, dashboard and event-log pages at 4 MiB, and a field read at the fields", async () => {
  369. const runId = "dwfrun-big-items";
  370. createRun(runId);
  371. started(runId);
  372. declareChart(runId);
  373. for (let ordinal = 1; ordinal <= TOTAL; ordinal += 1) {
  374. report(
  375. runId,
  376. ordinal,
  377. { n: ordinal, pad: "x".repeat(ITEM_PAD) },
  378. ordinal % 2 === 0 ? "perf" : undefined,
  379. );
  380. }
  381. journal.updateRunStatus(runId, "completed");
  382. const counted = byteCountingJournal(journal);
  383. const MiB = 1024 * 1024;
  384. // 终态快照:前若干条、至多 8 MiB(每条约 1 MB,所以 8 条),总数照实。
  385. const snapshot = snapshotOf(runId, new Map(), counted.journal);
  386. expect(snapshot?.reportCount).toBe(TOTAL);
  387. expect(snapshot?.reports).toHaveLength(8);
  388. expect(counted.bytes()).toBeLessThanOrEqual(8 * MiB);
  389. // 看板只取字段:20 条标签 report 一页装下,交到 JS 的只有 20 个小数字。
  390. counted.reset();
  391. const fieldPage = listArtifactItemsFrom(counted.journal, runId, "perf", {
  392. limit: 200,
  393. maxBytes: 4 * MiB,
  394. fields: ["n"],
  395. });
  396. expect(fieldPage.items.map((entry) => entry.fields?.n)).toEqual(
  397. Array.from({ length: TOTAL / 2 }, (_v, index) => (index + 1) * 2),
  398. );
  399. expect(fieldPage.hasMore).toBe(false);
  400. expect(counted.bytes()).toBeLessThan(1024);
  401. // 看板取整条(老渲染器):一页至多 4 MiB,于是 4 条、并报 hasMore。
  402. counted.reset();
  403. const wholePage = listArtifactItemsFrom(counted.journal, runId, "perf", {
  404. limit: 200,
  405. maxBytes: 4 * MiB,
  406. });
  407. expect(wholePage.items).toHaveLength(4);
  408. expect(wholePage.hasMore).toBe(true);
  409. expect(counted.bytes()).toBeLessThanOrEqual(4 * MiB);
  410. // 事件日志一页:同样至多 4 MiB。
  411. counted.reset();
  412. const eventPage = (
  413. counted.journal as unknown as DynamicWorkflowIntrospectableJournal
  414. ).listEventPage(runId, {
  415. limit: 500,
  416. maxBytes: 4 * MiB,
  417. });
  418. expect(eventPage.hasMore).toBe(true);
  419. expect(counted.bytes()).toBeLessThanOrEqual(4 * MiB);
  420. // resume 恢复的字节计数:sum(octet_length(result_json)),与写入时 JSON.stringify 的字节相同。
  421. const expected = Array.from({ length: TOTAL }, (_v, index) =>
  422. payloadBytes({ n: index + 1, pad: "x".repeat(ITEM_PAD) }),
  423. ).reduce((sum, value) => sum + value, 0);
  424. expect(journal.sumResultBytes(runId, "report")).toBe(expected);
  425. }, 120_000);
  426. it("extracts fields in SQLite exactly as the renderer reads them from the whole item", () => {
  427. // 路径规则是协议上的契约(readWorkflowArtifactField):CLI 在 SQLite 里取、渲染器在 JS 里
  428. // 取,同一条 item、同一条路径必须得到同一个值(走不通 = 表里没有这个键)。
  429. const runId = "dwfrun-field-parity";
  430. createRun(runId);
  431. started(runId);
  432. declareChart(runId);
  433. const items: unknown[] = [
  434. { a: { b: 1 }, list: [10, { c: "deep" }], flag: false, none: null },
  435. { a: [{ b: 2 }], list: { "0": "key-zero", "1": { c: "obj" } }, "": { x: 5 } },
  436. [{ a: 3 }, "tail"],
  437. "just a string",
  438. 42,
  439. null,
  440. {
  441. weird: { "1e0": "sci", "01": "lead", "-1": "neg" },
  442. arr: [
  443. [1, 2],
  444. [3, [4, 5]],
  445. ],
  446. },
  447. ];
  448. items.forEach((item, index) => report(runId, index + 1, item, "perf"));
  449. const paths = [
  450. "a.b",
  451. "a.0.b",
  452. "list.0",
  453. "list.1.c",
  454. "flag",
  455. "none",
  456. "missing",
  457. ".x",
  458. "0.a",
  459. "1",
  460. "weird.1e0",
  461. "weird.01",
  462. "weird.-1",
  463. "arr.1.1.0",
  464. "arr.1e0.0",
  465. "arr.01.1.1",
  466. "a.b.c",
  467. ];
  468. const page = listArtifactItemsFrom(journal, runId, "perf", {
  469. limit: 50,
  470. maxBytes: 1 << 30,
  471. fields: paths,
  472. });
  473. expect(page.items).toHaveLength(items.length);
  474. page.items.forEach((entry, index) => {
  475. const expected: Record<string, unknown> = {};
  476. for (const path of paths) {
  477. const value = readWorkflowArtifactField(items[index], path);
  478. if (value !== undefined) expected[path] = value;
  479. }
  480. expect(entry.fields, `item ${index}`).toEqual(expected);
  481. });
  482. });
  483. });