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

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