zcodeProtocolV4WorkflowRunsDelta.test.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. // workflowRuns 的键级增量(workflow-runs-delta.ts + delta.ts 的两条 op + apply 的两个 twin)。
  2. //
  3. // 本文件钉的是**一条**契约,其余断言都为它服务:对任意一对 reducer 产出的 (prior, next),
  4. // JSON.stringify(apply(带 prior 的快照, diff(prior, next)).workflowRuns) === JSON.stringify(next)
  5. // 逐字节,不是深相等——键序若不一致,桌面与 CLI 的两份状态就会在别处(比如快照哈希、
  6. // 回放比对)悄悄分叉,而这类分叉从现象上看只是"偶尔刷新一下"。
  7. import { describe, expect, it } from "vitest";
  8. import {
  9. WORKFLOW_RUNS_LIMITS,
  10. applyConversationDeltas,
  11. applyConversationDeltasMutable,
  12. canonicalWorkflowRun,
  13. coalesceConversationDeltas,
  14. conversationDeltaSchema,
  15. createMutableConversationSnapshotAccumulator,
  16. diffWorkflowRunsState,
  17. isCompleteWorkflowRunHeader,
  18. reduceWorkflowRunsState,
  19. workflowRunsStateSchema,
  20. type ConversationDelta,
  21. type ConversationSnapshot,
  22. type WorkflowRunProgressEnvelope,
  23. type WorkflowRunState,
  24. type WorkflowRunsState,
  25. } from "../src/zcode-protocol-v4/index.js";
  26. const RUN_ID = "dwfrun-1";
  27. /**
  28. * 只装 apply 会碰到的两处:rows 窗口(mutable accumulator 建索引要读它)与状态键。
  29. * 其余字段与本文件的契约无关,写全一份只会让真正的断言淹没在夹具里。
  30. */
  31. function snapshotWith(workflowRuns: WorkflowRunsState | undefined): ConversationSnapshot {
  32. const base = {
  33. protocolVersion: 1,
  34. sessionId: "s-1",
  35. logEpoch: "epoch-1",
  36. seq: 0,
  37. revision: 0,
  38. rows: { window: [], totalCount: 0, firstRowId: null },
  39. };
  40. return (workflowRuns === undefined
  41. ? base
  42. : { ...base, workflowRuns }) as unknown as ConversationSnapshot;
  43. }
  44. /** 事件信封工厂:sequence 按调用序自增,模拟 journal 的单调分配(与 reducer 测试同一习语)。 */
  45. function progressLog(runId = RUN_ID) {
  46. let sequence = -1;
  47. return function progress(
  48. eventType: string,
  49. payload: Record<string, unknown> = {},
  50. extra: Partial<WorkflowRunProgressEnvelope> = {},
  51. ): WorkflowRunProgressEnvelope {
  52. sequence += 1;
  53. return { runId, toolCallId: "tc-1", sequence, eventType, payload, ...extra };
  54. };
  55. }
  56. const ASK = { siteId: "ask#1", ordinal: 1 };
  57. const ACTOR = { siteId: "actor#1", ordinal: 1 };
  58. /**
  59. * 一条走完全程的 run:出生、阶段、子代理、节点全相位、进度读数、用量、report、产物、
  60. * 升级问答(`cleared` 路径的唯一来源:pendingQuestions 归零后整个键缺席)、缓存命中的结算、
  61. * 第二个子代理、终态。
  62. */
  63. function fullRunEvents(): WorkflowRunProgressEnvelope[] {
  64. const progress = progressLog();
  65. return [
  66. progress("run-started", {
  67. caps: { maxConcurrency: 2 },
  68. concurrencyCeiling: 8,
  69. subagentModel: "glm/glm-5",
  70. resumedFrom: "dwfrun-0",
  71. }),
  72. progress("run-launched", { phaseNames: ["调研", "实现"], phaseAlongside: [[1], [0]] }),
  73. progress("phase-entered", { name: "调研", ordinal: 1 }),
  74. progress(
  75. "actor-created",
  76. { actor: ACTOR, name: "reader", phaseName: "调研" },
  77. { actorSessionId: "sess_dwf-1-actor.1" },
  78. ),
  79. progress("node-queued", {
  80. instance: ASK,
  81. kind: "ask",
  82. actor: ACTOR,
  83. instructionsHead: "读一遍 a.ts",
  84. phaseName: "调研",
  85. }),
  86. progress("node-dispatched", { instance: ASK }),
  87. progress("node-executing", { instance: ASK }),
  88. progress("node-progress", {
  89. instance: ASK,
  90. turn: 2,
  91. toolCalls: 3,
  92. lastTool: { name: "Read", target: "a.ts" },
  93. }),
  94. progress("node-waiting", { instance: ASK }),
  95. progress("usage-updated", { spentTokens: 1_200 }),
  96. progress("report", { instance: { siteId: "report#1", ordinal: 1 }, item: "第一条发现" }),
  97. progress("artifact-published", {
  98. artifact: { id: "art-1", kind: "markdown", version: 1, title: "报告" },
  99. }),
  100. progress("escalation-raised", {
  101. qid: "dwfq-1",
  102. actor: ACTOR,
  103. actorName: "reader",
  104. question: "门是不是坏了?",
  105. askedAt: 1_756_000_000_000,
  106. }),
  107. // 划掉最后一条停驻问题 → 整个键缺席,这是 diff 的 `cleared` 路径。
  108. progress("escalation-resolved", { qid: "dwfq-1", answer: "坏了,跳过。" }),
  109. progress("node-settled", { instance: ASK, outcome: "ok" }),
  110. // resume 的完结命中短路:直接 settled、不经 queued,且它就是这条节点的出生事件。
  111. progress("node-settled", {
  112. instance: { siteId: "world-read#1", ordinal: 1 },
  113. outcome: "ok",
  114. cached: true,
  115. }),
  116. progress("phase-entered", { name: "实现", ordinal: 1 }),
  117. progress(
  118. "actor-created",
  119. { actor: { siteId: "actor#2", ordinal: 1 }, name: "writer", phaseName: "实现" },
  120. { actorSessionId: "sess_dwf-1-actor.2" },
  121. ),
  122. progress("node-queued", {
  123. instance: { siteId: "ask#2", ordinal: 1 },
  124. kind: "ask",
  125. actor: { siteId: "actor#2", ordinal: 1 },
  126. }),
  127. progress("node-dispatched", { instance: { siteId: "ask#2", ordinal: 1 } }),
  128. progress("concurrency-changed", { key: "glm/glm-5", previous: 8, next: 3, reason: "backoff" }),
  129. progress("usage-updated", { spentTokens: 4_800 }),
  130. progress("node-settled", { instance: { siteId: "ask#2", ordinal: 1 }, outcome: "failed" }),
  131. progress("run-settled", { status: "completed" }),
  132. ];
  133. }
  134. /** 第二条 run 的最小生命周期:同一份状态里两条 run 并存,diff 只能动被改的那条。 */
  135. function secondRunEvents(): WorkflowRunProgressEnvelope[] {
  136. const progress = progressLog("dwfrun-2");
  137. return [
  138. progress("run-started", { caps: { maxConcurrency: 1 } }),
  139. progress("actor-created", { actor: ACTOR, name: "planner" }),
  140. progress("node-queued", { instance: ASK, kind: "ask", actor: ACTOR }),
  141. progress("node-dispatched", { instance: ASK }),
  142. progress("run-settled", { status: "stopped", stopReason: "user", resumable: true }),
  143. ];
  144. }
  145. /** 把最旧的 run 挤出去:maxRuns + 2 条新 run,每条一个 run-started。 */
  146. function evictionEvents(): WorkflowRunProgressEnvelope[] {
  147. return Array.from({ length: WORKFLOW_RUNS_LIMITS.maxRuns + 2 }, (_, index) => ({
  148. runId: `dwfrun-evict-${index}`,
  149. sequence: 0,
  150. eventType: "run-started",
  151. payload: { caps: { maxConcurrency: 1 } },
  152. }));
  153. }
  154. /**
  155. * 契约裁判:逐条归约,每一步都用 diff 产出的增量把 prior 推到 next,两个 apply twin 都要
  156. * 得到与 next **逐字节**一致的 workflowRuns。返回走过的全部增量,供调用方再做别的断言。
  157. */
  158. function expectRoundTrip(envelopes: readonly WorkflowRunProgressEnvelope[]): ConversationDelta[] {
  159. let state: WorkflowRunsState | undefined;
  160. const all: ConversationDelta[] = [];
  161. for (const envelope of envelopes) {
  162. const next = reduceWorkflowRunsState(state, envelope);
  163. if (next === null) continue;
  164. const deltas = diffWorkflowRunsState(state, next);
  165. all.push(...deltas);
  166. const prior = snapshotWith(state);
  167. const immutable = applyConversationDeltas(prior, deltas);
  168. expect(JSON.stringify(immutable.workflowRuns)).toBe(JSON.stringify(next));
  169. const accumulator = createMutableConversationSnapshotAccumulator(prior);
  170. applyConversationDeltasMutable(accumulator, deltas);
  171. expect(JSON.stringify(accumulator.snapshot.workflowRuns)).toBe(JSON.stringify(next));
  172. // 增量不该能拼出一个非法状态:客户端侧的产物同样过 strict schema。
  173. expect(workflowRunsStateSchema.safeParse(immutable.workflowRuns).success).toBe(true);
  174. state = next;
  175. }
  176. return all;
  177. }
  178. describe("diffWorkflowRunsState × apply:逐事件往返", () => {
  179. it("一条走完全程的 run:每一步的终态逐字节一致", () => {
  180. const deltas = expectRoundTrip(fullRunEvents());
  181. // 全程没有一条整键重发——有一条就说明 diff 认不出某种结构变化,字节数退回改造前。
  182. expect(deltas.some((delta) => delta.op === "state.updated")).toBe(false);
  183. });
  184. it("两条 run 并存 + 最旧淘汰:淘汰说得出口(workflowRun.removed)", () => {
  185. const deltas = expectRoundTrip([...fullRunEvents(), ...secondRunEvents(), ...evictionEvents()]);
  186. expect(deltas.some((delta) => delta.op === "state.updated")).toBe(false);
  187. const removed = deltas.filter((delta) => delta.op === "workflowRun.removed");
  188. // 两条旧 run + maxRuns + 2 条新 run 进场,最旧的四条按进场序被挤出去。
  189. expect(removed.map((delta) => (delta.op === "workflowRun.removed" ? delta.runId : ""))).toEqual(
  190. [RUN_ID, "dwfrun-2", "dwfrun-evict-0", "dwfrun-evict-1"],
  191. );
  192. });
  193. it("停驻问题清零走 cleared(「零条 ⇒ 键缺席」的键必须说得出它没了)", () => {
  194. const progress = progressLog();
  195. const raised = reduceWorkflowRunsState(
  196. reduceWorkflowRunsState(undefined, progress("run-started", { caps: { maxConcurrency: 1 } })),
  197. progress("escalation-raised", { qid: "dwfq-1", question: "门坏了吗?" }),
  198. )!;
  199. const resolved = reduceWorkflowRunsState(
  200. raised,
  201. progress("escalation-resolved", { qid: "dwfq-1", answer: "坏了" }),
  202. )!;
  203. const deltas = diffWorkflowRunsState(raised, resolved);
  204. expect(deltas).toHaveLength(1);
  205. expect(deltas[0]).toMatchObject({ op: "workflowRun.updated", cleared: ["pendingQuestions"] });
  206. const applied = applyConversationDeltas(snapshotWith(raised), deltas);
  207. expect(applied.workflowRuns?.runs[0]).not.toHaveProperty("pendingQuestions");
  208. expect(JSON.stringify(applied.workflowRuns)).toBe(JSON.stringify(resolved));
  209. });
  210. it("一条节点事件只搬这条节点:增量里不出现没动过的条目", () => {
  211. const progress = progressLog();
  212. let state = reduceWorkflowRunsState(undefined, progress("run-started", {}))!;
  213. for (let ordinal = 1; ordinal <= 20; ordinal += 1) {
  214. state = reduceWorkflowRunsState(
  215. state,
  216. progress("node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" }),
  217. )!;
  218. }
  219. const next = reduceWorkflowRunsState(
  220. state,
  221. progress("node-dispatched", { instance: { siteId: "ask#1", ordinal: 7 } }),
  222. )!;
  223. const deltas = diffWorkflowRunsState(state, next);
  224. expect(deltas).toHaveLength(1);
  225. const op = deltas[0]!;
  226. expect(op.op).toBe("workflowRun.updated");
  227. if (op.op !== "workflowRun.updated") return;
  228. expect(op.nodes).toEqual([{ siteId: "ask#1", ordinal: 7, kind: "ask", phase: "dispatched" }]);
  229. expect(op.actors).toBeUndefined();
  230. // 派发计步改了 usage,header 里因此只有这一个键 + 水位。
  231. expect(Object.keys(op.run ?? {}).sort()).toEqual(["lastEventSequence", "usage"]);
  232. });
  233. // 删除有词汇(removedActors / removedNodes,腾位用),**重排没有**。所以下面第一种输入走键化
  234. // 路径、第二种只能退回整键重发——上面的往返用例断言「全程没有一条 state.updated」,任何一天
  235. // 有人让归约重排了条目,那里会立刻红。
  236. it("条目被删走键化路径,被重排则退回整键重发", () => {
  237. const state = expectRoundTripFinal(fullRunEvents());
  238. const run = state.runs[0]!;
  239. const shortened: WorkflowRunsState = {
  240. revision: state.revision + 1,
  241. runs: [{ ...run, nodes: run.nodes.slice(0, -1) }],
  242. };
  243. expect(diffWorkflowRunsState(state, shortened)).toEqual([
  244. {
  245. op: "workflowRun.updated",
  246. runId: RUN_ID,
  247. revision: shortened.revision,
  248. removedNodes: [{ siteId: run.nodes.at(-1)!.siteId, ordinal: run.nodes.at(-1)!.ordinal }],
  249. },
  250. ]);
  251. expect(
  252. JSON.stringify(
  253. applyConversationDeltas(snapshotWith(state), diffWorkflowRunsState(state, shortened))
  254. .workflowRuns,
  255. ),
  256. ).toBe(JSON.stringify(shortened));
  257. const reordered: WorkflowRunsState = {
  258. revision: state.revision + 1,
  259. runs: [{ ...run, nodes: [...run.nodes].reverse() }],
  260. };
  261. expect(diffWorkflowRunsState(state, reordered)).toEqual([
  262. { op: "state.updated", patch: { workflowRuns: reordered } },
  263. ]);
  264. // 退路本身仍然正确:整键替换后逐字节一致。
  265. const applied = applyConversationDeltas(
  266. snapshotWith(state),
  267. diffWorkflowRunsState(state, reordered),
  268. );
  269. expect(JSON.stringify(applied.workflowRuns)).toBe(JSON.stringify(reordered));
  270. });
  271. it("冷启动(客户端还没有这个键):整条 header + 全部条目的诞生增量", () => {
  272. const state = expectRoundTripFinal(fullRunEvents());
  273. const deltas = diffWorkflowRunsState(undefined, state);
  274. expect(deltas).toHaveLength(1);
  275. const op = deltas[0]!;
  276. if (op.op !== "workflowRun.updated") throw new Error("诞生必须是一条 workflowRun.updated");
  277. expect(isCompleteWorkflowRunHeader(op.run)).toBe(true);
  278. expect(op.nodes).toHaveLength(state.runs[0]!.nodes.length);
  279. const applied = applyConversationDeltas(snapshotWith(undefined), deltas);
  280. expect(JSON.stringify(applied.workflowRuns)).toBe(JSON.stringify(state));
  281. });
  282. });
  283. /** 跑完整串事件,返回终态(上面的往返断言在 expectRoundTrip 里,这里只要状态)。 */
  284. function expectRoundTripFinal(
  285. envelopes: readonly WorkflowRunProgressEnvelope[],
  286. ): WorkflowRunsState {
  287. let state: WorkflowRunsState | undefined;
  288. for (const envelope of envelopes) state = reduceWorkflowRunsState(state, envelope) ?? state;
  289. return state!;
  290. }
  291. describe("coalesce 规则 6 × diff 产出的真实增量", () => {
  292. /** 把两条 run 的事件交错成一个 flush 窗口,收集逐步 diff 出来的全部增量。 */
  293. function windowOf(...streams: readonly WorkflowRunProgressEnvelope[][]): {
  294. deltas: ConversationDelta[];
  295. final: WorkflowRunsState;
  296. } {
  297. const interleaved: WorkflowRunProgressEnvelope[] = [];
  298. const longest = Math.max(...streams.map((stream) => stream.length));
  299. for (let index = 0; index < longest; index += 1) {
  300. for (const stream of streams) {
  301. const envelope = stream[index];
  302. if (envelope !== undefined) interleaved.push(envelope);
  303. }
  304. }
  305. let state: WorkflowRunsState | undefined;
  306. const deltas: ConversationDelta[] = [];
  307. for (const envelope of interleaved) {
  308. const next = reduceWorkflowRunsState(state, envelope);
  309. if (next === null) continue;
  310. deltas.push(...diffWorkflowRunsState(state, next));
  311. state = next;
  312. }
  313. return { deltas, final: state! };
  314. }
  315. it("合并前后终态逐字节一致,且每条 run 在窗口里塌成一条增量", () => {
  316. const { deltas, final } = windowOf(fullRunEvents(), secondRunEvents());
  317. const base = snapshotWith(undefined);
  318. const direct = applyConversationDeltas(base, deltas);
  319. const coalesced = coalesceConversationDeltas(deltas);
  320. expect(JSON.stringify(applyConversationDeltas(base, coalesced).workflowRuns)).toBe(
  321. JSON.stringify(direct.workflowRuns),
  322. );
  323. // 逐条投递本来就该收敛到 reducer 的终态;合并只是不许改变它。
  324. expect(JSON.stringify(direct.workflowRuns)).toBe(JSON.stringify(final));
  325. // 塌缩:几十条引擎事件 → 每条 run 一条增量,与 fan-out 宽度无关(500 条帧界的由来)。
  326. expect(deltas.length).toBeGreaterThan(20);
  327. expect(coalesced).toHaveLength(2);
  328. });
  329. it("窗口里夹着整键重发的屏障时,屏障两侧各自塌缩且终态不变", () => {
  330. const { deltas, final } = windowOf(fullRunEvents(), secondRunEvents());
  331. const half = Math.floor(deltas.length / 2);
  332. const midpoint = applyConversationDeltas(
  333. snapshotWith(undefined),
  334. deltas.slice(0, half),
  335. ).workflowRuns!;
  336. const withBarrier: ConversationDelta[] = [
  337. ...deltas.slice(0, half),
  338. { op: "state.updated", patch: { workflowRuns: midpoint } },
  339. ...deltas.slice(half),
  340. ];
  341. const base = snapshotWith(undefined);
  342. const direct = applyConversationDeltas(base, withBarrier);
  343. const coalesced = coalesceConversationDeltas(withBarrier);
  344. expect(JSON.stringify(applyConversationDeltas(base, coalesced).workflowRuns)).toBe(
  345. JSON.stringify(direct.workflowRuns),
  346. );
  347. expect(JSON.stringify(direct.workflowRuns)).toBe(JSON.stringify(final));
  348. expect(coalesced.filter((delta) => delta.op === "state.updated")).toHaveLength(1);
  349. });
  350. it("淘汰吞掉同 run 此前的增量,终态仍与逐条投递一致", () => {
  351. const { deltas, final } = windowOf(fullRunEvents(), secondRunEvents(), evictionEvents());
  352. const base = snapshotWith(undefined);
  353. const direct = applyConversationDeltas(base, deltas);
  354. const coalesced = coalesceConversationDeltas(deltas);
  355. expect(JSON.stringify(applyConversationDeltas(base, coalesced).workflowRuns)).toBe(
  356. JSON.stringify(direct.workflowRuns),
  357. );
  358. expect(JSON.stringify(direct.workflowRuns)).toBe(JSON.stringify(final));
  359. // 被淘汰的 run:屏障之前的增量被吞干净(出生+淘汰同窗口 = 客户端没见过它)。屏障之后还可能
  360. // 再出现一条——迟到的事件让这条 runId 作为**新条目**回到队尾,那是另一件事,不该被吞。
  361. const removedAt = coalesced.findIndex(
  362. (delta) => delta.op === "workflowRun.removed" && delta.runId === RUN_ID,
  363. );
  364. expect(removedAt).toBeGreaterThanOrEqual(0);
  365. const firstUpdate = coalesced.findIndex(
  366. (delta) => delta.op === "workflowRun.updated" && delta.runId === RUN_ID,
  367. );
  368. expect(firstUpdate === -1 || firstUpdate > removedAt).toBe(true);
  369. });
  370. });
  371. describe("apply:workflowRun.* 的边界语义", () => {
  372. const born: ConversationDelta = {
  373. op: "workflowRun.updated",
  374. runId: RUN_ID,
  375. revision: 3,
  376. run: {
  377. runId: RUN_ID,
  378. status: "running",
  379. usage: { spentTokens: 0, nodesUsed: 0 },
  380. lastEventSequence: 0,
  381. },
  382. };
  383. it("未知 run + 完整 header = 诞生;条目缺席按空表建", () => {
  384. const applied = applyConversationDeltas(snapshotWith(undefined), [born]);
  385. expect(applied.workflowRuns).toEqual({
  386. revision: 3,
  387. runs: [
  388. {
  389. runId: RUN_ID,
  390. status: "running",
  391. usage: { spentTokens: 0, nodesUsed: 0 },
  392. actors: [],
  393. nodes: [],
  394. lastEventSequence: 0,
  395. },
  396. ],
  397. });
  398. expect(workflowRunsStateSchema.safeParse(applied.workflowRuns).success).toBe(true);
  399. });
  400. it("未知 run + 残缺 header = 不建条目(与 row.upserted 命中未加载行同一条裁决)", () => {
  401. const applied = applyConversationDeltas(snapshotWith(undefined), [
  402. { op: "workflowRun.updated", runId: "dwfrun-ghost", revision: 5, run: { status: "running" } },
  403. { op: "workflowRun.updated", runId: "dwfrun-ghost", revision: 6, nodes: [ASK_NODE] },
  404. ]);
  405. expect(applied.workflowRuns?.runs).toEqual([]);
  406. // 容器 revision 仍然跟上:生产者对版本的断言与它能不能安放这条 run 是两回事。
  407. expect(applied.workflowRuns?.revision).toBe(6);
  408. });
  409. it("removed 命中未知 runId 只让 revision 跟上,不抛", () => {
  410. const seeded = applyConversationDeltas(snapshotWith(undefined), [born]);
  411. const applied = applyConversationDeltas(seeded, [
  412. { op: "workflowRun.removed", runId: "dwfrun-别的", revision: 9 },
  413. ]);
  414. expect(applied.workflowRuns?.runs.map((run) => run.runId)).toEqual([RUN_ID]);
  415. expect(applied.workflowRuns?.revision).toBe(9);
  416. });
  417. it("revision 取 max:合并后靠前的 op 携带靠后的 revision 也不会把容器版本拉回去", () => {
  418. const seeded = applyConversationDeltas(snapshotWith(undefined), [born]);
  419. const applied = applyConversationDeltas(seeded, [
  420. { op: "workflowRun.updated", runId: RUN_ID, revision: 12, run: { status: "completed" } },
  421. { op: "workflowRun.updated", runId: RUN_ID, revision: 7, run: { lastEventSequence: 4 } },
  422. ]);
  423. expect(applied.workflowRuns?.revision).toBe(12);
  424. });
  425. it("身份:没动过的 run 与条目保持引用,动过的那条 run 与容器是新对象", () => {
  426. const twoRuns = applyConversationDeltas(snapshotWith(undefined), [
  427. born,
  428. { ...born, runId: "dwfrun-2", run: { ...born.run, runId: "dwfrun-2" } } as ConversationDelta,
  429. {
  430. op: "workflowRun.updated",
  431. runId: RUN_ID,
  432. revision: 4,
  433. nodes: [ASK_NODE, { siteId: "ask#2", ordinal: 1, phase: "queued" }],
  434. },
  435. ]);
  436. const before = twoRuns.workflowRuns!;
  437. const after = applyConversationDeltas(twoRuns, [
  438. {
  439. op: "workflowRun.updated",
  440. runId: RUN_ID,
  441. revision: 5,
  442. nodes: [{ siteId: "ask#2", ordinal: 1, phase: "dispatched" }],
  443. },
  444. ]).workflowRuns!;
  445. expect(after).not.toBe(before);
  446. expect(after.runs[0]).not.toBe(before.runs[0]);
  447. // 另一条 run 与被改 run 里没动过的那个节点都保持引用——GUI 的两级 memo 靠的就是这个。
  448. expect(after.runs[1]).toBe(before.runs[1]);
  449. expect(after.runs[0]!.nodes[0]).toBe(before.runs[0]!.nodes[0]);
  450. expect(after.runs[0]!.nodes[1]).not.toBe(before.runs[0]!.nodes[1]);
  451. // actors 没被这条 op 提到:整张表保持引用。
  452. expect(after.runs[0]!.actors).toBe(before.runs[0]!.actors);
  453. });
  454. it("客户端从不自行施加上界:maxRuns 之外的诞生照样落表(只有生产者淘汰,且必须说出来)", () => {
  455. const births = Array.from({ length: WORKFLOW_RUNS_LIMITS.maxRuns + 3 }, (_, index) => ({
  456. ...born,
  457. runId: `dwfrun-${index}`,
  458. revision: index + 1,
  459. run: { ...born.run, runId: `dwfrun-${index}` },
  460. })) as ConversationDelta[];
  461. const applied = applyConversationDeltas(snapshotWith(undefined), births);
  462. // 客户端自行裁剪只会让两侧悄悄分叉:生产者以为发过的 run 在这边根本不存在。
  463. expect(applied.workflowRuns?.runs).toHaveLength(WORKFLOW_RUNS_LIMITS.maxRuns + 3);
  464. });
  465. it("两个 apply twin 在 workflowRun.* 上逐字节等价", () => {
  466. const deltas: ConversationDelta[] = [
  467. born,
  468. { op: "workflowRun.updated", runId: RUN_ID, revision: 4, nodes: [ASK_NODE] },
  469. {
  470. op: "workflowRun.updated",
  471. runId: "dwfrun-2",
  472. revision: 5,
  473. run: { ...born.run, runId: "dwfrun-2" },
  474. },
  475. { op: "workflowRun.removed", runId: RUN_ID, revision: 6 },
  476. ];
  477. const base = snapshotWith(undefined);
  478. const immutable = applyConversationDeltas(base, deltas);
  479. const accumulator = createMutableConversationSnapshotAccumulator(base);
  480. applyConversationDeltasMutable(accumulator, deltas);
  481. expect(JSON.stringify(accumulator.snapshot.workflowRuns)).toBe(
  482. JSON.stringify(immutable.workflowRuns),
  483. );
  484. expect(immutable.workflowRuns?.runs.map((run) => run.runId)).toEqual(["dwfrun-2"]);
  485. // 入参不被修改。
  486. expect(base.workflowRuns).toBeUndefined();
  487. });
  488. });
  489. const ASK_NODE = { siteId: "ask#1", ordinal: 1, phase: "queued" } as const;
  490. // ── 条目淘汰的线上表达:removedActors / removedNodes ────────────────────────
  491. //
  492. // 归约到界之后会淘汰终态条目给活的新人腾位(workflow-runs-eviction.ts),于是这个模型第一次
  493. // 需要说出「这条走了」。下面钉的仍是文件头那条契约(diff 施加到 prior 与 next 逐字节一致),
  494. // 只是输入里多了删除;外加一条:合并两条增量必须等于顺序施加它们。
  495. /** 手搓一条 run:本节测的是 diff/apply/merge 的代数,走一遍归约反而看不清输入。 */
  496. function runWithNodes(
  497. nodes: readonly { siteId: string; ordinal: number; phase: string }[],
  498. actors: readonly { siteId: string; ordinal: number; status: string }[] = [],
  499. ): WorkflowRunState {
  500. return canonicalWorkflowRun({
  501. runId: RUN_ID,
  502. status: "running",
  503. usage: { spentTokens: 0, nodesUsed: 0 },
  504. actors: actors as WorkflowRunState["actors"],
  505. nodes: nodes as WorkflowRunState["nodes"],
  506. lastEventSequence: 1,
  507. } as WorkflowRunState);
  508. }
  509. const queued = (siteId: string) => ({ siteId, ordinal: 1, phase: "queued" as const });
  510. const settled = (siteId: string) => ({ siteId, ordinal: 1, phase: "settled" as const });
  511. const waiting = (siteId: string) => ({ siteId, ordinal: 1, status: "waiting" as const });
  512. /** 单条 run 的 diff,取出那条 updated(本节的输入都不触发整键重发)。 */
  513. function updateBetween(before: WorkflowRunState, after: WorkflowRunState) {
  514. const deltas = diffWorkflowRunsState(
  515. { revision: 1, runs: [before] },
  516. { revision: 2, runs: [after] },
  517. );
  518. expect(deltas).toHaveLength(1);
  519. const op = deltas[0]!;
  520. if (op.op !== "workflowRun.updated") throw new Error("应当是一条 workflowRun.updated");
  521. // 契约:施加到 prior 之后与 next 逐字节一致。
  522. const applied = applyConversationDeltas(snapshotWith({ revision: 1, runs: [before] }), deltas);
  523. expect(JSON.stringify(applied.workflowRuns)).toBe(JSON.stringify({ revision: 2, runs: [after] }));
  524. return op;
  525. }
  526. describe("diff:条目被删时走键化路径", () => {
  527. it("中间少了一条:removedNodes 说出来,其余条目一个字节都不重发", () => {
  528. const op = updateBetween(
  529. runWithNodes([queued("a"), queued("b"), queued("c")]),
  530. runWithNodes([queued("a"), queued("c")]),
  531. );
  532. expect(op.removedNodes).toEqual([{ siteId: "b", ordinal: 1 }]);
  533. expect(op.nodes).toBeUndefined();
  534. });
  535. it("删除 + 追加 + 幸存者变化同时发生", () => {
  536. const op = updateBetween(
  537. runWithNodes([queued("a"), queued("b"), queued("c")]),
  538. runWithNodes([settled("a"), queued("c"), queued("d")]),
  539. );
  540. expect(op.removedNodes).toEqual([{ siteId: "b", ordinal: 1 }]);
  541. expect(op.nodes).toEqual([settled("a"), queued("d")]);
  542. });
  543. it("两张表各自走各自的路径:actors 删、nodes 只追加", () => {
  544. const op = updateBetween(
  545. runWithNodes([queued("a")], [waiting("x"), waiting("y")]),
  546. runWithNodes([queued("a"), queued("b")], [waiting("y")]),
  547. );
  548. expect(op.removedActors).toEqual([{ siteId: "x", ordinal: 1 }]);
  549. expect(op.removedNodes).toBeUndefined();
  550. expect(op.nodes).toEqual([queued("b")]);
  551. });
  552. it("整张表被清空(溢出过的 run 在 resume 时重开)", () => {
  553. const op = updateBetween(
  554. runWithNodes([queued("a"), queued("b")], [waiting("x")]),
  555. runWithNodes([], []),
  556. );
  557. expect(op.removedNodes).toEqual([
  558. { siteId: "a", ordinal: 1 },
  559. { siteId: "b", ordinal: 1 },
  560. ]);
  561. expect(op.removedActors).toEqual([{ siteId: "x", ordinal: 1 }]);
  562. });
  563. });
  564. describe("apply:一条 op 内先删后加", () => {
  565. it("同一个键在一条 op 里被删又被加 → 落在表尾", () => {
  566. const seeded = applyConversationDeltas(snapshotWith(undefined), [
  567. {
  568. op: "workflowRun.updated",
  569. runId: RUN_ID,
  570. revision: 1,
  571. run: {
  572. runId: RUN_ID,
  573. status: "running",
  574. usage: { spentTokens: 0, nodesUsed: 0 },
  575. lastEventSequence: 0,
  576. },
  577. nodes: [queued("a"), queued("b")],
  578. },
  579. ]);
  580. const applied = applyConversationDeltas(seeded, [
  581. {
  582. op: "workflowRun.updated",
  583. runId: RUN_ID,
  584. revision: 2,
  585. removedNodes: [{ siteId: "a", ordinal: 1 }],
  586. nodes: [settled("a")],
  587. },
  588. ]);
  589. expect(applied.workflowRuns?.runs[0]?.nodes).toEqual([queued("b"), settled("a")]);
  590. });
  591. it("删到一条不剩 + 未命中的键是 no-op;没被提到的表保持引用", () => {
  592. const seeded = applyConversationDeltas(snapshotWith(undefined), [
  593. {
  594. op: "workflowRun.updated",
  595. runId: RUN_ID,
  596. revision: 1,
  597. run: {
  598. runId: RUN_ID,
  599. status: "running",
  600. usage: { spentTokens: 0, nodesUsed: 0 },
  601. lastEventSequence: 0,
  602. },
  603. actors: [waiting("x")],
  604. nodes: [queued("a")],
  605. },
  606. ]);
  607. const applied = applyConversationDeltas(seeded, [
  608. {
  609. op: "workflowRun.updated",
  610. runId: RUN_ID,
  611. revision: 2,
  612. removedNodes: [
  613. { siteId: "a", ordinal: 1 },
  614. { siteId: "从来没有过", ordinal: 7 },
  615. ],
  616. },
  617. ]);
  618. expect(applied.workflowRuns?.runs[0]?.nodes).toEqual([]);
  619. expect(applied.workflowRuns?.runs[0]?.actors).toBe(seeded.workflowRuns?.runs[0]?.actors);
  620. });
  621. });
  622. describe("merge(coalesce 规则 6 的载荷):合并必须等于顺序施加", () => {
  623. const birth: ConversationDelta = {
  624. op: "workflowRun.updated",
  625. runId: RUN_ID,
  626. revision: 1,
  627. run: {
  628. runId: RUN_ID,
  629. status: "running",
  630. usage: { spentTokens: 0, nodesUsed: 0 },
  631. lastEventSequence: 0,
  632. },
  633. nodes: [queued("a"), queued("b"), queued("c")],
  634. };
  635. /** 裁判:合并后施加 与 顺序施加 逐字节一致(两条 op 都以 birth 建好的表为底)。 */
  636. function expectMergeEqualsSequential(
  637. earlier: ConversationDelta,
  638. later: ConversationDelta,
  639. ): ConversationDelta {
  640. const base = applyConversationDeltas(snapshotWith(undefined), [birth]);
  641. const sequential = applyConversationDeltas(base, [earlier, later]);
  642. const merged = coalesceConversationDeltas([earlier, later]);
  643. expect(merged).toHaveLength(1);
  644. expect(JSON.stringify(applyConversationDeltas(base, merged).workflowRuns)).toBe(
  645. JSON.stringify(sequential.workflowRuns),
  646. );
  647. expect(conversationDeltaSchema.safeParse(merged[0]).success).toBe(true);
  648. return merged[0]!;
  649. }
  650. it("先删后加同一个键:合并后它仍然落在表尾", () => {
  651. const merged = expectMergeEqualsSequential(
  652. {
  653. op: "workflowRun.updated",
  654. runId: RUN_ID,
  655. revision: 2,
  656. removedNodes: [{ siteId: "a", ordinal: 1 }],
  657. },
  658. { op: "workflowRun.updated", runId: RUN_ID, revision: 3, nodes: [settled("a")] },
  659. );
  660. if (merged.op !== "workflowRun.updated") throw new Error("应合并成一条 updated");
  661. expect(merged.removedNodes).toEqual([{ siteId: "a", ordinal: 1 }]);
  662. expect(merged.nodes).toEqual([settled("a")]);
  663. });
  664. it("先者 upsert 的键被后者删掉:合并后它从 upsert 里消失", () => {
  665. const merged = expectMergeEqualsSequential(
  666. { op: "workflowRun.updated", runId: RUN_ID, revision: 2, nodes: [settled("b"), queued("d")] },
  667. {
  668. op: "workflowRun.updated",
  669. runId: RUN_ID,
  670. revision: 3,
  671. removedNodes: [{ siteId: "d", ordinal: 1 }],
  672. },
  673. );
  674. if (merged.op !== "workflowRun.updated") throw new Error("应合并成一条 updated");
  675. expect(merged.nodes).toEqual([settled("b")]);
  676. expect(merged.removedNodes).toEqual([{ siteId: "d", ordinal: 1 }]);
  677. });
  678. it("两侧的删除取并集、按首次出现去重", () => {
  679. const merged = expectMergeEqualsSequential(
  680. {
  681. op: "workflowRun.updated",
  682. runId: RUN_ID,
  683. revision: 2,
  684. removedNodes: [
  685. { siteId: "a", ordinal: 1 },
  686. { siteId: "b", ordinal: 1 },
  687. ],
  688. },
  689. {
  690. op: "workflowRun.updated",
  691. runId: RUN_ID,
  692. revision: 3,
  693. removedNodes: [
  694. { siteId: "b", ordinal: 1 },
  695. { siteId: "c", ordinal: 1 },
  696. ],
  697. },
  698. );
  699. if (merged.op !== "workflowRun.updated") throw new Error("应合并成一条 updated");
  700. expect(merged.removedNodes).toEqual([
  701. { siteId: "a", ordinal: 1 },
  702. { siteId: "b", ordinal: 1 },
  703. { siteId: "c", ordinal: 1 },
  704. ]);
  705. });
  706. it("先加新键、后删另一个旧键:新键仍追在幸存者后面", () => {
  707. expectMergeEqualsSequential(
  708. { op: "workflowRun.updated", runId: RUN_ID, revision: 2, nodes: [queued("d")] },
  709. {
  710. op: "workflowRun.updated",
  711. runId: RUN_ID,
  712. revision: 3,
  713. removedNodes: [{ siteId: "a", ordinal: 1 }],
  714. },
  715. );
  716. });
  717. it("合并出来会超界时**不合并**:超界的帧会被整帧丢掉,订阅从此静默", () => {
  718. // 腾位之前,「一个窗口里被碰过的不同键 ≤ 表界」是结构性的(表只增不减);腾位之后不是了。
  719. const ref = (ordinal: number) => ({ siteId: "ask#1", ordinal });
  720. const wide = (revision: number, from: number, count: number): ConversationDelta => ({
  721. op: "workflowRun.updated",
  722. runId: RUN_ID,
  723. revision,
  724. removedNodes: Array.from({ length: count }, (_, index) => ref(from + index)),
  725. });
  726. const deltas = [wide(2, 0, WORKFLOW_RUNS_LIMITS.maxNodes), wide(3, 100_000, 100)];
  727. const coalesced = coalesceConversationDeltas(deltas);
  728. expect(coalesced).toHaveLength(2);
  729. for (const delta of coalesced) {
  730. expect(conversationDeltaSchema.safeParse(delta).success).toBe(true);
  731. }
  732. // 不合并不改变终态:逐条投递与"合并"后的序列施加出来的是同一份状态。
  733. const base = applyConversationDeltas(snapshotWith(undefined), [
  734. {
  735. op: "workflowRun.updated",
  736. runId: RUN_ID,
  737. revision: 1,
  738. run: {
  739. runId: RUN_ID,
  740. status: "running",
  741. usage: { spentTokens: 0, nodesUsed: 0 },
  742. lastEventSequence: 0,
  743. },
  744. nodes: [queued("a"), { siteId: "ask#1", ordinal: 3, phase: "settled" }],
  745. },
  746. ]);
  747. expect(JSON.stringify(applyConversationDeltas(base, coalesced).workflowRuns)).toBe(
  748. JSON.stringify(applyConversationDeltas(base, deltas).workflowRuns),
  749. );
  750. // 界内的两条仍然照常合并(这道闸只在真的装不下时才拦)。
  751. expect(coalesceConversationDeltas([wide(2, 0, 10), wide(3, 100, 10)])).toHaveLength(1);
  752. });
  753. it("合并被拒之后,后来的 op 只能并进**最后**那条——并回更早那条会吃掉一个先删后加的键", () => {
  754. const ref = (ordinal: number) => ({ siteId: "ask#9", ordinal });
  755. const key = { siteId: "ask#1", ordinal: 1 };
  756. const base = applyConversationDeltas(snapshotWith(undefined), [
  757. {
  758. op: "workflowRun.updated",
  759. runId: RUN_ID,
  760. revision: 1,
  761. run: {
  762. runId: RUN_ID,
  763. status: "running",
  764. usage: { spentTokens: 0, nodesUsed: 0 },
  765. lastEventSequence: 0,
  766. },
  767. nodes: [queued("ask#1"), queued("x")],
  768. },
  769. ]);
  770. // A 把删除表塞到界上 → B 并不进去,只能另立一条;C 若越过 B 并回 A,
  771. // 它的 upsert 就跑到了 B 的删除**之前**,ask#1 会凭空消失。
  772. const deltas: ConversationDelta[] = [
  773. {
  774. op: "workflowRun.updated",
  775. runId: RUN_ID,
  776. revision: 2,
  777. removedNodes: Array.from({ length: WORKFLOW_RUNS_LIMITS.maxNodes }, (_, i) => ref(i)),
  778. },
  779. { op: "workflowRun.updated", runId: RUN_ID, revision: 3, removedNodes: [key] },
  780. { op: "workflowRun.updated", runId: RUN_ID, revision: 4, nodes: [settled("ask#1")] },
  781. ];
  782. const coalesced = coalesceConversationDeltas(deltas);
  783. expect(coalesced).toHaveLength(2);
  784. const direct = applyConversationDeltas(base, deltas);
  785. expect(JSON.stringify(applyConversationDeltas(base, coalesced).workflowRuns)).toBe(
  786. JSON.stringify(direct.workflowRuns),
  787. );
  788. // 先删后加的键落在表尾,而不是被吃掉。
  789. expect(direct.workflowRuns?.runs[0]?.nodes).toEqual([queued("x"), settled("ask#1")]);
  790. });
  791. it("actors 与 nodes 各删各的,互不相干", () => {
  792. expectMergeEqualsSequential(
  793. {
  794. op: "workflowRun.updated",
  795. runId: RUN_ID,
  796. revision: 2,
  797. removedNodes: [{ siteId: "a", ordinal: 1 }],
  798. actors: [waiting("x")],
  799. },
  800. {
  801. op: "workflowRun.updated",
  802. runId: RUN_ID,
  803. revision: 3,
  804. removedActors: [{ siteId: "x", ordinal: 1 }],
  805. nodes: [settled("c")],
  806. },
  807. );
  808. });
  809. });
  810. describe("canonicalWorkflowRun:规范键序", () => {
  811. it("按 schema 声明序重建,undefined 值的键按缺席处理", () => {
  812. const scrambled = {
  813. lastEventSequence: 3,
  814. nodes: [],
  815. status: "running",
  816. actors: [],
  817. usage: { spentTokens: 0, nodesUsed: 0 },
  818. runId: RUN_ID,
  819. error: undefined,
  820. } as unknown as WorkflowRunState;
  821. expect(Object.keys(canonicalWorkflowRun(scrambled))).toEqual([
  822. "runId",
  823. "status",
  824. "usage",
  825. "actors",
  826. "nodes",
  827. "lastEventSequence",
  828. ]);
  829. });
  830. it("归约产出的 run 已经是规范序(diff 的字节等价不靠调用方再排一次)", () => {
  831. const state = expectRoundTripFinal(fullRunEvents());
  832. const run = state.runs[0]!;
  833. expect(Object.keys(run)).toEqual(Object.keys(canonicalWorkflowRun(run)));
  834. });
  835. });
  836. describe("conversationDeltaSchema:两条新 op", () => {
  837. it("增量 op 解析通过,并保住 cleared / 条目载荷", () => {
  838. const parsed = conversationDeltaSchema.parse({
  839. op: "workflowRun.updated",
  840. runId: RUN_ID,
  841. revision: 7,
  842. run: { status: "completed", lastEventSequence: 9 },
  843. cleared: ["pendingQuestions"],
  844. actors: [{ siteId: "actor#1", ordinal: 1, status: "completed" }],
  845. nodes: [ASK_NODE],
  846. });
  847. expect(parsed).toMatchObject({ op: "workflowRun.updated", cleared: ["pendingQuestions"] });
  848. expect(
  849. conversationDeltaSchema.parse({ op: "workflowRun.removed", runId: RUN_ID, revision: 1 }),
  850. ).toMatchObject({ op: "workflowRun.removed" });
  851. });
  852. it("条目淘汰的两个载荷:只带身份,界与两张表同值", () => {
  853. const parsed = conversationDeltaSchema.parse({
  854. op: "workflowRun.updated",
  855. runId: RUN_ID,
  856. revision: 8,
  857. removedActors: [{ siteId: "actor#1", ordinal: 1 }],
  858. removedNodes: [{ siteId: "ask#1", ordinal: 1 }],
  859. });
  860. expect(parsed).toMatchObject({ removedNodes: [{ siteId: "ask#1", ordinal: 1 }] });
  861. // 淘汰载荷说的是**身份**,不是条目:多带的键被剥掉,不会让整条 op 变成一次 upsert。
  862. expect(
  863. conversationDeltaSchema.safeParse({
  864. op: "workflowRun.updated",
  865. runId: RUN_ID,
  866. revision: 1,
  867. removedNodes: [{ siteId: "ask#1" }],
  868. }).success,
  869. ).toBe(false);
  870. const ref = (ordinal: number) => ({ siteId: "ask#1", ordinal });
  871. expect(
  872. conversationDeltaSchema.safeParse({
  873. op: "workflowRun.updated",
  874. runId: RUN_ID,
  875. revision: 1,
  876. removedNodes: Array.from({ length: WORKFLOW_RUNS_LIMITS.maxNodes }, (_, i) => ref(i)),
  877. }).success,
  878. ).toBe(true);
  879. expect(
  880. conversationDeltaSchema.safeParse({
  881. op: "workflowRun.updated",
  882. runId: RUN_ID,
  883. revision: 1,
  884. removedNodes: Array.from({ length: WORKFLOW_RUNS_LIMITS.maxNodes + 1 }, (_, i) => ref(i)),
  885. }).success,
  886. ).toBe(false);
  887. });
  888. it("坏载荷一律拒收:负 revision、空 runId、非 header 键的 cleared", () => {
  889. expect(
  890. conversationDeltaSchema.safeParse({ op: "workflowRun.updated", runId: RUN_ID, revision: -1 })
  891. .success,
  892. ).toBe(false);
  893. expect(
  894. conversationDeltaSchema.safeParse({ op: "workflowRun.updated", runId: "", revision: 1 })
  895. .success,
  896. ).toBe(false);
  897. // nodes / actors 不是 header 键:它们有自己的增量载荷,清不掉。
  898. expect(
  899. conversationDeltaSchema.safeParse({
  900. op: "workflowRun.updated",
  901. runId: RUN_ID,
  902. revision: 1,
  903. cleared: ["nodes"],
  904. }).success,
  905. ).toBe(false);
  906. // 状态键上的坏值同样进不来(run 是 header 的 partial,不是任意对象)。
  907. expect(
  908. conversationDeltaSchema.safeParse({
  909. op: "workflowRun.updated",
  910. runId: RUN_ID,
  911. revision: 1,
  912. run: { status: "exploded" },
  913. }).success,
  914. ).toBe(false);
  915. });
  916. it("条目表的界与状态键同值:增量拼不出一个非法状态", () => {
  917. const node = (ordinal: number) => ({ siteId: "ask#1", ordinal, phase: "queued" });
  918. const withinBound = Array.from({ length: WORKFLOW_RUNS_LIMITS.maxNodes }, (_, i) => node(i));
  919. expect(
  920. conversationDeltaSchema.safeParse({
  921. op: "workflowRun.updated",
  922. runId: RUN_ID,
  923. revision: 1,
  924. nodes: withinBound,
  925. }).success,
  926. ).toBe(true);
  927. expect(
  928. conversationDeltaSchema.safeParse({
  929. op: "workflowRun.updated",
  930. runId: RUN_ID,
  931. revision: 1,
  932. nodes: [...withinBound, node(9_999)],
  933. }).success,
  934. ).toBe(false);
  935. const actor = (ordinal: number) => ({ siteId: "actor#1", ordinal, status: "waiting" });
  936. expect(
  937. conversationDeltaSchema.safeParse({
  938. op: "workflowRun.updated",
  939. runId: RUN_ID,
  940. revision: 1,
  941. actors: Array.from({ length: WORKFLOW_RUNS_LIMITS.maxActors + 1 }, (_, i) => actor(i)),
  942. }).success,
  943. ).toBe(false);
  944. });
  945. });