/** * plugins/workflow-runner/test/apiConcurrencyGate.test.ts —— llm() 与 agent() * 共用进程级模型调度器 * * `generate()`、`agent()`、`skill()` 都必须进入同一个进程级 model pool;测试从 * 统一配置读取边界,不能再复制一个常量,否则环境配置和测试会悄悄分叉。 */ import { afterEach, describe, expect, test } from 'bun:test'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { LoopEvent } from '../../../src/plugin-sdk.js'; import { createWorkflowContext } from '../src/runtime/context.js'; import { Journal } from '../src/journal.js'; import { readWorkflowRuntimeConfig } from '../src/runtime/config.js'; import type { RunContext } from '../src/types.js'; import { WorkflowState } from '../src/workflowState.js'; const dirs: string[] = []; const MODEL_LIMIT = readWorkflowRuntimeConfig({} as NodeJS.ProcessEnv) .modelConcurrency; afterEach(() => { for (const d of dirs.splice(0)) { try { rmSync(d, { recursive: true, force: true, maxRetries: 3 }); } catch { /* Windows 偶发 EBUSY;清理失败不影响断言 */ } } }); /** 造一套最小可跑的注入环境,chat stub 会记录任意时刻的实际并发数峰值。 */ async function harness() { const wd = mkdtempSync(join(tmpdir(), 'wf-gate-')); dirs.push(wd); const state = new WorkflowState(wd, 'demo', 's1'); await state.init({ goal: '测试目标' }, 'hash-v1', []); const journal = new Journal(state.journalPath, { bundleHash: 'test', rootRunId: 'test-root' }); await journal.load(); let active = 0; let peak = 0; const chat: NonNullable = async function* () { active++; peak = Math.max(peak, active); try { // 强制重叠:没有这个延迟,调用可能快到彼此从不同时在场,测不出并发峰值。 await new Promise((r) => setTimeout(r, 15)); yield { type: 'text_delta' as const, delta: 'ok' }; yield { type: 'done' as const, stopReason: 'stop' as const }; } finally { active--; } }; const events: LoopEvent[] = []; const ctx = { provider: { name: 'test' }, history: [{ role: 'system', content: 'sys' }], cwd: wd, tools: [], chat, } as unknown as RunContext; const globals = createWorkflowContext({ ctx, state, journal, emit: (ev) => events.push(ev), args: {}, workflowName: 'demo', session: 's1', task: state.taskId, }); return { globals, peakConcurrency: () => peak }; } describe('generate()/agent() 共用进程级模型调度器', () => { test(`★ 混合扇出 ${MODEL_LIMIT * 2} 个 generate()+agent() 调用,实际并发峰值不超过 ${MODEL_LIMIT}`, async () => { const h = await harness(); const N = MODEL_LIMIT * 2; await Promise.all( Array.from({ length: N }, (_, i) => i % 2 === 0 ? h.globals.model.generate(`任务 ${i}`) : h.globals.model.agent(`任务 ${i}`), ), ); expect(h.peakConcurrency()).toBeLessThanOrEqual(MODEL_LIMIT); }); test('★ 纯 llm() 扇出同样受同一把闸约束(不是只有 agent() 受限)', async () => { const h = await harness(); const N = MODEL_LIMIT * 2; await Promise.all( Array.from({ length: N }, (_, i) => h.globals.model.generate(`任务 ${i}`)), ); expect(h.peakConcurrency()).toBeLessThanOrEqual(MODEL_LIMIT); // 扇出规模显著大于闸门上限时,峰值应当明显叠起来、接近上限(否则上面的 // 断言可能只是因为并发压根没叠起来,同样是假绿)。账本落盘等异步开销会让 // 各调用起跑时间略有错开,所以不强求刚好等于上限,只要求足够接近。 expect(h.peakConcurrency()).toBeGreaterThanOrEqual(MODEL_LIMIT - 2); }); });