conversation-workflow-run-deltas.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // publisher 对 workflowRun 键级增量的两条纯规则(src/zcode-protocol-v4/conversation-workflow-run-deltas.ts)。
  2. // 一条决定旧消费者还能不能看见 run,一条决定 16MiB 闸门算得松不松——两条都不能靠"看起来对"。
  3. import { describe, expect, it } from "vitest";
  4. import type {
  5. ConversationDelta,
  6. WorkflowRunEntryLimits,
  7. WorkflowRunsState,
  8. } from "@zcode/shared/zcode-protocol-v4";
  9. import {
  10. WORKFLOW_RUNS_LEGACY_LIMITS,
  11. diffWorkflowRunsState,
  12. reduceWorkflowRunsState,
  13. utf8JsonByteLength,
  14. } from "@zcode/shared/zcode-protocol-v4";
  15. import {
  16. encodeConversationDeltasForLegacy,
  17. workflowRunDeltaGrowthUpperBound,
  18. } from "../src/zcode-protocol-v4/index.js";
  19. function runState(nodeCount: number, actorCount = 0): WorkflowRunsState {
  20. return {
  21. revision: 7,
  22. runs: [
  23. {
  24. runId: "dwfrun-1",
  25. status: "running",
  26. usage: { spentTokens: 0, nodesUsed: nodeCount },
  27. actors: Array.from({ length: actorCount }, (_unused, index) => ({
  28. siteId: "actor#1",
  29. ordinal: index + 1,
  30. status: "idle" as const,
  31. })),
  32. nodes: Array.from({ length: nodeCount }, (_unused, index) => ({
  33. siteId: "ask#1",
  34. ordinal: index + 1,
  35. phase: "dispatched" as const,
  36. })),
  37. lastEventSequence: nodeCount,
  38. },
  39. ],
  40. };
  41. }
  42. function updated(runId: string, revision: number): ConversationDelta {
  43. return { op: "workflowRun.updated", runId, revision, run: { lastEventSequence: revision } };
  44. }
  45. const ROW: ConversationDelta = {
  46. op: "row.appended",
  47. row: {
  48. rowId: 1,
  49. kind: "assistantText",
  50. turnId: "turn-1",
  51. text: "hi",
  52. streaming: false,
  53. createdAt: 0,
  54. },
  55. };
  56. describe("旧消费者编码", () => {
  57. it("没有键级增量的批次原样返回**同一个数组**", () => {
  58. const deltas = [
  59. ROW,
  60. { op: "state.updated", patch: { revision: 3 } } satisfies ConversationDelta,
  61. ];
  62. expect(encodeConversationDeltasForLegacy(deltas, runState(2))).toBe(deltas);
  63. });
  64. it("整批的键级增量折成一条整键 patch,落在**最后一条**被丢掉的位置上", () => {
  65. const tail: ConversationDelta = { op: "state.updated", patch: { revision: 9 } };
  66. const deltas: ConversationDelta[] = [
  67. updated("dwfrun-1", 5),
  68. ROW,
  69. updated("dwfrun-1", 6),
  70. { op: "workflowRun.removed", runId: "dwfrun-2", revision: 7 },
  71. tail,
  72. ];
  73. const encoded = encodeConversationDeltasForLegacy(deltas, runState(2));
  74. expect(encoded.map((delta) => delta.op)).toEqual([
  75. "row.appended",
  76. "state.updated",
  77. "state.updated",
  78. ]);
  79. // 位置在最后一条被丢掉的 op 上:整键替换蕴含这批增量的全部效果,与其余 op 的相对顺序
  80. // 因此与逐条投递一致(行 op 与状态键互不相干)。
  81. expect(encoded[0]).toBe(ROW);
  82. expect(encoded[2]).toBe(tail);
  83. const patch = (encoded[1] as { patch: { workflowRuns?: WorkflowRunsState } }).patch;
  84. expect(patch.workflowRuns?.revision).toBe(7);
  85. expect(patch.workflowRuns?.runs[0]?.nodes).toHaveLength(2);
  86. });
  87. it("超过旧界的表裁到 256 并置 truncated(旧二进制的 .max(256) 会让整帧解析失败)", () => {
  88. const state = runState(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes + 40, 300);
  89. const encoded = encodeConversationDeltasForLegacy([updated("dwfrun-1", 8)], state);
  90. const run = (encoded[0] as { patch: { workflowRuns: WorkflowRunsState } }).patch.workflowRuns
  91. .runs[0]!;
  92. expect(run.nodes).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes);
  93. expect(run.actors).toHaveLength(WORKFLOW_RUNS_LEGACY_LIMITS.maxActors);
  94. expect(run.truncated).toBe(true);
  95. // 「前 256 条」不是随手取的:旧归约触界时是拒新,它产出的恰好就是最早那 256 条。
  96. expect(run.nodes[0]?.ordinal).toBe(1);
  97. expect(run.nodes.at(-1)?.ordinal).toBe(WORKFLOW_RUNS_LEGACY_LIMITS.maxNodes);
  98. });
  99. it("投影里还没有 workflowRuns 键时只丢不补(没有能整键替换成的东西)", () => {
  100. expect(encodeConversationDeltasForLegacy([ROW, updated("dwfrun-1", 1)], undefined)).toEqual([
  101. ROW,
  102. ]);
  103. });
  104. });
  105. describe("快路径的增长上界", () => {
  106. it("整批都是键级增量:给出上界,且不小于这批 op 自己的字节数", () => {
  107. const deltas = [updated("dwfrun-1", 5), updated("dwfrun-2", 6)];
  108. const bound = workflowRunDeltaGrowthUpperBound(deltas);
  109. expect(bound).not.toBeNull();
  110. expect(bound!).toBeGreaterThan(JSON.stringify(deltas).length);
  111. });
  112. it("掺了任何其它 op 就必须精确测量", () => {
  113. expect(workflowRunDeltaGrowthUpperBound([updated("dwfrun-1", 5), ROW])).toBeNull();
  114. });
  115. /**
  116. * 一条 delta 都不产的事件(归约判了幂等重放)对快照的全部改动就是 `seq` 那个数字。让它落回
  117. * 精确路径等于为"什么都没发生"付一次整份序列化——而一个宽 fan-out 的 run 里重放并不罕见。
  118. */
  119. it("空批次走快路径,余量仍然盖得住 seq 位数的增长", () => {
  120. const bound = workflowRunDeltaGrowthUpperBound([]);
  121. expect(bound).not.toBeNull();
  122. expect(bound!).toBeGreaterThan(String(Number.MAX_SAFE_INTEGER).length);
  123. });
  124. /**
  125. * 这一条是快路径的安全边:diff 认不出结构变化时会退化成整键 `state.updated{workflowRuns}`,
  126. * 那条 op 的字节数**不是**增长的上界(它替换的是整个键,被替换掉的旧值不在其中)。
  127. */
  128. it("整键 workflowRuns patch 不走快路径", () => {
  129. const wholeKey: ConversationDelta = {
  130. op: "state.updated",
  131. patch: { workflowRuns: runState(300) },
  132. };
  133. expect(workflowRunDeltaGrowthUpperBound([wholeKey])).toBeNull();
  134. expect(workflowRunDeltaGrowthUpperBound([updated("dwfrun-1", 5), wholeKey])).toBeNull();
  135. });
  136. /**
  137. * 上界的论证是「一条 `workflowRun.updated` 写进快照的每个字节都在它自己的载荷里」。腾位
  138. * (workflow-runs-eviction.ts)给这条论证添了三处以前不存在的形状,每一处都是它可能破的地方:
  139. * 一条 op 同时带删除与 upsert、一个 header 键(`unlistedByPhase` / `truncated`)**第一次**出现、
  140. * 以及 upsert 用**更长**的条目替掉表里原来那条(增长是 new − old,不是 new——得真的是这样)。
  141. *
  142. * 所以这一条不靠论证,靠真归约跑一遍:每一步都把「快照长了多少」与「这批 op 有多少字节」摆在
  143. * 一起。界按 4 注入(归约留的测试口)——规则与界的大小无关,而 1024 要三千多条事件才撞得到。
  144. */
  145. it("腾位事件流:每一步的快照增长都不超过这批 op 自己的字节数", () => {
  146. let prior: WorkflowRunsState | undefined;
  147. let removals = 0;
  148. let headerBorn = 0;
  149. let longerUpserts = 0;
  150. let fallbacks = 0;
  151. for (const envelope of evictionEnvelopes()) {
  152. const next = reduceWorkflowRunsState(prior, envelope, TINY_LIMITS);
  153. if (next === null) continue;
  154. const ops = diffWorkflowRunsState(prior, next);
  155. // 「快照长了多少」按状态键整份量:prior 缺席时整个键是新的,这已经把它的外壳算进去了。
  156. const growth =
  157. utf8JsonByteLength(next) - (prior === undefined ? 0 : utf8JsonByteLength(prior));
  158. const bound = workflowRunDeltaGrowthUpperBound(ops);
  159. if (bound === null) fallbacks += 1;
  160. else {
  161. expect(bound).toBeGreaterThanOrEqual(growth);
  162. // 更紧的一条:64 的余量是留给 JSON 外壳与 `seq` 位数的,不该被 workflowRuns 自己吃掉。
  163. expect(utf8JsonByteLength(ops)).toBeGreaterThanOrEqual(growth);
  164. }
  165. longerUpserts += countLongerUpserts(prior, next);
  166. for (const op of ops) {
  167. if (op.op !== "workflowRun.updated") continue;
  168. if (op.removedActors !== undefined || op.removedNodes !== undefined) removals += 1;
  169. if (op.run?.unlistedByPhase !== undefined || op.run?.truncated !== undefined) {
  170. headerBorn += 1;
  171. }
  172. }
  173. prior = next;
  174. }
  175. // 三处形状都真的被走到了,否则上面那串断言只是在证明一条没发生过的事。
  176. expect(removals).toBeGreaterThan(0);
  177. expect(headerBorn).toBeGreaterThan(0);
  178. expect(longerUpserts).toBeGreaterThan(0);
  179. // 归约认得出的结构变化全程没有退化成整键重发——这一整段都在快路径上。
  180. expect(fallbacks).toBe(0);
  181. expect(prior?.runs[0]?.truncated).toBe(true);
  182. expect(prior?.runs[0]?.unlistedByPhase?.length).toBeGreaterThan(0);
  183. });
  184. });
  185. /** 界按 4 注入:腾位的规则与界的大小无关,小界让整条路径在几百条事件里走完。 */
  186. const TINY_LIMITS: WorkflowRunEntryLimits = { maxActors: 4, maxNodes: 4, maxPhases: 3 };
  187. /** 这一步里被**更长**的条目原地替掉的节点数(上界论证最容易被想当然的那一处)。 */
  188. function countLongerUpserts(prior: WorkflowRunsState | undefined, next: WorkflowRunsState): number {
  189. const before = prior?.runs[0];
  190. const after = next.runs[0];
  191. if (before === undefined || after === undefined) return 0;
  192. let count = 0;
  193. for (const node of after.nodes) {
  194. const old = before.nodes.find(
  195. (entry) => entry.siteId === node.siteId && entry.ordinal === node.ordinal,
  196. );
  197. if (old !== undefined && utf8JsonByteLength(node) > utf8JsonByteLength(old)) count += 1;
  198. }
  199. return count;
  200. }
  201. /**
  202. * 一段会反复撞界的引擎事件流:具名阶段的 ask 组(腾位的受害者)、无主的 world-read(游离节点)、
  203. * 越写越长的 `lastTool.target`(更长的 upsert),最后一次重臂 + 一批缓存命中的结算(孤儿规则)。
  204. */
  205. function evictionEnvelopes(): {
  206. runId: string;
  207. toolCallId: string;
  208. sequence: number;
  209. eventType: string;
  210. payload: Record<string, unknown>;
  211. }[] {
  212. const envelopes: ReturnType<typeof evictionEnvelopes> = [];
  213. const push = (eventType: string, payload: Record<string, unknown>): void => {
  214. envelopes.push({
  215. runId: "dwfrun-1",
  216. toolCallId: "tc-1",
  217. sequence: envelopes.length,
  218. eventType,
  219. payload,
  220. });
  221. };
  222. push("run-started", { runId: "dwfrun-1" });
  223. for (let ordinal = 1; ordinal <= 40; ordinal += 1) {
  224. const actor = { siteId: "agent#1", ordinal };
  225. const instance = { siteId: "ask#1", ordinal };
  226. const phaseName = `phase-${ordinal % 5}`;
  227. push("actor-created", { actor, name: `agent-${ordinal}`, phaseName });
  228. push("node-queued", { instance, actor, kind: "ask", phaseName });
  229. push("node-dispatched", { instance });
  230. push("node-executing", { instance });
  231. push("node-progress", {
  232. instance,
  233. turn: ordinal,
  234. toolCalls: ordinal * 3,
  235. lastTool: { name: "Bash", target: "t".repeat((ordinal * 5) % 64) },
  236. });
  237. if (ordinal % 4 === 0) {
  238. // 无主的 world-read:游离节点是 node 表的第一类受害者。
  239. push("node-queued", { instance: { siteId: "world#1", ordinal }, kind: "world-read" });
  240. push("node-settled", { instance: { siteId: "world#1", ordinal }, outcome: "ok" });
  241. }
  242. push("node-settled", { instance, outcome: ordinal % 9 === 0 ? "failed" : "ok" });
  243. }
  244. push("run-started", { runId: "dwfrun-1" });
  245. for (let ordinal = 1; ordinal <= 10; ordinal += 1) {
  246. // 出生即结算:它不腾位,被拒时走孤儿规则(连同那个带不进节点的 actor 一起记账)。
  247. push("node-settled", {
  248. instance: { siteId: "ask#1", ordinal },
  249. actor: { siteId: "agent#1", ordinal },
  250. cached: true,
  251. outcome: "ok",
  252. phaseName: `phase-${ordinal % 5}`,
  253. });
  254. }
  255. return envelopes;
  256. }