返回源码地图

packages/coding-agent/test/codemode-worker-admission.test.ts

v1.3.0 · 71023aec1546 · 09:读过上游live-worker admission、迟到WASM启动与burst测试,未本机执行

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { Worker } from "node:worker_threads";
2import * as codemode from "@earendil-works/pi-codemode";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4import { executeCodemode } from "../src/extensions/codemode/execute.ts";
5
6const terminate = Worker.prototype.terminate;
7const terminations = new Map<Worker, (code: number) => void>();
8
9beforeEach(() => {
10 vi.spyOn(Worker.prototype, "terminate").mockImplementation(function (this: Worker) {
11 this.ref();
12 return new Promise<number>((resolve) => {
13 terminations.set(this, resolve);
14 });
15 });
16});
17
18afterEach(async () => {
19 vi.restoreAllMocks();
20 await Promise.all(
21 [...terminations].map(async ([worker, resolve]) => {
22 resolve(await terminate.call(worker));
23 }),
24 );
25 terminations.clear();
26});
27
28const run = (code: string, signal?: AbortSignal) =>
29 executeCodemode("worker-admission", { code }, signal, undefined, undefined);
30
31describe("codemode worker admission", () => {
32 // #10748: fresh sandboxes must share capacity and retain it until actual worker exit.
33 it.each(["timeout", "abort", "success"] as const)("bounds surviving workers after %s", async (how) => {
34 const once = vi.spyOn(Worker.prototype, "once");
35 for (let i = 0; i < 2; i++) {
36 const controller = new AbortController();
37 const exitListenersBefore = once.mock.calls.filter(([event]) => event === "exit").length;
38 const pending = run(
39 how === "timeout"
40 ? '// @options: {"timeout_ms": 200}\nwhile (true) {}'
41 : how === "abort"
42 ? "while (true) {}"
43 : "return 1",
44 controller.signal,
45 );
46 if (how === "abort") {
47 await vi.waitFor(() =>
48 expect(once.mock.calls.filter(([event]) => event === "exit").length).toBeGreaterThan(
49 exitListenersBefore,
50 ),
51 );
52 controller.abort();
53 }
54 const result = await pending;
55 if (how === "success") expect(result.isError).toBeUndefined();
56 else {
57 expect(result.isError).toBe(true);
58 expect(result.content).toContainEqual({
59 type: "text",
60 text: expect.stringContaining(how === "timeout" ? "Script timed out:" : "Script aborted:"),
61 });
62 }
63 expect(terminations.size).toBe(i + 1);
64 }
65
66 const blocked = await run("return 3");
67 expect(blocked).toMatchObject({ isError: true, details: { calls: [] } });
68 expect(blocked.content).toContainEqual({
69 type: "text",
70 text: expect.stringContaining("Codemode worker limit reached (2 workers are still running or shutting down)"),
71 });
72 expect(terminations.size).toBe(2);
73
74 const aborted = await run("while (true) {}", AbortSignal.abort());
75 expect(aborted.isError).toBe(true);
76 expect(aborted.content).toContainEqual({ type: "text", text: expect.stringContaining("Script aborted:") });
77 expect(terminations.size).toBe(2);
78
79 // Releasing one actual worker, not its result, permits exactly one new execution.
80 const [worker, resolve] = [...terminations][0];
81 resolve(await terminate.call(worker));
82 terminations.delete(worker);
83 expect((await run("return 42")).isError).toBeUndefined();
84 expect(terminations.size).toBe(2);
85 });
86
87 // #10748: timed-out launches resuming after WASM loading must obey the same limit.
88 it("bounds workers that start after their results already timed out", async () => {
89 const wasm = await codemode.loadQuickJSWasm();
90 const loading = Promise.withResolvers<codemode.CodemodeWasmModule>();
91 vi.spyOn(codemode, "loadQuickJSWasm").mockReturnValue(loading.promise);
92 try {
93 const results = await Promise.all(
94 Array.from({ length: 3 }, () => run('// @options: {"timeout_ms": 20}\nwhile (true) {}')),
95 );
96 expect(results.every((result) => result.isError)).toBe(true);
97 expect(terminations.size).toBe(0);
98 loading.resolve(wasm);
99 const blocked = await run("return 1");
100 expect(blocked.isError).toBe(true);
101 expect(blocked.content).toContainEqual({
102 type: "text",
103 text: expect.stringContaining("Codemode worker limit reached"),
104 });
105 expect(terminations.size).toBe(2);
106 } finally {
107 loading.resolve(wasm);
108 }
109 });
110
111 // #10748: concurrent callers must not race past the shared admission limit.
112 it("admits only two workers from a concurrent burst", async () => {
113 const results = await Promise.all(Array.from({ length: 6 }, () => run("return 1")));
114 expect(results.filter((result) => !result.isError)).toHaveLength(2);
115 expect(results.filter((result) => result.isError)).toHaveLength(4);
116 expect(terminations.size).toBe(2);
117 });
118});