dwf-journal-store.test.ts 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111
  1. import {
  2. applySqliteSchemaMigration,
  3. ensureSqliteSchemaMigrationTable,
  4. } from "@zcode/shared/sqlite-migrations";
  5. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  6. /**
  7. * SQLite 版 JournalStorePort(dwf_* 表)的测试。
  8. *
  9. * 两层:共享契约套件(与内存实现同一份,来自 `@zcode/dynamic-workflow/testing`)+
  10. * 内存实现根本表达不了的 SQLite 专属语义——跨进程重开后记录还在、事件序号接着长、
  11. * run 删除级联清掉 actor/node/event。后者才是 roadmap step 8 的真正目的。
  12. */
  13. import { mkdtemp, readFile, rm } from "node:fs/promises";
  14. import { tmpdir } from "node:os";
  15. import { join } from "node:path";
  16. import { DatabaseSync } from "node:sqlite";
  17. import { afterAll, describe, expect, it, vi } from "vitest";
  18. import type {
  19. ActorRecord,
  20. Caps,
  21. JournalStorePort,
  22. NodeRecord,
  23. RunRecord,
  24. } from "@zcode/dynamic-workflow";
  25. import { runJournalStoreContract } from "@zcode/dynamic-workflow/testing";
  26. import type { DwfRunIntrospectionQueries, DwfRunSessionListItem } from "../src/storage/index.js";
  27. import { createDwfJournalStore, createSqliteSessionStore } from "../src/storage/index.js";
  28. import { runSqliteSessionMigrations } from "../src/storage/session-store/migration-runner.js";
  29. const openDatabases: DatabaseSync[] = [];
  30. /** 每次调用开一个全新的已迁移库;契约套件要求实现之间互不共享状态。 */
  31. function openJournalDb(dbPath = ":memory:"): { db: DatabaseSync; journal: JournalStorePort } {
  32. const db = new DatabaseSync(dbPath);
  33. openDatabases.push(db);
  34. // Journal 同步工厂只装载冻结 schema;异步启动、备份与锁由迁移专用测试验证。
  35. db.exec("BEGIN IMMEDIATE");
  36. ensureSqliteSchemaMigrationTable(db);
  37. for (const migration of SQLITE_MIGRATIONS) applySqliteSchemaMigration(db, migration);
  38. db.exec("COMMIT");
  39. return { db, journal: createDwfJournalStore(db) };
  40. }
  41. afterAll(() => {
  42. for (const db of openDatabases) {
  43. try {
  44. db.close();
  45. } catch {
  46. // 测试用库;关闭失败不该掩盖真正的断言失败。
  47. }
  48. }
  49. });
  50. runJournalStoreContract(() => openJournalDb().journal);
  51. const CAPS: Caps = { maxConcurrency: 4 };
  52. const RUN: RunRecord = {
  53. runId: "dwf_run_1",
  54. parentSessionId: "ses_parent",
  55. cwd: "/repo",
  56. scriptText: "const planner = agent('planner');",
  57. scriptHash: "sha-1",
  58. caps: CAPS,
  59. spentTokens: 0,
  60. status: "running",
  61. };
  62. const ACTOR: ActorRecord = {
  63. runId: RUN.runId,
  64. siteId: "actor#1",
  65. ordinal: 1,
  66. name: "planner",
  67. persona: { name: "planner", system: "plan carefully" },
  68. sessionId: "ses_actor",
  69. // 冻结的 persona 与子代理实际跑的模型分列存放,两者都必须跨重开存活。
  70. resolvedModel: "anthropic/haiku",
  71. };
  72. const NODE: NodeRecord = {
  73. runId: RUN.runId,
  74. siteId: "ask#1",
  75. ordinal: 1,
  76. kind: "ask",
  77. actorSiteId: "actor#1",
  78. actorOrdinal: 1,
  79. actorSeq: 0,
  80. inputHash: "abc123",
  81. status: "completed",
  82. result: { plan: ["step one", "step two"], nested: { depth: 2 } },
  83. stats: { tokens: 120, toolCalls: 2, turns: 1 },
  84. };
  85. describe("SQLite dwf journal store", () => {
  86. it("survives closing and reopening the database file", async () => {
  87. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-"));
  88. const dbPath = join(tempRoot, "session.sqlite");
  89. try {
  90. const first = await createSqliteSessionStore({ dbPath });
  91. const journal = first.workflowJournalStore();
  92. journal.createRun(RUN);
  93. journal.putActor(ACTOR);
  94. journal.putNode(NODE);
  95. journal.appendEvent(RUN.runId, { type: "run-started", runId: RUN.runId, caps: CAPS });
  96. journal.appendEvent(RUN.runId, { type: "log", message: "before the crash" });
  97. // 结算前最后一次用量回写:resume 必须看到它,而不是从零重来。
  98. journal.updateRunUsage(RUN.runId, 120);
  99. first.close();
  100. const second = await createSqliteSessionStore({ dbPath });
  101. const resumed = second.workflowJournalStore();
  102. expect(resumed.getRun(RUN.runId)).toEqual({ ...RUN, spentTokens: 120 });
  103. expect(resumed.getActor(RUN.runId, "actor#1", 1)).toEqual(ACTOR);
  104. expect(resumed.getNode(RUN.runId, "ask#1", 1)).toEqual(NODE);
  105. expect(resumed.listActors(RUN.runId, { withPersona: true })).toEqual([ACTOR]);
  106. expect(resumed.listNodes(RUN.runId, { kinds: "all", withResult: true })).toEqual([NODE]);
  107. expect(
  108. resumed.listEvents(RUN.runId, { types: "all", reportItems: "all" }).map((e) => e.sequence),
  109. ).toEqual([0, 1]);
  110. // 事件序号跨重开继续增长(engine-assigned、monotonic across resumes)。
  111. // 断言用 toMatchObject:追加还会带回写入时刻(StoredEvent.timeCreated),而这条用例
  112. // 说的是序号,不是时钟——时钟由契约套件的 timeCreated 用例钉住。
  113. expect(
  114. resumed.appendEvent(RUN.runId, { type: "log", message: "after resume" }),
  115. ).toMatchObject({
  116. sequence: 2,
  117. event: { type: "log", message: "after resume" },
  118. });
  119. expect(
  120. resumed.listEvents(RUN.runId, { types: "all", reportItems: "all" }).at(-1)?.event,
  121. ).toEqual({
  122. type: "log",
  123. message: "after resume",
  124. });
  125. second.close();
  126. } finally {
  127. await rm(tempRoot, { force: true, recursive: true });
  128. }
  129. });
  130. // `caps_max_concurrency` 的第二个写入者(docs/dynamic-workflow/concurrency.md
  131. // 「Two bounds on a run」)。契约套件已经钉住读写语义;这里钉的是内存实现表达不了的两件事:
  132. // UPDATE 真的只列了这一列(其余列逐字不动),以及新值跨进程重开还在——resume 沿用的正是它。
  133. it("retunes caps_max_concurrency in place, touching no other column", async () => {
  134. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-journal-caps-"));
  135. const dbPath = join(tempRoot, "session.sqlite");
  136. try {
  137. const first = await createSqliteSessionStore({ dbPath });
  138. const journal = first.workflowJournalStore();
  139. journal.createRun(RUN);
  140. journal.updateRunUsage(RUN.runId, 120);
  141. journal.updateRunCaps(RUN.runId, { maxConcurrency: 2 });
  142. // 同一个库里,除 caps 之外的每一列都还是建 run 时的那一份。
  143. expect(journal.getRun(RUN.runId)).toEqual({
  144. ...RUN,
  145. caps: { maxConcurrency: 2 },
  146. spentTokens: 120,
  147. });
  148. first.close();
  149. const second = await createSqliteSessionStore({ dbPath });
  150. expect(second.workflowJournalStore().getRun(RUN.runId)?.caps).toEqual({ maxConcurrency: 2 });
  151. second.close();
  152. } finally {
  153. await rm(tempRoot, { force: true, recursive: true });
  154. }
  155. });
  156. it("cascades a run delete to its actors, nodes and events", async () => {
  157. const { db, journal } = openJournalDb();
  158. journal.createRun(RUN);
  159. journal.createRun({ ...RUN, runId: "dwf_run_2" });
  160. journal.putActor(ACTOR);
  161. journal.putNode(NODE);
  162. journal.appendEvent(RUN.runId, { type: "log", message: "doomed" });
  163. journal.putActor({ ...ACTOR, runId: "dwf_run_2" });
  164. db.prepare("delete from dwf_run where id = ?").run(RUN.runId);
  165. expect(journal.getRun(RUN.runId)).toBeUndefined();
  166. expect(journal.listActors(RUN.runId, { withPersona: true })).toEqual([]);
  167. expect(journal.listNodes(RUN.runId, { kinds: "all", withResult: true })).toEqual([]);
  168. expect(journal.listEvents(RUN.runId, { types: "all", reportItems: "all" })).toEqual([]);
  169. // 级联只吃掉被删 run 的行。
  170. expect(journal.listActors("dwf_run_2", { withPersona: true })).toHaveLength(1);
  171. });
  172. it("rejects an actor belonging to no run", async () => {
  173. // FK 是开着的(migration runner 设 pragma foreign_keys = on),孤儿写入必须当场失败,
  174. // 而不是留下一条永远读不回来的记录。孤儿事件与 null/absent result 的语义已由共享契约
  175. // 套件在两个实现上一起把关,这里只补 FK 本身确实生效这一点。
  176. const { journal } = openJournalDb();
  177. expect(() => journal.putActor({ ...ACTOR, runId: "ghost" })).toThrow();
  178. });
  179. it("run 产物跨重开数据库文件存活", async () => {
  180. const tempRoot = await mkdtemp(join(tmpdir(), "zcode-dwf-result-"));
  181. const dbPath = join(tempRoot, "session.sqlite");
  182. try {
  183. const first = await createSqliteSessionStore({ dbPath });
  184. const journal = first.workflowJournalStore();
  185. journal.createRun(RUN);
  186. journal.updateRunStatus(RUN.runId, "completed", {
  187. result: { report: "done", steps: [1, 2, 3] },
  188. });
  189. first.close();
  190. // 桌面实测 bug 的持久化面:进程一退,产物必须仍能从 journal 读回来。
  191. const second = await createSqliteSessionStore({ dbPath });
  192. const resumed = second.workflowJournalStore().getRun(RUN.runId);
  193. expect(resumed?.status).toBe("completed");
  194. expect(resumed?.result).toEqual({ report: "done", steps: [1, 2, 3] });
  195. second.close();
  196. } finally {
  197. await rm(tempRoot, { force: true, recursive: true });
  198. }
  199. });
  200. it("result_json 为 NULL 的旧行解码不炸且 result 缺席", async () => {
  201. // 0020 之前落库的 run 行:列是新加的、值为 NULL。decodeRun 必须回一条没有 result 键的
  202. // 记录,而不是 undefined 值或抛错——否则升级后所有历史 run 都读不出来。
  203. const { db, journal } = openJournalDb();
  204. journal.createRun(RUN);
  205. db.prepare("update dwf_run set result_json = null where id = ?").run(RUN.runId);
  206. const record = journal.getRun(RUN.runId);
  207. expect(record).toEqual(RUN);
  208. expect("result" in (record ?? {})).toBe(false);
  209. });
  210. it("resolved_model 为 NULL 的旧行解码不炸且 resolvedModel 缺席", async () => {
  211. // 0023 之前落库的 actor 行(以及宿主还没解析过的行):必须解成没有 resolvedModel 键的
  212. // 记录,而不是 undefined 值或抛错。persona 里的档位与这一列各自独立缺席。
  213. const { db, journal } = openJournalDb();
  214. journal.createRun(RUN);
  215. journal.putActor(ACTOR);
  216. db.prepare("update dwf_actor set resolved_model = null where run_id = ?").run(RUN.runId);
  217. const record = journal.getActor(RUN.runId, "actor#1", 1);
  218. expect(record).toEqual({ ...ACTOR, resolvedModel: undefined });
  219. expect("resolvedModel" in (record ?? {})).toBe(false);
  220. // persona 仍在 persona_json 里:模型记录丢了不等于身份丢了。
  221. expect(record?.persona?.system).toBe("plan carefully");
  222. });
  223. it("同键重写只换 resolved_model,persona 与 session_id 原样保留", async () => {
  224. // 生产里这正是 driver 侧 `journalActorResolvedModel` 的读改写形状:putActor 是整条替换,
  225. // 所以「只更新解析结果」必须由调用方带齐其余字段,而存储层要如实照写。
  226. const { journal } = openJournalDb();
  227. journal.createRun(RUN);
  228. journal.putActor(ACTOR);
  229. journal.putActor({ ...ACTOR, resolvedModel: "anthropic/sonnet" });
  230. expect(journal.getActor(RUN.runId, "actor#1", 1)).toEqual({
  231. ...ACTOR,
  232. resolvedModel: "anthropic/sonnet",
  233. });
  234. expect(journal.listActors(RUN.runId, { withPersona: true })).toHaveLength(1);
  235. });
  236. it("终态与产物一笔写:单条 UPDATE 同时落 status 与 result_json", async () => {
  237. // 分两笔写会造出「completed 但产物丢失」的崩溃窗口,正是本列要关死的损失类别。
  238. const { db, journal } = openJournalDb();
  239. journal.createRun(RUN);
  240. journal.updateRunStatus(RUN.runId, "completed", { result: "artifact text" });
  241. const row = db
  242. .prepare("select status, result_json from dwf_run where id = ?")
  243. .get(RUN.runId) as { result_json: string | null; status: string } | undefined;
  244. expect(row?.status).toBe("completed");
  245. expect(row?.result_json).toBe(JSON.stringify("artifact text"));
  246. });
  247. it("CHECK 仍然拒绝一个不存在的 kind", async () => {
  248. // 重建 CHECK 的意义在于它**还在拦**:放开一个值不等于把闸门拆了。
  249. const { journal } = openJournalDb();
  250. journal.createRun(RUN);
  251. expect(() =>
  252. journal.putNode({
  253. runId: RUN.runId,
  254. siteId: "bogus#1",
  255. ordinal: 1,
  256. kind: "made-up" as NodeRecord["kind"],
  257. inputHash: "h",
  258. status: "completed",
  259. }),
  260. ).toThrow();
  261. });
  262. // `kind` 的 CHECK 含 'world-run'(world.run 的 journal 化命令执行,docs/dynamic-workflow/authoring.md)。
  263. it('dwf_node 接受 kind:"world-run" 并原样回读', async () => {
  264. const { journal } = openJournalDb();
  265. journal.createRun(RUN);
  266. const worldRun: NodeRecord = {
  267. runId: RUN.runId,
  268. siteId: "world-read#3",
  269. ordinal: 2,
  270. kind: "world-run",
  271. inputHash: "h-run",
  272. status: "completed",
  273. result: { exitCode: 1, stdout: "", stderr: "proof failed" },
  274. };
  275. journal.putNode(worldRun);
  276. expect(journal.getNode(RUN.runId, "world-read#3", 2)).toEqual(worldRun);
  277. });
  278. it("dwf_node 带 input_json 列:有界输入原样回读,ask 行缺席", async () => {
  279. // 工作区 transcript 的「what ran」(docs/dynamic-workflow/transcript-and-notifications.md)。
  280. const { db, journal } = openJournalDb();
  281. journal.createRun(RUN);
  282. const worldRun: NodeRecord = {
  283. runId: RUN.runId,
  284. siteId: "world-read#4",
  285. ordinal: 1,
  286. kind: "world-run",
  287. inputHash: "h-in",
  288. input: { op: "run", args: ["pnpm", ["vitest", "run", "--changed"], { timeoutMs: 60_000 }] },
  289. status: "running",
  290. };
  291. journal.putNode(worldRun);
  292. expect(journal.getNode(RUN.runId, "world-read#4", 1)).toEqual(worldRun);
  293. // 结算是整条 upsert:input 必须随行回来,而不是被抹成 NULL。
  294. const settled: NodeRecord = {
  295. ...worldRun,
  296. status: "completed",
  297. result: { exitCode: 1, stdout: "FAIL", stderr: "" },
  298. };
  299. journal.putNode(settled);
  300. expect(journal.getNode(RUN.runId, "world-read#4", 1)).toEqual(settled);
  301. const column = db
  302. .prepare("select input_json from dwf_node where site_id = ?")
  303. .get("world-read#4") as { input_json: string | null };
  304. expect(JSON.parse(column.input_json ?? "null")).toEqual(worldRun.input);
  305. journal.putNode(NODE);
  306. const ask = journal.getNode(RUN.runId, NODE.siteId, NODE.ordinal);
  307. expect(ask !== undefined && "input" in ask).toBe(false);
  308. });
  309. it("input_json 为 NULL 的旧行解码不炸且 input 缺席", async () => {
  310. const { db, journal } = openJournalDb();
  311. journal.createRun(RUN);
  312. db.prepare(
  313. `insert into dwf_node (run_id, site_id, ordinal, kind, input_hash, status, result_json, time_created, time_updated)
  314. values (?, ?, ?, 'world-read', 'h', 'completed', ?, 1, 2)`,
  315. ).run(RUN.runId, "world-read#9", 1, JSON.stringify("file body"));
  316. const row = journal.getNode(RUN.runId, "world-read#9", 1);
  317. expect(row).toBeDefined();
  318. expect(row !== undefined && "input" in row).toBe(false);
  319. expect(row?.result).toBe("file body");
  320. });
  321. it("listWorldNodes 只回 world-read / world-run 行,按落库先后,带时间戳与正文字节数、不带正文", async () => {
  322. const { journal } = openJournalDb();
  323. const queries = journal as unknown as DwfRunIntrospectionQueries;
  324. journal.createRun(RUN);
  325. journal.putNode(NODE);
  326. journal.putNode({
  327. runId: RUN.runId,
  328. siteId: "world-read#2",
  329. ordinal: 1,
  330. kind: "world-read",
  331. inputHash: "a",
  332. input: { op: "read", args: ["src/x.ts"] },
  333. status: "completed",
  334. result: "export const x = 1;\n",
  335. });
  336. journal.putNode({
  337. runId: RUN.runId,
  338. siteId: "world-read#3",
  339. ordinal: 1,
  340. kind: "world-run",
  341. inputHash: "b",
  342. input: { op: "run", args: ["lake", ["build"]] },
  343. status: "running",
  344. });
  345. journal.putNode({
  346. runId: RUN.runId,
  347. siteId: "report#1",
  348. ordinal: 1,
  349. kind: "report",
  350. inputHash: "r",
  351. status: "completed",
  352. result: { finding: "x" },
  353. });
  354. const rows = queries.listWorldNodes(RUN.runId);
  355. expect(rows.map((row) => row.siteId)).toEqual(["world-read#2", "world-read#3"]);
  356. expect(rows[0]).toMatchObject({
  357. kind: "world-read",
  358. status: "completed",
  359. input: { op: "read", args: ["src/x.ts"] },
  360. resultBytes: JSON.stringify("export const x = 1;\n").length,
  361. });
  362. expect("result" in rows[0]!).toBe(false);
  363. expect(typeof rows[0]!.timeCreated).toBe("number");
  364. expect(typeof rows[0]!.timeUpdated).toBe("number");
  365. expect("resultBytes" in rows[1]!).toBe(false);
  366. expect(queries.listWorldNodes("dwfrun-unknown")).toEqual([]);
  367. });
  368. it("listWorldNodes 用 SQLite 的 JSON 函数在库内算摘要:数组计数、run 的 exitCode 与输出字节数", async () => {
  369. const { journal } = openJournalDb();
  370. const queries = journal as unknown as DwfRunIntrospectionQueries;
  371. journal.createRun(RUN);
  372. journal.putNode({
  373. runId: RUN.runId,
  374. siteId: "world-read#1",
  375. ordinal: 1,
  376. kind: "world-read",
  377. inputHash: "g",
  378. input: { op: "glob", args: ["src/**/*.ts"] },
  379. status: "completed",
  380. result: ["src/a.ts", "src/b.ts", "src/c.ts"],
  381. });
  382. journal.putNode({
  383. runId: RUN.runId,
  384. siteId: "world-read#2",
  385. ordinal: 1,
  386. kind: "world-run",
  387. inputHash: "r",
  388. input: { op: "run", args: ["pnpm", ["test"]] },
  389. status: "completed",
  390. result: { exitCode: 1, stdout: "ok\n", stderr: "é" },
  391. });
  392. journal.putNode({
  393. runId: RUN.runId,
  394. siteId: "world-read#3",
  395. ordinal: 1,
  396. kind: "world-read",
  397. inputHash: "s",
  398. input: { op: "git-status", args: [] },
  399. status: "completed",
  400. result: " M src/a.ts\n",
  401. });
  402. journal.putNode({
  403. runId: RUN.runId,
  404. siteId: "world-read#4",
  405. ordinal: 1,
  406. kind: "world-run",
  407. inputHash: "f",
  408. input: { op: "run", args: ["false"] },
  409. status: "failed",
  410. error: { code: "DriverError", message: "boom" },
  411. });
  412. const rows = queries.listWorldNodes(RUN.runId);
  413. expect(rows[0]).toMatchObject({ resultCount: 3 });
  414. expect("exitCode" in rows[0]!).toBe(false);
  415. // stderr 是一个双字节字符:报的是 UTF-8 字节数,不是字符数。
  416. expect(rows[1]).toMatchObject({ exitCode: 1, stdoutBytes: 3, stderrBytes: 2 });
  417. expect("resultCount" in rows[1]!).toBe(false);
  418. // 字符串正文:既不是数组也不是对象,摘要列全部缺席,只有字节数。
  419. expect(rows[2]).toMatchObject({ resultBytes: JSON.stringify(" M src/a.ts\n").length });
  420. expect("resultCount" in rows[2]!).toBe(false);
  421. expect("exitCode" in rows[2]!).toBe(false);
  422. // 失败行没有正文:什么摘要都没有,只有 error。
  423. expect(rows[3]).toMatchObject({
  424. status: "failed",
  425. error: { code: "DriverError", message: "boom" },
  426. });
  427. expect("resultBytes" in rows[3]!).toBe(false);
  428. expect("exitCode" in rows[3]!).toBe(false);
  429. });
  430. // dwf_event 上的表达式索引不只要存在,还得**真的被用上**:它存在的全部理由是让看板取数
  431. // 不必扫完一条长 run 的整张事件表(那是最大的一张表)。查询计划变了这里就会响。
  432. it("dwf_event 的表达式索引真的服务于按 artifactId 取事件", async () => {
  433. const { db } = openJournalDb();
  434. const plan = (
  435. db
  436. .prepare(
  437. `explain query plan
  438. select sequence from dwf_event
  439. where run_id = ? and type = 'report' and json_extract(payload_json, '$.artifactId') = ?
  440. order by sequence`,
  441. )
  442. .all("run_1", "perf") as unknown as { detail: string }[]
  443. )
  444. .map((row) => row.detail)
  445. .join(" | ");
  446. expect(plan).toContain("dwf_event_artifact_idx");
  447. });
  448. });
  449. /**
  450. * 孤儿收敛的窄查询。刻意**不在** `JournalStorePort` 上:引擎从不按父会话找 run,这条查询
  451. * 只服务于宿主侧的收敛(`bootstrap/src/app/dynamic-workflow-run-service.ts` 构造时按能力
  452. * 探测调用它)。内存实现不提供它,所以它的语义只能在这里、对着真库钉住。
  453. */
  454. interface DwfNonTerminalRunQuery {
  455. listNonTerminalRuns(parentSessionId: string): RunRecord[];
  456. }
  457. /**
  458. * 开一个带窄查询的 journal。这里用与宿主侧**同一种**能力探测:方法名一旦漂移,宿主的收敛
  459. * 会静默跳过(回到「孤儿 run 永远 running」那个 bug),所以在这里就要大声失败。
  460. */
  461. function openSweepableJournal(): JournalStorePort & DwfNonTerminalRunQuery {
  462. const { journal } = openJournalDb();
  463. if (typeof (journal as Partial<DwfNonTerminalRunQuery>).listNonTerminalRuns !== "function") {
  464. throw new Error("sqlite dwf journal 缺少 listNonTerminalRuns:宿主侧的孤儿收敛会静默跳过");
  465. }
  466. return journal as JournalStorePort & DwfNonTerminalRunQuery;
  467. }
  468. describe("SQLite dwf journal store — listNonTerminalRuns", () => {
  469. const PARENT = "ses_sweep_parent";
  470. /** 预置一行 dwf_run(只关心父会话与状态)。 */
  471. function seed(
  472. journal: JournalStorePort,
  473. input: { runId: string; status: RunRecord["status"]; parentSessionId?: string },
  474. ): void {
  475. journal.createRun({
  476. runId: input.runId,
  477. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  478. caps: CAPS,
  479. spentTokens: 0,
  480. status: input.status,
  481. });
  482. }
  483. it("只回本父会话的非终态行", async () => {
  484. const journal = openSweepableJournal();
  485. seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
  486. seed(journal, { parentSessionId: PARENT, runId: "run_pending", status: "pending" });
  487. seed(journal, { parentSessionId: PARENT, runId: "run_completed", status: "completed" });
  488. seed(journal, { parentSessionId: PARENT, runId: "run_errored", status: "errored" });
  489. seed(journal, { parentSessionId: PARENT, runId: "run_stopped", status: "stopped" });
  490. // 兄弟会话正在飞的 run 与父会话缺席的行都不属于本会话——查全了就会把它们标死。
  491. seed(journal, { parentSessionId: "ses_other", runId: "run_sibling", status: "running" });
  492. seed(journal, { runId: "run_parentless", status: "running" });
  493. const rows = journal.listNonTerminalRuns(PARENT);
  494. expect(rows.map((row) => row.runId).sort()).toEqual(["run_pending", "run_running"]);
  495. // 回的是完整 RunRecord(同一个 decodeRun),收敛策略据 status 判断,不需要二次查询。
  496. expect(rows.every((row) => row.parentSessionId === PARENT)).toBe(true);
  497. expect(rows.find((row) => row.runId === "run_running")?.status).toBe("running");
  498. });
  499. it("收敛写入之后同一个查询返回空(幂等的 SQL 侧依据)", async () => {
  500. const journal = openSweepableJournal();
  501. seed(journal, { parentSessionId: PARENT, runId: "run_orphan", status: "running" });
  502. journal.updateRunStatus("run_orphan", "stopped", {
  503. stopReason: "interrupted",
  504. failure: { code: "Interrupted", message: "owning process exited" },
  505. });
  506. expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
  507. });
  508. it("未知父会话返回空数组", async () => {
  509. const journal = openSweepableJournal();
  510. seed(journal, { parentSessionId: PARENT, runId: "run_running", status: "running" });
  511. expect(journal.listNonTerminalRuns("ses_never_seen")).toEqual([]);
  512. });
  513. });
  514. /**
  515. * run 内省(`ListWorkflowRuns` / `GetWorkflowRun`)的宿主侧查询面。与 listNonTerminalRuns
  516. * 同款处理:引擎从不枚举 run,所以这些方法不进领域 `JournalStorePort`,内存实现也不提供它们——
  517. * 它们的语义只能在这里、对着真库钉住(docs/dynamic-workflow/launch.md
  518. * 的「枚举查询归属」行)。
  519. */
  520. function openIntrospectableJournal(): {
  521. db: DatabaseSync;
  522. journal: JournalStorePort & DwfRunIntrospectionQueries;
  523. } {
  524. const { db, journal } = openJournalDb();
  525. // 与宿主侧**同一种**能力探测:方法名一旦漂移,两个工具会静默降级成「本会话没有这个能力」,
  526. // 所以在这里就要大声失败。
  527. for (const method of [
  528. "listRuns",
  529. "getRunRow",
  530. "countNodesByStatus",
  531. "listRecentLogEvents",
  532. "listArtifactRows",
  533. "listArtifactItems",
  534. "countTaggedReports",
  535. "listEventPage",
  536. "listRunLifeSpans",
  537. ] as const) {
  538. if (typeof (journal as Partial<DwfRunIntrospectionQueries>)[method] !== "function") {
  539. throw new Error(`sqlite dwf journal 缺少 ${method}:run 内省工具会静默不可用`);
  540. }
  541. }
  542. return { db, journal: journal as JournalStorePort & DwfRunIntrospectionQueries };
  543. }
  544. /**
  545. * 预置一行 dwf_run。`timeUpdated` 必须能被显式钉住:createRun 写的是 Date.now(),同毫秒内
  546. * 建的多个 run 会拿到相同的时间戳,倒序断言就无从谈起。
  547. */
  548. function seedRun(
  549. db: DatabaseSync,
  550. journal: JournalStorePort,
  551. input: {
  552. args?: Record<string, unknown>;
  553. cwd?: string;
  554. name?: string;
  555. parentSessionId?: string;
  556. result?: unknown;
  557. runId: string;
  558. scriptText?: string;
  559. status?: RunRecord["status"];
  560. timeUpdated?: number;
  561. },
  562. ): void {
  563. journal.createRun({
  564. runId: input.runId,
  565. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  566. ...(input.cwd === undefined ? {} : { cwd: input.cwd }),
  567. ...(input.name === undefined ? {} : { name: input.name }),
  568. ...(input.args === undefined ? {} : { args: input.args }),
  569. ...(input.scriptText === undefined ? {} : { scriptText: input.scriptText }),
  570. caps: CAPS,
  571. spentTokens: 0,
  572. status: input.status ?? "running",
  573. });
  574. if (input.result !== undefined) {
  575. journal.updateRunStatus(input.runId, input.status ?? "completed", { result: input.result });
  576. }
  577. if (input.timeUpdated !== undefined) {
  578. db.prepare("update dwf_run set time_updated = ? where id = ?").run(
  579. input.timeUpdated,
  580. input.runId,
  581. );
  582. }
  583. }
  584. describe("SQLite dwf journal store — dwf_run.name 与 cwd 索引", () => {
  585. it("dwf_run 带 name 列,且 dwf_run_cwd_idx 的形状正对枚举查询", async () => {
  586. const { db } = openJournalDb();
  587. const columns = (
  588. db.prepare("select name from pragma_table_info('dwf_run')").all() as unknown as {
  589. name: string;
  590. }[]
  591. ).map((row) => row.name);
  592. expect(columns).toContain("name");
  593. // 索引列序就是查询形状(cwd 等值 + time_updated 排序):顺序反了索引就只能扫。
  594. const indexed = (
  595. db.prepare("select name from pragma_index_info('dwf_run_cwd_idx')").all() as unknown as {
  596. name: string;
  597. }[]
  598. ).map((row) => row.name);
  599. expect(indexed).toEqual(["cwd", "time_updated"]);
  600. });
  601. it("name 为 NULL 的旧行解码不炸且 name 缺席", async () => {
  602. // 0021 之前落库的 run 行:列是新加的、值为 NULL(不做回填)。decodeRun 必须回一条没有
  603. // name 键的记录,否则升级后所有历史 run 都读不出来。
  604. const { db, journal } = openJournalDb();
  605. journal.createRun(RUN);
  606. db.prepare("update dwf_run set name = null where id = ?").run(RUN.runId);
  607. const record = journal.getRun(RUN.runId);
  608. expect(record).toEqual(RUN);
  609. expect("name" in (record ?? {})).toBe(false);
  610. });
  611. });
  612. describe("SQLite dwf journal store — 基线形状", () => {
  613. // docs/dynamic-workflow/authoring.md:预算构造整体移除。基线 0019 直接以终态建表,这里钉住
  614. // 「两列不存在、用量列叫 spent_tokens」,以及老形状的 run 记录经 store 读回时 caps 只剩 maxConcurrency。
  615. it("dwf_run 没有节点上限 / 预算列,用量列叫 spent_tokens", async () => {
  616. const { db } = openJournalDb();
  617. const columns = (db.prepare("pragma table_info(dwf_run)").all() as Array<{ name: string }>).map(
  618. (c) => c.name,
  619. );
  620. expect(columns).not.toContain("caps_max_nodes");
  621. expect(columns).not.toContain("caps_budget_total");
  622. expect(columns).not.toContain("budget_spent");
  623. expect(columns).toContain("spent_tokens");
  624. db.prepare(
  625. `insert into dwf_run (id, caps_max_concurrency, spent_tokens, status, time_created, time_updated)
  626. values ('run_legacy', 8, 4242, 'completed', 1, 2)`,
  627. ).run();
  628. const journal = createDwfJournalStore(db);
  629. expect(journal.getRun("run_legacy")).toEqual({
  630. runId: "run_legacy",
  631. caps: { maxConcurrency: 8 },
  632. spentTokens: 4242,
  633. status: "completed",
  634. });
  635. });
  636. });
  637. describe("SQLite dwf journal store — listRuns", () => {
  638. const CWD = "/repo/project";
  639. it("只回本 cwd 的 run,按 time_updated 倒序", async () => {
  640. const { db, journal } = openIntrospectableJournal();
  641. seedRun(db, journal, { runId: "run_old", cwd: CWD, timeUpdated: 1_000 });
  642. seedRun(db, journal, { runId: "run_new", cwd: CWD, timeUpdated: 3_000 });
  643. seedRun(db, journal, { runId: "run_mid", cwd: CWD, timeUpdated: 2_000 });
  644. // 他项目的 run 与没有 cwd 的行都不属于本项目:查全了就把别人的 run 摆到模型面前。
  645. seedRun(db, journal, { runId: "run_other", cwd: "/repo/elsewhere", timeUpdated: 9_000 });
  646. seedRun(db, journal, { runId: "run_cwdless", timeUpdated: 9_000 });
  647. const rows = journal.listRuns({ cwd: CWD, limit: 20 });
  648. expect(rows.map((row) => row.runId)).toEqual(["run_new", "run_mid", "run_old"]);
  649. });
  650. it("cwd 是字面匹配,不做路径规范化", async () => {
  651. // 与 submit 写入同源(context.workingDirectory 原样落库、原样查询)。在读侧单方面
  652. // 规范化只会造出单侧不匹配。
  653. const { db, journal } = openIntrospectableJournal();
  654. seedRun(db, journal, { runId: "run_1", cwd: CWD });
  655. expect(journal.listRuns({ cwd: `${CWD}/`, limit: 20 })).toEqual([]);
  656. expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(1);
  657. });
  658. it("limit 只截最新的那几条", async () => {
  659. const { db, journal } = openIntrospectableJournal();
  660. for (let i = 0; i < 5; i++) {
  661. seedRun(db, journal, { runId: `run_${i}`, cwd: CWD, timeUpdated: 1_000 + i });
  662. }
  663. expect(journal.listRuns({ cwd: CWD, limit: 2 }).map((row) => row.runId)).toEqual([
  664. "run_4",
  665. "run_3",
  666. ]);
  667. // 超出条数不补空位;limit 0 是空页而不是全量(`limit -1` 那个 SQLite 惯用法不适用这里)。
  668. expect(journal.listRuns({ cwd: CWD, limit: 50 })).toHaveLength(5);
  669. expect(journal.listRuns({ cwd: CWD, limit: 0 })).toEqual([]);
  670. });
  671. it("statuses 过滤到给定子集", async () => {
  672. const { db, journal } = openIntrospectableJournal();
  673. seedRun(db, journal, { runId: "run_running", cwd: CWD, status: "running" });
  674. seedRun(db, journal, { runId: "run_pending", cwd: CWD, status: "pending" });
  675. seedRun(db, journal, { runId: "run_completed", cwd: CWD, status: "completed" });
  676. seedRun(db, journal, { runId: "run_errored", cwd: CWD, status: "errored" });
  677. expect(
  678. journal
  679. .listRuns({ cwd: CWD, limit: 20, statuses: ["running", "pending"] })
  680. .map((row) => row.runId)
  681. .sort(),
  682. ).toEqual(["run_pending", "run_running"]);
  683. expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: ["stopped"] })).toEqual([]);
  684. // 空集合就是「不匹配任何状态」,不是「不过滤」——后者会把过滤器静默取消掉。
  685. expect(journal.listRuns({ cwd: CWD, limit: 20, statuses: [] })).toEqual([]);
  686. });
  687. it("name 过滤下推到 SQL,且与 statuses 可叠加(GUI 中枢按工作流名归属运行历史)", async () => {
  688. const { db, journal } = openIntrospectableJournal();
  689. seedRun(db, journal, { runId: "run_a1", cwd: CWD, name: "release-check", timeUpdated: 3 });
  690. seedRun(db, journal, { runId: "run_a2", cwd: CWD, name: "release-check", timeUpdated: 1 });
  691. seedRun(db, journal, { runId: "run_b", cwd: CWD, name: "port-driver", timeUpdated: 2 });
  692. seedRun(db, journal, { runId: "run_nameless", cwd: CWD, timeUpdated: 9 });
  693. seedRun(db, journal, {
  694. runId: "run_a_failed",
  695. cwd: CWD,
  696. name: "release-check",
  697. status: "errored",
  698. timeUpdated: 5,
  699. });
  700. expect(
  701. journal.listRuns({ cwd: CWD, limit: 20, name: "release-check" }).map((row) => row.runId),
  702. ).toEqual(["run_a_failed", "run_a1", "run_a2"]);
  703. expect(
  704. journal
  705. .listRuns({ cwd: CWD, limit: 20, name: "release-check", statuses: ["errored"] })
  706. .map((row) => row.runId),
  707. ).toEqual(["run_a_failed"]);
  708. // 名字是字面等值;不存在的名字回空页,而不是退回「不过滤」。
  709. expect(journal.listRuns({ cwd: CWD, limit: 20, name: "nope" })).toEqual([]);
  710. // 不带 name 时行为不变(nameless 行也在)。
  711. expect(journal.listRuns({ cwd: CWD, limit: 20 })).toHaveLength(5);
  712. });
  713. it("cwd 缺省即跨所有项目枚举(全局工作流的运行历史跨 cwd),行带 cwd", async () => {
  714. // 全局工作流在不同项目里被发起,dwf_run.cwd 记的是各自实际运行的项目。`workflows/runs`
  715. // 的全局变体不按 cwd 过滤,把该名字在所有项目里的历史一并取出,行带 cwd 供 GUI 标项目
  716. // (docs/dynamic-workflow/launch.md「Data path」)。
  717. const { db, journal } = openIntrospectableJournal();
  718. seedRun(db, journal, {
  719. runId: "run_a",
  720. cwd: "/repo/one",
  721. name: "deep-research",
  722. timeUpdated: 3,
  723. });
  724. seedRun(db, journal, {
  725. runId: "run_b",
  726. cwd: "/repo/two",
  727. name: "deep-research",
  728. timeUpdated: 2,
  729. });
  730. seedRun(db, journal, { runId: "run_c", cwd: "/repo/one", name: "other", timeUpdated: 5 });
  731. seedRun(db, journal, { runId: "run_cwdless", name: "deep-research", timeUpdated: 1 });
  732. const rows = journal.listRuns({ name: "deep-research", limit: 20 });
  733. // 跨两个 cwd + 没有 cwd 的行,按 time_updated 倒序;别的名字不进来。
  734. expect(rows.map((row) => row.runId)).toEqual(["run_a", "run_b", "run_cwdless"]);
  735. const byId = new Map(rows.map((row) => [row.runId, row]));
  736. expect(byId.get("run_a")?.cwd).toBe("/repo/one");
  737. expect(byId.get("run_b")?.cwd).toBe("/repo/two");
  738. // cwd 为 NULL 的行不带 cwd 键(新列不回填,缺席可分辨)。
  739. expect(byId.get("run_cwdless") !== undefined && "cwd" in (byId.get("run_cwdless") ?? {})).toBe(
  740. false,
  741. );
  742. // 给了 cwd 就仍只回本项目那份(与全局变体互斥,行为逐字不变)。
  743. expect(
  744. journal.listRuns({ cwd: "/repo/one", limit: 20, name: "deep-research" }).map((r) => r.runId),
  745. ).toEqual(["run_a"]);
  746. });
  747. it("枚举行带 args(实参是小 JSON 袋,中枢的运行历史要展示它);无实参的行键缺席", async () => {
  748. const { db, journal } = openIntrospectableJournal();
  749. seedRun(db, journal, {
  750. runId: "run_args",
  751. cwd: CWD,
  752. name: "release-check",
  753. args: { target: "packages/ui", skipTests: false },
  754. });
  755. seedRun(db, journal, { runId: "run_bare", cwd: CWD, name: "release-check" });
  756. const byId = new Map(journal.listRuns({ cwd: CWD, limit: 20 }).map((row) => [row.runId, row]));
  757. expect(byId.get("run_args")?.args).toEqual({ target: "packages/ui", skipTests: false });
  758. expect(byId.get("run_bare")).not.toHaveProperty("args");
  759. });
  760. it("空结果回空数组", async () => {
  761. const { journal } = openIntrospectableJournal();
  762. expect(journal.listRuns({ cwd: "/never/seen", limit: 20 })).toEqual([]);
  763. });
  764. it("每行带齐下游合成真相所需的字段,但不驮 result/failure", async () => {
  765. const { db, journal } = openIntrospectableJournal();
  766. seedRun(db, journal, {
  767. runId: "run_1",
  768. cwd: CWD,
  769. name: "nightly triage",
  770. parentSessionId: "ses_owner",
  771. scriptText: "const planner = agent('planner');",
  772. status: "completed",
  773. result: { big: "artifact" },
  774. timeUpdated: 4_242,
  775. });
  776. const [row] = journal.listRuns({ cwd: CWD, limit: 20 });
  777. expect(row).toMatchObject({
  778. runId: "run_1",
  779. name: "nightly triage",
  780. // parentSessionId 是 ownedByThisSession / possiblyInterrupted 的判据,scriptText 是
  781. // label 兜底的原料——两者缺一,下游就只能再查一遍。
  782. parentSessionId: "ses_owner",
  783. cwd: CWD,
  784. scriptText: "const planner = agent('planner');",
  785. status: "completed",
  786. spentTokens: 0,
  787. caps: CAPS,
  788. timeUpdated: 4_242,
  789. });
  790. expect(typeof row?.timeCreated).toBe("number");
  791. // 列表刻意轻:产物可以很大,一页 50 行全解出来等于把整库产物读进内存。
  792. expect(row !== undefined && "result" in row).toBe(false);
  793. expect(row !== undefined && "failure" in row).toBe(false);
  794. });
  795. it("name 缺席的行不带 name 键", async () => {
  796. const { db, journal } = openIntrospectableJournal();
  797. seedRun(db, journal, { runId: "run_1", cwd: CWD, scriptText: "log('hi');" });
  798. const [row] = journal.listRuns({ cwd: CWD, limit: 20 });
  799. expect(row !== undefined && "name" in row).toBe(false);
  800. });
  801. });
  802. describe("SQLite dwf journal store — getRunRow", () => {
  803. it("回完整记录 + journal 时间戳", async () => {
  804. const { db, journal } = openIntrospectableJournal();
  805. seedRun(db, journal, {
  806. runId: "run_1",
  807. cwd: "/repo",
  808. name: "named run",
  809. status: "completed",
  810. result: { report: "done" },
  811. timeUpdated: 5_000,
  812. });
  813. const row = journal.getRunRow("run_1");
  814. // 时间戳直读 journal:RunRecord 本身不带时间,而详情页要报 createdAt / updatedAt。
  815. expect(row).toMatchObject({
  816. runId: "run_1",
  817. name: "named run",
  818. status: "completed",
  819. result: { report: "done" },
  820. timeUpdated: 5_000,
  821. });
  822. expect(typeof row?.timeCreated).toBe("number");
  823. });
  824. it("未知 runId 回 undefined", async () => {
  825. const { journal } = openIntrospectableJournal();
  826. expect(journal.getRunRow("nope")).toBeUndefined();
  827. });
  828. });
  829. describe("SQLite dwf journal store — countNodesByStatus", () => {
  830. /** 落一个节点(只关心 status 与归属 run)。 */
  831. function seedNode(
  832. journal: JournalStorePort,
  833. runId: string,
  834. siteId: string,
  835. ordinal: number,
  836. status: NodeRecord["status"],
  837. ): void {
  838. journal.putNode({ runId, siteId, ordinal, kind: "ask", inputHash: "h", status });
  839. }
  840. it("按三态计数,且只数本 run 的节点", async () => {
  841. const { db, journal } = openIntrospectableJournal();
  842. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  843. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  844. seedNode(journal, "run_1", "ask#1", 1, "completed");
  845. seedNode(journal, "run_1", "ask#1", 2, "completed");
  846. seedNode(journal, "run_1", "ask#2", 1, "running");
  847. seedNode(journal, "run_1", "ask#3", 1, "failed");
  848. seedNode(journal, "run_2", "ask#1", 1, "completed");
  849. expect(journal.countNodesByStatus("run_1")).toEqual({ running: 1, completed: 2, failed: 1 });
  850. });
  851. it("无节点(含未知 run)回三个 0,而不是缺键", async () => {
  852. // 下游要拿它直接算 nodesObserved;缺键会让「还没有节点」和「没有这个 run」都变成 NaN。
  853. const { db, journal } = openIntrospectableJournal();
  854. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  855. expect(journal.countNodesByStatus("run_1")).toEqual({ running: 0, completed: 0, failed: 0 });
  856. expect(journal.countNodesByStatus("nope")).toEqual({ running: 0, completed: 0, failed: 0 });
  857. });
  858. });
  859. describe("SQLite dwf journal store — listRecentLogEvents", () => {
  860. it("只取 log 事件的末 N 条,按时序回", async () => {
  861. const { db, journal } = openIntrospectableJournal();
  862. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  863. journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
  864. for (const message of ["l0", "l1", "l2", "l3"]) {
  865. journal.appendEvent("run_1", { type: "log", message });
  866. journal.appendEvent("run_1", {
  867. type: "usage-updated",
  868. spentTokens: 10,
  869. });
  870. }
  871. const tail = journal.listRecentLogEvents("run_1", 3);
  872. // 末 N 条按 sequence desc 取、再反转回时序:全量读进内存再筛是这条查询存在的反面。
  873. expect(
  874. tail.map((e) => (e.event.type === "log" ? e.event.message : `<${e.event.type}>`)),
  875. ).toEqual(["l1", "l2", "l3"]);
  876. // 序号是 journal 的真序号(log 之间夹着别的事件,所以不连续),不是重新编号的下标——
  877. // 下游拿它定位「叙事走到哪」。
  878. expect(tail.map((e) => e.sequence)).toEqual([3, 5, 7]);
  879. });
  880. it("limit 超过条数时给出全部 log 事件", async () => {
  881. const { db, journal } = openIntrospectableJournal();
  882. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  883. journal.appendEvent("run_1", { type: "log", message: "only" });
  884. journal.appendEvent("run_1", { type: "run-settled", status: "completed" });
  885. expect(journal.listRecentLogEvents("run_1", 20).map((e) => e.event.type)).toEqual(["log"]);
  886. });
  887. it("没有 log 事件(含未知 run、limit 0)回空数组", async () => {
  888. const { db, journal } = openIntrospectableJournal();
  889. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  890. journal.appendEvent("run_1", { type: "run-started", runId: "run_1", caps: CAPS });
  891. expect(journal.listRecentLogEvents("run_1", 20)).toEqual([]);
  892. expect(journal.listRecentLogEvents("nope", 20)).toEqual([]);
  893. expect(journal.listRecentLogEvents("run_1", 0)).toEqual([]);
  894. });
  895. it("按 runId 隔离", async () => {
  896. const { db, journal } = openIntrospectableJournal();
  897. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  898. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  899. journal.appendEvent("run_1", { type: "log", message: "mine" });
  900. journal.appendEvent("run_2", { type: "log", message: "theirs" });
  901. expect(
  902. journal
  903. .listRecentLogEvents("run_1", 20)
  904. .map((e) => (e.event.type === "log" ? e.event.message : "")),
  905. ).toEqual(["mine"]);
  906. });
  907. });
  908. describe("SQLite dwf journal store — listRunsByParentSession", () => {
  909. const PARENT = "ses_enum_parent";
  910. interface DwfRunEnumerationQuery {
  911. listRunsByParentSession(parentSessionId: string, limit: number): DwfRunSessionListItem[];
  912. }
  913. /** 能力探测同宿主侧(supportsRunEnumeration):方法名漂移要在这里先红。 */
  914. function openEnumerableJournal(): JournalStorePort & DwfRunEnumerationQuery {
  915. const { journal } = openJournalDb();
  916. if (
  917. typeof (journal as Partial<DwfRunEnumerationQuery>).listRunsByParentSession !== "function"
  918. ) {
  919. throw new Error(
  920. "sqlite dwf journal 缺少 listRunsByParentSession:UI 的重启后发现面会静默为空",
  921. );
  922. }
  923. return journal as JournalStorePort & DwfRunEnumerationQuery;
  924. }
  925. function seed(
  926. journal: JournalStorePort,
  927. input: {
  928. runId: string;
  929. status: RunRecord["status"];
  930. parentSessionId?: string;
  931. toolCallId?: string;
  932. },
  933. ): void {
  934. journal.createRun({
  935. runId: input.runId,
  936. ...(input.parentSessionId === undefined ? {} : { parentSessionId: input.parentSessionId }),
  937. ...(input.toolCallId === undefined ? {} : { toolCallId: input.toolCallId }),
  938. caps: CAPS,
  939. spentTokens: 0,
  940. status: input.status,
  941. });
  942. }
  943. it("只回本父会话的行,完整解码(含 toolCallId 与 failure)", async () => {
  944. const journal = openEnumerableJournal();
  945. seed(journal, {
  946. parentSessionId: PARENT,
  947. runId: "run_a",
  948. status: "stopped",
  949. toolCallId: "call-a",
  950. });
  951. seed(journal, { parentSessionId: PARENT, runId: "run_b", status: "completed" });
  952. seed(journal, { parentSessionId: "ses_other", runId: "run_sibling", status: "running" });
  953. seed(journal, { runId: "run_parentless", status: "running" });
  954. journal.updateRunStatus("run_b", "stopped", {
  955. stopReason: "interrupted",
  956. failure: { code: "Interrupted", message: "owning process exited" },
  957. });
  958. const rows = journal.listRunsByParentSession(PARENT, 10);
  959. expect(rows.map((row) => row.runId).sort()).toEqual(["run_a", "run_b"]);
  960. expect(rows.find((row) => row.runId === "run_a")?.toolCallId).toBe("call-a");
  961. // 逻辑词汇原样回来:stopped + reason + 结构化失败(物理层是 cancelled + 信封)。
  962. expect(rows.find((row) => row.runId === "run_a")).toMatchObject({
  963. status: "stopped",
  964. stopReason: "user",
  965. });
  966. expect(rows.find((row) => row.runId === "run_b")).toMatchObject({
  967. status: "stopped",
  968. stopReason: "interrupted",
  969. failure: { code: "Interrupted" },
  970. });
  971. });
  972. it("最近更新在前,limit 截断在最旧一侧", async () => {
  973. const journal = openEnumerableJournal();
  974. seed(journal, { parentSessionId: PARENT, runId: "run_old", status: "completed" });
  975. seed(journal, { parentSessionId: PARENT, runId: "run_mid", status: "completed" });
  976. seed(journal, { parentSessionId: PARENT, runId: "run_new", status: "running" });
  977. // 让 time_updated 真正拉开(同一毫秒内 createRun 会并列):更新最老那行,使它变最新。
  978. await new Promise((resolve) => setTimeout(resolve, 5));
  979. journal.updateRunUsage("run_old", 42);
  980. const rows = journal.listRunsByParentSession(PARENT, 2);
  981. expect(rows).toHaveLength(2);
  982. expect(rows[0]?.runId).toBe("run_old"); // 刚被触碰过 → 最近更新
  983. });
  984. it("未知父会话返回空数组;limit 0 返回空", async () => {
  985. const journal = openEnumerableJournal();
  986. seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
  987. expect(journal.listRunsByParentSession("ses_never_seen", 10)).toEqual([]);
  988. expect(journal.listRunsByParentSession(PARENT, 0)).toEqual([]);
  989. });
  990. // 窄投影:枚举面报 updatedAt,所以行必须带 journal 时间戳(`RunRecord` 自己不带时间)。
  991. it("行带 journal 时间戳(createdAt/updatedAt 的来源)", async () => {
  992. const journal = openEnumerableJournal();
  993. seed(journal, { parentSessionId: PARENT, runId: "run_timed", status: "running" });
  994. const [row] = journal.listRunsByParentSession(PARENT, 10);
  995. expect(typeof row?.timeCreated).toBe("number");
  996. expect(typeof row?.timeUpdated).toBe("number");
  997. expect(row?.timeUpdated).toBeGreaterThanOrEqual(row?.timeCreated ?? 0);
  998. // 元数据列齐全(标签派生要 name/scriptText,归属要 parentSessionId)。
  999. expect(row).toMatchObject({ parentSessionId: PARENT, runId: "run_timed", status: "running" });
  1000. });
  1001. /**
  1002. * `result_json` **不进这条查询的 SQL**。
  1003. *
  1004. * 断言必须打在 SQL 上而不是解码结果上:`decodeRunListItem` 本来就不读 result_json,所以
  1005. * 把 select 改回 `select *` 之后行为**完全不变**(行里照样没有 `result` 键),只有内存代价
  1006. * 会悄悄回来——一页 run 把每个产物一起读进内存。行为断言在这里是个假哨兵,实测过。
  1007. *
  1008. * 反过来 `failure_json` 必须在 SQL 里:resumable 的谓词依赖 failure.code(见下一个用例)。
  1009. */
  1010. it("枚举查询的 SQL 取 failure_json 而不取 result_json", async () => {
  1011. const db = new DatabaseSync(":memory:");
  1012. openDatabases.push(db);
  1013. await runSqliteSessionMigrations(db, ":memory:");
  1014. const prepared: string[] = [];
  1015. // prepare 的旁路记录器:只为了看见这条查询真正发出的列清单。
  1016. const recordingDb = new Proxy(db, {
  1017. get(target, property, receiver) {
  1018. if (property === "prepare") {
  1019. return (sql: string) => {
  1020. prepared.push(sql);
  1021. return target.prepare(sql);
  1022. };
  1023. }
  1024. const value = Reflect.get(target, property, receiver);
  1025. return typeof value === "function" ? value.bind(target) : value;
  1026. },
  1027. }) as DatabaseSync;
  1028. const journal = createDwfJournalStore(recordingDb) as JournalStorePort & DwfRunEnumerationQuery;
  1029. seed(journal, { parentSessionId: PARENT, runId: "run_a", status: "running" });
  1030. // 只看枚举查询自己发的 SQL(建行/迁移的语句当然会提到 result_json)。
  1031. prepared.length = 0;
  1032. journal.listRunsByParentSession(PARENT, 10);
  1033. const sql = prepared.join("\n");
  1034. expect(sql).toContain("failure_json");
  1035. expect(sql).not.toContain("result_json");
  1036. expect(sql).not.toMatch(/select\s+\*/i);
  1037. });
  1038. /** failure 必须活过窄投影:Interrupted 是 resume 门认可的可恢复形态。 */
  1039. it("窄投影仍解出 failure(resumable 谓词的输入)", async () => {
  1040. const journal = openEnumerableJournal();
  1041. seed(journal, { parentSessionId: PARENT, runId: "run_dead", status: "running" });
  1042. journal.updateRunStatus("run_dead", "stopped", {
  1043. stopReason: "interrupted",
  1044. failure: { code: "Interrupted", message: "owning process exited" },
  1045. });
  1046. const [row] = journal.listRunsByParentSession(PARENT, 10);
  1047. expect(row?.failure).toEqual({ code: "Interrupted", message: "owning process exited" });
  1048. expect(row?.stopReason).toBe("interrupted");
  1049. });
  1050. });
  1051. /**
  1052. * 用户面产物的两条宿主查询(docs/dynamic-workflow/authoring.md「Journal rows and events」)。
  1053. * ⚠ 这里的 artifact 是脚本发布给用户看的交付物,不是 `RunSettlement.artifact`(顶层返回值)。
  1054. *
  1055. * 两条都刻意**不在** `JournalStorePort` 上(同 `listRuns` 的论证:引擎不做的事不该进领域端口),
  1056. * 所以它们的语义只能在这里、对着真库钉住——内存实现根本不提供它们。
  1057. */
  1058. describe("SQLite dwf journal store — listArtifactRows", () => {
  1059. /** 落一条产物行(发布或声明)。 */
  1060. function seedArtifact(
  1061. journal: JournalStorePort,
  1062. runId: string,
  1063. siteId: string,
  1064. ordinal: number,
  1065. artifactId: string,
  1066. record: Record<string, unknown> | undefined,
  1067. ): void {
  1068. journal.putNode({
  1069. runId,
  1070. siteId,
  1071. ordinal,
  1072. kind: "artifact",
  1073. inputHash: `${siteId}@${ordinal}`,
  1074. status: record === undefined ? "failed" : "completed",
  1075. ...(record === undefined
  1076. ? { error: { code: "ArtifactSourceMissing" as const, message: "缺文件" } }
  1077. : { result: record }),
  1078. artifactId,
  1079. });
  1080. }
  1081. it("只回本 run 的产物行,按落库先后", async () => {
  1082. const { db, journal } = openIntrospectableJournal();
  1083. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1084. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1085. // 交错发布:同一个 id 的行**不**天然连续,所以排序只能是落库先后(版本的先后就是它)。
  1086. seedArtifact(journal, "run_1", "artifact#1", 1, "perf", {
  1087. id: "perf",
  1088. kind: "chart",
  1089. version: 1,
  1090. });
  1091. seedArtifact(journal, "run_1", "artifact#2", 1, "book", {
  1092. id: "book",
  1093. kind: "file",
  1094. version: 1,
  1095. bytes: 10,
  1096. });
  1097. seedArtifact(journal, "run_1", "artifact#2", 2, "book", {
  1098. id: "book",
  1099. kind: "file",
  1100. version: 2,
  1101. bytes: 20,
  1102. });
  1103. // 标签 report 与普通节点都不是产物行——混进来,读面会把每个数据点当成一个交付物。
  1104. journal.putNode({
  1105. runId: "run_1",
  1106. siteId: "report#1",
  1107. ordinal: 1,
  1108. kind: "report",
  1109. inputHash: "r",
  1110. status: "completed",
  1111. result: { round: 1 },
  1112. artifactId: "perf",
  1113. });
  1114. journal.putNode({
  1115. runId: "run_1",
  1116. siteId: "ask#1",
  1117. ordinal: 1,
  1118. kind: "ask",
  1119. inputHash: "k",
  1120. status: "completed",
  1121. });
  1122. // 别的 run 的产物:查全了就把别人的交付物摆到这个 run 的卡片区。
  1123. seedArtifact(journal, "run_2", "artifact#1", 1, "other", {
  1124. id: "other",
  1125. kind: "markdown",
  1126. version: 1,
  1127. });
  1128. const rows = journal.listArtifactRows("run_1");
  1129. expect(rows.map((row) => [row.siteId, row.ordinal, row.artifactId])).toEqual([
  1130. ["artifact#1", 1, "perf"],
  1131. ["artifact#2", 1, "book"],
  1132. ["artifact#2", 2, "book"],
  1133. ]);
  1134. expect(rows[2]?.result).toEqual({ id: "book", kind: "file", version: 2, bytes: 20 });
  1135. });
  1136. it("失败的发布照样在结果里(带 error、无 result)", async () => {
  1137. // 筛掉失败行等于让一个用户可见的失败在每张表面上都不存在。
  1138. const { db, journal } = openIntrospectableJournal();
  1139. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1140. seedArtifact(journal, "run_1", "artifact#1", 1, "book", undefined);
  1141. const [row] = journal.listArtifactRows("run_1");
  1142. expect(row?.status).toBe("failed");
  1143. expect(row?.artifactId).toBe("book");
  1144. expect(row?.error).toEqual({ code: "ArtifactSourceMissing", message: "缺文件" });
  1145. expect(row !== undefined && "result" in row).toBe(false);
  1146. });
  1147. it("无产物(含未知 run)回空数组", async () => {
  1148. const { db, journal } = openIntrospectableJournal();
  1149. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1150. expect(journal.listArtifactRows("run_1")).toEqual([]);
  1151. expect(journal.listArtifactRows("nope")).toEqual([]);
  1152. });
  1153. });
  1154. describe("SQLite dwf journal store — countTaggedReports", () => {
  1155. it("counts tagged report rows per artifact id in SQL, ignoring untagged rows, other kinds and other runs", async () => {
  1156. const { db, journal } = openIntrospectableJournal();
  1157. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1158. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1159. const put = (
  1160. runId: string,
  1161. siteId: string,
  1162. ordinal: number,
  1163. extra: Partial<NodeRecord>,
  1164. ): void =>
  1165. journal.putNode({
  1166. runId,
  1167. siteId,
  1168. ordinal,
  1169. kind: "report",
  1170. inputHash: `${siteId}@${ordinal}`,
  1171. status: "completed",
  1172. result: { big: "x".repeat(1024) },
  1173. ...extra,
  1174. });
  1175. put("run_1", "report#1", 1, { artifactId: "perf" });
  1176. put("run_1", "report#1", 2, { artifactId: "perf" });
  1177. put("run_1", "report#2", 1, { artifactId: "queue" });
  1178. put("run_1", "report#3", 1, {}); // 未打标签
  1179. put("run_1", "artifact#1", 1, { kind: "artifact", artifactId: "perf" }); // 产物行不算
  1180. put("run_2", "report#1", 1, { artifactId: "perf" }); // 别的 run
  1181. expect(journal.countTaggedReports("run_1")).toEqual(
  1182. new Map([
  1183. ["perf", 2],
  1184. ["queue", 1],
  1185. ]),
  1186. );
  1187. expect(journal.countTaggedReports("nope")).toEqual(new Map());
  1188. });
  1189. });
  1190. describe("SQLite dwf journal store — listArtifactItems", () => {
  1191. /** 足够大的字节界:只想测条数 / 游标 / 筛选的用例用它,让字节界不参与。 */
  1192. const ANY_BYTES = 1 << 30;
  1193. /** 追加一条标签 report 事件,回它拿到的 sequence。 */
  1194. function seedTaggedReport(
  1195. journal: JournalStorePort,
  1196. runId: string,
  1197. siteId: string,
  1198. ordinal: number,
  1199. item: unknown,
  1200. artifactId?: string,
  1201. ): number {
  1202. return journal.appendEvent(runId, {
  1203. type: "report",
  1204. instance: { siteId, ordinal },
  1205. item,
  1206. ...(artifactId === undefined ? {} : { artifactId }),
  1207. }).sequence;
  1208. }
  1209. it("按 sequence 升序回该 id 的条目,带站点坐标与原值", async () => {
  1210. const { db, journal } = openIntrospectableJournal();
  1211. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1212. const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
  1213. const s1 = seedTaggedReport(journal, "run_1", "report#1", 2, { round: 2 }, "perf");
  1214. expect(journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES })).toEqual({
  1215. items: [
  1216. { sequence: s0, siteId: "report#1", ordinal: 1, item: { round: 1 } },
  1217. { sequence: s1, siteId: "report#1", ordinal: 2, item: { round: 2 } },
  1218. ],
  1219. hasMore: false,
  1220. });
  1221. });
  1222. it("排除未打标签的 report、别的 id、别种事件与别的 run", async () => {
  1223. const { db, journal } = openIntrospectableJournal();
  1224. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1225. seedRun(db, journal, { runId: "run_2", cwd: "/repo" });
  1226. seedTaggedReport(journal, "run_1", "report#1", 1, { mine: true }, "perf");
  1227. // 未打标签:payload 里根本没有 artifactId 键,SQL 的 `= ?` 不匹配 NULL。
  1228. seedTaggedReport(journal, "run_1", "report#2", 1, { untagged: true });
  1229. seedTaggedReport(journal, "run_1", "report#3", 1, { other: true }, "queue");
  1230. // 别种事件:`artifact-published` 的 id 藏在嵌套的 `artifact.id` 里,不是顶层 artifactId;
  1231. // 但 type 过滤才是这条不变式的守门人(明天别的事件可能带顶层 artifactId)。
  1232. journal.appendEvent("run_1", {
  1233. type: "artifact-published",
  1234. instance: { siteId: "artifact#1", ordinal: 1 },
  1235. artifact: { id: "perf", kind: "chart", version: 1 },
  1236. });
  1237. journal.appendEvent("run_1", { type: "log", message: "perf" });
  1238. seedTaggedReport(journal, "run_2", "report#1", 1, { crossRun: true }, "perf");
  1239. const page = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES });
  1240. expect(page.items.map((entry) => entry.item)).toEqual([{ mine: true }]);
  1241. expect(page.hasMore).toBe(false);
  1242. });
  1243. it("afterSequence 是严格大于的游标", async () => {
  1244. const { db, journal } = openIntrospectableJournal();
  1245. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1246. const s0 = seedTaggedReport(journal, "run_1", "report#1", 1, 1, "perf");
  1247. // 中间夹一条别的事件:游标是 journal 的全局 sequence,不是「第几条产物条目」。
  1248. journal.appendEvent("run_1", { type: "log", message: "between" });
  1249. const s1 = seedTaggedReport(journal, "run_1", "report#1", 2, 2, "perf");
  1250. const after = (afterSequence: number) =>
  1251. journal.listArtifactItems("run_1", "perf", { afterSequence, limit: 10, maxBytes: ANY_BYTES });
  1252. expect(after(s0).items.map((entry) => entry.sequence)).toEqual([s1]);
  1253. expect(after(s1)).toEqual({ items: [], hasMore: false });
  1254. });
  1255. it("limit 逐字兑现,hasMore 由存储层判定:页之后还有没有条目", async () => {
  1256. // 存储层不加自己的天花板,也不要调用方多取一条来猜:页尾后面那一行存在与否就是 hasMore。
  1257. const { db, journal } = openIntrospectableJournal();
  1258. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1259. for (let round = 0; round < 5; round += 1) {
  1260. seedTaggedReport(journal, "run_1", "report#1", round + 1, round, "perf");
  1261. }
  1262. const page = (limit: number) =>
  1263. journal.listArtifactItems("run_1", "perf", { limit, maxBytes: ANY_BYTES });
  1264. expect(page(2)).toMatchObject({ hasMore: true });
  1265. expect(page(2).items.map((entry) => entry.item)).toEqual([0, 1]);
  1266. expect(page(4).hasMore).toBe(true);
  1267. // 恰好取尽:不报 hasMore(不会让看板白翻一页空的)。
  1268. expect(page(5)).toMatchObject({ hasMore: false });
  1269. expect(page(5).items).toHaveLength(5);
  1270. expect(page(99).items).toHaveLength(5);
  1271. });
  1272. it("字节界:再加一条就超界时收尾并报 hasMore,第一条总是带上", async () => {
  1273. const { db, journal } = openIntrospectableJournal();
  1274. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1275. const pad = "x".repeat(1000);
  1276. for (let round = 0; round < 4; round += 1) {
  1277. seedTaggedReport(journal, "run_1", "report#1", round + 1, { round, pad }, "perf");
  1278. }
  1279. // 每条载荷约 1.1 KB:2.5 KB 的界放得下两条、放不下第三条。
  1280. const first = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: 2500 });
  1281. expect(first.items.map((entry) => (entry.item as { round: number }).round)).toEqual([0, 1]);
  1282. expect(first.hasMore).toBe(true);
  1283. // 续拉从页尾接上,不重不漏。
  1284. const rest = journal.listArtifactItems("run_1", "perf", {
  1285. afterSequence: first.items.at(-1)!.sequence,
  1286. limit: 10,
  1287. maxBytes: 2500,
  1288. });
  1289. expect(rest.items.map((entry) => (entry.item as { round: number }).round)).toEqual([2, 3]);
  1290. expect(rest.hasMore).toBe(false);
  1291. // 一条就超过界:它自成一页(否则翻页永远卡在这一条上),后面的照样报 hasMore。
  1292. const tiny = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: 10 });
  1293. expect(tiny.items).toHaveLength(1);
  1294. expect(tiny.hasMore).toBe(true);
  1295. });
  1296. it("limit ≤ 0 是空页,未知 run / 未知 id 同样", async () => {
  1297. const { db, journal } = openIntrospectableJournal();
  1298. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1299. seedTaggedReport(journal, "run_1", "report#1", 1, { round: 1 }, "perf");
  1300. const empty = { items: [], hasMore: false };
  1301. expect(journal.listArtifactItems("run_1", "perf", { limit: 0, maxBytes: ANY_BYTES })).toEqual(
  1302. empty,
  1303. );
  1304. expect(journal.listArtifactItems("run_1", "perf", { limit: -1, maxBytes: ANY_BYTES })).toEqual(
  1305. empty,
  1306. );
  1307. expect(journal.listArtifactItems("run_1", "nope", { limit: 10, maxBytes: ANY_BYTES })).toEqual(
  1308. empty,
  1309. );
  1310. expect(journal.listArtifactItems("nope", "perf", { limit: 10, maxBytes: ANY_BYTES })).toEqual(
  1311. empty,
  1312. );
  1313. });
  1314. it("条目原值原样回来:null、标量与数组都不被加工", async () => {
  1315. const { db, journal } = openIntrospectableJournal();
  1316. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1317. seedTaggedReport(journal, "run_1", "report#1", 1, null, "perf");
  1318. seedTaggedReport(journal, "run_1", "report#1", 2, "文本", "perf");
  1319. seedTaggedReport(journal, "run_1", "report#1", 3, [1, { two: true }], "perf");
  1320. const page = journal.listArtifactItems("run_1", "perf", { limit: 10, maxBytes: ANY_BYTES });
  1321. expect(page.items.map((e) => e.item)).toEqual([null, "文本", [1, { two: true }]]);
  1322. });
  1323. });
  1324. describe("SQLite dwf journal store — listArtifactItems with fields", () => {
  1325. const FIELD_VALUE_BYTES = 4096;
  1326. function seed(journal: JournalStorePort, runId: string, items: unknown[]): void {
  1327. items.forEach((item, index) =>
  1328. journal.appendEvent(runId, {
  1329. type: "report",
  1330. instance: { siteId: "report#1", ordinal: index + 1 },
  1331. item,
  1332. artifactId: "perf",
  1333. }),
  1334. );
  1335. }
  1336. function readFields(
  1337. journal: JournalStorePort & DwfRunIntrospectionQueries,
  1338. paths: string[],
  1339. page: { limit?: number; maxBytes?: number; afterSequence?: number } = {},
  1340. ) {
  1341. return journal.listArtifactItems("run_1", "perf", {
  1342. limit: page.limit ?? 10,
  1343. maxBytes: page.maxBytes ?? 1 << 30,
  1344. ...(page.afterSequence === undefined ? {} : { afterSequence: page.afterSequence }),
  1345. fields: { paths, maxValueBytes: FIELD_VALUE_BYTES },
  1346. });
  1347. }
  1348. it("回点名的字段、不回整条 item;JSON 的 null 在表里,走不通的路径不在", async () => {
  1349. const { db, journal } = openIntrospectableJournal();
  1350. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1351. seed(journal, "run_1", [
  1352. { round: 1, ok: true, timing: { ms: 12.5 }, note: null, big: "x".repeat(99) },
  1353. ]);
  1354. const page = readFields(journal, [
  1355. "round",
  1356. "ok",
  1357. "timing.ms",
  1358. "note",
  1359. "missing",
  1360. "round.deeper",
  1361. ]);
  1362. expect(page.hasMore).toBe(false);
  1363. expect(page.items).toEqual([
  1364. {
  1365. sequence: expect.any(Number),
  1366. siteId: "report#1",
  1367. ordinal: 1,
  1368. fields: { round: 1, ok: true, "timing.ms": 12.5, note: null },
  1369. },
  1370. ]);
  1371. expect(page.items[0]).not.toHaveProperty("item");
  1372. });
  1373. it("像整数的段在数组上是下标、在对象上是键,与渲染器的路径规则相同", async () => {
  1374. const { db, journal } = openIntrospectableJournal();
  1375. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1376. seed(journal, "run_1", [
  1377. {
  1378. rows: [{ v: 1 }, { v: 2 }],
  1379. byKey: { "0": "zero", "01": "zero-one" },
  1380. empty: { "": { b: 7 } },
  1381. },
  1382. ]);
  1383. const [entry] = readFields(journal, [
  1384. "rows.1.v",
  1385. "rows.01.v", // Number("01") = 1:数组上仍是下标 1
  1386. "rows.5.v", // 越界
  1387. "rows.x", // 数组上的非整数段
  1388. "byKey.0",
  1389. "byKey.01",
  1390. "empty..b", // 空段是一个空键
  1391. ]).items;
  1392. expect(entry?.fields).toEqual({
  1393. "rows.1.v": 2,
  1394. "rows.01.v": 2,
  1395. "byKey.0": "zero",
  1396. "byKey.01": "zero-one",
  1397. "empty..b": 7,
  1398. });
  1399. });
  1400. it("键里带引号与反斜杠照样取得到", async () => {
  1401. const { db, journal } = openIntrospectableJournal();
  1402. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1403. seed(journal, "run_1", [{ 'say"hi': 1, "back\\slash": 2, 中文: 3 }]);
  1404. const [entry] = readFields(journal, ['say"hi', "back\\slash", "中文"]).items;
  1405. expect(entry?.fields).toEqual({ 'say"hi': 1, "back\\slash": 2, 中文: 3 });
  1406. });
  1407. it("超过值的字节上界的值回成截短的字符串,一个大值不会整段进 JavaScript", async () => {
  1408. const { db, journal } = openIntrospectableJournal();
  1409. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1410. seed(journal, "run_1", [
  1411. { text: "y".repeat(10_000), list: Array.from({ length: 2000 }, (_v, i) => i) },
  1412. ]);
  1413. const [entry] = readFields(journal, ["text", "list"]).items;
  1414. expect(entry?.fields?.text).toBe(`${"y".repeat(1000)}…`);
  1415. const list = entry?.fields?.list as string;
  1416. expect(typeof list).toBe("string");
  1417. expect(list.startsWith("[0,1,2,3")).toBe(true);
  1418. expect(list).toHaveLength(1001);
  1419. });
  1420. it("页按取出的字段值计字节:大 item 里只取一个小字段时一页装得下很多条", async () => {
  1421. const { db, journal } = openIntrospectableJournal();
  1422. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1423. seed(
  1424. journal,
  1425. "run_1",
  1426. Array.from({ length: 5 }, (_v, round) => ({ round, pad: "z".repeat(50_000) })),
  1427. );
  1428. // 整条 item 每条 50 KB,但只取 round:5 条远在 1 KB 之内。
  1429. const small = readFields(journal, ["round"], { maxBytes: 1000 });
  1430. expect(small.items.map((entry) => entry.fields?.round)).toEqual([0, 1, 2, 3, 4]);
  1431. expect(small.hasMore).toBe(false);
  1432. // 取 pad(每条截短到约 1 KB)时,同样的 2.5 KB 只装得下两条,并报 hasMore。
  1433. const padded = readFields(journal, ["pad"], { maxBytes: 2500 });
  1434. expect(padded.items).toHaveLength(2);
  1435. expect(padded.hasMore).toBe(true);
  1436. // 条数界与游标照常。
  1437. const limited = readFields(journal, ["round"], { limit: 2 });
  1438. expect(limited.items.map((entry) => entry.fields?.round)).toEqual([0, 1]);
  1439. expect(limited.hasMore).toBe(true);
  1440. const rest = readFields(journal, ["round"], { afterSequence: limited.items[1]!.sequence });
  1441. expect(rest.items.map((entry) => entry.fields?.round)).toEqual([2, 3, 4]);
  1442. });
  1443. });
  1444. describe("SQLite dwf journal store — listEventPage", () => {
  1445. it("全部类型、item 原样,按条数分页并判定 hasMore", async () => {
  1446. const { db, journal } = openIntrospectableJournal();
  1447. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1448. journal.appendEvent("run_1", { type: "log", message: "a" });
  1449. journal.appendEvent("run_1", {
  1450. type: "report",
  1451. instance: { siteId: "report#1", ordinal: 1 },
  1452. item: { finding: 1 },
  1453. });
  1454. journal.appendEvent("run_1", { type: "log", message: "b" });
  1455. const all = journal.listEvents("run_1", { types: "all", reportItems: "all" });
  1456. const first = journal.listEventPage("run_1", { limit: 2, maxBytes: 1 << 30 });
  1457. expect(first.events).toEqual(all.slice(0, 2));
  1458. expect(first.hasMore).toBe(true);
  1459. const rest = journal.listEventPage("run_1", {
  1460. afterSequence: first.events.at(-1)!.sequence,
  1461. limit: 2,
  1462. maxBytes: 1 << 30,
  1463. });
  1464. expect(rest).toEqual({ events: all.slice(2), hasMore: false });
  1465. });
  1466. it("字节界同看板条目:带大 item 的事件让页提前收尾,但每页至少一条", async () => {
  1467. const { db, journal } = openIntrospectableJournal();
  1468. seedRun(db, journal, { runId: "run_1", cwd: "/repo" });
  1469. for (let ordinal = 1; ordinal <= 3; ordinal += 1) {
  1470. journal.appendEvent("run_1", {
  1471. type: "report",
  1472. instance: { siteId: "report#1", ordinal },
  1473. item: "y".repeat(4096),
  1474. });
  1475. }
  1476. const seen: number[] = [];
  1477. let cursor: number | undefined;
  1478. for (;;) {
  1479. const page = journal.listEventPage("run_1", {
  1480. ...(cursor === undefined ? {} : { afterSequence: cursor }),
  1481. limit: 500,
  1482. maxBytes: 5000,
  1483. });
  1484. expect(page.events).toHaveLength(1);
  1485. seen.push(...page.events.map((stored) => stored.sequence));
  1486. cursor = page.events.at(-1)!.sequence;
  1487. if (!page.hasMore) break;
  1488. }
  1489. expect(seen).toHaveLength(3);
  1490. });
  1491. });
  1492. // ————————————————————————————————————————————————————————————————
  1493. // 零迁移终态编码(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「The journal」):物理列仍是旧五值,
  1494. // 逻辑 `errored` / `stopped{reason}` 只活在编解码里。下面这张表就是 spec 里用户复核过的那张。
  1495. // ————————————————————————————————————————————————————————————————
  1496. describe("SqliteDwfJournalStore 终态编码(零迁移)", () => {
  1497. const PARENT = "ses_terminal";
  1498. function insertPhysicalRow(
  1499. db: DatabaseSync,
  1500. runId: string,
  1501. status: string,
  1502. failureJson: string | null,
  1503. timeUpdated = 1,
  1504. ): void {
  1505. db.prepare(
  1506. `insert into dwf_run (id, parent_session_id, cwd, caps_max_concurrency, spent_tokens, status,
  1507. failure_json, time_created, time_updated) values (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
  1508. ).run(runId, PARENT, "/repo", 4, 0, status, failureJson, 1, timeUpdated);
  1509. }
  1510. it("历史行按表解码:cancelled→stopped(user),failed+Interrupted→stopped(interrupted),其余 failed→errored", async () => {
  1511. const { db, journal } = openIntrospectableJournal();
  1512. insertPhysicalRow(db, "old_pending", "pending", null);
  1513. insertPhysicalRow(db, "old_running", "running", null);
  1514. insertPhysicalRow(db, "old_completed", "completed", null);
  1515. insertPhysicalRow(db, "old_cancelled", "cancelled", null);
  1516. insertPhysicalRow(
  1517. db,
  1518. "old_interrupted",
  1519. "failed",
  1520. JSON.stringify({ code: "Interrupted", message: "owning process exited" }),
  1521. );
  1522. insertPhysicalRow(
  1523. db,
  1524. "old_provider_crash",
  1525. "failed",
  1526. JSON.stringify({
  1527. code: "DriverError",
  1528. message: "Subagent turn failed",
  1529. modelFailureReason: "rate_limited",
  1530. }),
  1531. );
  1532. insertPhysicalRow(
  1533. db,
  1534. "old_script_error",
  1535. "failed",
  1536. JSON.stringify({ code: "DriverError", message: "boom" }),
  1537. );
  1538. insertPhysicalRow(
  1539. db,
  1540. "old_cap",
  1541. "failed",
  1542. JSON.stringify({ code: "ReportCapExceeded", message: "over" }),
  1543. );
  1544. insertPhysicalRow(db, "old_failed_bare", "failed", null);
  1545. const statusOf = (runId: string) => {
  1546. const record = journal.getRun(runId)!;
  1547. return { status: record.status, stopReason: record.stopReason, code: record.failure?.code };
  1548. };
  1549. expect(statusOf("old_pending")).toEqual({
  1550. status: "pending",
  1551. stopReason: undefined,
  1552. code: undefined,
  1553. });
  1554. expect(statusOf("old_running")).toEqual({
  1555. status: "running",
  1556. stopReason: undefined,
  1557. code: undefined,
  1558. });
  1559. expect(statusOf("old_completed")).toEqual({
  1560. status: "completed",
  1561. stopReason: undefined,
  1562. code: undefined,
  1563. });
  1564. expect(statusOf("old_cancelled")).toEqual({
  1565. status: "stopped",
  1566. stopReason: "user",
  1567. code: undefined,
  1568. });
  1569. expect(statusOf("old_interrupted")).toEqual({
  1570. status: "stopped",
  1571. stopReason: "interrupted",
  1572. code: "Interrupted",
  1573. });
  1574. // 第 6 行(用户复核裁决):老的 provider 崩溃仍是 errored,不可 resume。
  1575. expect(statusOf("old_provider_crash")).toEqual({
  1576. status: "errored",
  1577. stopReason: undefined,
  1578. code: "DriverError",
  1579. });
  1580. expect(statusOf("old_script_error")).toEqual({
  1581. status: "errored",
  1582. stopReason: undefined,
  1583. code: "DriverError",
  1584. });
  1585. expect(statusOf("old_cap")).toEqual({
  1586. status: "errored",
  1587. stopReason: undefined,
  1588. code: "ReportCapExceeded",
  1589. });
  1590. expect(statusOf("old_failed_bare")).toEqual({
  1591. status: "errored",
  1592. stopReason: undefined,
  1593. code: undefined,
  1594. });
  1595. // 缺席的键真的缺席(契约测的 toEqual 风格)。
  1596. expect("stopReason" in journal.getRun("old_completed")!).toBe(false);
  1597. expect("failure" in journal.getRun("old_cancelled")!).toBe(false);
  1598. });
  1599. it("新写入的 stopped 落成 cancelled + 信封,errored 落成 failed + 原样失败;往返逐字段相等", async () => {
  1600. const { db, journal } = openIntrospectableJournal();
  1601. for (const runId of ["s_user", "s_model", "s_provider", "s_interrupted", "e_script"]) {
  1602. journal.createRun({
  1603. runId,
  1604. parentSessionId: PARENT,
  1605. cwd: "/repo",
  1606. caps: CAPS,
  1607. spentTokens: 0,
  1608. status: "running",
  1609. });
  1610. }
  1611. journal.updateRunStatus("s_user", "stopped", { stopReason: "user" });
  1612. journal.updateRunStatus("s_model", "stopped", { stopReason: "model" });
  1613. const providerStop = {
  1614. code: "ProviderStop" as const,
  1615. message: "Sign-in to BigModel expired.",
  1616. providerStop: {
  1617. kind: "auth" as const,
  1618. reason: "auth_failed",
  1619. providerCode: "1006",
  1620. subagent: "verify@2",
  1621. },
  1622. };
  1623. journal.updateRunStatus("s_provider", "stopped", {
  1624. stopReason: "provider",
  1625. failure: providerStop,
  1626. });
  1627. journal.updateRunStatus("s_interrupted", "stopped", {
  1628. stopReason: "interrupted",
  1629. failure: { code: "Interrupted", message: "owning process exited" },
  1630. });
  1631. journal.updateRunStatus("e_script", "errored", {
  1632. failure: { code: "DriverError", message: "boom" },
  1633. });
  1634. const physical = db
  1635. .prepare(
  1636. "select id, status, failure_json from dwf_run where parent_session_id = ? order by id",
  1637. )
  1638. .all(PARENT) as { id: string; status: string; failure_json: string | null }[];
  1639. expect(physical.map((row) => [row.id, row.status])).toEqual([
  1640. ["e_script", "failed"],
  1641. ["s_interrupted", "cancelled"],
  1642. ["s_model", "cancelled"],
  1643. ["s_provider", "cancelled"],
  1644. ["s_user", "cancelled"],
  1645. ]);
  1646. expect(JSON.parse(physical.find((row) => row.id === "s_user")!.failure_json!)).toEqual({
  1647. stopReason: "user",
  1648. });
  1649. expect(JSON.parse(physical.find((row) => row.id === "s_provider")!.failure_json!)).toEqual({
  1650. stopReason: "provider",
  1651. error: providerStop,
  1652. });
  1653. expect(JSON.parse(physical.find((row) => row.id === "e_script")!.failure_json!)).toEqual({
  1654. code: "DriverError",
  1655. message: "boom",
  1656. });
  1657. expect(journal.getRun("s_user")).toMatchObject({ status: "stopped", stopReason: "user" });
  1658. expect("failure" in journal.getRun("s_user")!).toBe(false);
  1659. expect(journal.getRun("s_model")).toMatchObject({ status: "stopped", stopReason: "model" });
  1660. expect(journal.getRun("s_provider")).toMatchObject({
  1661. status: "stopped",
  1662. stopReason: "provider",
  1663. failure: providerStop,
  1664. });
  1665. expect(journal.getRun("s_interrupted")).toMatchObject({
  1666. status: "stopped",
  1667. stopReason: "interrupted",
  1668. });
  1669. expect(journal.getRun("e_script")).toMatchObject({
  1670. status: "errored",
  1671. failure: { code: "DriverError" },
  1672. });
  1673. expect("stopReason" in journal.getRun("e_script")!).toBe(false);
  1674. // 物理终态集没变:非终态查询一条都不回。
  1675. expect(journal.listNonTerminalRuns(PARENT)).toEqual([]);
  1676. // resume 翻回 running 清掉信封(与契约套件同语义)。
  1677. journal.updateRunStatus("s_provider", "running");
  1678. expect(journal.getRun("s_provider")).toMatchObject({ status: "running" });
  1679. expect("stopReason" in journal.getRun("s_provider")!).toBe(false);
  1680. });
  1681. it("statuses 过滤在 SQL 里分清 errored 与 stopped(共享物理 failed)", async () => {
  1682. const { db, journal } = openIntrospectableJournal();
  1683. insertPhysicalRow(db, "p_cancelled", "cancelled", null, 5);
  1684. insertPhysicalRow(
  1685. db,
  1686. "p_interrupted",
  1687. "failed",
  1688. JSON.stringify({ code: "Interrupted", message: "x" }),
  1689. 4,
  1690. );
  1691. insertPhysicalRow(
  1692. db,
  1693. "p_errored",
  1694. "failed",
  1695. JSON.stringify({ code: "DriverError", message: "x" }),
  1696. 3,
  1697. );
  1698. insertPhysicalRow(db, "p_errored_bare", "failed", null, 2);
  1699. insertPhysicalRow(db, "p_completed", "completed", null, 1);
  1700. journal.createRun({
  1701. runId: "n_stopped",
  1702. parentSessionId: PARENT,
  1703. cwd: "/repo",
  1704. caps: CAPS,
  1705. spentTokens: 0,
  1706. status: "running",
  1707. });
  1708. journal.updateRunStatus("n_stopped", "stopped", { stopReason: "provider" });
  1709. const ids = (statuses: RunRecord["status"][]) =>
  1710. journal
  1711. .listRuns({ cwd: "/repo", limit: 20, statuses })
  1712. .map((row) => row.runId)
  1713. .sort();
  1714. expect(ids(["stopped"])).toEqual(["n_stopped", "p_cancelled", "p_interrupted"]);
  1715. expect(ids(["errored"])).toEqual(["p_errored", "p_errored_bare"]);
  1716. expect(ids(["completed", "errored"])).toEqual(["p_completed", "p_errored", "p_errored_bare"]);
  1717. // limit 作用在过滤之后:errored 只有两条时 limit 1 回最近更新的那条,且不被 stopped 行挤占。
  1718. expect(
  1719. journal.listRuns({ cwd: "/repo", limit: 1, statuses: ["errored"] }).map((row) => row.runId),
  1720. ).toEqual(["p_errored"]);
  1721. // 枚举行带 stopReason(逻辑词汇),不带 failure(仍是窄投影)。
  1722. const stopped = journal.listRuns({ cwd: "/repo", limit: 20, statuses: ["stopped"] });
  1723. expect(stopped.find((row) => row.runId === "p_interrupted")).toMatchObject({
  1724. stopReason: "interrupted",
  1725. });
  1726. expect(stopped.find((row) => row.runId === "n_stopped")).toMatchObject({
  1727. stopReason: "provider",
  1728. });
  1729. expect(stopped.every((row) => !("failure" in row))).toBe(true);
  1730. });
  1731. });
  1732. /**
  1733. * 每一世的活动区间(完成卡的时长口径,
  1734. * docs/dynamic-workflow/transcript-and-notifications.md「How long it took」)。
  1735. *
  1736. * 事件的时刻由 appendEvent 打 `Date.now()`,所以「一世持续了多久」在测试里只能事后钉:追加完
  1737. * 事件再按 sequence 改写 `time_created`,模拟一条跑了几个小时、中间被重启打断的 run。改写的是
  1738. * 这条读面唯一读的那一列,查询形状与真库上逐字相同。
  1739. */
  1740. describe("SQLite dwf journal store — listRunLifeSpans", () => {
  1741. const RUN_ID = "run_lives";
  1742. /** 按 sequence 钉住某几条事件的时刻。 */
  1743. function stampEvent(db: DatabaseSync, sequence: number, timeCreated: number): void {
  1744. db.prepare("update dwf_event set time_created = ? where run_id = ? and sequence = ?").run(
  1745. timeCreated,
  1746. RUN_ID,
  1747. sequence,
  1748. );
  1749. }
  1750. function seedLifeRun(): {
  1751. db: DatabaseSync;
  1752. journal: JournalStorePort & DwfRunIntrospectionQueries;
  1753. } {
  1754. const { db, journal } = openIntrospectableJournal();
  1755. journal.createRun({ runId: RUN_ID, caps: CAPS, spentTokens: 0, status: "running" });
  1756. return { db, journal };
  1757. }
  1758. it("单世:从 run-started 到这一世最后一条事件", async () => {
  1759. const { db, journal } = seedLifeRun();
  1760. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1761. journal.appendEvent(RUN_ID, { type: "log", message: "工作中" });
  1762. journal.appendEvent(RUN_ID, { type: "run-settled", status: "completed" });
  1763. stampEvent(db, 0, 1_000);
  1764. stampEvent(db, 1, 5_000);
  1765. stampEvent(db, 2, 61_000);
  1766. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([
  1767. { startedAt: 1_000, lastActivityAt: 61_000 },
  1768. ]);
  1769. });
  1770. it("多世:每一世各算一段,世与世之间的空档不出现在任何一段里", async () => {
  1771. const { db, journal } = seedLifeRun();
  1772. // 第一世:跑了一小时后被重启打断(没有 run-settled)。
  1773. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1774. journal.appendEvent(RUN_ID, { type: "log", message: "第一世的最后一次动作" });
  1775. // 第二世:整个周末之后才 resume,两分钟后完成。
  1776. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1777. journal.appendEvent(RUN_ID, { type: "log", message: "重放" });
  1778. journal.appendEvent(RUN_ID, { type: "run-settled", status: "completed" });
  1779. stampEvent(db, 0, 0);
  1780. stampEvent(db, 1, 3_600_000);
  1781. stampEvent(db, 2, 200_000_000);
  1782. stampEvent(db, 3, 200_060_000);
  1783. stampEvent(db, 4, 200_120_000);
  1784. const spans = journal.listRunLifeSpans(RUN_ID);
  1785. expect(spans).toEqual([
  1786. { startedAt: 0, lastActivityAt: 3_600_000 },
  1787. { startedAt: 200_000_000, lastActivityAt: 200_120_000 },
  1788. ]);
  1789. // 活动时长之和 = 1 小时 + 2 分钟;两世之间那段死时间(≈ 54 小时)不在其中。
  1790. const activeMs = spans.reduce((sum, span) => sum + (span.lastActivityAt - span.startedAt), 0);
  1791. expect(activeMs).toBe(3_600_000 + 120_000);
  1792. });
  1793. it("一世里只有 run-started 一条事件:区间退化成 0,不是 null", async () => {
  1794. const { db, journal } = seedLifeRun();
  1795. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1796. stampEvent(db, 0, 7_000);
  1797. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([{ startedAt: 7_000, lastActivityAt: 7_000 }]);
  1798. });
  1799. it("没有 run-started 的 run 与未知 run 都回空数组(无证据,不是 0 时长)", async () => {
  1800. const { journal } = seedLifeRun();
  1801. journal.appendEvent(RUN_ID, { type: "log", message: "只有日志" });
  1802. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([]);
  1803. expect(journal.listRunLifeSpans("run_never_seen")).toEqual([]);
  1804. });
  1805. it("只看本 run 的事件:另一条 run 的世不混进来", async () => {
  1806. const { db, journal } = seedLifeRun();
  1807. journal.createRun({ runId: "run_other", caps: CAPS, spentTokens: 0, status: "running" });
  1808. journal.appendEvent(RUN_ID, { type: "run-started", runId: RUN_ID, caps: CAPS });
  1809. journal.appendEvent("run_other", { type: "run-started", runId: "run_other", caps: CAPS });
  1810. journal.appendEvent("run_other", { type: "log", message: "别人的活" });
  1811. stampEvent(db, 0, 10_000);
  1812. db.prepare("update dwf_event set time_created = ? where run_id = 'run_other'").run(999_000);
  1813. expect(journal.listRunLifeSpans(RUN_ID)).toEqual([
  1814. { startedAt: 10_000, lastActivityAt: 10_000 },
  1815. ]);
  1816. expect(journal.listRunLifeSpans("run_other")).toEqual([
  1817. { startedAt: 999_000, lastActivityAt: 999_000 },
  1818. ]);
  1819. });
  1820. });
  1821. // 计数查询不得复用带 limit 的目录,也不能跨父会话或加载结果正文。
  1822. it("reads complete lightweight workflow activity history beyond preview limits", () => {
  1823. const { db, journal } = openJournalDb();
  1824. for (let index = 0; index < 11; index++) {
  1825. journal.createRun({
  1826. ...RUN,
  1827. runId: `history-${index}`,
  1828. status: index < 9 ? "completed" : "stopped",
  1829. });
  1830. }
  1831. journal.createRun({ ...RUN, runId: "foreign", parentSessionId: "another", status: "completed" });
  1832. journal.putActor({ ...ACTOR, runId: "history-0" });
  1833. const history = createDwfJournalStore(db) as JournalStorePort & {
  1834. getActivityHistory(
  1835. parentSessionId: string,
  1836. ): import("@zcode/contracts").DynamicWorkflowActivityHistory;
  1837. };
  1838. const result = history.getActivityHistory(RUN.parentSessionId!);
  1839. expect(result.runs).toHaveLength(11);
  1840. expect(result.runs.filter((run) => run.status === "completed")).toHaveLength(9);
  1841. expect(
  1842. result.runs.every((run) => Object.keys(run).sort().join() === "runId,sequence,status"),
  1843. ).toBe(true);
  1844. expect(result.childSessionIds).toEqual([ACTOR.sessionId]);
  1845. });
  1846. it.each(["baseline", "upgrade"] as const)(
  1847. "%s 活动历史查询只检索本会话,升级不改数据且重复打开幂等",
  1848. async (mode) => {
  1849. const directory = await mkdtemp(join(tmpdir(), "dwf-parent-index-"));
  1850. const dbPath = join(directory, "session.sqlite");
  1851. const db = new DatabaseSync(dbPath);
  1852. const migrationId = "0026_dwf_run_parent_session_index";
  1853. try {
  1854. if (mode === "baseline") {
  1855. db.exec(
  1856. await readFile(
  1857. new URL("../src/storage/session-store/schema.baseline.sql", import.meta.url),
  1858. "utf8",
  1859. ),
  1860. );
  1861. } else {
  1862. db.exec("BEGIN IMMEDIATE");
  1863. ensureSqliteSchemaMigrationTable(db);
  1864. for (const migration of SQLITE_MIGRATIONS.filter((item) => item.id < migrationId))
  1865. applySqliteSchemaMigration(db, migration);
  1866. db.exec("COMMIT");
  1867. }
  1868. const journal = createDwfJournalStore(db);
  1869. const history = journal as JournalStorePort & {
  1870. getActivityHistory(
  1871. parent: string,
  1872. ): import("@zcode/contracts").DynamicWorkflowActivityHistory;
  1873. };
  1874. journal.createRun(RUN);
  1875. journal.putActor(ACTOR);
  1876. journal.appendEvent(RUN.runId, { type: "run-started", runId: RUN.runId, caps: CAPS });
  1877. const expected = history.getActivityHistory(RUN.parentSessionId!);
  1878. // 无关会话远多于目标会话;断言查询计划而不是依赖机器速度的耗时阈值。
  1879. db.exec("BEGIN");
  1880. const insertRun = db.prepare(
  1881. "INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES(?,?,1,'completed',1,1)",
  1882. );
  1883. const insertActor = db.prepare(
  1884. "INSERT INTO dwf_actor(run_id,site_id,ordinal,session_id,time_created,time_updated) VALUES(?,'worker',?,?,1,1)",
  1885. );
  1886. for (let i = 0; i < 10_000; i++) {
  1887. const runId = `unrelated-${i}`;
  1888. insertRun.run(runId, "another-parent");
  1889. for (let j = 0; j < 3; j++) insertActor.run(runId, j, `${runId}-${j}`);
  1890. }
  1891. db.exec("COMMIT");
  1892. const rows = () =>
  1893. ["dwf_run", "dwf_actor", "dwf_node", "dwf_event"].map((table) =>
  1894. db.prepare(`SELECT * FROM ${table} ORDER BY id`).all(),
  1895. );
  1896. const before = rows();
  1897. if (mode === "upgrade") {
  1898. await runSqliteSessionMigrations(db, dbPath);
  1899. expect(rows()).toEqual(before);
  1900. const record = db.prepare("SELECT * FROM schema_migration WHERE id=?").get(migrationId);
  1901. expect(record).toBeDefined();
  1902. await runSqliteSessionMigrations(db, dbPath);
  1903. expect(db.prepare("SELECT * FROM schema_migration WHERE id=?").get(migrationId)).toEqual(
  1904. record,
  1905. );
  1906. expect(rows()).toEqual(before);
  1907. }
  1908. const prepare = vi.spyOn(db, "prepare");
  1909. const actual = history.getActivityHistory(RUN.parentSessionId!);
  1910. const queries = prepare.mock.calls.map(([sql]) => sql);
  1911. prepare.mockRestore();
  1912. expect(actual).toEqual(expected);
  1913. expect(queries).toHaveLength(2);
  1914. const plans = queries.map((sql) =>
  1915. db
  1916. .prepare("EXPLAIN QUERY PLAN " + sql)
  1917. .all(RUN.parentSessionId!)
  1918. .map((row) => String(row.detail))
  1919. .join("\n"),
  1920. );
  1921. for (const plan of plans) {
  1922. expect(plan).toContain("SEARCH r USING INDEX dwf_run_parent_session_idx");
  1923. expect(plan).not.toMatch(/SCAN [ra]\b/);
  1924. }
  1925. expect(plans[1]).toContain("SEARCH a USING INDEX dwf_actor_run_idx");
  1926. } finally {
  1927. db.close();
  1928. await rm(directory, { force: true, recursive: true });
  1929. }
  1930. },
  1931. );