zcodeProtocolV4WorkflowRunsCaps.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. // workflowRuns 的**界**留下的三样东西:被拒实例的计数器、整键的条目预算、给旧消费者的裁剪。
  2. //
  3. // 改造前 nodes/actors 压在 256,是因为状态键按事件整体重发、无界即 O(N²) 字节;键级增量落地后
  4. // 那条理由没了,界抬到 1024。但抬界不是免费的:一个 50 路 fan-out 的宽工作流仍然可能把整张表
  5. // 撑到几 MB,所以多了一条**跨 run 的**条目预算;而触界仍然会拒掉实例,所以读面必须能说出
  6. // 「有多少步没进表」——这就是两个计数器存在的全部理由。
  7. import { describe, expect, it } from "vitest";
  8. import { z } from "zod";
  9. import {
  10. WORKFLOW_RUNS_LEGACY_LIMITS,
  11. WORKFLOW_RUNS_LIMITS,
  12. applyConversationDeltas,
  13. clampWorkflowRunsForLegacy,
  14. diffWorkflowRunsState,
  15. reduceWorkflowRunsState,
  16. workflowRunActorSchema,
  17. workflowRunNodeSchema,
  18. workflowRunSchema,
  19. workflowRunStepCounts,
  20. workflowRunsStateSchema,
  21. type ConversationSnapshot,
  22. type WorkflowRunNode,
  23. type WorkflowRunProgressEnvelope,
  24. type WorkflowRunState,
  25. type WorkflowRunsState,
  26. } from "../src/zcode-protocol-v4/index.js";
  27. const RUN_ID = "dwfrun-1";
  28. /** 一条手搓的 run:直接把表灌满,省下上千次归约(被测的是触界之后的事)。 */
  29. function runWith(
  30. overrides: Partial<WorkflowRunState> & { runId?: string } = {},
  31. nodeCount = 0,
  32. actorCount = 0,
  33. ): WorkflowRunState {
  34. return {
  35. runId: overrides.runId ?? RUN_ID,
  36. // 事件信封一律带 tc-1:不在夹具里先补上,第一条事件就会因为「补齐 toolCallId」而产生变化,
  37. // 把本文件所有「这条事件什么都不该改」的断言变成假阳性。
  38. toolCallId: "tc-1",
  39. status: "running",
  40. usage: { spentTokens: 0, nodesUsed: 0 },
  41. actors: Array.from({ length: actorCount }, (_, index) => ({
  42. siteId: "actor#1",
  43. ordinal: index,
  44. status: "completed" as const,
  45. })),
  46. nodes: Array.from({ length: nodeCount }, (_, index) => ({
  47. siteId: "ask#1",
  48. ordinal: index,
  49. phase: "settled" as const,
  50. })),
  51. lastEventSequence: 100,
  52. ...overrides,
  53. };
  54. }
  55. function stateWith(...runs: WorkflowRunState[]): WorkflowRunsState {
  56. return { revision: 10, runs };
  57. }
  58. /** 事件信封:sequence 显式给,本文件大半的断言都盯着水位。 */
  59. function event(
  60. eventType: string,
  61. payload: Record<string, unknown>,
  62. sequence: number,
  63. runId = RUN_ID,
  64. ): WorkflowRunProgressEnvelope {
  65. return { runId, toolCallId: "tc-1", sequence, eventType, payload };
  66. }
  67. const FULL_NODES = WORKFLOW_RUNS_LIMITS.maxNodes;
  68. /**
  69. * 表已满、且**一条都淘汰不动**的 run:之后每一条新实例都会被拒。
  70. *
  71. * 节点全部停在 `executing` 是这条夹具的要点:腾位只淘汰终态条目
  72. * (workflow-runs-eviction.ts),所以一张全是活节点的满表恰好就是「拒新」那条老路径,
  73. * 而本节钉的正是被拒实例怎么继续可数。淘汰路径在 …WorkflowRunsEviction.test.ts。
  74. */
  75. const fullRun = () =>
  76. runWith(
  77. {
  78. truncated: true,
  79. nodes: Array.from({ length: FULL_NODES }, (_, index) => ({
  80. siteId: "ask#1",
  81. ordinal: index,
  82. phase: "executing" as const,
  83. })),
  84. },
  85. FULL_NODES,
  86. );
  87. /** 一个表里没有的实例(ordinal 远在界外)。 */
  88. const rejected = (ordinal: number) => ({ siteId: "ask#9", ordinal });
  89. describe("WORKFLOW_RUNS_LIMITS:抬界之后的两条界", () => {
  90. it("nodes 与 actors 同界 1024;条目预算 6144 小于「满 8 条 run」的 16384", () => {
  91. expect(WORKFLOW_RUNS_LIMITS.maxNodes).toBe(1_024);
  92. expect(WORKFLOW_RUNS_LIMITS.maxActors).toBe(WORKFLOW_RUNS_LIMITS.maxNodes);
  93. expect(WORKFLOW_RUNS_LIMITS.maxTotalEntries).toBe(6_144);
  94. const worstCaseWithoutBudget =
  95. WORKFLOW_RUNS_LIMITS.maxRuns *
  96. (WORKFLOW_RUNS_LIMITS.maxNodes + WORKFLOW_RUNS_LIMITS.maxActors);
  97. expect(WORKFLOW_RUNS_LIMITS.maxTotalEntries).toBeLessThan(worstCaseWithoutBudget);
  98. });
  99. it("旧消费者的界是 256,且**永远不能变**(它是别人编译进去的校验界)", () => {
  100. expect(WORKFLOW_RUNS_LEGACY_LIMITS).toEqual({ maxActors: 256, maxNodes: 256 });
  101. });
  102. });
  103. describe("被拒实例的计数器(usage.nodesUnlisted / nodesUnlistedSettled)", () => {
  104. it("node-queued 撞界 → nodesUnlisted +1,表本身不增长", () => {
  105. const next = reduceWorkflowRunsState(
  106. stateWith(fullRun()),
  107. event("node-queued", { instance: rejected(5_000), kind: "ask" }, 101),
  108. );
  109. expect(next?.runs[0]?.nodes).toHaveLength(FULL_NODES);
  110. expect(next?.runs[0]?.usage).toEqual({
  111. spentTokens: 0,
  112. nodesUsed: 0,
  113. nodesUnlisted: 1,
  114. });
  115. expect(workflowRunsStateSchema.safeParse(next).success).toBe(true);
  116. });
  117. it("缓存命中的结算是**出生**:两个计数器一起 +1", () => {
  118. const next = reduceWorkflowRunsState(
  119. stateWith(fullRun()),
  120. event("node-settled", { instance: rejected(5_000), outcome: "ok", cached: true }, 101),
  121. );
  122. expect(next?.runs[0]?.usage).toMatchObject({ nodesUnlisted: 1, nodesUnlistedSettled: 1 });
  123. });
  124. it("普通 node-settled 只 +settled:它的出生(queued)此前已经计过", () => {
  125. const queued = reduceWorkflowRunsState(
  126. stateWith(fullRun()),
  127. event("node-queued", { instance: rejected(5_000), kind: "ask" }, 101),
  128. )!;
  129. const settled = reduceWorkflowRunsState(
  130. queued,
  131. event("node-settled", { instance: rejected(5_000), outcome: "ok" }, 102),
  132. );
  133. expect(settled?.runs[0]?.usage).toMatchObject({ nodesUnlisted: 1, nodesUnlistedSettled: 1 });
  134. });
  135. it("被拒实例的中间相位一个都不计(dispatched / executing / waiting / repairing / nudged / progress)", () => {
  136. let state: WorkflowRunsState = stateWith(fullRun());
  137. let sequence = 100;
  138. for (const eventType of [
  139. "node-dispatched",
  140. "node-executing",
  141. "node-waiting",
  142. "node-repairing",
  143. "node-nudged",
  144. "node-progress",
  145. ]) {
  146. sequence += 1;
  147. state =
  148. reduceWorkflowRunsState(state, event(eventType, { instance: rejected(5_000) }, sequence)) ??
  149. state;
  150. }
  151. expect(state.runs[0]?.usage).not.toHaveProperty("nodesUnlisted");
  152. expect(state.runs[0]?.usage).not.toHaveProperty("nodesUnlistedSettled");
  153. // `nodesUsed` 是另一码事,而且是**既有**行为:首次派发计一步,被拒实例照样计——
  154. // 步数是 run 级事实,不受展示界约束(归约主文件里 firstDispatch 那段注释)。
  155. expect(state.runs[0]?.usage.nodesUsed).toBe(1);
  156. // 水位照抬:事件到达过是事实,只是它不改变「有多少步没进表」。
  157. expect(state.runs[0]?.lastEventSequence).toBe(sequence);
  158. });
  159. it("**在表里**的实例永远不计:queued 与 settled 都只更新那一行", () => {
  160. const state = stateWith(runWith({}, 3));
  161. const queued = reduceWorkflowRunsState(
  162. state,
  163. event("node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" }, 101),
  164. )!;
  165. expect(queued.runs[0]?.usage).toEqual({ spentTokens: 0, nodesUsed: 0 });
  166. const settled = reduceWorkflowRunsState(
  167. queued,
  168. event("node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" }, 102),
  169. )!;
  170. expect(settled.runs[0]?.usage).toEqual({ spentTokens: 0, nodesUsed: 0 });
  171. expect(settled.runs[0]?.nodes).toHaveLength(3);
  172. });
  173. it("同一条事件重放仍是 null no-op:只有抬过水位的事件才计数", () => {
  174. // 这是计数器唯一的幂等支点。没有这条守卫,一条被重传的队尾事件会把计数器越推越高,
  175. // 而计数器是**加出来**的、没有可去重的身份(被拒实例根本不在表里)。
  176. const replayed = event("node-queued", { instance: rejected(5_000), kind: "ask" }, 101);
  177. const once = reduceWorkflowRunsState(stateWith(fullRun()), replayed)!;
  178. expect(once.runs[0]?.usage).toMatchObject({ nodesUnlisted: 1 });
  179. expect(reduceWorkflowRunsState(once, replayed)).toBeNull();
  180. });
  181. it("迟到的低 sequence 事件不计数(水位没被抬过)", () => {
  182. const late = reduceWorkflowRunsState(
  183. stateWith(fullRun()),
  184. event("node-queued", { instance: rejected(5_000), kind: "ask" }, 50),
  185. );
  186. // 内容上没有任何变化:表满、水位不退、计数器不动 → 整条无变化。
  187. expect(late).toBeNull();
  188. });
  189. it("run-started 清零两个计数器:resume 会把整段脚本前缀重发一遍", () => {
  190. // 重开一世时引擎会把已完成实例的 cached settle 与新实例的 queued 全部再发一次,
  191. // 不清零就等于把上一世的「没进表的步数」和这一世的加在一起。
  192. const counted = reduceWorkflowRunsState(
  193. stateWith(fullRun()),
  194. event("node-settled", { instance: rejected(5_000), outcome: "ok", cached: true }, 101),
  195. )!;
  196. expect(counted.runs[0]?.usage).toMatchObject({ nodesUnlisted: 1, nodesUnlistedSettled: 1 });
  197. const rearmed = reduceWorkflowRunsState(
  198. counted,
  199. event("run-started", { caps: { maxConcurrency: 2 } }, 102),
  200. )!;
  201. expect(rearmed.runs[0]?.usage).toEqual({ spentTokens: 0, nodesUsed: 0 });
  202. });
  203. it("零时整个键缺席(不是 0):没撞过界的 run 一个新键都不多", () => {
  204. const next = reduceWorkflowRunsState(
  205. stateWith(runWith({}, 3)),
  206. event("node-queued", { instance: { siteId: "ask#2", ordinal: 1 }, kind: "ask" }, 101),
  207. );
  208. expect(next?.runs[0]?.usage).not.toHaveProperty("nodesUnlisted");
  209. expect(next?.runs[0]?.usage).not.toHaveProperty("nodesUnlistedSettled");
  210. });
  211. it("settled 永不超过 unlisted:每次结算的出生此前都计过(一世之内)", () => {
  212. // 引擎在一世之内对同一实例最多发一条 queued、最多发一条 settled(scheduler 的 settled 闩),
  213. // 缓存命中的结算则自带出生。所以这条不变量是**结构性**的,不靠夹逼。
  214. let state: WorkflowRunsState = stateWith(fullRun());
  215. let sequence = 100;
  216. const step = (eventType: string, payload: Record<string, unknown>) => {
  217. sequence += 1;
  218. state = reduceWorkflowRunsState(state, event(eventType, payload, sequence)) ?? state;
  219. };
  220. for (let ordinal = 5_000; ordinal < 5_005; ordinal += 1) {
  221. step("node-queued", { instance: rejected(ordinal), kind: "ask" });
  222. step("node-dispatched", { instance: rejected(ordinal) });
  223. step("node-settled", { instance: rejected(ordinal), outcome: "ok" });
  224. }
  225. // 一条只缓存命中的(没有 queued)。
  226. step("node-settled", { instance: rejected(6_000), outcome: "ok", cached: true });
  227. // 一条 queued 了但这一世永远没结算(run 级失败时引擎不补发 cancelled)。
  228. step("node-queued", { instance: rejected(7_000), kind: "ask" });
  229. const usage = state.runs[0]!.usage;
  230. expect(usage.nodesUnlisted).toBe(7);
  231. expect(usage.nodesUnlistedSettled).toBe(6);
  232. expect(usage.nodesUnlistedSettled!).toBeLessThanOrEqual(usage.nodesUnlisted!);
  233. });
  234. });
  235. describe("workflowRunStepCounts:表内 + 表外的唯一读法", () => {
  236. it("总数与已结算数都把被拒实例算进去", () => {
  237. const run = runWith(
  238. {
  239. usage: { spentTokens: 0, nodesUsed: 0, nodesUnlisted: 5, nodesUnlistedSettled: 2 },
  240. nodes: [
  241. { siteId: "ask#1", ordinal: 1, phase: "settled" },
  242. { siteId: "ask#1", ordinal: 2, phase: "executing" },
  243. { siteId: "ask#1", ordinal: 3, phase: "settled" },
  244. ] satisfies WorkflowRunNode[],
  245. },
  246. 0,
  247. );
  248. expect(workflowRunStepCounts(run)).toEqual({ total: 8, settled: 4 });
  249. });
  250. it("计数器缺席时退化成「表里有多少算多少」", () => {
  251. const run = runWith({
  252. nodes: [
  253. { siteId: "ask#1", ordinal: 1, phase: "settled" },
  254. { siteId: "ask#1", ordinal: 2, phase: "queued" },
  255. ] satisfies WorkflowRunNode[],
  256. });
  257. expect(workflowRunStepCounts(run)).toEqual({ total: 2, settled: 1 });
  258. });
  259. });
  260. describe("条目预算:整键 6144 条,淘汰最旧的终态 run", () => {
  261. // 一条**满界**的 run 是 1024 + 1024 = 2048 条,预算正好装得下三条。所以「四条满界的 run」
  262. // 是这条规则最小的现实场景:淘汰一条就回到预算内,不多淘汰一条。
  263. const FULL_RUN_ENTRIES = WORKFLOW_RUNS_LIMITS.maxNodes + WORKFLOW_RUNS_LIMITS.maxActors;
  264. const big = (runId: string, status: WorkflowRunState["status"]) =>
  265. runWith(
  266. { runId, status, truncated: true },
  267. WORKFLOW_RUNS_LIMITS.maxNodes,
  268. WORKFLOW_RUNS_LIMITS.maxActors,
  269. );
  270. const queueOne = (state: WorkflowRunsState) =>
  271. reduceWorkflowRunsState(
  272. state,
  273. event("node-queued", { instance: { siteId: "ask#new", ordinal: 1 }, kind: "ask" }, 101),
  274. )!;
  275. it("四条满界 run 超预算:淘汰最旧的终态 run,回到预算内就停手", () => {
  276. expect(FULL_RUN_ENTRIES * 4).toBeGreaterThan(WORKFLOW_RUNS_LIMITS.maxTotalEntries);
  277. expect(FULL_RUN_ENTRIES * 3).toBeLessThanOrEqual(WORKFLOW_RUNS_LIMITS.maxTotalEntries);
  278. const next = queueOne(
  279. stateWith(
  280. big("dwfrun-old-1", "completed"),
  281. big("dwfrun-old-2", "stopped"),
  282. big("dwfrun-live", "running"),
  283. big(RUN_ID, "running"),
  284. ),
  285. );
  286. // 只淘汰一条:老二虽然也是终态,但淘汰老大之后已经回到预算内。
  287. expect(next.runs.map((run) => run.runId)).toEqual(["dwfrun-old-2", "dwfrun-live", RUN_ID]);
  288. });
  289. it("绝不淘汰在跑的 run,也绝不淘汰事件所属的那条 run", () => {
  290. const next = queueOne(
  291. stateWith(
  292. big("dwfrun-live-1", "running"),
  293. big("dwfrun-live-2", "pending"),
  294. big("dwfrun-live-3", "running"),
  295. big(RUN_ID, "completed"),
  296. ),
  297. );
  298. // 唯一的终态 run 正是事件所属的那条 → 无人可淘汰,超预算也照留(诚实优先于省字节)。
  299. expect(next.runs.map((run) => run.runId)).toEqual([
  300. "dwfrun-live-1",
  301. "dwfrun-live-2",
  302. "dwfrun-live-3",
  303. RUN_ID,
  304. ]);
  305. });
  306. it("预算之内不动任何东西:run 对象保持引用(增量的快路径靠它)", () => {
  307. const state = stateWith(
  308. runWith({ runId: "dwfrun-old", status: "completed" }, 10),
  309. runWith({}, 10),
  310. );
  311. const next = queueOne(state);
  312. expect(next.runs).toHaveLength(2);
  313. expect(next.runs[0]).toBe(state.runs[0]);
  314. });
  315. it("预算淘汰在增量上说得出口:一条 workflowRun.removed,往返逐字节一致", () => {
  316. const state = stateWith(
  317. big("dwfrun-old-1", "completed"),
  318. big("dwfrun-old-2", "completed"),
  319. big("dwfrun-live", "running"),
  320. big(RUN_ID, "running"),
  321. );
  322. const next = queueOne(state);
  323. expect(next.runs.map((run) => run.runId)).toEqual(["dwfrun-old-2", "dwfrun-live", RUN_ID]);
  324. const deltas = diffWorkflowRunsState(state, next);
  325. expect(deltas[0]).toEqual({
  326. op: "workflowRun.removed",
  327. runId: "dwfrun-old-1",
  328. revision: next.revision,
  329. });
  330. const applied = applyConversationDeltas(snapshotWith(state), deltas);
  331. expect(JSON.stringify(applied.workflowRuns)).toBe(JSON.stringify(next));
  332. });
  333. });
  334. describe("clampWorkflowRunsForLegacy:没有增量能力的消费者", () => {
  335. // 旧消费者编译进去的是 .max(256):超界的帧会让**整个 state.updated patch** 解析失败、整帧被丢,
  336. // 于是那条订阅从此静默。这个裁剪是生产侧的第二道闸,「前 256 条」正是旧归约(拒新)的产物。
  337. const legacyStateSchema = z.object({
  338. revision: z.number().int().nonnegative(),
  339. runs: z
  340. .array(
  341. workflowRunSchema.extend({
  342. actors: z.array(workflowRunActorSchema).max(WORKFLOW_RUNS_LEGACY_LIMITS.maxActors),
  343. nodes: z.array(workflowRunNodeSchema).max(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes),
  344. }),
  345. )
  346. .max(WORKFLOW_RUNS_LIMITS.maxRuns),
  347. });
  348. it("每条 run 各裁到前 256,并置 truncated", () => {
  349. const state = stateWith(runWith({ runId: "dwfrun-wide" }, 900, 700));
  350. const clamped = clampWorkflowRunsForLegacy(state);
  351. expect(clamped.runs[0]?.nodes).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes);
  352. expect(clamped.runs[0]?.actors).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxActors);
  353. expect(clamped.runs[0]?.truncated).toBe(true);
  354. // 夹具里的条目全是终态,没有要先保的 → 留下的正是最早的那些实例。
  355. expect(clamped.runs[0]?.nodes[0]?.ordinal).toBe(0);
  356. expect(clamped.runs[0]?.nodes.at(-1)?.ordinal).toBe(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes - 1);
  357. expect(legacyStateSchema.safeParse(clamped).success).toBe(true);
  358. });
  359. // 裁剪保留的是**还在动的那些**:旧手机收到的是整键快照,而它要画的和新客户端一样是
  360. // 「此刻谁在跑」。一刀切前 256 条会让一个宽 run 在旧客户端上永远停在最早那批已结束的身上。
  361. it("还在动的先留:未结算的 node 与状态不是 completed 的 actor 不会被裁掉", () => {
  362. const live = (ordinal: number, phase: WorkflowRunNode["phase"]) => ({
  363. siteId: "ask#1",
  364. ordinal,
  365. phase,
  366. });
  367. const nodes: WorkflowRunNode[] = [
  368. ...Array.from({ length: 300 }, (_, index) => live(index, "settled")),
  369. live(300, "executing"),
  370. live(301, "queued"),
  371. ];
  372. const actors = [
  373. ...Array.from({ length: 300 }, (_, index) => ({
  374. siteId: "actor#1",
  375. ordinal: index,
  376. status: "completed" as const,
  377. })),
  378. { siteId: "actor#1", ordinal: 300, status: "running" as const },
  379. ];
  380. const clamped = clampWorkflowRunsForLegacy(stateWith(runWith({ nodes, actors }, 0, 0)));
  381. const keptNodes = clamped.runs[0]!.nodes;
  382. expect(keptNodes).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes);
  383. expect(keptNodes.map((node) => node.ordinal)).toContain(300);
  384. expect(keptNodes.map((node) => node.ordinal)).toContain(301);
  385. // 输出仍按原表序:留下的两条活节点在最后,剩下的名额按表序补最早的条目。
  386. expect(keptNodes.map((node) => node.ordinal)).toEqual([
  387. ...Array.from({ length: WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes - 2 }, (_, index) => index),
  388. 300,
  389. 301,
  390. ]);
  391. expect(clamped.runs[0]!.actors.map((actor) => actor.ordinal)).toContain(300);
  392. expect(legacyStateSchema.safeParse(clamped).success).toBe(true);
  393. });
  394. it("活条目多过旧界时按表序取前 256 条活的(仍然有界)", () => {
  395. const nodes: WorkflowRunNode[] = Array.from({ length: 400 }, (_, index) => ({
  396. siteId: "ask#1",
  397. ordinal: index,
  398. phase: "executing" as const,
  399. }));
  400. const clamped = clampWorkflowRunsForLegacy(stateWith(runWith({ nodes }, 0, 0)));
  401. expect(clamped.runs[0]!.nodes.map((node) => node.ordinal)).toEqual(
  402. Array.from({ length: WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes }, (_, index) => index),
  403. );
  404. });
  405. it("没什么可裁时返回**同一个对象**(每次 flush 都要跑一遍,身份不能白丢)", () => {
  406. const state = stateWith(runWith({}, 10, 10), runWith({ runId: "dwfrun-2" }, 0, 0));
  407. expect(clampWorkflowRunsForLegacy(state)).toBe(state);
  408. });
  409. it("只裁该裁的那条 run,其余保持引用", () => {
  410. const narrow = runWith({ runId: "dwfrun-narrow" }, 5, 5);
  411. const state = stateWith(narrow, runWith({ runId: "dwfrun-wide" }, 400, 0));
  412. const clamped = clampWorkflowRunsForLegacy(state);
  413. expect(clamped).not.toBe(state);
  414. expect(clamped.runs[0]).toBe(narrow);
  415. expect(clamped.runs[1]?.nodes).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes);
  416. });
  417. it("裁剪产物始终过旧界 schema:满界的 8 条 run 也一样", () => {
  418. const state: WorkflowRunsState = {
  419. revision: 3,
  420. runs: Array.from({ length: WORKFLOW_RUNS_LIMITS.maxRuns }, (_, index) =>
  421. runWith({ runId: `dwfrun-${index}` }, WORKFLOW_RUNS_LIMITS.maxNodes, 300),
  422. ),
  423. };
  424. const clamped = clampWorkflowRunsForLegacy(state);
  425. expect(legacyStateSchema.safeParse(clamped).success).toBe(true);
  426. // 新界的 schema 当然也过——裁剪只减不增。
  427. expect(workflowRunsStateSchema.safeParse(clamped).success).toBe(true);
  428. });
  429. });
  430. /** 只装 apply 会碰到的两处(与 …WorkflowRunsDelta.test.ts 同一个理由)。 */
  431. function snapshotWith(workflowRuns: WorkflowRunsState | undefined): ConversationSnapshot {
  432. const base = {
  433. protocolVersion: 1,
  434. sessionId: "s-1",
  435. logEpoch: "epoch-1",
  436. seq: 0,
  437. revision: 0,
  438. rows: { window: [], totalCount: 0, firstRowId: null },
  439. };
  440. return (workflowRuns === undefined
  441. ? base
  442. : { ...base, workflowRuns }) as unknown as ConversationSnapshot;
  443. }