workflow-driver-seat-gate.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /**
  2. * driver × 座位闸门 × 真治理器(docs/dynamic-workflow/concurrency.md「Retuning a live run」):
  3. * 上界从 4 压到 1 之后,工作中的子代理在**下一个 turn step** 上停驻,而手上有工具在跑的那个
  4. * 子代理的工具侧请求照常发得出去;抬高按 FIFO 放行;停驻期间取消 ask 会连同座位等待一起拒绝,
  5. * 并且不腾出任何座位。
  6. *
  7. * ask 的起止走的是**生产那两条**:起点是 `driver.startAsk`,终点是引擎经 `driver.emit` 记下的
  8. * `node-settled`——测试直接调 emit 来扮演引擎的 record()。
  9. */
  10. import { describe, expect, it } from "vitest";
  11. import {
  12. SessionEventType,
  13. type ModelRequestAdmission,
  14. type SessionEvent,
  15. type SessionEventSink,
  16. } from "@zcode/contracts";
  17. import {
  18. InMemoryJournalStore,
  19. type ActorRef,
  20. type InstanceRef,
  21. type RunEvent,
  22. type WorkflowReportSink,
  23. } from "@zcode/dynamic-workflow";
  24. import { createWorkflowEscalationRegistry } from "../src/app/workflow-escalation-registry.js";
  25. import { createJournalSequenceCapture } from "../src/app/dynamic-workflow-run-sequence-capture.js";
  26. import { createAgentRuntimeWorkflowDriver } from "../src/app/workflow-driver.js";
  27. import { createWorkflowConcurrencyGovernor } from "../src/app/workflow-concurrency-governor.js";
  28. import { createWorkflowRunControl } from "../src/app/workflow-run-control.js";
  29. import { createWorkflowRunSeatGate } from "../src/app/workflow-seat-gate.js";
  30. import { fakeFileSystemPort, unsupportedExecutionPort } from "./workflow-driver.helpers.js";
  31. const RUN = "run-seat";
  32. const MODEL = { providerId: "prov", modelId: "alpha" } as never;
  33. const actorOf = (ordinal: number): ActorRef => ({ siteId: "actor#1", ordinal });
  34. const instanceOf = (ordinal: number): InstanceRef => ({ siteId: "ask#1", ordinal });
  35. const flush = async (): Promise<void> => {
  36. await new Promise<void>((resolve) => setImmediate(resolve));
  37. };
  38. /** 最小 actor runtime:捕获 turn 的 abortSignal(cancelAsk 要经它到达座位等待),可发工具事件。 */
  39. function stubRuntime() {
  40. const sinks = new Set<SessionEventSink>();
  41. let sessionId = "";
  42. let abortSignal: AbortSignal | undefined;
  43. const emit = (type: string, toolCallId: string): void => {
  44. const event = {
  45. id: `evt-${toolCallId}`,
  46. sessionId,
  47. type,
  48. timestamp: new Date(),
  49. traceId: "trace",
  50. sequenceNumber: 1,
  51. payload: { toolCallId, toolName: "WebSearch", startedAt: new Date() },
  52. } as unknown as SessionEvent;
  53. for (const sink of sinks) void sink.onSessionEvent(event);
  54. };
  55. return {
  56. executeTurn: (_input: string, _history: unknown, options?: { abortSignal?: AbortSignal }) => {
  57. abortSignal = options?.abortSignal;
  58. return new Promise<never>(() => {});
  59. },
  60. subscribeEvents(sink: SessionEventSink) {
  61. sinks.add(sink);
  62. return () => sinks.delete(sink);
  63. },
  64. getModelRef: () => MODEL,
  65. close: async () => {},
  66. closeBrowserSession: async () => {},
  67. signal: (): AbortSignal | undefined => abortSignal,
  68. toolStarted: (toolCallId: string) => emit(SessionEventType.ToolCallStarted, toolCallId),
  69. toolFinished: (toolCallId: string) => emit(SessionEventType.ToolCallResult, toolCallId),
  70. bind: (id: string) => {
  71. sessionId = id;
  72. },
  73. };
  74. }
  75. const silentSink: WorkflowReportSink = {
  76. askSubmitAttempted: () => {},
  77. askTurnEnded: () => {},
  78. askProgress: () => {},
  79. askStats: () => {},
  80. askFailed: () => {},
  81. askWaiting: () => {},
  82. askExecuting: () => {},
  83. askMutating: () => {},
  84. concurrencyChanged: () => {},
  85. stopRun: () => {},
  86. runStalled: () => {},
  87. };
  88. /** 装配一个带闸门与真治理器的 driver,并起 `count` 个各自在飞一个 ask 的子代理。 */
  89. async function startRun(count: number, limit: number) {
  90. const journal = new InMemoryJournalStore();
  91. journal.createRun({
  92. runId: RUN,
  93. caps: { maxConcurrency: limit },
  94. spentTokens: 0,
  95. status: "running",
  96. });
  97. const seatGate = createWorkflowRunSeatGate({ limit });
  98. const control = createWorkflowRunControl();
  99. control.bindSeatGate(seatGate);
  100. // 引擎的替身:只回答「这次真的改了」——真引擎的 caps / journal / 事件那半边由
  101. // dynamic-workflow 侧的 engine-retune-concurrency 测试钉住。
  102. const engineCalls: number[] = [];
  103. control.bind({
  104. setMaxConcurrency: (next) => {
  105. engineCalls.push(next);
  106. return true;
  107. },
  108. });
  109. const runtimes = Array.from({ length: count }, () => stubRuntime());
  110. const admissions: ModelRequestAdmission[] = [];
  111. const emitted: RunEvent[] = [];
  112. const emittedSequences: (number | undefined)[] = [];
  113. // 与生产 launch 逐字同构:driver 拿到的是**被截获的** journal,emit 钩子按事件对象的引用
  114. // 反查刚分配到的 sequence(dynamic-workflow-run-launch.ts)。座位闸门那层包装如果换了对象,
  115. // 这里立刻就能看出来。
  116. const sequenceCapture = createJournalSequenceCapture(journal);
  117. let index = 0;
  118. const driver = createAgentRuntimeWorkflowDriver({
  119. journal: sequenceCapture.journal,
  120. emit: (event) => {
  121. emitted.push(event);
  122. emittedSequences.push(sequenceCapture.sequenceOf(event));
  123. },
  124. escalationRegistry: createWorkflowEscalationRegistry(),
  125. executionPort: unsupportedExecutionPort(),
  126. fileSystemPort: fakeFileSystemPort({}),
  127. cwd: process.cwd(),
  128. runId: RUN,
  129. concurrency: createWorkflowConcurrencyGovernor({ defaultConcurrency: 16 }),
  130. seatGate,
  131. runtimeFactory: ({ sessionId, modelRequestAdmission }) => {
  132. const runtime = runtimes[index++]!;
  133. runtime.bind(sessionId);
  134. admissions.push(modelRequestAdmission!);
  135. return runtime as never;
  136. },
  137. })(silentSink);
  138. for (let ordinal = 1; ordinal <= count; ordinal++) {
  139. const session = await driver.createActorSession(actorOf(ordinal), {});
  140. driver.startAsk(session, instanceOf(ordinal), { instructions: "go", typed: false });
  141. }
  142. await flush();
  143. return {
  144. admissions,
  145. control,
  146. driver,
  147. emitted,
  148. emittedSequences,
  149. engineCalls,
  150. journal,
  151. runtimes,
  152. seatGate,
  153. };
  154. }
  155. describe("driver 侧座位闸门", () => {
  156. it("压低 4→1:后来的 turn step 逐个停驻,工具在跑的那个子代理照常发请求", async () => {
  157. const run = await startRun(4, 4);
  158. expect(run.seatGate.stats()).toEqual({ limit: 4, working: 4, parked: 0 });
  159. // 一个子代理手上有两个并行工具调用;上界压低的那一刻它正在工具里。
  160. run.runtimes[0]!.toolStarted("tc-a");
  161. run.runtimes[0]!.toolStarted("tc-b");
  162. expect(run.control.setMaxConcurrency(1)).toBe(true);
  163. expect(run.engineCalls).toEqual([1]);
  164. expect(run.seatGate.stats().limit).toBe(1);
  165. // 工具侧请求:快路径命中、不停驻——它的主人本就在工作、本就占着座位。
  166. expect(run.admissions[0]!.tryAcquire?.({ model: MODEL })).toBeDefined();
  167. await run.admissions[0]!.acquire({ model: MODEL });
  168. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 4, parked: 0 });
  169. // 其余三个的下一个 turn step:快路径未命中(runner 因此发 queued → waiting(slot)),随后停驻。
  170. run.admissions.slice(1).map((admission, offset) => {
  171. expect(admission.tryAcquire?.({ model: MODEL })).toBeUndefined();
  172. return admission.acquire({
  173. model: MODEL,
  174. signal: run.runtimes[offset + 1]!.signal()!,
  175. });
  176. });
  177. await flush();
  178. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 3 });
  179. // 工具跑完之后,同一个子代理的下一个请求就是 turn step 了——但它是此刻唯一在工作的那个,
  180. // 上界之内,所以照常通过(上界 1 永远留得下一个在跑的人)。
  181. run.runtimes[0]!.toolFinished("tc-a");
  182. run.runtimes[0]!.toolFinished("tc-b");
  183. expect(run.admissions[0]!.tryAcquire?.({ model: MODEL })).toBeDefined();
  184. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 3 });
  185. });
  186. it("引擎记下的 node-settled 腾出座位并按 FIFO 放行一位;事件原样转交给 emit 钩子", async () => {
  187. const run = await startRun(3, 3);
  188. run.control.setMaxConcurrency(1);
  189. const granted: number[] = [];
  190. run.admissions.slice(0, 2).forEach((admission, offset) => {
  191. void admission.acquire({ model: MODEL }).then(() => granted.push(offset + 1));
  192. });
  193. await flush();
  194. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 2 });
  195. // 扮演引擎的 record():先 appendEvent、紧接着 emit **同一个对象**(engine.ts 的顺序)。
  196. const settled: RunEvent = { type: "node-settled", instance: instanceOf(3), outcome: "ok" };
  197. const stored = run.journal.appendEvent(RUN, settled);
  198. run.driver.emit(settled);
  199. await flush();
  200. // 闸门那层包装必须原样往下递:sequence 截取按**引用相等**核对,换了对象就反查不到。
  201. expect(run.emitted.at(-1)).toBe(settled);
  202. expect(run.emittedSequences.at(-1)).toBe(stored.sequence);
  203. expect(granted).toEqual([1]);
  204. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 1 });
  205. });
  206. it("闸门没见过开始的 node-settled(命中缓存、world 节点)是严格无操作", async () => {
  207. const run = await startRun(2, 2);
  208. run.control.setMaxConcurrency(1);
  209. const granted: number[] = [];
  210. void run.admissions[0]!.acquire({ model: MODEL }).then(() => granted.push(1));
  211. await flush();
  212. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 1 });
  213. // 命中导入缓存的 ask 只发一条 `node-settled { cached: true }`,从不经 startAsk;
  214. // world-read / world.run 节点住在另一套站点上,同样从不经 startAsk。
  215. run.driver.emit({
  216. type: "node-settled",
  217. instance: { siteId: "ask#1", ordinal: 42 },
  218. outcome: "ok",
  219. cached: true,
  220. });
  221. run.driver.emit({
  222. type: "node-settled",
  223. instance: { siteId: "world#1", ordinal: 1 },
  224. outcome: "ok",
  225. });
  226. await flush();
  227. expect(granted).toEqual([]);
  228. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 1 });
  229. });
  230. it("抬高上界按 FIFO 放行", async () => {
  231. const run = await startRun(4, 4);
  232. run.control.setMaxConcurrency(1);
  233. const granted: number[] = [];
  234. run.admissions.slice(1).forEach((admission, offset) => {
  235. void admission.acquire({ model: MODEL }).then(() => granted.push(offset + 2));
  236. });
  237. await flush();
  238. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 3 });
  239. expect(run.control.setMaxConcurrency(3)).toBe(true);
  240. await flush();
  241. expect(granted).toEqual([2, 3]);
  242. expect(run.seatGate.stats()).toEqual({ limit: 3, working: 3, parked: 1 });
  243. });
  244. it("停驻期间取消这个 ask:座位等待随 turn 的 abort 一起拒绝,且不腾座位", async () => {
  245. const run = await startRun(2, 2);
  246. run.control.setMaxConcurrency(1);
  247. const waiting = run.admissions[1]!.acquire({
  248. model: MODEL,
  249. signal: run.runtimes[1]!.signal()!,
  250. });
  251. await flush();
  252. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 1 });
  253. // 引擎取消 ask:abortInFlight 先调 cancelAsk(abort)、再记 node-settled,这里同序。
  254. run.driver.cancelAsk(instanceOf(2));
  255. await expect(waiting).rejects.toThrow(/cancelled/);
  256. run.driver.emit({ type: "node-settled", instance: instanceOf(2), outcome: "cancelled" });
  257. await flush();
  258. // 被取消的那位停驻时就已经不占座位,这里绝不能再腾一次。
  259. expect(run.seatGate.stats()).toEqual({ limit: 1, working: 1, parked: 0 });
  260. });
  261. it("从未被压低过的 run:闸门全程不介入,快路径逐次命中", async () => {
  262. const run = await startRun(3, 3);
  263. for (const admission of run.admissions) {
  264. expect(admission.tryAcquire?.({ model: MODEL })).toBeDefined();
  265. await admission.acquire({ model: MODEL });
  266. }
  267. expect(run.seatGate.stats()).toEqual({ limit: 3, working: 3, parked: 0 });
  268. });
  269. });