workflowTimelineCost.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // 时间线模型的成本契约(docs/dynamic-workflow/presentation.md「The timeline model」的 Cost 段):
  2. // 1. 参与者视图按 actors + nodes 线性,而不是两者的乘积——索引化之后输出必须与原来
  3. // 那套「每张卡重扫一遍 run.nodes」的算法逐字节相同,所以旧算法作为**参照实现**留在
  4. // 这个文件里,拿一条宽 run(一条车道上几百个实例、阶段再入、游离节点)对拍。
  5. // 2. 一对 (graph, run) 只建一次模型,两处消费拿到同一个对象。
  6. import { describe, expect, it } from "vitest";
  7. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  8. import {
  9. instanceCardId,
  10. liveParticipantView,
  11. type LiveParticipantView,
  12. type ParticipantInstance,
  13. } from "@/components/workflow-graph/participant-model.js";
  14. import { phaseBinder } from "@/components/workflow-graph/instance-phases.js";
  15. import { aggregateRunStatuses, statusOfRunNode } from "@/components/workflow-graph/run-status.js";
  16. import type {
  17. StepRunStatus,
  18. WorkflowCausalityGraphData,
  19. WorkflowHandoffData,
  20. WorkflowParticipantData,
  21. } from "@/components/workflow-graph/types.js";
  22. import { buildWorkflowTimeline } from "@/components/workflow-timeline/timeline-model.js";
  23. // ============================================================
  24. // 参照实现:索引化之前的 liveParticipantView,逐字保留
  25. // ============================================================
  26. function referenceBoundInstance(
  27. participantId: string,
  28. actor: WorkflowRunState["actors"][number],
  29. ): ParticipantInstance {
  30. return {
  31. bound: true,
  32. ordinal: actor.ordinal,
  33. participant: participantId,
  34. ...(actor.name === undefined ? {} : { name: actor.name }),
  35. };
  36. }
  37. function referenceLiveParticipantView(
  38. graph: WorkflowCausalityGraphData,
  39. run: WorkflowRunState | undefined,
  40. ): LiveParticipantView {
  41. if (run === undefined) return { graph, instances: {}, participantStatuses: {} };
  42. const siteOf = new Map(graph.steps.map((step) => [step.id, step.source ?? step.id]));
  43. const binder = phaseBinder(graph, run);
  44. const sitesOf = (participant: WorkflowParticipantData) =>
  45. new Set(participant.steps.map((id) => siteOf.get(id) ?? id));
  46. const instancesOfCard = (participant: WorkflowParticipantData) => {
  47. const sites = sitesOf(participant);
  48. const seen = new Set<number>();
  49. const here = new Set<number>();
  50. for (const node of run.nodes) {
  51. if (node.actorSiteId !== participant.lane || !sites.has(node.siteId)) continue;
  52. if (node.actorOrdinal === undefined) continue;
  53. seen.add(node.actorOrdinal);
  54. if (binder.has(participant.phase, node.phaseName)) here.add(node.actorOrdinal);
  55. }
  56. return run.actors
  57. .filter(
  58. (actor) =>
  59. actor.siteId === participant.lane &&
  60. (here.has(actor.ordinal) ||
  61. (!seen.has(actor.ordinal) && binder.has(participant.phase, actor.phaseName))),
  62. )
  63. .sort((a, b) => a.ordinal - b.ordinal);
  64. };
  65. const statusFor = (participant: WorkflowParticipantData, ordinal: number): StepRunStatus => {
  66. const sites = sitesOf(participant);
  67. const values = run.nodes
  68. .filter(
  69. (node) =>
  70. sites.has(node.siteId) &&
  71. node.actorSiteId === participant.lane &&
  72. node.actorOrdinal === ordinal &&
  73. binder.has(participant.phase, node.phaseName),
  74. )
  75. .map(statusOfRunNode);
  76. return aggregateRunStatuses(values) ?? "pending";
  77. };
  78. const participants: WorkflowParticipantData[] = [];
  79. const replacements = new Map<string, string[]>();
  80. const participantStatuses: Record<string, StepRunStatus> = {};
  81. const instances: Record<string, ParticipantInstance> = {};
  82. let changed = false;
  83. for (const participant of graph.participants) {
  84. const actors = instancesOfCard(participant);
  85. if (participant.member !== undefined) {
  86. const actor = actors[participant.member.index];
  87. participantStatuses[participant.id] =
  88. actor === undefined ? "pending" : statusFor(participant, actor.ordinal);
  89. if (actor !== undefined) {
  90. instances[participant.id] = referenceBoundInstance(participant.id, actor);
  91. }
  92. participants.push(participant);
  93. continue;
  94. }
  95. if (participant.many !== true && actors.length === 1) {
  96. instances[participant.id] = referenceBoundInstance(participant.id, actors[0]!);
  97. participants.push(participant);
  98. continue;
  99. }
  100. if (participant.many === true || actors.length > 1) {
  101. if (actors.length === 0) {
  102. participants.push(participant);
  103. continue;
  104. }
  105. changed = true;
  106. const ids: string[] = [];
  107. for (const actor of actors) {
  108. const id = instanceCardId(participant.id, actor.ordinal);
  109. const { many: _many, ...rest } = participant;
  110. participants.push({ ...rest, id });
  111. participantStatuses[id] = statusFor(participant, actor.ordinal);
  112. instances[id] = {
  113. ordinal: actor.ordinal,
  114. participant: participant.id,
  115. ...(actor.name === undefined ? {} : { name: actor.name }),
  116. };
  117. ids.push(id);
  118. }
  119. replacements.set(participant.id, ids);
  120. continue;
  121. }
  122. participants.push(participant);
  123. }
  124. if (!changed) return { graph, instances, participantStatuses };
  125. const handoffs: WorkflowHandoffData[] = [];
  126. for (const edge of graph.handoffs) {
  127. const froms = replacements.get(edge.from) ?? [edge.from];
  128. const tos = replacements.get(edge.to) ?? [edge.to];
  129. for (const from of froms) for (const to of tos) handoffs.push({ ...edge, from, to });
  130. }
  131. return { graph: { ...graph, handoffs, participants }, instances, participantStatuses };
  132. }
  133. // ============================================================
  134. // 一条宽 run:一条车道上几百个实例、阶段再入、成员卡、游离节点
  135. // ============================================================
  136. const PHASE_ONE = "起草";
  137. const PHASE_TWO = "校订";
  138. // `ask#m2` 带 source:站点键是 `ask#m1`,两张 many 卡因此共享一个站点、只靠阶段戳分开
  139. // (阶段再入正是索引化最容易画错的形状)。
  140. const GRAPH: WorkflowCausalityGraphData = {
  141. steps: [
  142. { id: "ask#m1", kind: "ask", label: "写", lane: "actor#many", phase: "phase#1" },
  143. {
  144. id: "ask#m2",
  145. kind: "ask",
  146. label: "改",
  147. lane: "actor#many",
  148. phase: "phase#2",
  149. source: "ask#m1",
  150. },
  151. { id: "ask#t1", kind: "ask", label: "评审", lane: "actor#team", phase: "phase#1" },
  152. { id: "ask#s1", kind: "ask", label: "汇总", lane: "actor#solo", phase: "phase#2" },
  153. { id: "world-read#1", kind: "world-read", label: "读稿", lane: "workspace", phase: "phase#1" },
  154. ],
  155. lanes: [
  156. { id: "actor#many", name: "写手" },
  157. { id: "actor#team", name: "评审" },
  158. { id: "actor#solo" },
  159. { id: "workspace" },
  160. ],
  161. participants: [
  162. { id: "phase#1:many", phase: "phase#1", lane: "actor#many", steps: ["ask#m1"], many: true },
  163. { id: "phase#2:many", phase: "phase#2", lane: "actor#many", steps: ["ask#m2"], many: true },
  164. {
  165. id: "phase#1:team#0",
  166. phase: "phase#1",
  167. lane: "actor#team",
  168. steps: ["ask#t1"],
  169. member: { index: 0, of: 3 },
  170. },
  171. {
  172. id: "phase#1:team#1",
  173. phase: "phase#1",
  174. lane: "actor#team",
  175. steps: ["ask#t1"],
  176. member: { index: 1, of: 3 },
  177. },
  178. {
  179. id: "phase#1:team#2",
  180. phase: "phase#1",
  181. lane: "actor#team",
  182. steps: ["ask#t1"],
  183. member: { index: 2, of: 3 },
  184. },
  185. { id: "phase#2:solo", phase: "phase#2", lane: "actor#solo", steps: ["ask#s1"] },
  186. { id: "phase#1:workspace", phase: "phase#1", lane: "workspace", steps: ["world-read#1"] },
  187. ],
  188. // 两端都会拆分的边会把交接表炸成乘积;这里各留一端拆分,替换逻辑照样走到。
  189. handoffs: [
  190. { from: "phase#1:team#0", to: "phase#1:many" },
  191. { from: "phase#2:many", to: "phase#2:solo" },
  192. ],
  193. phases: [
  194. { id: "phase#1", name: PHASE_ONE },
  195. { id: "phase#2", name: PHASE_TWO },
  196. ],
  197. phaseEdges: [{ from: "phase#1", to: "phase#2" }],
  198. exits: ["phase#2"],
  199. };
  200. type Node = WorkflowRunState["nodes"][number];
  201. type Actor = WorkflowRunState["actors"][number];
  202. /** 确定性伪随机:同一个种子每次生成同一条 run,失败可复现。 */
  203. function seeded(seed: number): () => number {
  204. let state = seed >>> 0;
  205. return () => {
  206. state = (state * 1664525 + 1013904223) >>> 0;
  207. return state / 0x100000000;
  208. };
  209. }
  210. const NODE_PHASES = ["queued", "dispatched", "executing", "waiting", "settled"] as const;
  211. /**
  212. * `solo` 车道上的实例数决定单卡走绑定还是拆分(1 张绑定、2 张拆分),两条路都要对拍。
  213. * actors 刻意**不按 ordinal 排**:认领顺序由算法自己排,顺序错了这里就会红。
  214. */
  215. function wideRun(options: { solo: number; stamped: boolean; many?: number }): WorkflowRunState {
  216. const random = seeded(20260920);
  217. const many = options.many ?? 400;
  218. const stamp = (phaseName: string) => (options.stamped ? { phaseName } : {});
  219. const actors: Actor[] = [];
  220. const nodes: Node[] = [];
  221. for (let i = many; i >= 1; i -= 1) {
  222. // 前一半出生在 phase#1,后一半出生在 phase#2:两张 many 卡各认领一半。
  223. const born = i <= many / 2 ? PHASE_ONE : PHASE_TWO;
  224. actors.push({
  225. siteId: "actor#many",
  226. ordinal: i,
  227. status: "running",
  228. ...(i % 7 === 0 ? {} : { name: `写手${i}` }),
  229. ...stamp(born),
  230. });
  231. // 七分之一的实例一个节点都没有:它们按**自己的出生戳**归位(pending 药丸)。
  232. if (i % 7 === 0) continue;
  233. const count = 1 + Math.floor(random() * 3);
  234. for (let k = 0; k < count; k += 1) {
  235. const phase = NODE_PHASES[Math.floor(random() * NODE_PHASES.length)]!;
  236. nodes.push({
  237. siteId: "ask#m1",
  238. ordinal: k + 1,
  239. phase,
  240. ...(phase === "settled"
  241. ? { outcome: k % 5 === 0 ? ("failed" as const) : ("ok" as const) }
  242. : {}),
  243. actorSiteId: "actor#many",
  244. actorOrdinal: i,
  245. ...stamp(born),
  246. });
  247. }
  248. // 图里不存在的站点:叠加与认领都必须忽略它。
  249. if (i % 11 === 0) {
  250. nodes.push({
  251. siteId: "ask#gone",
  252. ordinal: 1,
  253. phase: "settled",
  254. outcome: "ok",
  255. actorSiteId: "actor#many",
  256. actorOrdinal: i,
  257. ...stamp(born),
  258. });
  259. }
  260. }
  261. // 成员卡:车道上 4 个实例,`of` 是 3——多出来的那个不出卡。
  262. for (let i = 1; i <= 4; i += 1) {
  263. actors.push({ siteId: "actor#team", ordinal: i, status: "completed", ...stamp(PHASE_ONE) });
  264. nodes.push({
  265. siteId: "ask#t1",
  266. ordinal: 1,
  267. phase: "settled",
  268. outcome: i === 2 ? "failed" : "ok",
  269. actorSiteId: "actor#team",
  270. actorOrdinal: i,
  271. ...stamp(PHASE_ONE),
  272. });
  273. }
  274. for (let i = 1; i <= options.solo; i += 1) {
  275. actors.push({ siteId: "actor#solo", ordinal: i, status: "waiting", ...stamp(PHASE_TWO) });
  276. }
  277. // 游离节点:没有 actor(world-read),以及有 actorSiteId 却没有 ordinal 的旧载荷。
  278. nodes.push({ siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok" });
  279. nodes.push({
  280. siteId: "ask#m1",
  281. ordinal: 1,
  282. phase: "executing",
  283. actorSiteId: "actor#many",
  284. ...stamp(PHASE_ONE),
  285. });
  286. return {
  287. runId: "dwfrun-wide",
  288. toolCallId: "tool-wide",
  289. status: "running",
  290. usage: { spentTokens: 0, nodesUsed: nodes.length },
  291. actors,
  292. nodes,
  293. lastEventSequence: nodes.length,
  294. };
  295. }
  296. /** 顺序敏感的对拍:`toEqual` 不看键序,卡序与状态表的键序都要自己比。 */
  297. function expectSameView(actual: LiveParticipantView, expected: LiveParticipantView): void {
  298. expect(actual.graph.participants.map((participant) => participant.id)).toEqual(
  299. expected.graph.participants.map((participant) => participant.id),
  300. );
  301. expect(actual.graph.handoffs).toEqual(expected.graph.handoffs);
  302. expect(Object.keys(actual.participantStatuses)).toEqual(
  303. Object.keys(expected.participantStatuses),
  304. );
  305. expect(Object.keys(actual.instances)).toEqual(Object.keys(expected.instances));
  306. expect(actual).toEqual(expected);
  307. }
  308. describe("liveParticipantView · 索引化与参照实现对拍", () => {
  309. for (const solo of [1, 2]) {
  310. for (const stamped of [true, false]) {
  311. it(`宽 run 逐字节相同(solo=${solo},${stamped ? "有" : "无"}阶段戳)`, () => {
  312. const run = wideRun({ solo, stamped });
  313. expectSameView(liveParticipantView(GRAPH, run), referenceLiveParticipantView(GRAPH, run));
  314. });
  315. }
  316. }
  317. it("拆分出的实例卡按 ordinal 升序,与 run.actors 的到达序无关", () => {
  318. const run = wideRun({ solo: 2, stamped: true });
  319. const ids = liveParticipantView(GRAPH, run)
  320. .graph.participants.filter((participant) => participant.id.startsWith("phase#1:many@"))
  321. .map((participant) => Number(participant.id.split("@")[1]));
  322. expect(ids.length).toBeGreaterThan(100);
  323. expect(ids).toEqual([...ids].sort((left, right) => left - right));
  324. });
  325. it("阶段再入:共享站点的两张 many 卡各认领自己那一半实例", () => {
  326. const view = liveParticipantView(GRAPH, wideRun({ solo: 1, stamped: true }));
  327. const count = (prefix: string) =>
  328. view.graph.participants.filter((participant) => participant.id.startsWith(prefix)).length;
  329. expect(count("phase#1:many@")).toBe(200);
  330. expect(count("phase#2:many@")).toBe(200);
  331. });
  332. it("无 run 时原样返回输入图(引用相等)", () => {
  333. const view = liveParticipantView(GRAPH, undefined);
  334. expect(view.graph).toBe(GRAPH);
  335. expect(view.instances).toEqual({});
  336. });
  337. });
  338. describe("buildWorkflowTimeline · 一对 (graph, run) 只建一次", () => {
  339. it("同一对对象两次调用返回同一个模型", () => {
  340. const run = wideRun({ solo: 1, stamped: true });
  341. expect(buildWorkflowTimeline(GRAPH, run)).toBe(buildWorkflowTimeline(GRAPH, run));
  342. });
  343. it("run 换了新对象就重建——投影每帧发新对象,身份是正确的键", () => {
  344. const first = wideRun({ solo: 1, stamped: true });
  345. const second = { ...first };
  346. const before = buildWorkflowTimeline(GRAPH, first);
  347. const after = buildWorkflowTimeline(GRAPH, second);
  348. expect(after).not.toBe(before);
  349. expect(after).toEqual(before);
  350. });
  351. it("同一条 run 配两张图各建各的", () => {
  352. const run = wideRun({ solo: 1, stamped: true });
  353. const other: WorkflowCausalityGraphData = { ...GRAPH, exits: [] };
  354. expect(buildWorkflowTimeline(other, run)).not.toBe(buildWorkflowTimeline(GRAPH, run));
  355. });
  356. it("无 run 的静态图同样只建一次", () => {
  357. expect(buildWorkflowTimeline(GRAPH, undefined)).toBe(buildWorkflowTimeline(GRAPH, undefined));
  358. });
  359. });