zcodeProtocolV4WorkflowRunsDelta.test.ts 41 KB

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