From 47d889b2ba481e5bf923d7b7090bd7050956e412 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CM4n5ter=E2=80=9D?= Date: Sat, 28 Nov 2026 11:21:13 +0800 Subject: [PATCH 1/4] feat(mock-ai): add deterministic benchmark scenarios, strict session routing, and harness-bench runner Upgrade maka-mock-ai into a protocol-faithful, receipt-driven simulator for fair multi-harness stress benchmarking, and add a zero-dependency Node ESM benchmark runner under tools/harness-bench: - Scoped routing & lineage (src/routing.rs, src/control.rs, src/proxy.rs): - Single-pass /s///... route parser across HTTP, WS, /models/{id}, /v1/messages/count_tokens, /v1/responses/compact, and owner-scoped GET/DELETE /v1/responses/{id}. - Explicit SessionRegistry, strict identity precedence with conflict diagnostics, side-channel/compaction classifier (Main / Side / Compact / Control), and separated session/lineage/stored-body lifecycles with lock-free drops. - Proxy v2 canonical request fingerprints (including response_format, text.format, anthropic-beta, query, lane) with versioned compatibility checks and replay for response GET/DELETE. - Deterministic semantic scenario engine & cross-harness tool binder (src/scenario/, src/schema_synth.rs): - Receipt-driven atomic revision state machine with PlanRecipe/RequestKey idempotency across 429/503/disconnect/HTTP-WS retries, out-of-order parallel receipts, client & native compaction checkpoints, and runner observations via POST /admin/sessions/{id}/observations. - Schema-validated (jsonschema) and freeform grammar tool binding across Maka (direct & Code Mode), Claude Code, Codex (custom apply_patch + nested namespace MCP), OpenCode v2, Pi 1.0, Pi-Durable, Dim, DeepSeek Harness, ZCode, Kimi Code, and Shared MCP. - Wire codec fidelity & zero-waste streaming (src/protocol.rs, src/plan.rs, src/codec/, src/server/): - EncodedFrame carries FrameKind + semantic_bytes (removing hot-path TTFT JSON reparsing and redundant non-streaming chunk iteration). - Anthropic ping/thinking+signature/is_error/disable_parallel_tool_use/pause_after_compaction, Chat stream_options.include_usage & dialect-gated reasoning_content, Responses sequence_number/content_index/namespace/WS generate:false warmup. - Observability, fact-driven watchdog & pacing (src/watchdog.rs, src/metrics.rs, src/pacing.rs, src/ratelimit.rs, src/server/admin.rs): - Monotonic-ns AttemptSpan, dual-budget per-session rings, paginated /admin/sessions* export/finalize/reclaim, interval-union attribution (mock_service_sum / outside_mock_wall / mock_union), Prometheus status label fix, generation-guarded reset/faults, and absolute decode deadlines. - Multi-harness benchmark runner (tools/harness-bench/): - Zero-dependency Node ESM CLI (preflight, run, calibrate, matrix), 5 built-in scenarios, isolated workspace fixture verifier, stdio Shared MCP server with independent JSONL audit log, process-tree RSS/CPU monitor with SIGKILL injection, 16 isolated adapters (10 harnesses + ref-agent), and end-to-end tests. --- Cargo.lock | 1 + tools/harness-bench/README.md | 85 + tools/harness-bench/adapters.mjs | 1054 ++++++ tools/harness-bench/bench.test.mjs | 277 ++ tools/harness-bench/fixtures.mjs | 297 ++ tools/harness-bench/mcp-server.mjs | 227 ++ tools/harness-bench/mock-client.mjs | 305 ++ tools/harness-bench/proc-monitor.mjs | 227 ++ tools/harness-bench/report.mjs | 236 ++ tools/harness-bench/run.mjs | 549 +++ .../scenarios/chaos-recovery.json | 67 + .../scenarios/concurrency-fanout.json | 58 + .../scenarios/long-compaction.json | 50 + .../scenarios/mcp-smoke-edit.json | 47 + tools/harness-bench/scenarios/smoke-edit.json | 47 + tools/mock-ai/Cargo.toml | 1 + tools/mock-ai/README.md | 46 + tools/mock-ai/src/codec/anthropic.rs | 1175 ++++--- tools/mock-ai/src/codec/chat_completions.rs | 720 ++-- tools/mock-ai/src/codec/mod.rs | 327 +- tools/mock-ai/src/codec/responses.rs | 1501 ++++++--- tools/mock-ai/src/control.rs | 363 +- tools/mock-ai/src/handler.rs | 24 + tools/mock-ai/src/lib.rs | 33 +- tools/mock-ai/src/main.rs | 92 +- tools/mock-ai/src/metrics.rs | 1273 ++++++- tools/mock-ai/src/pacing.rs | 288 +- tools/mock-ai/src/plan.rs | 167 +- tools/mock-ai/src/protocol.rs | 1151 +++++-- tools/mock-ai/src/proxy.rs | 1473 ++++++-- tools/mock-ai/src/ratelimit.rs | 241 +- tools/mock-ai/src/routing.rs | 1369 ++++++++ tools/mock-ai/src/rules.rs | 25 +- tools/mock-ai/src/scenario/mod.rs | 2952 +++++++++++++++++ tools/mock-ai/src/scenario/tools.rs | 1461 ++++++++ tools/mock-ai/src/schema_synth.rs | 879 ++++- tools/mock-ai/src/server.rs | 1395 +++++++- tools/mock-ai/src/server/admin.rs | 861 ++++- tools/mock-ai/src/server/http.rs | 2352 +++++++------ tools/mock-ai/src/server/ws.rs | 1429 ++++---- tools/mock-ai/src/watchdog.rs | 1026 ++++-- tools/mock-ai/src/workload.rs | 211 +- tools/mock-ai/tests/advanced_simulation.rs | 610 +++- tools/mock-ai/tests/protocol_conformance.rs | 810 ++++- tools/mock-ai/tests/stress_and_scenarios.rs | 510 ++- 45 files changed, 23494 insertions(+), 4798 deletions(-) create mode 100644 tools/harness-bench/README.md create mode 100644 tools/harness-bench/adapters.mjs create mode 100644 tools/harness-bench/bench.test.mjs create mode 100644 tools/harness-bench/fixtures.mjs create mode 100644 tools/harness-bench/mcp-server.mjs create mode 100644 tools/harness-bench/mock-client.mjs create mode 100644 tools/harness-bench/proc-monitor.mjs create mode 100644 tools/harness-bench/report.mjs create mode 100644 tools/harness-bench/run.mjs create mode 100644 tools/harness-bench/scenarios/chaos-recovery.json create mode 100644 tools/harness-bench/scenarios/concurrency-fanout.json create mode 100644 tools/harness-bench/scenarios/long-compaction.json create mode 100644 tools/harness-bench/scenarios/mcp-smoke-edit.json create mode 100644 tools/harness-bench/scenarios/smoke-edit.json create mode 100644 tools/mock-ai/src/routing.rs create mode 100644 tools/mock-ai/src/scenario/mod.rs create mode 100644 tools/mock-ai/src/scenario/tools.rs diff --git a/Cargo.lock b/Cargo.lock index be7f06f6ed6..bce6cc4ff89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9806,6 +9806,7 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", + "jsonschema 0.63.1", "maka-provider-protocol", "regex", "reqwest", diff --git a/tools/harness-bench/README.md b/tools/harness-bench/README.md new file mode 100644 index 00000000000..291e44f5e78 --- /dev/null +++ b/tools/harness-bench/README.md @@ -0,0 +1,85 @@ + + +# Harness benchmark + +Run coding agents against the same deterministic, loopback mock model and check the resulting workspace, session telemetry and, on the Shared MCP track, tool audit. Use Node.js 26 and a Unix environment with `ps` available. + +## Build and run + +```sh +cargo build -p maka-mock-ai --bin maka-mock-ai +node tools/harness-bench/run.mjs preflight +node tools/harness-bench/run.mjs preflight --harnesses ref-agent,codex-http --json +node tools/harness-bench/run.mjs run --scenario smoke-edit --harnesses ref-agent --lanes 4 --runs 2 +node tools/harness-bench/run.mjs calibrate --lanes 16 +node tools/harness-bench/run.mjs matrix --harnesses ref-agent,codex-http --scenarios mcp-smoke-edit +node --test tools/harness-bench/bench.test.mjs +``` + +The runner searches `target/release` and then `target/debug` for `maka-mock-ai`. Build with `--release` for performance comparisons. Use `--mock-bin /path/to/maka-mock-ai` for a binary under a custom Cargo target directory or to pin the exact build. Preflight reports binary paths, versions, tracks and install hints. Its version probes use temporary config and working directories. + +`run` accepts a built-in scenario name or a JSON path. Each repeat runs the candidates in a rotated order with `--lanes` clients in parallel per candidate. Both `--lanes` and `--runs` default to one. Use the same scenario, lane count and profile when comparing candidates. `--latency-profile` accepts `instant` (default), `frontier` and `degraded`. `--provider-dialect` forwards the selected mock dialect, such as `standard-openai`, `deepseek-chat`, `kimi-chat`, `anthropic-messages` or `openai-responses`. + +`--timeout-ms` sets a process deadline per segment and defaults to `120000`. `--sigkill-after-ms` kills the first client process group after the given delay. Add `--resume-after-kill` to launch a second client against the same workspace, isolated config and mock session. The reference agent checkpoints completed tool batches and compaction state in this mode. Other adapters relaunch their configured CLI with its existing state and may fail to recover. A kill during a tool write can leave incomplete work. A kill during a stream can produce an `abandoned_stream` watchdog violation and a nonzero exit even when the restarted client finishes the task. + +`calibrate` uses `ref-agent` with `instant`, one batch and 16 lanes by default. Compare median mock union time, median outside-mock time, verified lanes per second and the before/after `/admin/metrics` snapshots across lane counts. Union time measures the overlap-adjusted mock service intervals during a session. Outside-mock time covers the rest of the registration-to-finalization window, including runner and client overhead. Process wall time uses the measured CLI segments. A warm daemon lives outside the CLI process tree. The calibration measures the local benchmark workload at the chosen lane count. + +`matrix` runs all five built-ins by default. Use `--scenarios a,b` to select scenarios. It writes `matrix-report.md` with links to each exercised scenario. Unsupported tracks show `N/A`. An adapter that supports the track but fails to launch or verify is a failed result. + +## Built-in scenarios + +| Scenario | Track | Workload | +| --- | --- | --- | +| `smoke-edit` | Native | Read and edit a source file, then verify the change with a parallel read and grep. | +| `concurrency-fanout` | Native | Create an artifact and verify successive state transitions, with a parallel read and shell check. Increase `--lanes` to exercise fanout. | +| `long-compaction` | Native | Generate 128 KiB of tool output, hit a context limit and adopt a checkpoint before completing the edit. | +| `chaos-recovery` | Native | Recover from HTTP 429, HTTP 503 and a mid-stream disconnect, and report errors for malformed and unknown calls. | +| `mcp-smoke-edit` | Shared MCP | Perform the smoke edit over the benchmark stdio MCP tools and reconcile their audit with the workspace and mock receipts. | + +## Adapters + +| Adapter | Model protocol | Tracks | +| --- | --- | --- | +| `ref-agent` | Chat Completions | Native, Shared MCP | +| `maka-direct` | Chat Completions | Native, Shared MCP | +| `maka-codemode` | Chat Completions | Native | +| `claude` | Anthropic Messages | Native, Shared MCP | +| `codex-ws` | Responses WebSocket | Native, Shared MCP | +| `codex-http` | Responses HTTP | Native, Shared MCP | +| `opencode-cold` | Chat Completions | Native, Shared MCP | +| `opencode-attach` | Chat Completions | Native, Shared MCP | +| `pi` | Chat Completions | Native | +| `pi-durable` | Chat Completions | Native | +| `dim` | Chat Completions | Native, Shared MCP | +| `dsh` | Chat Completions | Native, Shared MCP | +| `zcode` | Chat Completions | Native, Shared MCP | +| `kimi-openai` | Chat Completions | Native, Shared MCP | +| `kimi-responses` | Responses HTTP | Native, Shared MCP | +| `kimi-anthropic` | Anthropic Messages | Native, Shared MCP | + +Use `preflight` for installation hints and environment requirements. For either Maka adapter, use a disposable OS account or container and point `HARNESS_BENCH_MAKA_ACCOUNT_HOME` at that account's home. `MAKA_BENCH_BINARY` can select the Maka binary. + +## Isolation and artifacts + +Each run starts a strict scenario server on `127.0.0.1:0`. Each lane has a unique scoped model endpoint and test credential, its own fixture workspace and private HOME, XDG, config, cache and temp directories. The adapter supplies these settings to the client. Native tools operate with the OS permissions of the benchmark account. Use a disposable account or container when you need OS-level file or network isolation. The Shared MCP server restricts benchmark tools to each lane's workspace and structured commands. Warm Maka and OpenCode attach adapters start a daemon per lane so their workspaces and session routes stay independent. + +Use `--output` with a new or empty directory. With no flag, the runner creates a temp directory and prints its path. The output retains the fixtures and final files, per-segment process samples and log tails, mock session exports, and MCP audit logs where applicable. `manifest.json` records candidate order and options. `results.json` contains lane outcomes and mock metrics. `report.md` summarizes comparisons and failures. Timing and RSS/CPU samples cover each CLI and its live descendants. The monitor keeps up to 256 KiB each of stdout and stderr per segment and records truncation in `lane.json`. + +A successful lane has a clean CLI result, independent workspace proof and a finalized mock session with a verified final response. The runner exports telemetry before acknowledging its cursor and deleting the session. A failed lane or run error makes the command exit nonzero after writing diagnostics. diff --git a/tools/harness-bench/adapters.mjs b/tools/harness-bench/adapters.mjs new file mode 100644 index 00000000000..f12aa47caeb --- /dev/null +++ b/tools/harness-bench/adapters.mjs @@ -0,0 +1,1054 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { execFile, spawn } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { text as consumeText } from 'node:stream/consumers'; +import { constants } from 'node:fs'; +import { access, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { tmpdir, userInfo } from 'node:os'; +import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path'; +import { createInterface } from 'node:readline'; +import { setTimeout as delay } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { parseBenchmarkCommand, replaceUnique, resolveWorkspaceFile } from './fixtures.mjs'; + +const exec = promisify(execFile); +const script = fileURLToPath(import.meta.url); +const defaultRepoRoot = resolve(dirname(script), '../..'); +const chat = 'openai-chat-completions'; +const anthropic = 'anthropic-messages'; +const responses = 'openai-responses-http'; +const websockets = 'openai-responses-ws'; +const native = Object.freeze(['native']); +const both = Object.freeze(['native', 'sharedMcp']); +const makaIsolation = 'Maka requires a disposable OS account or container. Set HARNESS_BENCH_MAKA_ACCOUNT_HOME to that account home.'; +const toml = value => JSON.stringify(value); + +async function privateFile(path, content, { exclusive = false } = {}) { + await mkdir(dirname(path), { recursive: true, mode: 0o700 }); + const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_NOFOLLOW + | (exclusive ? constants.O_EXCL : constants.O_TRUNC); + const file = await open(path, flags, 0o600); + try { + await file.chmod(0o600); + await file.writeFile(content, 'utf8'); + } finally { + await file.close(); + } +} + +function jsonFile(path, value) { + return privateFile(path, JSON.stringify(value, null, 2) + '\n'); +} + +async function isolatedEnv(directory, source) { + const dirs = Object.fromEntries([ + ['HOME', 'home'], ['XDG_CONFIG_HOME', 'config'], ['XDG_DATA_HOME', 'data'], + ['XDG_CACHE_HOME', 'cache'], ['XDG_STATE_HOME', 'state'], ['XDG_RUNTIME_DIR', 'runtime'], + ['TMPDIR', 'tmp'], ['APPDATA', 'app-data'], ['LOCALAPPDATA', 'local-app-data'], + ].map(([name, leaf]) => [name, join(directory, leaf)])); + await Promise.all(Object.values(dirs).map(dir => mkdir(dir, { recursive: true, mode: 0o700 }))); + const path = (source.PATH ?? source.Path ?? '/usr/bin:/bin').split(delimiter) + .filter(isAbsolute).join(delimiter); + return { + ...dirs, PATH: path, USERPROFILE: dirs.HOME, TMP: dirs.TMPDIR, TEMP: dirs.TMPDIR, + LC_ALL: 'C', TERM: 'dumb', CI: '1', NO_COLOR: '1', + GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: join(dirs.HOME, '.gitconfig'), + ...(process.platform === 'win32' ? { SystemRoot: source.SystemRoot, ComSpec: source.ComSpec } : {}), + }; +} + +async function findBinary(name, env, repoRoot) { + const suffixes = process.platform === 'win32' ? ['.exe'] : ['']; + const explicit = name === 'maka' ? env.MAKA_BENCH_BINARY : undefined; + const cargoTarget = resolve(repoRoot, env.CARGO_TARGET_DIR ?? 'target'); + const searchDirs = (env.PATH ?? env.Path ?? '').split(delimiter).filter(isAbsolute); + const dirs = name === 'maka' ? [join(cargoTarget, 'release'), ...searchDirs] : searchDirs; + const candidates = explicit ? [resolve(explicit)] + : dirs.flatMap(dir => suffixes.map(suffix => join(dir, name + suffix))); + for (const file of candidates) { + try { + await access(file, constants.X_OK); + if ((await stat(file)).isFile()) return file; + } catch (error) { + if (!['ENOENT', 'ENOTDIR', 'EACCES'].includes(error.code)) throw error; + } + } + return undefined; +} + +function scopedUrl(origin, run, session) { + const url = new URL(origin); + if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) + || !['http:', 'https:'].includes(url.protocol) || url.href !== url.origin + '/') { + throw new Error('scopedOrigin must be a bare loopback HTTP(S) origin'); + } + const path = '/s/' + run + '/' + session; + if ([run, session].some(id => typeof id !== 'string' || !id || /[/?#\\]/.test(id)) + || new URL(path, url).pathname !== path) { + throw new Error('Expected raw mock-ai run and session path IDs'); + } + return url.origin + path; +} + +function mcpServer({ mcpServerCmd, mcpAuditPath, workspace, resumeAfterKill }) { + if (!mcpAuditPath) throw new Error('sharedMcp requires mcpAuditPath'); + let command; + let args; + if (mcpServerCmd === undefined) { + command = process.execPath; + args = [join(dirname(script), 'mcp-server.mjs')]; + } else if (Array.isArray(mcpServerCmd)) { + [command, ...args] = mcpServerCmd; + } else if (typeof mcpServerCmd === 'string') { + command = mcpServerCmd.endsWith('.mjs') ? process.execPath : mcpServerCmd; + args = mcpServerCmd.endsWith('.mjs') ? [mcpServerCmd] : []; + } else { + ({ command, args = [] } = mcpServerCmd); + } + if (!command || !Array.isArray(args)) throw new Error('Invalid MCP server command'); + return { + command, + args: [...args, '--workspace', workspace, '--audit-log', resolve(mcpAuditPath), + ...(resumeAfterKill ? ['--resume-audit'] : [])], + }; +} + +function adapter({ id, harness = id, binary = harness, protocol = chat, supportedTracks = native, + defaultModel = 'gpt-4.1', installHint, versionArgs = ['--version'], prepare, start, locate, version }) { + const commandPath = locate ?? ((env, repoRoot) => findBinary(binary, env, repoRoot)); + const launchMode = start ? 'warm-daemon' : 'cold'; + const requireCommand = async (env, repoRoot) => { + const command = await commandPath(env, repoRoot); + if (!command) throw new Error(`${id}: could not locate ${binary}. ${installHint}`); + return command; + }; + async function context(options) { + const { track, env: source = process.env } = options; + if (!supportedTracks.includes(track)) { + throw new Error(`${id} does not support track ${JSON.stringify(track)}`); + } + if (!options.apiKey) throw new Error(`${id} requires a mock API key`); + const model = options.model ?? defaultModel; + if (typeof model !== 'string' || !model.trim()) throw new Error(`${id} requires a model ID`); + const repoRoot = resolve(options.repoRoot ?? defaultRepoRoot); + const base = scopedUrl(options.scopedOrigin, options.runId, options.sessionId); + const isolatedDir = resolve(options.isolatedDir); + const workspace = await realpath(options.workspace); + const command = await requireCommand(source, repoRoot); + if (harness === 'maka' && source.HARNESS_BENCH_MAKA_ACCOUNT_HOME !== userInfo().homedir) { + throw new Error(makaIsolation); + } + const env = await isolatedEnv(isolatedDir, source); + const mcp = track === 'sharedMcp' ? mcpServer({ ...options, workspace }) : undefined; + return { ...options, model, base, v1: base + '/v1', isolatedDir, workspace, repoRoot, source, command, env, mcp }; + } + return Object.freeze({ + id, harness, protocol, launchMode, supportedTracks, defaultModel, + async probe({ env = process.env, repoRoot = defaultRepoRoot } = {}) { + const result = { id, available: false, installHint }; + let scratch; + try { + const binaryPath = await requireCommand(env, repoRoot); + result.binaryPath = binaryPath; + if (harness === 'maka' && env.HARNESS_BENCH_MAKA_ACCOUNT_HOME !== userInfo().homedir) { + return { ...result, reason: makaIsolation }; + } + scratch = await mkdtemp(join(tmpdir(), 'harness-probe-')); + const invocation = { cwd: scratch, env: await isolatedEnv(scratch, env), timeout: 8_000 }; + const detected = version ? await version(env, repoRoot, invocation) + : (({ stdout, stderr }) => (stdout || stderr).trim())( + await exec(binaryPath, versionArgs, invocation)); + if (!detected) return { ...result, reason: 'Version command returned an empty version' }; + return { ...result, available: true, version: detected }; + } catch (error) { + return { ...result, reason: error.message }; + } finally { + if (scratch) await rm(scratch, { recursive: true, force: true }); + } + }, + async prepareInvocation(options) { + const ctx = await context(options); + return { command: ctx.command, cwd: ctx.workspace, env: ctx.env, ...await prepare(ctx) }; + }, + ...(start ? { + async startDaemon(options) { + return start(await context(options)); + }, + stopDaemon, + } : {}), + }); +} + +function startChild(command, args, { env, workspace }, ready) { + const child = spawn(command, args, { + env, cwd: workspace, detached: process.platform !== 'win32', + stdio: ['ignore', 'pipe', 'pipe'], + }); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', chunk => { stderr = (stderr + chunk).slice(-8192); }); + const state = { child, exited: new Promise(resolveExit => { + child.once('error', error => resolveExit({ error })); + child.once('exit', (code, signal) => resolveExit({ code, signal })); + }) }; + const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); + const timeout = AbortSignal.timeout(30_000); + const started = new Promise((resolveReady, reject) => { + timeout.addEventListener('abort', () => reject(new Error('Daemon readiness timed out')), { once: true }); + lines.on('line', line => { + const value = ready(line); + if (value) resolveReady(value); + }); + }); + return Promise.race([started, state.exited.then(({ error, code, signal }) => { + throw error ?? new Error(`Daemon exited before ready (${signal ?? code}): ${stderr}`); + })]).then(value => ({ ...state, value }), async error => { + await stopDaemon(state); + throw error; + }); +} + +async function stopDaemon({ child, exited }) { + if (child.pid && child.exitCode === null && child.signalCode === null) { + const target = process.platform === 'win32' ? child.pid : -child.pid; + const sending = signal => { + try { + process.kill(target, signal); + } catch (error) { + if (error.code !== 'ESRCH') throw error; + } + }; + sending('SIGTERM'); + if (!await Promise.race([exited.then(() => true), delay(3000, false, { ref: false })])) { + sending('SIGKILL'); + } + } + await exited; +} + +async function runSetup(ctx, args, stdinText) { + if (stdinText === undefined) { + await exec(ctx.command, args, { env: ctx.env, cwd: ctx.workspace, timeout: 30_000 }); + return; + } + await new Promise((resolveRun, reject) => { + const child = execFile(ctx.command, args, { + env: ctx.env, cwd: ctx.workspace, timeout: 30_000, + }, error => error ? reject(error) : resolveRun()); + child.stdin.on('error', reject); + child.stdin.end(stdinText); + }); +} + +function makaAdapter(id, codeMode) { + const rootPath = ctx => join(ctx.isolatedDir, 'maka-root'); + return adapter({ + id, harness: 'maka', supportedTracks: codeMode ? native : both, + installHint: 'cargo build --release -p maka-cli', + async start(ctx) { + const root = rootPath(ctx); + if (ctx.mcp) await jsonFile(join(ctx.env.HOME, '.maka/mcp.json'), { + mcpServers: { bench: { ...ctx.mcp, cwd: ctx.workspace } }, + }); + await runSetup(ctx, ['host', 'init', '--root', root, '--settings-stdin'], JSON.stringify({ + connections: [{ + slug: 'benchmark', provider: 'openai-compatible', + configuration: { baseUrl: ctx.v1 }, apiKey: ctx.apiKey, enabledModelIds: [ctx.model], + modelOverrides: { + [ctx.model]: { codeMode, apiProtocol: chat, ...(codeMode ? { codeModeLanguage: 'javascript' } : {}) }, + }, + }], + defaultTarget: { slug: 'benchmark', modelId: ctx.model }, + projectDirectoryRoots: [{ label: 'Benchmark workspace', path: ctx.workspace }], + })); + return startChild(ctx.command, ['host', 'serve', '--root', root], ctx, + line => line.startsWith('{"kind":"ready",') && root); + }, + prepare(ctx) { + const root = rootPath(ctx); + if (ctx.daemonState?.value !== root) throw new Error(`${id} requires its isolated Host`); + return { args: ['run', '--root', root, '--workspace', ctx.workspace], stdinText: ctx.prompt }; + }, + }); +} + +const claude = adapter({ + id: 'claude', protocol: anthropic, supportedTracks: both, + installHint: 'Install Claude Code (claude on PATH).', + async prepare(ctx) { + const home = join(ctx.isolatedDir, 'claude'); + await mkdir(home, { recursive: true, mode: 0o700 }); + Object.assign(ctx.env, { + CLAUDE_CONFIG_DIR: home, ANTHROPIC_BASE_URL: ctx.base, ANTHROPIC_AUTH_TOKEN: ctx.apiKey, + DISABLE_TELEMETRY: '1', CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', + }); + const args = ['-p', ctx.prompt, '--dangerously-skip-permissions', '--output-format', 'stream-json', + '--verbose', '--no-session-persistence', '--model', ctx.model]; + if (ctx.mcp) { + const path = join(home, 'mcp-config.json'); + await jsonFile(path, { mcpServers: { bench: { type: 'stdio', ...ctx.mcp } } }); + args.push('--mcp-config', path, '--strict-mcp-config'); + } + return { args }; + }, +}); + +function codexAdapter(ws) { + return adapter({ + id: ws ? 'codex-ws' : 'codex-http', harness: 'codex', protocol: ws ? websockets : responses, + supportedTracks: both, + defaultModel: 'gpt-5.5', + installHint: 'npm install -g @openai/codex. Use a model with apply_patch.', + async prepare(ctx) { + ctx.env.CODEX_HOME = join(ctx.isolatedDir, 'codex'); + ctx.env.OPENAI_API_KEY = ctx.apiKey; + const lines = [ + `model = ${toml(ctx.model)}`, 'model_provider = "mock"', 'check_for_update_on_startup = false', + '[model_providers.mock]', 'name = "Benchmark mock"', 'wire_api = "responses"', + `base_url = ${toml(ctx.v1)}`, 'env_key = "OPENAI_API_KEY"', 'requires_openai_auth = false', + `supports_websockets = ${ws}`, 'request_max_retries = 4', 'stream_max_retries = 4', + '[features]', 'plugins = false', + ]; + if (ctx.mcp) lines.push( + '[mcp_servers.bench]', `command = ${toml(ctx.mcp.command)}`, + `args = ${toml(ctx.mcp.args)}`, 'required = true', + // The scenario binds the tool schemas Codex sends in the Responses request. + 'omit_tools_from = ["deferred"]', + ); + await privateFile(join(ctx.env.CODEX_HOME, 'config.toml'), lines.join('\n') + '\n'); + return { args: ['exec', '--dangerously-bypass-approvals-and-sandbox', '--skip-git-repo-check', '--json', '-'], + stdinText: ctx.prompt }; + }, + }); +} + +async function configureOpencode(ctx) { + const config = join(ctx.isolatedDir, 'opencode.json'); + Object.assign(ctx.env, { + OPENCODE_CONFIG: config, OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_MODELS_FETCH: '1', + OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENAI_API_KEY: ctx.apiKey, + }); + await jsonFile(config, { + model: `mock/${ctx.model}`, + providers: { mock: { + name: 'Benchmark mock', package: '@opencode/ai/providers/openai-compatible', + settings: { baseURL: ctx.v1, apiKey: '{env:OPENAI_API_KEY}' }, + models: { [ctx.model]: { name: ctx.model } }, + } }, + permissions: [{ action: '*', resource: '*', effect: 'allow' }], + ...(ctx.mcp ? { mcp: { servers: { bench: { + type: 'local', codemode: false, command: [ctx.mcp.command, ...ctx.mcp.args], + } } } } : {}), + }); +} + +function opencodeAdapter(attach) { + return adapter({ + id: attach ? 'opencode-attach' : 'opencode-cold', harness: 'opencode', supportedTracks: both, + installHint: 'Install OpenCode v2 (opencode on PATH).', + ...(attach ? { + async start(ctx) { + await configureOpencode(ctx); + const password = randomBytes(24).toString('hex'); + ctx.env.OPENCODE_PASSWORD = password; + const state = await startChild(ctx.command, ['serve', '--hostname', '127.0.0.1', '--port', '0'], ctx, + line => /https?:\/\/127\.0\.0\.1:[1-9][0-9]*/.exec(line)?.[0]); + return { ...state, isolatedDir: ctx.isolatedDir, password }; + }, + } : {}), + async prepare(ctx) { + let server = ['--standalone']; + if (attach) { + if (ctx.daemonState?.isolatedDir !== ctx.isolatedDir) { + throw new Error('opencode-attach requires its isolated daemon'); + } + ctx.env.OPENCODE_PASSWORD = ctx.daemonState.password; + server = ['--server', ctx.daemonState.value]; + } else { + await configureOpencode(ctx); + } + return { args: ['run', ...server, '--model', `mock/${ctx.model}`, '--format', 'json', '--', ctx.prompt] }; + }, + }); +} + +const pi = adapter({ + id: 'pi', installHint: 'Install pi (pi on PATH).', + async prepare(ctx) { + ctx.env.PI_CODING_AGENT_DIR = join(ctx.isolatedDir, 'pi'); + ctx.env.OPENAI_API_KEY = ctx.apiKey; + const home = ctx.env.PI_CODING_AGENT_DIR; + await Promise.all([ + jsonFile(join(home, 'models.json'), { providers: { mock: { + baseUrl: ctx.v1, api: 'openai-completions', apiKey: '$OPENAI_API_KEY', + models: [{ id: ctx.model, name: ctx.model }], + } } }), + jsonFile(join(home, 'settings.json'), { defaultProvider: 'mock', defaultModel: ctx.model }), + ]); + return { args: ['-p', '--mode', 'json', '--no-session', '--', ctx.prompt] }; + }, +}); + +const durablePackages = ['@earendil-works/pi-durable', '@earendil-works/pi-ai', '@earendil-works/chord']; +const durableImports = { + Harness: '@earendil-works/pi-durable', + sqlite: '@earendil-works/pi-durable/storage/sqlite/node', + tools: '@earendil-works/pi-durable/tools', + environment: '@earendil-works/pi-durable/env/node', + ai: '@earendil-works/pi-ai', + completions: '@earendil-works/pi-ai/api/openai-completions.lazy', + context: '@earendil-works/chord/context', +}; + +async function durableEntries(env, repoRoot, invocation) { + const directory = resolve(env.HARNESS_BENCH_PI_DURABLE_DIR ?? repoRoot); + const imports = JSON.stringify(durableImports); + const expression = `console.log(JSON.stringify(Object.fromEntries( + Object.entries(${imports}).map(([name, specifier]) => [name, import.meta.resolve(specifier)]))))`; + const { stdout } = await exec(process.execPath, ['--input-type=module', '--eval', expression], { + ...invocation, cwd: directory, + }); + return JSON.parse(stdout); +} + +const piDurable = adapter({ + id: 'pi-durable', locate: () => process.execPath, + installHint: `Install ${durablePackages.join(' ')} in a directory and set HARNESS_BENCH_PI_DURABLE_DIR to it.`, + async version(env, repoRoot, invocation) { + const entries = await durableEntries(env, repoRoot, invocation); + const path = join(dirname(fileURLToPath(entries.Harness)), '../package.json'); + return JSON.parse(await readFile(path, 'utf8')).version; + }, + async prepare(ctx) { + const entries = await durableEntries(ctx.source, ctx.repoRoot, { + env: ctx.env, timeout: 8_000, + }); + const path = join(ctx.isolatedDir, 'pi-durable-driver.mjs'); + ctx.env.OPENAI_API_KEY = ctx.apiKey; + const { model, v1, sessionId, workspace, isolatedDir } = ctx; + await privateFile(path, `import { readFileSync } from 'node:fs'; +import { Harness, AssistantEntry, createRegistry } from ${toml(entries.Harness)}; +import { openNodeSqliteStorage } from ${toml(entries.sqlite)}; +import { createCodingTools } from ${toml(entries.tools)}; +import { NodeExecutionEnv } from ${toml(entries.environment)}; +import { createModels, createProvider, envApiKeyAuth } from ${toml(entries.ai)}; +import { openAICompletionsApi } from ${toml(entries.completions)}; +import { BACKGROUND_CONTEXT as context } from ${toml(entries.context)}; + +const modelId = ${toml(model)}; +const baseUrl = ${toml(v1)}; +const models = createModels(); +models.setProvider(createProvider({ + id: 'mock', name: 'Benchmark mock', baseUrl, + auth: { apiKey: envApiKeyAuth('Benchmark mock', ['OPENAI_API_KEY']) }, + api: openAICompletionsApi(), + models: [{ + id: modelId, name: modelId, api: 'openai-completions', provider: 'mock', baseUrl, + reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, maxTokens: 8192, + }], +})); +const registry = createRegistry(); +registry.install(createCodingTools()); +const cwd = ${toml(workspace)}; +const harness = await Harness.open(await openNodeSqliteStorage(${toml(join(isolatedDir, 'pi-durable.sqlite'))}), { + models, registry, env: () => new NodeExecutionEnv({ cwd }), +}, context); +try { + const root = await harness.root(context, { agent: { model: { provider: 'mock', modelId }, cwd } }); + const submission = await root.submit({ + type: 'input', content: readFileSync(0, 'utf8'), requestId: ${toml(sessionId)}, + }, context); + harness.resume(); + const settled = await submission.wait(context); + if (settled.status !== 'done' || settled.type !== 'input') { + throw new Error('pi-durable did not produce an answer: ' + JSON.stringify(settled)); + } + const answer = await root.commit(tx => tx.entry(AssistantEntry, settled.answer), context); + const text = answer?.model?.flatMap(message => message.content ?? []) + .filter(block => block.type === 'text').map(block => block.text).join(''); + if (!text) throw new Error('pi-durable returned an empty answer'); + console.log(text); +} finally { + await harness.close(context); +} +`); + return { args: [path], stdinText: ctx.prompt }; + }, +}); + +const dim = adapter({ + id: 'dim', binary: 'dimcode', supportedTracks: both, versionArgs: ['version'], + installHint: 'npm install -g dimcode', + async prepare(ctx) { + const path = join(ctx.isolatedDir, 'model.json'); + await jsonFile(path, { adapter: 'openai', baseUrl: ctx.v1, model: ctx.model }); + // Released Dim resolves custom providers from its SQLite catalog. + await runSetup(ctx, ['provider', 'add', 'bench-mock', '--adapter', 'openai', + '--base-url', ctx.v1, '--api-key', ctx.apiKey, '--model', ctx.model]); + await runSetup(ctx, ['provider', 'switch', 'bench-mock', '--model', ctx.model]); + if (ctx.mcp) await runSetup(ctx, ['mcp', 'add-json', 'bench', JSON.stringify(ctx.mcp)]); + return { args: ['exec', '--model-config', path], stdinText: ctx.prompt }; + }, +}); + +const dsh = adapter({ + id: 'dsh', supportedTracks: both, installHint: 'npm install -g @deepseek-ai/dsh', + async prepare(ctx) { + ctx.env.DSH_HOME = join(ctx.isolatedDir, 'dsh'); + ctx.env.OPENAI_API_KEY = ctx.apiKey; + // JSON is a YAML subset and preserves paths and prompts without custom quoting. + const patches = [{ + id: 'llm-pi-ai', config: { providers: { mock: { + api: 'openai-completions', baseURL: ctx.v1, apiKeyEnv: 'OPENAI_API_KEY', + models: [{ id: ctx.model }], + } } }, + }, { + id: 'agent-default-model', config: { provider: 'mock', model: ctx.model }, + }]; + if (ctx.mcp) patches.push({ insert: [{ + id: 'bench-mcp', name: '@deepseek-ai/dsh-mcp-client', config: { + transport: 'stdio', serverName: 'bench', ...ctx.mcp, cwd: ctx.workspace, failOnStartupError: true, + }, + }] }); + await jsonFile(join(ctx.env.DSH_HOME, 'cordis.patch.yml'), patches); + return { args: ['--profile', 'headless', '--', ctx.prompt] }; + }, +}); + +const zcode = adapter({ + id: 'zcode', supportedTracks: both, installHint: 'Install the ZCode CLI (zcode on PATH).', + async prepare(ctx) { + const home = join(ctx.env.HOME, '.zcode', 'v2'); + const secret = join(home, 'credential-secret'); + await privateFile(secret, randomBytes(32).toString('hex'), { exclusive: true }); + Object.assign(ctx.env, { + ZCODE_DATA_BASE_DIR: ctx.env.HOME, ZCODE_CREDENTIAL_SECRET_FILE: secret, OPENAI_API_KEY: ctx.apiKey, + }); + await jsonFile(join(home, 'config.json'), { + model: { + main: { kind: 'openai-compatible', provider: 'mock', model: ctx.model, baseURL: ctx.v1, apiKey: ctx.apiKey }, + }, + }); + const selection = { providerId: 'mock', modelId: ctx.model }; + await jsonFile(join(home, 'provider_config.json'), { + schemaVersion: 1, + config: { + providerConfigRules: { providerRules: [{ + providerId: 'mock', providerName: 'Benchmark mock', enabled: true, + config: { + group: 'standard-personal', api: { type: chat, baseUrl: ctx.v1 }, + access: { type: 'api-key', apiKey: ctx.apiKey }, personalModelIds: [ctx.model], + }, + }] }, + modelConfigRules: { + providerModelRules: [{ ...selection, config: { enabled: true, properties: { contextWindow: 128000 } } }], + manualProviderModelRules: [], + }, + defaultModelSelection: selection, + }, + }); + if (ctx.mcp) await jsonFile(join(ctx.env.HOME, '.zcode/cli/config.json'), { + mcp: { servers: { bench: { type: 'stdio', ...ctx.mcp, cwd: ctx.workspace } } }, + }); + return { args: ['-p', ctx.prompt] }; + }, +}); + +function kimiAdapter(id, protocol, type) { + return adapter({ + id, harness: 'kimi', protocol, supportedTracks: both, + installHint: 'npm install -g @moonshot-ai/kimi-code', + async prepare(ctx) { + const home = join(ctx.isolatedDir, 'kimi'); + ctx.env.KIMI_CODE_HOME = home; + const path = join(home, 'config.toml'); + await privateFile(path, [ + 'default_model = "mock"', 'telemetry = false', '[providers.mock]', `type = ${toml(type)}`, + `base_url = ${toml(type === 'anthropic' ? ctx.base : ctx.v1)}`, + `api_key = ${toml(ctx.apiKey)}`, '[models.mock]', 'provider = "mock"', + `model = ${toml(ctx.model)}`, 'max_context_size = 128000', '', + ].join('\n')); + if (ctx.mcp) await jsonFile(join(home, 'mcp.json'), { + mcpServers: { bench: { transport: 'stdio', ...ctx.mcp, deferred: false } }, + }); + return { args: ['-p', ctx.prompt] }; + }, + }); +} + +const refAgent = adapter({ + id: 'ref-agent', supportedTracks: both, locate: () => process.execPath, + installHint: 'Built in. Uses Node.js 26.', + prepare(ctx) { + const protocol = ctx.protocol ?? chat; + if (![chat, anthropic].includes(protocol)) throw new Error(`ref-agent does not support ${protocol}`); + ctx.env.HARNESS_BENCH_REF_KEY = ctx.apiKey; + return { + args: [script, '--ref-agent'], + stdinText: JSON.stringify({ + endpoint: ctx.v1 + (protocol === anthropic ? '/messages' : '/chat/completions'), + protocol, model: ctx.model, prompt: ctx.prompt, mcp: ctx.mcp, stream: ctx.stream, + checkpoint: ctx.resumeAfterKill ? join(ctx.isolatedDir, 'ref-checkpoint.json') : undefined, + }), + }; + }, +}); + +const adapters = [ + refAgent, makaAdapter('maka-direct', false), makaAdapter('maka-codemode', true), claude, + codexAdapter(true), codexAdapter(false), opencodeAdapter(false), opencodeAdapter(true), + pi, piDurable, dim, dsh, zcode, + kimiAdapter('kimi-openai', chat, 'openai'), + kimiAdapter('kimi-responses', responses, 'openai_responses'), + kimiAdapter('kimi-anthropic', anthropic, 'anthropic'), +]; + +export function getAdapter(id) { + const adapter = adapters.find(adapter => adapter.id === id); + if (!adapter) throw new Error(`Unknown benchmark adapter ${JSON.stringify(id)}`); + return adapter; +} + +export function listAdapters() { + return [...adapters]; +} + +export async function probeAllAdapters({ env, repoRoot, filter } = {}) { + let selected = adapters; + if (typeof filter === 'function') { + selected = adapters.filter(filter); + } else if (filter !== undefined) { + const ids = typeof filter === 'string' ? filter.split(',') : [...filter]; + selected = ids.map(getAdapter); + } + return Promise.all(selected.map(adapter => adapter.probe({ env, repoRoot }))); +} + +const referenceTools = [ + ['Read', 'Read a workspace file.', ['path']], + ['Write', 'Write a workspace file.', ['path', 'content']], + ['Edit', 'Replace exactly one match in a workspace file.', ['path', 'old_string', 'new_string']], + ['Bash', 'Run a fixture grep or printf command.', ['command']], +].map(([name, description, required]) => ({ + name, description, + inputSchema: { + type: 'object', required, additionalProperties: false, + properties: Object.fromEntries(required.map(key => [key, { type: 'string' }])), + }, +})); + +async function referenceNative(workspace, name, args) { + if (name === 'Bash') { + // scenario::large_output_command quotes fixture data and inserts three decimal loop bounds. + const large = /^BENCH_PATTERN='((?:[^']|'\\'')*)' BENCH_TAIL='((?:[^']|'\\'')*)' LC_ALL=C awk 'BEGIN \{ p = ENVIRON\["BENCH_PATTERN"\]; for \(i = 0; i < (\d+); i\+\+\) block = block p; for \(i = 0; i < (\d+); i\+\+\) printf "%s", block; for \(i = 0; i < (\d+); i\+\+\) printf "%s", p; printf "%s", ENVIRON\["BENCH_TAIL"\] \}'$/.exec(args.command); + if (large?.[0] === args.command) { + const [, pattern, tail, perBlock, blocks, repetitions] = large; + const { stdout } = await exec('/usr/bin/awk', [ + '-v', 'perBlock=' + perBlock, '-v', 'blocks=' + blocks, '-v', 'repetitions=' + repetitions, + 'BEGIN { p = ENVIRON["BENCH_PATTERN"]; for (i = 0; i < perBlock; i++) block = block p; for (i = 0; i < blocks; i++) printf "%s", block; for (i = 0; i < repetitions; i++) printf "%s", p; printf "%s", ENVIRON["BENCH_TAIL"] }', + ], { + cwd: workspace, timeout: 10_000, maxBuffer: 16 * 1024 * 1024, + env: { + LC_ALL: 'C', BENCH_PATTERN: pattern.replaceAll("'\\''", "'"), BENCH_TAIL: tail.replaceAll("'\\''", "'"), + }, + }); + return { text: stdout }; + } + const parsed = parseBenchmarkCommand(args.command); + const argv = parsed.kind === 'grep' + ? ['exec grep -Fx -- "$1" "$2"', parsed.marker, await resolveWorkspaceFile(workspace, parsed.path)] + : ['printf "%s" "$1"', parsed.text]; + const [source, ...operands] = argv; + const { stdout, stderr } = await exec('/bin/sh', ['-c', source, 'bench', ...operands], { + cwd: workspace, env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, timeout: 10_000, + }); + return { text: stdout + stderr }; + } + const path = await resolveWorkspaceFile(workspace, args.path, { create: name === 'Write' }); + if (name === 'Write') { + await writeFile(path, args.content, { + flag: constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, + }); + } else { + const content = await readFile(path, { encoding: 'utf8', flag: constants.O_RDONLY | constants.O_NOFOLLOW }); + if (name === 'Read') return { text: content }; + await writeFile(path, replaceUnique(content, args.old_string, args.new_string), { + flag: constants.O_WRONLY | constants.O_TRUNC | constants.O_NOFOLLOW, + }); + } + return { text: 'OK' }; +} + +async function connectReferenceMcp(mcp, workspace) { + const child = spawn(mcp.command, mcp.args, { + cwd: workspace, env: process.env, stdio: ['pipe', 'pipe', 'inherit'], + }); + const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); + const pending = new Map(); + let nextId = 0; + let failure; + function fail(error) { + failure ??= error; + for (const request of pending.values()) request.reject(failure); + pending.clear(); + child.kill(); + } + child.once('error', fail); + child.stdin.on('error', fail); + const closed = new Promise(resolveClose => { + child.once('close', (code, signal) => { + if (code !== 0 || pending.size) fail(new Error(`MCP server closed (${signal ?? code})`)); + resolveClose({ code, signal }); + }); + }); + lines.on('line', line => { + try { + const response = JSON.parse(line); + const request = pending.get(response.id); + if (!request) throw new Error(`Unexpected MCP response ID ${response.id}`); + pending.delete(response.id); + if (response.error) request.reject(new Error(response.error.message)); + else request.resolve(response.result); + } catch (error) { + fail(error); + } + }); + function request(method, params) { + if (failure) throw failure; + const id = ++nextId; + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n'); + }); + } + try { + await request('initialize', { + protocolVersion: '2024-11-05', clientInfo: { name: 'ref-agent', version: '1.0.0' }, + capabilities: {}, + }); + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); + const { tools } = await request('tools/list'); + return { + tools, + async call(name, args) { + const reply = await request('tools/call', { name, arguments: args }); + return { text: reply.content.map(block => block.text).join('\n'), isError: reply.isError }; + }, + async close() { + child.stdin.end(); + const result = await closed; + if (failure) throw failure; + if (result.code !== 0) throw new Error(`MCP server failed to close: ${result.signal ?? result.code}`); + }, + }; + } catch (error) { + fail(error); + await closed; + throw error; + } +} + +class RefRequestError extends Error { + constructor(message, { status, provider, retryAfter, cause, disconnected } = {}) { + super(message, { cause }); + this.status = status; + this.provider = provider; + this.retryAfter = retryAfter; + this.disconnected = disconnected; + } + + get overflow() { + return this.provider?.code === 'context_length_exceeded' + || (this.provider?.type === 'invalid_request_error' && /prompt is too long/i.test(this.provider.message)); + } + + get retryable() { + return this.disconnected || this.status === 429 || this.status === 503 + || ['rate_limit_error', 'overloaded_error'].includes(this.provider?.type); + } +} + +async function* sseData(body) { + const decoder = new TextDecoder(); + const reader = body.getReader(); + let buffer = ''; + let data = []; + try { + for (;;) { + let chunk; + try { + chunk = await reader.read(); + } catch (cause) { + throw new RefRequestError('Model stream disconnected', { disconnected: true, cause }); + } + if (chunk.done) break; + buffer += decoder.decode(chunk.value, { stream: true }); + let end; + while ((end = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, end).replace(/\r$/, ''); + buffer = buffer.slice(end + 1); + if (line.startsWith('data:')) { + data.push(line.slice(5).replace(/^ /, '')); + } else if (!line && data.length) { + const event = data.join('\n'); + data = []; + yield event; + } + } + } + } finally { + if (reader.closed) await reader.cancel().catch(error => { + if (!(error instanceof TypeError)) throw error; + }); + reader.releaseLock(); + } +} + +function responseError(error) { + return new RefRequestError(error?.message ?? 'Model returned a stream error', { provider: error }); +} + +async function decodeRefStream(response, isAnthropic) { + const blocks = new Map(); + const calls = new Map(); + let content = ''; + let complete = false; + for await (const data of sseData(response.body)) { + if (data === '[DONE]') { + if (isAnthropic) throw new Error('Unexpected OpenAI stream terminator'); + complete = true; + break; + } + const event = JSON.parse(data); + if (event.error || event.type === 'error') throw responseError(event.error); + if (isAnthropic) { + if (event.type === 'message_stop') { + complete = true; + break; + } + if (event.type === 'content_block_start') { + blocks.set(event.index, { ...event.content_block }); + } + if (event.type === 'content_block_delta') { + const block = blocks.get(event.index); + const delta = event.delta; + if (delta.type === 'text_delta') block.text += delta.text; + if (delta.type === 'input_json_delta') block.partial = (block.partial ?? '') + delta.partial_json; + if (delta.type === 'compaction_delta') block.content = (block.content ?? '') + delta.content; + } + } else { + const delta = event.choices?.[0]?.delta; + content += delta?.content ?? ''; + for (const piece of delta?.tool_calls ?? []) { + if (!calls.has(piece.index)) calls.set(piece.index, { + type: 'function', id: '', function: { name: '', arguments: '' }, + }); + const call = calls.get(piece.index); + call.id += piece.id ?? ''; + call.function.name += piece.function?.name ?? ''; + call.function.arguments += piece.function?.arguments ?? ''; + } + } + } + if (!complete) throw new RefRequestError('Model stream ended before its terminal event', { disconnected: true }); + if (!isAnthropic) { + return { role: 'assistant', content, ...(calls.size ? { tool_calls: [...calls.values()] } : {}) }; + } + return { role: 'assistant', content: [...blocks.values()].map(({ partial, ...block }) => { + if (partial === undefined) return block; + try { + return { ...block, input: JSON.parse(partial) }; + } catch { + return { ...block, input: partial }; + } + }) }; +} + +async function refRequest(config, messages, tools, summary = false) { + const isAnthropic = config.protocol === anthropic; + const headers = { + 'content-type': 'application/json', + ...(isAnthropic + ? { 'x-api-key': config.key, 'anthropic-version': '2023-06-01' } + : { authorization: 'Bearer ' + config.key }), + ...(summary ? { 'x-maka-bench-request-use': 'client_summary' } : {}), + }; + const body = JSON.stringify({ + model: config.model, stream: config.stream !== false, messages, + ...(isAnthropic ? { max_tokens: 8192 } : {}), + ...(tools.length ? { tools: tools.map(({ name, description, inputSchema }) => isAnthropic + ? { name, description, input_schema: inputSchema } + : { type: 'function', function: { name, description, parameters: inputSchema } }) } : {}), + }); + for (let attempt = 0; ; attempt++) { + try { + let response; + try { + response = await fetch(config.endpoint, { + method: 'POST', headers, body, redirect: 'manual', signal: AbortSignal.timeout(120_000), + }); + } catch (cause) { + throw new RefRequestError('Model connection failed', { disconnected: true, cause }); + } + if (!response.ok) { + const raw = await response.text(); + let provider; + if (response.headers.get('content-type')?.includes('json')) provider = JSON.parse(raw).error; + throw new RefRequestError(provider?.message ?? raw, { + status: response.status, provider, retryAfter: response.headers.get('retry-after'), + }); + } + if (response.headers.get('content-type')?.includes('text/event-stream')) { + return await decodeRefStream(response, isAnthropic); + } + const data = await response.json(); + if (data.error) throw responseError(data.error); + if (isAnthropic) return { role: 'assistant', content: data.content }; + const message = data.choices?.[0]?.message; + if (!message) throw new Error('Model JSON response has no assistant message'); + return message; + } catch (error) { + if (!error.retryable || attempt >= 4) throw error; + const seconds = Number(error.retryAfter); + const retryAfter = !error.retryAfter ? 0 : Number.isFinite(seconds) + ? seconds * 1000 : Date.parse(error.retryAfter) - Date.now(); + await delay(Math.max(50 * 2 ** attempt, Number.isFinite(retryAfter) ? retryAfter : 0)); + } + } +} + +const assistantText = message => typeof message.content === 'string' + ? message.content + : message.content.filter(block => block.type === 'text').map(block => block.text).join(''); + +async function compactReference(config, history) { + const instruction = 'Summarize the task, changes, and important facts. Preserve checkpoint IDs and proof markers exactly.'; + const excerpt = history.map(message => { + const text = JSON.stringify(message); + return text.length > 2048 ? text.slice(0, 1024) + ' … ' + text.slice(-1024) : text; + }).join('\n').slice(-32_768); + const summary = assistantText(await refRequest(config, [{ + role: 'user', content: instruction + '\n\n' + excerpt, + }], [], true)); + if (!summary.trim()) throw new Error('Model returned an empty compaction summary'); + return [{ role: 'user', content: 'Continue from this conversation summary:\n' + summary }]; +} + +async function executeReferenceCall(toolset, call, invoke) { + try { + const schema = toolset.find(tool => tool.name === call.name)?.inputSchema; + if (!schema) throw new Error(`Unknown tool ${call.name}`); + const args = call.json ? JSON.parse(call.args) : call.args; + if (!args || typeof args !== 'object' || Array.isArray(args) + || Object.keys(args).length !== schema.required.length + || schema.required.some(key => !Object.hasOwn(args, key) || typeof args[key] !== 'string')) { + throw new Error(`Invalid arguments for ${call.name}`); + } + return await invoke(call.name, args); + } catch (error) { + return { text: error.message, isError: true }; + } +} + +export async function runRefAgentCli() { + const config = JSON.parse(await consumeText(process.stdin)); + config.key = process.env.HARNESS_BENCH_REF_KEY; + let history = [{ role: 'user', content: config.prompt }]; + let compactedAtTurn = false; + if (config.checkpoint) { + try { + ({ history, compactedAtTurn } = JSON.parse(await readFile(config.checkpoint, 'utf8'))); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + } + async function saveCheckpoint() { + const next = config.checkpoint + '.next'; + await jsonFile(next, { history, compactedAtTurn }); + await rename(next, config.checkpoint); + } + const workspace = await realpath(process.cwd()); + const shared = config.mcp ? await connectReferenceMcp(config.mcp, workspace) : undefined; + const tools = shared?.tools ?? referenceTools; + const invoke = shared?.call ?? ((name, args) => referenceNative(workspace, name, args)); + const isAnthropic = config.protocol === anthropic; + try { + for (let round = 0; round < 100; round++) { + let message; + try { + message = await refRequest(config, history, tools); + } catch (error) { + if (!error.overflow || compactedAtTurn) throw error; + history = await compactReference(config, history); + compactedAtTurn = true; + if (config.checkpoint) await saveCheckpoint(); + continue; + } + const calls = isAnthropic + ? message.content.filter(block => block.type === 'tool_use').map(block => ({ + id: block.id, name: block.name, args: block.input, + })) + : (message.tool_calls ?? []).map(call => ({ + id: call.id, name: call.function.name, args: call.function.arguments, json: true, + })); + if (calls.length) { + const outcomes = await Promise.all(calls.map(call => executeReferenceCall(tools, call, invoke))); + history.push(message); + if (isAnthropic) { + history.push({ role: 'user', content: outcomes.map(({ text, isError }, index) => ({ + type: 'tool_result', tool_use_id: calls[index].id, content: text, is_error: Boolean(isError), + })) }); + } else { + history.push(...outcomes.map(({ text, isError }, index) => ({ + role: 'tool', tool_call_id: calls[index].id, content: text, is_error: Boolean(isError), + }))); + } + compactedAtTurn = false; + if (config.checkpoint) await saveCheckpoint(); + continue; + } + const text = assistantText(message); + if (/^Compact the conversation and preserve cmp_\S+ \S+\.$/.test(text)) { + if (compactedAtTurn) throw new Error('Repeated compaction checkpoint'); + history = await compactReference(config, [...history, message]); + compactedAtTurn = true; + if (config.checkpoint) await saveCheckpoint(); + continue; + } + if (!text.trim()) throw new Error('Model returned an empty final answer'); + process.stdout.write(text + '\n'); + return; + } + throw new Error('Reference agent exceeded its 100-turn budget'); + } finally { + await shared?.close(); + } +} + +if (process.argv[2] === '--ref-agent' && process.argv[1] && resolve(process.argv[1]) === script) { + try { + await runRefAgentCli(); + } catch (error) { + console.error(error); + process.exitCode = 1; + } +} diff --git a/tools/harness-bench/bench.test.mjs b/tools/harness-bench/bench.test.mjs new file mode 100644 index 00000000000..2ecb04e0d7c --- /dev/null +++ b/tools/harness-bench/bench.test.mjs @@ -0,0 +1,277 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { access, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { before, test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { resolveMockAiBinary } from './mock-client.mjs'; + +const cli = fileURLToPath(new URL('run.mjs', import.meta.url)); +const repoRoot = fileURLToPath(new URL('../..', import.meta.url)); +const exec = promisify(execFile); +const readJson = async path => JSON.parse(await readFile(path, 'utf8')); +const readySource = 'pub fn status() -> &\'static str {\n "ready"\n}\n'; + +let mockBinary; +before(async () => { + const name = process.platform === 'win32' ? 'maka-mock-ai.exe' : 'maka-mock-ai'; + const debug = resolve(repoRoot, process.env.CARGO_TARGET_DIR ?? 'target', 'debug', name); + try { + await access(debug); + mockBinary = resolveMockAiBinary(repoRoot, debug); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + mockBinary = resolveMockAiBinary(repoRoot); + } +}); + +async function scratch(t) { + const dir = await mkdtemp(join(tmpdir(), 'harness-bench-test-')); + t.after(() => rm(dir, { recursive: true, force: true })); + return dir; +} + +async function invoke(args, { env = process.env, expectedCode = 0 } = {}) { + let result; + try { + result = { ...await exec(process.execPath, [cli, ...args], { env, timeout: 30_000 }), code: 0 }; + } catch (error) { + result = error; + } + assert.equal(result.code, expectedCode, [result.message, result.stdout, result.stderr].filter(Boolean).join('\n')); + return result; +} + +async function runScenario(t, scenario, args = []) { + const output = join(await scratch(t), 'output'); + const result = await invoke([ + 'run', '--scenario', scenario, '--harnesses', 'ref-agent', + '--mock-bin', mockBinary, '--output', output, ...args, + ]); + return { output, result, results: await readJson(join(output, 'results.json')) }; +} + +async function assertCleanServer(results) { + assert.deepEqual(results.errors, []); + assert.deepEqual(results.server.sessionsAfterCleanup, { items: [], nextCursor: null }); + assert.deepEqual(results.server.exit, { code: 0, signal: null }); + await assert.rejects(fetch(results.server.origin + '/admin/health', { + signal: AbortSignal.timeout(1000), + }), error => error.cause?.code === 'ECONNREFUSED'); +} + +async function laneEvidence(output, lane, markers) { + const dir = join(output, lane.artifacts); + const evidence = await readJson(join(dir, 'lane.json')); + const detail = await readJson(join(dir, 'mock-session.json')); + assert.equal(lane.mockCompleted, true); + assert.equal(lane.sessionDeleted, true); + assert.equal(evidence.workspaceProof.passed, true, JSON.stringify(evidence.workspaceProof)); + assert.deepEqual(evidence.observedMarkers, markers); + assert.deepEqual(detail.completionProof.observedMarkers, markers); + assert.equal(detail.scenarioCompleted, true); + assert.equal(detail.summary.finalized, true); + assert.equal(detail.summary.sessionId, lane.sessionId); + assert.equal(detail.summary.runId, lane.runId); + assert.equal(detail.summary.dropped, 0); + assert.equal(detail.nextCursor, detail.summary.attempts); + const final = detail.items.find(item => item.responseId === detail.completionProof.responseId + && item.stepId === 'done' && item.outcome === 'completed'); + assert.equal(final?.purpose, 'main'); + return { dir, evidence, detail }; +} + +test('preflight reports all adapters and runs the version probe in isolated HOME', async t => { + const dir = await scratch(t); + const home = join(dir, 'home'); + const bin = join(dir, 'bin'); + await Promise.all([mkdir(home), mkdir(bin)]); + await writeFile(join(home, 'sentinel'), 'user config\n'); + await writeFile(join(bin, 'claude'), + '#!/bin/sh\nprintf "isolated\\n" > "$HOME/probe-write"\nprintf "test-cli 1.0\\n"\n', { mode: 0o700 }); + const env = { ...process.env, HOME: home, USERPROFILE: home, PATH: bin }; + const { stdout } = await invoke(['preflight', '--json'], { env }); + const probes = JSON.parse(stdout); + assert.deepEqual(probes.map(probe => probe.id), [ + 'ref-agent', 'maka-direct', 'maka-codemode', 'claude', 'codex-ws', 'codex-http', + 'opencode-cold', 'opencode-attach', 'pi', 'pi-durable', 'dim', 'dsh', 'zcode', + 'kimi-openai', 'kimi-responses', 'kimi-anthropic', + ]); + const claude = probes.find(probe => probe.id === 'claude'); + assert.equal(claude.binaryPath, join(bin, 'claude')); + assert.equal(claude.version, 'test-cli 1.0'); + assert.equal(claude.available, true); + assert.deepEqual(claude.supportedTracks, ['native', 'sharedMcp']); + for (const id of ['codex-http', 'codex-ws', 'dim']) { + assert.deepEqual(probes.find(probe => probe.id === id).supportedTracks, ['native', 'sharedMcp']); + } + const opencode = probes.find(probe => probe.id === 'opencode-cold'); + assert.equal(opencode.available, false); + assert.match(opencode.installHint, /Install OpenCode/); + assert.deepEqual(await readdir(home), ['sentinel']); + assert.equal(await readFile(join(home, 'sentinel'), 'utf8'), 'user config\n'); +}); + +test('smoke-edit runs four concurrent lanes per repeat and exports proof before cleanup', async t => { + const { output, result, results } = await runScenario(t, 'smoke-edit', ['--lanes', '4', '--runs', '2']); + assert.match(result.stdout, /\| smoke-edit \| native \| ref-agent \| 8\/8 passed \|/); + const manifest = await readJson(join(output, 'manifest.json')); + assert.equal(manifest.runId, results.runId); + assert.equal(manifest.mockBinary, mockBinary); + assert.equal(results.lanes.length, 8); + assert.equal(new Set(results.lanes.map(lane => lane.sessionId)).size, 8); + assert.equal(results.summary[0].verifiedWorkRate, 1); + assert.equal(results.summary[0].watchdogViolationsTotal, 0); + assert.equal(results.server.watchdog.totalViolations, 0); + const report = await readFile(join(output, 'report.md'), 'utf8'); + assert.match(report, /\| smoke-edit \| native \| ref-agent \| 8 \| 100\.0% \| 100\.0% \|/); + for (const repeat of [1, 2]) { + const times = []; + const lanes = results.lanes.filter(lane => lane.artifacts.startsWith('repeat-' + repeat + '/')); + assert.deepEqual(lanes.map(lane => lane.logicalLane), ['lane-1', 'lane-2', 'lane-3', 'lane-4']); + for (const lane of lanes) { + const { dir, detail, evidence } = await laneEvidence(output, lane, ['SMOKE_EDIT_OK']); + assert.equal(await readFile(join(dir, 'workspace', 'src', 'lib.rs'), 'utf8'), readySource); + assert.equal(lane.completedToolRounds, 3); + assert.deepEqual(detail.violations, []); + const [segment] = evidence.process; + assert.equal(segment.code, 0); + assert.match(await readFile(join(dir, segment.stdoutLog), 'utf8'), /SMOKE_EDIT_OK/); + times.push([BigInt(segment.startNs), BigInt(segment.endNs)]); + } + times.sort(([a], [b]) => a < b ? -1 : 1); + assert.ok(times.some(([, end], index) => index + 1 < times.length && end > times[index + 1][0]), + 'Expected CLI process windows to overlap'); + } + await assertCleanServer(results); +}); + +test('Shared MCP reconciles actual audit calls, workspace hash and mock tool receipts', async t => { + const { output, results } = await runScenario(t, 'mcp-smoke-edit', ['--lanes', '2']); + assert.equal(results.lanes.length, 2); + for (const lane of results.lanes) { + const { dir, detail, evidence } = await laneEvidence(output, lane, ['SMOKE_EDIT_OK']); + const audit = (await readFile(join(dir, 'mcp-audit.jsonl'), 'utf8')).trimEnd().split('\n') + .map(line => JSON.parse(line)).sort((a, b) => a.seq - b.seq); + assert.deepEqual(audit.map(row => row.seq), [1, 2, 3, 4]); + assert.deepEqual(audit.slice(0, 2).map(row => row.tool), ['bench_read_file', 'bench_edit_file']); + assert.deepEqual(audit.slice(2).map(row => row.tool).sort(), ['bench_exec_shell', 'bench_read_file']); + assert.ok(audit.every(row => row.ok)); + const workspace = await readFile(join(dir, 'workspace', 'src', 'lib.rs'), 'utf8'); + assert.equal(workspace, readySource); + const hash = createHash('sha256').update(workspace).digest('hex'); + assert.deepEqual(evidence.workspaceProof.files.find(file => file.path === 'src/lib.rs'), + { path: 'src/lib.rs', expectedSha256: hash, actualSha256: hash }); + const receipts = new Set(detail.items.flatMap(attempt => attempt.confirmedCallIds)); + assert.equal(receipts.size, audit.length); + assert.equal(evidence.workspaceProof.mcpAudit.calls, receipts.size); + } + await assertCleanServer(results); +}); + +test('chaos-recovery retries real injected HTTP failures and stream disconnect', async t => { + const { output, results } = await runScenario(t, 'chaos-recovery'); + const [lane] = results.lanes; + const { dir, detail } = await laneEvidence(output, lane, ['CHAOS_RECOVERY_OK']); + assert.equal(await readFile(join(dir, 'workspace', 'artifacts', 'recovery.txt'), 'utf8'), 'state=recovered\n'); + assert.deepEqual(detail.items.filter(item => item.faultId).map(item => item.faultId), + ['read/1:Http429', 'write/1:Http503', 'interrupted-check/1:Disconnect']); + assert.deepEqual(detail.items.filter(item => item.retryReason === 'scenario_replay' && item.outcome === 'completed') + .map(item => item.stepId), ['read', 'write', 'interrupted-check']); + assert.equal(lane.retries, 3); + await assertCleanServer(results); +}); + +test('long-compaction adopts the returned checkpoint and reduces request context', async t => { + const { output, results } = await runScenario(t, 'long-compaction'); + const [lane] = results.lanes; + const { dir, detail } = await laneEvidence(output, lane, ['COMPACTION_OK', 'handoff-ticket-6f32']); + assert.equal(await readFile(join(dir, 'workspace', 'state', 'handoff.txt'), 'utf8'), + 'fact=handoff-ticket-6f32\nstate=recovered\n'); + const [issued, adopted] = detail.compactions; + assert.equal(issued.purpose, 'compact'); + assert.match(issued.checkpointId, /^cmp_/); + assert.equal(adopted.adoptedCheckpointId, issued.checkpointId); + assert.equal(adopted.purpose, 'main'); + assert.ok(lane.promptBytesPeak >= 131072 && lane.promptBytesFinal < 65536); + assert.equal(results.server.metrics.contextOverflowsEmitted, 1); + await assertCleanServer(results); +}); + +test('matrix rotates candidates and distinguishes an unavailable compatible adapter from an unsupported track', async t => { + const dir = await scratch(t); + const output = join(dir, 'output'); + const bin = join(dir, 'bin'); + await mkdir(bin); + await symlink('/bin/ps', join(bin, 'ps')); + const { stdout } = await invoke([ + 'matrix', '--scenarios', 'smoke-edit,mcp-smoke-edit', '--harnesses', 'pi,ref-agent', + '--runs', '2', '--mock-bin', mockBinary, '--output', output, + ], { env: { ...process.env, PATH: bin }, expectedCode: 1 }); + assert.match(stdout, /\| mcp-smoke-edit \| sharedMcp \| pi \| N\/A \(unsupported track\) \|/); + const report = await readFile(join(output, 'matrix-report.md'), 'utf8'); + assert.match(report, /\| smoke-edit \| native \| pi \| 0\/2 passed \|/); + assert.match(report, /\| mcp-smoke-edit \| sharedMcp \| pi \| N\/A \(unsupported track\) \|/); + assert.match(report, /\| mcp-smoke-edit \| sharedMcp \| ref-agent \| 2\/2 passed \|/); + const native = await readJson(join(output, 'scenario-1', 'results.json')); + assert.deepEqual(native.lanes.map(lane => [lane.harness, lane.success]), [ + ['pi', false], ['ref-agent', true], ['ref-agent', true], ['pi', false], + ]); + for (const lane of native.lanes.filter(lane => !lane.success)) { + assert.match(lane.failures.join('\n'), /could not locate pi/); + assert.equal(lane.sessionDeleted, true); + } + const mcp = await readJson(join(output, 'scenario-2', 'results.json')); + assert.deepEqual(mcp.lanes.map(lane => [lane.harness, lane.success]), [['ref-agent', true], ['ref-agent', true]]); + await assertCleanServer(native); + await assertCleanServer(mcp); +}); + +test('SIGKILL restarts the reference client with one workspace, session and MCP audit', async t => { + const scratchDir = await scratch(t); + const output = join(scratchDir, 'output'); + const scenarioPath = join(scratchDir, 'restart.json'); + const scenario = await readJson(new URL('scenarios/mcp-smoke-edit.json', import.meta.url)); + // Four 429s hold the second step in exponential backoff after the first tool receipt. + scenario.faults = [1, 2, 3, 4].map(attempt => ({ step: 'edit', attempt, emit: 'http429' })); + await writeFile(scenarioPath, JSON.stringify(scenario)); + await invoke([ + 'run', '--scenario', scenarioPath, '--harnesses', 'ref-agent', + '--mock-bin', mockBinary, '--output', output, + '--sigkill-after-ms', '600', '--resume-after-kill', + ]); + const results = await readJson(join(output, 'results.json')); + assert.equal(results.lanes.length, 1); + const [lane] = results.lanes; + const { dir, evidence, detail } = await laneEvidence(output, lane, ['SMOKE_EDIT_OK']); + assert.deepEqual(evidence.process.map(({ signal, termination, code }) => [signal, termination, code]), + [['SIGKILL', 'sigkill', null], [null, null, 0]]); + assert.equal(await readFile(join(dir, 'workspace', 'src', 'lib.rs'), 'utf8'), readySource); + assert.equal(evidence.workspaceProof.mcpAudit.calls, 4); + assert.deepEqual(lane.watchdogViolations, []); + assert.deepEqual(detail.items.filter(item => item.faultId).map(item => item.faultId), + ['edit/1:Http429', 'edit/2:Http429', 'edit/3:Http429', 'edit/4:Http429']); + await assertCleanServer(results); +}); diff --git a/tools/harness-bench/fixtures.mjs b/tools/harness-bench/fixtures.mjs new file mode 100644 index 00000000000..3cda0bb2f97 --- /dev/null +++ b/tools/harness-bench/fixtures.mjs @@ -0,0 +1,297 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { createHash } from 'node:crypto'; +import { constants } from 'node:fs'; +import { lstat, mkdir, readFile, readdir, realpath, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +const sha256 = (data) => createHash('sha256').update(data).digest('hex'); +const readFlags = constants.O_RDONLY | constants.O_NOFOLLOW; + +export async function loadScenario(scenarioPath) { + const source = await readFile(scenarioPath, 'utf8'); + try { + return JSON.parse(source); + } catch (cause) { + throw new Error(`Invalid scenario JSON at ${scenarioPath}`, { cause }); + } +} + +export async function workspaceRoot(workspaceDir) { + if (!(await lstat(workspaceDir)).isDirectory()) { + throw new Error(`Workspace root must be a directory: ${workspaceDir}`); + } + return realpath(workspaceDir); +} + +export async function resolveWorkspaceFile(root, path, { create = false } = {}) { + const parts = path.split('/'); + if (/[\0\r\n\\:]/.test(path) || parts.some((part) => !part || part === '.' || part === '..')) { + throw new Error(`Invalid workspace-relative file path ${JSON.stringify(path)}`); + } + const name = parts.pop(); + let parent = root; + for (const part of parts) { + parent = join(parent, part); + if (create) { + try { + await mkdir(parent); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + } + } + if (!(await lstat(parent)).isDirectory()) { + throw new Error(`Workspace path traverses a non-directory or symlink: ${path}`); + } + } + const file = join(parent, name); + try { + const stat = await lstat(file); + if (!stat.isFile() || stat.nlink !== 1) { + throw new Error(`Workspace path must be a regular file with one link: ${path}`); + } + } catch (error) { + if (!create || error.code !== 'ENOENT') throw error; + } + return file; +} + +export function replaceUnique(content, old, replacement) { + const index = content.indexOf(old); + if (!old || old === replacement || index < 0 || content.includes(old, index + 1)) { + throw new Error('Edit requires exactly one occurrence of a nonempty, changing match'); + } + return content.slice(0, index) + replacement + content.slice(index + old.length); +} + +export function parseBenchmarkCommand(command) { + const grep = /^grep -Fx -- '([^'\0\r\n]*)' (?:'([^'\0\r\n]+)'|([\w./-]+))$/.exec(command); + if (grep?.[0] === command) { + return { kind: 'grep', marker: grep[1], path: grep[2] ?? grep[3] }; + } + const printf = /^printf (?:'([^'%\\\0\r\n]*)'|([\w.]+))$/.exec(command); + if (printf?.[0] === command) { + return { kind: 'printf', text: printf[1] ?? printf[2] }; + } + throw new Error("Expected grep -Fx -- 'line' 'path' or printf with one literal argument"); +} + +function fixtureFiles(spec) { + return new Map( + Object.values(spec.fixtures ?? {}) + .filter((fixture) => fixture.kind === 'file') + .map(({ path, content }) => [path, content]), + ); +} + +export async function materializeWorkspace(spec, workspaceDir) { + await mkdir(workspaceDir, { recursive: true }); + const root = await workspaceRoot(workspaceDir); + for (const [path, content] of fixtureFiles(spec)) { + const file = await resolveWorkspaceFile(root, path, { create: true }); + await writeFile(file, content, { flag: 'wx' }); + } + const manifest = new Map(); + async function collect(directory, prefix) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = prefix + entry.name; + if (entry.isDirectory()) { + await collect(join(directory, entry.name), path + '/'); + } else { + const file = await resolveWorkspaceFile(root, path); + manifest.set(path, sha256(await readFile(file, { flag: readFlags }))); + } + } + } + await collect(root, ''); + return manifest; +} + +function expectedMcpCall(spec, contents, action) { + const call = (tool, args, output, extra) => ({ + tool, + path: args.path, + inputBytes: Buffer.byteLength(JSON.stringify(args)), + outputBytes: Buffer.byteLength(output), + ...extra, + }); + if (action.readFile) { + const { path } = action.readFile; + return call('bench_read_file', { path }, contents.get(path)); + } + if (action.writeFile) { + const { path, content } = action.writeFile; + return call('bench_write_file', { path, content }, 'OK'); + } + if (action.editFile) { + const { path, old, new: replacement } = action.editFile; + return call('bench_edit_file', { path, old_string: old, new_string: replacement }, 'OK'); + } + if (action.shell) { + const { command } = spec.fixtures[action.shell.commandId]; + const parsed = parseBenchmarkCommand(command); + let output = parsed.text; + if (parsed.kind === 'grep') { + const content = contents.get(parsed.path); + if (content === undefined) throw new Error(`No scenario content for grep target ${parsed.path}`); + const lines = content.split('\n'); + if (lines.at(-1) === '') lines.pop(); + output = lines.filter((line) => line === parsed.marker).map((line) => line + '\n').join(''); + } + return call('bench_exec_shell', { command }, output, { exitCode: 0 }); + } + if (action.finalAnswer) return null; + throw new Error('Shared MCP proof requires benchmark file and shell actions'); +} + +function expectedWorkspace(spec, initialManifest, errors) { + const contents = fixtureFiles(spec); + for (const [path, content] of contents) { + if (initialManifest.get(path) !== sha256(content)) { + errors.push(`Initial fixture hash mismatch: ${path}`); + } + } + const mcpGroups = []; + for (const step of spec.steps) { + const changes = new Map(); + const calls = []; + for (const action of step.parallelBatch ?? [step]) { + if (spec.track === 'sharedMcp') { + const call = expectedMcpCall(spec, contents, action); + if (call) calls.push(call); + } + if (action.writeFile) { + const { path, content } = action.writeFile; + changes.set(path, content); + } + if (action.editFile) { + const { path, old, new: replacement } = action.editFile; + changes.set(path, replaceUnique(contents.get(path), old, replacement)); + } + } + if (calls.length) mcpGroups.push({ step: step.id, calls }); + for (const [path, content] of changes) contents.set(path, content); + } + const hashes = new Map(initialManifest); + for (const [path, content] of contents) hashes.set(path, sha256(content)); + return { hashes, mcpGroups }; +} + +function validAuditRow(row) { + const nonnegativeInteger = (value) => Number.isSafeInteger(value) && value >= 0; + if (!row || !nonnegativeInteger(row.seq) || row.seq < 1 + || typeof row.tool !== 'string' || typeof row.ok !== 'boolean' + || !nonnegativeInteger(row.inputBytes) || !nonnegativeInteger(row.outputBytes) + || ![row.startedNs, row.endedNs, row.durationNs] + .every((value) => typeof value === 'string' && /^\d+$/.test(value))) { + return false; + } + return BigInt(row.endedNs) - BigInt(row.startedNs) === BigInt(row.durationNs); +} + +async function verifyMcpAudit(path, groups, errors) { + const expectedCalls = groups.reduce((count, { calls }) => count + calls.length, 0); + const proof = { expectedCalls, calls: 0, inputBytes: 0, outputBytes: 0 }; + if (!path) { + errors.push('Shared MCP track requires an audit log'); + return proof; + } + let source; + try { + source = await readFile(path, 'utf8'); + } catch (error) { + errors.push(`Cannot read MCP audit log: ${error.message}`); + return proof; + } + const lines = source.split('\n'); + if (lines.at(-1) === '') lines.pop(); + proof.calls = lines.length; + const rows = []; + for (const [index, line] of lines.entries()) { + let row; + try { + row = JSON.parse(line); + } catch (error) { + errors.push(`Invalid MCP audit JSON on line ${index + 1}: ${error.message}`); + continue; + } + if (!validAuditRow(row)) { + errors.push(`Invalid MCP audit fields on line ${index + 1}`); + continue; + } + rows.push(row); + proof.inputBytes += row.inputBytes; + proof.outputBytes += row.outputBytes; + } + if (proof.calls !== expectedCalls) { + errors.push(`Expected ${expectedCalls} MCP calls, got ${proof.calls}`); + } + rows.sort((a, b) => a.seq - b.seq); + if (rows.some((row, index) => row.seq !== index + 1)) { + errors.push('MCP audit sequence is discontinuous'); + } + let offset = 0; + for (const { step, calls } of groups) { + const unmatched = rows.slice(offset, offset + calls.length); + offset += calls.length; + for (const expected of calls) { + const index = unmatched.findIndex((row) => row.ok + && row.tool === expected.tool && row.path === expected.path + && row.exitCode === expected.exitCode + && row.inputBytes === expected.inputBytes && row.outputBytes === expected.outputBytes); + if (index < 0) { + errors.push(`MCP audit mismatch at ${step}: expected ${JSON.stringify(expected)}`); + } else { + unmatched.splice(index, 1); + } + } + } + return proof; +} + +export async function verifyWorkspace(spec, { workspaceDir, initialManifest, agentOutputText, mcpAuditPath }) { + const errors = []; + const { hashes, mcpGroups } = expectedWorkspace(spec, initialManifest, errors); + let root; + try { + root = await workspaceRoot(workspaceDir); + } catch (error) { + errors.push(`Cannot verify workspace root: ${error.message}`); + } + const files = []; + for (const [path, expectedSha256] of hashes) { + let actualSha256 = null; + if (root) { + try { + const file = await resolveWorkspaceFile(root, path); + actualSha256 = sha256(await readFile(file, { flag: readFlags })); + if (actualSha256 !== expectedSha256) errors.push(`Final file hash mismatch: ${path}`); + } catch (error) { + errors.push(`Cannot verify workspace file ${path}: ${error.message}`); + } + } + files.push({ path, expectedSha256, actualSha256 }); + } + const markers = spec.steps.at(-1).finalAnswer.expectMarkers ?? []; + const missingMarkers = markers.filter((marker) => !agentOutputText.includes(marker)); + for (const marker of missingMarkers) errors.push(`Missing final answer marker: ${marker}`); + const mcpAudit = spec.track === 'sharedMcp' ? await verifyMcpAudit(mcpAuditPath, mcpGroups, errors) : null; + return { passed: errors.length === 0, errors, files, missingMarkers, mcpAudit }; +} diff --git a/tools/harness-bench/mcp-server.mjs b/tools/harness-bench/mcp-server.mjs new file mode 100644 index 00000000000..2c655b5bcde --- /dev/null +++ b/tools/harness-bench/mcp-server.mjs @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { execFile } from 'node:child_process'; +import { constants } from 'node:fs'; +import { open, readFile, writeFile } from 'node:fs/promises'; +import { isAbsolute } from 'node:path'; +import { createInterface } from 'node:readline'; +import { parseArgs, promisify } from 'node:util'; +import { parseBenchmarkCommand, replaceUnique, resolveWorkspaceFile, workspaceRoot } from './fixtures.mjs'; + +const protocolVersions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']; +const execFileAsync = promisify(execFile); +const readFlags = constants.O_RDONLY | constants.O_NOFOLLOW; +const writeFlags = constants.O_WRONLY | constants.O_TRUNC | constants.O_NOFOLLOW; +const tools = [ + ['bench_read_file', 'Read a UTF-8 file in the benchmark workspace.', ['path']], + ['bench_write_file', 'Write a UTF-8 file in the benchmark workspace.', ['path', 'content']], + ['bench_edit_file', 'Replace one exact match in a workspace file.', ['path', 'old_string', 'new_string']], + ['bench_exec_shell', 'Run a fixed-line grep or literal printf in the benchmark workspace.', ['command']], +].map(([name, description, required]) => ({ + name, + description, + inputSchema: { + type: 'object', + properties: Object.fromEntries(required.map((key) => [key, { type: 'string' }])), + required, + additionalProperties: false, + }, +})); + +async function runShell(root, command) { + const parsed = parseBenchmarkCommand(command); + // Pass fixture values as arguments to fixed shell source. + const args = parsed.kind === 'grep' + ? ['exec grep -Fx -- "$1" "$2"', parsed.marker, await resolveWorkspaceFile(root, parsed.path)] + : ['printf "%s" "$1"', parsed.text]; + const [source, ...operands] = args; + try { + const { stdout, stderr } = await execFileAsync('/bin/sh', ['-c', source, 'bench', ...operands], { + cwd: root, + env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, + }); + return { text: stdout + stderr, exitCode: 0 }; + } catch (error) { + if (!Number.isInteger(error.code)) throw error; + return { text: error.stdout + error.stderr || error.message, exitCode: error.code }; + } +} + +async function runTool(root, tool, args) { + const schema = tools.find(({ name }) => name === tool)?.inputSchema; + if (!schema) throw new Error(`Unknown benchmark tool ${tool}`); + if (!args || typeof args !== 'object' || Array.isArray(args) + || Object.keys(args).length !== schema.required.length + || schema.required.some((key) => !Object.hasOwn(args, key) || typeof args[key] !== 'string')) { + throw new Error(`Expected string arguments: ${schema.required.join(', ')}`); + } + if (tool === 'bench_exec_shell') return runShell(root, args.command); + const create = tool === 'bench_write_file'; + const file = await resolveWorkspaceFile(root, args.path, { create }); + if (create) { + await writeFile(file, args.content, { flag: writeFlags | constants.O_CREAT }); + return { text: 'OK' }; + } + const content = await readFile(file, { encoding: 'utf8', flag: readFlags }); + if (tool === 'bench_read_file') return { text: content }; + const edited = replaceUnique(content, args.old_string, args.new_string); + await writeFile(file, edited, { flag: writeFlags }); + return { text: 'OK' }; +} + +async function callTool(root, audit, seq, tool, args) { + const started = process.hrtime.bigint(); + let result; + let ok; + try { + result = await runTool(root, tool, args); + ok = result.exitCode === undefined || result.exitCode === 0; + } catch (error) { + result = { text: error.message }; + ok = false; + } + const ended = process.hrtime.bigint(); + // Measure UTF-8 tool arguments and text before JSON-RPC framing. + const row = { + seq, + tool, + ok, + startedNs: started.toString(), + endedNs: ended.toString(), + durationNs: (ended - started).toString(), + inputBytes: args === undefined ? 0 : Buffer.byteLength(JSON.stringify(args)), + outputBytes: Buffer.byteLength(result.text), + ...(typeof args?.path === 'string' ? { path: args.path } : {}), + ...(result.exitCode === undefined ? {} : { exitCode: result.exitCode }), + }; + const line = JSON.stringify(row) + '\n'; + const { bytesWritten } = await audit.write(line); + if (bytesWritten !== Buffer.byteLength(line)) throw new Error('Short write to MCP audit log'); + return { content: [{ type: 'text', text: result.text }], isError: !ok }; +} + +async function serve(root, audit, sequence) { + const errorResponse = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } }); + async function handleLine(line) { + let request; + try { + request = JSON.parse(line); + } catch { + return errorResponse(null, -32700, 'Parse error'); + } + const id = request?.id; + const validId = typeof id === 'string' || Number.isFinite(id); + if (request?.jsonrpc !== '2.0' || typeof request.method !== 'string' + || (id !== undefined && !validId)) { + return errorResponse(validId ? id : null, -32600, 'Invalid request'); + } + if (id === undefined) return null; + + let result; + switch (request.method) { + case 'initialize': { + const requested = request.params?.protocolVersion; + if (typeof requested !== 'string') { + return errorResponse(id, -32602, 'Expected a protocolVersion'); + } + result = { + protocolVersion: protocolVersions.includes(requested) ? requested : protocolVersions[0], + capabilities: { tools: {} }, + serverInfo: { name: 'harness-bench', version: '1.0.0' }, + }; + break; + } + case 'ping': + result = {}; + break; + case 'tools/list': + result = { tools }; + break; + case 'tools/call': { + const name = request.params?.name; + if (typeof name !== 'string') return errorResponse(id, -32602, 'Expected a tool name'); + result = await callTool(root, audit, ++sequence, name, request.params.arguments); + break; + } + default: + return errorResponse(id, -32601, 'Method not found'); + } + return { jsonrpc: '2.0', id, result }; + } + + const input = createInterface({ input: process.stdin, crlfDelay: Infinity }); + const pending = new Set(); + let failure; + for await (const line of input) { + if (failure) break; + const operation = handleLine(line).then((response) => { + if (response) process.stdout.write(JSON.stringify(response) + '\n'); + }).catch((error) => { + failure ??= error; + input.close(); + process.stdin.pause(); + }); + pending.add(operation); + void operation.then(() => pending.delete(operation)); + } + await Promise.all(pending); + if (failure) throw failure; +} + +async function main() { + const { values } = parseArgs({ + options: { workspace: { type: 'string' }, 'audit-log': { type: 'string' }, 'resume-audit': { type: 'boolean' } }, + }); + const auditPath = values['audit-log']; + if (!values.workspace || !isAbsolute(values.workspace) || !auditPath) { + throw new Error('Usage: node mcp-server.mjs --workspace --audit-log '); + } + const root = await workspaceRoot(values.workspace); + const resume = values['resume-audit']; + const audit = await open( + auditPath, + (resume ? constants.O_RDWR : constants.O_WRONLY) | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, + 0o600, + ); + try { + const info = await audit.stat(); + if (!info.isFile() || info.nlink !== 1 || (!resume && info.size !== 0)) { + throw new Error('MCP audit log must be a regular file with one link, empty unless resuming'); + } + let sequence = 0; + if (info.size) { + const source = await audit.readFile('utf8'); + if (!source.endsWith('\n')) throw new Error('MCP audit log ends with a partial row'); + for (const line of source.slice(0, -1).split('\n')) { + sequence = Math.max(sequence, JSON.parse(line).seq); + } + } + await serve(root, audit, sequence); + } finally { + await audit.close(); + } +} + +try { + await main(); +} catch (error) { + console.error(error); + process.exitCode = 1; +} diff --git a/tools/harness-bench/mock-client.mjs b/tools/harness-bench/mock-client.mjs new file mode 100644 index 00000000000..81364916fc8 --- /dev/null +++ b/tools/harness-bench/mock-client.mjs @@ -0,0 +1,305 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { spawn } from 'node:child_process'; +import { accessSync, constants, statSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { createInterface } from 'node:readline'; +import { setTimeout as delay } from 'node:timers/promises'; +import { stripVTControlCharacters } from 'node:util'; + +const buildCommand = 'cargo build --release -p maka-mock-ai --bin maka-mock-ai'; + +export function resolveMockAiBinary(repoRoot, explicitPath) { + if (explicitPath !== undefined) { + const binary = resolve(explicitPath); + try { + if (!statSync(binary).isFile()) throw new Error('expected an executable file'); + accessSync(binary, constants.X_OK); + } catch (cause) { + throw new Error(`Cannot execute maka-mock-ai at ${binary}: ${cause.message}`, { cause }); + } + return binary; + } + + const name = process.platform === 'win32' ? 'maka-mock-ai.exe' : 'maka-mock-ai'; + const candidates = ['release', 'debug'].map(profile => resolve(repoRoot, 'target', profile, name)); + for (const binary of candidates) { + try { + if (!statSync(binary).isFile()) continue; + accessSync(binary, constants.X_OK); + return binary; + } catch (error) { + if (!['ENOENT', 'ENOTDIR', 'EACCES'].includes(error.code)) throw error; + } + } + throw new Error(`Cannot find an executable maka-mock-ai at ${candidates.join(' or ')}. Run ${buildCommand}.`); +} + +// The Rust router uses raw path components and query values as IDs. +function pathId(id) { + const path = `/s/${id}/x`; + if (typeof id !== 'string' || !id || /[/\\?#]/.test(id) + || new URL(path, 'http://localhost').pathname !== path) { + throw new TypeError(`Invalid mock-ai path ID: ${id}`); + } + return id; +} + +class MockAdminError extends Error { + constructor(method, path, status, body) { + super(`${method} ${path} returned HTTP ${status}: ${body}`); + this.name = 'MockAdminError'; + this.status = status; + this.body = body; + } +} + +export class MockAdminClient { + #origin; + + constructor(baseUrl) { + this.#origin = new URL(baseUrl).origin; + } + + async #request(path, { method = 'GET', body, status = 200, text = false, signal } = {}) { + const request = { method, redirect: 'error', signal }; + if (body !== undefined) { + request.headers = { 'content-type': 'application/json' }; + request.body = JSON.stringify(body); + } + const response = await fetch(new URL(path, this.#origin), request); + if (response.status !== status) { + throw new MockAdminError(method, path, response.status, await response.text()); + } + return text ? response.text() : response.json(); + } + + health({ signal } = {}) { + return this.#request('/admin/health', { signal }); + } + + registerSession({ + runId, sessionId, harness, logicalLane, scenario, launchMode, workspace, + credentialBinding, clientSessionAliases, + }) { + return this.#request('/admin/sessions', { + method: 'POST', + status: 201, + body: { + run_id: pathId(runId), + session_id: pathId(sessionId), + harness, + logical_lane: logicalLane, + scenario, + launch_mode: launchMode, + workspace, + credential_binding: credentialBinding, + client_session_aliases: clientSessionAliases, + }, + }); + } + + listSessions({ run, cursor, limit } = {}) { + const params = new URLSearchParams(); + if (cursor !== undefined && cursor !== null) params.set('cursor', cursor); + if (limit !== undefined) params.set('limit', limit); + if (run !== undefined) { + if (typeof run !== 'string' || /[&#]/.test(run) + || new URL(`http://localhost/?run=${run}`).search !== `?run=${run}`) { + throw new TypeError(`Invalid mock-ai run filter: ${run}`); + } + return this.#request(`/admin/sessions?run=${run}${params.size ? `&${params}` : ''}`); + } + return this.#request(`/admin/sessions${params.size ? `?${params}` : ''}`); + } + + // The optional finalization carries the result of the proof-bearing POST. + async getSessionDetailAll(sessionId, { finalization } = {}) { + const path = `/admin/sessions/${pathId(sessionId)}`; + const items = []; + let after = 0; + while (true) { + const page = await this.#request(`${path}?after=${after}&limit=500`); + const { nextCursor, summary } = page; + items.push(...page.items); + // Only items are paged. nextCursor also acknowledges dropped attempts. + if (!Number.isSafeInteger(nextCursor) || nextCursor < after || nextCursor > summary.attempts) { + throw new Error(`Invalid mock-ai cursor for ${sessionId}: ${after} -> ${nextCursor}`); + } + if (nextCursor === summary.attempts) { + if (finalization && (!summary.finalized || finalization.runId !== summary.runId + || finalization.sessionId !== summary.sessionId || finalization.cursor !== summary.cursor)) { + throw new Error(`Finalization does not match mock-ai session ${sessionId}`); + } + return { ...page, items, scenarioCompleted: finalization?.scenarioCompleted === true }; + } + if (nextCursor === after) { + throw new Error(`Mock-ai cursor did not advance for ${sessionId}: ${after}`); + } + after = nextCursor; + } + } + + recordObservation(sessionId, observation) { + return this.#request(`/admin/sessions/${pathId(sessionId)}/observations`, { + method: 'POST', body: observation, + }); + } + + async finalizeSession(sessionId, proof) { + const summary = await this.#request(`/admin/sessions/${pathId(sessionId)}/finalize`, { + method: 'POST', body: proof, + }); + return { ...summary, scenarioCompleted: proof !== undefined && proof !== null }; + } + + deleteSession(sessionId, { cursor, after }) { + const query = new URLSearchParams({ cursor, after }); + return this.#request(`/admin/sessions/${pathId(sessionId)}?${query}`, { method: 'DELETE' }); + } + + reset() { + return this.#request('/admin/reset', { method: 'POST' }); + } + + metrics() { + return this.#request('/admin/metrics'); + } + + violations() { + return this.#request('/admin/violations'); + } + + prometheus() { + return this.#request('/metrics', { text: true }); + } +} + +export class MockAiProcess { + #child; + #closed; + #exit; + #error; + #origin; + #log = ''; + #stopping; + + constructor(binary, args) { + this.#child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + this.#child.on('error', error => { this.#error = error; }); + this.#closed = new Promise(resolveClose => { + this.#child.once('close', (code, signal) => { + this.#exit = { code, signal }; + resolveClose(this.#exit); + }); + }); + + for (const stream of [this.#child.stdout, this.#child.stderr]) { + const lines = createInterface({ input: stream, crlfDelay: Infinity }); + lines.on('line', raw => { + const line = stripVTControlCharacters(raw); + this.#log = `${this.#log}${line}\n`.slice(-16_384); + const match = /maka-mock-ai listening origin=(https?:\/\/\S+)/.exec(line); + if (match) this.#origin = new URL(match[1]).origin; + }); + lines.on('error', error => { this.#error = error; }); + } + } + + get baseUrl() { + return this.#origin; + } + + scopedUrl(runId, sessionId, suffix = '/v1') { + const tail = suffix && !suffix.startsWith('/') ? `/${suffix}` : suffix; + return `${this.baseUrl}/s/${pathId(runId)}/${pathId(sessionId)}${tail}`; + } + + async waitUntilReady() { + const deadline = performance.now() + 10_000; + let lastError; + while (performance.now() < deadline) { + if (this.#error || this.#exit) { + const reason = this.#error?.message ?? this.#exit.signal ?? `exit ${this.#exit.code}`; + throw new Error(`maka-mock-ai exited during startup (${reason})\n${this.#log}`, { + cause: this.#error, + }); + } + if (this.#origin) { + try { + const health = await new MockAdminClient(this.#origin).health({ + signal: AbortSignal.timeout(500), + }); + if (health.ok !== true) throw new Error('Expected mock-ai health to report ok: true'); + if (!this.#exit && !this.#error) return this; + } catch (error) { + if (!(error instanceof TypeError) && error.name !== 'TimeoutError') { + throw new Error(`maka-mock-ai health check failed: ${error.message}\n${this.#log}`, { cause: error }); + } + lastError = error; + } + } + await delay(50); + } + throw new Error(`maka-mock-ai startup timed out\n${this.#log}`, { cause: lastError }); + } + + stop() { + this.#stopping ??= this.#stop(); + return this.#stopping; + } + + async #stop() { + if (this.#exit || !this.#child.pid) return this.#closed; + // The binary shuts down gracefully on SIGINT. + this.#child.kill('SIGINT'); + const force = setTimeout(() => this.#child.kill('SIGKILL'), 5_000); + try { + return await this.#closed; + } finally { + clearTimeout(force); + } + } +} + +export async function startMockAi({ + binary, scenarioPath, listen = '127.0.0.1:0', strictBenchmark = true, + latencyProfile, providerDialect, maxConcurrent, rpm, itpm, extraArgs = [], +}) { + const args = ['--listen', listen, '--admin']; + if (strictBenchmark) args.push('--strict-benchmark'); + for (const [flag, value] of [ + ['--scenario', scenarioPath], + ['--latency-profile', latencyProfile], + ['--provider-dialect', providerDialect], + ['--max-concurrent', maxConcurrent], + ['--rpm', rpm], + ['--itpm', itpm], + ]) { + if (value !== undefined) args.push(flag, String(value)); + } + const mock = new MockAiProcess(binary, [...args, ...extraArgs]); + try { + return await mock.waitUntilReady(); + } catch (error) { + await mock.stop(); + throw error; + } +} diff --git a/tools/harness-bench/proc-monitor.mjs b/tools/harness-bench/proc-monitor.mjs new file mode 100644 index 00000000000..038a1983c66 --- /dev/null +++ b/tools/harness-bench/proc-monitor.mjs @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { execFile, spawn } from 'node:child_process'; +import { createInterface } from 'node:readline'; +import { finished } from 'node:stream/promises'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); +const logLimit = 256 * 1024; + +function killGroup(pid) { + try { + process.kill(-pid, 'SIGKILL'); + } catch (error) { + if (error.code !== 'ESRCH') throw error; + } +} + +async function sampleTree(rootPid, signal) { + const { stdout } = await execFileAsync('ps', ['-axo', 'pid=,ppid=,rss=,pcpu='], { + signal, + env: { ...process.env, LC_ALL: 'C' }, + maxBuffer: 8 * 1024 * 1024, + }); + const children = new Map(); + let root; + for (const line of stdout.trim().split('\n')) { + const [pid, parent, rssKib, cpuPercent] = line.trim().split(/\s+/).map(Number); + const entry = { pid, rssKib, cpuPercent }; + if (pid === rootPid) root = entry; + const siblings = children.get(parent); + if (siblings) siblings.push(entry); + else children.set(parent, [entry]); + } + if (!root) return null; + + let rssKib = 0; + let cpuPercent = 0; + const tree = [root]; + for (const entry of tree) { + rssKib += entry.rssKib; + cpuPercent += entry.cpuPercent; + const descendants = children.get(entry.pid); + if (descendants) tree.push(...descendants); + } + return { rssKib, cpuPercent, processCount: tree.length }; +} + +async function collectOutput(stream, onLine) { + const chunks = []; + let bytes = 0; + let truncated = false; + stream.on('data', chunk => { + chunks.push(chunk); + bytes += chunk.length; + while (bytes > logLimit) { + truncated = true; + const excess = bytes - logLimit; + if (chunks[0].length <= excess) { + bytes -= chunks.shift().length; + } else { + chunks[0] = chunks[0].subarray(excess); + bytes -= excess; + } + } + }); + if (onLine) { + const lines = createInterface({ input: stream, crlfDelay: Infinity }); + for await (const line of lines) await onLine(line); + } else { + await finished(stream, { cleanup: true }); + } + return { text: Buffer.concat(chunks, bytes).toString('utf8'), truncated }; +} + +export async function runMonitoredProcess({ + command, args = [], cwd, env, stdinText, timeoutMs, sampleIntervalMs = 100, sigkillAfterMs, + onStdoutLine, onStderrLine, signal, +}) { + for (const [name, value, minimum] of [ + ['sampleIntervalMs', sampleIntervalMs, 1], + ['timeoutMs', timeoutMs, 0], + ['sigkillAfterMs', sigkillAfterMs, 0], + ]) { + if (value !== undefined && (!Number.isFinite(value) || value < minimum || value > 2 ** 31 - 1)) { + throw new RangeError(`Invalid ${name}: ${value}`); + } + } + if (stdinText !== undefined && typeof stdinText !== 'string') { + throw new TypeError('stdinText must be a string'); + } + signal?.throwIfAborted(); + const startNs = process.hrtime.bigint(); + const child = spawn(command, args, { + cwd, + env, + detached: true, + stdio: [stdinText === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], + }); + + const samples = []; + const sampling = new AbortController(); + let peakRssKib = 0; + let peakProcessCount = 0; + let endNs; + let failure; + let stdinError = null; + let termination = null; + let sampleTimer; + let sampleInFlight; + let timeout; + let injection; + + function kill() { + if (!child.pid) return; + try { + killGroup(child.pid); + } catch (error) { + failure ??= error; + } + } + + function fail(error) { + failure ??= error; + if (endNs === undefined) kill(); + } + + function terminate(reason) { + if (endNs !== undefined || termination || !child.pid) return; + termination = reason; + kill(); + } + + function abort() { + terminate('aborted'); + } + + function sample() { + const atNs = process.hrtime.bigint().toString(); + sampleInFlight = sampleTree(child.pid, sampling.signal).then(tree => { + if (!tree) return; + samples.push({ atNs, ...tree }); + peakRssKib = Math.max(peakRssKib, tree.rssKib); + peakProcessCount = Math.max(peakProcessCount, tree.processCount); + }).catch(error => { + if (!sampling.signal.aborted) fail(new Error('Could not sample child process tree', { cause: error })); + }).finally(() => { + if (!sampling.signal.aborted) sampleTimer = setTimeout(sample, sampleIntervalMs); + }); + } + + child.on('error', fail); + child.once('spawn', sample); + child.once('exit', () => { + endNs = process.hrtime.bigint(); + clearTimeout(timeout); + clearTimeout(injection); + clearTimeout(sampleTimer); + sampling.abort(); + // Descendants may still own the stdio pipes after the group leader exits. + kill(); + }); + const closed = new Promise(resolveClose => { + child.once('close', (code, signal) => resolveClose({ code, signal })); + }); + + const outputs = [ + [child.stdout, onStdoutLine], + [child.stderr, onStderrLine], + ].map(([stream, onLine]) => collectOutput(stream, onLine).catch(error => { + fail(error); + stream.resume(); + })); + if (child.stdin) { + child.stdin.on('error', error => { + stdinError = error.message; + if (error.code !== 'EPIPE' && error.code !== 'ERR_STREAM_DESTROYED') fail(error); + }); + child.stdin.end(stdinText); + } + if (timeoutMs !== undefined) timeout = setTimeout(() => terminate('timeout'), timeoutMs); + if (sigkillAfterMs !== undefined) injection = setTimeout(() => terminate('sigkill'), sigkillAfterMs); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + + try { + const [exit, stdout, stderr] = await Promise.all([closed, ...outputs]); + await sampleInFlight; + if (failure) throw failure; + return { + ...exit, + termination, + stdinError, + startNs: startNs.toString(), + endNs: endNs.toString(), + wallMs: Number(endNs - startNs) / 1e6, + peakRssKib, + peakProcessCount, + samples, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + }; + } finally { + clearTimeout(timeout); + clearTimeout(injection); + signal?.removeEventListener('abort', abort); + } +} diff --git a/tools/harness-bench/report.mjs b/tools/harness-bench/report.mjs new file mode 100644 index 00000000000..6d763cd0e9e --- /dev/null +++ b/tools/harness-bench/report.mjs @@ -0,0 +1,236 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +const sideChannelPurposes = new Set([ + 'title', 'probe', 'summary_aux', 'side', 'count_tokens', 'warmup', 'control', +]); + +function summarizeAttempts(items) { + const receiptRevisions = new Set(); + let newestRevision = 0; + let completedAttempts = 0; + let retries = 0; + let sideChannelCalls = 0; + for (const item of items) { + if (item.revision !== null) newestRevision = Math.max(newestRevision, item.revision); + if (item.outcome === 'completed') completedAttempts++; + if (item.retryReason !== null) retries++; + if (sideChannelPurposes.has(item.purpose)) sideChannelCalls++; + for (const id of item.confirmedCallIds) { + // The scenario emits call___. + const receipt = /^call_.+_(\d+)_\d+$/.exec(id); + if (!receipt) throw new Error(`Invalid mock-ai scenario call ID: ${id}`); + receiptRevisions.add(Number(receipt[1])); + } + } + let completedToolRounds = 0; + for (const revision of receiptRevisions) { + // One receipt from a parallel batch does not advance the scenario. + if (revision < newestRevision) completedToolRounds++; + } + return { completedAttempts, completedToolRounds, retries, sideChannelCalls }; +} + +function summarizePrompt(trajectory) { + let promptBytesPeak = null; + let promptBytesFinal = null; + for (const point of trajectory) { + if (point.purpose !== 'main') continue; + promptBytesFinal = point.effectiveContextBytes; + promptBytesPeak = Math.max(promptBytesPeak ?? 0, promptBytesFinal); + } + return { promptBytesPeak, promptBytesFinal }; +} + +export function reconcileLaneResult({ laneConfig, procResult, workspaceProof, sessionDetail }) { + const { scenario, track, harness, logicalLane, expectedToolRounds, minAttempts } = laneConfig; + const failures = []; + const cliPassed = procResult?.code === 0 && procResult.signal === null + && procResult.termination === null && !procResult.stdinError; + if (!cliPassed) { + const exit = procResult + ? procResult.termination ?? procResult.signal ?? `exit ${procResult.code}` + : 'missing process result'; + const input = procResult?.stdinError ? `, stdin: ${procResult.stdinError}` : ''; + failures.push(`CLI failed (${exit}${input})`); + } + + const workspacePassed = workspaceProof?.passed === true; + if (!workspacePassed) { + const evidence = workspaceProof?.errors?.slice(0, 3).join(', '); + failures.push(evidence ? `Workspace proof failed (${evidence})` : 'Workspace proof missing or failed'); + } + + const mockFailures = []; + const mock = {}; + if (sessionDetail) { + const { summary, items, violations, audit, attribution, registration } = sessionDetail; + Object.assign(mock, summarizeAttempts(items), summarizePrompt(attribution.promptBytesTrajectory), { + attempts: summary.attempts, + watchdogViolations: violations, + mockServiceSumMs: attribution.mockServiceSumNs / 1e6, + mockUnionMs: attribution.mockUnionNs / 1e6, + outsideMockWallMs: attribution.outsideMockWallNs / 1e6, + }); + + if (registration.scenario !== scenario || registration.harness !== harness + || (logicalLane !== undefined && registration.logicalLane !== logicalLane) + || (laneConfig.runId !== undefined && summary.runId !== laneConfig.runId) + || (laneConfig.sessionId !== undefined && summary.sessionId !== laneConfig.sessionId)) { + mockFailures.push('Mock session identity differs from the lane configuration'); + } + if (!summary.finalized || sessionDetail.scenarioCompleted !== true) { + mockFailures.push('Mock scenario completion unverified'); + } + if (summary.dropped !== 0 || items.length !== summary.attempts) { + mockFailures.push(`Mock attempt export incomplete (${items.length}/${summary.attempts} retained, ${summary.dropped} dropped)`); + } + if (audit?.auditIncomplete) mockFailures.push('Watchdog audit incomplete'); + if (violations.length > 0) mockFailures.push(`Watchdog reported ${violations.length} violation(s)`); + if (mock.completedAttempts === 0) mockFailures.push('No completed mock attempts'); + if (expectedToolRounds !== undefined && mock.completedToolRounds !== expectedToolRounds) { + mockFailures.push(`Completed tool rounds ${mock.completedToolRounds}/${expectedToolRounds}`); + } + if (minAttempts !== undefined && mock.attempts < minAttempts) { + mockFailures.push(`Mock attempts ${mock.attempts}/${minAttempts} minimum`); + } + } else { + mockFailures.push('Mock session detail missing'); + } + + const verifiedWork = workspacePassed && mockFailures.length === 0; + return { + scenario, + track, + harness, + logicalLane, + runId: sessionDetail?.summary.runId ?? laneConfig.runId, + sessionId: sessionDetail?.summary.sessionId ?? laneConfig.sessionId, + success: cliPassed && verifiedWork, + verifiedWork, + failures: [...failures, ...mockFailures], + wallMs: procResult?.wallMs ?? null, + peakRssMib: procResult?.peakRssKib > 0 ? procResult.peakRssKib / 1024 : null, + mockServiceSumMs: mock.mockServiceSumMs ?? null, + mockUnionMs: mock.mockUnionMs ?? null, + outsideMockWallMs: mock.outsideMockWallMs ?? null, + retries: mock.retries ?? null, + sideChannelCalls: mock.sideChannelCalls ?? null, + watchdogViolations: mock.watchdogViolations ?? null, + promptBytesPeak: mock.promptBytesPeak ?? null, + promptBytesFinal: mock.promptBytesFinal ?? null, + attempts: mock.attempts ?? null, + completedAttempts: mock.completedAttempts ?? null, + completedToolRounds: mock.completedToolRounds ?? null, + }; +} + +function distribution(records, field) { + const values = records.map(record => record[field]).filter(Number.isFinite).sort((a, b) => a - b); + const count = values.length; + if (count === 0) return { median: null, min: null, max: null, p95: null }; + const mid = Math.floor(count / 2); + return { + median: count % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2, + min: values[0], + max: values[count - 1], + p95: values[Math.ceil(count * 0.95) - 1], + }; +} + +export function aggregateComparison(runRecords) { + const groups = new Map(); + for (const record of runRecords) { + const key = JSON.stringify([record.scenario, record.track, record.harness]); + const group = groups.get(key); + if (group) group.push(record); + else groups.set(key, [record]); + } + return Array.from(groups.values(), records => { + const [{ scenario, track, harness }] = records; + const runs = records.length; + return { + scenario, + track, + harness, + runs, + successRate: records.filter(record => record.success).length / runs, + verifiedWorkRate: records.filter(record => record.verifiedWork).length / runs, + wallMs: distribution(records, 'wallMs'), + outsideMockWallMs: { median: distribution(records, 'outsideMockWallMs').median }, + mockUnionMs: { median: distribution(records, 'mockUnionMs').median }, + peakRssMib: { median: distribution(records, 'peakRssMib').median }, + watchdogViolationsTotal: records.reduce((sum, lane) => sum + (lane.watchdogViolations?.length ?? 0), 0), + retriesTotal: records.reduce((sum, lane) => sum + (lane.retries ?? 0), 0), + }; + }).sort((a, b) => a.scenario.localeCompare(b.scenario) || a.track.localeCompare(b.track) + || a.harness.localeCompare(b.harness)); +} + +function markdownText(value) { + return String(value).replace(/[\r\n]+/g, ' ').replace(/[\\|`*_\[\]<>]/g, '\\$&'); +} + +function measurement(value) { + return value === null ? '—' : value.toFixed(1); +} + +function rate(value) { + return `${(value * 100).toFixed(1)}%`; +} + +export function renderMarkdownReport(manifest, summary, lanes) { + const lines = ['# Harness benchmark', '']; + if (manifest.runId !== undefined) lines.push(`Run ${markdownText(manifest.runId)}`, ''); + if (summary.length === 0) lines.push('No benchmark runs recorded.'); + else { + lines.push( + '| Scenario | Track | Harness | Runs | Success | Verified work | Wall median (ms) | Wall min–max (ms) | Wall p95 (ms) | Outside mock median (ms) | Mock union median (ms) | Peak RSS median (MiB) | Retries | Violations |', + '| --- | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |', + ); + for (const row of summary) { + const range = row.wallMs.min === null ? '—' : `${measurement(row.wallMs.min)}–${measurement(row.wallMs.max)}`; + const cells = [ + markdownText(row.scenario), markdownText(row.track), markdownText(row.harness), row.runs, + rate(row.successRate), rate(row.verifiedWorkRate), measurement(row.wallMs.median), range, + measurement(row.wallMs.p95), measurement(row.outsideMockWallMs.median), + measurement(row.mockUnionMs.median), measurement(row.peakRssMib.median), + row.retriesTotal, row.watchdogViolationsTotal, + ]; + lines.push(`| ${cells.join(' | ')} |`); + } + } + + const failed = lanes.filter(lane => !lane.success || lane.watchdogViolations?.length > 0); + if (failed.length) { + lines.push('', '## Failures and violations', ''); + for (const lane of failed) { + const label = [lane.scenario, lane.track, lane.harness, lane.logicalLane, lane.sessionId] + .filter(value => value !== undefined).map(markdownText).join(' / '); + lines.push(`- ${label} — ${lane.failures.map(markdownText).join('. ')}`); + for (const violation of lane.watchdogViolations?.slice(0, 3) ?? []) { + lines.push(` - ${markdownText(violation.kind)} — ${markdownText(violation.detail).slice(0, 240)}`); + } + if (lane.watchdogViolations?.length > 3) { + lines.push(` - ${lane.watchdogViolations.length - 3} more violation(s)`); + } + } + } + return `${lines.join('\n')}\n`; +} diff --git a/tools/harness-bench/run.mjs b/tools/harness-bench/run.mjs new file mode 100644 index 00000000000..bc70d82720e --- /dev/null +++ b/tools/harness-bench/run.mjs @@ -0,0 +1,549 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { randomUUID } from 'node:crypto'; +import { mkdir, mkdtemp, readdir, realpath, rmdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { fileURLToPath } from 'node:url'; +import { parseArgs, stripVTControlCharacters } from 'node:util'; +import { getAdapter, listAdapters, probeAllAdapters } from './adapters.mjs'; +import { loadScenario, materializeWorkspace, verifyWorkspace } from './fixtures.mjs'; +import { MockAdminClient, resolveMockAiBinary, startMockAi } from './mock-client.mjs'; +import { runMonitoredProcess } from './proc-monitor.mjs'; +import { aggregateComparison, reconcileLaneResult, renderMarkdownReport } from './report.mjs'; + +const directory = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(directory, '../..'); +const builtIns = ['smoke-edit', 'concurrency-fanout', 'long-compaction', 'chaos-recovery', 'mcp-smoke-edit']; +const prompt = 'Complete the benchmark task in this workspace. Use the supplied tools to inspect, edit, and verify files as directed, then return the final answer with its requested markers.'; +const usage = [ + 'Usage: node tools/harness-bench/run.mjs [flags]', + ' preflight [--harnesses a,b] [--json]', + ' run --scenario --harnesses a,b [--lanes 1] [--runs 1]', + ' [--latency-profile instant|frontier|degraded] [--provider-dialect ]', + ' [--timeout-ms 120000] [--sigkill-after-ms ] [--resume-after-kill]', + ' calibrate [--scenario smoke-edit] [--lanes 16]', + ' matrix --harnesses a,b [--scenarios smoke-edit,concurrency-fanout,long-compaction,chaos-recovery,mcp-smoke-edit]', + ' [--lanes 1] [--runs 1]', + ' All commands that run lanes accept --mock-bin and --output .', +].join('\n'); + +const string = { type: 'string' }; +const boolean = { type: 'boolean' }; +const sharedOptions = { output: string, 'mock-bin': string, lanes: string }; +const commandOptions = { + preflight: { harnesses: string, json: boolean }, + run: { + ...sharedOptions, harnesses: string, scenario: string, runs: string, + 'latency-profile': string, 'provider-dialect': string, 'timeout-ms': string, + 'sigkill-after-ms': string, 'resume-after-kill': boolean, + }, + calibrate: { ...sharedOptions, scenario: string }, + matrix: { ...sharedOptions, harnesses: string, scenarios: string, runs: string }, +}; + +function csv(value, flag) { + const values = value?.split(',').map(item => item.trim()); + if (!values || values.some(item => !item) || new Set(values).size !== values.length) { + throw new Error('Expected a comma-separated list of distinct values for --' + flag); + } + return values; +} + +function integer(value, flag, fallback, minimum = 1) { + if (value === undefined) return fallback; + const number = Number(value); + if (!/^\d+$/.test(value) || number < minimum || number > 2 ** 31 - 1) { + throw new Error('Invalid --' + flag + ' value: ' + value); + } + return number; +} + +function json(path, data) { + return writeFile(path, JSON.stringify(data, null, 2) + '\n'); +} + +function diagnose(errors, stage, error) { + errors.push(stage + ': ' + (error instanceof Error ? error.message : String(error))); +} + +async function withOutput(path, run) { + if (path !== undefined) { + if (!path.trim()) throw new Error('--output requires a directory'); + await mkdir(path, { recursive: true, mode: 0o700 }); + } + const output = await realpath(path ?? await mkdtemp(join(tmpdir(), 'maka-harness-bench-'))); + const claim = join(output, '.running'); + await mkdir(claim); + try { + if ((await readdir(output)).some(entry => entry !== '.running')) { + throw new Error('Output directory must be empty: ' + output); + } + console.log('Artifacts: ' + output); + return await run(output); + } finally { + await rmdir(claim); + } +} + +async function scenarioConfig(value) { + if (!value?.trim()) throw new Error('--scenario requires a built-in name or JSON path'); + const path = builtIns.includes(value) ? join(directory, 'scenarios', value + '.json') : resolve(value); + const source = await loadScenario(path); + return { path, source }; +} + +async function preflight(values) { + const filter = values.harnesses === undefined ? undefined : csv(values.harnesses, 'harnesses'); + const adapters = new Map(listAdapters().map(adapter => [adapter.id, adapter])); + const probes = await probeAllAdapters({ repoRoot, filter }); + const results = probes.map(({ id, binaryPath, version, ...probe }) => { + const { supportedTracks, protocol, launchMode } = adapters.get(id); + return { id, binaryPath: binaryPath ?? null, version: version ?? null, supportedTracks, protocol, launchMode, ...probe }; + }); + if (values.json) console.log(JSON.stringify(results, null, 2)); + else { + for (const probe of results) { + const label = probe.id + ' [' + probe.supportedTracks.join(', ') + ']'; + if (probe.available) console.log(label + ' ' + probe.binaryPath + ' (' + probe.version + ')'); + else { + const reason = probe.reason.split('\n')[0]; + console.log(label + ' unavailable' + (probe.binaryPath ? ' at ' + probe.binaryPath : '') + + '\n ' + reason + (reason.includes(probe.installHint) ? '' : '\n ' + probe.installHint)); + } + } + } +} + +async function prepareLane({ output, adapter, spec, mock, admin, repeat, laneIndex, runId, options }) { + const sessionId = randomUUID(); + const logicalLane = 'lane-' + (laneIndex + 1); + const artifactDir = join('repeat-' + (repeat + 1), adapter.id, logicalLane); + const laneDir = join(output, artifactDir); + const workspaceDir = join(laneDir, 'workspace'); + const isolatedDir = join(laneDir, 'isolated'); + const mcpAuditPath = spec.track === 'sharedMcp' ? join(laneDir, 'mcp-audit.jsonl') : undefined; + const identity = { runId, sessionId, harness: adapter.id, logicalLane, scenario: spec.scenario }; + const lane = { identity, laneDir, artifactDir, workspaceDir, mcpAuditPath, errors: [] }; + try { + await mkdir(laneDir, { recursive: true, mode: 0o700 }); + lane.initialManifest = await materializeWorkspace(spec, workspaceDir); + await mkdir(isolatedDir, { mode: 0o700 }); + await admin.registerSession({ + ...identity, launchMode: adapter.launchMode, workspace: workspaceDir, + }); + lane.registered = true; + const context = { + ...identity, repoRoot, prompt, track: spec.track, workspace: workspaceDir, isolatedDir, + scopedOrigin: mock.baseUrl, apiKey: 'maka-benchmark-' + sessionId, mcpAuditPath, + resumeAfterKill: options.resumeAfterKill, + }; + if (adapter.startDaemon) lane.daemon = await adapter.startDaemon(context); + lane.invocation = await adapter.prepareInvocation({ ...context, daemonState: lane.daemon }); + } catch (error) { + diagnose(lane.errors, 'Lane setup', error); + } + return lane; +} + +async function finalizeWhenIdle(admin, sessionId, proof) { + const deadline = performance.now() + 2000; + while (true) { + try { + return await admin.finalizeSession(sessionId, proof); + } catch (error) { + // A killed client can exit before the server drops its response body. + if (error.status !== 409 || !error.body.includes('in-flight attempts') || performance.now() >= deadline) throw error; + await delay(20); + } + } +} + +async function exportSession(lane, admin, finalStep, observedMarkers) { + const { sessionId } = lane.identity; + const detailPath = join(lane.laneDir, 'mock-session.json'); + const preliminary = await admin.getSessionDetailAll(sessionId); + const response = preliminary.items.findLast(item => item.stepId === finalStep.id + && item.purpose === 'main' && item.outcome === 'completed' && item.responseId); + const markers = finalStep.finalAnswer.expectMarkers ?? []; + const proof = response && observedMarkers.length === markers.length + ? { responseId: response.responseId, observedMarkers } : undefined; + let finalization; + // Even unsuccessful lanes must export and release their mock session. + if (proof) { + try { + finalization = await finalizeWhenIdle(admin, sessionId, proof); + } catch (error) { + if (error.status !== 422) throw error; + diagnose(lane.errors, 'Mock rejected completion proof', error); + } + } + try { + finalization ??= await finalizeWhenIdle(admin, sessionId); + const detail = await admin.getSessionDetailAll(sessionId, { finalization }); + await json(detailPath, { ...detail, completionProof: detail.scenarioCompleted ? proof : null }); + lane.sessionDetail = detail; + lane.completionProof = detail.scenarioCompleted ? proof : null; + lane.deletion = await admin.deleteSession(sessionId, { cursor: finalization.cursor, after: detail.nextCursor }); + if (lane.deletion.deleted !== true) throw new Error('Mock did not acknowledge session deletion'); + } catch (error) { + if (!lane.sessionDetail) await json(detailPath, { ...preliminary, completionProof: null }); + throw error; + } +} + +async function executeLane(lane, { admin, adapter, spec, options, signal }) { + const { laneDir } = lane; + const segments = []; + let proc; + let agentOutputText = ''; + try { + if (lane.invocation) { + proc = await runMonitoredProcess({ + ...lane.invocation, signal, timeoutMs: options.timeoutMs, sigkillAfterMs: options.sigkillAfterMs, + }); + segments.push(proc); + if (options.sigkillAfterMs !== undefined && proc.termination !== 'sigkill') { + lane.errors.push('Scheduled SIGKILL did not occur'); + } + if (proc.termination === 'sigkill' && options.resumeAfterKill) { + proc = await runMonitoredProcess({ ...lane.invocation, signal, timeoutMs: options.timeoutMs }); + segments.push(proc); + } + // Only the final invocation can supply completion markers after a restart. + agentOutputText = stripVTControlCharacters(proc.stdout); + } + } catch (error) { + proc = null; + diagnose(lane.errors, 'Lane process', error); + } finally { + if (lane.daemon) { + try { + await adapter.stopDaemon(lane.daemon); + } catch (error) { + diagnose(lane.errors, 'Daemon shutdown', error); + } + } + } + const processEvidence = await Promise.all(segments.map(async ({ stdout, stderr, ...metrics }, index) => { + const prefix = 'segment-' + (index + 1); + const stdoutLog = prefix + '.stdout.log'; + const stderrLog = prefix + '.stderr.log'; + const writes = await Promise.allSettled([writeFile(join(laneDir, stdoutLog), stdout), writeFile(join(laneDir, stderrLog), stderr)]); + for (const write of writes) { + if (write.status === 'rejected') diagnose(lane.errors, 'Process log write', write.reason); + } + return { ...metrics, stdoutLog, stderrLog }; + })); + + let workspaceProof; + if (lane.initialManifest) { + try { + workspaceProof = await verifyWorkspace(spec, { + workspaceDir: lane.workspaceDir, initialManifest: lane.initialManifest, + agentOutputText, mcpAuditPath: lane.mcpAuditPath, + }); + } catch (error) { + diagnose(lane.errors, 'Workspace verification', error); + } + } + + const finalStep = spec.steps.at(-1); + const observedMarkers = (finalStep.finalAnswer.expectMarkers ?? []) + .filter(marker => agentOutputText.includes(marker)); + if (lane.registered) { + try { + await exportSession(lane, admin, finalStep, observedMarkers); + } catch (error) { + diagnose(lane.errors, 'Mock session export or cleanup', error); + } + } + const sessionDetail = lane.sessionDetail; + const toolRounds = spec.steps.filter(step => !step.finalAnswer && !step.triggerCompaction + && ![step.badToolCall, step.unknownTool].some(action => action && action.expectHandling !== 'toolError')); + const result = reconcileLaneResult({ + laneConfig: { ...lane.identity, track: spec.track, expectedToolRounds: toolRounds.length }, + procResult: proc && { + ...proc, + wallMs: segments.reduce((sum, segment) => sum + segment.wallMs, 0), + peakRssKib: Math.max(...segments.map(segment => segment.peakRssKib)), + }, + workspaceProof, + sessionDetail, + }); + if (workspaceProof?.mcpAudit && sessionDetail) { + const confirmedCalls = new Set(sessionDetail.items.flatMap(item => item.confirmedCallIds)).size; + if (confirmedCalls !== workspaceProof.mcpAudit.calls) { + result.verifiedWork = false; + lane.errors.push('MCP audit has ' + workspaceProof.mcpAudit.calls + ' calls but mock confirmed ' + confirmedCalls); + } + } + result.failures.push(...lane.errors); + result.success &&= result.failures.length === 0; + const record = { + ...result, artifacts: lane.artifactDir, + mockCompleted: sessionDetail?.scenarioCompleted === true, sessionDeleted: lane.deletion?.deleted === true, + }; + await json(join(laneDir, 'lane.json'), { + ...record, process: processEvidence, workspaceProof, observedMarkers, completionProof: lane.completionProof, + }); + return { + record, + firstStart: segments[0]?.startNs, + lastEnd: segments.at(-1)?.endNs, + }; +} + +async function benchmark({ scenario, adapters, output, options, signal, calibrate }) { + const { source: spec, path } = scenario; + const runId = randomUUID(); + const candidates = adapters.map(({ id, protocol, launchMode, supportedTracks }) => ({ id, protocol, launchMode, supportedTracks })); + const batches = []; + for (let repeat = 0; repeat < options.runs; repeat++) { + for (let index = 0; index < adapters.length; index++) { + batches.push({ repeat, harness: adapters[(repeat + index) % adapters.length].id }); + } + } + const manifest = { + runId, scenario: spec.scenario, track: spec.track, scenarioPath: path, + startedAt: new Date().toISOString(), candidates, batches, ...options, mockBinary: null, + }; + const records = []; + let calibration; + const errors = []; + const server = {}; + let mock; + let admin; + try { + manifest.mockBinary = resolveMockAiBinary(repoRoot, options.mockBin); + mock = await startMockAi({ + binary: manifest.mockBinary, scenarioPath: path, + latencyProfile: options.latencyProfile, providerDialect: options.providerDialect, + }); + server.origin = mock.baseUrl; + admin = new MockAdminClient(mock.baseUrl); + if (calibrate) server.metricsBefore = await admin.metrics(); + for (const { repeat, harness } of batches) { + signal.throwIfAborted(); + const adapter = getAdapter(harness); + const lanes = await Promise.all(Array.from({ length: options.lanes }, (_, laneIndex) => + prepareLane({ output, adapter, spec, mock, admin, repeat, laneIndex, runId, options }))); + const finished = await Promise.allSettled(lanes.map(lane => executeLane(lane, { admin, adapter, spec, options, signal }))); + const starts = []; + const ends = []; + for (const [index, lane] of finished.entries()) { + if (lane.status === 'fulfilled') { + records.push(lane.value.record); + if (lane.value.firstStart) starts.push(BigInt(lane.value.firstStart)); + if (lane.value.lastEnd) ends.push(BigInt(lane.value.lastEnd)); + } else { + diagnose(errors, 'Could not record ' + lanes[index].artifactDir, lane.reason); + } + } + if (calibrate && starts.length) { + const start = starts.reduce((min, ns) => ns < min ? ns : min); + const end = ends.reduce((max, ns) => ns > max ? ns : max); + const wallMs = Number(end - start) / 1e6; + const verifiedLanes = records.filter(row => row.success).length; + calibration = { wallMs, verifiedLanes, verifiedLanesPerSecond: 1000 * verifiedLanes / wallMs }; + } + } + } catch (error) { + diagnose(errors, 'Benchmark', error); + } finally { + if (admin) { + try { + [server.metrics, server.sessionsAfterCleanup, server.watchdog] = await Promise.all([ + admin.metrics(), admin.listSessions({ run: runId }), admin.violations(), + ]); + if (server.sessionsAfterCleanup.items.length) errors.push('Mock still has sessions after cleanup'); + const exportedViolations = records.reduce((total, row) => total + (row.watchdogViolations?.length ?? 0), 0); + if (server.watchdog.totalViolations > exportedViolations) { + errors.push('Mock recorded watchdog violations outside the exported lane diagnostics'); + } + } catch (error) { + diagnose(errors, 'Mock metrics or cleanup check', error); + } + } + if (mock) { + try { + server.exit = await mock.stop(); + if (server.exit.code !== 0) errors.push('Mock shutdown failed: ' + (server.exit.signal ?? server.exit.code)); + } catch (error) { + diagnose(errors, 'Mock shutdown', error); + } + } + } + + const summary = aggregateComparison(records); + const results = { runId, lanes: records, summary, server, errors, calibration }; + let report = renderMarkdownReport(manifest, summary, records); + if (calibrate && calibration) { + report += '\n## Calibration\n\n' + calibration.verifiedLanesPerSecond.toFixed(2) + + ' verified lanes/s over the ' + calibration.wallMs.toFixed(1) + + ' ms batch process window.\n'; + if (server.metrics) { + const { totalRequests, ttftMs, turnDurationMs, abandonedStreams } = server.metrics; + report += '\nMock handled ' + (totalRequests - server.metricsBefore.totalRequests) + + ' model requests with p95 TTFT of ' + ttftMs.p95 + ' ms, p95 turn duration of ' + + turnDurationMs.p95 + ' ms and ' + abandonedStreams + ' abandoned streams. ' + + 'Full metrics snapshots are in results.json.\n'; + } + } + if (errors.length) report += '\n## Run errors\n\n' + errors.map(error => '- ' + error).join('\n') + '\n'; + await Promise.all([ + json(join(output, 'manifest.json'), manifest), + json(join(output, 'results.json'), results), + writeFile(join(output, 'report.md'), report), + ]); + return { + summary, calibration, + passed: errors.length === 0 && records.length === batches.length * options.lanes && records.every(row => row.success), + }; +} + +const markdown = value => String(value).replace(/\|/g, '\\|').replace(/[\r\n]/g, ' '); +const ms = value => value == null ? '—' : value.toFixed(1); + +function overview(rows) { + const lines = [ + '| Scenario | Track | Adapter | Result | Wall ms (median) | Mock union ms | Outside mock ms |', + '| --- | --- | --- | --- | ---: | ---: | ---: |', + ]; + for (const { scenario, track, harness, result, summary } of rows) { + lines.push('| ' + [ + scenario, track, harness, result, + ms(summary?.wallMs.median), ms(summary?.mockUnionMs.median), ms(summary?.outsideMockWallMs.median), + ].map(markdown).join(' | ') + ' |'); + } + return lines.join('\n'); +} + +function overviewRow(scenario, track, harness, summary) { + const result = summary + ? Math.round(summary.runs * summary.successRate) + '/' + summary.runs + ' passed' : 'Failed'; + return { scenario, track, harness, result, summary }; +} + +async function matrix({ scenarios, adapters, output, options, signal }) { + const rows = []; + const links = []; + let passed = true; + for (const [index, scenario] of scenarios.entries()) { + if (signal.aborted) { + passed = false; + break; + } + const { scenario: name, track } = scenario.source; + const compatible = adapters.filter(adapter => adapter.supportedTracks.includes(track)); + const folder = 'scenario-' + (index + 1); + let summary = []; + if (compatible.length) { + const scenarioOutput = join(output, folder); + await mkdir(scenarioOutput); + const result = await benchmark({ scenario, adapters: compatible, output: scenarioOutput, options, signal }); + summary = result.summary; + passed &&= result.passed; + links.push('- ' + markdown(name) + ' [' + folder + '/report.md](' + folder + '/report.md)' + + (result.passed ? '' : ' (failed)')); + } + for (const adapter of adapters) { + const row = overviewRow(name, track, adapter.id, summary.find(item => item.harness === adapter.id)); + if (!adapter.supportedTracks.includes(track)) row.result = 'N/A (unsupported track)'; + rows.push(row); + } + } + const table = overview(rows); + await writeFile(join(output, 'matrix-report.md'), '# Harness benchmark matrix\n\n' + table + + '\n\n' + links.join('\n') + '\n'); + console.log(table); + return passed; +} + +async function main(args, signal) { + const [command, ...tokens] = args; + if (!command || ['-h', '--help', 'help'].includes(command)) { + console.log(usage); + return true; + } + if (!Object.hasOwn(commandOptions, command)) throw new Error('Unknown command ' + command + '\n' + usage); + const { values } = parseArgs({ args: tokens, options: { ...commandOptions[command], help: boolean } }); + if (values.help) { + console.log(usage); + return true; + } + if (command === 'preflight') { + await preflight(values); + return true; + } + + const calibrate = command === 'calibrate'; + const adapters = calibrate ? [getAdapter('ref-agent')] : csv(values.harnesses, 'harnesses').map(getAdapter); + const options = { + lanes: integer(values.lanes, 'lanes', calibrate ? 16 : 1), + runs: integer(values.runs, 'runs', 1), + timeoutMs: integer(values['timeout-ms'], 'timeout-ms', 120_000), + sigkillAfterMs: integer(values['sigkill-after-ms'], 'sigkill-after-ms', undefined, 0), + resumeAfterKill: values['resume-after-kill'] ?? false, + latencyProfile: values['latency-profile'] ?? 'instant', + providerDialect: values['provider-dialect'], + mockBin: values['mock-bin'], + }; + if (options.resumeAfterKill && options.sigkillAfterMs === undefined) { + throw new Error('--resume-after-kill requires --sigkill-after-ms'); + } + if (options.sigkillAfterMs >= options.timeoutMs) throw new Error('--sigkill-after-ms must be less than --timeout-ms'); + if (command === 'matrix') { + const names = values.scenarios === undefined ? builtIns : csv(values.scenarios, 'scenarios'); + const scenarios = await Promise.all(names.map(scenarioConfig)); + return withOutput(values.output, output => matrix({ scenarios, adapters, output, options, signal })); + } + + const scenario = await scenarioConfig(values.scenario ?? (calibrate ? 'smoke-edit' : undefined)); + for (const adapter of adapters) { + if (!adapter.supportedTracks.includes(scenario.source.track)) { + throw new Error(adapter.id + ' does not support track ' + scenario.source.track); + } + } + return withOutput(values.output, async output => { + const result = await benchmark({ scenario, adapters, output, options, signal, calibrate }); + console.log(overview(adapters.map(adapter => overviewRow( + scenario.source.scenario, scenario.source.track, adapter.id, + result.summary.find(row => row.harness === adapter.id), + )))); + if (result.calibration) console.log(result.calibration.verifiedLanesPerSecond.toFixed(2) + ' verified lanes/s'); + return result.passed; + }); +} + +const stop = new AbortController(); +const interrupt = () => stop.abort(new Error('Benchmark interrupted')); +process.on('SIGINT', interrupt); +process.on('SIGTERM', interrupt); +try { + process.exitCode = await main(process.argv.slice(2), stop.signal) && !stop.signal.aborted ? 0 : 1; +} catch (error) { + console.error(error.message); + process.exitCode = 1; +} finally { + process.off('SIGINT', interrupt); + process.off('SIGTERM', interrupt); +} diff --git a/tools/harness-bench/scenarios/chaos-recovery.json b/tools/harness-bench/scenarios/chaos-recovery.json new file mode 100644 index 00000000000..42fad13a9f0 --- /dev/null +++ b/tools/harness-bench/scenarios/chaos-recovery.json @@ -0,0 +1,67 @@ +{ + "version": 1, + "scenario": "chaos-recovery", + "seed": 41004, + "fixture": "chaos-recovery-v1", + "track": "native", + "fixtures": { + "input": { + "kind": "file", + "path": "artifacts/input.txt", + "content": "recovery-token=783b\n" + }, + "verifyBatch": { + "kind": "command", + "command": "grep -Fx -- 'state=started' 'artifacts/recovery.txt'" + }, + "verifyDone": { + "kind": "command", + "command": "grep -Fx -- 'state=recovered' 'artifacts/recovery.txt'" + } + }, + "steps": [ + { + "id": "read", + "readFile": { "path": "artifacts/input.txt", "expectMarker": "recovery-token=783b" } + }, + { + "id": "write", + "writeFile": { "path": "artifacts/recovery.txt", "content": "state=started\n" } + }, + { + "id": "interrupted-check", + "parallelBatch": [ + { "readFile": { "path": "artifacts/recovery.txt", "expectMarker": "state=started" } }, + { "shell": { "commandId": "verifyBatch" } } + ] + }, + { + "id": "bad-arguments", + "badToolCall": { "mode": "wrongType", "expectHandling": "toolError" } + }, + { + "id": "unknown-tool", + "unknownTool": { "name": "bench_unlisted_recovery_tool", "expectHandling": "toolError" } + }, + { + "id": "recover", + "editFile": { "path": "artifacts/recovery.txt", "old": "state=started", "new": "state=recovered" } + }, + { + "id": "verify", + "shell": { "commandId": "verifyDone" } + }, + { + "id": "done", + "finalAnswer": { + "text": "CHAOS_RECOVERY_OK: artifacts/recovery.txt records recovery.", + "expectMarkers": ["CHAOS_RECOVERY_OK"] + } + } + ], + "faults": [ + { "step": "read", "attempt": 1, "at": "beforeHeaders", "emit": "http429" }, + { "step": "write", "attempt": 1, "at": "beforeHeaders", "emit": "http503" }, + { "step": "interrupted-check", "attempt": 1, "at": "afterFirstCompleteCall", "emit": "disconnect" } + ] +} diff --git a/tools/harness-bench/scenarios/concurrency-fanout.json b/tools/harness-bench/scenarios/concurrency-fanout.json new file mode 100644 index 00000000000..025927fffe3 --- /dev/null +++ b/tools/harness-bench/scenarios/concurrency-fanout.json @@ -0,0 +1,58 @@ +{ + "version": 1, + "scenario": "concurrency-fanout", + "seed": 41002, + "fixture": "concurrency-fanout-v1", + "track": "native", + "fixtures": { + "input": { + "kind": "file", + "path": "artifacts/input.txt", + "content": "source=fanout\n" + }, + "verifyFirst": { + "kind": "command", + "command": "grep -Fx -- 'stage=running' 'artifacts/lane.txt'" + }, + "verifyDone": { + "kind": "command", + "command": "grep -Fx -- 'stage=verified' 'artifacts/lane.txt'" + } + }, + "steps": [ + { + "id": "read", + "readFile": { "path": "artifacts/input.txt", "expectMarker": "source=fanout" } + }, + { + "id": "write", + "writeFile": { "path": "artifacts/lane.txt", "content": "stage=queued\nsource=fanout\n" } + }, + { + "id": "start", + "editFile": { "path": "artifacts/lane.txt", "old": "stage=queued", "new": "stage=running" } + }, + { + "id": "check-start", + "parallelBatch": [ + { "readFile": { "path": "artifacts/lane.txt", "expectMarker": "stage=running" } }, + { "shell": { "commandId": "verifyFirst" } } + ] + }, + { + "id": "finish", + "editFile": { "path": "artifacts/lane.txt", "old": "stage=running", "new": "stage=verified" } + }, + { + "id": "verify", + "shell": { "commandId": "verifyDone" } + }, + { + "id": "done", + "finalAnswer": { + "text": "FANOUT_OK: artifacts/lane.txt reached the verified stage.", + "expectMarkers": ["FANOUT_OK"] + } + } + ] +} diff --git a/tools/harness-bench/scenarios/long-compaction.json b/tools/harness-bench/scenarios/long-compaction.json new file mode 100644 index 00000000000..2b9551049e2 --- /dev/null +++ b/tools/harness-bench/scenarios/long-compaction.json @@ -0,0 +1,50 @@ +{ + "version": 1, + "scenario": "long-compaction", + "seed": 41003, + "fixture": "long-compaction-v1", + "track": "native", + "fixtures": { + "checkpoint": { + "kind": "file", + "path": "state/handoff.txt", + "content": "fact=handoff-ticket-6f32\nstate=pending\n" + }, + "transcript": { + "kind": "largeOutput", + "pattern": "benchmark transcript segment with no handoff data" + } + }, + "steps": [ + { + "id": "read-fact", + "readFile": { "path": "state/handoff.txt", "expectMarker": "handoff-ticket-6f32" } + }, + { + "id": "fill-context", + "largeOutput": { "fixture": "transcript", "bytes": 131072 } + }, + { + "id": "compact", + "triggerCompaction": { + "mode": { "contextOverflow": { "actualBytes": 131072, "limitBytes": 65536 } }, + "proofMarker": "handoff-ticket-6f32" + } + }, + { + "id": "read-retained-fact", + "readFile": { "path": "state/handoff.txt", "expectMarker": "handoff-ticket-6f32" } + }, + { + "id": "record-handoff", + "editFile": { "path": "state/handoff.txt", "old": "state=pending", "new": "state=recovered" } + }, + { + "id": "done", + "finalAnswer": { + "text": "COMPACTION_OK: handoff-ticket-6f32 was recovered.", + "expectMarkers": ["COMPACTION_OK", "handoff-ticket-6f32"] + } + } + ] +} diff --git a/tools/harness-bench/scenarios/mcp-smoke-edit.json b/tools/harness-bench/scenarios/mcp-smoke-edit.json new file mode 100644 index 00000000000..20edf52d8ad --- /dev/null +++ b/tools/harness-bench/scenarios/mcp-smoke-edit.json @@ -0,0 +1,47 @@ +{ + "version": 1, + "scenario": "mcp-smoke-edit", + "seed": 41001, + "fixture": "smoke-edit-v1", + "track": "sharedMcp", + "fixtures": { + "source": { + "kind": "file", + "path": "src/lib.rs", + "content": "pub fn status() -> &'static str {\n \"pending\"\n}\n" + }, + "readme": { + "kind": "file", + "path": "README.md", + "content": "# Smoke edit fixture\n" + }, + "verify": { + "kind": "command", + "command": "grep -Fx -- ' \"ready\"' 'src/lib.rs'" + } + }, + "steps": [ + { + "id": "read", + "readFile": { "path": "src/lib.rs", "expectMarker": "\"pending\"" } + }, + { + "id": "edit", + "editFile": { "path": "src/lib.rs", "old": "\"pending\"", "new": "\"ready\"" } + }, + { + "id": "check", + "parallelBatch": [ + { "readFile": { "path": "src/lib.rs", "expectMarker": "\"ready\"" } }, + { "shell": { "commandId": "verify" } } + ] + }, + { + "id": "done", + "finalAnswer": { + "text": "SMOKE_EDIT_OK: src/lib.rs now reports ready.", + "expectMarkers": ["SMOKE_EDIT_OK"] + } + } + ] +} diff --git a/tools/harness-bench/scenarios/smoke-edit.json b/tools/harness-bench/scenarios/smoke-edit.json new file mode 100644 index 00000000000..9fe3237f8a8 --- /dev/null +++ b/tools/harness-bench/scenarios/smoke-edit.json @@ -0,0 +1,47 @@ +{ + "version": 1, + "scenario": "smoke-edit", + "seed": 41001, + "fixture": "smoke-edit-v1", + "track": "native", + "fixtures": { + "source": { + "kind": "file", + "path": "src/lib.rs", + "content": "pub fn status() -> &'static str {\n \"pending\"\n}\n" + }, + "readme": { + "kind": "file", + "path": "README.md", + "content": "# Smoke edit fixture\n" + }, + "verify": { + "kind": "command", + "command": "grep -Fx -- ' \"ready\"' 'src/lib.rs'" + } + }, + "steps": [ + { + "id": "read", + "readFile": { "path": "src/lib.rs", "expectMarker": "\"pending\"" } + }, + { + "id": "edit", + "editFile": { "path": "src/lib.rs", "old": "\"pending\"", "new": "\"ready\"" } + }, + { + "id": "check", + "parallelBatch": [ + { "readFile": { "path": "src/lib.rs", "expectMarker": "\"ready\"" } }, + { "shell": { "commandId": "verify" } } + ] + }, + { + "id": "done", + "finalAnswer": { + "text": "SMOKE_EDIT_OK: src/lib.rs now reports ready.", + "expectMarkers": ["SMOKE_EDIT_OK"] + } + } + ] +} diff --git a/tools/mock-ai/Cargo.toml b/tools/mock-ai/Cargo.toml index b9a08659a9f..f49862ba449 100644 --- a/tools/mock-ai/Cargo.toml +++ b/tools/mock-ai/Cargo.toml @@ -58,6 +58,7 @@ futures-util.workspace = true http-body-util = "0.1.5" hyper = { version = "1.13.0", features = ["server", "http1"] } hyper-util = { version = "0.1.21", features = ["tokio"] } +jsonschema.workspace = true regex = { workspace = true, optional = true } reqwest = { workspace = true, features = ["stream"], optional = true } rustls-pemfile = { version = "2.2.0", optional = true } diff --git a/tools/mock-ai/README.md b/tools/mock-ai/README.md index 8b3c3550ed6..b9479c79693 100644 --- a/tools/mock-ai/README.md +++ b/tools/mock-ai/README.md @@ -65,3 +65,49 @@ cargo run -p maka-mock-ai --bin maka-mock-ai -- \ cargo run -p maka-mock-ai --bin maka-mock-ai -- \ --replay ./trace.ndjson --replay-speed 10 --replay-match fingerprint ``` + +## Benchmark Mode + +Pass a JSON or YAML [scenario spec](src/scenario/mod.rs) to script the same workload across harnesses. +Scenario mode enables strict session routing and the Admin API. Pass +`--strict-benchmark` on its own to require session routing with a different workload. + +```bash +cargo run -p maka-mock-ai --bin maka-mock-ai -- \ + --listen 127.0.0.1:4014 --scenario ./scenario.yaml --strict-benchmark +``` + +Register each lane before launching its harness. Give it a unique session ID and a +logical lane name within the run. In scenario mode, use the scenario name from the spec +and the absolute path to the lane's fixture workspace. + +```bash +origin=http://127.0.0.1:4014 +curl -fsS "$origin/admin/sessions" -H 'Content-Type: application/json' \ + -d '{"runId":"run-1","sessionId":"lane-01","logicalLane":"01","harness":"codex","scenario":"tool-chain","workspace":"/absolute/path/to/fixture"}' +``` + +Set the harness base URL to `http://127.0.0.1:4014/s/run-1/lane-01/v1`. +The `/s//` prefix also works for Responses WebSocket and the +provider control endpoints. Keep `/admin/` and `/metrics` on the server origin. + +| Provider endpoint | Use | +| --- | --- | +| `GET /v1/models/{id}` | Fetch metadata for a configured model. | +| `POST /v1/messages/count_tokens` | Estimate input tokens for an Anthropic Messages payload. | +| `POST /v1/responses/compact` | Compact Responses input and return a checkpoint for the next turn. | +| `GET /v1/responses/{id}` and `DELETE /v1/responses/{id}` | Read or delete a stored response from its owning session. A response created with `store: false` is unavailable to GET. | + +Export benchmark telemetry through the origin Admin API. + +| Admin endpoint | Use | +| --- | --- | +| `GET /admin/sessions?run=run-1&limit=100` | List session summaries. Pass the returned `nextCursor` as `cursor` for the next page until it is null. | +| `POST /admin/sessions/{id}/finalize` | Close the session after its requests finish. For scenario completion verification, send `{"responseId":"…","observedMarkers":["…"]}`. | +| `GET /admin/sessions/{id}?limit=100&after=0` | Export attempt spans, attribution, and watchdog diagnostics. Resume with `after=nextCursor` until `nextCursor` equals `summary.attempts`, including any reported dropped attempts. | +| `DELETE /admin/sessions/{id}?cursor=&after=` | Reclaim a finalized session after export. Use `summary.cursor` for the first value and the final `nextCursor` for the second. | + +Attribution reports `mockServiceSumNs` across attempts, `mockUnionNs` for the +wall time covered by at least one attempt, and `outsideMockWallNs` for the rest +of the session window. `POST /admin/reset` returns `409` while benchmark sessions +remain registered. diff --git a/tools/mock-ai/src/codec/anthropic.rs b/tools/mock-ai/src/codec/anthropic.rs index c85cdaa14df..91448fb64e3 100644 --- a/tools/mock-ai/src/codec/anthropic.rs +++ b/tools/mock-ai/src/codec/anthropic.rs @@ -17,9 +17,14 @@ * under the License. */ -use super::{TurnCompletion, WireEncoder, WireFrame, split_utf8_chunks, sse_named}; -use crate::plan::{FinishReason, NativeToolEvent, TurnEvent, Usage}; +use super::{ + EncodedFrame, EventFrames, FrameKind, StringField, TurnCompletion, WireEncoder, WireFrame, + chunk_frames, split_utf8_chunks, +}; +use crate::plan::{Citation, FinishReason, NativeToolEvent, ToolCallPayload, TurnEvent, TurnUsage}; +use serde::Serialize; use serde_json::{Value, json}; +use std::borrow::Cow; pub struct AnthropicEncoder { id: String, @@ -27,26 +32,95 @@ pub struct AnthropicEncoder { stream: bool, started: bool, finished: bool, - errored: bool, - next_index: usize, - active_block: Option, - completed_blocks: Vec, - usage: Usage, + paused: bool, + error: Option, + active: Option, + blocks: Vec, + usage: TurnUsage, } enum ActiveBlock { Text { - index: usize, text: String, citations: Vec, }, Thinking { - index: usize, - thinking: String, + text: String, signature: Option, }, } +fn frame( + event: &str, + value: &impl Serialize, + kind: FrameKind, + semantic_bytes: usize, +) -> EncodedFrame { + EncodedFrame::new_sse(Some(event), value, kind, semantic_bytes) +} + +fn block_start(index: usize, block: &Value, kind: FrameKind, bytes: usize) -> EncodedFrame { + frame( + "content_block_start", + &json!({ + "type": "content_block_start", "index": index, "content_block": block, + }), + kind, + bytes, + ) +} + +fn block_stop(index: usize) -> EncodedFrame { + frame( + "content_block_stop", + &json!({ "type": "content_block_stop", "index": index }), + FrameKind::Lifecycle, + 0, + ) +} + +fn block_delta( + index: usize, + kind: &str, + field: &str, + chunk: &str, + semantic_bytes: usize, +) -> EncodedFrame { + #[derive(Serialize)] + struct Delta<'a> { + #[serde(rename = "type")] + kind: &'a str, + #[serde(flatten)] + data: StringField<'a>, + } + #[derive(Serialize)] + struct BlockDelta<'a> { + #[serde(rename = "type")] + kind: &'a str, + index: usize, + delta: Delta<'a>, + } + + let kind_on_wire = if semantic_bytes == 0 { + FrameKind::Lifecycle + } else { + FrameKind::SemanticDelta + }; + frame( + "content_block_delta", + &BlockDelta { + kind: "content_block_delta", + index, + delta: Delta { + kind, + data: StringField(field, chunk), + }, + }, + kind_on_wire, + semantic_bytes, + ) +} + impl AnthropicEncoder { pub fn new(id: String, model: String, stream: bool) -> Self { Self { @@ -55,608 +129,499 @@ impl AnthropicEncoder { stream, started: false, finished: false, - errored: false, - next_index: 0, - active_block: None, - completed_blocks: Vec::new(), - usage: Usage::new(10, 10), + paused: false, + error: None, + active: None, + blocks: Vec::new(), + usage: TurnUsage::default(), } } - fn emit(&self, event: &str, value: Value, out: &mut Vec) { - if self.stream { - out.push(sse_named(event, &value)); - } - } - - fn uncached_input_tokens(&self) -> u64 { - let cached = self - .usage + fn wire_usage(&self, starting: bool) -> Value { + let totals = &self.usage.totals; + let cached = totals .cache_read_tokens .unwrap_or(0) - .saturating_add(self.usage.cache_creation_tokens.unwrap_or(0)); - self.usage.input_tokens.saturating_sub(cached) + .saturating_add(totals.cache_creation_tokens.unwrap_or(0)); + let mut usage = json!({ + "input_tokens": totals.input_tokens.saturating_sub(cached), + "output_tokens": if starting { 0 } else { totals.output_tokens }, + }); + if let Some(read) = totals.cache_read_tokens { + usage["cache_read_input_tokens"] = json!(read); + } + if let Some(create) = totals.cache_creation_tokens { + usage["cache_creation_input_tokens"] = json!(create); + } + if !starting && !self.usage.iterations.is_empty() { + usage["iterations"] = json!(self.usage.iterations); + } + usage } - fn ensure_started(&mut self, out: &mut Vec) { - if self.started { + fn ensure_started(&mut self, emit: &mut dyn FnMut(EncodedFrame)) { + if !self.stream || self.started { return; } self.started = true; - let mut usage = serde_json::Map::new(); - // Anthropic wire `input_tokens` is uncached input; total input = input + cache_read + cache_creation. - usage.insert("input_tokens".into(), json!(self.uncached_input_tokens())); - usage.insert("output_tokens".into(), json!(0)); - if let Some(cr) = self.usage.cache_read_tokens { - usage.insert("cache_read_input_tokens".into(), json!(cr)); - } - if let Some(cw) = self.usage.cache_creation_tokens { - usage.insert("cache_creation_input_tokens".into(), json!(cw)); - } - self.emit( + emit(frame( "message_start", - json!({ + &json!({ "type": "message_start", "message": { - "id": self.id, - "type": "message", - "role": "assistant", - "model": self.model, - "content": [], - "stop_reason": Value::Null, - "stop_sequence": Value::Null, - "usage": Value::Object(usage), - } + "id": self.id, "type": "message", "role": "assistant", "model": self.model, + "content": [], "stop_reason": null, "stop_sequence": null, + "usage": self.wire_usage(true), + }, }), - out, - ); + FrameKind::Lifecycle, + 0, + )); } - fn close_active(&mut self, out: &mut Vec) { - if let Some(active) = self.active_block.take() { - match active { - ActiveBlock::Text { - index, - text, - citations, - } => { - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": index }), - out, - ); - let mut block = json!({ "type": "text", "text": text }); - if !citations.is_empty() { - block["citations"] = Value::Array(citations); - } - self.completed_blocks.push(block); + fn close_active(&mut self, emit: &mut dyn FnMut(EncodedFrame)) { + let Some(active) = self.active.take() else { + return; + }; + let index = self.blocks.len(); + let block = match active { + ActiveBlock::Text { text, citations } => { + let mut block = json!({ "type": "text" }); + block["text"] = Value::String(text); + if !citations.is_empty() { + block["citations"] = Value::Array(citations); } - ActiveBlock::Thinking { - index, - thinking, - signature, - } => { - let sig = signature.unwrap_or_else(|| format!("sig_{}_{index}", self.id)); - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "signature_delta", "signature": sig }, - }), - out, - ); - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": index }), - out, - ); - self.completed_blocks.push(json!({ - "type": "thinking", - "thinking": thinking, - "signature": sig, - })); + block + } + ActiveBlock::Thinking { text, signature } => { + let signature = signature.unwrap_or_else(|| format!("sig_{}_{index}", self.id)); + if self.stream { + emit(block_delta( + index, + "signature_delta", + "signature", + &signature, + 0, + )); } + let mut block = json!({ "type": "thinking" }); + block["thinking"] = Value::String(text); + block["signature"] = Value::String(signature); + block } + }; + if self.stream { + emit(block_stop(index)); } + self.blocks.push(block); } - fn map_stop_reason(reason: &FinishReason) -> &'static str { - match reason { - FinishReason::Stop => "end_turn", - FinishReason::ToolCalls => "tool_use", - FinishReason::Length | FinishReason::Incomplete(_) => "max_tokens", - FinishReason::ContentFilter | FinishReason::Refusal => "refusal", - FinishReason::Compaction => "compaction", + fn begin_atomic(&mut self, prefix: &mut Vec) -> usize { + self.ensure_started(&mut |frame| prefix.push(frame)); + self.close_active(&mut |frame| prefix.push(frame)); + self.blocks.len() + } + + fn atomic_block(&mut self, block: Value, bytes: usize, prefix: &mut Vec) { + if self.stream { + let index = self.blocks.len(); + let kind = if bytes == 0 { + FrameKind::Lifecycle + } else { + FrameKind::SemanticDelta + }; + prefix.push(block_start(index, &block, kind, bytes)); + prefix.push(block_stop(index)); + } + self.blocks.push(block); + } + + fn text( + &mut self, + text: String, + chunk_chars: usize, + citations: Vec, + ) -> EventFrames<'_> { + let mut prefix = Vec::new(); + self.ensure_started(&mut |frame| prefix.push(frame)); + if !matches!(self.active, Some(ActiveBlock::Text { .. })) { + let index = self.begin_atomic(&mut prefix); + if self.stream { + prefix.push(block_start( + index, + &json!({ "type": "text", "text": "" }), + FrameKind::Lifecycle, + 0, + )); + } + self.active = Some(ActiveBlock::Text { + text: String::new(), + citations: Vec::new(), + }); } + let index = self.blocks.len(); + let Some(ActiveBlock::Text { + text: buffer, + citations: annotations, + }) = &mut self.active + else { + unreachable!() + }; + let start = buffer.len(); + append(buffer, text); + let first_citation = annotations.len(); + annotations.extend(citations.into_iter().map(|citation| { + json!({ + "type": "web_search_result_location", + "url": citation.url, + "title": citation.title.unwrap_or_default(), + "cited_text": citation.cited_text.unwrap_or_default(), + "encrypted_index": format!("idx_{index}"), + }) + })); + if !self.stream { + return EventFrames::default(); + } + let deltas = split_utf8_chunks(&buffer[start..], chunk_chars) + .map(move |chunk| block_delta(index, "text_delta", "text", chunk, chunk.len())); + let citations = annotations[first_citation..].iter().map(move |citation| { + frame( + "content_block_delta", + &json!({ + "type": "content_block_delta", "index": index, + "delta": { "type": "citations_delta", "citation": citation }, + }), + FrameKind::Lifecycle, + 0, + ) + }); + EventFrames::then(prefix, deltas.chain(citations)) + } + + fn thinking( + &mut self, + text: String, + chunk_chars: usize, + signature: Option, + ) -> EventFrames<'_> { + let mut prefix = Vec::new(); + self.ensure_started(&mut |frame| prefix.push(frame)); + if !matches!(self.active, Some(ActiveBlock::Thinking { .. })) { + let index = self.begin_atomic(&mut prefix); + if self.stream { + prefix.push(block_start( + index, + &json!({ "type": "thinking", "thinking": "", "signature": "" }), + FrameKind::Lifecycle, + 0, + )); + } + self.active = Some(ActiveBlock::Thinking { + text: String::new(), + signature: None, + }); + } + let index = self.blocks.len(); + let Some(ActiveBlock::Thinking { + text: buffer, + signature: stored_signature, + }) = &mut self.active + else { + unreachable!() + }; + if signature.is_some() { + *stored_signature = signature; + } + let start = buffer.len(); + append(buffer, text); + if !self.stream { + return EventFrames::default(); + } + EventFrames::then( + prefix, + split_utf8_chunks(&buffer[start..], chunk_chars).map(move |chunk| { + block_delta(index, "thinking_delta", "thinking", chunk, chunk.len()) + }), + ) + } +} + +fn append(buffer: &mut String, text: String) { + if buffer.is_empty() { + *buffer = text; + } else { + buffer.push_str(&text); } } impl WireEncoder for AnthropicEncoder { - fn push_event(&mut self, event: TurnEvent, out: &mut Vec) { + fn encode_event(&mut self, event: TurnEvent) -> EventFrames<'_> { if self.finished { - return; - } - // Apply Usage before message_start if caller pushed Usage early! - if let TurnEvent::Usage(usage) = event { - self.usage = usage; - return; + return EventFrames::default(); } + let event = match event { + TurnEvent::Usage(totals) => { + self.usage = totals.into(); + return EventFrames::default(); + } + TurnEvent::UsageWithIterations(usage) => { + self.usage = usage; + return EventFrames::default(); + } + _ if self.paused => return EventFrames::default(), + event => event, + }; + let mut prefix = Vec::new(); match event { + TurnEvent::Text { + text, + chunk_chars, + citations, + } => return self.text(text, chunk_chars, citations), + TurnEvent::Refusal { text } => return self.text(text, 0, Vec::new()), TurnEvent::Reasoning { text, chunk_chars, signature, .. - } => { - self.ensure_started(out); - let is_thinking = matches!(self.active_block, Some(ActiveBlock::Thinking { .. })); - if !is_thinking { - self.close_active(out); - let index = self.next_index; - self.next_index += 1; - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": index, - "content_block": { "type": "thinking", "thinking": "" }, - }), - out, - ); - self.active_block = Some(ActiveBlock::Thinking { - index, - thinking: String::new(), - signature: signature.clone(), - }); - } - let index = match &mut self.active_block { - Some(ActiveBlock::Thinking { - index, - signature: sig_slot, - .. - }) => { - if signature.is_some() { - *sig_slot = signature; - } - *index - } - _ => unreachable!(), - }; - for chunk in split_utf8_chunks(&text, chunk_chars) { - if let Some(ActiveBlock::Thinking { thinking, .. }) = &mut self.active_block { - thinking.push_str(chunk); - } - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "thinking_delta", "thinking": chunk }, - }), - out, - ); - } - } + } => return self.thinking(text, chunk_chars, signature), TurnEvent::RedactedThinking { data } => { - self.ensure_started(out); - self.close_active(out); - let index = self.next_index; - self.next_index += 1; - let block = json!({ "type": "redacted_thinking", "data": data }); - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": index, - "content_block": block, - }), - out, - ); - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": index }), - out, - ); - self.completed_blocks.push(block); - } - TurnEvent::Text { - text, - chunk_chars, - citations, - } => { - self.ensure_started(out); - let is_text = matches!(self.active_block, Some(ActiveBlock::Text { .. })); - if !is_text { - self.close_active(out); - let index = self.next_index; - self.next_index += 1; - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": index, - "content_block": { "type": "text", "text": "" }, - }), - out, - ); - self.active_block = Some(ActiveBlock::Text { - index, - text: String::new(), - citations: Vec::new(), - }); - } - let index = match &self.active_block { - Some(ActiveBlock::Text { index, .. }) => *index, - _ => unreachable!(), - }; - for chunk in split_utf8_chunks(&text, chunk_chars) { - if let Some(ActiveBlock::Text { text: buf, .. }) = &mut self.active_block { - buf.push_str(chunk); - } - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "text_delta", "text": chunk }, - }), - out, - ); - } - for cit in citations { - let wire_cit = json!({ - "type": "web_search_result_location", - "url": cit.url, - "title": cit.title.unwrap_or_default(), - "cited_text": cit.cited_text.unwrap_or_default(), - "encrypted_index": format!("idx_{index}"), - }); - if let Some(ActiveBlock::Text { citations: buf, .. }) = &mut self.active_block { - buf.push(wire_cit.clone()); - } - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "citations_delta", "citation": wire_cit }, - }), - out, - ); - } - } - TurnEvent::Refusal { text } => { - self.push_event( - TurnEvent::Text { - text, - chunk_chars: 0, - citations: Vec::new(), - }, - out, + let bytes = data.len(); + self.begin_atomic(&mut prefix); + self.atomic_block( + json!({ "type": "redacted_thinking", "data": data }), + bytes, + &mut prefix, ); } TurnEvent::ToolCall(spec) => { - self.ensure_started(out); - self.close_active(out); - let index = self.next_index; - self.next_index += 1; - let tool_id = if spec.id.is_empty() { + let index = self.begin_atomic(&mut prefix); + let id = if spec.id.is_empty() { format!("toolu_{}_{index}", self.id) } else { - spec.id.clone() + spec.id }; - let args = spec.arguments_string(); - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": index, - "content_block": { - "type": "tool_use", - "id": tool_id, - "name": spec.name, - "input": {}, + let (input, raw, literal) = match spec.payload { + Some(ToolCallPayload::FunctionArgs(input)) => (input, None, false), + Some( + ToolCallPayload::MalformedRaw(raw) | ToolCallPayload::FreeformInput(raw), + ) => (Value::String(raw), None, true), + None => match spec.arguments { + Value::String(raw) if spec.custom_tool => (Value::String(raw), None, true), + Value::String(raw) => match serde_json::from_str(&raw) { + Ok(input) => (input, Some(raw), false), + Err(_) => (Value::String(raw), None, true), }, - }), - out, - ); - for chunk in split_utf8_chunks(&args, spec.chunk_chars) { - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "input_json_delta", "partial_json": chunk }, - }), - out, + input => (input, None, false), + }, + }; + let mut block = + json!({ "type": "tool_use", "id": id, "name": spec.name, "input": {} }); + if self.stream { + prefix.push(block_start( + index, + &block, + FrameKind::SemanticDelta, + spec.name.len(), + )); + } + block["input"] = input; + self.blocks.push(block); + if self.stream { + let input = &self.blocks[index]["input"]; + let args = match raw { + Some(raw) => Cow::Owned(raw), + None if literal => { + Cow::Borrowed(input.as_str().expect("literal tool input is a string")) + } + None => Cow::Owned(input.to_string()), + }; + return EventFrames::then( + prefix, + chunk_frames(args, spec.chunk_chars, move |chunk| { + block_delta( + index, + "input_json_delta", + "partial_json", + chunk, + chunk.len(), + ) + }) + .chain(std::iter::once_with(move || block_stop(index))), ); } - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": index }), - out, - ); - let parsed_input = match &spec.arguments { - Value::String(s) => serde_json::from_str(s).unwrap_or_else(|_| json!({})), - other => other.clone(), - }; - self.completed_blocks.push(json!({ - "type": "tool_use", - "id": tool_id, - "name": spec.name, - "input": parsed_input, - })); } - TurnEvent::NativeTool(NativeToolEvent::WebSearch { id, query, results }) => { - self.ensure_started(out); - self.close_active(out); - let tool_id = if id.is_empty() { - format!("srvtoolu_{}_{}", self.id, self.next_index) + TurnEvent::NativeTool(tool) => { + let index = self.begin_atomic(&mut prefix); + let (id, query, results) = match tool { + NativeToolEvent::WebSearch { id, query, results } => (id, query, Some(results)), + NativeToolEvent::WebSearchStarted { id, query } => (id, query, None), + }; + let id = if id.is_empty() { + format!("srvtoolu_{}_{index}", self.id) } else { id }; - let call_idx = self.next_index; - self.next_index += 1; - let server_call = json!({ - "type": "server_tool_use", - "id": tool_id, - "name": "web_search", - "input": { "query": query }, - }); - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": call_idx, - "content_block": server_call, - }), - out, - ); - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": call_idx }), - out, - ); - self.completed_blocks.push(server_call); - - let res_idx = self.next_index; - self.next_index += 1; - let items: Vec = results - .into_iter() - .map(|r| { + self.atomic_block(json!({ + "type": "server_tool_use", "id": id, "name": "web_search", "input": { "query": query }, + }), query.len(), &mut prefix); + if let Some(results) = results { + let results: Vec<_> = results.into_iter().map(|result| json!({ + "type": "web_search_result", "url": result.url, "title": result.title, + "encrypted_content": result.encrypted_content.as_deref().unwrap_or("opaque"), + })).collect(); + self.atomic_block( json!({ - "type": "web_search_result", - "url": r.url, - "title": r.title, - "encrypted_content": r.encrypted_content.unwrap_or_else(|| "opaque".into()), - }) - }) - .collect(); - let res_block = json!({ - "type": "web_search_tool_result", - "tool_use_id": tool_id, - "content": items, - }); - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": res_idx, - "content_block": res_block, - }), - out, - ); - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": res_idx }), - out, - ); - self.completed_blocks.push(res_block); + "type": "web_search_tool_result", "tool_use_id": id, "content": results, + }), + 0, + &mut prefix, + ); + } } - TurnEvent::NativeTool(NativeToolEvent::WebSearchStarted { id, query }) => { - self.ensure_started(out); - self.close_active(out); - let tool_id = if id.is_empty() { - format!("srvtoolu_{}_{}", self.id, self.next_index) + TurnEvent::NativeCompaction(compaction) => { + let index = self.begin_atomic(&mut prefix); + self.paused = compaction.pause_after_compaction; + let summary = if !compaction.summary.is_empty() { + compaction.summary + } else if !compaction.encrypted_content.is_empty() { + compaction.encrypted_content } else { - id + "Compacted conversation summary.".into() }; - let call_idx = self.next_index; - self.next_index += 1; - let server_call = json!({ - "type": "server_tool_use", - "id": tool_id, - "name": "web_search", - "input": { "query": query }, - }); - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": call_idx, - "content_block": server_call, - }), - out, - ); - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": call_idx }), - out, - ); - self.completed_blocks.push(server_call); - } - TurnEvent::NativeCompaction(comp) => { - self.ensure_started(out); - self.close_active(out); - let index = self.next_index; - self.next_index += 1; - let summary = if comp.summary.is_empty() { - if comp.encrypted_content.is_empty() { - "Compacted conversation summary.".into() - } else { - comp.encrypted_content + if self.stream { + prefix.push(block_start( + index, + &json!({ "type": "compaction", "content": null }), + FrameKind::Lifecycle, + 0, + )); + prefix.push(block_delta( + index, + "compaction_delta", + "content", + &summary, + summary.len(), + )); + if let Some(signature) = &compaction.signature { + prefix.push(block_delta( + index, + "signature_delta", + "signature", + signature, + 0, + )); } - } else { - comp.summary - }; - // Per Anthropic stream decoder: start with content: null, deliver summary via compaction_delta! - let mut start_block = serde_json::Map::new(); - start_block.insert("type".into(), json!("compaction")); - start_block.insert("content".into(), Value::Null); - if let Some(sig) = &comp.signature { - start_block.insert("signature".into(), json!(sig)); + prefix.push(block_stop(index)); } - self.emit( - "content_block_start", - json!({ - "type": "content_block_start", - "index": index, - "content_block": Value::Object(start_block), - }), - out, - ); - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { - "type": "compaction_delta", - "content": summary, - }, - }), - out, - ); - if let Some(sig) = &comp.signature { - self.emit( - "content_block_delta", - json!({ - "type": "content_block_delta", - "index": index, - "delta": { "type": "signature_delta", "signature": sig }, - }), - out, - ); - } - self.emit( - "content_block_stop", - json!({ "type": "content_block_stop", "index": index }), - out, - ); - let mut done_block = json!({ - "type": "compaction", - "content": summary, - }); - if let Some(sig) = comp.signature { - done_block["signature"] = json!(sig); + let mut block = json!({ "type": "compaction" }); + block["content"] = Value::String(summary); + if let Some(signature) = compaction.signature { + block["signature"] = Value::String(signature); } - self.completed_blocks.push(done_block); + self.blocks.push(block); } - TurnEvent::MidStreamError(err) => { - self.ensure_started(out); - self.errored = true; + TurnEvent::MidStreamError(error) => { + self.ensure_started(&mut |frame| prefix.push(frame)); self.finished = true; - let mut err_obj = serde_json::Map::new(); - err_obj.insert("type".into(), json!(err.error_type)); - err_obj.insert("message".into(), json!(err.message)); - if let Some(code) = err.code { - err_obj.insert("code".into(), json!(code)); + let mut body = json!({ "type": "error", "error": { "type": error.error_type, "message": error.message } }); + if let Some(code) = error.code { + body["error"]["code"] = Value::String(code); } - if let Some(retryable) = err.retryable { - err_obj.insert("isRetryable".into(), json!(retryable)); + if let Some(retryable) = error.retryable { + body["error"]["isRetryable"] = Value::Bool(retryable); } - self.emit( - "error", - json!({ - "type": "error", - "error": Value::Object(err_obj), - }), - out, - ); - } - TurnEvent::RawJson { value } => { if self.stream { - let event_name = value["type"].as_str().unwrap_or("message"); - out.push(sse_named(event_name, &value)); + prefix.push(frame("error", &body, FrameKind::Terminal, 0)); } + self.error = Some(body); } - TurnEvent::StreamStart => { - self.ensure_started(out); + TurnEvent::Ping if self.stream => { + self.ensure_started(&mut |frame| prefix.push(frame)); + prefix.push(frame( + "ping", + &json!({ "type": "ping" }), + FrameKind::Keepalive, + 0, + )); } - TurnEvent::Flush => { - self.close_active(out); + TurnEvent::StreamStart => self.ensure_started(&mut |frame| prefix.push(frame)), + TurnEvent::Flush => self.close_active(&mut |frame| prefix.push(frame)), + TurnEvent::RawJson { value } if self.stream => prefix.push(frame( + value["type"].as_str().unwrap_or("message"), + &value, + FrameKind::Lifecycle, + 0, + )), + TurnEvent::SseComment { comment } if self.stream => { + prefix.push(EncodedFrame::comment(&comment)) } - TurnEvent::SseComment { comment } => { - if self.stream { - out.push(WireFrame::Sse(bytes::Bytes::from(format!( - ": {comment}\n\n" - )))); - } - } - TurnEvent::RawBytes(bytes) => { - out.push(WireFrame::Raw(bytes)); - } - TurnEvent::Usage(_) - | TurnEvent::Delay { .. } - | TurnEvent::JitterDelay { .. } - | TurnEvent::Stall - | TurnEvent::HttpError(_) - | TurnEvent::DropConnection - | TurnEvent::TruncateEof - | TurnEvent::Finish { .. } => {} + TurnEvent::RawBytes(bytes) if self.stream => prefix.push(EncodedFrame::new( + WireFrame::Raw(bytes), + FrameKind::Lifecycle, + 0, + )), + _ => {} } + EventFrames::prefix(prefix) } - fn finish(&mut self, reason: FinishReason, out: &mut Vec) -> TurnCompletion { - self.ensure_started(out); - self.close_active(out); - - let stop_reason = Self::map_stop_reason(&reason); - let mut usage_delta = serde_json::Map::new(); - usage_delta.insert("input_tokens".into(), json!(self.uncached_input_tokens())); - // Mandatory per Anthropic stream decoder validation. - usage_delta.insert("output_tokens".into(), json!(self.usage.output_tokens)); - if let Some(cr) = self.usage.cache_read_tokens { - usage_delta.insert("cache_read_input_tokens".into(), json!(cr)); + fn finish_encoded( + &mut self, + reason: FinishReason, + emit: &mut dyn FnMut(EncodedFrame), + ) -> TurnCompletion { + if let Some(response_json) = self.error.take() { + return TurnCompletion { + response_json, + response_id: self.id.clone(), + ws_reusable: false, + errored: true, + }; } - if let Some(cw) = self.usage.cache_creation_tokens { - usage_delta.insert("cache_creation_input_tokens".into(), json!(cw)); - } - + let stop_reason = match reason { + _ if self.paused => "compaction", + FinishReason::Stop => "end_turn", + FinishReason::ToolCalls => "tool_use", + FinishReason::Length | FinishReason::Incomplete(_) => "max_tokens", + FinishReason::ContentFilter | FinishReason::Refusal => "refusal", + FinishReason::Compaction => "compaction", + }; + let usage = self.wire_usage(false); if !self.finished { + self.ensure_started(emit); + self.close_active(emit); self.finished = true; - self.emit( - "message_delta", - json!({ - "type": "message_delta", - "delta": { - "stop_reason": stop_reason, - "stop_sequence": Value::Null, - }, - "usage": Value::Object(usage_delta.clone()), - }), - out, - ); - self.emit("message_stop", json!({ "type": "message_stop" }), out); + if self.stream { + emit(frame( + "message_delta", + &json!({ + "type": "message_delta", + "delta": { "stop_reason": stop_reason, "stop_sequence": null }, + "usage": usage, + }), + FrameKind::Terminal, + 0, + )); + emit(frame( + "message_stop", + &json!({ "type": "message_stop" }), + FrameKind::Terminal, + 0, + )); + } } - - let resp = json!({ - "id": self.id, - "type": "message", - "role": "assistant", - "model": self.model, - "content": self.completed_blocks, - "stop_reason": stop_reason, - "stop_sequence": Value::Null, - "usage": Value::Object(usage_delta), + let mut response_json = json!({ + "id": self.id, "type": "message", "role": "assistant", "model": self.model, + "stop_reason": stop_reason, "stop_sequence": null, }); - + response_json["content"] = Value::Array(std::mem::take(&mut self.blocks)); + response_json["usage"] = usage; TurnCompletion { - response_json: resp, + response_json, response_id: self.id.clone(), ws_reusable: false, - errored: self.errored, + errored: false, } } @@ -664,3 +629,141 @@ impl WireEncoder for AnthropicEncoder { self.finished } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::codec::sse_json; + use crate::plan::{CompactionOutput, ToolCallSpec, Usage, UsageIteration, UsageIterationKind}; + + #[test] + fn ping_and_signed_thinking_preserve_the_stream_and_usage() { + let mut encoder = AnthropicEncoder::new("msg_1".into(), "test".into(), true); + let mut frames = Vec::new(); + for event in [ + TurnEvent::Usage(Usage::new(52, 9).with_cache_read(20).with_cache_creation(7)), + TurnEvent::Ping, + TurnEvent::Reasoning { + text: "🦀思".into(), + chunk_chars: 1, + signature: Some("signed".into()), + encrypted_content: None, + }, + TurnEvent::RedactedThinking { + data: "opaque".into(), + }, + ] { + frames.extend(encoder.encode_event(event)); + } + let result = encoder.finish_encoded(FinishReason::Stop, &mut |frame| frames.push(frame)); + let events: Vec<_> = frames.iter().map(sse_json).collect(); + assert_eq!( + events[0]["message"]["usage"], + json!({ + "input_tokens": 25, "output_tokens": 0, "cache_read_input_tokens": 20, "cache_creation_input_tokens": 7, + }) + ); + assert_eq!(frames[1].kind, FrameKind::Keepalive); + assert_eq!(frames[1].semantic_bytes, 0); + let WireFrame::Sse(ping) = &frames[1].wire else { + panic!("expected ping SSE"); + }; + assert_eq!(&ping[..], b"event: ping\ndata: {\"type\":\"ping\"}\n\n"); + let deltas: Vec<_> = events + .iter() + .filter_map(|event| event.get("delta")) + .filter(|delta| delta.get("type").is_some()) + .cloned() + .collect(); + assert_eq!( + deltas, + vec![ + json!({ "type": "thinking_delta", "thinking": "🦀" }), + json!({ "type": "thinking_delta", "thinking": "思" }), + json!({ "type": "signature_delta", "signature": "signed" }), + ] + ); + assert_eq!( + result.response_json["content"], + json!([ + { "type": "thinking", "thinking": "🦀思", "signature": "signed" }, + { "type": "redacted_thinking", "data": "opaque" }, + ]) + ); + } + + #[test] + fn compaction_can_pause_or_continue_with_iteration_usage() { + for pause in [false, true] { + let mut encoder = AnthropicEncoder::new("msg_1".into(), "test".into(), true); + let mut frames = Vec::new(); + let usage = Usage::new(100, 6).with_iterations(vec![ + UsageIteration { + kind: UsageIterationKind::Compaction, + input_tokens: 80, + output_tokens: 2, + cache_read_input_tokens: None, + cache_creation_input_tokens: None, + }, + UsageIteration { + kind: UsageIterationKind::Message, + input_tokens: 20, + output_tokens: 4, + cache_read_input_tokens: None, + cache_creation_input_tokens: None, + }, + ]); + for event in [ + TurnEvent::UsageWithIterations(usage), + TurnEvent::NativeCompaction(CompactionOutput::new("summary").with_pause(pause)), + TurnEvent::Text { + text: "continued".into(), + chunk_chars: 0, + citations: Vec::new(), + }, + ] { + frames.extend(encoder.encode_event(event)); + } + let result = + encoder.finish_encoded(FinishReason::Stop, &mut |frame| frames.push(frame)); + let delta = sse_json(&frames[frames.len() - 2]); + assert_eq!(delta["type"], "message_delta"); + assert_eq!( + delta["delta"]["stop_reason"], + if pause { "compaction" } else { "end_turn" } + ); + assert_eq!( + delta["usage"]["iterations"], + json!([ + { "type": "compaction", "input_tokens": 80, "output_tokens": 2 }, + { "type": "message", "input_tokens": 20, "output_tokens": 4 }, + ]) + ); + let mut expected = vec![json!({ "type": "compaction", "content": "summary" })]; + if !pause { + expected.push(json!({ "type": "text", "text": "continued" })); + } + assert_eq!(result.response_json["content"], Value::Array(expected)); + } + } + + #[test] + fn nonstreaming_malformed_tool_input_remains_observable() { + let mut encoder = AnthropicEncoder::new("msg_1".into(), "test".into(), false); + let call = ToolCallSpec::with_payload( + "toolu_1", + "lookup", + ToolCallPayload::MalformedRaw("{-".into()), + ) + .with_chunk_chars(1); + assert_eq!(encoder.encode_event(call.into()).count(), 0); + let result = + encoder.finish_encoded(FinishReason::ToolCalls, &mut |_| panic!("unexpected frame")); + assert_eq!( + result.response_json["content"], + json!([ + { "type": "tool_use", "id": "toolu_1", "name": "lookup", "input": "{-" }, + ]) + ); + } +} diff --git a/tools/mock-ai/src/codec/chat_completions.rs b/tools/mock-ai/src/codec/chat_completions.rs index 7d6f3fb83c9..c7edd270ec4 100644 --- a/tools/mock-ai/src/codec/chat_completions.rs +++ b/tools/mock-ai/src/codec/chat_completions.rs @@ -17,308 +17,423 @@ * under the License. */ -use super::{TurnCompletion, WireEncoder, WireFrame, split_utf8_chunks, sse_data}; -use crate::plan::{FinishReason, TurnEvent, Usage}; +use super::{ + EncodedFrame, EventFrames, FrameKind, StringField, TurnCompletion, Utf8ChunkIter, WireEncoder, + WireFrame, split_utf8_chunks, unix_timestamp, +}; +use crate::plan::{FinishReason, ProviderDialectProfile, ToolCallSpec, TurnEvent, Usage}; +use crate::protocol::RequestOptions; use bytes::Bytes; +use serde::Serialize; use serde_json::{Value, json}; pub struct ChatCompletionsEncoder { - id: String, - model: String, + wire: ChatWire, stream: bool, - started_role: bool, + profile: ProviderDialectProfile, finished: bool, errored: bool, - next_tool_index: usize, usage: Option, - // Accumulated state for non-streaming JSON responses. - text_buf: String, - reasoning_buf: String, - refusal_buf: String, - tool_calls_acc: Vec, + text: String, + reasoning: String, + refusal: String, + tool_calls: Vec, +} + +struct ChatWire { + id: String, + model: String, + created: u64, + include_usage: bool, + role_sent: bool, +} + +#[derive(Serialize)] +struct Chunk<'a, C> { + id: &'a str, + object: &'static str, + created: u64, + model: &'a str, + choices: C, + #[serde(skip_serializing_if = "Option::is_none")] + usage: Option>, +} + +impl ChatWire { + fn chunk( + &mut self, + delta: impl Serialize, + finish_reason: Option<&str>, + kind: FrameKind, + semantic_bytes: usize, + ) -> EncodedFrame { + #[derive(Serialize)] + struct Delta<'a, D> { + #[serde(skip_serializing_if = "Option::is_none")] + role: Option<&'a str>, + #[serde(flatten)] + fields: D, + } + #[derive(Serialize)] + struct Choice<'a, D> { + index: usize, + delta: Delta<'a, D>, + finish_reason: Option<&'a str>, + } + + let role = if !self.role_sent && finish_reason.is_none() { + self.role_sent = true; + Some("assistant") + } else { + None + }; + self.frame( + [Choice { + index: 0, + delta: Delta { + role, + fields: delta, + }, + finish_reason, + }], + None, + kind, + semantic_bytes, + ) + } + + fn frame( + &self, + choices: impl Serialize, + usage: Option<&Value>, + kind: FrameKind, + semantic_bytes: usize, + ) -> EncodedFrame { + let body = Chunk { + id: &self.id, + object: "chat.completion.chunk", + created: self.created, + model: &self.model, + choices, + usage: self.include_usage.then_some(usage), + }; + EncodedFrame::new_sse(None, &body, kind, semantic_bytes) + } +} + +struct CallChunks<'a> { + index: usize, + call: &'a Value, + declaration: &'a str, + input_key: &'a str, + chunks: Utf8ChunkIter<'a>, + first: bool, +} + +impl<'a> CallChunks<'a> { + fn new(index: usize, call: &'a Value, chunk_chars: usize) -> Self { + let (declaration, input_key) = if call["type"] == "custom" { + ("custom", "input") + } else { + ("function", "arguments") + }; + let input = call[declaration][input_key] + .as_str() + .expect("encoded tool input is a string"); + Self { + index, + call, + declaration, + input_key, + chunks: split_utf8_chunks(input, chunk_chars), + first: true, + } + } + + fn next(&mut self, wire: &mut ChatWire) -> Option { + let first = std::mem::take(&mut self.first); + let chunk = self.chunks.next().or(first.then_some(""))?; + let mut call_delta = json!({ "index": self.index }); + let mut declaration = json!({ self.input_key: chunk }); + let mut semantic_bytes = chunk.len(); + if first { + let name = &self.call[self.declaration]["name"]; + declaration["name"] = name.clone(); + semantic_bytes += name.as_str().map_or(0, str::len); + call_delta["id"] = self.call["id"].clone(); + call_delta["type"] = self.call["type"].clone(); + if let Some(extra) = self.call.get("extra_content") { + call_delta["extra_content"] = extra.clone(); + } + } + call_delta[self.declaration] = declaration; + Some(wire.chunk( + json!({ "tool_calls": [call_delta] }), + None, + FrameKind::SemanticDelta, + semantic_bytes, + )) + } } impl ChatCompletionsEncoder { pub fn new(id: String, model: String, stream: bool) -> Self { - Self { + Self::with_options( id, model, stream, - started_role: false, + &RequestOptions::default(), + ProviderDialectProfile::StandardOpenAi, + ) + } + + pub fn with_options( + id: String, + model: String, + stream: bool, + options: &RequestOptions, + profile: ProviderDialectProfile, + ) -> Self { + Self { + wire: ChatWire { + id, + model, + created: unix_timestamp(), + include_usage: options.stream_include_usage, + role_sent: false, + }, + stream, + profile, finished: false, errored: false, - next_tool_index: 0, usage: None, - text_buf: String::new(), - reasoning_buf: String::new(), - refusal_buf: String::new(), - tool_calls_acc: Vec::new(), + text: String::new(), + reasoning: String::new(), + refusal: String::new(), + tool_calls: Vec::new(), } } - fn emit_chunk( - &mut self, - mut delta: serde_json::Map, - finish_reason: Value, - out: &mut Vec, - ) { - if !self.started_role && finish_reason.is_null() { - delta.insert("role".into(), json!("assistant")); - self.started_role = true; - } - if self.stream { - out.push(sse_data(&json!({ - "id": self.id, - "object": "chat.completion.chunk", - "model": self.model, - "choices": [{ - "index": 0, - "delta": Value::Object(delta), - "finish_reason": finish_reason, - }] - }))); + pub fn with_created_at(mut self, created: u64) -> Self { + self.wire.created = created; + self + } + + fn store_call(&mut self, mut spec: ToolCallSpec) { + let id = if spec.id.is_empty() { + format!("call_{}_{}", self.wire.id, self.tool_calls.len()) + } else { + std::mem::take(&mut spec.id) + }; + let (declaration, input_key) = if spec.is_freeform() { + ("custom", "input") + } else { + ("function", "arguments") + }; + let input = spec.take_wire_arguments(); + let mut call = json!({ "id": id, "type": declaration, declaration: { "name": spec.name } }); + call[declaration][input_key] = Value::String(input); + if let Some(signature) = spec.thought_signature { + call["extra_content"] = json!({ "google": { "thought_signature": signature } }); } + self.tool_calls.push(call); } fn wire_usage(usage: &Usage) -> Value { - let reasoning = usage.reasoning_tokens.unwrap_or(0); - // OpenAI spec & Maka decoder invariant: completion_tokens includes reasoning_tokens. - let completion_tokens = usage.output_tokens.max(reasoning); - let mut obj = serde_json::Map::new(); - obj.insert("prompt_tokens".into(), json!(usage.input_tokens)); - obj.insert("completion_tokens".into(), json!(completion_tokens)); - obj.insert( - "total_tokens".into(), - json!(usage.input_tokens.saturating_add(completion_tokens)), - ); - if usage.cache_read_tokens.is_some() || usage.cache_creation_tokens.is_some() { - let mut details = serde_json::Map::new(); - if let Some(cached) = usage.cache_read_tokens { - details.insert("cached_tokens".into(), json!(cached)); - } - if let Some(write) = usage.cache_creation_tokens { - details.insert("cache_write_tokens".into(), json!(write)); - } - obj.insert("prompt_tokens_details".into(), Value::Object(details)); + let completion_tokens = usage.output_tokens.max(usage.reasoning_tokens.unwrap_or(0)); + let mut usage_json = json!({ + "prompt_tokens": usage.input_tokens, + "completion_tokens": completion_tokens, + "total_tokens": usage.input_tokens.saturating_add(completion_tokens), + }); + if let Some(cached) = usage.cache_read_tokens { + usage_json["prompt_tokens_details"]["cached_tokens"] = json!(cached); } - if let Some(r) = usage.reasoning_tokens { - obj.insert( - "completion_tokens_details".into(), - json!({ "reasoning_tokens": r }), - ); + if let Some(write) = usage.cache_creation_tokens { + usage_json["prompt_tokens_details"]["cache_write_tokens"] = json!(write); + } + if let Some(reasoning) = usage.reasoning_tokens { + usage_json["completion_tokens_details"]["reasoning_tokens"] = json!(reasoning); } - Value::Object(obj) + usage_json } - fn map_finish_reason(reason: &FinishReason) -> &'static str { - match reason { - FinishReason::Stop | FinishReason::Compaction => "stop", - FinishReason::ToolCalls => "tool_calls", - FinishReason::Length => "length", - FinishReason::ContentFilter | FinishReason::Refusal => "content_filter", - FinishReason::Incomplete(_) => "length", + fn delta_text( + &mut self, + field: &'static str, + text: String, + chunk_chars: usize, + ) -> EventFrames<'_> { + let buffer = match field { + "content" => &mut self.text, + "reasoning_content" => &mut self.reasoning, + "refusal" => &mut self.refusal, + _ => unreachable!(), + }; + let start = buffer.len(); + if buffer.is_empty() { + *buffer = text; + } else { + buffer.push_str(&text); } + if !self.stream || buffer.len() == start { + return EventFrames::default(); + } + let wire = &mut self.wire; + EventFrames::then( + Vec::new(), + split_utf8_chunks(&buffer[start..], chunk_chars).map(move |chunk| { + wire.chunk( + StringField(field, chunk), + None, + FrameKind::SemanticDelta, + chunk.len(), + ) + }), + ) } } impl WireEncoder for ChatCompletionsEncoder { - fn push_event(&mut self, event: TurnEvent, out: &mut Vec) { + fn encode_event(&mut self, event: TurnEvent) -> EventFrames<'_> { if self.finished { - return; + return EventFrames::default(); } - match event { + let frame = match event { TurnEvent::Text { text, chunk_chars, .. - } => { - self.text_buf.push_str(&text); - for chunk in split_utf8_chunks(&text, chunk_chars) { - let mut delta = serde_json::Map::new(); - delta.insert("content".into(), json!(chunk)); - self.emit_chunk(delta, Value::Null, out); - } - } + } => return self.delta_text("content", text, chunk_chars), + TurnEvent::Refusal { text } => return self.delta_text("refusal", text, 0), TurnEvent::Reasoning { text, chunk_chars, .. - } => { - if text.is_empty() { - return; - } - self.reasoning_buf.push_str(&text); - for chunk in split_utf8_chunks(&text, chunk_chars) { - let mut delta = serde_json::Map::new(); - // Only include reasoning_content when non-empty; never emit empty string. - delta.insert("reasoning_content".into(), json!(chunk)); - self.emit_chunk(delta, Value::Null, out); - } - } - TurnEvent::Refusal { text } => { - self.refusal_buf.push_str(&text); - let mut delta = serde_json::Map::new(); - delta.insert("refusal".into(), json!(text)); - self.emit_chunk(delta, Value::Null, out); + } if self.profile.emits_chat_reasoning() => { + return self.delta_text("reasoning_content", text, chunk_chars); } TurnEvent::ToolCall(spec) => { - let index = self.next_tool_index; - self.next_tool_index += 1; - let call_id = if spec.id.is_empty() { - format!("call_{}_{index}", self.id) - } else { - spec.id.clone() - }; - let args = spec.arguments_string(); - - let mut acc_call = json!({ - "id": call_id, - "type": "function", - "function": { - "name": spec.name, - "arguments": args, - } - }); - if let Some(sig) = &spec.thought_signature { - acc_call["extra_content"] = json!({ "google": { "thought_signature": sig } }); - } - self.tool_calls_acc.push(acc_call); - - let arg_chunks = if args.is_empty() { - vec![""] - } else { - split_utf8_chunks(&args, spec.chunk_chars) - }; - for (i, chunk) in arg_chunks.into_iter().enumerate() { - let mut call_delta = serde_json::Map::new(); - call_delta.insert("index".into(), json!(index)); - if i == 0 { - call_delta.insert("id".into(), json!(call_id)); - call_delta.insert("type".into(), json!("function")); - call_delta.insert( - "function".into(), - json!({ "name": spec.name, "arguments": chunk }), - ); - if let Some(sig) = &spec.thought_signature { - call_delta.insert( - "extra_content".into(), - json!({ "google": { "thought_signature": sig } }), - ); - } - } else { - call_delta.insert("function".into(), json!({ "arguments": chunk })); - } - let mut delta = serde_json::Map::new(); - delta.insert( - "tool_calls".into(), - Value::Array(vec![Value::Object(call_delta)]), + let index = self.tool_calls.len(); + let chunk_chars = spec.chunk_chars; + self.store_call(spec); + if self.stream { + let mut chunks = CallChunks::new(index, &self.tool_calls[index], chunk_chars); + let wire = &mut self.wire; + return EventFrames::then( + Vec::new(), + std::iter::from_fn(move || chunks.next(wire)), ); - self.emit_chunk(delta, Value::Null, out); } + None } TurnEvent::Usage(usage) => { self.usage = Some(usage); + None + } + TurnEvent::UsageWithIterations(usage) => { + self.usage = Some(usage.totals); + None } TurnEvent::MidStreamError(err) => { self.errored = true; self.finished = true; - let mut detail = serde_json::Map::new(); - detail.insert("message".into(), json!(err.message)); - detail.insert("type".into(), json!(err.error_type)); - if let Some(code) = err.code { - detail.insert("code".into(), json!(code)); - } - if self.stream { - out.push(sse_data(&json!({ "error": Value::Object(detail) }))); - } - } - TurnEvent::RawJson { value } => { - if self.stream { - out.push(sse_data(&value)); - } + self.stream.then(|| { + let mut detail = json!({ "message": err.message, "type": err.error_type }); + if let Some(code) = err.code { + detail["code"] = json!(code); + } + EncodedFrame::new_sse(None, &json!({ "error": detail }), FrameKind::Terminal, 0) + }) } - TurnEvent::StreamStart => { - if !self.started_role { - self.emit_chunk(serde_json::Map::new(), Value::Null, out); - } + TurnEvent::RawJson { value } if self.stream => { + Some(EncodedFrame::new_sse(None, &value, FrameKind::Lifecycle, 0)) } - TurnEvent::SseComment { comment } => { - if self.stream { - out.push(WireFrame::Sse(Bytes::from(format!(": {comment}\n\n")))); - } + TurnEvent::StreamStart if self.stream && !self.wire.role_sent => { + Some(self.wire.chunk(json!({}), None, FrameKind::Lifecycle, 0)) } - TurnEvent::RawBytes(bytes) => { - out.push(WireFrame::Raw(bytes)); + TurnEvent::SseComment { comment } if self.stream => { + Some(EncodedFrame::comment(&comment)) } - TurnEvent::Flush - | TurnEvent::NativeTool(_) - | TurnEvent::NativeCompaction(_) - | TurnEvent::RedactedThinking { .. } - | TurnEvent::Delay { .. } - | TurnEvent::JitterDelay { .. } - | TurnEvent::Stall - | TurnEvent::HttpError(_) - | TurnEvent::DropConnection - | TurnEvent::TruncateEof - | TurnEvent::Finish { .. } => {} + TurnEvent::Ping if self.stream => Some(EncodedFrame::comment("ping")), + TurnEvent::RawBytes(bytes) if self.stream => Some(EncodedFrame::new( + WireFrame::Raw(bytes), + FrameKind::Lifecycle, + 0, + )), + _ => None, + }; + match frame { + Some(frame) => EventFrames::prefix(vec![frame]), + None => EventFrames::default(), } } - fn finish(&mut self, reason: FinishReason, out: &mut Vec) -> TurnCompletion { - let finish_str = Self::map_finish_reason(&reason); - if !self.finished { - self.finished = true; - if self.stream { - // 1) Choice finish_reason chunk - self.emit_chunk(serde_json::Map::new(), json!(finish_str), out); - // 2) Separate choices:[] usage chunk (matches OpenAI stream_options.include_usage) - if let Some(usage) = &self.usage { - out.push(sse_data(&json!({ - "id": self.id, - "object": "chat.completion.chunk", - "model": self.model, - "choices": [], - "usage": Self::wire_usage(usage), - }))); - } - // 3) [DONE] sentinel - out.push(WireFrame::Sse(Bytes::from_static(b"data: [DONE]\n\n"))); + fn finish_encoded( + &mut self, + reason: FinishReason, + emit: &mut dyn FnMut(EncodedFrame), + ) -> TurnCompletion { + let finish = match reason { + FinishReason::Stop | FinishReason::Compaction => "stop", + FinishReason::ToolCalls => "tool_calls", + FinishReason::Length | FinishReason::Incomplete(_) => "length", + FinishReason::ContentFilter | FinishReason::Refusal => "content_filter", + }; + let usage = self.usage.as_ref().map(Self::wire_usage); + if !self.finished && self.stream { + if !self.wire.role_sent { + emit(self.wire.chunk(json!({}), None, FrameKind::Lifecycle, 0)); + } + emit( + self.wire + .chunk(json!({}), Some(finish), FrameKind::Terminal, 0), + ); + if self.wire.include_usage { + let fallback; + let usage = if let Some(usage) = &usage { + usage + } else { + fallback = Self::wire_usage(&Usage::default()); + &fallback + }; + emit( + self.wire + .frame(json!([]), Some(usage), FrameKind::Terminal, 0), + ); } + emit(EncodedFrame::new( + WireFrame::Sse(Bytes::from_static(b"data: [DONE]\n\n")), + FrameKind::Terminal, + 0, + )); } + self.finished = true; - let mut message = serde_json::Map::new(); - message.insert("role".into(), json!("assistant")); - if !self.text_buf.is_empty() || self.tool_calls_acc.is_empty() { - message.insert("content".into(), json!(self.text_buf)); - } else { - message.insert("content".into(), Value::Null); + let mut message = json!({ "role": "assistant", "content": null }); + if !self.text.is_empty() || self.tool_calls.is_empty() { + message["content"] = Value::String(std::mem::take(&mut self.text)); } - if !self.reasoning_buf.is_empty() { - message.insert("reasoning_content".into(), json!(self.reasoning_buf)); + if !self.reasoning.is_empty() { + message["reasoning_content"] = Value::String(std::mem::take(&mut self.reasoning)); } - if !self.refusal_buf.is_empty() { - message.insert("refusal".into(), json!(self.refusal_buf)); + if !self.refusal.is_empty() { + message["refusal"] = Value::String(std::mem::take(&mut self.refusal)); } - if !self.tool_calls_acc.is_empty() { - message.insert( - "tool_calls".into(), - Value::Array(self.tool_calls_acc.clone()), - ); + if !self.tool_calls.is_empty() { + message["tool_calls"] = Value::Array(std::mem::take(&mut self.tool_calls)); } - let mut resp = json!({ - "id": self.id, + let mut response_json = json!({ + "id": self.wire.id, "object": "chat.completion", - "model": self.model, - "choices": [{ - "index": 0, - "message": Value::Object(message), - "finish_reason": finish_str, - }] + "created": self.wire.created, + "model": self.wire.model, + "choices": [{ "index": 0, "message": null, "finish_reason": finish }], }); - if let Some(usage) = &self.usage { - resp["usage"] = Self::wire_usage(usage); + response_json["choices"][0]["message"] = message; + if let Some(usage) = usage { + response_json["usage"] = usage; } - TurnCompletion { - response_json: resp, - response_id: self.id.clone(), + response_json, + response_id: self.wire.id.clone(), ws_reusable: false, errored: self.errored, } @@ -328,3 +443,144 @@ impl WireEncoder for ChatCompletionsEncoder { self.finished } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::codec::sse_json; + + #[test] + fn stream_usage_and_reasoning_follow_request_and_profile() { + for (include_usage, profile, reasoning) in [ + (false, ProviderDialectProfile::StandardOpenAi, false), + (true, ProviderDialectProfile::DeepSeekChat, true), + (false, ProviderDialectProfile::KimiChat, true), + ] { + let options = RequestOptions { + stream_include_usage: include_usage, + ..Default::default() + }; + let mut encoder = ChatCompletionsEncoder::with_options( + "chat_1".into(), + "test".into(), + true, + &options, + profile, + ) + .with_created_at(42); + let mut frames: Vec<_> = encoder + .encode_event(TurnEvent::Reasoning { + text: "想".into(), + chunk_chars: 1, + signature: None, + encrypted_content: None, + }) + .collect(); + assert_eq!(frames.len(), usize::from(reasoning)); + if reasoning { + assert_eq!(frames[0].semantic_bytes, 3); + assert_eq!( + sse_json(&frames[0])["choices"][0]["delta"]["reasoning_content"], + "想" + ); + } + frames.extend(encoder.encode_event(TurnEvent::Text { + text: "ok".into(), + chunk_chars: 1, + citations: Vec::new(), + })); + frames.extend(encoder.encode_event(TurnEvent::Usage(Usage::new(7, 2)))); + let result = + encoder.finish_encoded(FinishReason::Stop, &mut |frame| frames.push(frame)); + assert_eq!( + result.response_json["choices"][0]["message"] + .get("reasoning_content") + .is_some(), + reasoning + ); + let WireFrame::Sse(last) = &frames.pop().unwrap().wire else { + panic!("expected SSE"); + }; + assert_eq!(&last[..], b"data: [DONE]\n\n"); + let events: Vec<_> = frames.iter().map(sse_json).collect(); + assert!(events.iter().all(|event| event["created"] == 42)); + let finish_index = events.len() - 1 - usize::from(include_usage); + assert_eq!(events[finish_index]["choices"][0]["finish_reason"], "stop"); + for event in &events[..=finish_index] { + assert_eq!(event.get("usage"), include_usage.then_some(&Value::Null)); + } + if include_usage { + let usage = &events[finish_index + 1]; + assert_eq!(usage["choices"], json!([])); + assert_eq!( + usage["usage"], + json!({ "prompt_tokens": 7, "completion_tokens": 2, "total_tokens": 9 }) + ); + } + } + } + + #[test] + fn tool_deltas_fold_into_the_same_calls_as_json() { + use crate::plan::ToolCallPayload; + + let calls = vec![ + ToolCallSpec::new("call_a", "lookup", json!({ "q": "東京" })).with_chunk_chars(3), + ToolCallSpec::with_payload( + "call_b", + "apply_patch", + ToolCallPayload::FreeformInput("line\n🦀".into()), + ) + .with_chunk_chars(2), + ]; + let mut stream = + ChatCompletionsEncoder::new("chat_1".into(), "test".into(), true).with_created_at(42); + let mut json_encoder = + ChatCompletionsEncoder::new("chat_1".into(), "test".into(), false).with_created_at(42); + + let mut folded = [Value::Null, Value::Null]; + for call in calls { + let event = TurnEvent::ToolCall(call); + for frame in stream.encode_event(event.clone()) { + let event = sse_json(&frame); + let delta = &event["choices"][0]["delta"]["tool_calls"][0]; + let index = delta["index"].as_u64().unwrap() as usize; + let (member, field) = if index == 0 { + ("function", "arguments") + } else { + ("custom", "input") + }; + if delta.get("id").is_some() { + let mut call = delta.clone(); + call.as_object_mut().unwrap().remove("index"); + folded[index] = call; + } else { + let mut input = folded[index][member][field].as_str().unwrap().to_owned(); + input.push_str(delta[member][field].as_str().unwrap()); + folded[index][member][field] = Value::String(input); + } + } + assert_eq!(json_encoder.encode_event(event).count(), 0); + } + let json = json_encoder + .finish_encoded(FinishReason::ToolCalls, &mut |_| panic!("unexpected frame")) + .response_json; + assert_eq!( + json["choices"][0]["message"]["tool_calls"], + Value::Array(folded.into()) + ); + assert_eq!( + json["choices"][0]["message"]["tool_calls"], + json!([ + {"id": "call_a", "type": "function", "function": {"name": "lookup", "arguments": "{\"q\":\"東京\"}"}}, + {"id": "call_b", "type": "custom", "custom": {"name": "apply_patch", "input": "line\n🦀"}} + ]) + ); + assert_eq!( + stream + .finish_encoded(FinishReason::ToolCalls, &mut |_| {}) + .response_json, + json + ); + } +} diff --git a/tools/mock-ai/src/codec/mod.rs b/tools/mock-ai/src/codec/mod.rs index 95b2e0ffb99..7654886887a 100644 --- a/tools/mock-ai/src/codec/mod.rs +++ b/tools/mock-ai/src/codec/mod.rs @@ -21,19 +21,22 @@ pub mod anthropic; pub mod chat_completions; pub mod responses; -use crate::plan::{FinishReason, HttpErrorSpec, TurnEvent}; -use crate::protocol::Protocol; +use crate::plan::{FinishReason, HttpErrorSpec, ProviderDialectProfile, TurnEvent}; +use crate::protocol::{Protocol, RequestOptions}; use bytes::Bytes; +use serde::Serialize; +use serde::ser::SerializeMap as _; use serde_json::{Value, json}; +use std::borrow::Cow; +use std::time::{SystemTime, UNIX_EPOCH}; -/// Wire frame emitted by a protocol encoder. +pub use crate::plan::FrameKind; + +/// Transport payload used by the existing server adapters. #[derive(Debug, Clone)] pub enum WireFrame { - /// HTTP SSE chunk (already formatted as `data: ...\n\n` or `event: ...\ndata: ...\n\n`). Sse(Bytes), - /// WebSocket JSON text message. WsText(String), - /// Raw bytes written directly onto HTTP body (escape hatch). Raw(Bytes), } @@ -46,24 +49,139 @@ impl WireFrame { } } +/// A wire payload with the metadata needed for pacing and TTFT accounting. +#[derive(Debug, Clone)] +pub struct EncodedFrame { + pub wire: WireFrame, + pub kind: FrameKind, + pub semantic_bytes: usize, +} + +impl EncodedFrame { + pub fn new(wire: WireFrame, kind: FrameKind, semantic_bytes: usize) -> Self { + Self { + wire, + kind, + semantic_bytes, + } + } + + pub fn new_sse( + event: Option<&str>, + payload: &T, + kind: FrameKind, + semantic_bytes: usize, + ) -> Self { + let mut wire = Vec::new(); + if let Some(event) = event { + wire.extend_from_slice(b"event: "); + wire.extend_from_slice(event.as_bytes()); + wire.push(b'\n'); + } + wire.extend_from_slice(b"data: "); + serde_json::to_writer(&mut wire, payload).expect("serializing an SSE event"); + wire.extend_from_slice(b"\n\n"); + Self::new(WireFrame::Sse(wire.into()), kind, semantic_bytes) + } + + pub fn new_ws( + payload: &T, + kind: FrameKind, + semantic_bytes: usize, + ) -> Self { + Self::new( + WireFrame::WsText( + serde_json::to_string(payload).expect("serializing a websocket event"), + ), + kind, + semantic_bytes, + ) + } + + pub fn byte_len(&self) -> usize { + self.wire.byte_len() + } + + fn comment(comment: &str) -> Self { + Self::new( + WireFrame::Sse(format!(": {comment}\n\n").into()), + FrameKind::Keepalive, + 0, + ) + } +} + +struct StringField<'a>(&'a str, &'a str); + +impl Serialize for StringField<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(Some(1))?; + map.serialize_entry(self.0, self.1)?; + map.end() + } +} + +/// Frames for one plan event. The prefix contains only lifecycle or atomic frames. +/// Chunked payloads are encoded when the iterator advances. +#[derive(Default)] +pub struct EventFrames<'a> { + prefix: std::vec::IntoIter, + rest: Option + Send + 'a>>, +} + +impl<'a> EventFrames<'a> { + fn prefix(prefix: Vec) -> Self { + Self { + prefix: prefix.into_iter(), + rest: None, + } + } + + fn then( + prefix: Vec, + rest: impl Iterator + Send + 'a, + ) -> Self { + Self { + prefix: prefix.into_iter(), + rest: Some(Box::new(rest)), + } + } +} + +impl Iterator for EventFrames<'_> { + type Item = EncodedFrame; + + fn next(&mut self) -> Option { + self.prefix.next().or_else(|| self.rest.as_mut()?.next()) + } +} + /// Terminal state produced when an encoder finishes a turn. #[derive(Debug, Clone, Default)] pub struct TurnCompletion { - /// Complete JSON response body (for non-streaming HTTP responses & Responses storage). + /// Complete JSON body for non-streaming HTTP and Responses storage. pub response_json: Value, - /// Response/message ID emitted on the wire. pub response_id: String, - /// True if a Responses WebSocket connection may safely reuse this socket for another turn. pub ws_reusable: bool, - /// True if the turn ended with a mid-stream error. pub errored: bool, } -/// Stateful per-turn encoder translating semantic `TurnEvent`s into wire frames. pub trait WireEncoder: Send { - fn push_event(&mut self, event: TurnEvent, out: &mut Vec); - fn finish(&mut self, reason: FinishReason, out: &mut Vec) -> TurnCompletion; + fn encode_event(&mut self, event: TurnEvent) -> EventFrames<'_>; + fn finish_encoded( + &mut self, + reason: FinishReason, + emit: &mut dyn FnMut(EncodedFrame), + ) -> TurnCompletion; fn is_finished(&self) -> bool; + + fn push_event(&mut self, event: TurnEvent, out: &mut Vec) { + out.extend(self.encode_event(event).map(|frame| frame.wire)); + } + + fn finish(&mut self, reason: FinishReason, out: &mut Vec) -> TurnCompletion { + self.finish_encoded(reason, &mut |frame| out.push(frame.wire)) + } } pub fn create_encoder( @@ -71,25 +189,51 @@ pub fn create_encoder( response_id: String, model: String, stream: bool, +) -> Box { + // The original server entry point has no request options. + let mut options = RequestOptions::default(); + let profile = match protocol { + Protocol::OpenaiChatCompletions => { + options.stream_include_usage = true; + ProviderDialectProfile::DeepSeekChat + } + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { + options.include.push("reasoning.encrypted_content".into()); + ProviderDialectProfile::OpenAiResponses + } + Protocol::AnthropicMessages => ProviderDialectProfile::AnthropicMessages, + }; + create_encoder_with_options(protocol, response_id, model, stream, &options, profile) +} + +pub fn create_encoder_with_options( + protocol: Protocol, + response_id: String, + model: String, + stream: bool, + options: &RequestOptions, + profile: ProviderDialectProfile, ) -> Box { match protocol { - Protocol::OpenaiChatCompletions => Box::new(chat_completions::ChatCompletionsEncoder::new( - response_id, - model, - stream, - )), - Protocol::OpenaiResponsesHttp => Box::new(responses::ResponsesEncoder::new( - response_id, - model, - false, - stream, - )), - Protocol::OpenaiResponsesWs => Box::new(responses::ResponsesEncoder::new( - response_id, - model, - true, - true, - )), + Protocol::OpenaiChatCompletions => { + Box::new(chat_completions::ChatCompletionsEncoder::with_options( + response_id, + model, + stream, + options, + profile, + )) + } + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { + let websocket = protocol == Protocol::OpenaiResponsesWs; + Box::new(responses::ResponsesEncoder::with_options( + response_id, + model, + websocket, + stream || websocket, + options, + )) + } Protocol::AnthropicMessages => { Box::new(anthropic::AnthropicEncoder::new(response_id, model, stream)) } @@ -98,61 +242,96 @@ pub fn create_encoder( /// Format a pre-stream HTTP error body in the wire envelope expected by the client protocol. pub fn format_http_error_body(protocol: Protocol, spec: &HttpErrorSpec) -> Value { + let profile = match protocol { + Protocol::AnthropicMessages => ProviderDialectProfile::AnthropicMessages, + Protocol::OpenaiChatCompletions => ProviderDialectProfile::StandardOpenAi, + _ => ProviderDialectProfile::OpenAiResponses, + }; + format_http_error_body_for_profile(profile, spec) +} + +pub fn format_http_error_body_for_profile( + profile: ProviderDialectProfile, + spec: &HttpErrorSpec, +) -> Value { if let Some(raw) = &spec.raw_body { return raw.clone(); } - match protocol { - Protocol::AnthropicMessages => json!({ - "type": "error", - "error": { - "type": spec.error_type, - "message": spec.message, - } - }), - Protocol::OpenaiChatCompletions - | Protocol::OpenaiResponsesHttp - | Protocol::OpenaiResponsesWs => { - let mut err = serde_json::Map::new(); - err.insert("message".into(), json!(spec.message)); - err.insert("type".into(), json!(spec.error_type)); - if let Some(code) = &spec.code { - err.insert("code".into(), json!(code)); - } - json!({ "error": Value::Object(err) }) - } + let mut detail = json!({ "message": spec.message, "type": spec.error_type }); + if profile == ProviderDialectProfile::AnthropicMessages { + return json!({ "type": "error", "error": detail }); } + if let Some(code) = &spec.code { + detail["code"] = json!(code); + } + json!({ "error": detail }) } -/// Split UTF-8 text into chunks of at most `chunk_chars` Unicode scalar values. -/// `chunk_chars == 0` returns the entire string as a single chunk (if non-empty). -pub fn split_utf8_chunks(text: &str, chunk_chars: usize) -> Vec<&str> { - if text.is_empty() { - return Vec::new(); - } - if chunk_chars == 0 { - return vec![text]; - } - let mut chunks = Vec::new(); - let mut start = 0; - let mut count = 0; - for (idx, _) in text.char_indices() { - if count == chunk_chars { - chunks.push(&text[start..idx]); - start = idx; - count = 0; +#[derive(Clone, Debug)] +pub struct Utf8ChunkIter<'a> { + remaining: &'a str, + chunk_chars: usize, +} + +impl<'a> Iterator for Utf8ChunkIter<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option { + if self.remaining.is_empty() { + return None; } - count += 1; + let end = if self.chunk_chars == 0 { + self.remaining.len() + } else { + self.remaining + .char_indices() + .nth(self.chunk_chars) + .map_or(self.remaining.len(), |(index, _)| index) + }; + let (chunk, remaining) = self.remaining.split_at(end); + self.remaining = remaining; + Some(chunk) } - if start < text.len() { - chunks.push(&text[start..]); +} + +/// Split UTF-8 text into borrowed chunks of at most the given number of Unicode scalars. +/// A size of zero yields the whole string in one chunk. +pub fn split_utf8_chunks(text: &str, chunk_chars: usize) -> Utf8ChunkIter<'_> { + Utf8ChunkIter { + remaining: text, + chunk_chars, } - chunks } -pub(crate) fn sse_data(value: &Value) -> WireFrame { - WireFrame::Sse(Bytes::from(format!("data: {value}\n\n"))) +fn chunk_frames<'a>( + text: Cow<'a, str>, + chunk_chars: usize, + mut frame: impl FnMut(&str) -> EncodedFrame + 'a, +) -> impl Iterator + 'a { + let mut offset = 0; + std::iter::from_fn(move || { + let chunk = split_utf8_chunks(&text[offset..], chunk_chars).next()?; + offset += chunk.len(); + Some(frame(chunk)) + }) +} + +fn unix_timestamp() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() } -pub(crate) fn sse_named(event: &str, value: &Value) -> WireFrame { - WireFrame::Sse(Bytes::from(format!("event: {event}\ndata: {value}\n\n"))) +#[cfg(test)] +fn sse_json(frame: &EncodedFrame) -> Value { + let WireFrame::Sse(bytes) = &frame.wire else { + panic!("expected SSE, got {frame:?}"); + }; + let payload = std::str::from_utf8(bytes) + .unwrap() + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .expect("SSE data line"); + serde_json::from_str(payload).unwrap() } diff --git a/tools/mock-ai/src/codec/responses.rs b/tools/mock-ai/src/codec/responses.rs index 18d28c13254..bc6fcf45bde 100644 --- a/tools/mock-ai/src/codec/responses.rs +++ b/tools/mock-ai/src/codec/responses.rs @@ -17,651 +17,858 @@ * under the License. */ -use super::{TurnCompletion, WireEncoder, WireFrame, split_utf8_chunks, sse_data}; -use crate::plan::{FinishReason, NativeToolEvent, TurnEvent, Usage}; +use super::{ + EncodedFrame, EventFrames, FrameKind, StringField, TurnCompletion, WireEncoder, WireFrame, + split_utf8_chunks, unix_timestamp, +}; +use crate::plan::{Citation, FinishReason, NativeToolEvent, ToolCallSpec, TurnEvent, Usage}; +use crate::protocol::RequestOptions; +use serde::Serialize; use serde_json::{Value, json}; pub struct ResponsesEncoder { - id: String, - model: String, - websocket: bool, - stream: bool, - created_emitted: bool, + wire: ResponsesWire, + created: bool, finished: bool, - errored: bool, - next_item_seq: usize, - active_message: Option, - active_reasoning: Option, - completed_output: Vec, + include_encrypted_reasoning: bool, + active: Option, + output: Vec, usage: Option, + failure: Option, +} + +struct ResponsesWire { + id: String, + model: String, + created_at: u64, + transport: Option, + sequence: usize, +} + +#[derive(Clone, Copy)] +enum StreamTransport { + Sse, + WebSocket, +} + +#[derive(Serialize)] +struct Sequenced { + sequence_number: usize, + #[serde(flatten)] + event: T, +} + +#[derive(Serialize)] +struct ItemEvent<'a> { + #[serde(rename = "type")] + kind: &'a str, + output_index: usize, + item: &'a Value, +} + +#[derive(Serialize)] +struct ResponseEvent<'a> { + #[serde(rename = "type")] + kind: &'a str, + response: &'a Value, +} + +impl ResponsesWire { + fn frame(&mut self, event: impl Serialize, kind: FrameKind, bytes: usize) -> EncodedFrame { + let payload = Sequenced { + sequence_number: self.sequence, + event, + }; + self.sequence += 1; + match self + .transport + .expect("only streaming encoders emit wire frames") + { + StreamTransport::Sse => EncodedFrame::new_sse(None, &payload, kind, bytes), + StreamTransport::WebSocket => EncodedFrame::new_ws(&payload, kind, bytes), + } + } + + fn raw_json(&self, value: &Value) -> EncodedFrame { + match self + .transport + .expect("only streaming encoders emit wire frames") + { + StreamTransport::Sse => EncodedFrame::new_sse(None, value, FrameKind::Lifecycle, 0), + StreamTransport::WebSocket => EncodedFrame::new_ws(value, FrameKind::Lifecycle, 0), + } + } + + fn response(&self, status: &str) -> Value { + json!({ + "id": self.id, "object": "response", "status": status, + "model": self.model, "created_at": self.created_at, "output": [], + }) + } + + fn item(&mut self, kind: &str, output_index: usize, item: &Value) -> EncodedFrame { + self.frame( + ItemEvent { + kind, + output_index, + item, + }, + FrameKind::Lifecycle, + 0, + ) + } +} + +enum ActiveItem { + Message { + id: String, + content: Vec, + part: Option, + }, + Reasoning { + id: String, + summary: String, + encrypted_content: Option, + }, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PartKind { + Text, + Refusal, +} + +impl PartKind { + fn fragment(self) -> &'static str { + match self { + Self::Text => "text", + Self::Refusal => "refusal", + } + } + + fn part_type(self) -> &'static str { + match self { + Self::Text => "output_text", + Self::Refusal => "refusal", + } + } + + fn delta_event(self) -> &'static str { + match self { + Self::Text => "response.output_text.delta", + Self::Refusal => "response.refusal.delta", + } + } + + fn done_event(self) -> &'static str { + match self { + Self::Text => "response.output_text.done", + Self::Refusal => "response.refusal.done", + } + } } -struct ActiveMessage { - item_id: String, +struct MessagePart { + kind: PartKind, text: String, - refusal: String, annotations: Vec, } -struct ActiveReasoning { - item_id: String, - summary: String, - encrypted_content: Option, +#[derive(Clone, Copy, Serialize)] +struct PartLocation<'a> { + item_id: &'a str, + output_index: usize, + content_index: usize, +} + +#[derive(Serialize)] +struct PartEvent<'a> { + #[serde(rename = "type")] + kind: &'a str, + #[serde(flatten)] + location: PartLocation<'a>, + part: &'a Value, +} + +#[derive(Serialize)] +struct PartTextEvent<'a> { + #[serde(rename = "type")] + kind: &'a str, + #[serde(flatten)] + location: PartLocation<'a>, + #[serde(flatten)] + text: StringField<'a>, +} + +#[derive(Serialize)] +struct ToolInputEvent<'a> { + #[serde(rename = "type")] + kind: &'a str, + item_id: &'a str, + output_index: usize, + #[serde(skip_serializing_if = "Option::is_none")] + name: Option<&'a str>, + #[serde(flatten)] + input: StringField<'a>, +} + +fn close_part( + wire: &mut ResponsesWire, + output_index: usize, + item_id: &str, + content: &mut Vec, + part: &mut Option, + emit: &mut dyn FnMut(EncodedFrame), +) { + let Some(part) = part.take() else { + return; + }; + let location = PartLocation { + item_id, + output_index, + content_index: content.len(), + }; + let mut value = json!({ "type": part.kind.part_type() }); + value[part.kind.fragment()] = Value::String(part.text); + if part.kind == PartKind::Text { + value["annotations"] = Value::Array(part.annotations); + } + if wire.transport.is_some() { + let field = part.kind.fragment(); + let text = value[field].as_str().expect("a content part has text"); + emit(wire.frame( + PartTextEvent { + kind: part.kind.done_event(), + location, + text: StringField(field, text), + }, + FrameKind::Lifecycle, + 0, + )); + emit(wire.frame( + PartEvent { + kind: "response.content_part.done", + location, + part: &value, + }, + FrameKind::Lifecycle, + 0, + )); + } + content.push(value); } impl ResponsesEncoder { pub fn new(id: String, model: String, websocket: bool, stream: bool) -> Self { + Self::with_options(id, model, websocket, stream, &RequestOptions::default()) + } + + pub fn with_options( + id: String, + model: String, + websocket: bool, + stream: bool, + options: &RequestOptions, + ) -> Self { Self { - id, - model, - websocket, - stream, - created_emitted: false, + wire: ResponsesWire { + id, + model, + created_at: unix_timestamp(), + transport: stream.then_some(if websocket { + StreamTransport::WebSocket + } else { + StreamTransport::Sse + }), + sequence: 0, + }, + created: false, finished: false, - errored: false, - next_item_seq: 0, - active_message: None, - active_reasoning: None, - completed_output: Vec::new(), + include_encrypted_reasoning: options + .include + .iter() + .any(|item| item == "reasoning.encrypted_content"), + active: None, + output: Vec::new(), usage: None, + failure: None, } } - fn next_id(&mut self, prefix: &str) -> String { - let idx = self.next_item_seq; - self.next_item_seq += 1; - format!("{prefix}_{}_{idx}", self.id) + pub fn with_created_at(mut self, created_at: u64) -> Self { + self.wire.created_at = created_at; + self } - fn emit(&mut self, value: Value, out: &mut Vec) { - if !self.stream { - return; - } - if self.websocket { - out.push(WireFrame::WsText(value.to_string())); - } else { - out.push(sse_data(&value)); + fn ensure_created(&mut self, emit: &mut dyn FnMut(EncodedFrame)) { + if !self.created && self.wire.transport.is_some() { + self.created = true; + let response = self.wire.response("in_progress"); + emit(self.wire.frame( + ResponseEvent { + kind: "response.created", + response: &response, + }, + FrameKind::Lifecycle, + 0, + )); } } - fn ensure_created(&mut self, out: &mut Vec) { - if !self.created_emitted { - self.created_emitted = true; - let event = json!({ - "type": "response.created", - "response": { - "id": self.id, - "object": "response", - "status": "in_progress", - "model": self.model, - "output": [], + fn item_id(&self, prefix: &str) -> String { + format!("{prefix}_{}_{}", self.wire.id, self.output.len()) + } + + fn close_active(&mut self, emit: &mut dyn FnMut(EncodedFrame)) { + let Some(active) = self.active.take() else { + return; + }; + let index = self.output.len(); + let item = match active { + ActiveItem::Message { + id, + mut content, + mut part, + } => { + close_part(&mut self.wire, index, &id, &mut content, &mut part, emit); + let mut item = json!({ "type": "message", "id": id, "role": "assistant", "status": "completed" }); + item["content"] = Value::Array(content); + item + } + ActiveItem::Reasoning { + id, + summary, + encrypted_content, + } => { + let mut item = json!({ "type": "reasoning", "id": id, "summary": [] }); + if !summary.is_empty() { + if self.wire.transport.is_some() { + emit(self.wire.frame( + json!({ + "type": "response.reasoning_summary_text.done", "item_id": id, + "output_index": index, "summary_index": 0, "text": summary, + }), + FrameKind::Lifecycle, + 0, + )); + } + let mut summary_part = json!({ "type": "summary_text" }); + summary_part["text"] = Value::String(summary); + if self.wire.transport.is_some() { + emit(self.wire.frame( + json!({ + "type": "response.reasoning_summary_part.done", "item_id": id, + "output_index": index, "summary_index": 0, "part": summary_part, + }), + FrameKind::Lifecycle, + 0, + )); + } + item["summary"] = Value::Array(vec![summary_part]); } - }); - self.emit(event, out); + if let Some(encrypted_content) = encrypted_content { + item["encrypted_content"] = Value::String(encrypted_content); + } + item + } + }; + if self.wire.transport.is_some() { + emit(self.wire.item("response.output_item.done", index, &item)); } + self.output.push(item); } - fn close_reasoning(&mut self, out: &mut Vec) { - if let Some(r) = self.active_reasoning.take() { - let mut item = serde_json::Map::new(); - item.insert("type".into(), json!("reasoning")); - item.insert("id".into(), json!(r.item_id)); - item.insert( - "summary".into(), - if r.summary.is_empty() { - json!([]) - } else { - json!([{ "type": "summary_text", "text": r.summary }]) - }, - ); - if let Some(enc) = r.encrypted_content { - item.insert("encrypted_content".into(), json!(enc)); + fn begin_atomic(&mut self, prefix: &mut Vec) -> usize { + self.ensure_created(&mut |frame| prefix.push(frame)); + self.close_active(&mut |frame| prefix.push(frame)); + self.output.len() + } + + fn message( + &mut self, + kind: PartKind, + text: String, + chunk_chars: usize, + citations: Vec, + ) -> EventFrames<'_> { + let mut prefix = Vec::new(); + self.ensure_created(&mut |frame| prefix.push(frame)); + if !matches!(self.active, Some(ActiveItem::Message { .. })) { + self.close_active(&mut |frame| prefix.push(frame)); + let id = self.item_id("msg"); + if self.wire.transport.is_some() { + prefix.push(self.wire.item("response.output_item.added", self.output.len(), &json!({ + "type": "message", "id": id, "role": "assistant", "status": "in_progress", "content": [], + }))); + } + self.active = Some(ActiveItem::Message { + id, + content: Vec::new(), + part: None, + }); + } + let Some(ActiveItem::Message { id, content, part }) = &mut self.active else { + unreachable!() + }; + let output_index = self.output.len(); + let wire = &mut self.wire; + let stream = wire.transport.is_some(); + if part.as_ref().is_none_or(|part| part.kind != kind) { + close_part(wire, output_index, id, content, part, &mut |frame| { + prefix.push(frame) + }); + if stream { + let mut initial = json!({ "type": kind.part_type(), kind.fragment(): "" }); + if kind == PartKind::Text { + initial["annotations"] = json!([]); + } + prefix.push(wire.frame( + PartEvent { + kind: "response.content_part.added", + location: PartLocation { + item_id: id, + output_index, + content_index: content.len(), + }, + part: &initial, + }, + FrameKind::Lifecycle, + 0, + )); } - let item_val = Value::Object(item); - self.completed_output.push(item_val.clone()); - self.emit( + *part = Some(MessagePart { + kind, + text: String::new(), + annotations: Vec::new(), + }); + } + let part = part.as_mut().expect("a message part is active"); + let start = part.text.len(); + append(&mut part.text, text); + let first_annotation = part.annotations.len(); + part.annotations + .extend(citations.into_iter().map(|citation| { json!({ - "type": "response.output_item.done", - "item": item_val, - }), - out, - ); + "type": "url_citation", + "url": citation.url, "title": citation.title.unwrap_or_default(), + "start_index": 0, "end_index": 0, + }) + })); + if !stream { + return EventFrames::default(); } + let location = PartLocation { + item_id: id, + output_index, + content_index: content.len(), + }; + let mut deltas = split_utf8_chunks(&part.text[start..], chunk_chars); + let mut annotations = part.annotations.iter().enumerate().skip(first_annotation); + EventFrames::then( + prefix, + std::iter::from_fn(move || { + if let Some(delta) = deltas.next() { + return Some(wire.frame( + PartTextEvent { + kind: kind.delta_event(), + location, + text: StringField("delta", delta), + }, + FrameKind::SemanticDelta, + delta.len(), + )); + } + let (annotation_index, annotation) = annotations.next()?; + Some(wire.frame(json!({ + "type": "response.output_text.annotation.added", "item_id": location.item_id, + "output_index": location.output_index, "content_index": location.content_index, + "annotation_index": annotation_index, "annotation": annotation, + }), FrameKind::Lifecycle, 0)) + }), + ) } - fn close_message(&mut self, out: &mut Vec) { - if let Some(msg) = self.active_message.take() { - let mut content = Vec::new(); - if !msg.text.is_empty() { - content.push(json!({ - "type": "output_text", - "text": msg.text, - "annotations": msg.annotations, - })); - } - if !msg.refusal.is_empty() { - content.push(json!({ - "type": "refusal", - "refusal": msg.refusal, - })); + fn reasoning( + &mut self, + text: String, + chunk_chars: usize, + encrypted_content: Option, + ) -> EventFrames<'_> { + let mut prefix = Vec::new(); + self.ensure_created(&mut |frame| prefix.push(frame)); + if !matches!(self.active, Some(ActiveItem::Reasoning { .. })) { + self.close_active(&mut |frame| prefix.push(frame)); + let id = self.item_id("rs"); + if self.wire.transport.is_some() { + prefix.push(self.wire.item( + "response.output_item.added", + self.output.len(), + &json!({ + "type": "reasoning", "id": id, "summary": [], + }), + )); } - let item = json!({ - "type": "message", - "id": msg.item_id, - "role": "assistant", - "status": "completed", - "content": content, + self.active = Some(ActiveItem::Reasoning { + id, + summary: String::new(), + encrypted_content: None, }); - self.completed_output.push(item.clone()); - self.emit( + } + let output_index = self.output.len(); + let Some(ActiveItem::Reasoning { + id, + summary, + encrypted_content: stored, + }) = &mut self.active + else { + unreachable!() + }; + if self.include_encrypted_reasoning && encrypted_content.is_some() { + *stored = encrypted_content; + } + let start = summary.len(); + append(summary, text); + let wire = &mut self.wire; + if wire.transport.is_none() { + return EventFrames::default(); + } + if start == 0 && !summary.is_empty() { + prefix.push(wire.frame( json!({ - "type": "response.output_item.done", - "item": item, + "type": "response.reasoning_summary_part.added", "item_id": id, + "output_index": output_index, "summary_index": 0, + "part": { "type": "summary_text", "text": "" }, }), - out, - ); + FrameKind::Lifecycle, + 0, + )); } + EventFrames::then( + prefix, + split_utf8_chunks(&summary[start..], chunk_chars).map(move |delta| { + wire.frame( + json!({ + "type": "response.reasoning_summary_text.delta", "item_id": id, + "output_index": output_index, "summary_index": 0, "delta": delta, + }), + FrameKind::SemanticDelta, + delta.len(), + ) + }), + ) } - fn ensure_message(&mut self, out: &mut Vec) -> String { - self.close_reasoning(out); - if let Some(msg) = &self.active_message { - return msg.item_id.clone(); + fn tool_call(&mut self, mut spec: ToolCallSpec) -> EventFrames<'_> { + let mut prefix = Vec::new(); + let output_index = self.begin_atomic(&mut prefix); + let id = spec + .item_id + .take() + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| self.item_id("fc")); + let call_id = if spec.id.is_empty() { + self.item_id("call") + } else { + std::mem::take(&mut spec.id) + }; + let (kind, field, delta_event, done_event) = if spec.is_freeform() { + ( + "custom_tool_call", + "input", + "response.custom_tool_call_input.delta", + "response.custom_tool_call_input.done", + ) + } else { + ( + "function_call", + "arguments", + "response.function_call_arguments.delta", + "response.function_call_arguments.done", + ) + }; + let input = spec.take_wire_arguments(); + let wire = &mut self.wire; + let mut item = json!({ "type": kind, "id": id, "call_id": call_id, "name": spec.name, "status": "completed" }); + if let Some(namespace) = spec.namespace { + item["namespace"] = Value::String(namespace); } - let item_id = self.next_id("msg"); - self.emit( - json!({ - "type": "response.output_item.added", - "item": { - "type": "message", - "id": item_id, - "role": "assistant", - "status": "in_progress", - "content": [], + if wire.transport.is_some() { + let mut added = item.clone(); + added["status"] = json!("in_progress"); + added[field] = json!(""); + prefix.push(wire.item("response.output_item.added", output_index, &added)); + } + item[field] = Value::String(input); + self.output.push(item); + if wire.transport.is_none() { + return EventFrames::default(); + } + let item = &self.output[output_index]; + let input = item[field] + .as_str() + .expect("encoded tool input is a string"); + let mut chunks = split_utf8_chunks(input, spec.chunk_chars); + let mut done = false; + let mut item_done = false; + EventFrames::then( + prefix, + std::iter::from_fn(move || { + if let Some(delta) = chunks.next() { + return Some(wire.frame( + ToolInputEvent { + kind: delta_event, + item_id: &id, + output_index, + name: None, + input: StringField("delta", delta), + }, + FrameKind::SemanticDelta, + delta.len(), + )); + } + if !std::mem::replace(&mut done, true) { + return Some(wire.frame( + ToolInputEvent { + kind: done_event, + item_id: &id, + output_index, + name: Some(&spec.name), + input: StringField(field, input), + }, + FrameKind::Lifecycle, + 0, + )); + } + if !std::mem::replace(&mut item_done, true) { + return Some(wire.item("response.output_item.done", output_index, item)); } + None }), - out, - ); - self.active_message = Some(ActiveMessage { - item_id: item_id.clone(), - text: String::new(), - refusal: String::new(), - annotations: Vec::new(), - }); - item_id + ) } fn wire_usage(usage: &Usage) -> Value { let reasoning = usage.reasoning_tokens.unwrap_or(0); let output_tokens = usage.output_tokens.max(reasoning); - let mut obj = serde_json::Map::new(); - obj.insert("input_tokens".into(), json!(usage.input_tokens)); - obj.insert("output_tokens".into(), json!(output_tokens)); - obj.insert( - "total_tokens".into(), - json!(usage.input_tokens.saturating_add(output_tokens)), - ); - if let Some(cached) = usage.cache_read_tokens { - obj.insert( - "input_tokens_details".into(), - json!({ "cached_tokens": cached }), - ); - } - if let Some(r) = usage.reasoning_tokens { - obj.insert( - "output_tokens_details".into(), - json!({ "reasoning_tokens": r }), - ); - } - Value::Object(obj) + json!({ + "input_tokens": usage.input_tokens, "output_tokens": output_tokens, + "total_tokens": usage.input_tokens.saturating_add(output_tokens), + "input_tokens_details": { "cached_tokens": usage.cache_read_tokens.unwrap_or(0) }, + "output_tokens_details": { "reasoning_tokens": reasoning }, + }) + } +} + +fn append(buffer: &mut String, text: String) { + if buffer.is_empty() { + *buffer = text; + } else { + buffer.push_str(&text); } } impl WireEncoder for ResponsesEncoder { - fn push_event(&mut self, event: TurnEvent, out: &mut Vec) { + fn encode_event(&mut self, event: TurnEvent) -> EventFrames<'_> { if self.finished { - return; + return EventFrames::default(); } + let mut prefix = Vec::new(); match event { - TurnEvent::Reasoning { - text, - chunk_chars, - encrypted_content, - .. - } => { - self.ensure_created(out); - self.close_message(out); - if self.active_reasoning.is_none() { - let item_id = self.next_id("rs"); - self.emit( - json!({ - "type": "response.output_item.added", - "item": { - "type": "reasoning", - "id": item_id, - "summary": [], - } - }), - out, - ); - self.active_reasoning = Some(ActiveReasoning { - item_id, - summary: String::new(), - encrypted_content: None, - }); - } - if let Some(enc) = encrypted_content - && let Some(r) = &mut self.active_reasoning - { - r.encrypted_content = Some(enc); - } - let item_id = self.active_reasoning.as_ref().unwrap().item_id.clone(); - for chunk in split_utf8_chunks(&text, chunk_chars) { - if let Some(r) = &mut self.active_reasoning { - r.summary.push_str(chunk); - } - self.emit( - json!({ - "type": "response.reasoning_summary_text.delta", - "item_id": item_id, - "summary_index": 0, - "delta": chunk, - }), - out, - ); - } - } TurnEvent::Text { text, chunk_chars, citations, - } => { - self.ensure_created(out); - let item_id = self.ensure_message(out); - for chunk in split_utf8_chunks(&text, chunk_chars) { - if let Some(msg) = &mut self.active_message { - msg.text.push_str(chunk); - } - self.emit( - json!({ - "type": "response.output_text.delta", - "item_id": item_id, - "content_index": 0, - "delta": chunk, - }), - out, - ); - } - for cit in citations { - let ann = json!({ - "type": "url_citation", - "url": cit.url, - "title": cit.title.unwrap_or_default(), - }); - let annotation_index = if let Some(msg) = &mut self.active_message { - let idx = msg.annotations.len(); - msg.annotations.push(ann.clone()); - idx - } else { - 0 - }; - self.emit( - json!({ - "type": "response.output_text.annotation.added", - "item_id": item_id, - "content_index": 0, - "annotation_index": annotation_index, - "annotation": ann, - }), - out, - ); - } - } + } => return self.message(PartKind::Text, text, chunk_chars, citations), TurnEvent::Refusal { text } => { - self.ensure_created(out); - let item_id = self.ensure_message(out); - if let Some(msg) = &mut self.active_message { - msg.refusal.push_str(&text); - } - self.emit( - json!({ - "type": "response.refusal.delta", - "item_id": item_id, - "content_index": 0, - "delta": text, - }), - out, - ); + return self.message(PartKind::Refusal, text, 0, Vec::new()); } - TurnEvent::ToolCall(spec) => { - self.ensure_created(out); - self.close_reasoning(out); - self.close_message(out); - // Deliberately keep item_id distinct from call_id to catch ID mix-ups. - let item_id = spec - .item_id - .clone() - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| self.next_id("fc")); - let call_id = if spec.id.is_empty() { - self.next_id("call") - } else { - spec.id.clone() + TurnEvent::Reasoning { + text, + chunk_chars, + encrypted_content, + .. + } => return self.reasoning(text, chunk_chars, encrypted_content), + TurnEvent::ToolCall(spec) => return self.tool_call(spec), + TurnEvent::NativeTool(tool) => { + let index = self.begin_atomic(&mut prefix); + let (id, query, results) = match tool { + NativeToolEvent::WebSearch { id, query, results } => (id, query, Some(results)), + NativeToolEvent::WebSearchStarted { id, query } => (id, query, None), }; - let args = spec.arguments_string(); - - if spec.custom_tool { - self.emit( - json!({ - "type": "response.output_item.added", - "item": { - "type": "custom_tool_call", - "id": item_id, - "call_id": call_id, - "name": spec.name, - "input": "", - "status": "in_progress", - } - }), - out, - ); - for chunk in split_utf8_chunks(&args, spec.chunk_chars) { - self.emit( - json!({ - "type": "response.custom_tool_call_input.delta", - "item_id": item_id, - "delta": chunk, - }), - out, - ); - } - let done_item = json!({ - "type": "custom_tool_call", - "id": item_id, - "call_id": call_id, - "name": spec.name, - "input": args, - "status": "completed", - }); - self.completed_output.push(done_item.clone()); - self.emit( - json!({ - "type": "response.output_item.done", - "item": done_item, - }), - out, - ); + let id = if id.is_empty() { + self.item_id("ws") } else { - self.emit( - json!({ - "type": "response.output_item.added", - "item": { - "type": "function_call", - "id": item_id, - "call_id": call_id, - "name": spec.name, - "arguments": "", - "status": "in_progress", - } - }), - out, - ); - for chunk in split_utf8_chunks(&args, spec.chunk_chars) { - self.emit( + id + }; + let mut item = + json!({ "type": "web_search_call", "id": id, "status": "in_progress" }); + if !query.is_empty() || results.is_some() { + item["action"] = json!({ "type": "search", "query": query }); + } + if self.wire.transport.is_some() { + prefix.push(self.wire.item("response.output_item.added", index, &item)); + } + if let Some(results) = results { + let sources: Vec<_> = results + .into_iter() + .map(|result| { json!({ - "type": "response.function_call_arguments.delta", - "item_id": item_id, - "delta": chunk, - }), - out, - ); + "type": "url", "url": result.url, "title": result.title, + }) + }) + .collect(); + item["status"] = json!("completed"); + item["action"]["sources"] = Value::Array(sources); + if self.wire.transport.is_some() { + prefix.push(self.wire.item("response.output_item.done", index, &item)); } - let done_item = json!({ - "type": "function_call", - "id": item_id, - "call_id": call_id, - "name": spec.name, - "arguments": args, - "status": "completed", - }); - self.completed_output.push(done_item.clone()); - self.emit( - json!({ - "type": "response.output_item.done", - "item": done_item, - }), - out, - ); } + self.output.push(item); } - TurnEvent::NativeTool(NativeToolEvent::WebSearch { id, query, results }) => { - self.ensure_created(out); - self.close_reasoning(out); - self.close_message(out); - let item_id = if id.is_empty() { - self.next_id("ws") + TurnEvent::NativeCompaction(compaction) => { + let index = self.begin_atomic(&mut prefix); + let id = if compaction.id.is_empty() { + self.item_id("cmp") } else { - id + compaction.id }; - self.emit( - json!({ - "type": "response.output_item.added", - "item": { - "type": "web_search_call", - "id": item_id, - "status": "in_progress", - "action": { "type": "search", "query": query }, - } - }), - out, - ); - let sources: Vec = results - .iter() - .map(|r| json!({ "type": "url", "url": r.url, "title": r.title })) - .collect(); - let done_item = json!({ - "type": "web_search_call", - "id": item_id, - "status": "completed", - "action": { - "type": "search", - "query": query, - "sources": sources, - }, - }); - self.completed_output.push(done_item.clone()); - self.emit( - json!({ - "type": "response.output_item.done", - "item": done_item, - }), - out, - ); - } - TurnEvent::NativeTool(NativeToolEvent::WebSearchStarted { id, query }) => { - self.ensure_created(out); - self.close_reasoning(out); - self.close_message(out); - let item_id = if id.is_empty() { - self.next_id("ws") + let encrypted = if !compaction.encrypted_content.is_empty() { + compaction.encrypted_content + } else if !compaction.summary.is_empty() { + compaction.summary } else { - id + format!("enc_compaction_{}", self.wire.id) }; - let mut item = serde_json::Map::new(); - item.insert("type".into(), json!("web_search_call")); - item.insert("id".into(), json!(item_id)); - item.insert("status".into(), json!("in_progress")); - if !query.is_empty() { - item.insert("action".into(), json!({ "type": "search", "query": query })); + let mut item = json!({ "type": "compaction", "id": id }); + if self.wire.transport.is_some() { + prefix.push(self.wire.item("response.output_item.added", index, &item)); } - self.emit( - json!({ - "type": "response.output_item.added", - "item": Value::Object(item), - }), - out, - ); - } - TurnEvent::NativeCompaction(comp) => { - self.ensure_created(out); - self.close_reasoning(out); - self.close_message(out); - let item_id = if comp.id.is_empty() { - self.next_id("cmp") - } else { - comp.id - }; - let encrypted = if comp.encrypted_content.is_empty() { - if comp.summary.is_empty() { - format!("enc_compaction_{}", self.id) - } else { - comp.summary - } - } else { - comp.encrypted_content - }; - // Exact same JSON item emitted in output_item.done AND response.completed.response.output - // (required by plugins/agent/model/src/adapters/responses/decode.rs). - let item = json!({ - "type": "compaction", - "id": item_id, - "encrypted_content": encrypted, - }); - self.completed_output.push(item.clone()); - self.emit( - json!({ - "type": "response.output_item.done", - "item": item, - }), - out, - ); - } - TurnEvent::Usage(usage) => { - self.usage = Some(usage); + let bytes = encrypted.len(); + item["encrypted_content"] = Value::String(encrypted); + if self.wire.transport.is_some() { + prefix.push(self.wire.frame( + ItemEvent { + kind: "response.output_item.done", + output_index: index, + item: &item, + }, + FrameKind::SemanticDelta, + bytes, + )); + } + self.output.push(item); } - TurnEvent::MidStreamError(err) => { - self.ensure_created(out); - self.errored = true; + TurnEvent::Usage(usage) => self.usage = Some(usage), + TurnEvent::UsageWithIterations(usage) => self.usage = Some(usage.totals), + TurnEvent::MidStreamError(error) => { + self.ensure_created(&mut |frame| prefix.push(frame)); self.finished = true; - let mut err_obj = serde_json::Map::new(); - err_obj.insert( - "code".into(), - json!(err.code.unwrap_or_else(|| err.error_type.clone())), - ); - err_obj.insert("message".into(), json!(err.message)); - self.emit( - json!({ - "type": "response.failed", - "response": { - "id": self.id, - "object": "response", - "status": "failed", - "model": self.model, - "output": self.completed_output, - "error": Value::Object(err_obj), - } - }), - out, - ); - } - TurnEvent::RawJson { value } => { - self.emit(value, out); + let mut response = self.wire.response("failed"); + response["output"] = Value::Array(std::mem::take(&mut self.output)); + response["error"] = json!({ "code": error.code.unwrap_or(error.error_type), "message": error.message }); + if self.wire.transport.is_some() { + prefix.push(self.wire.frame( + ResponseEvent { + kind: "response.failed", + response: &response, + }, + FrameKind::Terminal, + 0, + )); + } + self.failure = Some(response); } - TurnEvent::StreamStart => { - self.ensure_created(out); + TurnEvent::StreamStart => self.ensure_created(&mut |frame| prefix.push(frame)), + TurnEvent::Flush => self.close_active(&mut |frame| prefix.push(frame)), + TurnEvent::RawJson { value } if self.wire.transport.is_some() => { + prefix.push(self.wire.raw_json(&value)) } - TurnEvent::Flush => { - self.close_reasoning(out); - self.close_message(out); + TurnEvent::SseComment { comment } + if matches!(self.wire.transport, Some(StreamTransport::Sse)) => + { + prefix.push(EncodedFrame::comment(&comment)) } - TurnEvent::SseComment { comment } => { - if self.stream && !self.websocket { - out.push(WireFrame::Sse(bytes::Bytes::from(format!( - ": {comment}\n\n" - )))); - } + TurnEvent::Ping if matches!(self.wire.transport, Some(StreamTransport::Sse)) => { + prefix.push(EncodedFrame::comment("ping")) } - TurnEvent::RawBytes(bytes) => { - if self.websocket { - if let Ok(s) = std::str::from_utf8(&bytes) { - out.push(WireFrame::WsText(s.to_owned())); + TurnEvent::RawBytes(bytes) => match self.wire.transport { + Some(StreamTransport::Sse) => prefix.push(EncodedFrame::new( + WireFrame::Raw(bytes), + FrameKind::Lifecycle, + 0, + )), + Some(StreamTransport::WebSocket) => { + if let Ok(text) = std::str::from_utf8(&bytes) { + prefix.push(EncodedFrame::new( + WireFrame::WsText(text.into()), + FrameKind::Lifecycle, + 0, + )); } - } else { - out.push(WireFrame::Raw(bytes)); } - } - TurnEvent::RedactedThinking { .. } - | TurnEvent::Delay { .. } - | TurnEvent::JitterDelay { .. } - | TurnEvent::Stall - | TurnEvent::HttpError(_) - | TurnEvent::DropConnection - | TurnEvent::TruncateEof - | TurnEvent::Finish { .. } => {} + None => {} + }, + _ => {} } + EventFrames::prefix(prefix) } - fn finish(&mut self, reason: FinishReason, out: &mut Vec) -> TurnCompletion { - self.ensure_created(out); - self.close_reasoning(out); - self.close_message(out); - - let (event_type, status, incomplete_details, ws_reusable) = match &reason { - FinishReason::Length => ( - "response.incomplete", - "incomplete", - Some(json!({ "reason": "max_output_tokens" })), - true, - ), - FinishReason::ContentFilter => ( - "response.incomplete", - "incomplete", - Some(json!({ "reason": "content_filter" })), - false, - ), - FinishReason::Incomplete(detail) => ( - "response.incomplete", - "incomplete", - Some(json!({ "reason": detail })), - detail == "max_output_tokens", - ), - FinishReason::Stop - | FinishReason::ToolCalls - | FinishReason::Compaction - | FinishReason::Refusal => ("response.completed", "completed", None, true), + fn finish_encoded( + &mut self, + reason: FinishReason, + emit: &mut dyn FnMut(EncodedFrame), + ) -> TurnCompletion { + if let Some(response_json) = self.failure.take() { + return TurnCompletion { + response_json, + response_id: self.wire.id.clone(), + ws_reusable: false, + errored: true, + }; + } + let incomplete = match &reason { + FinishReason::Length => Some("max_output_tokens"), + FinishReason::ContentFilter => Some("content_filter"), + FinishReason::Incomplete(detail) => Some(detail.as_str()), + _ => None, }; - - let mut resp = serde_json::Map::new(); - resp.insert("id".into(), json!(self.id)); - resp.insert("object".into(), json!("response")); - resp.insert("status".into(), json!(status)); - resp.insert("model".into(), json!(self.model)); - resp.insert("output".into(), Value::Array(self.completed_output.clone())); - if let Some(details) = incomplete_details { - resp.insert("incomplete_details".into(), details); + let mut response = self.wire.response(if incomplete.is_some() { + "incomplete" + } else { + "completed" + }); + if let Some(reason) = incomplete { + response["incomplete_details"] = json!({ "reason": reason }); } if let Some(usage) = &self.usage { - resp.insert("usage".into(), Self::wire_usage(usage)); + response["usage"] = Self::wire_usage(usage); } - let response_val = Value::Object(resp); - if !self.finished { + self.ensure_created(emit); + self.close_active(emit); + response["output"] = Value::Array(std::mem::take(&mut self.output)); self.finished = true; - // Never emit trailing frames or [DONE] after terminal JSON event. - self.emit( - json!({ - "type": event_type, - "response": response_val, - }), - out, - ); + if self.wire.transport.is_some() { + let kind = if incomplete.is_some() { + "response.incomplete" + } else { + "response.completed" + }; + emit(self.wire.frame( + ResponseEvent { + kind, + response: &response, + }, + FrameKind::Terminal, + 0, + )); + } } - TurnCompletion { - response_json: response_val, - response_id: self.id.clone(), - ws_reusable: !self.errored && ws_reusable, - errored: self.errored, + response_json: response, + response_id: self.wire.id.clone(), + ws_reusable: incomplete.is_none_or(|reason| reason == "max_output_tokens"), + errored: false, } } @@ -669,3 +876,193 @@ impl WireEncoder for ResponsesEncoder { self.finished } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::codec::sse_json; + use crate::control::StoredResponses; + use crate::plan::{ToolCallPayload, TurnPlan}; + + #[test] + fn indexed_sse_folds_to_the_same_output_as_json_and_storage() { + let options = RequestOptions { + include: vec!["reasoning.encrypted_content".into()], + ..Default::default() + }; + let plan = TurnPlan::new() + .push_reasoning_encrypted("", "opaque") + .push(TurnEvent::Refusal { + text: "partial refusal".into(), + }) + .push_text_chunked("答🦀", 1) + .push(TurnEvent::Refusal { + text: "last refusal".into(), + }) + .push( + ToolCallSpec::with_payload( + "call_patch", + "apply_patch", + ToolCallPayload::FreeformInput("one\n二".into()), + ) + .with_chunk_chars(1), + ) + .push(ToolCallSpec::new("call_lookup", "lookup", json!({ "x": 1 })).with_chunk_chars(2)) + .with_usage(Usage::new(22, 8).with_cache_read(6).with_reasoning(3)); + let make = |stream| { + ResponsesEncoder::with_options("resp_1".into(), "test".into(), false, stream, &options) + .with_created_at(123) + }; + let mut sse = make(true); + let mut json_encoder = make(false); + let mut frames = Vec::new(); + for event in plan.events { + frames.extend(sse.encode_event(event.clone())); + assert_eq!(json_encoder.encode_event(event).count(), 0); + } + let streamed = sse.finish_encoded(FinishReason::ToolCalls, &mut |frame| frames.push(frame)); + let standalone = json_encoder + .finish_encoded(FinishReason::ToolCalls, &mut |_| panic!("unexpected frame")); + + let mut added = Vec::new(); + let mut parts = Vec::new(); + let mut custom = String::new(); + let mut function = String::new(); + let mut semantic_bytes = 0; + for (sequence, frame) in frames.iter().enumerate() { + let event = sse_json(frame); + assert_eq!(event["sequence_number"], sequence); + if frame.kind == FrameKind::SemanticDelta { + semantic_bytes += frame.semantic_bytes; + } + match event["type"].as_str().unwrap() { + "response.created" => assert_eq!(event["response"]["created_at"], 123), + "response.output_item.added" => { + assert_eq!(event["output_index"], added.len()); + added.push(event["item"].clone()); + } + "response.content_part.added" => { + assert_eq!(event["output_index"], 1); + assert_eq!(event["content_index"], parts.len()); + parts.push(event["part"].clone()); + } + "response.output_text.delta" | "response.refusal.delta" => { + assert_eq!(event["output_index"], 1); + let part = &mut parts[event["content_index"].as_u64().unwrap() as usize]; + let key = if part["type"] == "output_text" { + "text" + } else { + "refusal" + }; + let text = format!( + "{}{}", + part[key].as_str().unwrap(), + event["delta"].as_str().unwrap() + ); + part[key] = Value::String(text); + } + "response.content_part.done" => { + assert_eq!(event["output_index"], 1); + assert_eq!( + event["part"], + parts[event["content_index"].as_u64().unwrap() as usize] + ); + } + "response.output_text.done" => { + assert_eq!(event["content_index"], 1); + assert_eq!(event["text"], "答🦀"); + } + "response.custom_tool_call_input.delta" => { + assert_eq!(event["output_index"], 2); + custom.push_str(event["delta"].as_str().unwrap()); + } + "response.function_call_arguments.delta" => { + assert_eq!(event["output_index"], 3); + function.push_str(event["delta"].as_str().unwrap()); + } + "response.custom_tool_call_input.done" => { + assert_eq!(event["input"], custom); + added[2]["input"] = Value::String(custom.clone()); + added[2]["status"] = json!("completed"); + } + "response.function_call_arguments.done" => { + assert_eq!(event["arguments"], function); + added[3]["arguments"] = Value::String(function.clone()); + added[3]["status"] = json!("completed"); + } + "response.output_item.done" => { + let index = event["output_index"].as_u64().unwrap() as usize; + match index { + 0 => added[0]["encrypted_content"] = json!("opaque"), + 1 => { + added[1]["content"] = json!(parts); + added[1]["status"] = json!("completed"); + } + _ => {} + } + assert_eq!(event["item"], added[index]); + } + _ => {} + } + } + assert_eq!(custom, "one\n二"); + assert_eq!(function, "{\"x\":1}"); + assert_eq!( + parts + .iter() + .map(|part| part["type"].as_str().unwrap()) + .collect::>(), + ["refusal", "output_text", "refusal"] + ); + assert_eq!( + semantic_bytes, + "partial refusal答🦀last refusalone\n二{\"x\":1}".len() + ); + let response = sse_json(frames.last().unwrap()); + assert_eq!(response["type"], "response.completed"); + assert_eq!(response["response"]["output"], Value::Array(added)); + assert_eq!( + response["response"]["usage"], + json!({ + "input_tokens": 22, "output_tokens": 8, "total_tokens": 30, + "input_tokens_details": { "cached_tokens": 6 }, + "output_tokens_details": { "reasoning_tokens": 3 }, + }) + ); + let store = StoredResponses::new(1, 0); + store.put(streamed.response_id.clone(), streamed.response_json); + assert_eq!(response["response"], standalone.response_json); + assert_eq!(store.get("resp_1"), Some(standalone.response_json)); + } + + #[test] + fn encrypted_reasoning_is_omitted_without_include() { + let mut encoder = ResponsesEncoder::new("resp_1".into(), "test".into(), true, true); + let event = TurnPlan::new() + .push_reasoning_encrypted("plan", "secret") + .events + .pop() + .unwrap(); + let mut frames: Vec<_> = encoder.encode_event(event).collect(); + let result = encoder.finish_encoded(FinishReason::Stop, &mut |frame| frames.push(frame)); + assert_eq!( + result.response_json["output"][0]["summary"], + json!([{ "type": "summary_text", "text": "plan" }]) + ); + assert!( + result.response_json["output"][0] + .get("encrypted_content") + .is_none() + ); + for (sequence, frame) in frames.iter().enumerate() { + let WireFrame::WsText(text) = &frame.wire else { + panic!("expected websocket JSON"); + }; + assert!(!text.contains("secret"), "{text}"); + assert_eq!( + serde_json::from_str::(text).unwrap()["sequence_number"], + sequence + ); + } + } +} diff --git a/tools/mock-ai/src/control.rs b/tools/mock-ai/src/control.rs index abdad961837..22b6f2a8f11 100644 --- a/tools/mock-ai/src/control.rs +++ b/tools/mock-ai/src/control.rs @@ -17,6 +17,8 @@ * under the License. */ +use crate::plan::Usage; +use crate::routing::{ResponseId, SessionId}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::{BTreeMap, HashMap, VecDeque}; @@ -115,10 +117,10 @@ pub struct ControlPlaneConfig { /// Static extra JSON routes keyed by exact path (e.g. `"/v1/users/me/balance"`). #[serde(default)] pub extra_get_routes: BTreeMap, - /// Max stored Responses objects retained for `GET/DELETE /v1/responses/{id}`. + /// Max stored Responses objects per owner retained for `GET/DELETE /v1/responses/{id}`. #[serde(default = "default_stored_responses_cap")] pub stored_responses_capacity: usize, - /// Max approximate byte budget for stored Responses objects. + /// Max serialized JSON byte budget for stored Responses objects per owner. #[serde(default = "default_stored_responses_bytes")] pub stored_responses_max_bytes: usize, /// Enable `/admin/*` control endpoints (`/admin/metrics`, `/admin/requests`, `/admin/reset`, `/admin/rules`). @@ -158,6 +160,13 @@ impl Default for ControlPlaneConfig { } impl ControlPlaneConfig { + pub fn find_model(&self, id: &str) -> Option { + self.models + .iter() + .find(|model| model.id == id) + .map(ModelEntry::to_wire_json) + } + pub fn render_models_page(&self, query: Option<&str>) -> Value { let mut after: Option = None; let mut limit: Option = None; @@ -224,90 +233,228 @@ impl ControlPlaneConfig { } } -/// Bounded in-memory store for completed OpenAI Responses objects (`GET/DELETE /v1/responses/{id}`). +pub fn render_count_tokens(input_tokens: u64) -> Value { + json!({ "input_tokens": input_tokens }) +} + +pub fn render_responses_compact( + id: &str, + created_at: u64, + item_id: &str, + encrypted_content: &str, + mut retained_user_items: Vec, + usage: &Usage, +) -> Value { + let reasoning = usage.reasoning_tokens.unwrap_or(0); + let output_tokens = usage.output_tokens.max(reasoning); + retained_user_items.push(json!({ + "type": "compaction", "id": item_id, "encrypted_content": encrypted_content, + })); + json!({ + "id": id, + "object": "response.compaction", + "created_at": created_at, + "output": retained_user_items, + "usage": { + "input_tokens": usage.input_tokens, + "input_tokens_details": { + "cached_tokens": usage.cache_read_tokens.unwrap_or(0), + "cache_write_tokens": usage.cache_creation_tokens.unwrap_or(0), + }, + "output_tokens": output_tokens, + "output_tokens_details": { "reasoning_tokens": reasoning }, + "total_tokens": usage.input_tokens.saturating_add(output_tokens), + }, + }) +} + +/// Completed Responses bodies, with a count and byte budget per owner. pub struct StoredResponses { capacity: usize, max_bytes: usize, inner: Mutex, } +#[derive(Default)] struct StoredResponsesInner { + legacy: ResponseBucket, + by_owner: HashMap, +} + +#[derive(Default)] +struct ResponseBucket { order: VecDeque, - map: HashMap, + map: HashMap>, total_bytes: usize, } +struct StoredEntry { + response: Arc, + byte_len: usize, +} + +#[derive(Default)] +struct JsonByteCount(usize); + +impl std::io::Write for JsonByteCount { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 += bytes.len(); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl ResponseBucket { + fn insert( + &mut self, + id: String, + entry: Arc, + capacity: usize, + max_bytes: usize, + retired: &mut Vec>, + ) { + retired.extend(self.delete(&id)); + while self.order.len() >= capacity + || (max_bytes > 0 && self.total_bytes > max_bytes - entry.byte_len) + { + let evicted = self + .order + .pop_front() + .expect("full response bucket has a head"); + let removed = self + .map + .remove(&evicted) + .expect("queue entry has a response"); + self.total_bytes -= removed.byte_len; + retired.push(removed); + } + self.total_bytes += entry.byte_len; + self.order.push_back(id.clone()); + self.map.insert(id, entry); + } + + fn get(&self, id: &str) -> Option> { + self.map.get(id).cloned() + } + + fn delete(&mut self, id: &str) -> Option> { + let entry = self.map.remove(id)?; + self.total_bytes -= entry.byte_len; + self.order.retain(|key| key != id); + Some(entry) + } +} + impl StoredResponses { pub fn new(capacity: usize, max_bytes: usize) -> Self { Self { capacity, max_bytes, - inner: Mutex::new(StoredResponsesInner { - order: VecDeque::new(), - map: HashMap::new(), - total_bytes: 0, - }), + inner: Mutex::new(StoredResponsesInner::default()), } } - pub fn put(&self, id: String, response: Value) { - if self.capacity == 0 { - return; - } - let approx_bytes = response.to_string().len(); - if self.max_bytes > 0 && approx_bytes > self.max_bytes { - return; - } - let mut guard = self.inner.lock().unwrap(); - if let Some((_, old_bytes)) = guard.map.remove(&id) { - guard.total_bytes = guard.total_bytes.saturating_sub(old_bytes); - guard.order.retain(|k| k != &id); + pub fn insert_owned( + &self, + owner: &SessionId, + id: ResponseId, + response: Value, + store: bool, + ) -> bool { + if !store { + return false; } - while guard.order.len() >= self.capacity - || (self.max_bytes > 0 - && !guard.order.is_empty() - && guard.total_bytes.saturating_add(approx_bytes) > self.max_bytes) + let Some(bytes) = self.admitted_size(&response) else { + return false; + }; + self.insert_sized(Some(owner), id.0, response, bytes); + true + } + + pub(crate) fn insert_sized( + &self, + owner: Option<&SessionId>, + id: String, + response: Value, + bytes: usize, + ) { + let entry = Arc::new(StoredEntry { + response: Arc::new(response), + byte_len: bytes, + }); + let mut retired = Vec::new(); { - if let Some(evicted) = guard.order.pop_front() - && let Some((_, b)) = guard.map.remove(&evicted) - { - guard.total_bytes = guard.total_bytes.saturating_sub(b); - } + let mut guard = self.inner.lock().unwrap(); + let bucket = match owner { + Some(owner) => guard.by_owner.entry(owner.clone()).or_default(), + None => &mut guard.legacy, + }; + bucket.insert(id, entry, self.capacity, self.max_bytes, &mut retired); } - guard.total_bytes = guard.total_bytes.saturating_add(approx_bytes); - guard.order.push_back(id.clone()); - guard.map.insert(id, (response, approx_bytes)); + drop(retired); + } + + pub fn get_owned(&self, owner: &SessionId, id: &ResponseId) -> Option { + let entry = self.inner.lock().unwrap().by_owner.get(owner)?.get(&id.0)?; + Some(entry.response.as_ref().clone()) + } + + pub fn delete_owned(&self, owner: &SessionId, id: &ResponseId) -> bool { + let retired = { + let mut guard = self.inner.lock().unwrap(); + let Some(bucket) = guard.by_owner.get_mut(owner) else { + return false; + }; + let retired = bucket.delete(&id.0); + if bucket.map.is_empty() { + guard.by_owner.remove(owner); + } + retired + }; + retired.is_some() + } + + pub fn finalize_owner(&self, owner: &SessionId) { + let retired = self.inner.lock().unwrap().by_owner.remove(owner); + drop(retired); + } + + pub fn put(&self, id: String, response: Value) { + let Some(bytes) = self.admitted_size(&response) else { + return; + }; + self.insert_sized(None, id, response, bytes); } pub fn get(&self, id: &str) -> Option { - self.inner - .lock() - .unwrap() - .map - .get(id) - .map(|(v, _)| v.clone()) + let entry = self.inner.lock().unwrap().legacy.get(id)?; + Some(entry.response.as_ref().clone()) } pub fn contains(&self, id: &str) -> bool { - self.inner.lock().unwrap().map.contains_key(id) + self.inner.lock().unwrap().legacy.map.contains_key(id) } pub fn delete(&self, id: &str) -> bool { - let mut guard = self.inner.lock().unwrap(); - if let Some((_, b)) = guard.map.remove(id) { - guard.total_bytes = guard.total_bytes.saturating_sub(b); - guard.order.retain(|k| k != id); - true - } else { - false - } + let retired = self.inner.lock().unwrap().legacy.delete(id); + retired.is_some() } pub fn clear(&self) { - let mut guard = self.inner.lock().unwrap(); - guard.order.clear(); - guard.map.clear(); - guard.total_bytes = 0; + let retired = std::mem::take(&mut *self.inner.lock().unwrap()); + drop(retired); + } + + pub(crate) fn admitted_size(&self, response: &Value) -> Option { + if self.capacity == 0 { + return None; + } + let mut count = JsonByteCount::default(); + serde_json::to_writer(&mut count, response).expect("JSON value serializes to byte counter"); + (self.max_bytes == 0 || count.0 <= self.max_bytes).then_some(count.0) } } @@ -345,3 +492,115 @@ impl CustomResponse { pub type CustomRouteFn = Arc< dyn Fn(&str, &str, &BTreeMap, &[u8]) -> Option + Send + Sync, >; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stored_bodies_are_isolated_by_owner_and_store_flag() { + let responses = StoredResponses::new(1, 64); + let a = SessionId("a".into()); + let b = SessionId("b".into()); + let first = ResponseId("first".into()); + let second = ResponseId("second".into()); + let ephemeral = ResponseId("ephemeral".into()); + + assert!(responses.insert_owned(&a, first.clone(), json!({"owner": "a"}), true)); + assert!(!responses.delete_owned(&b, &first)); + assert_eq!(responses.get_owned(&b, &first), None); + assert_eq!(responses.get("first"), None); + assert!(responses.insert_owned(&b, first.clone(), json!({"owner": "b"}), true)); + assert!(responses.insert_owned(&b, second.clone(), json!({"owner": "b"}), true)); + assert!(!responses.insert_owned(&b, ephemeral.clone(), json!({"store": false}), false)); + + assert_eq!(responses.get_owned(&a, &first), Some(json!({"owner": "a"}))); + assert_eq!(responses.get_owned(&b, &first), None); + assert_eq!(responses.get_owned(&b, &ephemeral), None); + assert_eq!( + responses.get_owned(&b, &second), + Some(json!({"owner": "b"})) + ); + responses.finalize_owner(&a); + assert_eq!(responses.get_owned(&a, &first), None); + assert!(responses.delete_owned(&b, &second)); + } + + #[test] + fn stored_bodies_evict_using_serialized_json_size() { + let responses = StoredResponses::new(4, 17); + responses.put("escaped".into(), json!("你\n\"")); + assert_eq!(responses.get("escaped"), Some(json!("你\n\""))); + responses.put("next".into(), json!("1234567")); + assert_eq!(responses.get("escaped"), None); + assert_eq!(responses.get("next"), Some(json!("1234567"))); + + responses.put("next".into(), json!("123456789012345")); + responses.put("oversized".into(), json!("1234567890123456")); + assert_eq!(responses.get("next"), Some(json!("123456789012345"))); + assert_eq!(responses.get("oversized"), None); + } + + #[test] + fn stored_bodies_support_concurrent_owner_reads_and_writes() { + let responses = StoredResponses::new(1, 8192); + let start = std::sync::Barrier::new(8); + let id = ResponseId("shared-id".into()); + let payload = "x".repeat(4096); + + std::thread::scope(|threads| { + for index in 0..8 { + let (responses, start, id, payload) = (&responses, &start, &id, &payload); + threads.spawn(move || { + let owner = SessionId(index.to_string()); + start.wait(); + for revision in 0..64 { + let value = json!({"owner": index, "revision": revision, "text": payload}); + assert!(responses.insert_owned(&owner, id.clone(), value.clone(), true)); + assert_eq!(responses.get_owned(&owner, id), Some(value)); + } + assert!(responses.delete_owned(&owner, id)); + assert_eq!(responses.get_owned(&owner, id), None); + }); + } + }); + } + + #[test] + fn control_plane_payloads_match_wire_shapes() { + let cfg = ControlPlaneConfig::default(); + assert_eq!(cfg.find_model("missing"), None); + assert_eq!( + cfg.find_model("mock-model"), + Some(json!({ + "id": "mock-model", "object": "model", "owned_by": "maka-mock-ai", + "context_length": 200000, "top_provider": { "max_completion_tokens": 16384 }, + })) + ); + assert_eq!(render_count_tokens(73), json!({"input_tokens": 73})); + let retained = json!({ + "type": "message", "id": "msg_1", "role": "user", "status": "completed", + "content": [{"type": "input_text", "text": "Keep this instruction"}], + }); + assert_eq!( + render_responses_compact( + "resp_1", + 123, + "cmp_1", + "opaque", + vec![retained.clone()], + &Usage::new(73, 9) + ), + json!({ + "id": "resp_1", "object": "response.compaction", "created_at": 123, + "output": [retained, {"id": "cmp_1", "type": "compaction", "encrypted_content": "opaque"}], + "usage": { + "input_tokens": 73, + "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, + "output_tokens": 9, "output_tokens_details": {"reasoning_tokens": 0}, + "total_tokens": 82, + }, + }) + ); + } +} diff --git a/tools/mock-ai/src/handler.rs b/tools/mock-ai/src/handler.rs index f9c08bcff0d..760665908c9 100644 --- a/tools/mock-ai/src/handler.rs +++ b/tools/mock-ai/src/handler.rs @@ -81,6 +81,13 @@ impl SessionTracker { 1 } + pub(crate) fn remove(&self, session_key: &str) { + let mut guard = self.inner.lock().unwrap(); + if guard.turns.remove(session_key).is_some() { + guard.order.retain(|key| key != session_key); + } + } + pub fn clear(&self) { let mut guard = self.inner.lock().unwrap(); guard.order.clear(); @@ -133,6 +140,23 @@ pub type HandlerFuture<'a> = Pin> + pub trait TurnHandler: Send + Sync { fn handle<'a>(&'a self, req: &'a NormalizedRequest, ctx: &'a TurnContext) -> HandlerFuture<'a>; + /// Pre-stream admission faults may be retried without advancing the session turn. + fn reject_before_turn( + &self, + _request: &NormalizedRequest, + _chaos: Option<&crate::workload::ChaosConfig>, + ) -> Option { + None + } + + fn handle_admitted<'a>( + &'a self, + request: &'a NormalizedRequest, + ctx: &'a TurnContext, + ) -> HandlerFuture<'a> { + self.handle(request, ctx) + } + /// Reset internal counters/state (called by `MockAiServer::reset()` and `POST /admin/reset`). fn reset(&self) {} } diff --git a/tools/mock-ai/src/lib.rs b/tools/mock-ai/src/lib.rs index a5ac5974347..87974e2d15a 100644 --- a/tools/mock-ai/src/lib.rs +++ b/tools/mock-ai/src/lib.rs @@ -35,8 +35,10 @@ pub mod protocol; #[cfg(feature = "proxy")] pub mod proxy; pub mod ratelimit; +pub mod routing; #[cfg(feature = "rules")] pub mod rules; +pub mod scenario; pub mod schema_synth; pub mod server; #[cfg(feature = "tls")] @@ -50,20 +52,22 @@ pub use handler::{ TurnDecision, TurnHandle, TurnHandler, }; pub use metrics::{ - AtomicHistogram, DimensionCounter, HistogramSummary, MetricsSnapshot, RecordedControlRequest, - RecordedRequest, RecorderMode, RequestRecorder, ServerMetrics, + AtomicHistogram, AttemptOutcome, AttemptSpan, DimensionCounter, HistogramSummary, + MetricsSnapshot, RecordedControlRequest, RecordedRequest, RecorderMode, RequestPurpose, + RequestRecorder, ServerMetrics, SessionTelemetryStore, }; pub use pacing::{ DynamicProfileManager, LatencyProfile, ProfileSnapshot, RuntimeProfile, ScenarioPhase, ScenarioSchedule, TurnPacer, }; pub use plan::{ - Citation, CloseSignal, CompactionOutput, FinishReason, HttpErrorSpec, MidStreamErrorSpec, - NativeToolEvent, ToolCallSpec, TurnEvent, TurnPlan, Usage, WebSearchResult, + Citation, CloseSignal, CompactionOutput, FinishReason, FrameKind, HttpErrorSpec, + MidStreamErrorSpec, NativeToolEvent, ProviderDialectProfile, ToolCallPayload, ToolCallSpec, + TurnEvent, TurnPlan, TurnUsage, Usage, WebSearchResult, }; pub use protocol::{ AuthPolicy, NormalizedMessage, NormalizedRequest, NormalizedRole, NormalizedTool, Protocol, - Transport, + RequestOptions, RequestSizeBreakdown, ToolDeclKind, Transport, }; #[cfg(feature = "proxy")] pub use proxy::{ @@ -74,8 +78,10 @@ pub use ratelimit::{ RateLimitConfig, RateLimitDecision, RateLimitHeaders, RateLimitLease, RateLimitScope, RateLimiter, }; +pub use routing::{RequestClassifier, RequestUse, SessionRegistration}; #[cfg(feature = "rules")] pub use rules::{ConfigError, MockServerConfig, RuleEngine, RuleMatcher, RuleSpec}; +pub use scenario::{ScenarioEngine, ScenarioSpec}; pub use schema_synth::{ SynthMode, WirePoisonConfig, context_overflow_error, poison_sse_frame, synthesize_tool_arguments, try_synthesize_tool_arguments, @@ -84,7 +90,8 @@ pub use server::{MockAiBuilder, MockAiServer, ServerTuning}; #[cfg(feature = "tls")] pub use tls::{TlsServerConfig, UpstreamWsStream, build_tls_connector, connect_ws_upstream}; pub use watchdog::{ - ProtocolWatchdog, ViolationKind, ViolationRecord, WatchdogConfig, WatchdogSnapshot, + ProtocolWatchdog, StreamCloseReason, ViolationKind, ViolationRecord, WatchdogConfig, + WatchdogSnapshot, }; pub use workload::{ChaosConfig, SyntheticToolTemplate, WorkloadConfig, WorkloadGenerator}; @@ -93,6 +100,9 @@ pub use workload::{ChaosConfig, SyntheticToolTemplate, WorkloadConfig, WorkloadG pub fn builder_from_config(config: MockServerConfig) -> Result { use std::sync::Arc; + config.validate()?; + + let has_workload = config.workload.is_some(); let mut handlers: Vec> = Vec::new(); let mut rule_engine_ref = None; @@ -127,7 +137,16 @@ pub fn builder_from_config(config: MockServerConfig) -> Result for ProviderDialectProfile { + fn from(dialect: CliDialect) -> Self { + match dialect { + CliDialect::StandardOpenAi => Self::StandardOpenAi, + CliDialect::DeepSeekChat => Self::DeepSeekChat, + CliDialect::KimiChat => Self::KimiChat, + CliDialect::AnthropicMessages => Self::AnthropicMessages, + CliDialect::OpenAiResponses => Self::OpenAiResponses, + } + } +} + #[derive(Debug, Clone, Copy, ValueEnum)] enum CliReplayMatch { Sequential, @@ -61,6 +86,22 @@ struct Cli { #[arg(long)] config: Option, + /// Benchmark scenario file (JSON or YAML). + #[arg(long, conflicts_with_all = ["preset", "proxy_record", "replay"])] + scenario: Option, + + /// Require requests to resolve to a registered benchmark session. + #[arg(long)] + strict_benchmark: bool, + + /// Select the provider response dialect. + #[arg(long, value_enum)] + provider_dialect: Option, + + /// Reject missing, exhausted or truncated recordings instead of simulating them. + #[arg(long, requires = "replay")] + strict_replay: bool, + /// Built-in workload preset when --config is omitted. #[arg(long, value_enum, default_value_t = Preset::Echo)] preset: Preset, @@ -155,6 +196,22 @@ async fn main() -> Result<(), Box> { ..Default::default() }; + let scenario = if let Some(path) = &cli.scenario { + let source = tokio::fs::read_to_string(path).await?; + Some( + if path + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("json")) + { + ScenarioSpec::from_json_str(&source)? + } else { + ScenarioSpec::from_yaml_str(&source)? + }, + ) + } else { + None + }; + let mut strict_benchmark = cli.strict_benchmark; let mut builder = if let Some(path) = &cli.config { let mut cfg = MockServerConfig::from_file(path)?; if cli.admin { @@ -166,6 +223,14 @@ async fn main() -> Result<(), Box> { if cli.no_watchdog { cfg.watchdog.enabled = false; } + if scenario.is_some() { + cfg.scenario = scenario; + } + strict_benchmark |= cfg.strict_benchmark; + cfg.strict_benchmark = strict_benchmark; + if let Some(dialect) = cli.provider_dialect { + cfg.provider_dialect = Some(dialect.into()); + } builder_from_config(cfg)? } else { let control = ControlPlaneConfig { @@ -184,10 +249,17 @@ async fn main() -> Result<(), Box> { enabled: !cli.no_watchdog, ..Default::default() }; - let b = MockAiBuilder::new() + let mut b = MockAiBuilder::new() .control(control) .recorder(recorder) - .watchdog(watchdog); + .watchdog(watchdog) + .strict_benchmark(strict_benchmark); + if let Some(dialect) = cli.provider_dialect { + b = b.provider_dialect(dialect.into()); + } + if let Some(scenario) = scenario { + b = b.scenario(scenario); + } match cli.preset { Preset::Echo => b, Preset::Stress => b.workload(WorkloadConfig::stress_preset(cli.seed)), @@ -248,12 +320,12 @@ async fn main() -> Result<(), Box> { CliReplayMatch::Sequential => ReplayMatchMode::Sequential, CliReplayMatch::Fingerprint => ReplayMatchMode::Fingerprint, }; + let mut replay = ReplayConfig::new(replay_path) + .with_speed(cli.replay_speed) + .with_match_mode(mode); + replay.strict_replay = cli.strict_replay || strict_benchmark; builder = builder - .replay( - ReplayConfig::new(replay_path) - .with_speed(cli.replay_speed) - .with_match_mode(mode), - ) + .replay(replay) .map_err(|e| format!("replay setup failed: {e}"))?; } diff --git a/tools/mock-ai/src/metrics.rs b/tools/mock-ai/src/metrics.rs index 7e80d5db073..7d4f0f4d3c8 100644 --- a/tools/mock-ai/src/metrics.rs +++ b/tools/mock-ai/src/metrics.rs @@ -17,13 +17,18 @@ * under the License. */ -use crate::protocol::{NormalizedRequest, Protocol}; +use crate::protocol::{NormalizedRequest, Protocol, Transport}; +use crate::routing::{ + AttemptId, CallId, LogicalLane, RequestUse, ResponseId, Revision, RunId, SessionId, SideKind, + StepId, +}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::fmt::Write as _; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::Instant; /// Controls how much request history is retained in memory. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -238,13 +243,133 @@ impl AtomicHistogram { } } -/// Per-(protocol, model, status_class) dimensional counter & latency slice. +macro_rules! metric_labels { + ($name:ident { $( $variant:ident => $label:literal ),+ $(,)? }) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] + pub enum $name { + $(#[serde(rename = $label)] $variant),+ + } + + impl $name { + pub const fn as_str(self) -> &'static str { + match self { + $(Self::$variant => $label),+ + } + } + } + + impl Default for $name { + fn default() -> Self { + Self::Unclassified + } + } + }; +} + +metric_labels!(RequestPurpose { + Main => "main", + Title => "title", + Probe => "probe", + SummaryAux => "summary_aux", + Side => "side", + Compact => "compact", + CountTokens => "count_tokens", + Warmup => "warmup", + Control => "control", + Unclassified => "unclassified", +}); + +impl From<&RequestUse> for RequestPurpose { + fn from(request_use: &RequestUse) -> Self { + match request_use { + RequestUse::Main => Self::Main, + RequestUse::Side(SideKind::Title) => Self::Title, + RequestUse::Side(SideKind::Probe) => Self::Probe, + RequestUse::Side(SideKind::SummaryAux) => Self::SummaryAux, + RequestUse::Side(SideKind::Custom(_)) => Self::Side, + RequestUse::Compact(_) => Self::Compact, + RequestUse::Control => Self::Control, + } + } +} + +metric_labels!(AttemptOutcome { + Completed => "completed", + Rejected => "rejected", + RateLimited => "rate_limited", + InjectedFault => "injected_fault", + ClientDisconnected => "client_disconnected", + ServerShutdown => "server_shutdown", + ParseFailed => "parse_failed", + TransportError => "transport_error", + Unclassified => "unclassified", +}); + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +enum MetricStatus { + Code(u16), + Fault, + Aborted, + Unknown, +} + +impl MetricStatus { + fn from_legacy(status: &str) -> (Self, AttemptOutcome) { + match status { + "fault" => (Self::Fault, AttemptOutcome::InjectedFault), + "aborted" => (Self::Aborted, AttemptOutcome::ClientDisconnected), + _ => match status.parse::() { + Ok(code @ 200..=299) => (Self::Code(code), AttemptOutcome::Completed), + Ok(429) => (Self::Code(429), AttemptOutcome::RateLimited), + Ok(code @ (100..=199 | 300..=599)) => (Self::Code(code), AttemptOutcome::Rejected), + _ => (Self::Unknown, AttemptOutcome::Unclassified), + }, + } + } + + fn label(self) -> String { + match self { + Self::Code(code) => code.to_string(), + Self::Fault => "fault".into(), + Self::Aborted => "aborted".into(), + Self::Unknown => "unknown".into(), + } + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct DimensionKey { + protocol: &'static str, + model: String, + status: MetricStatus, + purpose: RequestPurpose, + outcome: AttemptOutcome, +} + +impl DimensionKey { + fn prometheus_labels(&self) -> String { + format!( + "protocol=\"{}\",model=\"{}\",status=\"{}\",purpose=\"{}\",outcome=\"{}\"", + self.protocol, + escape_prom_label(&self.model), + self.status.label(), + self.purpose.as_str(), + self.outcome.as_str(), + ) + } +} + +/// Counter and latency slice grouped by request dimensions. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DimensionCounter { pub protocol: String, pub model: String, pub status_class: String, + #[serde(default)] + pub purpose: RequestPurpose, + #[serde(default)] + pub outcome: AttemptOutcome, pub requests: u64, pub input_tokens: u64, pub output_tokens: u64, @@ -254,9 +379,7 @@ pub struct DimensionCounter { } struct DimensionState { - protocol: String, - model: String, - status_class: String, + key: DimensionKey, requests: AtomicU64, input_tokens: AtomicU64, output_tokens: AtomicU64, @@ -266,11 +389,9 @@ struct DimensionState { } impl DimensionState { - fn new(protocol: String, model: String, status_class: String) -> Self { + fn new(key: DimensionKey) -> Self { Self { - protocol, - model, - status_class, + key, requests: AtomicU64::new(0), input_tokens: AtomicU64::new(0), output_tokens: AtomicU64::new(0), @@ -282,9 +403,11 @@ impl DimensionState { fn snapshot(&self) -> DimensionCounter { DimensionCounter { - protocol: self.protocol.clone(), - model: self.model.clone(), - status_class: self.status_class.clone(), + protocol: self.key.protocol.into(), + model: self.key.model.clone(), + status_class: self.key.status.label(), + purpose: self.key.purpose, + outcome: self.key.outcome, requests: self.requests.load(Ordering::Relaxed), input_tokens: self.input_tokens.load(Ordering::Relaxed), output_tokens: self.output_tokens.load(Ordering::Relaxed), @@ -296,6 +419,8 @@ impl DimensionState { } const MAX_DIMENSION_KEYS: usize = 256; +const MAX_OVERFLOW_DIMENSION_KEYS: usize = 256; +const MAX_MODEL_LABEL_BYTES: usize = 128; /// Point-in-time snapshot of server metrics (safe to serialize over `/admin/metrics`). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -356,7 +481,9 @@ pub struct ServerMetrics { pub turn_duration_ms: AtomicHistogram, pub prompt_bytes_hist: AtomicHistogram, pub effective_tps: AtomicHistogram, - dimensions: RwLock>>, + generation: AtomicU64, + generation_gate: RwLock<()>, + dimensions: RwLock>>, } impl Default for ServerMetrics { @@ -387,6 +514,8 @@ impl Default for ServerMetrics { turn_duration_ms: AtomicHistogram::new(LATENCY_BOUNDS), prompt_bytes_hist: AtomicHistogram::new(BYTES_BOUNDS), effective_tps: AtomicHistogram::new(TPS_BOUNDS), + generation: AtomicU64::new(0), + generation_gate: RwLock::new(()), dimensions: RwLock::new(HashMap::new()), } } @@ -427,32 +556,101 @@ impl ServerMetrics { ttft_ms: Option, turn_duration_ms: Option, ) { - let proto = protocol_label(protocol).to_string(); - let model_label = if model.is_empty() { - "unknown".to_string() - } else { - model.to_string() + let (status, outcome) = MetricStatus::from_legacy(status_class); + self.record_dimension_sample( + protocol, + model, + status, + RequestPurpose::Unclassified, + outcome, + input_tokens, + output_tokens, + cache_read_tokens, + ttft_ms, + turn_duration_ms, + ); + } + + #[allow(clippy::too_many_arguments)] + pub fn record_dimension_with_labels( + &self, + protocol: Protocol, + model: &str, + status: Option, + purpose: RequestPurpose, + outcome: AttemptOutcome, + input_tokens: u64, + output_tokens: u64, + cache_read_tokens: u64, + ttft_ms: Option, + turn_duration_ms: Option, + ) { + let status = match status { + Some(code @ 100..=599) => MetricStatus::Code(code), + _ => MetricStatus::Unknown, }; - let status = status_class.to_string(); - let lookup_key = (proto.clone(), model_label.clone(), status.clone()); - let entry = if let Some(existing) = self - .dimensions - .read() - .unwrap_or_else(|e| e.into_inner()) - .get(&lookup_key) - .cloned() - { - existing + self.record_dimension_sample( + protocol, + model, + status, + purpose, + outcome, + input_tokens, + output_tokens, + cache_read_tokens, + ttft_ms, + turn_duration_ms, + ); + } + + #[allow(clippy::too_many_arguments)] + fn record_dimension_sample( + &self, + protocol: Protocol, + model: &str, + status: MetricStatus, + purpose: RequestPurpose, + outcome: AttemptOutcome, + input_tokens: u64, + output_tokens: u64, + cache_read_tokens: u64, + ttft_ms: Option, + turn_duration_ms: Option, + ) { + let model = match model { + "" => "unknown", + model if model.len() > MAX_MODEL_LABEL_BYTES => "_other_", + model => model, + }; + let mut key = DimensionKey { + protocol: protocol_label(protocol), + model: model.into(), + status, + purpose, + outcome, + }; + let dims = self.dimensions.read().unwrap_or_else(|e| e.into_inner()); + let entry = if let Some(existing) = dims.get(&key) { + existing.clone() } else { - let mut guard = self.dimensions.write().unwrap_or_else(|e| e.into_inner()); - let key = if guard.len() >= MAX_DIMENSION_KEYS && !guard.contains_key(&lookup_key) { - (proto, "_other_".to_string(), status) - } else { - lookup_key - }; - guard - .entry(key.clone()) - .or_insert_with(|| std::sync::Arc::new(DimensionState::new(key.0, key.1, key.2))) + drop(dims); + let mut dims = self.dimensions.write().unwrap_or_else(|e| e.into_inner()); + if dims.len() >= MAX_DIMENSION_KEYS && !dims.contains_key(&key) { + key.model = "_other_".into(); + if dims.len() >= MAX_DIMENSION_KEYS + MAX_OVERFLOW_DIMENSION_KEYS + && !dims.contains_key(&key) + { + key = DimensionKey { + protocol: "other", + model: "_other_".into(), + status: MetricStatus::Unknown, + purpose: RequestPurpose::Unclassified, + outcome: AttemptOutcome::Unclassified, + }; + } + } + dims.entry(key.clone()) + .or_insert_with(|| Arc::new(DimensionState::new(key))) .clone() }; entry.requests.fetch_add(1, Ordering::Relaxed); @@ -473,19 +671,24 @@ impl ServerMetrics { } } - pub fn snapshot(&self) -> MetricsSnapshot { - let entries: Vec> = self + fn dimension_entries(&self) -> Vec> { + let mut entries: Vec<_> = self .dimensions .read() .unwrap_or_else(|e| e.into_inner()) .values() .cloned() .collect(); - let mut by_dimension: Vec = - entries.iter().map(|e| e.snapshot()).collect(); - by_dimension.sort_by(|a, b| { - (&a.protocol, &a.model, &a.status_class).cmp(&(&b.protocol, &b.model, &b.status_class)) - }); + entries.sort_unstable_by(|a, b| a.key.cmp(&b.key)); + entries + } + + pub fn snapshot(&self) -> MetricsSnapshot { + self.snapshot_with_dimensions(&self.dimension_entries()) + } + + fn snapshot_with_dimensions(&self, entries: &[Arc]) -> MetricsSnapshot { + let by_dimension = entries.iter().map(|entry| entry.snapshot()).collect(); MetricsSnapshot { active_connections: self.active_connections.load(Ordering::Relaxed), active_streams: self.active_streams.load(Ordering::Relaxed), @@ -516,11 +719,35 @@ impl ServerMetrics { } } + pub fn generation(&self) -> u64 { + self.generation.load(Ordering::Acquire) + } + + /// Apply synchronous metric updates in the generation captured at request entry. + pub fn record_for_generation(&self, generation: u64, record: impl FnOnce(&Self)) -> bool { + if self.generation() != generation { + return false; + } + let _guard = self + .generation_gate + .read() + .unwrap_or_else(|e| e.into_inner()); + if self.generation() != generation { + return false; + } + record(self); + true + } + pub fn reset(&self) { self.reset_counters(); } pub fn reset_counters(&self) { + let _guard = self + .generation_gate + .write() + .unwrap_or_else(|e| e.into_inner()); self.total_requests.store(0, Ordering::Relaxed); self.chat_completions_requests.store(0, Ordering::Relaxed); self.responses_http_requests.store(0, Ordering::Relaxed); @@ -548,11 +775,17 @@ impl ServerMetrics { .write() .unwrap_or_else(|e| e.into_inner()) .clear(); + self.generation.fetch_add(1, Ordering::Release); } /// Render Prometheus text exposition format (0.0.4) for scraping via `GET /metrics`. pub fn render_prometheus(&self, watchdog_violations: u64) -> String { - let s = self.snapshot(); + let dim_entries = self.dimension_entries(); + let s = self.snapshot_with_dimensions(&dim_entries); + let labels: Vec<_> = dim_entries + .iter() + .map(|entry| entry.key.prometheus_labels()) + .collect(); let mut out = String::with_capacity(4096); let _ = writeln!( out, @@ -645,42 +878,35 @@ impl ServerMetrics { s.bytes_sent ); - if !s.by_dimension.is_empty() { + if !dim_entries.is_empty() { let _ = writeln!( out, - "# HELP mock_ai_dimension_requests_total Requests by protocol, model, and status" + "# HELP mock_ai_dimension_requests_total Requests by protocol, model, status, purpose and outcome" ); let _ = writeln!(out, "# TYPE mock_ai_dimension_requests_total counter"); - for d in &s.by_dimension { - let m = escape_prom_label(&d.model); + for (d, labels) in s.by_dimension.iter().zip(&labels) { let _ = writeln!( out, - "mock_ai_dimension_requests_total{{protocol=\"{}\",model=\"{m}\",status=\"{}\"}} {}", - d.protocol, d.status_class, d.requests + "mock_ai_dimension_requests_total{{{labels}}} {}", + d.requests ); } let _ = writeln!( out, - "# HELP mock_ai_dimension_tokens_total Tokens by protocol, model, and kind" + "# HELP mock_ai_dimension_tokens_total Tokens by request dimensions and kind" ); let _ = writeln!(out, "# TYPE mock_ai_dimension_tokens_total counter"); - for d in &s.by_dimension { - let m = escape_prom_label(&d.model); - let _ = writeln!( - out, - "mock_ai_dimension_tokens_total{{protocol=\"{}\",model=\"{m}\",kind=\"input\"}} {}", - d.protocol, d.input_tokens - ); - let _ = writeln!( - out, - "mock_ai_dimension_tokens_total{{protocol=\"{}\",model=\"{m}\",kind=\"output\"}} {}", - d.protocol, d.output_tokens - ); - let _ = writeln!( - out, - "mock_ai_dimension_tokens_total{{protocol=\"{}\",model=\"{m}\",kind=\"cache_read\"}} {}", - d.protocol, d.cache_read_tokens - ); + for (d, labels) in s.by_dimension.iter().zip(&labels) { + for (kind, value) in [ + ("input", d.input_tokens), + ("output", d.output_tokens), + ("cache_read", d.cache_read_tokens), + ] { + let _ = writeln!( + out, + "mock_ai_dimension_tokens_total{{{labels},kind=\"{kind}\"}} {value}" + ); + } } } @@ -705,28 +931,19 @@ impl ServerMetrics { "Measured effective streaming output tokens per second", ); - let dim_entries: Vec> = self - .dimensions - .read() - .unwrap_or_else(|e| e.into_inner()) - .values() - .cloned() - .collect(); if !dim_entries.is_empty() { let _ = writeln!( out, "# HELP mock_ai_dimension_ttft_ms Per-model TTFT histogram in ms" ); let _ = writeln!(out, "# TYPE mock_ai_dimension_ttft_ms histogram"); - for d in &dim_entries { + for (d, labels) in dim_entries.iter().zip(&labels) { if d.ttft_ms.count.load(Ordering::Relaxed) > 0 { - let m = escape_prom_label(&d.model); - let lbl = format!( - "protocol=\"{}\",model=\"{m}\",status=\"{}\"", - d.protocol, d.status_class + d.ttft_ms.write_prometheus_series( + &mut out, + "mock_ai_dimension_ttft_ms", + labels, ); - d.ttft_ms - .write_prometheus_series(&mut out, "mock_ai_dimension_ttft_ms", &lbl); } } let _ = writeln!( @@ -734,17 +951,12 @@ impl ServerMetrics { "# HELP mock_ai_dimension_turn_duration_ms Per-model turn duration histogram in ms" ); let _ = writeln!(out, "# TYPE mock_ai_dimension_turn_duration_ms histogram"); - for d in &dim_entries { + for (d, labels) in dim_entries.iter().zip(&labels) { if d.turn_duration_ms.count.load(Ordering::Relaxed) > 0 { - let m = escape_prom_label(&d.model); - let lbl = format!( - "protocol=\"{}\",model=\"{m}\",status=\"{}\"", - d.protocol, d.status_class - ); d.turn_duration_ms.write_prometheus_series( &mut out, "mock_ai_dimension_turn_duration_ms", - &lbl, + labels, ); } } @@ -769,28 +981,16 @@ fn escape_prom_label(s: &str) -> String { } enum RecordedEntry { - Model(RecordedRequest), - Control { - entry: RecordedControlRequest, - bytes: usize, - }, -} - -impl RecordedEntry { - fn bytes(&self) -> usize { - match self { - Self::Model(r) => r.prompt_bytes, - Self::Control { bytes, .. } => *bytes, - } - } + Model(Arc), + Control(Arc), } struct RecorderInner { - entries: VecDeque, + entries: VecDeque<(RecordedEntry, usize)>, retained_bytes: usize, } -/// Thread-safe request recorder supporting unbounded, byte-and-entry bounded ring, or zero-overhead metrics-only mode. +/// Thread-safe request recorder supporting a full history, a bounded ring, or metrics only. pub struct RequestRecorder { mode: RecorderMode, inner: Mutex, @@ -811,42 +1011,39 @@ impl RequestRecorder { self.mode } - fn push_entry(&self, entry: RecordedEntry) { - let bytes = entry.bytes(); - match self.mode { - RecorderMode::MetricsOnly => {} - RecorderMode::Full => { - let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - guard.retained_bytes = guard.retained_bytes.saturating_add(bytes); - guard.entries.push_back(entry); - } - RecorderMode::Ring { - capacity, - max_bytes, - } => { - if capacity == 0 || max_bytes == 0 || bytes > max_bytes { - return; - } - let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - while guard.entries.len() >= capacity - || (guard.retained_bytes.saturating_add(bytes) > max_bytes - && !guard.entries.is_empty()) - { - if let Some(evicted) = guard.entries.pop_front() { - guard.retained_bytes = guard.retained_bytes.saturating_sub(evicted.bytes()); - } - } - guard.retained_bytes = guard.retained_bytes.saturating_add(bytes); - guard.entries.push_back(entry); + fn push_entry(&self, bytes: usize, make_entry: impl FnOnce() -> RecordedEntry) { + if matches!(self.mode, RecorderMode::MetricsOnly) + || matches!(self.mode, RecorderMode::Ring { capacity, max_bytes } + if capacity == 0 || max_bytes == 0 || bytes > max_bytes) + { + return; + } + + let entry = make_entry(); + let mut evicted = Vec::new(); + let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let RecorderMode::Ring { + capacity, + max_bytes, + } = self.mode + { + while guard.entries.len() >= capacity || guard.retained_bytes > max_bytes - bytes { + let (old, old_bytes) = guard.entries.pop_front().expect("ring exceeds its budget"); + guard.retained_bytes -= old_bytes; + evicted.push(old); } + guard.retained_bytes += bytes; } + guard.entries.push_back((entry, bytes)); + drop(guard); + drop(evicted); } pub fn record(&self, req: &NormalizedRequest) { - if matches!(self.mode, RecorderMode::MetricsOnly) { - return; - } - self.push_entry(RecordedEntry::Model(RecordedRequest::from(req))); + let bytes = req.prompt_bytes.max(req.size_breakdown.body_bytes); + self.push_entry(bytes, || { + RecordedEntry::Model(Arc::new(RecordedRequest::from(req))) + }); } pub fn record_control( @@ -866,44 +1063,810 @@ impl RequestRecorder { .iter() .map(|(k, v)| k.len() + v.len()) .sum::(); - let entry = RecordedControlRequest { - method: method.to_owned(), - path: path.to_owned(), - query: query.map(str::to_owned), - headers: headers.clone(), - }; - self.push_entry(RecordedEntry::Control { entry, bytes }); + self.push_entry(bytes, || { + RecordedEntry::Control(Arc::new(RecordedControlRequest { + method: method.to_owned(), + path: path.to_owned(), + query: query.map(str::to_owned), + headers: headers.clone(), + })) + }); } pub fn snapshot(&self) -> Vec { - self.inner + let entries: Vec<_> = self + .inner .lock() .unwrap_or_else(|e| e.into_inner()) .entries .iter() - .filter_map(|e| match e { - RecordedEntry::Model(r) => Some(r.clone()), - RecordedEntry::Control { .. } => None, + .filter_map(|(entry, _)| match entry { + RecordedEntry::Model(request) => Some(request.clone()), + RecordedEntry::Control(_) => None, }) - .collect() + .collect(); + entries.into_iter().map(|entry| (*entry).clone()).collect() } pub fn control_snapshot(&self) -> Vec { - self.inner + let entries: Vec<_> = self + .inner .lock() .unwrap_or_else(|e| e.into_inner()) .entries .iter() - .filter_map(|e| match e { - RecordedEntry::Control { entry, .. } => Some(entry.clone()), + .filter_map(|(entry, _)| match entry { + RecordedEntry::Control(request) => Some(request.clone()), RecordedEntry::Model(_) => None, }) - .collect() + .collect(); + entries.into_iter().map(|entry| (*entry).clone()).collect() } pub fn clear(&self) { let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - guard.entries.clear(); + let previous = std::mem::take(&mut guard.entries); guard.retained_bytes = 0; + drop(guard); + drop(previous); + } +} + +#[derive(Debug, Clone, Copy)] +pub struct RunClock { + started_at: Instant, +} + +impl RunClock { + pub fn new(started_at: Instant) -> Self { + Self { started_at } + } + + pub fn elapsed_ns(&self) -> u64 { + self.started_at.elapsed().as_nanos().min(u64::MAX as u128) as u64 + } +} + +impl Default for RunClock { + fn default() -> Self { + Self::new(Instant::now()) + } +} + +/// All timestamps are monotonic nanoseconds relative to the owning run's start. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttemptSpan { + pub run_id: RunId, + pub session_id: SessionId, + pub lane: Option, + pub step_id: Option, + pub revision: Option, + pub attempt: Option, + pub connection_id: Option, + pub response_id: Option, + pub parent_response_id: Option, + pub purpose: RequestPurpose, + pub protocol: Protocol, + pub transport: Transport, + pub fault_id: Option, + pub outcome: AttemptOutcome, + pub retry_reason: Option, + pub confirmed_call_ids: Vec, + pub checkpoint_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub adopted_checkpoint_id: Option, + pub headers_received_ns: u64, + pub body_read_ns: Option, + pub parsed_ns: Option, + pub admitted_ns: Option, + pub plan_ready_ns: Option, + pub first_byte_ns: Option, + pub first_semantic_delta_ns: Option, + pub last_frame_consumed_ns: Option, + pub body_dropped_ns: Option, + /// End of an attempt that has no body/transport endpoint, such as a parsing failure. + pub finished_ns: Option, + pub simulated_delay_ns: u64, + pub actual_sleep_ns: u64, + pub backpressure_wait_ns: u64, + pub request_wire_bytes: u64, + pub response_wire_bytes: u64, + pub effective_context_bytes: u64, + pub input_tokens: u64, + pub output_tokens: u64, + pub cache_read_tokens: u64, + pub cache_creation_tokens: u64, + pub reasoning_tokens: u64, +} + +impl AttemptSpan { + pub fn new( + run_id: RunId, + session_id: SessionId, + protocol: Protocol, + transport: Transport, + headers_received_ns: u64, + ) -> Self { + let connection_id = match &transport { + Transport::Http => None, + Transport::WebSocket { connection_id, .. } => Some(*connection_id), + }; + Self { + run_id, + session_id, + protocol, + transport, + headers_received_ns, + connection_id, + lane: None, + step_id: None, + revision: None, + attempt: None, + response_id: None, + parent_response_id: None, + purpose: RequestPurpose::default(), + fault_id: None, + outcome: AttemptOutcome::default(), + retry_reason: None, + confirmed_call_ids: Vec::new(), + checkpoint_id: None, + adopted_checkpoint_id: None, + body_read_ns: None, + parsed_ns: None, + admitted_ns: None, + plan_ready_ns: None, + first_byte_ns: None, + first_semantic_delta_ns: None, + last_frame_consumed_ns: None, + body_dropped_ns: None, + finished_ns: None, + simulated_delay_ns: 0, + actual_sleep_ns: 0, + backpressure_wait_ns: 0, + request_wire_bytes: 0, + response_wire_bytes: 0, + effective_context_bytes: 0, + input_tokens: 0, + output_tokens: 0, + cache_read_tokens: 0, + cache_creation_tokens: 0, + reasoning_tokens: 0, + } + } + + fn interval(&self) -> Option<(u64, u64)> { + let end = self + .body_dropped_ns + .max(self.last_frame_consumed_ns) + .max(self.finished_ns)?; + (end > self.headers_received_ns).then_some((self.headers_received_ns, end)) + } + + fn retained_bytes(&self) -> usize { + let strings = [ + Some(&self.run_id.0), + Some(&self.session_id.0), + self.lane.as_ref().map(|id| &id.0), + self.step_id.as_ref().map(|id| &id.0), + self.response_id.as_ref().map(|id| &id.0), + self.parent_response_id.as_ref().map(|id| &id.0), + self.fault_id.as_ref(), + self.retry_reason.as_ref(), + self.checkpoint_id.as_ref(), + self.adopted_checkpoint_id.as_ref(), + ]; + size_of::() + + strings + .into_iter() + .flatten() + .map(String::capacity) + .sum::() + + self.confirmed_call_ids.capacity() * size_of::() + + self + .confirmed_call_ids + .iter() + .map(|id| id.0.capacity()) + .sum::() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PromptBytesPoint { + pub headers_received_ns: u64, + pub purpose: RequestPurpose, + pub request_wire_bytes: u64, + pub effective_context_bytes: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AttributionSummary { + pub mock_service_sum_ns: u64, + pub mock_service_sum_by_purpose_ns: BTreeMap, + pub outside_mock_wall_ns: u64, + pub mock_union_ns: u64, + /// Number of clipped intervals that overlap an earlier interval in start order. + pub overlapping_intervals_count: usize, + pub prompt_bytes_trajectory: Vec, +} + +/// Sum the full attempt durations and independently measure the occupied portion of the wall window. +pub fn compute_attribution( + wall_start_ns: u64, + wall_end_ns: u64, + spans: &[AttemptSpan], +) -> AttributionSummary { + let mut summary = AttributionSummary::default(); + let mut intervals = Vec::with_capacity(spans.len()); + for span in spans { + if let Some((start, end)) = span.interval() { + let duration = end - start; + summary.mock_service_sum_ns = summary.mock_service_sum_ns.saturating_add(duration); + let purpose_sum = summary + .mock_service_sum_by_purpose_ns + .entry(span.purpose) + .or_default(); + *purpose_sum = purpose_sum.saturating_add(duration); + let start = start.max(wall_start_ns); + let end = end.min(wall_end_ns); + if start < end { + intervals.push((start, end)); + } + } + summary.prompt_bytes_trajectory.push(PromptBytesPoint { + headers_received_ns: span.headers_received_ns, + purpose: span.purpose, + request_wire_bytes: span.request_wire_bytes, + effective_context_bytes: span.effective_context_bytes, + }); + } + intervals.sort_unstable(); + let mut covered_until = wall_start_ns; + for (start, end) in intervals { + if start < covered_until { + summary.overlapping_intervals_count += 1; + } + summary.mock_union_ns += end.saturating_sub(start.max(covered_until)); + covered_until = covered_until.max(end); + } + summary.outside_mock_wall_ns = + wall_end_ns.saturating_sub(wall_start_ns) - summary.mock_union_ns; + summary + .prompt_bytes_trajectory + .sort_by_key(|point| point.headers_received_ns); + summary +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TimelineItem { + pub cursor: u64, + #[serde(flatten)] + pub span: AttemptSpan, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionTelemetrySummary { + pub run_id: RunId, + pub session_id: SessionId, + pub cursor: u64, + pub finalized: bool, + pub attempts: u64, + pub retained: usize, + pub retained_bytes: usize, + pub dropped: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionListPage { + pub items: Vec, + pub next_cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionDetailPage { + pub items: Vec, + /// Exclusive resume cursor, including dropped attempts when the page reaches the end. + pub next_cursor: u64, + pub oldest_cursor: Option, + pub dropped: u64, + pub summary: SessionTelemetrySummary, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum SessionTelemetryError { + #[error("session telemetry capacity exhausted")] + Capacity, + #[error("session telemetry belongs to a different run")] + RunMismatch, + #[error("session telemetry is not registered")] + Unregistered, + #[error("session telemetry is finalized")] + Finalized, +} + +#[derive(Default)] +struct SessionTimeline { + items: VecDeque<(Arc, usize)>, + attempts: u64, + retained_bytes: usize, + dropped: u64, + finalized: bool, +} + +struct TelemetrySession { + cursor: u64, + run_id: RunId, + session_id: SessionId, + timeline: Mutex, +} + +impl TelemetrySession { + fn summary(&self, state: &SessionTimeline) -> SessionTelemetrySummary { + SessionTelemetrySummary { + run_id: self.run_id.clone(), + session_id: self.session_id.clone(), + cursor: self.cursor, + attempts: state.attempts, + retained: state.items.len(), + retained_bytes: state.retained_bytes, + dropped: state.dropped, + finalized: state.finalized, + } + } +} + +#[derive(Default)] +struct TelemetryIndex { + by_id: HashMap>, + by_cursor: BTreeMap>, + last_cursor: u64, +} + +pub struct SessionTelemetryStore { + max_sessions: usize, + max_entries_per_session: usize, + max_bytes_per_session: usize, + sessions: RwLock, +} + +impl SessionTelemetryStore { + pub fn new( + max_sessions: usize, + max_entries_per_session: usize, + max_bytes_per_session: usize, + ) -> Self { + Self { + max_sessions, + max_entries_per_session, + max_bytes_per_session, + sessions: RwLock::new(TelemetryIndex::default()), + } + } + + pub fn register_session( + &self, + run_id: &RunId, + session_id: &SessionId, + ) -> Result<(), SessionTelemetryError> { + let session = self.session_for_run(run_id, session_id)?; + let state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + if state.finalized { + return Err(SessionTelemetryError::Finalized); + } + Ok(()) + } + + fn get_session(&self, session_id: &str) -> Option> { + self.sessions + .read() + .unwrap_or_else(|e| e.into_inner()) + .by_id + .get(session_id) + .cloned() + } + + fn session_for_run( + &self, + run_id: &RunId, + session_id: &SessionId, + ) -> Result, SessionTelemetryError> { + let session = if let Some(session) = self.get_session(&session_id.0) { + session + } else { + let mut index = self.sessions.write().unwrap_or_else(|e| e.into_inner()); + if let Some(session) = index.by_id.get(&session_id.0) { + session.clone() + } else { + if index.by_id.len() >= self.max_sessions { + return Err(SessionTelemetryError::Capacity); + } + index.last_cursor += 1; + let session = Arc::new(TelemetrySession { + cursor: index.last_cursor, + run_id: run_id.clone(), + session_id: session_id.clone(), + timeline: Mutex::default(), + }); + index.by_id.insert(session_id.0.clone(), session.clone()); + index.by_cursor.insert(session.cursor, session.clone()); + session + } + }; + if &session.run_id != run_id { + return Err(SessionTelemetryError::RunMismatch); + } + Ok(session) + } + + /// Returns the cursor even when the attempt exceeds the configured retention budget. + pub fn record(&self, span: AttemptSpan) -> Result { + let session = self + .get_session(&span.session_id.0) + .ok_or(SessionTelemetryError::Unregistered)?; + if session.run_id != span.run_id { + return Err(SessionTelemetryError::RunMismatch); + } + let bytes = span.retained_bytes(); + let mut state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + if state.finalized { + return Err(SessionTelemetryError::Finalized); + } + state.attempts += 1; + let cursor = state.attempts; + if self.max_entries_per_session == 0 || bytes > self.max_bytes_per_session { + state.dropped += 1; + return Ok(cursor); + } + while state.items.len() >= self.max_entries_per_session + || state.retained_bytes > self.max_bytes_per_session - bytes + { + let (_, old_bytes) = state + .items + .pop_front() + .expect("timeline exceeds its budget"); + state.retained_bytes -= old_bytes; + state.dropped += 1; + } + state + .items + .push_back((Arc::new(TimelineItem { cursor, span }), bytes)); + state.retained_bytes += bytes; + Ok(cursor) + } + + pub fn list_sessions( + &self, + run_filter: Option<&str>, + cursor: Option, + limit: usize, + ) -> SessionListPage { + use std::ops::Bound::{Excluded, Unbounded}; + + let index = self.sessions.read().unwrap_or_else(|e| e.into_inner()); + let mut matches = index + .by_cursor + .range((Excluded(cursor.unwrap_or(0)), Unbounded)) + .map(|(_, session)| session) + .filter(|session| run_filter.is_none_or(|run| session.run_id.0 == run)); + let sessions: Vec<_> = matches.by_ref().take(limit).cloned().collect(); + let next_cursor = if matches.next().is_some() { + sessions.last().map(|session| session.cursor) + } else { + None + }; + drop(index); + let items = sessions + .into_iter() + .map(|session| { + let state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + session.summary(&state) + }) + .collect(); + SessionListPage { items, next_cursor } + } + + pub fn session_detail( + &self, + session_id: &str, + after_cursor: Option, + limit: usize, + ) -> Option { + let session = self.get_session(session_id)?; + let state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + let after = after_cursor.unwrap_or(0); + let start = state + .items + .partition_point(|(item, _)| item.cursor <= after); + let items: Vec<_> = state + .items + .range(start..) + .take(limit) + .map(|(item, _)| item.clone()) + .collect(); + let next_cursor = if start + items.len() == state.items.len() { + after.max(state.attempts) + } else { + items.last().map_or(after, |item| item.cursor) + }; + let oldest_cursor = state.items.front().map(|(item, _)| item.cursor); + let summary = session.summary(&state); + drop(state); + Some(SessionDetailPage { + items: items.into_iter().map(|item| (*item).clone()).collect(), + next_cursor, + oldest_cursor, + dropped: summary.dropped, + summary, + }) + } + + pub fn finalize(&self, session_id: &str) -> Option { + let session = self.get_session(session_id)?; + let mut state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + state.finalized = true; + Some(session.summary(&state)) + } + + /// Reclaim a finalized session after the exporter has acknowledged its final cursor. + pub fn acknowledge_export( + &self, + session_id: &str, + session_cursor: u64, + through_cursor: u64, + ) -> bool { + let Some(session) = self + .get_session(session_id) + .filter(|session| session.cursor == session_cursor) + else { + return false; + }; + { + let state = session.timeline.lock().unwrap_or_else(|e| e.into_inner()); + if !state.finalized || through_cursor != state.attempts { + return false; + } + } + let mut index = self.sessions.write().unwrap_or_else(|e| e.into_inner()); + if index + .by_id + .get(session_id) + .is_none_or(|current| current.cursor != session_cursor) + { + return false; + } + index.by_id.remove(session_id); + index.by_cursor.remove(&session_cursor); + drop(index); + true + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + use crate::protocol::normalize_request; + use serde_json::json; + + fn span(session: &str, start: u64, end: u64) -> AttemptSpan { + let mut span = AttemptSpan::new( + RunId("run".into()), + SessionId(session.into()), + Protocol::OpenaiResponsesHttp, + Transport::Http, + start, + ); + span.finished_ns = Some(end); + span.purpose = RequestPurpose::Main; + span.outcome = AttemptOutcome::Completed; + span + } + + #[test] + fn prometheus_samples_are_unique_for_mixed_statuses_and_purposes() { + let metrics = ServerMetrics::default(); + let protocol = Protocol::OpenaiResponsesHttp; + for status in ["200", "429", "503"] { + metrics.record_dimension(protocol, "\"model\\\n", status, 23, 2, 1, Some(4), Some(9)); + } + for (purpose, outcome) in [ + (RequestPurpose::Title, AttemptOutcome::Completed), + (RequestPurpose::Title, AttemptOutcome::InjectedFault), + (RequestPurpose::Main, AttemptOutcome::Completed), + ] { + metrics.record_dimension_with_labels( + protocol, + "\"model\\\n", + Some(200), + purpose, + outcome, + 7, + 1, + 0, + Some(3), + Some(8), + ); + } + let output = metrics.render_prometheus(0); + let mut samples = HashSet::new(); + for line in output + .lines() + .filter(|line| !line.is_empty() && !line.starts_with('#')) + { + let sample = line.rsplit_once(' ').unwrap().0; + assert!( + samples.insert(sample), + "duplicate Prometheus sample: {sample}" + ); + } + for status in ["200", "429", "503"] { + assert!(samples.iter().any(|sample| { + sample.starts_with("mock_ai_dimension_tokens_total{") + && sample.contains(&format!("status=\"{status}\"")) + && sample.contains("model=\"\\\"model\\\\\\n\"") + })); + } + assert!(samples.iter().any(|sample| { + sample.starts_with("mock_ai_dimension_ttft_ms_bucket{") + && sample.contains("purpose=\"title\",outcome=\"injected_fault\"") + })); + } + + #[test] + fn attribution_measures_union_inside_wall_and_sums_failed_attempts() { + let mut main = span("session", 5, 105); + main.effective_context_bytes = 500; + let mut title = span("session", 20, 80); + title.purpose = RequestPurpose::Title; + let mut failed = span("session", 130, 150); + failed.outcome = AttemptOutcome::RateLimited; + let summary = compute_attribution(10, 140, &[failed, title, main]); + assert_eq!(summary.mock_service_sum_ns, 180); + assert_eq!( + summary.mock_service_sum_by_purpose_ns, + BTreeMap::from([(RequestPurpose::Main, 120), (RequestPurpose::Title, 60),]) + ); + assert_eq!(summary.mock_union_ns, 105); + assert_eq!(summary.outside_mock_wall_ns, 25); + assert_eq!(summary.overlapping_intervals_count, 1); + assert_eq!( + summary + .prompt_bytes_trajectory + .iter() + .map(|point| (point.headers_received_ns, point.effective_context_bytes)) + .collect::>(), + [(5, 500), (20, 0), (130, 0)] + ); + } + + #[test] + fn session_ring_enforces_both_budgets_and_exports_across_gaps() { + let base = size_of::(); + let store = SessionTelemetryStore::new(3, 2, 3 * base + 128); + let run = RunId("run".into()); + store + .register_session(&run, &SessionId("session".into())) + .unwrap(); + for start in 0..4 { + store.record(span("session", start, start + 1)).unwrap(); + } + + let first = store.session_detail("session", None, 1).unwrap(); + assert_eq!( + (first.oldest_cursor, first.next_cursor, first.dropped), + (Some(3), 3, 2) + ); + assert_eq!(first.items[0].span.headers_received_ns, 2); + let second = store + .session_detail("session", Some(first.next_cursor), 1) + .unwrap(); + assert_eq!(second.items[0].cursor, 4); + + let mut large = span("session", 4, 5); + large.response_id = Some(ResponseId("r".repeat(base + 128))); + store.record(large).unwrap(); + let mut oversized = span("session", 5, 6); + oversized.response_id = Some(ResponseId("r".repeat(4 * base))); + store.record(oversized).unwrap(); + let tail = store + .session_detail("session", Some(second.next_cursor), 10) + .unwrap(); + assert_eq!( + (tail.oldest_cursor, tail.next_cursor, tail.dropped), + (Some(5), 6, 5) + ); + assert_eq!( + tail.items + .iter() + .map(|item| item.cursor) + .collect::>(), + [5] + ); + + let other = RunId("other-run".into()); + store + .register_session(&other, &SessionId("other-session".into())) + .unwrap(); + store + .register_session(&run, &SessionId("second-session".into())) + .unwrap(); + store.record(span("second-session", 0, 1)).unwrap(); + assert_eq!( + store.register_session(&run, &SessionId("over-capacity".into())), + Err(SessionTelemetryError::Capacity) + ); + let finalized = store.finalize("session").unwrap(); + assert_eq!( + store.record(span("session", 6, 7)), + Err(SessionTelemetryError::Finalized) + ); + let page = store.list_sessions(Some("run"), None, 1); + assert_eq!(page.items, std::slice::from_ref(&finalized)); + let next = store.list_sessions(Some("run"), page.next_cursor, 1); + assert_eq!(next.items[0].session_id.0, "second-session"); + assert!(next.next_cursor.is_none()); + assert!(!store.acknowledge_export("session", finalized.cursor, 5)); + assert!(store.acknowledge_export("session", finalized.cursor, tail.next_cursor)); + assert!(store.session_detail("session", None, 10).is_none()); + assert_eq!( + store.record(span("session", 6, 7)), + Err(SessionTelemetryError::Unregistered) + ); + store + .register_session(&other, &SessionId("session".into())) + .unwrap(); + } + + #[test] + fn request_recorder_keeps_small_requests_when_an_oversize_body_arrives() { + let recorder = RequestRecorder::new(RecorderMode::Ring { + capacity: 2, + max_bytes: 130, + }); + let make_request = |sequence, text: &str| { + let body = json!({"model": "model", "input": text}); + normalize_request( + sequence, + Protocol::OpenaiResponsesHttp, + Transport::Http, + "/v1/responses".into(), + BTreeMap::new(), + body.to_string().into(), + body, + ) + }; + recorder.record(&make_request(1, "one")); + recorder.record(&make_request(2, &"large".repeat(50))); + recorder.record(&make_request(3, "three")); + assert_eq!( + recorder + .snapshot() + .into_iter() + .map(|record| record.sequence) + .collect::>(), + [1, 3] + ); + } + + #[test] + fn reset_excludes_completions_from_the_previous_generation() { + let metrics = ServerMetrics::default(); + let old = metrics.generation(); + assert!(metrics.record_for_generation(old, |metrics| metrics.ttft_ms.record(10))); + metrics.reset(); + assert!(!metrics.record_for_generation(old, |metrics| metrics.ttft_ms.record(11))); + assert!( + metrics + .record_for_generation(metrics.generation(), |metrics| metrics.ttft_ms.record(7)) + ); + let snapshot = metrics.snapshot(); + assert_eq!((snapshot.ttft_ms.count, snapshot.ttft_ms.sum), (1, 7)); } } diff --git a/tools/mock-ai/src/pacing.rs b/tools/mock-ai/src/pacing.rs index 7afc201305e..e586a0b5207 100644 --- a/tools/mock-ai/src/pacing.rs +++ b/tools/mock-ai/src/pacing.rs @@ -17,6 +17,7 @@ * under the License. */ +use crate::plan::FrameKind; use crate::ratelimit::RateLimitConfig; use crate::workload::ChaosConfig; use serde::{Deserialize, Serialize}; @@ -47,9 +48,9 @@ pub struct LatencyProfile { pub tps_congestion_factor: f64, /// Target streaming generation speed in tokens/sec (approx 4 chars/token). 0 = unlimited/instant. pub tokens_per_sec: f64, - /// Log-normal coefficient of variation for per-chunk inter-token timing jitter. + /// Log-normal coefficient of variation for per-turn decode speed. pub tps_jitter_cv: f64, - /// Probability [0.0, 1.0] of inserting a mid-stream thinking/network micro-stall before a chunk. + /// Probability [0.0, 1.0] of adding a thinking/network micro-stall to a decoding turn. pub micro_stall_prob: f64, /// Micro-stall duration range (min_ms, max_ms). pub micro_stall_ms_range: (u64, u64), @@ -318,6 +319,12 @@ pub struct TurnPacer { in_flight: usize, explicit_ttft_ms: Option, explicit_chunk_delay_ms: Option, + ttft: Duration, + decode_jitter: f64, + decode_stall: Duration, + decoded_bytes: usize, + decode_started: Option, + non_streaming_output_bytes: Option, } impl TurnPacer { @@ -328,15 +335,66 @@ impl TurnPacer { explicit_ttft_ms: Option, explicit_chunk_delay_ms: Option, ) -> Self { + let rng = fastrand::Rng::with_seed(seed); + let mut decode_rng = rng.clone().fork(); + let decode_jitter = if profile.tps_jitter_cv > 0.0 && profile.tokens_per_sec > 0.0 { + sample_lognormal_multiplier(&mut decode_rng, profile.tps_jitter_cv) + } else { + 1.0 + }; + let decode_stall = + if profile.micro_stall_prob > 0.0 && decode_rng.f64() < profile.micro_stall_prob { + let (lo, hi) = profile.micro_stall_ms_range; + Duration::from_millis(decode_rng.u64(lo..=hi.max(lo))) + } else { + Duration::ZERO + }; Self { profile, - rng: fastrand::Rng::with_seed(seed), + rng, in_flight, explicit_ttft_ms, explicit_chunk_delay_ms, + ttft: Duration::ZERO, + decode_jitter, + decode_stall, + decoded_bytes: 0, + decode_started: None, + non_streaming_output_bytes: None, } } + /// `logical_seed` identifies a scenario lane, step, and attempt without using arrival order. + pub fn new_deterministic( + profile: LatencyProfile, + logical_seed: u64, + prompt_bytes: usize, + cache_hit_ratio: f64, + is_streaming: bool, + output_bytes: usize, + ) -> Self { + let mut pacer = Self::new(profile, logical_seed, 0, None, None); + let input_tokens = (prompt_bytes as u64).div_ceil(4); + let cached_tokens = ((input_tokens as f64 * cache_hit_ratio.clamp(0.0, 1.0)).round() + as u64) + .min(input_tokens); + pacer.compute_ttft(input_tokens - cached_tokens, cached_tokens); + pacer.non_streaming_output_bytes = (!is_streaming).then_some(output_bytes); + pacer + } + + /// Streaming waits for prefill, while non-streaming waits for prefill and the entire decode. + pub fn initial_delay(&self) -> Duration { + match self.non_streaming_output_bytes { + Some(bytes) => self.non_streaming_total_delay(bytes), + None => self.ttft, + } + } + + pub fn non_streaming_total_delay(&self, output_bytes: usize) -> Duration { + self.ttft.saturating_add(self.decode_budget(output_bytes)) + } + pub fn sse_ping_interval(&self) -> Option { (self.profile.sse_ping_interval_ms > 0) .then(|| Duration::from_millis(self.profile.sse_ping_interval_ms)) @@ -344,6 +402,11 @@ impl TurnPacer { /// Compute TTFT for this turn taking prompt prefill, cache read, concurrency congestion, and jitter into account. pub fn compute_ttft(&mut self, uncached_tokens: u64, cached_tokens: u64) -> Duration { + self.ttft = self.sample_ttft(uncached_tokens, cached_tokens); + self.ttft + } + + fn sample_ttft(&mut self, uncached_tokens: u64, cached_tokens: u64) -> Duration { if let Some(ms) = self.explicit_ttft_ms { return Duration::from_millis(ms); } @@ -375,41 +438,55 @@ impl TurnPacer { Duration::from_millis(clamped) } - /// Compute streaming delay for an emitted chunk of `payload_bytes`, including TPS degradation, jitter, and micro-stalls. - pub fn next_chunk_delay(&mut self, payload_bytes: usize) -> Duration { - let mut delay_ms = if let Some(ms) = self.explicit_chunk_delay_ms { - ms as f64 - } else if self.profile.tokens_per_sec > 0.0 && payload_bytes > 0 { - let mut effective_tps = self.profile.tokens_per_sec; - if self.profile.concurrency_knee > 0 && self.in_flight > self.profile.concurrency_knee { - let excess = (self.in_flight - self.profile.concurrency_knee) as f64 - / self.profile.concurrency_knee as f64; - effective_tps /= 1.0 + self.profile.tps_congestion_factor * excess; - } - // Approximate 4 UTF-8 bytes per token, minimum 0.5 token per delta chunk. - let est_tokens = (payload_bytes as f64 / 4.0).max(0.5); - let mut ms = (est_tokens / effective_tps.max(0.1)) * 1000.0; - if self.profile.tps_jitter_cv > 0.0 { - ms *= sample_lognormal_multiplier(&mut self.rng, self.profile.tps_jitter_cv); + /// Anchor decode after the first wire frame and charge semantic bytes against that clock. + pub fn next_frame_deadline( + &mut self, + kind: FrameKind, + semantic_bytes: usize, + sent_at: tokio::time::Instant, + ) -> Option { + if kind == FrameKind::Keepalive { + return None; + } + let started = *self.decode_started.get_or_insert(sent_at); + if kind != FrameKind::SemanticDelta || semantic_bytes == 0 { + return None; + } + let first_delta = self.decoded_bytes == 0; + self.decoded_bytes = self.decoded_bytes.saturating_add(semantic_bytes); + if let Some(ms) = self.explicit_chunk_delay_ms { + let mut delay = Duration::from_millis(ms); + if first_delta { + delay = delay.saturating_add(self.decode_stall); } - ms - } else { - 0.0 - }; - - // Optional mid-stream micro-stall. - if self.profile.micro_stall_prob > 0.0 && self.rng.f64() < self.profile.micro_stall_prob { - let (lo, hi) = self.profile.micro_stall_ms_range; - let hi = hi.max(lo); - let stall = if hi > lo { self.rng.u64(lo..=hi) } else { lo }; - delay_ms += stall as f64; + return Some(sent_at + delay); } + Some(started + self.decode_budget(self.decoded_bytes)) + } - if delay_ms <= 0.0 { - Duration::ZERO - } else { - Duration::from_millis(delay_ms.round().min(60_000.0) as u64) + pub fn jitter_ms(&mut self, min_ms: u64, max_ms: u64) -> u64 { + let lo = min_ms.min(max_ms); + let hi = min_ms.max(max_ms); + if lo == hi { lo } else { self.rng.u64(lo..=hi) } + } + + fn decode_budget(&self, bytes: usize) -> Duration { + if bytes == 0 { + return Duration::ZERO; + } + if self.profile.tokens_per_sec <= 0.0 { + return self.decode_stall; + } + let mut tps = self.profile.tokens_per_sec; + if self.profile.concurrency_knee > 0 && self.in_flight > self.profile.concurrency_knee { + let excess = (self.in_flight - self.profile.concurrency_knee) as f64 + / self.profile.concurrency_knee as f64; + tps /= 1.0 + self.profile.tps_congestion_factor * excess; } + let tokens = bytes as f64 / 4.0; + let millis = (tokens / tps) * self.decode_jitter * 1000.0; + // Round the cumulative budget once, at the timer's millisecond granularity. + Duration::from_millis(millis.round() as u64).saturating_add(self.decode_stall) } } @@ -427,3 +504,146 @@ fn sample_lognormal_multiplier(rng: &mut fastrand::Rng, cv: f64) -> f64 { let z = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos(); (mu + sigma * z).exp().clamp(0.05, 20.0) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn deterministic_delays_follow_logical_attempts_across_interleavings() { + fn pacer(seed: u64) -> TurnPacer { + TurnPacer::new_deterministic( + LatencyProfile::realistic_frontier(), + seed, + 18_000, + 0.5, + true, + 1_200, + ) + } + + let now = tokio::time::Instant::now(); + let delta = |pacer: &mut TurnPacer, bytes| { + pacer.next_frame_deadline(FrameKind::SemanticDelta, bytes, now) + }; + let mut first = pacer(17); + let mut second = pacer(18); + let first_delays = ( + first.initial_delay(), + delta(&mut first, 400), + first.jitter_ms(10, 800), + delta(&mut first, 800), + ); + let second_delays = ( + second.initial_delay(), + delta(&mut second, 400), + second.jitter_ms(10, 800), + delta(&mut second, 800), + ); + assert_ne!(first_delays, second_delays); + + let mut second = pacer(18); + let mut first = pacer(17); + let second_chunk = delta(&mut second, 400); + let first_chunk = delta(&mut first, 400); + assert_eq!( + first.next_frame_deadline(FrameKind::Lifecycle, 500, now), + None + ); + let second_jitter = second.jitter_ms(10, 800); + assert_eq!( + first_delays, + ( + first.initial_delay(), + first_chunk, + first.jitter_ms(10, 800), + delta(&mut first, 800), + ) + ); + assert_eq!( + second_delays, + ( + second.initial_delay(), + second_chunk, + second_jitter, + delta(&mut second, 800), + ) + ); + } + + #[test] + fn semantic_bytes_drive_streaming_and_full_decode() { + let profile = LatencyProfile { + base_ttft_ms: 100, + prefill_tokens_per_sec: 100.0, + cache_read_tokens_per_sec: 200.0, + tokens_per_sec: 10.0, + ..Default::default() + }; + let mut streaming = TurnPacer::new_deterministic(profile.clone(), 1, 400, 0.5, true, 80); + let first_frame = tokio::time::Instant::now(); + assert_eq!(streaming.initial_delay(), Duration::from_millis(850)); + assert_eq!( + streaming.next_frame_deadline(FrameKind::Lifecycle, 500, first_frame), + None + ); + assert_eq!( + streaming.next_frame_deadline(FrameKind::SemanticDelta, 20, first_frame), + Some(first_frame + Duration::from_millis(500)) + ); + assert_eq!( + streaming.next_frame_deadline( + FrameKind::SemanticDelta, + 60, + first_frame + Duration::from_millis(510), + ), + Some(first_frame + Duration::from_millis(2_000)) + ); + let json = TurnPacer::new_deterministic(profile, 1, 400, 0.5, false, 80); + assert_eq!(json.initial_delay(), Duration::from_millis(2_850)); + assert_eq!( + json.non_streaming_total_delay(160), + Duration::from_millis(4_850) + ); + } + + #[test] + fn decode_budget_is_the_same_for_single_frame_fragmented_and_json_output() { + let bytes = 64 * 1024; + let profile = LatencyProfile { + base_ttft_ms: 23, + tokens_per_sec: 127.0, + micro_stall_prob: 1.0, + micro_stall_ms_range: (37, 37), + ..Default::default() + }; + for jitter in [0.0, 0.2] { + let profile = LatencyProfile { + tps_jitter_cv: jitter, + ..profile.clone() + }; + let pacer = + |stream| TurnPacer::new_deterministic(profile.clone(), 17, 0, 0.0, stream, bytes); + let mut single = pacer(true); + let mut fragmented = pacer(true); + let now = tokio::time::Instant::now(); + let single_decode = single + .next_frame_deadline(FrameKind::SemanticDelta, bytes, now) + .unwrap() + - now; + let fragmented_decode = (0..bytes) + .filter_map(|_| fragmented.next_frame_deadline(FrameKind::SemanticDelta, 1, now)) + .last() + .unwrap() + - now; + if jitter == 0.0 { + assert_eq!(single_decode, Duration::from_millis(129_045)); + } + assert_eq!(fragmented_decode, single_decode); + assert_eq!( + pacer(false).initial_delay() - single.initial_delay(), + single_decode + ); + } + } +} diff --git a/tools/mock-ai/src/plan.rs b/tools/mock-ai/src/plan.rs index c7396ce597c..76f3b156ba3 100644 --- a/tools/mock-ai/src/plan.rs +++ b/tools/mock-ai/src/plan.rs @@ -20,6 +20,7 @@ use bytes::Bytes; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::borrow::Cow; use std::collections::BTreeMap; use std::time::Duration; use tokio_util::sync::CancellationToken; @@ -73,6 +74,31 @@ pub enum FinishReason { Incomplete(String), } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProviderDialectProfile { + #[default] + StandardOpenAi, + DeepSeekChat, + KimiChat, + AnthropicMessages, + OpenAiResponses, +} + +impl ProviderDialectProfile { + pub fn emits_chat_reasoning(self) -> bool { + matches!(self, Self::DeepSeekChat | Self::KimiChat) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameKind { + Lifecycle, + SemanticDelta, + Keepalive, + Terminal, +} + /// Token accounting attached to a turn completion. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -110,6 +136,51 @@ impl Usage { self.reasoning_tokens = Some(tokens); self } + + pub fn with_iterations(self, iterations: Vec) -> TurnUsage { + TurnUsage { + totals: self, + iterations, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum UsageIterationKind { + Message, + Compaction, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub struct UsageIteration { + #[serde(rename = "type")] + pub kind: UsageIterationKind, + pub input_tokens: u64, + pub output_tokens: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_read_input_tokens: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cache_creation_input_tokens: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TurnUsage { + #[serde(flatten)] + pub totals: Usage, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub iterations: Vec, +} + +impl From for TurnUsage { + fn from(totals: Usage) -> Self { + Self { + totals, + iterations: Vec::new(), + } + } } /// Citation attached to visible assistant text or search outputs. @@ -124,6 +195,14 @@ pub struct Citation { } /// Tool/function invocation emitted by the simulated model. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum ToolCallPayload { + FunctionArgs(Value), + FreeformInput(String), + MalformedRaw(String), +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ToolCallSpec { @@ -133,8 +212,14 @@ pub struct ToolCallSpec { #[serde(default, skip_serializing_if = "Option::is_none")] pub item_id: Option, pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub namespace: Option, /// JSON object/value or raw JSON string (useful for partial/custom arguments). + #[serde(default)] pub arguments: Value, + /// Explicit payload takes precedence over legacy arguments. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub payload: Option, /// Split serialized arguments into streaming chunks of this many chars (0 = single chunk). #[serde(default)] pub chunk_chars: usize, @@ -158,27 +243,84 @@ impl ToolCallSpec { id: id.into(), item_id: None, name: name.into(), + namespace: None, arguments, + payload: None, chunk_chars: 0, custom_tool: false, thought_signature: None, } } + pub fn with_payload( + id: impl Into, + name: impl Into, + payload: ToolCallPayload, + ) -> Self { + let mut spec = Self::new(id, name, Value::Null); + spec.custom_tool = matches!(payload, ToolCallPayload::FreeformInput(_)); + spec.payload = Some(payload); + spec + } + pub fn with_chunk_chars(mut self, chars: usize) -> Self { self.chunk_chars = chars; self } + pub fn with_namespace(mut self, namespace: impl Into) -> Self { + self.namespace = Some(namespace.into()); + self + } + pub fn as_custom_tool(mut self) -> Self { self.custom_tool = true; + if let Some(payload) = self.payload.take() { + self.payload = Some(ToolCallPayload::FreeformInput(match payload { + ToolCallPayload::FunctionArgs(args) => args.to_string(), + ToolCallPayload::FreeformInput(input) | ToolCallPayload::MalformedRaw(input) => { + input + } + })); + } self } pub fn arguments_string(&self) -> String { - match &self.arguments { - Value::String(s) => s.clone(), - other => other.to_string(), + self.wire_arguments().into_owned() + } + + pub fn wire_arguments(&self) -> Cow<'_, str> { + match &self.payload { + Some(ToolCallPayload::FunctionArgs(args)) => Cow::Owned(args.to_string()), + Some(ToolCallPayload::FreeformInput(input) | ToolCallPayload::MalformedRaw(input)) => { + Cow::Borrowed(input) + } + None => match &self.arguments { + Value::String(raw) => Cow::Borrowed(raw), + value => Cow::Owned(value.to_string()), + }, + } + } + + pub fn is_freeform(&self) -> bool { + match self.payload { + Some(ToolCallPayload::FreeformInput(_)) => true, + Some(_) => false, + None => self.custom_tool, + } + } + + pub(crate) fn take_wire_arguments(&mut self) -> String { + match self.payload.take() { + Some(ToolCallPayload::FunctionArgs(args)) => args.to_string(), + Some(ToolCallPayload::FreeformInput(input) | ToolCallPayload::MalformedRaw(input)) => { + input + } + None => match std::mem::take(&mut self.arguments) { + Value::String(raw) => raw, + value => value.to_string(), + }, } } } @@ -413,6 +555,8 @@ pub enum TurnEvent { NativeCompaction(CompactionOutput), /// Attach usage accounting (consumed when completing the turn). Usage(Usage), + /// Attach usage accounting with individual provider iterations. + UsageWithIterations(TurnUsage), /// Sleep before emitting subsequent events. Delay { ms: u64 }, /// Sleep for a random duration within [min_ms, max_ms] (seeded if configured). @@ -435,6 +579,8 @@ pub enum TurnEvent { /// Immediately close any currently open reasoning/message item (`response.output_item.done` /// or `content_block_stop`) before continuing or stalling. Flush, + /// Emit a provider ping or HTTP SSE keepalive. + Ping, /// Emit an HTTP SSE comment frame (`: \n\n`); no-op on WebSocket / non-streaming. SseComment { comment: String }, /// Emit raw bytes directly onto the HTTP response stream (escape hatch). @@ -568,8 +714,10 @@ impl TurnPlan { name: impl Into, input: impl Into, ) -> Self { - self.push(TurnEvent::ToolCall( - ToolCallSpec::new(id, name, Value::String(input.into())).as_custom_tool(), + self.push(ToolCallSpec::with_payload( + id, + name, + ToolCallPayload::FreeformInput(input.into()), )) } @@ -577,8 +725,13 @@ impl TurnPlan { self.push(TurnEvent::NativeCompaction(output)) } - pub fn with_usage(self, usage: Usage) -> Self { - self.push(TurnEvent::Usage(usage)) + pub fn with_usage(self, usage: impl Into) -> Self { + let usage = usage.into(); + if usage.iterations.is_empty() { + self.push(TurnEvent::Usage(usage.totals)) + } else { + self.push(TurnEvent::UsageWithIterations(usage)) + } } pub fn with_delay(self, duration: Duration) -> Self { diff --git a/tools/mock-ai/src/protocol.rs b/tools/mock-ai/src/protocol.rs index ab15a6689d6..0d8b7407547 100644 --- a/tools/mock-ai/src/protocol.rs +++ b/tools/mock-ai/src/protocol.rs @@ -111,6 +111,71 @@ pub struct NormalizedMessage { pub has_image: bool, #[serde(default)] pub is_compaction_item: bool, + #[serde(default)] + pub kind: NormalizedMessageKind, + #[serde(default)] + pub message_index: usize, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tool_calls: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_content: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub thinking: Vec, + #[serde(default)] + pub is_error: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum NormalizedMessageKind { + #[default] + Message, + FunctionCall, + CustomToolCall, + FunctionCallOutput, + CustomToolCallOutput, + ToolUse, + ToolResult, + Thinking, + Compaction, + Reasoning { + #[serde(default, skip_serializing_if = "Option::is_none")] + encrypted_content: Option, + #[serde(default)] + summary: Vec, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum NormalizedThinking { + Thinking { + text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + signature: Option, + }, + RedactedThinking { + data: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NormalizedToolCall { + pub id: Option, + pub item_id: Option, + pub name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub namespace: Option, + pub payload: NormalizedToolCallPayload, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", content = "value", rename_all = "snake_case")] +pub enum NormalizedToolCallPayload { + FunctionArguments(String), + FreeformInput(String), + AnthropicInput(Value), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -118,9 +183,53 @@ pub struct NormalizedMessage { pub struct NormalizedTool { pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] + pub namespace: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option, + #[serde(default)] + pub tool_kind: ToolDeclKind, + #[serde(default)] + pub deferred: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ToolDeclKind { + #[default] + Function, + Freeform { + format: Option, + }, + ProviderBuiltin, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RequestSizeBreakdown { + pub wire_bytes: usize, + pub body_bytes: usize, + pub tools_bytes: usize, + pub system_bytes: usize, + pub history_bytes: usize, + pub estimated_history_tokens: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RequestOptions { + pub stream_include_usage: bool, + pub tool_choice: Option, + pub parallel_tool_calls: Option, + pub reasoning_effort: Option, + pub include: Vec, + pub store: Option, + pub generate: Option, + pub max_output_tokens: Option, + pub thinking_enabled: bool, + pub anthropic_pause_after_compaction: bool, + pub anthropic_compaction_trigger_tokens: Option, } /// Protocol-independent view of a single incoming model turn request. @@ -138,6 +247,10 @@ pub struct NormalizedRequest { pub session_key: String, /// Byte length of the serialized request body (O(1) context-size signal). pub prompt_bytes: usize, + #[serde(default)] + pub size_breakdown: RequestSizeBreakdown, + #[serde(default)] + pub options: RequestOptions, #[serde(default, skip_serializing_if = "Option::is_none")] pub system_text: Option, pub messages: Vec, @@ -247,288 +360,97 @@ pub fn normalize_request( .as_str() .unwrap_or("mock-model") .to_owned(); - let stream = match protocol { - Protocol::OpenaiResponsesWs => true, - _ => raw_body["stream"].as_bool().unwrap_or(false), + let stream = + protocol == Protocol::OpenaiResponsesWs || raw_body["stream"].as_bool().unwrap_or(false); + let (system_key, history_key) = match protocol { + Protocol::AnthropicMessages => (Some("system"), "messages"), + Protocol::OpenaiChatCompletions => (None, "messages"), + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { + (Some("instructions"), "input") + } }; - let mut system_parts = Vec::new(); + let mut size_breakdown = RequestSizeBreakdown { + wire_bytes: prompt_bytes, + // The current WS create event is flat, so the payload is also the request body. + body_bytes: if raw_wire_bytes.is_empty() { + json_size(&raw_body) + } else { + prompt_bytes + }, + tools_bytes: raw_body.get("tools").map_or(0, json_size), + ..Default::default() + }; + let mut system_text = None; + if let Some(system) = system_key.and_then(|key| raw_body.get(key)) { + size_breakdown.system_bytes = json_size(system); + append_text(&mut system_text, extract_content(system).0); + } + let mut messages = Vec::new(); - let mut tools = Vec::new(); let mut has_compaction_trigger = false; - - match protocol { - Protocol::OpenaiChatCompletions => { - if let Some(arr) = raw_body["messages"].as_array() { - for item in arr { - let role_str = item["role"].as_str().unwrap_or("user"); - let role = match role_str { - "system" => NormalizedRole::System, - "developer" => NormalizedRole::Developer, - "assistant" => NormalizedRole::Assistant, - "tool" => NormalizedRole::Tool, - _ => NormalizedRole::User, - }; - let (text, has_image) = extract_content(&item["content"]); - if matches!(role, NormalizedRole::System | NormalizedRole::Developer) - && !text.is_empty() - { - system_parts.push(text.clone()); - } - messages.push(NormalizedMessage { - role, - text, - tool_call_id: item["tool_call_id"].as_str().map(str::to_owned), - tool_name: item["name"].as_str().map(str::to_owned), - has_image, - is_compaction_item: false, - }); - } - } - if let Some(arr) = raw_body["tools"].as_array() { - for t in arr { - let name = t - .pointer("/function/name") - .or_else(|| t.get("name")) - .and_then(Value::as_str); - if let Some(name) = name { - let parameters = t - .pointer("/function/parameters") - .or_else(|| t.get("parameters")) - .cloned(); - tools.push(NormalizedTool { - name: name.to_owned(), - kind: t["type"].as_str().map(str::to_owned), - parameters, - }); - } - } - } + let mut history_text_bytes = 0; + match &raw_body[history_key] { + Value::String(text) if protocol.is_responses() => { + size_breakdown.history_bytes = json_size(&raw_body[history_key]); + history_text_bytes = text.len(); + messages.push(NormalizedMessage::new( + 0, + NormalizedRole::User, + text.clone(), + false, + )); } - Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { - if let Some(inst) = raw_body["instructions"].as_str() - && !inst.is_empty() - { - system_parts.push(inst.to_owned()); - } - match &raw_body["input"] { - Value::String(s) => { - messages.push(NormalizedMessage { - role: NormalizedRole::User, - text: s.clone(), - tool_call_id: None, - tool_name: None, - has_image: false, - is_compaction_item: false, - }); + Value::Array(items) => { + size_breakdown.history_bytes = 2; // JSON array brackets. + let mut history_items = 0; + for (index, item) in items.iter().enumerate() { + let role = normalized_role(item["role"].as_str()); + let serialized_bytes = json_size(item); + if matches!(role, NormalizedRole::System | NormalizedRole::Developer) { + size_breakdown.system_bytes += serialized_bytes; + append_text(&mut system_text, extract_content(&item["content"]).0); + } else { + size_breakdown.history_bytes += + serialized_bytes + usize::from(history_items != 0); + history_items += 1; } - Value::Array(items) => { - for item in items { - let kind = item["type"].as_str().unwrap_or(""); - match kind { - "compaction_trigger" => { - has_compaction_trigger = true; - } - "compaction" => { - messages.push(NormalizedMessage { - role: NormalizedRole::Assistant, - text: item["encrypted_content"] - .as_str() - .unwrap_or("") - .to_owned(), - tool_call_id: None, - tool_name: None, - has_image: false, - is_compaction_item: true, - }); - } - "function_call_output" | "custom_tool_call_output" => { - let (text, has_image) = extract_content(&item["output"]); - messages.push(NormalizedMessage { - role: NormalizedRole::Tool, - text, - tool_call_id: item["call_id"].as_str().map(str::to_owned), - tool_name: None, - has_image, - is_compaction_item: false, - }); - } - "function_call" | "custom_tool_call" => { - messages.push(NormalizedMessage { - role: NormalizedRole::Assistant, - text: item["arguments"] - .as_str() - .or_else(|| item["input"].as_str()) - .unwrap_or("") - .to_owned(), - tool_call_id: item["call_id"].as_str().map(str::to_owned), - tool_name: item["name"].as_str().map(str::to_owned), - has_image: false, - is_compaction_item: false, - }); - } - _ => { - let role = match item["role"].as_str().unwrap_or("user") { - "system" => NormalizedRole::System, - "developer" => NormalizedRole::Developer, - "assistant" => NormalizedRole::Assistant, - _ => NormalizedRole::User, - }; - let (text, has_image) = extract_content(&item["content"]); - if matches!( - role, - NormalizedRole::System | NormalizedRole::Developer - ) && !text.is_empty() - { - system_parts.push(text.clone()); - } - messages.push(NormalizedMessage { - role, - text, - tool_call_id: None, - tool_name: None, - has_image, - is_compaction_item: false, - }); - } - } + + let start = messages.len(); + match protocol { + Protocol::AnthropicMessages => { + normalize_anthropic_message(index, role, item, &mut messages) } - } - _ => {} - } - if let Some(arr) = raw_body["tools"].as_array() { - for t in arr { - let kind = t["type"].as_str().map(str::to_owned); - let name = t["name"] - .as_str() - .or_else(|| t["type"].as_str()) - .unwrap_or(""); - if !name.is_empty() { - tools.push(NormalizedTool { - name: name.to_owned(), - kind, - parameters: t.get("parameters").cloned(), - }); + Protocol::OpenaiChatCompletions => { + messages.push(normalize_chat_message(index, role, item)) } + _ if item["type"] == "compaction_trigger" => has_compaction_trigger = true, + _ => messages.push(normalize_response_item(index, role, item)), } - } - } - Protocol::AnthropicMessages => { - let (sys_text, _) = extract_content(&raw_body["system"]); - if !sys_text.is_empty() { - system_parts.push(sys_text); - } - if let Some(arr) = raw_body["messages"].as_array() { - for item in arr { - let role = match item["role"].as_str().unwrap_or("user") { - "assistant" => NormalizedRole::Assistant, - _ => NormalizedRole::User, - }; - if let Some(blocks) = item["content"].as_array() { - let mut text_buf = Vec::new(); - let mut has_image = false; - for block in blocks { - match block["type"].as_str().unwrap_or("") { - "text" => { - if let Some(t) = block["text"].as_str() { - text_buf.push(t.to_owned()); - } - } - "image" => { - has_image = true; - } - "tool_result" => { - let (tr_text, tr_img) = extract_content(&block["content"]); - messages.push(NormalizedMessage { - role: NormalizedRole::Tool, - text: tr_text, - tool_call_id: block["tool_use_id"] - .as_str() - .map(str::to_owned), - tool_name: None, - has_image: tr_img, - is_compaction_item: false, - }); - } - "tool_use" => { - messages.push(NormalizedMessage { - role: NormalizedRole::Assistant, - text: block["input"].to_string(), - tool_call_id: block["id"].as_str().map(str::to_owned), - tool_name: block["name"].as_str().map(str::to_owned), - has_image: false, - is_compaction_item: false, - }); - } - "compaction" => { - messages.push(NormalizedMessage { - role: NormalizedRole::Assistant, - text: block["content"].as_str().unwrap_or("").to_owned(), - tool_call_id: None, - tool_name: None, - has_image: false, - is_compaction_item: true, - }); - } - _ => {} - } - } - if !text_buf.is_empty() || has_image { - messages.push(NormalizedMessage { - role, - text: text_buf.join("\n"), - tool_call_id: None, - tool_name: None, - has_image, - is_compaction_item: false, - }); - } - } else { - let (text, has_image) = extract_content(&item["content"]); - messages.push(NormalizedMessage { - role, - text, - tool_call_id: None, - tool_name: None, - has_image, - is_compaction_item: false, - }); - } - } - } - if let Some(arr) = raw_body["tools"].as_array() { - for t in arr { - let name = t["name"].as_str().or_else(|| t["type"].as_str()); - if let Some(name) = name { - tools.push(NormalizedTool { - name: name.to_owned(), - kind: t["type"].as_str().map(str::to_owned), - parameters: t.get("input_schema").cloned(), - }); + for message in &messages[start..] { + if !matches!( + message.role, + NormalizedRole::System | NormalizedRole::Developer + ) { + history_text_bytes += message.estimated_text_bytes(); } } } } + _ => {} } + size_breakdown.estimated_history_tokens = (history_text_bytes as u64).div_ceil(4); - let previous_response_id = raw_body["previous_response_id"].as_str().map(str::to_owned); - - let anthropic_compaction_enabled = protocol == Protocol::AnthropicMessages - && (raw_body - .get("context_management") - .is_some_and(|v| !v.is_null()) - || headers - .get("anthropic-beta") - .is_some_and(|h| h.contains("compact"))); - - let system_text = if system_parts.is_empty() { - None - } else { - Some(system_parts.join("\n")) - }; - + let tools = tool_declarations(protocol, &raw_body["tools"]) + .filter_map(|(tool, namespace)| normalize_tool(protocol, tool, namespace)) + .collect(); + let compaction_edit = (protocol == Protocol::AnthropicMessages) + .then(|| anthropic_compaction_edit(&raw_body, &headers)) + .flatten(); + let options = request_options(protocol, &raw_body, compaction_edit); + let anthropic_compaction_enabled = compaction_edit.is_some(); + let previous_response_id = owned_str(&raw_body["previous_response_id"]); let session_key = derive_session_key(&headers, &raw_body, &messages, &transport); - let estimated_input_tokens = ((prompt_bytes as u64).max(4)) / 4; NormalizedRequest { sequence, @@ -540,18 +462,488 @@ pub fn normalize_request( stream, session_key, prompt_bytes, + size_breakdown, + options, system_text, messages, tools, previous_response_id, has_compaction_trigger, anthropic_compaction_enabled, - estimated_input_tokens, + estimated_input_tokens: (prompt_bytes as u64).max(4) / 4, raw_body, raw_wire_bytes, } } +fn json_size(value: &Value) -> usize { + struct Counter(usize); + + impl std::io::Write for Counter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 += bytes.len(); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + let mut counter = Counter(0); + serde_json::to_writer(&mut counter, value).expect("serializing JSON to a byte counter"); + counter.0 +} + +fn owned_str(value: &Value) -> Option { + value.as_str().map(str::to_owned) +} + +fn append_text(target: &mut Option, text: String) { + if text.is_empty() { + return; + } + match target { + Some(target) => { + target.push('\n'); + target.push_str(&text); + } + None => *target = Some(text), + } +} + +fn normalized_role(role: Option<&str>) -> NormalizedRole { + match role { + Some("system") => NormalizedRole::System, + Some("developer") => NormalizedRole::Developer, + Some("assistant") => NormalizedRole::Assistant, + Some("tool") => NormalizedRole::Tool, + _ => NormalizedRole::User, + } +} + +impl NormalizedMessage { + fn new(message_index: usize, role: NormalizedRole, text: String, has_image: bool) -> Self { + Self { + role, + text, + has_image, + message_index, + tool_call_id: None, + tool_name: None, + is_compaction_item: false, + kind: NormalizedMessageKind::Message, + tool_calls: Vec::new(), + reasoning_content: None, + thinking: Vec::new(), + is_error: false, + } + } + + fn for_content(index: usize, role: NormalizedRole, content: &Value) -> Self { + let (text, has_image) = extract_content(content); + Self::new(index, role, text, has_image) + } + + fn estimated_text_bytes(&self) -> usize { + let mut bytes = self.text.len() + self.reasoning_content.as_ref().map_or(0, String::len); + match self.kind { + NormalizedMessageKind::Message => { + bytes += self + .tool_calls + .iter() + .map(|call| match &call.payload { + NormalizedToolCallPayload::FunctionArguments(raw) + | NormalizedToolCallPayload::FreeformInput(raw) => raw.len(), + NormalizedToolCallPayload::AnthropicInput(value) => json_size(value), + }) + .sum::(); + } + NormalizedMessageKind::Thinking => { + bytes += self + .thinking + .iter() + .map(|block| match block { + NormalizedThinking::Thinking { text, .. } => text.len(), + NormalizedThinking::RedactedThinking { .. } => 0, + }) + .sum::(); + } + _ => {} + } + bytes + } +} + +fn normalize_chat_message(index: usize, role: NormalizedRole, item: &Value) -> NormalizedMessage { + let mut message = NormalizedMessage::for_content(index, role, &item["content"]); + message.tool_call_id = owned_str(&item["tool_call_id"]); + message.tool_name = owned_str(&item["name"]); + message.reasoning_content = owned_str(&item["reasoning_content"]); + message.tool_calls = item["tool_calls"] + .as_array() + .into_iter() + .flatten() + .map(|call| { + let (decl, payload) = if call["type"] == "custom" { + let custom = &call["custom"]; + ( + custom, + NormalizedToolCallPayload::FreeformInput( + custom["input"].as_str().unwrap_or_default().into(), + ), + ) + } else { + let function = &call["function"]; + ( + function, + NormalizedToolCallPayload::FunctionArguments( + function["arguments"].as_str().unwrap_or_default().into(), + ), + ) + }; + NormalizedToolCall { + id: owned_str(&call["id"]), + item_id: None, + name: owned_str(&decl["name"]), + namespace: None, + payload, + } + }) + .collect(); + message +} + +fn normalize_response_item(index: usize, role: NormalizedRole, item: &Value) -> NormalizedMessage { + use NormalizedMessageKind as Kind; + match item["type"].as_str() { + Some(kind @ ("function_call" | "custom_tool_call")) => { + let freeform = kind == "custom_tool_call"; + let input = item[if freeform { "input" } else { "arguments" }] + .as_str() + .unwrap_or_default(); + let mut message = + NormalizedMessage::new(index, NormalizedRole::Assistant, input.into(), false); + message.kind = if freeform { + Kind::CustomToolCall + } else { + Kind::FunctionCall + }; + message.tool_call_id = owned_str(&item["call_id"]); + message.tool_name = owned_str(&item["name"]); + message.tool_calls.push(NormalizedToolCall { + id: message.tool_call_id.clone(), + item_id: owned_str(&item["id"]), + name: message.tool_name.clone(), + namespace: owned_str(&item["namespace"]), + payload: if freeform { + NormalizedToolCallPayload::FreeformInput(input.into()) + } else { + NormalizedToolCallPayload::FunctionArguments(input.into()) + }, + }); + message + } + Some(kind @ ("function_call_output" | "custom_tool_call_output")) => { + let mut message = + NormalizedMessage::for_content(index, NormalizedRole::Tool, &item["output"]); + message.kind = if kind == "custom_tool_call_output" { + Kind::CustomToolCallOutput + } else { + Kind::FunctionCallOutput + }; + message.tool_call_id = owned_str(&item["call_id"]); + message + } + Some("reasoning") => { + let summary: Vec<_> = item["summary"] + .as_array() + .into_iter() + .flatten() + .filter_map(|part| owned_str(&part["text"])) + .collect(); + let mut message = + NormalizedMessage::new(index, NormalizedRole::Assistant, summary.join("\n"), false); + message.kind = Kind::Reasoning { + encrypted_content: owned_str(&item["encrypted_content"]), + summary, + }; + message + } + Some("compaction") => { + let mut message = NormalizedMessage::new( + index, + NormalizedRole::Assistant, + item["encrypted_content"] + .as_str() + .unwrap_or_default() + .into(), + false, + ); + message.kind = Kind::Compaction; + message.is_compaction_item = true; + message + } + _ => NormalizedMessage::for_content(index, role, &item["content"]), + } +} + +fn normalize_anthropic_message( + index: usize, + role: NormalizedRole, + item: &Value, + messages: &mut Vec, +) { + use NormalizedMessageKind as Kind; + let Some(blocks) = item["content"].as_array() else { + messages.push(NormalizedMessage::for_content( + index, + role, + &item["content"], + )); + return; + }; + let mut text = None; + let mut has_image = false; + for block in blocks { + let kind = match block["type"].as_str() { + Some("text") => { + if let Some(part) = block["text"].as_str() { + append_text(&mut text, part.into()); + } + continue; + } + Some("image") => { + has_image = true; + continue; + } + Some("tool_result") => Kind::ToolResult, + Some("tool_use") => Kind::ToolUse, + Some("thinking" | "redacted_thinking") => Kind::Thinking, + Some("compaction") => Kind::Compaction, + _ => continue, + }; + if text.is_some() || has_image { + messages.push(NormalizedMessage::new( + index, + role.clone(), + text.take().unwrap_or_default(), + std::mem::take(&mut has_image), + )); + } + + let mut message = match kind { + Kind::ToolResult => { + let mut message = + NormalizedMessage::for_content(index, NormalizedRole::Tool, &block["content"]); + message.tool_call_id = owned_str(&block["tool_use_id"]); + message.is_error = block["is_error"].as_bool().unwrap_or(false); + message + } + Kind::ToolUse => { + let mut message = NormalizedMessage::new( + index, + NormalizedRole::Assistant, + block["input"].to_string(), + false, + ); + message.tool_call_id = owned_str(&block["id"]); + message.tool_name = owned_str(&block["name"]); + message.tool_calls.push(NormalizedToolCall { + id: message.tool_call_id.clone(), + item_id: None, + name: message.tool_name.clone(), + namespace: None, + payload: NormalizedToolCallPayload::AnthropicInput(block["input"].clone()), + }); + message + } + Kind::Thinking => { + let mut message = NormalizedMessage::new(index, role.clone(), String::new(), false); + message.thinking.push(if block["type"] == "thinking" { + NormalizedThinking::Thinking { + text: block["thinking"].as_str().unwrap_or_default().into(), + signature: owned_str(&block["signature"]), + } + } else { + NormalizedThinking::RedactedThinking { + data: block["data"].as_str().unwrap_or_default().into(), + } + }); + message + } + Kind::Compaction => { + let mut message = NormalizedMessage::for_content( + index, + NormalizedRole::Assistant, + &block["content"], + ); + message.is_compaction_item = true; + message + } + _ => unreachable!(), + }; + message.kind = kind; + messages.push(message); + } + if text.is_some() || has_image || blocks.is_empty() { + messages.push(NormalizedMessage::new( + index, + role, + text.unwrap_or_default(), + has_image, + )); + } +} + +pub(crate) fn tool_declarations( + protocol: Protocol, + tools: &Value, +) -> impl Iterator)> { + tools + .as_array() + .into_iter() + .flatten() + .flat_map(move |tool| { + let (entries, namespace) = if protocol.is_responses() && tool["type"] == "namespace" { + match (tool["name"].as_str(), tool["tools"].as_array()) { + (Some(name), Some(entries)) => (entries.as_slice(), Some(name)), + _ => (&[][..], None), + } + } else { + (std::slice::from_ref(tool), None) + }; + entries.iter().map(move |entry| (entry, namespace)) + }) +} + +fn normalize_tool( + protocol: Protocol, + tool: &Value, + namespace: Option<&str>, +) -> Option { + let kind = tool["type"].as_str(); + let declaration = match protocol { + Protocol::OpenaiChatCompletions => match kind { + Some("function") => tool.get("function").unwrap_or(tool), + Some("custom") => tool.get("custom").unwrap_or(tool), + _ => tool, + }, + _ => tool, + }; + let name = declaration["name"].as_str().or(kind)?; + let (tool_kind, parameter_key) = match (protocol, kind) { + (Protocol::AnthropicMessages, None | Some("custom")) => { + (ToolDeclKind::Function, "input_schema") + } + (Protocol::AnthropicMessages, _) => (ToolDeclKind::ProviderBuiltin, "input_schema"), + (_, Some("custom")) => ( + ToolDeclKind::Freeform { + format: declaration.get("format").cloned(), + }, + "parameters", + ), + (_, None | Some("function")) => (ToolDeclKind::Function, "parameters"), + _ => (ToolDeclKind::ProviderBuiltin, "parameters"), + }; + Some(NormalizedTool { + name: name.into(), + namespace: namespace.map(str::to_owned), + kind: kind.map(str::to_owned), + parameters: declaration.get(parameter_key).cloned(), + tool_kind, + deferred: declaration["defer_loading"] + .as_bool() + .or_else(|| tool["defer_loading"].as_bool()) + .unwrap_or(false), + }) +} + +fn anthropic_compaction_edit<'a>( + body: &'a Value, + headers: &BTreeMap, +) -> Option<&'a Value> { + let beta_enabled = headers.get("anthropic-beta").is_some_and(|header| { + header + .split(',') + .map(str::trim) + .any(|beta| beta.starts_with("compact-") || beta.starts_with("compaction-")) + }); + body.pointer("/context_management/edits")? + .as_array()? + .iter() + .find(|edit| { + edit["type"].as_str().is_some_and(|kind| { + kind.starts_with("compact_") || (beta_enabled && kind == "compact") + }) + }) +} + +fn request_options( + protocol: Protocol, + body: &Value, + compaction_edit: Option<&Value>, +) -> RequestOptions { + let reasoning_effort = match protocol { + Protocol::AnthropicMessages => body.pointer("/output_config/effort"), + Protocol::OpenaiChatCompletions => body.get("reasoning_effort"), + _ => body.pointer("/reasoning/effort"), + }; + let max_output_tokens = match protocol { + Protocol::OpenaiChatCompletions => body["max_completion_tokens"] + .as_u64() + .or_else(|| body["max_tokens"].as_u64()), + Protocol::AnthropicMessages => body["max_tokens"].as_u64(), + _ => body["max_output_tokens"].as_u64(), + }; + RequestOptions { + stream_include_usage: body + .pointer("/stream_options/include_usage") + .and_then(Value::as_bool) + .unwrap_or(false), + tool_choice: body.get("tool_choice").cloned(), + parallel_tool_calls: match protocol { + Protocol::AnthropicMessages + if body.pointer("/tool_choice/disable_parallel_tool_use") + == Some(&Value::Bool(true)) => + { + Some(false) + } + _ => body["parallel_tool_calls"].as_bool(), + }, + reasoning_effort: reasoning_effort.and_then(owned_str), + include: body["include"] + .as_array() + .into_iter() + .flatten() + .filter_map(owned_str) + .collect(), + store: body["store"].as_bool(), + generate: body["generate"].as_bool(), + max_output_tokens, + thinking_enabled: matches!( + body.pointer("/thinking/type").and_then(Value::as_str), + Some("enabled" | "adaptive") + ), + anthropic_pause_after_compaction: compaction_edit + .and_then(|edit| edit["pause_after_compaction"].as_bool()) + .unwrap_or(false), + anthropic_compaction_trigger_tokens: compaction_edit.and_then(|edit| { + let trigger = &edit["trigger"]; + if trigger["type"] != "input_tokens" { + return None; + } + let value = &trigger["value"]; + value.as_u64().or_else(|| { + // Some clients serialize the integer threshold as a JSON float. + let value = value.as_f64()?; + (value >= 0.0 && value < u64::MAX as f64 && value.fract() == 0.0) + .then_some(value as u64) + }) + }), + } +} + fn extract_content(value: &Value) -> (String, bool) { match value { Value::String(s) => (s.clone(), false), @@ -621,3 +1013,228 @@ fn derive_session_key( } format!("conv:{:016x}", hasher.finish()) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn normalize( + protocol: Protocol, + body: Value, + headers: BTreeMap, + ) -> NormalizedRequest { + let bytes = Bytes::from(body.to_string()); + normalize_request( + 1, + protocol, + Transport::Http, + "/test".into(), + headers, + bytes, + body, + ) + } + + #[test] + fn chat_history_preserves_tool_calls_reasoning_and_accounts_for_images() { + let body = json!({ + "stream_options": { "include_usage": true }, + "max_completion_tokens": 24, + "parallel_tool_calls": false, + "reasoning_effort": "high", + "tools": [{ "type": "function", "function": { "name": "look", "parameters": { "type": "object" } } }], + "messages": [ + { "role": "system", "content": "system prompt" }, + { "role": "user", "content": [ + { "type": "text", "text": "look" }, + { "type": "image_url", "image_url": { "url": "data:image/png;base64,AAAAAAAA" } }, + ] }, + { "role": "assistant", "content": null, "reasoning_content": "work", "tool_calls": [ + { "id": "call_1", "type": "function", "function": { "name": "look", "arguments": "{\"x\":1}" } }, + ] }, + ], + }); + let request = normalize( + Protocol::OpenaiChatCompletions, + body.clone(), + BTreeMap::new(), + ); + assert_eq!( + request.size_breakdown, + RequestSizeBreakdown { + wire_bytes: body.to_string().len(), + body_bytes: body.to_string().len(), + tools_bytes: body["tools"].to_string().len(), + system_bytes: body["messages"][0].to_string().len(), + history_bytes: json!([body["messages"][1], body["messages"][2]]) + .to_string() + .len(), + estimated_history_tokens: 4, + } + ); + assert!(request.messages[1].has_image); + assert_eq!( + request.messages[2].reasoning_content.as_deref(), + Some("work") + ); + assert_eq!( + request.messages[2].tool_calls, + vec![NormalizedToolCall { + id: Some("call_1".into()), + item_id: None, + name: Some("look".into()), + namespace: None, + payload: NormalizedToolCallPayload::FunctionArguments("{\"x\":1}".into()), + }] + ); + assert!(request.options.stream_include_usage); + assert_eq!(request.options.reasoning_effort.as_deref(), Some("high")); + assert_eq!(request.options.parallel_tool_calls, Some(false)); + assert_eq!(request.options.max_output_tokens, Some(24)); + } + + #[test] + fn anthropic_preserves_signed_and_redacted_thinking_and_tool_failure() { + let mut body = json!({ + "thinking": { "type": "adaptive" }, + "context_management": { "edits": [{ "type": "clear_tool_uses_20250919" }] }, + "tools": [{ "name": "lookup", "input_schema": {"type": "object"}, "defer_loading": true }], + "messages": [ + { "role": "assistant", "content": [ + { "type": "thinking", "thinking": "thought", "signature": "signed" }, + { "type": "redacted_thinking", "data": "opaque" }, + ] }, + { "role": "user", "content": [ + { "type": "tool_result", "tool_use_id": "toolu_1", "content": "failed", "is_error": true }, + { "type": "text", "text": "try again" }, + ] }, + ], + }); + let headers = BTreeMap::from([("anthropic-beta".into(), "compact-2026-01-12".into())]); + let request = normalize(Protocol::AnthropicMessages, body.clone(), headers.clone()); + assert!(!request.anthropic_compaction_enabled); + assert!(request.options.thinking_enabled); + assert_eq!( + request.messages[0].thinking, + vec![NormalizedThinking::Thinking { + text: "thought".into(), + signature: Some("signed".into()) + }] + ); + assert_eq!( + request.messages[1].thinking, + vec![NormalizedThinking::RedactedThinking { + data: "opaque".into() + }] + ); + assert_eq!(request.messages[2].kind, NormalizedMessageKind::ToolResult); + assert!(request.messages[2].is_error); + assert_eq!( + request.messages[2].message_index, + request.messages[3].message_index + ); + assert_eq!(request.messages[3].text, "try again"); + assert!(request.tools[0].deferred); + body["context_management"]["edits"][0] = json!({ + "type": "compact_20260112", "trigger": { "type": "input_tokens", "value": 80_000.0 }, + "pause_after_compaction": true, + }); + let request = normalize(Protocol::AnthropicMessages, body, headers); + assert!(request.anthropic_compaction_enabled); + assert!(request.options.anthropic_pause_after_compaction); + assert_eq!( + request.options.anthropic_compaction_trigger_tokens, + Some(80_000) + ); + } + + #[test] + fn responses_preserves_item_order_and_freeform_grammar() { + let format = json!({ "type": "grammar", "syntax": "lark", "definition": "start: /.+/" }); + let request = normalize( + Protocol::OpenaiResponsesHttp, + json!({ + "include": ["reasoning.encrypted_content"], + "store": false, "generate": false, + "tools": [ + { "type": "custom", "name": "apply_patch", "format": format }, + { "type": "namespace", "name": "mcp__bench", "tools": [ + { "type": "function", "name": "lookup", "defer_loading": true, + "parameters": { "type": "object" } }, + { "type": "function", "name": "read_file", "defer_loading": false } + ] } + ], + "input": [ + { "type": "reasoning", "encrypted_content": "enc", "summary": [{ "type": "summary_text", "text": "plan" }] }, + { "type": "function_call", "id": "item_1", "call_id": "call_1", "name": "lookup", "namespace": "mcp__bench", "arguments": "{}" }, + { "type": "custom_tool_call", "id": "item_2", "call_id": "call_2", "name": "apply_patch", "input": "raw\npatch" }, + { "type": "custom_tool_call_output", "call_id": "call_2", "output": [{ "type": "input_text", "text": "done" }] }, + ], + }), + BTreeMap::new(), + ); + assert_eq!( + request.tools[0].tool_kind, + ToolDeclKind::Freeform { + format: Some(format) + } + ); + assert_eq!( + request + .tools + .iter() + .map(|tool| (tool.name.as_str(), tool.namespace.as_deref(), tool.deferred)) + .collect::>(), + [ + ("apply_patch", None, false), + ("lookup", Some("mcp__bench"), true), + ("read_file", Some("mcp__bench"), false), + ] + ); + assert_eq!(request.tools[1].tool_kind, ToolDeclKind::Function); + assert_eq!(request.tools[1].parameters, Some(json!({"type": "object"}))); + assert_eq!( + request + .messages + .iter() + .map(|message| (message.message_index, message.kind.clone())) + .collect::>(), + vec![ + ( + 0, + NormalizedMessageKind::Reasoning { + encrypted_content: Some("enc".into()), + summary: vec!["plan".into()] + } + ), + (1, NormalizedMessageKind::FunctionCall), + (2, NormalizedMessageKind::CustomToolCall), + (3, NormalizedMessageKind::CustomToolCallOutput), + ] + ); + assert_eq!( + request.messages[1].tool_calls, + [NormalizedToolCall { + id: Some("call_1".into()), + item_id: Some("item_1".into()), + name: Some("lookup".into()), + namespace: Some("mcp__bench".into()), + payload: NormalizedToolCallPayload::FunctionArguments("{}".into()), + }] + ); + assert_eq!( + request.messages[2].tool_calls[0].payload, + NormalizedToolCallPayload::FreeformInput("raw\npatch".into()) + ); + assert_eq!( + request.messages[2].tool_calls[0].item_id.as_deref(), + Some("item_2") + ); + assert_eq!(request.messages[3].tool_call_id.as_deref(), Some("call_2")); + assert_eq!(request.messages[3].text, "done"); + assert_eq!(request.options.include, ["reasoning.encrypted_content"]); + assert_eq!(request.options.store, Some(false)); + assert_eq!(request.options.generate, Some(false)); + } +} diff --git a/tools/mock-ai/src/proxy.rs b/tools/mock-ai/src/proxy.rs index 49afad9088d..1783815b36f 100644 --- a/tools/mock-ai/src/proxy.rs +++ b/tools/mock-ai/src/proxy.rs @@ -18,6 +18,9 @@ */ use crate::protocol::{NormalizedRequest, Protocol}; +use crate::routing::{ + LogicalLane, ParsedRoute, is_local_control_path, is_runner_routing_header, strip_scope_prefix, +}; use base64::Engine as _; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; @@ -57,6 +60,8 @@ const HOP_BY_HOP_HEADERS: &[&str] = &[ "content-length", "host", ]; +const FINGERPRINT_VERSION: u32 = 2; +const FINGERPRINT_HEX_LEN: usize = 64; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -93,11 +98,15 @@ impl TimedChunk { is_binary: false, data: s.to_string(), }, - Err(_) => Self { - delay_ms, - is_binary: true, - data: base64::engine::general_purpose::STANDARD.encode(bytes), - }, + Err(_) => Self::from_binary(delay_ms, bytes), + } + } + + fn from_binary(delay_ms: u64, bytes: &[u8]) -> Self { + Self { + delay_ms, + is_binary: true, + data: base64::engine::general_purpose::STANDARD.encode(bytes), } } @@ -120,13 +129,19 @@ impl TimedChunk { pub struct RecordedExchange { pub kind: ExchangeKind, pub fingerprint: String, + #[serde(default)] + pub fingerprint_version: u32, pub method: String, + /// Canonical provider path and optional query as sent by the proxy. pub path: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope_lane: Option, pub model: String, #[serde(default)] pub request_headers: BTreeMap, + #[serde(default)] pub request_body: Value, pub status: u16, #[serde(default)] @@ -190,6 +205,9 @@ impl ProxyRecordConfig { let mut out = BTreeMap::new(); for (k, v) in headers { let lower = k.to_ascii_lowercase(); + if is_runner_routing_header(&lower) { + continue; + } let sensitive = DEFAULT_REDACTED_HEADERS.contains(&lower.as_str()) || self .extra_redact_headers @@ -212,7 +230,7 @@ pub enum ReplayMatchMode { /// Match exchanges strictly in recorded order (wraps if `loop_cassette == true`). #[default] Sequential, - /// Match by request fingerprint `(kind, path, model, message_count, last_user)`, with optional sequential fallback. + /// Match by request fingerprint, with optional sequential fallback in permissive replay. Fingerprint, } @@ -235,6 +253,9 @@ pub struct ReplayConfig { /// When `match_mode == Fingerprint`, fall back to sequential replay if no fingerprint matches. #[serde(default = "default_true")] pub fallback_to_sequential: bool, + /// Require a matching, untruncated recording and consume it only once. + #[serde(default)] + pub strict_replay: bool, } fn default_speed() -> f64 { @@ -256,6 +277,7 @@ impl ReplayConfig { max_chunk_delay_ms: default_max_chunk_delay_ms(), loop_cassette: true, fallback_to_sequential: true, + strict_replay: false, } } @@ -269,6 +291,11 @@ impl ReplayConfig { self } + pub fn with_strict_replay(mut self) -> Self { + self.strict_replay = true; + self + } + pub fn scaled_delay(&self, recorded_delay_ms: u64) -> Duration { if recorded_delay_ms == 0 || self.speed_multiplier <= 0.0 @@ -281,67 +308,327 @@ impl ReplayConfig { } } -/// Compute a stable fingerprint for matching requests across runs despite volatile headers/IDs. +/// Compute a provider request fingerprint independently of the runner URL prefix. pub fn compute_fingerprint( kind: ExchangeKind, method: &str, - path: &str, + path_and_query: &str, model: &str, body: &Value, ) -> String { - let mut hasher = Sha256::new(); - hasher.update(match kind { - ExchangeKind::Http => b"http|" as &[u8], - ExchangeKind::WebSocketTurn => b"ws|" as &[u8], - }); - hasher.update(method.as_bytes()); - hasher.update(b"|"); - hasher.update(path.as_bytes()); - hasher.update(b"|"); - hasher.update(model.as_bytes()); - hasher.update(b"|"); - // Hash semantic request content (system/instructions, declared tools, and full message/input - // sequence) while ignoring volatile transport/cache fields so distinct prompts never collide. - if let Some(sys) = body.get("system").or_else(|| body.get("instructions")) { - hasher.update(b"sys:"); - hasher.update(sys.to_string().as_bytes()); - hasher.update(b"|"); - } - if let Some(tools) = body.get("tools") { - hasher.update(b"tools:"); - hasher.update(tools.to_string().as_bytes()); - hasher.update(b"|"); - } - if let Some(prev) = body.get("previous_response_id").and_then(Value::as_str) { - hasher.update(b"prev:"); - hasher.update(prev.as_bytes()); - hasher.update(b"|"); - } - if let Some(msgs) = body.get("messages").or_else(|| body.get("input")) { - hasher.update(b"msgs:"); - hasher.update(msgs.to_string().as_bytes()); - } - let digest = hasher.finalize(); - let mut hex = String::with_capacity(16); - for b in &digest[..8] { - use std::fmt::Write as _; - let _ = write!(&mut hex, "{b:02x}"); - } - hex + compute_fingerprint_for_lane(kind, method, path_and_query, model, body, None) } -pub fn fingerprint_from_normalized(req: &NormalizedRequest) -> String { - let kind = if req.protocol == Protocol::OpenaiResponsesWs { - ExchangeKind::WebSocketTurn +pub fn compute_fingerprint_for_lane( + kind: ExchangeKind, + method: &str, + path_and_query: &str, + model: &str, + body: &Value, + scope_lane: Option<&LogicalLane>, +) -> String { + canonical_request_fingerprint(CanonicalRequest { + kind, + method, + path_and_query, + protocol: None, + model, + body, + headers: &BTreeMap::new(), + scope_lane: scope_lane.map(|lane| lane.0.as_str()), + }) +} + +struct CanonicalRequest<'a> { + kind: ExchangeKind, + method: &'a str, + path_and_query: &'a str, + protocol: Option, + model: &'a str, + body: &'a Value, + headers: &'a BTreeMap, + scope_lane: Option<&'a str>, +} + +fn request_protocol(kind: ExchangeKind, method: &str, provider_path: &str) -> Option { + if kind == ExchangeKind::WebSocketTurn { + return Some(Protocol::OpenaiResponsesWs); + } + let path = provider_path + .split_once('?') + .map_or(provider_path, |(path, _)| path); + match (method, path.strip_prefix("/v1").unwrap_or(path)) { + ("POST", "/chat/completions") => Some(Protocol::OpenaiChatCompletions), + ("POST", "/responses" | "/responses/compact") => Some(Protocol::OpenaiResponsesHttp), + ("POST", "/messages" | "/messages/count_tokens") => Some(Protocol::AnthropicMessages), + _ => None, + } +} + +fn protocol_headers(protocol: Option) -> &'static [&'static str] { + match protocol { + Some(Protocol::AnthropicMessages) => &["anthropic-beta", "anthropic-version"], + Some(_) => &["openai-beta", "openai-version"], + None => &[], + } +} + +fn request_header<'a>(headers: &'a BTreeMap, name: &str) -> Option<&'a str> { + headers + .get(name) + .or_else(|| { + headers + .iter() + .find_map(|(key, value)| key.eq_ignore_ascii_case(name).then_some(value)) + }) + .map(String::as_str) +} + +fn hash_field(hasher: &mut Sha256, field: &str) { + hasher.update((field.len() as u64).to_be_bytes()); + hasher.update(field.as_bytes()); +} + +fn exchange_kind_label(kind: ExchangeKind) -> &'static str { + match kind { + ExchangeKind::Http => "http", + ExchangeKind::WebSocketTurn => "ws", + } +} + +fn canonical_request_fingerprint(request: CanonicalRequest<'_>) -> String { + let path = strip_scope_prefix(request.path_and_query); + let protocol = request + .protocol + .or_else(|| request_protocol(request.kind, request.method, &path)); + let mut hasher = Sha256::new(); + hasher.update(FINGERPRINT_VERSION.to_be_bytes()); + for field in [ + exchange_kind_label(request.kind), + request.method, + &path, + protocol.map_or("", Protocol::as_str), + request.model, + ] { + hash_field(&mut hasher, field); + } + // Use a presence marker so that absent and empty settings remain distinct. + for field in std::iter::once(request.scope_lane).chain( + protocol_headers(protocol) + .iter() + .map(|name| request_header(request.headers, name).map(str::trim)), + ) { + match field { + Some(value) => { + hasher.update([1]); + hash_field(&mut hasher, value); + } + None => hasher.update([0]), + } + } + // Include provider extensions alongside the common fields. Cache affinity is per run. + if let Value::Object(body) = request.body { + hash_object(&mut hasher, body, Some("prompt_cache_key")); } else { - ExchangeKind::Http + hash_json(&mut hasher, request.body); + } + use std::fmt::Write as _; + let mut fingerprint = String::with_capacity(FINGERPRINT_HEX_LEN); + for byte in hasher.finalize() { + write!(fingerprint, "{byte:02x}").expect("writing to a String"); + } + fingerprint +} + +fn hash_json(hasher: &mut Sha256, value: &Value) { + match value { + Value::Null => hasher.update(b"n"), + Value::Bool(value) => hasher.update(if *value { b"t" } else { b"f" }), + Value::Number(value) => { + hasher.update(b"d"); + hash_field(hasher, &value.to_string()); + } + Value::String(value) => { + hasher.update(b"s"); + hash_field(hasher, value); + } + Value::Array(values) => { + hasher.update(b"a"); + hasher.update((values.len() as u64).to_be_bytes()); + for value in values { + hash_json(hasher, value); + } + } + Value::Object(object) => hash_object(hasher, object, None), + } +} + +fn hash_object(hasher: &mut Sha256, object: &serde_json::Map, omit: Option<&str>) { + let len = object.len() - usize::from(omit.is_some_and(|key| object.contains_key(key))); + hasher.update(b"o"); + hasher.update((len as u64).to_be_bytes()); + let entries = object.iter().filter(|(key, _)| Some(key.as_str()) != omit); + let hash_entry = |(key, value): (&String, &Value)| { + hash_field(hasher, key); + hash_json(hasher, value); }; + // Map order can depend on Cargo feature unification for serde_json. + if entries.clone().is_sorted_by(|(a, _), (b, _)| a <= b) { + entries.for_each(hash_entry); + } else { + let mut entries: Vec<_> = entries.collect(); + entries.sort_unstable_by_key(|(key, _)| *key); + entries.into_iter().for_each(hash_entry); + } +} + +// Verify that the old recorder saved the lane it hashed and used the path with its query. +fn legacy_fingerprint_matches(exchange: &RecordedExchange, scope_lane: Option<&str>) -> bool { + let mut hasher = Sha256::new(); + let kind = exchange_kind_label(exchange.kind); + let body = &exchange.request_body; + for field in [kind, &exchange.method, &exchange.path, &exchange.model] { + hash_field(&mut hasher, field); + } + if let Some(lane) = scope_lane { + hash_field(&mut hasher, "scope_lane"); + hash_field(&mut hasher, lane); + } + for (name, field) in [ + ( + "system", + body.get("system").or_else(|| body.get("instructions")), + ), + ( + "history", + body.get("messages").or_else(|| body.get("input")), + ), + ("tools", body.get("tools")), + ("previous_response_id", body.get("previous_response_id")), + ("stream", body.get("stream")), + ("stream_options", body.get("stream_options")), + ("tool_choice", body.get("tool_choice")), + ("parallel_tool_calls", body.get("parallel_tool_calls")), + ("reasoning", body.get("reasoning")), + ("reasoning_effort", body.get("reasoning_effort")), + ("include", body.get("include")), + ("generate", body.get("generate")), + ("store", body.get("store")), + ("context_management", body.get("context_management")), + ("max_output_tokens", body.get("max_output_tokens")), + ("max_completion_tokens", body.get("max_completion_tokens")), + ("max_tokens", body.get("max_tokens")), + ] { + if let Some(value) = field { + hash_field(&mut hasher, name); + hash_field(&mut hasher, &value.to_string()); + } + } + format!( + "{:016x}", + u64::from_be_bytes(hasher.finalize()[..8].try_into().unwrap()) + ) == exchange.fingerprint +} + +fn normalized_exchange_kind(req: &NormalizedRequest) -> (ExchangeKind, &'static str) { + if req.protocol == Protocol::OpenaiResponsesWs { + (ExchangeKind::WebSocketTurn, "WS") + } else { + (ExchangeKind::Http, "POST") + } +} + +/// Fixture lane label used for capture independently of per-run IDs. +pub const SCOPE_LANE_HEADER: &str = "x-maka-bench-lane"; + +pub fn fingerprint_from_normalized(req: &NormalizedRequest) -> String { + let (kind, method) = normalized_exchange_kind(req); + canonical_request_fingerprint(CanonicalRequest { + kind, + method, + path_and_query: &req.path, + protocol: Some(req.protocol), + model: req.raw_body["model"].as_str().unwrap_or(""), + body: &req.raw_body, + headers: &req.headers, + scope_lane: request_header(&req.headers, SCOPE_LANE_HEADER), + }) +} + +pub fn fingerprint_from_route( + req: &NormalizedRequest, + method: &str, + route: &ParsedRoute<'_>, + scope_lane: Option<&LogicalLane>, +) -> String { + let (kind, normalized_method) = normalized_exchange_kind(req); let method = if kind == ExchangeKind::WebSocketTurn { - "WS" + normalized_method } else { - "POST" + method }; - compute_fingerprint(kind, method, &req.path, &req.model, &req.raw_body) + canonical_request_fingerprint(CanonicalRequest { + kind, + method, + path_and_query: &route.canonical_path_and_query(), + protocol: Some(req.protocol), + model: req.raw_body["model"].as_str().unwrap_or(""), + body: &req.raw_body, + headers: &req.headers, + scope_lane: scope_lane + .map(|lane| lane.0.as_str()) + .or_else(|| request_header(&req.headers, SCOPE_LANE_HEADER)), + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum ReplayError { + #[error("cassette fingerprint miss")] + Miss, + #[error("cassette replay exhausted")] + Exhausted, + #[error("cassette recording was truncated")] + Truncated, + #[error("cassette exchange does not match the request constraints")] + Rejected, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum ReplayBodyError { + #[error("cassette recording was truncated")] + Truncated, + #[error("recorded upstream HTTP stream failed")] + UpstreamError, + #[error("recorded client disconnected before HTTP stream completion")] + ClientDisconnected, +} + +impl RecordedExchange { + /// Emit the captured HTTP prefix at recorded intervals, then reproduce its termination. + pub fn replay_http_body( + self, + config: ReplayConfig, + ) -> impl futures_util::Stream> { + let terminal_error = match self.outcome { + ExchangeOutcome::Completed => None, + ExchangeOutcome::Truncated => Some(ReplayBodyError::Truncated), + ExchangeOutcome::UpstreamError => Some(ReplayBodyError::UpstreamError), + ExchangeOutcome::ClientDisconnected => Some(ReplayBodyError::ClientDisconnected), + }; + futures_util::stream::unfold( + (self.chunks.into_iter(), config, terminal_error), + |(mut chunks, config, error)| async move { + if let Some(chunk) = chunks.next() { + let delay = config.scaled_delay(chunk.delay_ms); + if !delay.is_zero() { + tokio::time::sleep(delay).await; + } + return Some((Ok(chunk.to_bytes()), (chunks, config, error))); + } + error.map(|err| (Err(err), (chunks, config, None))) + }, + ) + } } struct PendingGuard { @@ -434,36 +721,31 @@ pub struct CassetteReplayer { ws_cursor: AtomicUsize, http_by_fp: HashMap>, ws_by_fp: HashMap>, - fp_cursors: Mutex>, + http_fp_cursors: Mutex>, + ws_fp_cursors: Mutex>, } impl CassetteReplayer { pub fn load(config: ReplayConfig) -> Result { - let exchanges = load_ndjson(&config.cassette_path)?; + let indexed = config.match_mode == ReplayMatchMode::Fingerprint; + let exchanges = read_ndjson(&config.cassette_path, indexed || config.strict_replay)?; let mut http_exchanges = Vec::new(); let mut ws_exchanges = Vec::new(); let mut http_by_fp: HashMap> = HashMap::new(); let mut ws_by_fp: HashMap> = HashMap::new(); for ex in exchanges { - match ex.kind { - ExchangeKind::Http => { - let idx = http_exchanges.len(); - http_by_fp - .entry(ex.fingerprint.clone()) - .or_default() - .push(idx); - http_exchanges.push(ex); - } - ExchangeKind::WebSocketTurn => { - let idx = ws_exchanges.len(); - ws_by_fp - .entry(ex.fingerprint.clone()) - .or_default() - .push(idx); - ws_exchanges.push(ex); - } + let (list, by_fp) = match ex.kind { + ExchangeKind::Http => (&mut http_exchanges, &mut http_by_fp), + ExchangeKind::WebSocketTurn => (&mut ws_exchanges, &mut ws_by_fp), + }; + if indexed { + by_fp + .entry(ex.fingerprint.clone()) + .or_default() + .push(list.len()); } + list.push(ex); } Ok(Self { @@ -474,7 +756,8 @@ impl CassetteReplayer { ws_cursor: AtomicUsize::new(0), http_by_fp, ws_by_fp, - fp_cursors: Mutex::new(HashMap::new()), + http_fp_cursors: Mutex::default(), + ws_fp_cursors: Mutex::default(), }) } @@ -493,103 +776,142 @@ impl CassetteReplayer { pub fn reset(&self) { self.http_cursor.store(0, Ordering::Relaxed); self.ws_cursor.store(0, Ordering::Relaxed); - self.fp_cursors - .lock() - .unwrap_or_else(|e| e.into_inner()) - .clear(); + self.http_fp_cursors.lock().unwrap().clear(); + self.ws_fp_cursors.lock().unwrap().clear(); } pub fn next_http(&self, fingerprint: &str) -> Option<&RecordedExchange> { self.next_http_if(fingerprint, |_| true) } - /// Select the next HTTP exchange only if `accept` returns true; never advances cursors on rejection. + /// Select the next HTTP exchange only if the caller accepts it. pub fn next_http_if( &self, fingerprint: &str, accept: impl Fn(&RecordedExchange) -> bool, ) -> Option<&RecordedExchange> { - self.select( - &self.http_exchanges, - &self.http_cursor, - &self.http_by_fp, - fingerprint, - accept, - ) + self.legacy_selection(self.try_next_http_if(fingerprint, accept)) } pub fn next_ws(&self, fingerprint: &str) -> Option<&RecordedExchange> { - self.select( - &self.ws_exchanges, - &self.ws_cursor, - &self.ws_by_fp, - fingerprint, - |_| true, - ) + self.legacy_selection(self.try_next_ws(fingerprint)) } - fn select<'a>( - &'a self, - list: &'a [RecordedExchange], - cursor: &AtomicUsize, - by_fp: &HashMap>, - fingerprint: &str, - accept: impl Fn(&RecordedExchange) -> bool, + fn legacy_selection<'a>( + &self, + result: Result<&'a RecordedExchange, ReplayError>, ) -> Option<&'a RecordedExchange> { - if list.is_empty() { - return None; + if self.config.strict_replay + && let Err(err) = &result + { + tracing::warn!("strict cassette replay: {err}"); } + result.ok() + } + + pub fn try_next_http(&self, fingerprint: &str) -> Result<&RecordedExchange, ReplayError> { + self.try_next_http_if(fingerprint, |_| true) + } + + pub fn try_next_http_if( + &self, + fingerprint: &str, + accept: impl Fn(&RecordedExchange) -> bool, + ) -> Result<&RecordedExchange, ReplayError> { + self.select(ExchangeKind::Http, fingerprint, accept) + } + + pub fn try_next_ws(&self, fingerprint: &str) -> Result<&RecordedExchange, ReplayError> { + self.try_next_ws_if(fingerprint, |_| true) + } + + pub fn try_next_ws_if( + &self, + fingerprint: &str, + accept: impl Fn(&RecordedExchange) -> bool, + ) -> Result<&RecordedExchange, ReplayError> { + self.select(ExchangeKind::WebSocketTurn, fingerprint, accept) + } + + fn select( + &self, + kind: ExchangeKind, + fingerprint: &str, + accept: impl Fn(&RecordedExchange) -> bool, + ) -> Result<&RecordedExchange, ReplayError> { + let (list, cursor, by_fp, fp_cursors) = match kind { + ExchangeKind::Http => ( + &self.http_exchanges, + &self.http_cursor, + &self.http_by_fp, + &self.http_fp_cursors, + ), + ExchangeKind::WebSocketTurn => ( + &self.ws_exchanges, + &self.ws_cursor, + &self.ws_by_fp, + &self.ws_fp_cursors, + ), + }; + let strict = self.config.strict_replay; + let looping = self.config.loop_cassette && !strict; + let validate = |candidate: &RecordedExchange| { + if strict && candidate.outcome == ExchangeOutcome::Truncated { + Err(ReplayError::Truncated) + } else if !accept(candidate) { + Err(ReplayError::Rejected) + } else { + Ok(()) + } + }; if self.config.match_mode == ReplayMatchMode::Fingerprint { if let Some(indices) = by_fp.get(fingerprint) { - let mut fp_map = self.fp_cursors.lock().unwrap_or_else(|e| e.into_inner()); - let slot = fp_map.entry(fingerprint.to_string()).or_insert(0); - let pos = if *slot < indices.len() { - *slot - } else if self.config.loop_cassette { + let mut fp_map = fp_cursors.lock().unwrap(); + let slot = fp_map.entry(fingerprint.to_owned()).or_insert(0); + let pos = if looping { *slot % indices.len() } else { - indices.len() - 1 + *slot }; - let candidate = list.get(indices[pos])?; - if !accept(candidate) { - return None; - } - if *slot < indices.len() || self.config.loop_cassette { - *slot += 1; - } - return Some(candidate); + let idx = *indices.get(pos).ok_or(ReplayError::Exhausted)?; + let candidate = &list[idx]; + validate(candidate)?; + *slot += 1; + return Ok(candidate); } - if !self.config.fallback_to_sequential { - return None; + if strict || !self.config.fallback_to_sequential { + return Err(ReplayError::Miss); } } - // Atomically peek-and-validate before advancing sequential cursor so a rejected request - // (e.g. mismatched previous_response_id) never consumes the next recorded exchange. + // Rejected requests leave the current exchange available for the matching request. loop { let idx = cursor.load(Ordering::Acquire); - let target = if idx < list.len() { - idx - } else if self.config.loop_cassette { + let target = if looping && !list.is_empty() { idx % list.len() } else { - return None; + idx }; - let candidate = list.get(target)?; - if !accept(candidate) { - return None; + let candidate = list.get(target).ok_or(ReplayError::Exhausted)?; + if strict && candidate.fingerprint != fingerprint { + return Err(ReplayError::Miss); } + validate(candidate)?; if cursor .compare_exchange(idx, idx + 1, Ordering::AcqRel, Ordering::Acquire) .is_ok() { - return Some(candidate); + return Ok(candidate); } } } } pub fn load_ndjson(path: &Path) -> Result, String> { + read_ndjson(path, false) +} + +fn read_ndjson(path: &Path, require_fingerprint: bool) -> Result, String> { let file = File::open(path).map_err(|e| format!("failed to open cassette {}: {e}", path.display()))?; let reader = BufReader::new(file); @@ -600,13 +922,88 @@ pub fn load_ndjson(path: &Path) -> Result, String> { if trimmed.is_empty() { continue; } - let ex: RecordedExchange = serde_json::from_str(trimmed) - .map_err(|e| format!("invalid cassette JSON at line {}: {e}", idx + 1))?; + let invalid_json = |e| format!("invalid cassette JSON at line {}: {e}", idx + 1); + let ex = if require_fingerprint { + let raw = serde_json::from_str(trimmed).map_err(invalid_json)?; + prepare_recorded_fingerprint(raw) + .map_err(|err| format!("cassette incompatible at line {}: {err}", idx + 1))? + } else { + serde_json::from_str(trimmed).map_err(invalid_json)? + }; out.push(ex); } Ok(out) } +fn prepare_recorded_fingerprint(raw: Value) -> Result { + if !raw["requestHeaders"].is_object() { + return Err("fingerprint matching requires recorded requestHeaders".into()); + } + if raw.get("requestBody").is_none() { + return Err("fingerprint matching requires recorded requestBody".into()); + } + let mut exchange: RecordedExchange = + serde_json::from_value(raw).map_err(|err| err.to_string())?; + if exchange.fingerprint.is_empty() || !exchange.path.starts_with('/') { + return Err("missing recorded fingerprint or provider path".into()); + } + if exchange.fingerprint_version == FINGERPRINT_VERSION { + if exchange.fingerprint.len() != FINGERPRINT_HEX_LEN + || !exchange + .fingerprint + .bytes() + .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + { + return Err("fingerprint version 2 requires a lowercase SHA-256 key".into()); + } + return Ok(exchange); + } + if exchange.fingerprint_version > FINGERPRINT_VERSION { + return Err(format!( + "unsupported fingerprint version {}", + exchange.fingerprint_version + )); + } + let path = strip_scope_prefix(&exchange.path); + let protocol = exchange + .protocol + .or_else(|| request_protocol(exchange.kind, &exchange.method, &path)); + if protocol.is_some() && !exchange.request_body.is_object() { + return Err("legacy recording is missing its JSON request body".into()); + } + if protocol_headers(protocol) + .iter() + .any(|name| request_header(&exchange.request_headers, name) == Some("[REDACTED]")) + { + return Err( + "legacy recording has redacted protocol headers; re-record the cassette".into(), + ); + } + let scope_lane = exchange + .scope_lane + .as_ref() + .map(|lane| lane.0.as_str()) + .or_else(|| request_header(&exchange.request_headers, SCOPE_LANE_HEADER)); + if scope_lane == Some("[REDACTED]") || !legacy_fingerprint_matches(&exchange, scope_lane) { + return Err( + "legacy fingerprint cannot be reconstructed from the recorded request (path/query or scope lane unavailable); re-record the cassette" + .into(), + ); + } + exchange.fingerprint = canonical_request_fingerprint(CanonicalRequest { + kind: exchange.kind, + method: &exchange.method, + path_and_query: &path, + protocol, + model: &exchange.model, + body: &exchange.request_body, + headers: &exchange.request_headers, + scope_lane, + }); + exchange.fingerprint_version = FINGERPRINT_VERSION; + Ok(exchange) +} + /// Transparent HTTP + WebSocket upstream proxy recorder (supports HTTP, HTTPS, WS, and WSS). pub struct ProxyRecorder { config: ProxyRecordConfig, @@ -666,14 +1063,22 @@ impl ProxyRecorder { raw_body: Bytes, shutdown: CancellationToken, ) -> Result { - let url = format!("{}{}", self.config.upstream_base_url, path_and_query); + let canonical = provider_path_and_query(path_and_query)?; + let url = reqwest::Url::parse(&format!("{}{canonical}", self.config.upstream_base_url)) + .map_err(|e| format!("invalid upstream HTTP URL: {e}"))?; + if canonical != path_and_query && is_local_control_path(url.path()) { + return Err(SCOPED_CONTROL_ERROR.into()); + } let req_method = reqwest::Method::from_bytes(method.as_bytes()) .map_err(|e| format!("invalid HTTP method {method}: {e}"))?; - let mut builder = self.client.request(req_method, &url); + let mut builder = self.client.request(req_method, url.clone()); for (k, v) in headers { let lower = k.to_ascii_lowercase(); - if HOP_BY_HOP_HEADERS.contains(&lower.as_str()) || lower == "accept-encoding" { + if HOP_BY_HOP_HEADERS.contains(&lower.as_str()) + || lower == "accept-encoding" + || is_runner_routing_header(&lower) + { continue; } if let Some((ref override_k, _)) = self.config.upstream_auth_header @@ -715,13 +1120,19 @@ impl ProxyRecorder { .and_then(Value::as_str) .unwrap_or("") .to_string(); - let path_only = path_and_query - .split('?') - .next() - .unwrap_or(path_and_query) - .to_string(); - let fingerprint = - compute_fingerprint(ExchangeKind::Http, method, &path_only, &model, &req_json); + let scope_lane = request_header(headers, SCOPE_LANE_HEADER); + let fingerprint = canonical_request_fingerprint(CanonicalRequest { + kind: ExchangeKind::Http, + method, + path_and_query: &canonical, + protocol, + model: &model, + body: &req_json, + headers, + scope_lane, + }); + let scope_lane = scope_lane.map(|lane| LogicalLane(lane.into())); + let path = canonical.into_owned(); let redacted_req_headers = self.config.redact_headers(headers); let redacted_resp_headers = self.config.redact_headers(&resp_headers_map); @@ -737,7 +1148,6 @@ impl ProxyRecorder { let mut chunks = Vec::new(); let mut recorded_bytes = 0usize; let mut outcome = ExchangeOutcome::Completed; - let mut truncated = false; let mut last_tick = started; loop { @@ -765,13 +1175,12 @@ impl ProxyRecorder { let now = Instant::now(); let delay_ms = now.saturating_duration_since(last_tick).as_millis() as u64; last_tick = now; - if !truncated { + if outcome != ExchangeOutcome::Truncated { if recorded_bytes.saturating_add(chunk.len()) <= max_record { recorded_bytes = recorded_bytes.saturating_add(chunk.len()); chunks.push(TimedChunk::from_bytes(delay_ms, &chunk)); } else { // Stop recording once capped so we never save a broken stream with missing middle + terminal. - truncated = true; outcome = ExchangeOutcome::Truncated; } } @@ -783,19 +1192,24 @@ impl ProxyRecorder { } } Err(err) => { - outcome = ExchangeOutcome::UpstreamError; + if outcome != ExchangeOutcome::Truncated { + outcome = ExchangeOutcome::UpstreamError; + } let _ = tx.send(Err(format!("upstream stream error: {err}"))).await; break; } } } + drop(tx); let exchange = RecordedExchange { kind: ExchangeKind::Http, fingerprint, + fingerprint_version: FINGERPRINT_VERSION, method: method_owned, - path: path_only, + path, protocol, + scope_lane, model, request_headers: redacted_req_headers, request_body: req_json, @@ -826,50 +1240,7 @@ impl ProxyRecorder { where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, { - let ws_base = if let Some(rest) = self.config.upstream_base_url.strip_prefix("http://") { - format!("ws://{rest}") - } else if let Some(rest) = self.config.upstream_base_url.strip_prefix("https://") { - format!("wss://{rest}") - } else { - self.config.upstream_base_url.clone() - }; - let url = format!("{ws_base}{path_and_query}"); - - use tokio_tungstenite::tungstenite::client::IntoClientRequest; - let mut req = url - .into_client_request() - .map_err(|e| format!("invalid upstream ws url: {e}"))?; - for (k, v) in headers { - let lower = k.to_ascii_lowercase(); - if HOP_BY_HOP_HEADERS.contains(&lower.as_str()) || lower.starts_with("sec-websocket-") { - continue; - } - if let Some((ref override_k, _)) = self.config.upstream_auth_header - && override_k.eq_ignore_ascii_case(&lower) - { - continue; - } - if let (Ok(hk), Ok(hv)) = ( - tokio_tungstenite::tungstenite::http::header::HeaderName::from_bytes( - lower.as_bytes(), - ), - tokio_tungstenite::tungstenite::http::HeaderValue::from_str(v), - ) { - req.headers_mut().insert(hk, hv); - } - } - if let Some((ref override_k, ref override_v)) = self.config.upstream_auth_header - && let (Ok(hk), Ok(hv)) = ( - tokio_tungstenite::tungstenite::http::header::HeaderName::from_bytes( - override_k.as_bytes(), - ), - tokio_tungstenite::tungstenite::http::HeaderValue::from_str(override_v), - ) - { - req.headers_mut().insert(hk, hv); - } - - let upstream_ws = crate::tls::connect_ws_upstream(req, &self.tls_connector).await?; + let upstream_ws = self.connect_upstream_ws(path_and_query, headers).await?; self.bridge_websocket( client_ws, upstream_ws, @@ -893,7 +1264,8 @@ impl ProxyRecorder { } else { self.config.upstream_base_url.clone() }; - let url = format!("{ws_base}{path_and_query}"); + let canonical = provider_path_and_query(path_and_query)?; + let url = format!("{ws_base}{canonical}"); use tokio_tungstenite::tungstenite::client::IntoClientRequest; let mut req = url @@ -901,7 +1273,10 @@ impl ProxyRecorder { .map_err(|e| format!("invalid upstream ws url: {e}"))?; for (k, v) in headers { let lower = k.to_ascii_lowercase(); - if HOP_BY_HOP_HEADERS.contains(&lower.as_str()) || lower.starts_with("sec-websocket-") { + if HOP_BY_HOP_HEADERS.contains(&lower.as_str()) + || lower.starts_with("sec-websocket-") + || is_runner_routing_header(&lower) + { continue; } if let Some((ref override_k, _)) = self.config.upstream_auth_header @@ -933,7 +1308,7 @@ impl ProxyRecorder { } /// Bridge an upgraded client WebSocket to an already-connected upstream WebSocket, - /// flushing each completed turn immediately upon terminal frames so shutdown never drops it. + /// recording completed turns in connection order while forwarding frames. pub async fn bridge_websocket( &self, client_ws: tokio_tungstenite::WebSocketStream, @@ -945,194 +1320,178 @@ impl ProxyRecorder { where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, { + let canonical = provider_path_and_query(path_and_query)?; + let scope_lane = request_header(headers, SCOPE_LANE_HEADER); + let redacted_headers = self.config.redact_headers(headers); + let max_record = self.config.max_record_bytes_per_exchange; let (mut client_tx, mut client_rx) = client_ws.split(); let (mut upstream_tx, mut upstream_rx) = upstream_ws.split(); - let path_only = path_and_query - .split('?') - .next() - .unwrap_or(path_and_query) - .to_string(); - let redacted_headers = self.config.redact_headers(headers); - struct WsTurnBuf { - fp: String, - model: String, - req_body: Value, - last_tick: Instant, - chunks: Vec, - recorded_bytes: usize, - outcome: ExchangeOutcome, - } - let max_record = self.config.max_record_bytes_per_exchange; - let mut active_turn: Option = None; + let (completed_tx, mut completed_rx) = mpsc::channel(16); + let writer = self.writer.clone(); + tokio::spawn(async move { + while let Some((exchange, _in_flight)) = completed_rx.recv().await { + if let Err(err) = writer.append(exchange).await { + tracing::warn!("ws proxy cassette write failed: {err}"); + } + } + }); + let enqueue = |job| async { + completed_tx + .send(job) + .await + .map_err(|_| "ws cassette writer stopped".to_owned()) + }; + let track = + |turn: WsRecording, outcome| (turn.finish(outcome), self.writer.track_in_flight()); - loop { + let mut active_turn: Option = None; + let outcome = loop { tokio::select! { biased; - _ = shutdown.cancelled() => { - if let Some(ref mut turn) = active_turn - && turn.outcome == ExchangeOutcome::Completed - { - turn.outcome = ExchangeOutcome::ClientDisconnected; - } - break; - } - c_msg = client_rx.next() => { - match c_msg { - Some(Ok(msg)) => { - if let WsMessage::Text(ref txt) = msg { - if let Some(turn) = active_turn.take() { - let ex = RecordedExchange { - kind: ExchangeKind::WebSocketTurn, - fingerprint: turn.fp, - method: "WS".into(), - path: path_only.clone(), - protocol: Some(Protocol::OpenaiResponsesWs), - model: turn.model, - request_headers: redacted_headers.clone(), - request_body: turn.req_body, - status: 200, - outcome: turn.outcome, - response_headers: BTreeMap::new(), - chunks: turn.chunks, - }; - if let Err(err) = self.writer.append(ex).await { - tracing::warn!("ws proxy cassette write failed: {err}"); - } - } - let body: Value = serde_json::from_str(txt).unwrap_or(Value::Null); - let model = body.get("model").and_then(Value::as_str).unwrap_or("").to_string(); - let fp = compute_fingerprint(ExchangeKind::WebSocketTurn, "WS", &path_only, &model, &body); - active_turn = Some(WsTurnBuf { - fp, - model, - req_body: body, - last_tick: Instant::now(), - chunks: Vec::new(), - recorded_bytes: 0, - outcome: ExchangeOutcome::Completed, - }); - } - let is_close = matches!(msg, WsMessage::Close(_)); - if upstream_tx.send(msg).await.is_err() || is_close { - break; - } - } - _ => { - if let Some(ref mut turn) = active_turn - && turn.outcome == ExchangeOutcome::Completed { - turn.outcome = ExchangeOutcome::ClientDisconnected; - } - break; + _ = shutdown.cancelled() => break ExchangeOutcome::ClientDisconnected, + incoming = client_rx.next() => { + let Some(Ok(msg)) = incoming else { + break ExchangeOutcome::ClientDisconnected; + }; + if let WsMessage::Text(text) = &msg { + if let Some(turn) = active_turn.take() { + enqueue(track(turn, ExchangeOutcome::Truncated)).await?; } + let body: Value = serde_json::from_str(text).unwrap_or(Value::Null); + let model = body["model"].as_str().unwrap_or("").to_owned(); + let fingerprint = canonical_request_fingerprint(CanonicalRequest { + kind: ExchangeKind::WebSocketTurn, + method: "WS", + path_and_query: &canonical, + protocol: Some(Protocol::OpenaiResponsesWs), + model: &model, + body: &body, + headers, + scope_lane, + }); + active_turn = Some(WsRecording { + exchange: RecordedExchange { + kind: ExchangeKind::WebSocketTurn, + fingerprint, + fingerprint_version: FINGERPRINT_VERSION, + method: "WS".into(), + path: canonical.to_string(), + protocol: Some(Protocol::OpenaiResponsesWs), + scope_lane: scope_lane.map(|lane| LogicalLane(lane.into())), + model, + request_headers: redacted_headers.clone(), + request_body: body, + status: 200, + outcome: ExchangeOutcome::Completed, + response_headers: BTreeMap::new(), + chunks: Vec::new(), + }, + last_tick: Instant::now(), + recorded_bytes: 0, + }); + } + let is_close = matches!(msg, WsMessage::Close(_)); + let sent = upstream_tx.send(msg).await; + if is_close { + break ExchangeOutcome::ClientDisconnected; + } + if sent.is_err() { + break ExchangeOutcome::UpstreamError; } } - u_msg = upstream_rx.next() => { - match u_msg { - Some(Ok(msg)) => { - let mut is_terminal = false; - if let Some(ref mut turn) = active_turn { - match &msg { - WsMessage::Text(txt) => { - is_terminal = is_ws_terminal_frame(txt); - if turn.outcome != ExchangeOutcome::Truncated { - let now = Instant::now(); - let delay = now.saturating_duration_since(turn.last_tick).as_millis() as u64; - turn.last_tick = now; - if turn.recorded_bytes.saturating_add(txt.len()) <= max_record { - turn.recorded_bytes += txt.len(); - turn.chunks.push(TimedChunk { - delay_ms: delay, - is_binary: false, - data: txt.to_string(), - }); - } else { - turn.outcome = ExchangeOutcome::Truncated; - } - } - } - WsMessage::Binary(bin) - if turn.outcome != ExchangeOutcome::Truncated => - { - let now = Instant::now(); - let delay = now.saturating_duration_since(turn.last_tick).as_millis() as u64; - turn.last_tick = now; - if turn.recorded_bytes.saturating_add(bin.len()) <= max_record { - turn.recorded_bytes += bin.len(); - turn.chunks.push(TimedChunk::from_bytes(delay, bin)); - } else { - turn.outcome = ExchangeOutcome::Truncated; - } - } - _ => {} - } - } - let is_close = matches!(msg, WsMessage::Close(_)); - // Flush terminal turn BEFORE delivering the terminal frame to the client - // so immediate post-turn shutdown/replay always sees the persisted record. - if is_terminal - && let Some(turn) = active_turn.take() - { - let ex = RecordedExchange { - kind: ExchangeKind::WebSocketTurn, - fingerprint: turn.fp, - method: "WS".into(), - path: path_only.clone(), - protocol: Some(Protocol::OpenaiResponsesWs), - model: turn.model, - request_headers: redacted_headers.clone(), - request_body: turn.req_body, - status: 200, - outcome: turn.outcome, - response_headers: BTreeMap::new(), - chunks: turn.chunks, - }; - if let Err(err) = self.writer.append(ex).await { - tracing::warn!("ws proxy cassette write failed: {err}"); - } - } - if client_tx.send(msg).await.is_err() || is_close { - break; - } - } - _ => { - if let Some(ref mut turn) = active_turn - && turn.outcome == ExchangeOutcome::Completed { - turn.outcome = ExchangeOutcome::UpstreamError; - } - break; - } + incoming = upstream_rx.next() => { + let Some(Ok(msg)) = incoming else { + break ExchangeOutcome::UpstreamError; + }; + let terminal = active_turn.is_some() + && matches!(&msg, WsMessage::Text(text) if is_ws_terminal_frame(text)); + if let Some(turn) = &mut active_turn { + turn.record(&msg, max_record); + } + + let is_close = matches!(msg, WsMessage::Close(_)); + let recording = if terminal { + active_turn.take().map(|turn| track(turn, ExchangeOutcome::Completed)) + } else { + None + }; + let sent = client_tx.send(msg).await; + if let Some(job) = recording { + enqueue(job).await?; + } + if is_close { + break ExchangeOutcome::UpstreamError; + } + if sent.is_err() { + break ExchangeOutcome::ClientDisconnected; } } } - } + }; - if let Some(turn) = active_turn.take() - && !turn.chunks.is_empty() - { - let ex = RecordedExchange { - kind: ExchangeKind::WebSocketTurn, - fingerprint: turn.fp, - method: "WS".into(), - path: path_only, - protocol: Some(Protocol::OpenaiResponsesWs), - model: turn.model, - request_headers: redacted_headers, - request_body: turn.req_body, - status: 200, - outcome: turn.outcome, - response_headers: BTreeMap::new(), - chunks: turn.chunks, - }; - if let Err(err) = self.writer.append(ex).await { - tracing::warn!("ws proxy cassette write failed: {err}"); - } + if let Some(turn) = active_turn { + enqueue(track(turn, outcome)).await?; } Ok(()) } } +const SCOPED_CONTROL_ERROR: &str = "scoped requests cannot access local control endpoints"; + +fn provider_path_and_query(raw: &str) -> Result, String> { + let canonical = strip_scope_prefix(raw); + let (path, _) = canonical.split_once('?').unwrap_or((&canonical, "")); + if canonical != raw && is_local_control_path(path) { + return Err(SCOPED_CONTROL_ERROR.into()); + } + Ok(canonical) +} + +struct WsRecording { + exchange: RecordedExchange, + last_tick: Instant, + recorded_bytes: usize, +} + +impl WsRecording { + fn record(&mut self, message: &WsMessage, limit: usize) { + let len = match message { + WsMessage::Text(text) => text.len(), + WsMessage::Binary(bytes) => bytes.len(), + _ => return, + }; + if self.exchange.outcome == ExchangeOutcome::Truncated { + return; + } + if self.recorded_bytes.saturating_add(len) > limit { + self.exchange.outcome = ExchangeOutcome::Truncated; + return; + } + let now = Instant::now(); + let delay_ms = now.saturating_duration_since(self.last_tick).as_millis() as u64; + self.last_tick = now; + self.recorded_bytes += len; + self.exchange.chunks.push(match message { + WsMessage::Text(text) => TimedChunk { + delay_ms, + is_binary: false, + data: text.to_string(), + }, + WsMessage::Binary(bytes) => TimedChunk::from_binary(delay_ms, bytes), + _ => unreachable!("only data frames are recorded"), + }); + } + + fn finish(mut self, outcome: ExchangeOutcome) -> RecordedExchange { + if self.exchange.outcome != ExchangeOutcome::Truncated { + self.exchange.outcome = outcome; + } + self.exchange + } +} + fn is_ws_terminal_frame(txt: &str) -> bool { let Ok(val) = serde_json::from_str::(txt) else { return false; @@ -1148,3 +1507,395 @@ fn is_ws_terminal_frame(txt: &str) -> bool { ) ) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn fingerprint_follows_provider_path_query_semantics_and_logical_lane() { + let body = json!({"messages":[{"role":"user","content":"hello"}], "stream":true}); + let lane = LogicalLane("stable-lane".into()); + let fingerprint = |path, body: &Value, lane| { + compute_fingerprint_for_lane(ExchangeKind::Http, "POST", path, "model", body, lane) + }; + let first = fingerprint( + "/s/run1/a/v1/chat/completions?version=1", + &body, + Some(&lane), + ); + assert_eq!( + first, + fingerprint( + "/s/run2/b/v1/chat/completions?version=1", + &body, + Some(&lane) + ) + ); + assert_ne!( + first, + fingerprint("/v1/chat/completions?version=2", &body, Some(&lane)) + ); + assert_ne!( + first, + fingerprint("/v1/chat/completions?version=1", &body, None) + ); + for (option, value) in [ + ("stream", json!(false)), + ("tool_choice", json!("none")), + ("parallel_tool_calls", json!(false)), + ("reasoning", json!({"effort":"low"})), + ("include", json!(["reasoning.encrypted_content"])), + ] { + let mut changed = body.clone(); + changed[option] = value; + assert_ne!( + first, + fingerprint("/v1/chat/completions?version=1", &changed, Some(&lane)), + "{option}" + ); + } + } + + fn recording(fingerprint: &str, outcome: ExchangeOutcome) -> RecordedExchange { + RecordedExchange { + kind: ExchangeKind::Http, + fingerprint: fingerprint.into(), + fingerprint_version: FINGERPRINT_VERSION, + method: "POST".into(), + path: "/v1/responses".into(), + protocol: Some(Protocol::OpenaiResponsesHttp), + scope_lane: None, + model: "model".into(), + request_headers: BTreeMap::new(), + request_body: json!({"input":"fixture"}), + status: 200, + outcome, + response_headers: BTreeMap::new(), + chunks: vec![TimedChunk::from_bytes(0, b"prefix")], + } + } + + #[tokio::test] + async fn strict_replay_distinguishes_response_formats_and_provider_headers() { + let path = std::env::temp_dir().join(format!( + "maka-mock-ai-{}-{}.ndjson", + std::process::id(), + fastrand::u64(..), + )); + let upstream = crate::MockAiBuilder::new() + .custom_route(Arc::new(|_, path, headers, body| { + let body: Value = serde_json::from_slice(body).unwrap(); + let format = match path { + "/v1/chat/completions" => body["response_format"]["type"].as_str(), + "/v1/responses" => body["text"]["format"]["type"].as_str(), + "/v1/messages" => headers.get("anthropic-beta").map(String::as_str), + _ => return None, + }; + Some(crate::control::CustomResponse::text( + 200, + format.unwrap().to_string(), + )) + })) + .start() + .await + .unwrap(); + let recorder = crate::MockAiBuilder::new() + .proxy_record(ProxyRecordConfig::new(upstream.origin_url(), &path)) + .unwrap() + .start() + .await + .unwrap(); + let cases = [ + ( + "/chat/completions", + json!({"model":"model", "messages":[{"role":"user","content":"hi"}], + "response_format":{"type":"text"}}), + None, + "text", + ), + ( + "/chat/completions", + json!({"model":"model", "messages":[{"role":"user","content":"hi"}], + "response_format":{"type":"json_object"}}), + None, + "json_object", + ), + ( + "/responses", + json!({"model":"model", "input":"hi", "text":{"format":{"type":"text"}}}), + None, + "text", + ), + ( + "/responses", + json!({"model":"model", "input":"hi", "text":{"format":{"type":"json_object"}}}), + None, + "json_object", + ), + ( + "/messages", + json!({"model":"model", "messages":[{"role":"user","content":"hi"}], "max_tokens":8}), + Some("first-beta"), + "first-beta", + ), + ( + "/messages", + json!({"model":"model", "messages":[{"role":"user","content":"hi"}], "max_tokens":8}), + Some("second-beta"), + "second-beta", + ), + ]; + let client = reqwest::Client::new(); + let send = |base: String, (path, body, beta, _): &(&str, Value, Option<&str>, &str)| { + let mut request = client + .post(format!("{base}{path}?variant=1")) + .header(SCOPE_LANE_HEADER, "fixture-lane") + .header("content-type", "application/json") + .body(body.to_string()); + if let Some(beta) = beta { + request = request.header("anthropic-beta", *beta); + } + request + }; + for case in &cases { + let response = send(recorder.base_url(), case).send().await.unwrap(); + assert_eq!(response.status(), 200); + assert_eq!(response.text().await.unwrap(), case.3); + } + recorder.shutdown().await; + upstream.shutdown().await; + + let exchanges = load_ndjson(&path).unwrap(); + assert_eq!(exchanges.len(), cases.len()); + assert!(exchanges.iter().all(|exchange| { + exchange.fingerprint_version == 2 + && exchange + .scope_lane + .as_ref() + .is_some_and(|lane| lane.0 == "fixture-lane") + })); + let replay = crate::MockAiBuilder::new() + .replay( + ReplayConfig::new(&path) + .with_match_mode(ReplayMatchMode::Fingerprint) + .with_strict_replay(), + ) + .unwrap() + .start() + .await + .unwrap(); + std::fs::remove_file(path).unwrap(); + for case in cases.iter().rev() { + let response = send(replay.base_url(), case).send().await.unwrap(); + let status = response.status(); + let body = response.text().await.unwrap(); + assert_eq!(status, 200, "{body}"); + assert_eq!(body, case.3); + } + replay.shutdown().await; + } + + #[test] + fn replay_rebuilds_legacy_fingerprints_from_captured_requests() { + let path = std::env::temp_dir().join(format!( + "maka-mock-ai-{}-{}.ndjson", + std::process::id(), + fastrand::u64(..), + )); + let mut text = json!({ + "kind":"http", "fingerprint":"444b7668ab871a1b", + "method":"POST", "path":"/v1/responses", "model":"model", + "requestHeaders":{}, + "requestBody":{"model":"model", "input":"fixture", "text":{"format":{"type":"text"}}}, + "status":200, "chunks":[{"delayMs":0, "data":"plain text"}] + }); + let plain_body = text["requestBody"].clone(); + let mut object = text.clone(); + object["fingerprintVersion"] = json!(1); + object["requestBody"]["text"]["format"]["type"] = json!("json_object"); + object["chunks"][0]["data"] = json!("JSON object"); + std::fs::write(&path, format!("{text}\n{object}")).unwrap(); + let config = ReplayConfig::new(&path) + .with_match_mode(ReplayMatchMode::Fingerprint) + .with_strict_replay(); + let replay = CassetteReplayer::load(config.clone()).unwrap(); + let fingerprint = + |body| compute_fingerprint(ExchangeKind::Http, "POST", "/v1/responses", "model", body); + for (body, expected) in [ + (&object["requestBody"], "JSON object"), + (&plain_body, "plain text"), + ] { + let exchange = replay.try_next_http(&fingerprint(body)).unwrap(); + assert_eq!(exchange.chunks[0].data, expected); + } + + for legacy_key in [ + "740f6f69133b0227", // The recorder stripped a lane that it hashed. + "d100b0c6244cef32", // The earliest recorder always discarded query. + ] { + text["fingerprint"] = json!(legacy_key); + std::fs::write(&path, text.to_string()).unwrap(); + let error = CassetteReplayer::load(config.clone()).err().unwrap(); + assert!(error.contains("cassette incompatible at line 1"), "{error}"); + assert!(error.contains("cannot be reconstructed"), "{error}"); + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn fingerprint_and_strict_load_reject_incomplete_legacy_requests() { + let path = std::env::temp_dir().join(format!( + "maka-mock-ai-{}-{}.ndjson", + std::process::id(), + fastrand::u64(..), + )); + let mut legacy = + serde_json::to_value(recording("d100b0c6244cef32", ExchangeOutcome::Completed)) + .unwrap(); + legacy["fingerprintVersion"] = json!(0); + for missing in ["requestHeaders", "requestBody"] { + let mut incomplete = legacy.clone(); + incomplete.as_object_mut().unwrap().remove(missing); + std::fs::write(&path, incomplete.to_string()).unwrap(); + for config in [ + ReplayConfig::new(&path).with_match_mode(ReplayMatchMode::Fingerprint), + ReplayConfig::new(&path).with_strict_replay(), + ] { + let error = CassetteReplayer::load(config).err().unwrap(); + assert!(error.contains("cassette incompatible at line 1"), "{error}"); + assert!(error.contains(missing), "{error}"); + } + let sequential = CassetteReplayer::load(ReplayConfig::new(&path)).unwrap(); + let exchange = sequential.try_next_http("anything").unwrap(); + assert_eq!(exchange.chunks[0].data, "prefix"); + } + std::fs::remove_file(path).unwrap(); + } + + #[test] + fn strict_replay_never_falls_back_wraps_or_accepts_truncation() { + let path = std::env::temp_dir().join(format!( + "maka-mock-ai-{}-{}.ndjson", + std::process::id(), + fastrand::u64(..), + )); + let first = "a".repeat(64); + let second = "b".repeat(64); + let lines = [ + recording(&first, ExchangeOutcome::Completed), + recording(&second, ExchangeOutcome::Truncated), + ] + .map(|exchange| serde_json::to_string(&exchange).unwrap()) + .join("\n"); + std::fs::write(&path, lines).unwrap(); + let replay = CassetteReplayer::load( + ReplayConfig::new(&path) + .with_match_mode(ReplayMatchMode::Fingerprint) + .with_strict_replay(), + ); + std::fs::remove_file(path).unwrap(); + let replay = replay.unwrap(); + + assert_eq!( + replay.try_next_http("missing").unwrap_err(), + ReplayError::Miss + ); + assert_eq!(replay.try_next_http(&first).unwrap().fingerprint, first); + assert_eq!( + replay.try_next_http(&first).unwrap_err(), + ReplayError::Exhausted + ); + assert_eq!( + replay.try_next_http(&second).unwrap_err(), + ReplayError::Truncated + ); + } + + #[tokio::test] + async fn scoped_http_preserves_provider_query_and_headers() { + let upstream = crate::MockAiBuilder::new().start().await.unwrap(); + let path = std::env::temp_dir().join(format!( + "maka-mock-ai-{}-{}.ndjson", + std::process::id(), + fastrand::u64(..), + )); + let proxy = + ProxyRecorder::new(ProxyRecordConfig::new(upstream.origin_url(), &path)).unwrap(); + let headers = BTreeMap::from([ + ("x-maka-bench-session".into(), "fixture-session".into()), + ("x-maka-session-id".into(), "fixture-session".into()), + ("openai-beta".into(), "responses=experimental".into()), + ]); + let mut response = proxy + .forward_http( + "GET", + "/s/run/session/v1/models?client_version=1", + None, + &headers, + Bytes::new(), + CancellationToken::new(), + ) + .await + .unwrap(); + assert_eq!(response.status, 200); + let mut bytes = Vec::new(); + while let Some(chunk) = response.rx.recv().await { + bytes.extend(chunk.unwrap()); + } + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["models"][0]["slug"], "mock-model"); + let recorded = upstream.control_plane_requests(); + assert_eq!(recorded[0].path, "/v1/models"); + assert_eq!(recorded[0].query.as_deref(), Some("client_version=1")); + assert_eq!(recorded[0].headers["openai-beta"], "responses=experimental"); + assert!(!recorded[0].headers.contains_key("x-maka-bench-session")); + assert!(!recorded[0].headers.contains_key("x-maka-session-id")); + + for path in ["/s/run/session/metrics", "/s/run/session/v1/%2e%2e/metrics"] { + let result = proxy + .forward_http( + "GET", + path, + None, + &headers, + Bytes::new(), + CancellationToken::new(), + ) + .await; + assert_eq!(result.err().as_deref(), Some(SCOPED_CONTROL_ERROR)); + } + + proxy.flush().await; + let recorded = load_ndjson(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + assert_eq!(recorded[0].path, "/v1/models?client_version=1"); + upstream.shutdown().await; + } + + #[tokio::test] + async fn http_replay_emits_recorded_prefix_and_then_clean_eof_or_body_error() { + for (outcome, terminal_error) in [ + (ExchangeOutcome::Completed, None), + (ExchangeOutcome::Truncated, Some(ReplayBodyError::Truncated)), + ( + ExchangeOutcome::UpstreamError, + Some(ReplayBodyError::UpstreamError), + ), + ( + ExchangeOutcome::ClientDisconnected, + Some(ReplayBodyError::ClientDisconnected), + ), + ] { + let config = ReplayConfig::new("unused").with_speed(0.0); + let replay = recording("http", outcome).replay_http_body(config); + let mut replay = std::pin::pin!(replay); + assert_eq!(replay.next().await, Some(Ok(Bytes::from_static(b"prefix")))); + assert_eq!(replay.next().await, terminal_error.map(Err)); + if terminal_error.is_some() { + assert_eq!(replay.next().await, None); + } + } + } +} diff --git a/tools/mock-ai/src/ratelimit.rs b/tools/mock-ai/src/ratelimit.rs index 6b3c00353f0..c5e22d553cf 100644 --- a/tools/mock-ai/src/ratelimit.rs +++ b/tools/mock-ai/src/ratelimit.rs @@ -18,10 +18,10 @@ */ use serde::{Deserialize, Serialize}; -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, RwLock}; -use std::time::Instant; +use std::time::{Duration, Instant}; /// Isolation scope for stateful rate-limit token buckets and concurrency caps. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -114,12 +114,11 @@ impl RateLimitHeaders { } } -/// RAII guard that releases the concurrency slot and debits post-turn output tokens on drop. +/// RAII guard for a concurrency slot and its output-token accounting. pub struct RateLimitLease { limiter: Arc, - bucket_key: String, + bucket_key: Arc, generation: u64, - active_slot_held: bool, output_tokens_debited: bool, } @@ -139,10 +138,7 @@ impl RateLimitLease { impl Drop for RateLimitLease { fn drop(&mut self) { - if self.active_slot_held { - self.active_slot_held = false; - self.limiter.release_slot(&self.bucket_key, self.generation); - } + self.limiter.release_slot(&self.bucket_key, self.generation); } } @@ -234,7 +230,7 @@ struct BucketState { itpm: Option, otpm: Option, in_flight: usize, - last_seen: Instant, + evict_at: Option, } impl BucketState { @@ -244,7 +240,7 @@ impl BucketState { itpm: cfg.itpm.map(|v| TokenBucket::new(v, None, now)), otpm: cfg.otpm.map(|v| TokenBucket::new(v, None, now)), in_flight: 0, - last_seen: now, + evict_at: None, } } @@ -291,12 +287,48 @@ impl BucketState { } } +#[derive(Default)] +struct BucketTable { + entries: HashMap, BucketState>, + // One deadline per idle bucket. A bucket is evictable only after all its quotas refill. + idle: BTreeSet<(Instant, Arc)>, +} + +impl BucketTable { + fn evict_refilled(&mut self, now: Instant) -> bool { + if self.idle.first().is_none_or(|(at, _)| *at > now) { + return false; + } + let (_, key) = self.idle.pop_first().expect("eligible deadline exists"); + self.entries.remove(&key); + true + } + + fn index_idle(&mut self, key: Arc, now: Instant) { + let state = self.entries.get_mut(&key).expect("indexed bucket exists"); + let mut ready_at = now; + for bucket in [&state.rpm, &state.itpm, &state.otpm].into_iter().flatten() { + let seconds = (bucket.capacity - bucket.tokens) / bucket.rate_per_sec; + let Some(at) = Duration::try_from_secs_f64(seconds) + .ok() + .and_then(|delay| delay.checked_add(Duration::from_nanos(u64::from(seconds > 0.0)))) + .and_then(|delay| bucket.last_refill.checked_add(delay)) + else { + return; + }; + ready_at = ready_at.max(at); + } + state.evict_at = Some(ready_at); + self.idle.insert((ready_at, key)); + } +} + /// Stateful, runtime-reconfigurable token bucket and concurrency rate limiter. pub struct RateLimiter { active: AtomicBool, generation: AtomicU64, config: RwLock, - buckets: Mutex>, + buckets: Mutex, } impl RateLimiter { @@ -306,7 +338,7 @@ impl RateLimiter { active, generation: AtomicU64::new(0), config: RwLock::new(config), - buckets: Mutex::new(HashMap::new()), + buckets: Mutex::new(BucketTable::default()), }) } @@ -318,14 +350,18 @@ impl RateLimiter { } pub fn update_config(&self, config: RateLimitConfig) { - self.active.store(config.is_active(), Ordering::Release); - *self.config.write().unwrap_or_else(|e| e.into_inner()) = config; + let active = config.is_active(); + let mut guard = self.config.write().unwrap_or_else(|e| e.into_inner()); + *guard = config; + self.active.store(active, Ordering::Release); } pub fn reset(&self) { let mut guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - self.generation.fetch_add(1, Ordering::AcqRel); - guard.clear(); + let old = std::mem::take(&mut *guard); + self.generation.fetch_add(1, Ordering::Release); + drop(guard); + drop(old); } /// Evaluate admission for a single model turn. Optionally uses a phase-level override config. @@ -354,51 +390,33 @@ impl RateLimiter { } let key = bucket_key(cfg.scope, api_key, model); - let now = Instant::now(); let mut guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - - // Bounded eviction when distinct keys exceed max_buckets: only evict idle buckets whose - // token buckets have refilled to full capacity (prevents resetting active quota deficits). - let max_buckets = cfg.max_buckets.max(1); - if !guard.contains_key(&key) && guard.len() >= max_buckets { - let mut evict_key: Option = None; - let mut oldest = now; - for (k, s) in guard.iter_mut() { - if s.in_flight != 0 { - continue; - } - if let Some(ref mut b) = s.rpm { - b.refill(now); - } - if let Some(ref mut b) = s.itpm { - b.refill(now); - } - if let Some(ref mut b) = s.otpm { - b.refill(now); - } - let full = s.rpm.as_ref().is_none_or(|b| b.tokens >= b.capacity) - && s.itpm.as_ref().is_none_or(|b| b.tokens >= b.capacity) - && s.otpm.as_ref().is_none_or(|b| b.tokens >= b.capacity); - if full && (evict_key.is_none() || s.last_seen < oldest) { - oldest = s.last_seen; - evict_key = Some(k.clone()); - } - } - if let Some(ek) = evict_key { - guard.remove(&ek); - } else { + let now = Instant::now(); + let key = if let Some((key, _)) = guard.entries.get_key_value(key.as_str()) { + key.clone() + } else { + let max_buckets = cfg.max_buckets.max(1); + if guard.entries.len() >= max_buckets + && (!guard.evict_refilled(now) || guard.entries.len() >= max_buckets) + { return RateLimitDecision::Rejected { retry_after_ms: 250, reason: "rate_limit_table_full", headers: RateLimitHeaders::default(), }; } - } + let key: Arc = key.into(); + guard + .entries + .insert(key.clone(), BucketState::new(&cfg, now)); + key + }; - let state = guard - .entry(key.clone()) - .or_insert_with(|| BucketState::new(&cfg, now)); - state.last_seen = now; + let BucketTable { entries, idle } = &mut *guard; + let state = entries.get_mut(&key).expect("admitted bucket exists"); + if let Some(at) = state.evict_at.take() { + idle.remove(&(at, key.clone())); + } state.sync_config(&cfg, now); // 1. Check concurrency cap first. @@ -406,6 +424,9 @@ impl RateLimiter { && state.in_flight >= max_conc { let headers = state.headers(&cfg); + if state.in_flight == 0 { + guard.index_idle(key, now); + } return RateLimitDecision::Rejected { retry_after_ms: 250, reason: "max_concurrent_requests", @@ -439,6 +460,9 @@ impl RateLimiter { if let Some((retry_after_ms, reason)) = wait_ms { let headers = state.headers(&cfg); + if state.in_flight == 0 { + guard.index_idle(key, now); + } return RateLimitDecision::Rejected { retry_after_ms, reason, @@ -463,34 +487,43 @@ impl RateLimiter { limiter: self.clone(), bucket_key: key, generation, - active_slot_held: true, output_tokens_debited: false, }), } } - fn release_slot(&self, key: &str, generation: u64) { - let mut guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - if self.generation.load(Ordering::Acquire) != generation { + fn release_slot(&self, key: &Arc, generation: u64) { + let Some(mut guard) = self.buckets_for_generation(generation) else { return; - } - if let Some(state) = guard.get_mut(key) { - state.in_flight = state.in_flight.saturating_sub(1); + }; + let state = guard.entries.get_mut(key).expect("leased bucket exists"); + state.in_flight -= 1; + if state.in_flight == 0 { + guard.index_idle(key.clone(), Instant::now()); } } - fn debit_output(&self, key: &str, generation: u64, output_tokens: u64) { - let mut guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); - if self.generation.load(Ordering::Acquire) != generation { + fn debit_output(&self, key: &Arc, generation: u64, output_tokens: u64) { + let Some(mut guard) = self.buckets_for_generation(generation) else { return; - } - if let Some(state) = guard.get_mut(key) - && let Some(ref mut otpm) = state.otpm - { + }; + let state = guard.entries.get_mut(key).expect("leased bucket exists"); + if let Some(otpm) = &mut state.otpm { otpm.refill(Instant::now()); otpm.consume(output_tokens as f64); } } + + fn buckets_for_generation( + &self, + generation: u64, + ) -> Option> { + if self.generation.load(Ordering::Acquire) != generation { + return None; + } + let guard = self.buckets.lock().unwrap_or_else(|e| e.into_inner()); + (self.generation.load(Ordering::Relaxed) == generation).then_some(guard) + } } fn bucket_key(scope: RateLimitScope, api_key: &str, model: &str) -> String { @@ -501,3 +534,75 @@ fn bucket_key(scope: RateLimitScope, api_key: &str, model: &str) -> String { RateLimitScope::PerApiKeyAndModel => format!("key:{api_key}|model:{model}"), } } + +#[cfg(test)] +mod tests { + use super::*; + + fn acquire(limiter: &Arc, model: &str) -> RateLimitLease { + match limiter.check_and_acquire("", model, 1, None) { + RateLimitDecision::Allowed { + lease: Some(lease), .. + } => lease, + _ => panic!("expected a lease for {model}"), + } + } + + #[test] + fn full_table_can_reuse_idle_refilled_buckets_but_keeps_active_slots_and_debt() { + let limiter = RateLimiter::new(RateLimitConfig { + enabled: true, + scope: RateLimitScope::PerModel, + max_concurrent: Some(1), + max_buckets: 1, + ..Default::default() + }); + let first = acquire(&limiter, "first"); + assert!(matches!( + limiter.check_and_acquire("", "second", 1, None), + RateLimitDecision::Rejected { + reason: "rate_limit_table_full", + .. + } + )); + drop(first); + + limiter.update_config(RateLimitConfig { + rpm: Some(1), + ..limiter.config() + }); + drop(acquire(&limiter, "second")); + assert!(matches!( + limiter.check_and_acquire("", "third", 1, None), + RateLimitDecision::Rejected { + reason: "rate_limit_table_full", + .. + } + )); + } + + #[test] + fn stale_lease_neither_releases_new_slot_nor_debits_new_quota() { + let limiter = RateLimiter::new(RateLimitConfig { + enabled: true, + max_concurrent: Some(1), + otpm: Some(1), + max_buckets: 1, + ..Default::default() + }); + let mut old = acquire(&limiter, "model"); + limiter.reset(); + let current = acquire(&limiter, "model"); + old.debit_output_tokens(10); + drop(old); + assert!(matches!( + limiter.check_and_acquire("", "model", 1, None), + RateLimitDecision::Rejected { + reason: "max_concurrent_requests", + .. + } + )); + drop(current); + drop(acquire(&limiter, "model")); + } +} diff --git a/tools/mock-ai/src/routing.rs b/tools/mock-ai/src/routing.rs new file mode 100644 index 00000000000..495018bd0ef --- /dev/null +++ b/tools/mock-ai/src/routing.rs @@ -0,0 +1,1369 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! Scoped routing, session identity resolution, request classification, and response lineage. + +use crate::protocol::{NormalizedRequest, NormalizedRole}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{BTreeMap, HashMap, hash_map::Entry}; + +macro_rules! id_types { + ($($name:ident($inner:ty)),+ $(,)?) => {$( + #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] + #[serde(transparent)] + pub struct $name(pub $inner); + + impl std::fmt::Display for $name { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } + } + )+}; +} + +id_types!( + RunId(String), + SessionId(String), + ResponseId(String), + StepId(String), + CallId(String), + Revision(u64), + AttemptId(u64), + LogicalLane(String), + PrincipalId(String), +); + +impl std::borrow::Borrow for SessionId { + fn borrow(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct RouteScope { + pub run_id: RunId, + pub session_id: SessionId, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EndpointKind { + ScopedForbidden, + Metrics, + Admin, + Models, + ModelById(String), + ChatCompletions, + AnthropicMessages, + AnthropicCountTokens, + ResponsesCreate, + ResponsesWs, + ResponsesCompact, + GetResponse(String), + DeleteResponse(String), + RelayTokenUsage, + V1Usage, + ExtraGet(String), + Unknown, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParsedRoute<'a> { + pub scope: Option, + pub canonical_path: &'a str, + pub raw_path: &'a str, + pub query: Option<&'a str>, + pub endpoint: EndpointKind, +} + +impl ParsedRoute<'_> { + pub fn canonical_path_and_query(&self) -> std::borrow::Cow<'_, str> { + match self.query { + Some(query) => format!("{}?{query}", self.canonical_path).into(), + None => self.canonical_path.into(), + } + } +} + +fn scoped_parts(path: &str) -> Option<(&str, &str, &str)> { + let (run, tail) = path.strip_prefix("/s/")?.split_once('/')?; + let session_end = tail.find('/').unwrap_or(tail.len()); + let (session, canonical) = tail.split_at(session_end); + (!run.is_empty() && !session.is_empty()).then_some((run, session, canonical)) +} + +/// Strip the runner prefix from a path or path-and-query, preserving the provider suffix verbatim. +pub fn strip_scope_prefix(path_and_query: &str) -> std::borrow::Cow<'_, str> { + let (path, query) = path_and_query + .split_once('?') + .map_or((path_and_query, None), |(path, query)| (path, Some(query))); + let Some((_, _, canonical)) = scoped_parts(path) else { + return path_and_query.into(); + }; + if canonical.is_empty() { + return match query { + Some(query) => format!("/?{query}").into(), + None => "/".into(), + }; + } + path_and_query[path.len() - canonical.len()..].into() +} + +fn is_admin_path(path: &str) -> bool { + path == "/admin" || path.starts_with("/admin/") +} + +pub(crate) fn is_local_control_path(path: &str) -> bool { + is_admin_path(path) || path == "/metrics" +} + +pub fn parse_route<'a>( + method: &str, + path: &'a str, + query: Option<&'a str>, + is_ws_upgrade: bool, + extra_get_routes: &BTreeMap, +) -> ParsedRoute<'a> { + use EndpointKind::*; + + let (scope, canonical_path) = match scoped_parts(path) { + Some((run, session, canonical)) => ( + Some(RouteScope { + run_id: RunId(run.into()), + session_id: SessionId(session.into()), + }), + if canonical.is_empty() { "/" } else { canonical }, + ), + None => (None, path), + }; + let endpoint = if scope.is_some() && is_local_control_path(canonical_path) { + ScopedForbidden + } else if is_admin_path(canonical_path) { + Admin + } else { + let provider_path = canonical_path + .strip_prefix("/v1/") + .unwrap_or_else(|| canonical_path.strip_prefix('/').unwrap_or(canonical_path)); + let mut segments = provider_path.split('/'); + match ( + method, + is_ws_upgrade, + segments.next(), + segments.next(), + segments.next(), + ) { + ("GET", false, ..) if canonical_path == "/metrics" => Metrics, + ("GET", false, ..) if canonical_path == "/v1/usage" => V1Usage, + ("GET", false, ..) + if matches!(canonical_path, "/api/usage/token" | "/api/usage/token/") => + { + RelayTokenUsage + } + ("GET", false, Some("models"), None, None) => Models, + ("GET", false, Some("models"), Some(id), None) if !id.is_empty() => { + ModelById(id.into()) + } + ("POST", false, Some("chat"), Some("completions"), None) => ChatCompletions, + ("POST", false, Some("messages"), None, None) => AnthropicMessages, + ("POST", false, Some("messages"), Some("count_tokens"), None) => AnthropicCountTokens, + ("POST", false, Some("responses"), None, None) => ResponsesCreate, + ("GET", true, Some("responses"), None, None) => ResponsesWs, + ("POST", false, Some("responses"), Some("compact"), None) => ResponsesCompact, + (_, _, Some("responses"), Some("compact"), None) => Unknown, + ("GET", false, Some("responses"), Some(id), None) if !id.is_empty() => { + GetResponse(id.into()) + } + ("DELETE", false, Some("responses"), Some(id), None) if !id.is_empty() => { + DeleteResponse(id.into()) + } + ("GET", false, ..) if extra_get_routes.contains_key(canonical_path) => { + ExtraGet(canonical_path.into()) + } + _ => Unknown, + } + }; + ParsedRoute { + scope, + canonical_path, + raw_path: path, + query, + endpoint, + } +} + +const SESSION_HEADERS: [&str; 2] = ["x-maka-bench-session", "x-maka-session-id"]; + +#[cfg(feature = "proxy")] +pub(crate) fn is_runner_routing_header(name: &str) -> bool { + name.starts_with("x-maka-bench-") || name == "x-maka-session-id" +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CredentialBinding { + Shared(PrincipalId), + UniqueTestCredential(PrincipalId), +} + +impl CredentialBinding { + fn principal(&self) -> &PrincipalId { + match self { + Self::Shared(id) | Self::UniqueTestCredential(id) => id, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ClientSessionSource { + Header(String), + MetadataField(String), +} + +impl ClientSessionSource { + fn value<'a>(&self, headers: &'a BTreeMap, body: &'a Value) -> Option<&'a str> { + match self { + Self::Header(name) => headers.get(name).map(String::as_str), + Self::MetadataField(name) => body.get("metadata")?.get(name)?.as_str(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClientSessionAlias { + pub source: ClientSessionSource, + pub value: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionRegistration { + #[serde(alias = "runId", alias = "run")] + pub run_id: RunId, + #[serde(alias = "sessionId", alias = "session")] + pub session_id: SessionId, + pub harness: String, + #[serde(alias = "logicalLane", alias = "lane")] + pub logical_lane: LogicalLane, + pub scenario: String, + #[serde(default, alias = "launchMode")] + pub launch_mode: String, + #[serde(alias = "credentialBinding", alias = "credential")] + pub credential_binding: Option, + #[serde(default, alias = "clientSessionAliases")] + pub client_session_aliases: Vec, + #[serde(default = "active_registration")] + pub active: bool, +} + +fn active_registration() -> bool { + true +} + +impl SessionRegistration { + fn principal(&self) -> Option<&PrincipalId> { + self.credential_binding + .as_ref() + .map(CredentialBinding::principal) + } + + fn accepts(&self, principal: Option<&PrincipalId>) -> bool { + self.principal() + .is_none_or(|bound| Some(bound) == principal) + } +} + +type AliasIndex = BTreeMap>; + +#[derive(Debug)] +enum PrincipalSessions { + Shared(usize), + Unique(SessionId), +} + +#[derive(Debug, Default)] +pub struct SessionRegistry { + sessions: HashMap, + credentials: HashMap, + aliases: HashMap, AliasIndex>, + connections: HashMap, +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum RegistrationError { + #[error("session {0} is already registered")] + DuplicateSession(SessionId), + #[error("invalid session registration")] + InvalidRegistration, + #[error("test credential is already bound")] + DuplicateCredential, + #[error("stable client session alias is already bound")] + DuplicateAlias, + #[error("invalid stable client session alias")] + InvalidAlias, +} + +impl SessionRegistry { + pub fn register(&mut self, mut record: SessionRegistration) -> Result<(), RegistrationError> { + use RegistrationError::*; + + if [&record.run_id.0, &record.session_id.0] + .into_iter() + .any(|id| id.is_empty() || id.contains(['/', '?', '#'])) + || !record.active + { + return Err(InvalidRegistration); + } + if self.sessions.contains_key(&record.session_id) { + return Err(DuplicateSession(record.session_id)); + } + if let Some(binding) = &record.credential_binding + && let Some(existing) = self.credentials.get(binding.principal()) + && !matches!( + (binding, existing), + (CredentialBinding::Shared(_), PrincipalSessions::Shared(_)) + ) + { + return Err(DuplicateCredential); + } + + for alias in &mut record.client_session_aliases { + let source_is_valid = match &mut alias.source { + ClientSessionSource::Header(name) => { + name.make_ascii_lowercase(); + !name.is_empty() + && !matches!( + name.as_str(), + "authorization" + | "x-api-key" + | "api-key" + | "x-codex-turn-state" + | "prompt_cache_key" + ) + && !name.starts_with("x-maka-bench-") + && !SESSION_HEADERS.contains(&name.as_str()) + } + ClientSessionSource::MetadataField(name) => !matches!( + name.as_str(), + "" | "prompt_cache_key" | "x-codex-turn-state" + ), + }; + if !source_is_valid || alias.value.is_empty() { + return Err(InvalidAlias); + } + } + let principal = record.principal().cloned(); + let aliases = self.aliases.get(&principal); + for alias in &record.client_session_aliases { + if aliases + .and_then(|index| index.get(&alias.source)) + .is_some_and(|values| values.contains_key(&alias.value)) + { + return Err(DuplicateAlias); + } + } + + match &record.credential_binding { + Some(CredentialBinding::UniqueTestCredential(principal)) => { + self.credentials.insert( + principal.clone(), + PrincipalSessions::Unique(record.session_id.clone()), + ); + } + Some(CredentialBinding::Shared(principal)) => { + let PrincipalSessions::Shared(count) = self + .credentials + .entry(principal.clone()) + .or_insert(PrincipalSessions::Shared(0)) + else { + unreachable!("conflicting credentials were rejected"); + }; + *count += 1; + } + None => {} + } + for alias in &record.client_session_aliases { + self.aliases + .entry(principal.clone()) + .or_default() + .entry(alias.source.clone()) + .or_default() + .insert(alias.value.clone(), record.session_id.clone()); + } + self.sessions.insert(record.session_id.clone(), record); + Ok(()) + } + + pub fn get(&self, session: &SessionId) -> Option<&SessionRegistration> { + self.sessions.get(session) + } + + pub fn finalize(&mut self, session: &SessionId) -> bool { + let Some(record) = self + .sessions + .get_mut(session) + .filter(|record| record.active) + else { + return false; + }; + record.active = false; + if let Some(principal) = record.principal() + && let Entry::Occupied(mut entry) = self.credentials.entry(principal.clone()) + { + match entry.get_mut() { + PrincipalSessions::Shared(count) if *count > 1 => *count -= 1, + _ => { + entry.remove(); + } + } + } + let principal = record.principal().cloned(); + if let Some(index) = self.aliases.get_mut(&principal) { + for alias in &record.client_session_aliases { + if let std::collections::btree_map::Entry::Occupied(mut source) = + index.entry(alias.source.clone()) + { + source.get_mut().remove(&alias.value); + if source.get().is_empty() { + source.remove(); + } + } + } + if index.is_empty() { + self.aliases.remove(&principal); + } + } + true + } + + pub(crate) fn remove_session(&mut self, session: &SessionId) { + self.finalize(session); + self.sessions.remove(session); + self.connections.retain(|_, owner| owner != session); + } + + pub fn bind_connection( + &mut self, + connection: u64, + session: &SessionId, + ) -> Result<(), IdentityError> { + if !self.get(session).is_some_and(|record| record.active) { + return Err(IdentityError::Unroutable); + } + match self.connections.entry(connection) { + Entry::Vacant(entry) => { + entry.insert(session.clone()); + Ok(()) + } + Entry::Occupied(entry) if entry.get() == session => Ok(()), + Entry::Occupied(entry) => Err(IdentityError::Conflict { + preferred: session.clone(), + conflicting: entry.get().clone(), + evidence: IdentitySource::WebSocket, + }), + } + } + + pub fn unbind_connection(&mut self, connection: u64) { + self.connections.remove(&connection); + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IdentitySource { + PathScope, + RunnerHeader, + TestCredential, + ClientAlias, + PreviousResponse, + WebSocket, +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum IdentityError { + #[error("request has no registered session identity")] + Unroutable, + #[error("unknown benchmark scope {run_id}/{session_id}")] + UnknownScope { + run_id: RunId, + session_id: SessionId, + }, + #[error("unregistered session in {0}")] + UnknownSessionHeader(&'static str), + #[error("session {0} is finalized")] + InactiveSession(SessionId), + #[error("authenticated principal does not own session {0}")] + PrincipalMismatch(SessionId), + #[error("session {preferred} conflicts with {conflicting} from {evidence:?}")] + Conflict { + preferred: SessionId, + conflicting: SessionId, + evidence: IdentitySource, + }, +} + +pub struct IdentityRequest<'a> { + pub scope: Option<&'a RouteScope>, + /// The authenticated fixture principal, determined by the caller before resolving identity. + pub principal: Option<&'a PrincipalId>, + pub headers: &'a BTreeMap, + pub body: &'a Value, + pub previous_response_id: Option<&'a ResponseId>, + pub connection_id: Option, +} + +pub struct SessionIdentityResolver<'a> { + registry: &'a SessionRegistry, + lineage: &'a LineageStore, +} + +impl<'a> SessionIdentityResolver<'a> { + pub fn new(registry: &'a SessionRegistry, lineage: &'a LineageStore) -> Self { + Self { registry, lineage } + } + + pub fn resolve( + &self, + request: IdentityRequest<'_>, + ) -> Result<&'a SessionRegistration, IdentityError> { + let mut preferred: Option<&SessionRegistration> = None; + let mut consider = |candidate: &'a SessionRegistration, evidence| { + if let Some(first) = preferred + && first.session_id != candidate.session_id + { + return Err(IdentityError::Conflict { + preferred: first.session_id.clone(), + conflicting: candidate.session_id.clone(), + evidence, + }); + } + if !candidate.active { + return Err(IdentityError::InactiveSession(candidate.session_id.clone())); + } + if !candidate.accepts(request.principal) { + return Err(IdentityError::PrincipalMismatch( + candidate.session_id.clone(), + )); + } + preferred = Some(candidate); + Ok(()) + }; + + if let Some(scope) = request.scope { + let record = self + .registry + .get(&scope.session_id) + .filter(|record| record.run_id == scope.run_id) + .ok_or_else(|| IdentityError::UnknownScope { + run_id: scope.run_id.clone(), + session_id: scope.session_id.clone(), + })?; + consider(record, IdentitySource::PathScope)?; + } + for name in SESSION_HEADERS { + if let Some(value) = request.headers.get(name) { + let record = self + .registry + .sessions + .get(value.as_str()) + .ok_or(IdentityError::UnknownSessionHeader(name))?; + consider(record, IdentitySource::RunnerHeader)?; + } + } + if let Some(PrincipalSessions::Unique(session)) = request + .principal + .and_then(|id| self.registry.credentials.get(id)) + { + consider( + &self.registry.sessions[session], + IdentitySource::TestCredential, + )?; + } + if let Some(aliases) = self.registry.aliases.get(&request.principal.cloned()) { + for (source, values) in aliases { + if let Some(session) = source + .value(request.headers, request.body) + .and_then(|value| values.get(value)) + { + consider( + &self.registry.sessions[session], + IdentitySource::ClientAlias, + )?; + } + } + } + if let Some(record) = request + .previous_response_id + .and_then(|id| self.lineage.owner(id)) + .and_then(|owner| self.registry.get(owner)) + .filter(|record| record.active && record.principal() == request.principal) + { + consider(record, IdentitySource::PreviousResponse)?; + } + if let Some(session) = request + .connection_id + .and_then(|id| self.registry.connections.get(&id)) + { + consider(&self.registry.sessions[session], IdentitySource::WebSocket)?; + } + preferred.ok_or(IdentityError::Unroutable) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RequestUse { + Main, + Side(SideKind), + Compact(CompactKind), + Control, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SideKind { + Title, + Probe, + SummaryAux, + Custom(String), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CompactKind { + ResponsesEndpoint, + ResponsesTrigger, + AnthropicNative, + ClientSummary, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RequestClassifier { + pub paths: BTreeMap, + pub model_aliases: BTreeMap, +} + +impl RequestClassifier { + /// Call after the runner headers and harness identity have been verified. + pub fn classify( + &self, + route: &ParsedRoute<'_>, + request: &NormalizedRequest, + harness: Option<&str>, + ) -> RequestUse { + use EndpointKind::*; + use RequestUse::*; + + match route.endpoint { + ResponsesCompact => return Compact(CompactKind::ResponsesEndpoint), + ResponsesCreate | ResponsesWs if request.has_compaction_trigger => { + return Compact(CompactKind::ResponsesTrigger); + } + ChatCompletions | AnthropicMessages | ResponsesCreate | ResponsesWs | Unknown => {} + _ => return Control, + } + let explicit = self + .paths + .get(route.canonical_path) + .cloned() + .or_else(|| { + request + .headers + .get("x-maka-bench-request-use") + .and_then(|value| { + Some(match value.as_str() { + "title" => Side(SideKind::Title), + "probe" => Side(SideKind::Probe), + "summary_aux" => Side(SideKind::SummaryAux), + "client_summary" => Compact(CompactKind::ClientSummary), + "anthropic_native" => Compact(CompactKind::AnthropicNative), + value => { + Side(SideKind::Custom(value.strip_prefix("side:")?.to_owned())) + } + }) + }) + }) + .or_else(|| self.model_aliases.get(&request.model).cloned()); + + let system = request.system_text.as_deref().unwrap_or(""); + let is_opencode = harness == Some("opencode"); + let is_claude = harness == Some("claude-code") && route.endpoint == AnthropicMessages; + let last_user = request + .messages + .last() + .filter(|msg| msg.role == NormalizedRole::User) + .map_or("", |msg| msg.text.as_str()); + + let opencode_summary = is_opencode + && ((last_user + .starts_with("Provide a detailed prompt for continuing our conversation above.") + && last_user.contains("## Discoveries") + && last_user.contains("## Accomplished")) + || ((last_user.starts_with( + "You MUST summarize the conversation above into a structured summary", + ) || last_user + .starts_with("Update the existing checkpoint in the conversation above")) + && last_user + .contains("Return only the structured summary in the requested format."))); + let claude_summary = is_claude + && last_user.starts_with("CRITICAL: Respond with TEXT ONLY.") + && last_user.contains("Your task is to create a detailed summary of the conversation") + && last_user.contains("") + && last_user.contains(""); + let codex_summary = harness == Some("codex") + && matches!(route.endpoint, ResponsesCreate | ResponsesWs) + && request.tools.is_empty() + && request.last_user_text().is_some_and(|text| { + text.starts_with( + "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM", + ) + }); + if opencode_summary || claude_summary || codex_summary { + return Compact(CompactKind::ClientSummary); + } + if let Some(explicit) = explicit { + return explicit; + } + + // A native edit can be configured on every turn. Only an explicit compaction-only + // request is a separate operation; a normal turn can trigger compaction in its response. + if route.endpoint == AnthropicMessages + && request.anthropic_compaction_enabled + && request.options.anthropic_pause_after_compaction + { + return Compact(CompactKind::AnthropicNative); + } + + if !request.tools.is_empty() { + return Main; + } + if is_opencode + && (system.contains("You are a title generator. You output ONLY a thread title.") + || ((last_user + .starts_with("Here is the first message of the conversation:\n\n\n") + && last_user.ends_with("\n\nReply with only the title.")) + || (last_user + .starts_with("Here is the conversation so far:\n\n\n") + && last_user.ends_with("\n\nReply with only the title."))) + && request + .messages + .iter() + .filter(|msg| msg.role == NormalizedRole::User) + .count() + == 1) + { + return Side(SideKind::Title); + } + if is_claude { + if system.contains("Generate a concise, sentence-case title (3-7 words)") + && system.contains("Return JSON with a single \"title\" field.") + { + return Side(SideKind::Title); + } + if request.options.max_output_tokens == Some(1) + && system.is_empty() + && request.messages.len() == 1 + && last_user == "quota" + { + return Side(SideKind::Probe); + } + } + Main + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResponseLineage { + pub response_id: ResponseId, + pub owner_session: SessionId, + pub parent_id: Option, + pub logical_revision: Revision, + pub effective_context_tokens: u64, + pub effective_context_bytes: usize, + /// Whether an authorized request can resume independently of the originating connection. + pub resumable: bool, + /// Whether the protocol allows a stored body for this response. + pub store_readable: bool, + pub created_on_conn: Option, +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum LineageError { + #[error("previous_response_not_found: {0}")] + PreviousResponseNotFound(ResponseId), + #[error("cross_session_parent: {0}")] + CrossSessionParent(ResponseId), + #[error("deleted_parent: {0}")] + DeletedParent(ResponseId), + #[error("response {0} already has lineage")] + DuplicateResponse(ResponseId), +} + +#[derive(Debug)] +enum LineageEntry { + Live(ResponseLineage), + Deleted(SessionId), +} + +impl LineageEntry { + fn owner(&self) -> &SessionId { + match self { + Self::Live(response) => &response.owner_session, + Self::Deleted(owner) => owner, + } + } +} + +#[derive(Debug, Default)] +pub struct LineageStore { + entries: HashMap, + latest_on_connection: HashMap, +} + +impl LineageStore { + pub fn insert(&mut self, response: ResponseLineage) -> Result<(), LineageError> { + self.insert_with_parent_check(response, true) + } + + pub(crate) fn insert_admitted( + &mut self, + response: ResponseLineage, + ) -> Result<(), LineageError> { + self.insert_with_parent_check(response, false) + } + + fn insert_with_parent_check( + &mut self, + response: ResponseLineage, + check_parent: bool, + ) -> Result<(), LineageError> { + if self.entries.contains_key(&response.response_id) { + return Err(LineageError::DuplicateResponse(response.response_id)); + } + if check_parent && let Some(parent) = &response.parent_id { + self.resolve_parent(&response.owner_session, parent, response.created_on_conn)?; + } + if let Some(connection) = response.created_on_conn { + self.latest_on_connection + .insert(connection, response.response_id.clone()); + } + self.entries + .insert(response.response_id.clone(), LineageEntry::Live(response)); + Ok(()) + } + + pub fn owner(&self, id: &ResponseId) -> Option<&SessionId> { + self.entries.get(id).map(LineageEntry::owner) + } + + pub fn resolve_parent( + &self, + owner: &SessionId, + id: &ResponseId, + connection: Option, + ) -> Result<&ResponseLineage, LineageError> { + use LineageError::*; + + match self.entries.get(id) { + Some(entry) if entry.owner() == owner => match entry { + LineageEntry::Live(response) => { + let is_baseline = connection + .is_some_and(|conn| self.latest_on_connection.get(&conn) == Some(id)); + if response.resumable || is_baseline { + Ok(response) + } else { + Err(PreviousResponseNotFound(id.clone())) + } + } + LineageEntry::Deleted(_) => Err(DeletedParent(id.clone())), + }, + Some(_) => Err(CrossSessionParent(id.clone())), + None => Err(PreviousResponseNotFound(id.clone())), + } + } + + pub fn delete_owned(&mut self, owner: &SessionId, id: &ResponseId) -> bool { + if let Some(entry @ LineageEntry::Live(_)) = self.entries.get_mut(id) + && let LineageEntry::Live(response) = entry + && &response.owner_session == owner + && response.store_readable + { + if let Some(conn) = response.created_on_conn + && self.latest_on_connection.get(&conn) == Some(id) + { + self.latest_on_connection.remove(&conn); + } + *entry = LineageEntry::Deleted(owner.clone()); + true + } else { + false + } + } + + pub(crate) fn observe_on_connection(&mut self, connection: u64, id: &ResponseId) { + if matches!(self.entries.get(id), Some(LineageEntry::Live(_))) { + self.latest_on_connection.insert(connection, id.clone()); + } + } + + pub(crate) fn remove_owner(&mut self, owner: &SessionId) { + self.entries.retain(|_, entry| entry.owner() != owner); + self.latest_on_connection + .retain(|_, id| self.entries.contains_key(id)); + } + + pub fn close_connection(&mut self, connection: u64) { + self.latest_on_connection.remove(&connection); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Protocol, Transport, normalize_request}; + use serde_json::json; + + fn registration( + id: &str, + credential_binding: Option, + ) -> SessionRegistration { + SessionRegistration { + run_id: RunId("run".into()), + session_id: SessionId(id.into()), + harness: "opencode".into(), + logical_lane: LogicalLane(id.into()), + scenario: "benchmark".into(), + launch_mode: "cold".into(), + credential_binding, + client_session_aliases: Vec::new(), + active: true, + } + } + + #[test] + fn scoped_static_routes_take_precedence_over_ids_and_extras() { + let extra = BTreeMap::from([("/v1/responses/compact".into(), json!({}))]); + let path = "/s/run/a/v1/responses/compact"; + let route = parse_route("POST", path, Some("beta=1"), false, &extra); + assert_eq!(route.scope.unwrap().session_id, SessionId("a".into())); + assert_eq!(route.canonical_path, "/v1/responses/compact"); + assert_eq!(route.raw_path, path); + assert_eq!(route.endpoint, EndpointKind::ResponsesCompact); + assert_eq!( + strip_scope_prefix("/s/run/a/v1/responses/compact?beta=%2f&beta=1"), + "/v1/responses/compact?beta=%2f&beta=1" + ); + for (method, path, upgrade, expected) in [ + ("GET", path, false, EndpointKind::Unknown), + ("DELETE", path, false, EndpointKind::Unknown), + ( + "GET", + "/s/run/a/admin/reset", + false, + EndpointKind::ScopedForbidden, + ), + ( + "GET", + "/s/run/a/metrics", + false, + EndpointKind::ScopedForbidden, + ), + ( + "GET", + "/s/run/a/responses/r1", + false, + EndpointKind::GetResponse("r1".into()), + ), + ( + "GET", + "/s/run/a/responses/r1/more", + false, + EndpointKind::Unknown, + ), + ( + "GET", + "/s/run/a/v1/responses", + true, + EndpointKind::ResponsesWs, + ), + ("GET", "/s/run/a/v1/responses", false, EndpointKind::Unknown), + ] { + assert_eq!( + parse_route(method, path, None, upgrade, &extra).endpoint, + expected + ); + } + } + + #[test] + fn identical_openers_in_64_sessions_remain_distinct_after_the_opener_is_dropped() { + let shared = PrincipalId("shared".into()); + let mut registry = SessionRegistry::default(); + for i in 0..64 { + registry + .register(registration( + &format!("s{i}"), + Some(CredentialBinding::Shared(shared.clone())), + )) + .unwrap(); + } + let lineage = LineageStore::default(); + let resolver = SessionIdentityResolver::new(®istry, &lineage); + let empty_headers = BTreeMap::new(); + let initial = json!({"messages":[{"role":"user","content":"same task"}]}); + let compacted = json!({ + "messages":[{"role":"user","content":"continue from checkpoint"}], + "prompt_cache_key": "shared", + }); + for i in 0..64 { + let id = SessionId(format!("s{i}")); + let scope = RouteScope { + run_id: RunId("run".into()), + session_id: id.clone(), + }; + for body in [&initial, &compacted] { + let resolved = resolver + .resolve(IdentityRequest { + scope: Some(&scope), + principal: Some(&shared), + headers: &empty_headers, + body, + previous_response_id: None, + connection_id: None, + }) + .unwrap(); + assert_eq!(resolved.session_id, id); + } + } + let weak_headers = BTreeMap::from([("x-codex-turn-state".into(), "s0".into())]); + assert_eq!( + resolver + .resolve(IdentityRequest { + scope: None, + principal: Some(&shared), + headers: &weak_headers, + body: &compacted, + previous_response_id: None, + connection_id: None, + }) + .unwrap_err(), + IdentityError::Unroutable + ); + } + + #[test] + fn independent_authorities_must_agree_and_previous_owner_requires_same_principal() { + let shared = PrincipalId("shared".into()); + let unique = PrincipalId("one-to-one".into()); + let mut registry = SessionRegistry::default(); + registry + .register(registration( + "a", + Some(CredentialBinding::Shared(shared.clone())), + )) + .unwrap(); + let mut b = registration("b", Some(CredentialBinding::Shared(shared.clone()))); + b.client_session_aliases.push(ClientSessionAlias { + source: ClientSessionSource::MetadataField("client_session".into()), + value: "client-b".into(), + }); + registry.register(b).unwrap(); + registry + .register(registration( + "c", + Some(CredentialBinding::UniqueTestCredential(unique.clone())), + )) + .unwrap(); + registry + .bind_connection(10, &SessionId("b".into())) + .unwrap(); + + let a_id = SessionId("a".into()); + let b_id = SessionId("b".into()); + let mut lineage = LineageStore::default(); + let a_response = response("r-a", &a_id, None, None, true); + lineage.insert(a_response.clone()).unwrap(); + + let scope = RouteScope { + run_id: RunId("run".into()), + session_id: a_id.clone(), + }; + let header = BTreeMap::from([("x-maka-bench-session".into(), "b".into())]); + let empty = BTreeMap::new(); + let body = json!({}); + let metadata = json!({"metadata":{"client_session":"client-b"}}); + let resolver = SessionIdentityResolver::new(®istry, &lineage); + let request = || IdentityRequest { + scope: None, + principal: Some(&shared), + headers: &empty, + body: &body, + previous_response_id: None, + connection_id: None, + }; + assert_eq!( + resolver + .resolve(IdentityRequest { + scope: Some(&scope), + headers: &header, + ..request() + }) + .unwrap_err(), + IdentityError::Conflict { + preferred: a_id.clone(), + conflicting: b_id.clone(), + evidence: IdentitySource::RunnerHeader + }, + ); + for req in [ + IdentityRequest { + headers: &header, + ..request() + }, + IdentityRequest { + body: &metadata, + ..request() + }, + IdentityRequest { + connection_id: Some(10), + ..request() + }, + ] { + assert_eq!(resolver.resolve(req).unwrap().session_id, b_id); + } + assert_eq!( + resolver + .resolve(IdentityRequest { + previous_response_id: Some(&a_response.response_id), + ..request() + }) + .unwrap() + .session_id, + a_id + ); + assert_eq!( + resolver + .resolve(IdentityRequest { + principal: None, + previous_response_id: Some(&a_response.response_id), + ..request() + }) + .unwrap_err(), + IdentityError::Unroutable, + ); + assert_eq!( + resolver + .resolve(IdentityRequest { + principal: Some(&unique), + ..request() + }) + .unwrap() + .session_id + .0, + "c" + ); + assert!(registry.finalize(&b_id)); + assert_eq!( + SessionIdentityResolver::new(®istry, &lineage) + .resolve(IdentityRequest { + headers: &header, + ..request() + }) + .unwrap_err(), + IdentityError::InactiveSession(b_id) + ); + } + + fn response( + id: &str, + owner: &SessionId, + parent: Option<&str>, + connection: Option, + store: bool, + ) -> ResponseLineage { + ResponseLineage { + response_id: ResponseId(id.into()), + parent_id: parent.map(|id| ResponseId(id.into())), + owner_session: owner.clone(), + logical_revision: Revision(1), + effective_context_tokens: 22, + effective_context_bytes: 90, + created_on_conn: connection, + resumable: store, + store_readable: store, + } + } + + #[test] + fn transient_parent_works_only_as_the_latest_same_connection_baseline() { + let owner = SessionId("owner".into()); + let intruder = SessionId("other".into()); + let transient = ResponseId("ephemeral".into()); + let persisted = ResponseId("persisted".into()); + let mut lineage = LineageStore::default(); + lineage + .insert(response("ephemeral", &owner, None, Some(10), false)) + .unwrap(); + assert_eq!( + lineage + .resolve_parent(&owner, &transient, Some(10)) + .unwrap() + .effective_context_tokens, + 22 + ); + assert_eq!( + lineage.resolve_parent(&owner, &transient, Some(11)), + Err(LineageError::PreviousResponseNotFound(transient.clone())) + ); + assert_eq!( + lineage.resolve_parent(&intruder, &transient, Some(10)), + Err(LineageError::CrossSessionParent(transient.clone())) + ); + assert!(!lineage.delete_owned(&owner, &transient)); + lineage + .insert(response( + "persisted", + &owner, + Some("ephemeral"), + Some(10), + true, + )) + .unwrap(); + assert_eq!( + lineage.resolve_parent(&owner, &transient, Some(10)), + Err(LineageError::PreviousResponseNotFound(transient)) + ); + lineage.close_connection(10); + assert_eq!( + lineage + .resolve_parent(&owner, &persisted, Some(11)) + .unwrap() + .logical_revision, + Revision(1) + ); + assert!(!lineage.delete_owned(&intruder, &persisted)); + assert!(lineage.delete_owned(&owner, &persisted)); + assert_eq!( + lineage.resolve_parent(&owner, &persisted, None), + Err(LineageError::DeletedParent(persisted)) + ); + } + + fn classify(harness: &str, protocol: Protocol, body: Value) -> RequestUse { + let path = match protocol { + Protocol::AnthropicMessages => "/v1/messages", + _ => "/v1/chat/completions", + }; + let req = normalize_request( + 1, + protocol, + Transport::Http, + path.into(), + BTreeMap::new(), + body.to_string().into(), + body, + ); + let routes = BTreeMap::new(); + RequestClassifier::default().classify( + &parse_route("POST", path, None, false, &routes), + &req, + Some(harness), + ) + } + + #[test] + fn only_known_title_and_probe_shapes_leave_the_main_lane() { + let v2_title = json!({"messages":[{"role":"user","content": + "Here is the first message of the conversation:\n\n\nFix tests\n\n\nReply with only the title." + }]}); + assert_eq!( + classify( + "opencode", + Protocol::OpenaiChatCompletions, + v2_title.clone() + ), + RequestUse::Side(SideKind::Title) + ); + assert_eq!( + classify("unknown", Protocol::OpenaiChatCompletions, v2_title), + RequestUse::Main + ); + + let claude = Protocol::AnthropicMessages; + let title = json!({ + "system":[{"type":"text","text":"Generate a concise, sentence-case title (3-7 words) ... Return JSON with a single \"title\" field."}], + "messages":[{"role":"user","content":"Fix tests"}] + }); + assert_eq!( + classify("claude-code", claude, title), + RequestUse::Side(SideKind::Title) + ); + for (model, prompt, max_tokens, expected) in [ + ( + "claude-haiku-4-5-20251001", + "quota", + 1, + RequestUse::Side(SideKind::Probe), + ), + ( + "claude-haiku-4-5-20251001", + "给文章起标题", + 1, + RequestUse::Main, + ), + ("claude-haiku-4-5-20251001", "quota", 16, RequestUse::Main), + ] { + let body = json!({"model":model, "max_tokens":max_tokens, "messages":[{"role":"user","content":prompt}]}); + assert_eq!(classify("claude-code", claude, body), expected); + } + } + + #[test] + fn compaction_summary_is_a_checkpoint_operation() { + let codex = Protocol::OpenaiResponsesHttp; + let ordinary = json!({"input": [ + {"role": "user", "content": "Can you explain what a CONTEXT CHECKPOINT COMPACTION is and how a handoff summary works?"} + ]}); + assert_eq!(classify("codex", codex, ordinary), RequestUse::Main); + + let body = json!({"messages":[ + {"role":"user","content":"Implement feature A"}, + {"role":"assistant","content":"I edited the request parser."}, + {"role":"user","content":"You MUST summarize the conversation above into a structured summary ... Return only the structured summary in the requested format."} + ]}); + assert_eq!( + classify("opencode", Protocol::OpenaiChatCompletions, body), + RequestUse::Compact(CompactKind::ClientSummary) + ); + + let mut body = json!({ + "messages":[{"role":"user","content":"Continue feature A"}], + "context_management":{"edits":[{"type":"compact_20260112"}]}, + }); + assert_eq!( + classify("claude-code", Protocol::AnthropicMessages, body.clone()), + RequestUse::Main + ); + body["context_management"]["edits"][0]["pause_after_compaction"] = json!(true); + assert_eq!( + classify("claude-code", Protocol::AnthropicMessages, body), + RequestUse::Compact(CompactKind::AnthropicNative) + ); + } +} diff --git a/tools/mock-ai/src/rules.rs b/tools/mock-ai/src/rules.rs index 5a8c58e4ed5..e5f00a54344 100644 --- a/tools/mock-ai/src/rules.rs +++ b/tools/mock-ai/src/rules.rs @@ -41,6 +41,8 @@ pub enum ConfigError { Json(#[from] serde_json::Error), #[error("failed to parse YAML config: {0}")] Yaml(String), + #[error("scenario and workload are mutually exclusive")] + ScenarioWorkloadConflict, #[error("invalid regex in rule '{rule_id}': {source}")] Regex { rule_id: String, @@ -72,12 +74,22 @@ pub struct MockServerConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub workload: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub scenario: Option, + #[serde(default)] + pub strict_benchmark: bool, + #[serde(default)] + pub request_classifier: crate::routing::RequestClassifier, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_dialect: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub default_reply: Option, } impl MockServerConfig { pub fn from_json_str(src: &str) -> Result { - Ok(serde_json::from_str(src)?) + let config: Self = serde_json::from_str(src)?; + config.validate()?; + Ok(config) } pub fn from_yaml_str(src: &str) -> Result { @@ -87,7 +99,16 @@ impl MockServerConfig { .next() .ok_or_else(|| ConfigError::Yaml("empty YAML document".into()))?; let json_val = yaml_to_json(doc)?; - Ok(serde_json::from_value(json_val)?) + let config: Self = serde_json::from_value(json_val)?; + config.validate()?; + Ok(config) + } + + pub(crate) fn validate(&self) -> Result<(), ConfigError> { + if self.scenario.is_some() && self.workload.is_some() { + return Err(ConfigError::ScenarioWorkloadConflict); + } + Ok(()) } pub fn from_file(path: &Path) -> Result { diff --git a/tools/mock-ai/src/scenario/mod.rs b/tools/mock-ai/src/scenario/mod.rs new file mode 100644 index 00000000000..78b1732c98b --- /dev/null +++ b/tools/mock-ai/src/scenario/mod.rs @@ -0,0 +1,2952 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! Deterministic canonical semantic scenario engine for fair multi-harness benchmarking. + +pub mod tools; + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::fmt::Write as _; +use std::hash::{Hash, Hasher}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::handler::{HandlerFuture, TurnContext, TurnDecision, TurnHandler}; +use crate::plan::{ + CompactionOutput, FinishReason, HttpErrorSpec, ToolCallPayload, ToolCallSpec, TurnEvent, + TurnPlan, +}; +use crate::protocol::{NormalizedMessageKind, NormalizedRequest, NormalizedRole, Protocol}; +use crate::schema_synth::{ + context_overflow_error, overloaded_error, payload_too_large_error, + previous_response_not_found_error, rate_limit_error, +}; + +use self::tools::{ + BadBinding, Binding, CallPayload, EditHunk, ToolAction, ToolBindError, ToolCatalog, + ValidatorCache, shell_quote, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BenchmarkTrack { + Native, + SharedMcp, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ScenarioSpec { + pub version: u32, + pub scenario: String, + pub seed: u64, + pub fixture: String, + pub track: BenchmarkTrack, + pub steps: Vec, + #[serde(default)] + pub faults: Vec, + #[serde(default)] + pub fixtures: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ScenarioStep { + pub id: String, + #[serde(flatten)] + pub action: CanonicalAction, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum CanonicalAction { + ReadFile { + path: String, + expect_marker: String, + }, + WriteFile { + path: String, + content: String, + }, + EditFile { + path: String, + old: String, + new: String, + }, + Shell { + command_id: String, + #[serde(default)] + command: String, + }, + ParallelBatch(Vec), + LargeOutput { + fixture: String, + bytes: usize, + }, + BadToolCall { + mode: BadToolMode, + expect_handling: FailureHandling, + }, + UnknownTool { + name: String, + expect_handling: FailureHandling, + }, + TriggerCompaction { + mode: CompactionMode, + proof_marker: String, + }, + FinalAnswer { + text: String, + #[serde(default)] + expect_markers: Vec, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +pub enum FixtureDef { + File { path: String, content: String }, + Command { command: String }, + LargeOutput { pattern: String }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BadToolMode { + MissingRequired, + WrongType, + MalformedJson, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FailureHandling { + ToolError, + ProtocolRejection, + HarnessTermination, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum RunnerObservationKind { + ProtocolRejection, + HarnessTermination, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunnerObservation { + pub session_id: String, + pub attempt: u32, + pub call_id: String, + pub kind: RunnerObservationKind, + pub detail: String, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum CompactionMode { + Native, + ContextOverflow { + actual_bytes: usize, + limit_bytes: usize, + }, + Prompt, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ScheduledFault { + pub step: String, + pub attempt: u32, + #[serde(default)] + pub at: FaultBoundary, + pub emit: FaultKind, +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FaultBoundary { + #[default] + BeforeHeaders, + AfterFirstCompleteCall, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FaultKind { + Http429, + Http503, + PayloadTooLarge, + PreviousResponseNotFound, + Eof, + Disconnect, +} + +#[derive(Debug, thiserror::Error)] +pub enum ScenarioSpecError { + #[error("invalid scenario: {0}")] + Invalid(String), + #[error("invalid JSON scenario: {0}")] + Json(#[from] serde_json::Error), + #[cfg(feature = "rules")] + #[error("invalid YAML scenario: {0}")] + Yaml(String), +} + +impl ScenarioSpec { + pub fn new( + scenario: impl Into, + seed: u64, + fixture: impl Into, + track: BenchmarkTrack, + ) -> Self { + Self { + version: 1, + scenario: scenario.into(), + seed, + fixture: fixture.into(), + track, + steps: Vec::new(), + faults: Vec::new(), + fixtures: BTreeMap::new(), + } + } + + pub fn with_step(mut self, id: impl Into, action: CanonicalAction) -> Self { + self.steps.push(ScenarioStep { + id: id.into(), + action, + }); + self + } + + pub fn with_fault(mut self, fault: ScheduledFault) -> Self { + self.faults.push(fault); + self + } + + pub fn with_fixture(mut self, id: impl Into, fixture: FixtureDef) -> Self { + self.fixtures.insert(id.into(), fixture); + self + } + + pub fn from_json_str(source: &str) -> Result { + let spec: Self = serde_json::from_str(source)?; + spec.validate()?; + Ok(spec) + } + + #[cfg(feature = "rules")] + pub fn from_yaml_str(source: &str) -> Result { + let mut docs = yaml_rust2::YamlLoader::load_from_str(source) + .map_err(|error| ScenarioSpecError::Yaml(error.to_string()))?; + if docs.len() != 1 { + return Err(ScenarioSpecError::Yaml("expected one YAML document".into())); + } + let spec: Self = serde_json::from_value(yaml_value(docs.remove(0))?)?; + spec.validate()?; + Ok(spec) + } + + pub fn validate(&self) -> Result<(), ScenarioSpecError> { + self.compile().map(drop) + } + + fn compile(&self) -> Result { + use CanonicalAction as Action; + let invalid = |message: &str| ScenarioSpecError::Invalid(message.into()); + if self.version != 1 || self.scenario.trim().is_empty() || self.fixture.trim().is_empty() { + return Err(invalid( + "expected version 1 and nonempty scenario and fixture names", + )); + } + if !matches!( + self.steps.last().map(|step| &step.action), + Some(Action::FinalAnswer { .. }) + ) { + return Err(invalid("the last step must be a final answer")); + } + + let mut files = BTreeMap::new(); + for (id, fixture) in &self.fixtures { + if id.trim().is_empty() { + return Err(invalid("empty fixture ID")); + } + match fixture { + FixtureDef::File { path, content } => { + if !valid_path(path) || files.insert(path.as_str(), content.clone()).is_some() { + return Err(invalid(&format!( + "invalid or duplicate fixture file path {path:?}" + ))); + } + } + FixtureDef::Command { command } + if command.trim().is_empty() || command.contains('\0') => + { + return Err(invalid(&format!("empty or invalid command fixture {id:?}"))); + } + FixtureDef::LargeOutput { pattern } + if pattern.is_empty() || pattern.contains('\0') => + { + return Err(invalid(&format!( + "empty or invalid large-output pattern {id:?}" + ))); + } + _ => {} + } + } + + let mut step_ids = HashMap::new(); + let mut edit_hunks = Vec::with_capacity(self.steps.len()); + for (index, step) in self.steps.iter().enumerate() { + if step.id.trim().is_empty() || step_ids.insert(step.id.as_str(), index).is_some() { + return Err(invalid(&format!( + "empty or duplicate step ID {:?}", + step.id + ))); + } + let fail = |message: &str| invalid(&format!("step {:?}: {message}", step.id)); + let actions = match &step.action { + Action::ParallelBatch(actions) if !actions.is_empty() => actions.as_slice(), + Action::ParallelBatch(_) => return Err(fail("empty parallel batch")), + _ => std::slice::from_ref(&step.action), + }; + if matches!(step.action, Action::ParallelBatch(_)) { + let mut paths = HashMap::new(); + for action in actions { + let access = match action { + Action::ReadFile { path, .. } => Some((path, false)), + Action::WriteFile { path, .. } | Action::EditFile { path, .. } => { + Some((path, true)) + } + Action::Shell { .. } | Action::LargeOutput { .. } => None, + _ => { + return Err(fail( + "parallel batch allows only independent file, shell and output actions", + )); + } + }; + if let Some((path, writes)) = access + && let Some(previous_writes) = paths.insert(path, writes) + && (writes || previous_writes) + { + return Err(fail(&format!("parallel file access conflicts at {path:?}"))); + } + } + } + let mut hunks = BTreeMap::new(); + for (slot, action) in actions.iter().enumerate() { + match action { + Action::ReadFile { + path, + expect_marker, + } => { + if !valid_path(path) + || expect_marker.is_empty() + || !files + .get(path.as_str()) + .is_some_and(|content| content.contains(expect_marker)) + { + return Err(fail(&format!( + "read fixture {path:?} is missing its expected marker" + ))); + } + } + Action::WriteFile { path, content } => { + if !valid_path(path) { + return Err(fail(&format!("invalid write path {path:?}"))); + } + files.insert(path, content.clone()); + } + Action::EditFile { path, old, new } => { + let content = files.get_mut(path.as_str()).ok_or_else(|| { + fail(&format!("edit references missing fixture file {path:?}")) + })?; + let hunk = EditHunk::new(content, old, new) + .map_err(|err| fail(&err.to_string()))?; + *content = content.replacen(old, new, 1); + hunks.insert(slot, hunk); + } + Action::Shell { + command_id, + command, + } => match self.fixtures.get(command_id) { + Some(FixtureDef::Command { command: fixture }) + if command.is_empty() || command == fixture => {} + _ => { + return Err(fail(&format!( + "missing or mismatched command fixture {command_id:?}" + ))); + } + }, + Action::LargeOutput { fixture, bytes } => { + if *bytes == 0 + || !matches!( + self.fixtures.get(fixture), + Some(FixtureDef::LargeOutput { .. }) + ) + { + return Err(fail(&format!( + "missing large-output fixture or invalid size: {fixture:?}" + ))); + } + } + Action::UnknownTool { name, .. } + if name.is_empty() + || !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') => + { + return Err(fail("unknown tool name must be a nonempty tool identifier")); + } + Action::TriggerCompaction { proof_marker, mode } => { + if proof_marker.trim().is_empty() + || matches!(mode, CompactionMode::ContextOverflow { actual_bytes, limit_bytes } if actual_bytes <= limit_bytes) + { + return Err(fail("invalid compaction marker or context limit")); + } + } + Action::FinalAnswer { + text, + expect_markers, + } => { + if index + 1 != self.steps.len() + || text.trim().is_empty() + || expect_markers + .iter() + .any(|marker| marker.is_empty() || !text.contains(marker)) + { + return Err(fail( + "final answer must be last and contain every expected marker", + )); + } + } + Action::BadToolCall { .. } | Action::UnknownTool { .. } => {} + Action::ParallelBatch(_) => unreachable!("nested batches rejected above"), + } + } + edit_hunks.push(hunks); + } + + let mut faults = HashMap::new(); + for fault in &self.faults { + let step = *step_ids.get(fault.step.as_str()).ok_or_else(|| { + invalid(&format!("fault references unknown step {:?}", fault.step)) + })?; + if fault.attempt == 0 + || faults + .insert((step, fault.attempt), (fault.at, fault.emit)) + .is_some() + { + return Err(invalid(&format!( + "invalid or duplicate fault attempt for {:?}", + fault.step + ))); + } + let action = &self.steps[step].action; + let streams = matches!(fault.emit, FaultKind::Eof | FaultKind::Disconnect); + if fault.at == FaultBoundary::AfterFirstCompleteCall + && (!streams + || matches!( + action, + Action::FinalAnswer { .. } | Action::TriggerCompaction { .. } + )) + { + return Err(invalid(&format!( + "fault cannot fire after a tool call in {:?}", + fault.step + ))); + } + } + Ok(CompiledSpec { edit_hunks, faults }) + } +} + +#[cfg(feature = "rules")] +fn yaml_value(value: yaml_rust2::Yaml) -> Result { + use yaml_rust2::Yaml; + match value { + Yaml::Null => Ok(Value::Null), + Yaml::Boolean(value) => Ok(Value::Bool(value)), + Yaml::Integer(value) => Ok(value.into()), + Yaml::String(value) => Ok(value.into()), + Yaml::Real(value) => Ok(serde_json::from_str(&value)?), + Yaml::Array(items) => items.into_iter().map(yaml_value).collect(), + Yaml::Hash(entries) => entries + .into_iter() + .map(|(key, value)| { + let Yaml::String(key) = key else { + return Err(ScenarioSpecError::Yaml("expected a string key".into())); + }; + Ok((key, yaml_value(value)?)) + }) + .collect::, _>>() + .map(Value::Object), + _ => Err(ScenarioSpecError::Yaml("unsupported YAML value".into())), + } +} + +struct CompiledSpec { + edit_hunks: Vec>, + faults: HashMap<(usize, u32), (FaultBoundary, FaultKind)>, +} + +pub(crate) fn valid_path(path: &str) -> bool { + !path.is_empty() + && !path.contains(['\0', '\r', '\n', '\\', ':']) + && path.split('/').all(|part| !matches!(part, "" | "." | "..")) +} + +pub(crate) fn digest(value: &T) -> u64 { + let mut hash = std::hash::DefaultHasher::new(); + value.hash(&mut hash); + hash.finish() +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Revision(pub usize); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct RequestKey { + pub parent_revision: Revision, + pub turn_boundary_key: u64, + pub pending_call_ids_digest: u64, + pub constraint_digest: u64, +} + +#[derive(Debug)] +pub struct IssuedDecision { + pub revision: Revision, + pub request_key: RequestKey, + pub response_id: String, + pub calls: Vec, + pub recipe: PlanRecipe, +} + +#[derive(Debug)] +pub struct IssuedCall { + pub call_id: String, + pub item_id: String, + pub tool_name: String, + pub namespace: Option, + pub slots: Vec, +} + +#[derive(Debug)] +pub struct PlanRecipe { + step: usize, + kind: PlanKind, +} + +impl PlanRecipe { + pub fn step_index(&self) -> usize { + self.step + } +} + +#[derive(Debug)] +enum PlanKind { + Tools(Vec), + BadTool(BadBinding), + UnknownTool, + Checkpoint, + Final, +} + +#[derive(Debug, Clone)] +pub enum ScenarioSessionState { + AwaitingInput, + AwaitingReceipts(PendingBatch), + AwaitingRunnerObservation { + revision: Revision, + kind: RunnerObservationKind, + }, + AwaitingCheckpoint(PendingCheckpoint), + FinalIssued(FinalReceipt), + Verified(CompletionProof), + RunnerTerminated { + revision: Revision, + }, +} + +#[derive(Debug, Clone)] +pub struct PendingBatch { + pub revision: Revision, + pub outstanding: usize, +} + +#[derive(Debug, Clone)] +pub struct PendingCheckpoint { + pub revision: Revision, + pub checkpoint_id: String, + pub proof_marker: String, + pub evidence_kind: CheckpointEvidenceKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CheckpointEvidenceKind { + NativeCompaction, + ClientSummary, +} + +impl From for CheckpointEvidenceKind { + fn from(mode: CompactionMode) -> Self { + match mode { + CompactionMode::Native => Self::NativeCompaction, + CompactionMode::ContextOverflow { .. } | CompactionMode::Prompt => Self::ClientSummary, + } + } +} + +impl FailureHandling { + fn runner_observation(self) -> Option { + match self { + Self::ToolError => None, + Self::ProtocolRejection => Some(RunnerObservationKind::ProtocolRejection), + Self::HarnessTermination => Some(RunnerObservationKind::HarnessTermination), + } + } +} + +#[derive(Debug, Clone)] +pub struct FinalReceipt { + pub revision: Revision, + pub response_id: String, +} + +#[derive(Debug, Clone)] +pub struct CompletionProof { + pub response_id: String, + pub observed_markers: BTreeSet, +} + +#[derive(Debug)] +pub struct ScenarioEvaluation { + pub decision: Arc, + pub attempt: u32, + pub replayed: bool, + pub confirmed_call_ids: Vec, + pub adopted_checkpoint_id: Option, + pub fault: Option, + pub plan: TurnPlan, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ReceiptOutcome { + Success, + ToolError, +} + +#[derive(Debug, Clone, Copy)] +pub struct ToolReceipt<'a> { + pub call_id: &'a str, + pub result: &'a Value, + pub outcome: ReceiptOutcome, +} + +#[derive(Debug, Clone, Copy)] +pub struct CheckpointReceipt<'a> { + pub checkpoint_id: &'a str, + pub proof_marker: &'a str, + pub kind: CheckpointEvidenceKind, +} + +pub struct ScenarioRequest<'a> { + pub catalog: &'a ToolCatalog, + pub protocol: Protocol, + pub parent_response_id: Option<&'a str>, + pub turn_boundary: Option<&'a str>, + pub receipts: &'a [ToolReceipt<'a>], + pub checkpoint: Option>, + pub tool_choice: &'a Value, + pub allow_parallel_tools: bool, + pub native_compaction: bool, +} + +impl<'a> ScenarioRequest<'a> { + pub fn new(catalog: &'a ToolCatalog, protocol: Protocol) -> Self { + Self { + catalog, + protocol, + parent_response_id: None, + turn_boundary: None, + receipts: &[], + checkpoint: None, + tool_choice: &Value::Null, + allow_parallel_tools: true, + native_compaction: protocol.is_responses(), + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum ScenarioError { + #[error("unknown scenario session {0:?}")] + UnknownSession(String), + #[error("invalid or duplicate session registration {0:?}")] + InvalidSession(String), + #[error("previous response {0:?} does not belong to the session")] + UnknownParent(String), + #[error("receipt for call {0:?} belongs to a different session")] + ForeignCall(String), + #[error("receipt references unknown call {0:?}")] + UnknownCall(String), + #[error("receipt content changed for call {0:?}")] + ChangedReceipt(String), + #[error("unexpected receipt for call {call_id:?}: {reason}")] + UnexpectedReceipt { call_id: String, reason: String }, + #[error("checkpoint evidence does not match an issued checkpoint")] + InvalidCheckpoint, + #[error("runner observation does not match the pending failure for call {0:?}")] + InvalidRunnerObservation(String), + #[error("the runner reported harness termination")] + RunnerTerminated, + #[error("completion proof does not match the issued final answer")] + InvalidCompletionProof, + #[error(transparent)] + Bind(#[from] ToolBindError), +} + +struct Session { + id_scope: String, + logical_lane: String, + workspace: PathBuf, + inner: Mutex, +} + +struct SessionData { + epoch: u64, + step: usize, + state: ScenarioSessionState, + decisions: Vec, + by_request: HashMap, + by_response: HashMap, + by_call: HashMap, + accepted: HashMap, + checkpoints: HashMap, +} + +struct Publication { + decision: Arc, + attempt: u32, + runner_observation: Option, +} + +impl Default for SessionData { + fn default() -> Self { + Self { + epoch: 0, + step: 0, + state: ScenarioSessionState::AwaitingInput, + decisions: Vec::new(), + by_request: HashMap::new(), + by_response: HashMap::new(), + by_call: HashMap::new(), + accepted: HashMap::new(), + checkpoints: HashMap::new(), + } + } +} + +pub struct ScenarioEngine { + spec: ScenarioSpec, + compiled: CompiledSpec, + run_scope: String, + run_id: String, + sessions: Mutex>>, + registrations: AtomicU64, + validators: ValidatorCache, +} + +impl ScenarioEngine { + pub fn new(spec: ScenarioSpec, run_id: impl AsRef) -> Result { + if run_id.as_ref().trim().is_empty() { + return Err(ScenarioSpecError::Invalid("empty run ID".into())); + } + let compiled = spec.compile()?; + Ok(Self { + spec, + compiled, + run_scope: hex(run_id.as_ref()), + run_id: run_id.as_ref().into(), + sessions: Mutex::new(HashMap::new()), + registrations: AtomicU64::new(0), + validators: ValidatorCache::default(), + }) + } + + pub fn register_session( + &self, + session_id: &str, + logical_lane: impl Into, + workspace: impl Into, + ) -> Result<(), ScenarioError> { + let workspace = workspace.into(); + let logical_lane = logical_lane.into(); + let mut sessions = self.sessions.lock().unwrap(); + if session_id.trim().is_empty() + || logical_lane.trim().is_empty() + || !workspace.is_absolute() + || workspace.to_str().is_none() + || sessions.contains_key(session_id) + { + return Err(ScenarioError::InvalidSession(session_id.into())); + } + sessions.insert( + session_id.into(), + Arc::new(Session { + id_scope: format!( + "{}_{}_{:x}", + self.run_scope, + hex(session_id), + self.registrations.fetch_add(1, Ordering::Relaxed) + ), + logical_lane, + workspace, + inner: Mutex::new(SessionData::default()), + }), + ); + Ok(()) + } + + pub fn state(&self, session_id: &str) -> Result { + Ok(self + .session(session_id)? + .inner + .lock() + .unwrap() + .state + .clone()) + } + + pub fn record_runner_observation( + &self, + session_id: &str, + observation: RunnerObservation, + ) -> Result<(), ScenarioError> { + let session = self.session(session_id)?; + let mut data = session.inner.lock().unwrap(); + let invalid = || ScenarioError::InvalidRunnerObservation(observation.call_id.clone()); + if observation.session_id != session_id { + return Err(invalid()); + } + let &(revision, _) = data.by_call.get(&observation.call_id).ok_or_else(invalid)?; + let publication = &data.decisions[revision.0 - 1]; + if publication.runner_observation.as_ref() == Some(&observation) { + return Ok(()); + } + if !matches!(data.state, ScenarioSessionState::AwaitingRunnerObservation { + revision: pending_revision, kind + } if pending_revision == revision && kind == observation.kind) + || publication.attempt != observation.attempt + || matches!( + self.compiled.faults.get(&(data.step, observation.attempt)), + Some((FaultBoundary::BeforeHeaders, _)) + ) + { + return Err(invalid()); + } + + data.state = match observation.kind { + RunnerObservationKind::ProtocolRejection => { + data.step += 1; + ScenarioSessionState::AwaitingInput + } + RunnerObservationKind::HarnessTermination => { + ScenarioSessionState::RunnerTerminated { revision } + } + }; + data.decisions[revision.0 - 1].runner_observation = Some(observation); + data.epoch += 1; + Ok(()) + } + + pub fn verify_completion( + &self, + session_id: &str, + proof: CompletionProof, + ) -> Result<(), ScenarioError> { + let session = self.session(session_id)?; + let CanonicalAction::FinalAnswer { expect_markers, .. } = + &self.spec.steps.last().expect("validated final").action + else { + unreachable!("validated final"); + }; + if !expect_markers + .iter() + .all(|marker| proof.observed_markers.contains(marker)) + { + return Err(ScenarioError::InvalidCompletionProof); + } + let mut data = session.inner.lock().unwrap(); + match &data.state { + ScenarioSessionState::FinalIssued(final_receipt) + if final_receipt.response_id == proof.response_id => + { + data.epoch += 1; + data.state = ScenarioSessionState::Verified(proof); + Ok(()) + } + ScenarioSessionState::Verified(known) + if known.response_id == proof.response_id + && known.observed_markers == proof.observed_markers => + { + Ok(()) + } + _ => Err(ScenarioError::InvalidCompletionProof), + } + } + + pub fn remove_session(&self, session_id: &str) -> bool { + self.sessions.lock().unwrap().remove(session_id).is_some() + } + + fn session(&self, id: &str) -> Result, ScenarioError> { + self.sessions + .lock() + .unwrap() + .get(id) + .cloned() + .ok_or_else(|| ScenarioError::UnknownSession(id.into())) + } + + pub fn evaluate_request( + &self, + session_id: &str, + request: ScenarioRequest<'_>, + ) -> Result { + let session = self.session(session_id)?; + self.evaluate(&session, request) + } + + fn evaluate( + &self, + session: &Session, + request: ScenarioRequest<'_>, + ) -> Result { + let receipts = prepare_receipts(request.receipts)?; + let constraint_digest = digest(&( + request.catalog.constraint_digest(request.tool_choice), + request.allow_parallel_tools, + request.native_compaction, + )); + let boundary = digest(&request.turn_boundary); + loop { + let proposal = session.inner.lock().unwrap().propose( + session, + &request, + &receipts, + boundary, + constraint_digest, + )?; + + for receipt in &proposal.receipts { + self.check_receipt(&receipt.decision, receipt.slot, receipt.receipt)?; + } + + let prepared = match proposal.next { + Next::Issue { step, revision } => self + .prepare_decision(session, &request, step, revision, &proposal.key) + .map(Some), + Next::Replay(_) => Ok(None), + }; + + let (committed, prepared) = { + let mut data = session.inner.lock().unwrap(); + if data.epoch != proposal.epoch { + continue; + } + match prepared { + Ok(prepared) => ( + data.commit( + proposal, + prepared.as_ref().map(|(decision, _)| Arc::clone(decision)), + &self.spec, + ), + prepared, + ), + Err(error) => { + data.accept_progress(proposal); + return Err(error); + } + } + }; + + let fault = if committed.allow_fault { + self.compiled + .faults + .get(&(committed.decision.recipe.step, committed.attempt)) + .copied() + } else { + None + }; + let plan = if let Some((FaultBoundary::BeforeHeaders, fault)) = fault { + fault_plan(fault, request.protocol, request.parent_response_id) + } else if let Some((_, plan)) = prepared { + plan + } else { + self.materialize( + session, + &committed.decision, + &committed.outstanding, + request.protocol, + )? + }; + if constraint_digest != committed.decision.request_key.constraint_digest + && matches!(committed.decision.recipe.kind, PlanKind::Tools(_)) + && !committed.outstanding.is_empty() + { + let catalog = request.catalog.with_tool_choice(request.tool_choice)?; + if !request.allow_parallel_tools && committed.outstanding.len() > 1 { + return Err(ToolBindError::UnsupportedAction { + action: "parallel batch replay".into(), + differences: vec!["request disallows multiple tool calls".into()], + } + .into()); + } + for event in &plan.events { + if let TurnEvent::ToolCall(call) = event { + catalog.validate_replay( + &self.validators, + &call.name, + call.namespace.as_deref(), + call.payload.as_ref().expect("typed scenario payload"), + )?; + } + } + } + let mut plan = if let Some((FaultBoundary::AfterFirstCompleteCall, fault)) = fault { + after_first_call(plan, fault) + } else { + plan + }; + plan.response_id = Some(committed.decision.response_id.clone()); + return Ok(ScenarioEvaluation { + decision: committed.decision, + attempt: committed.attempt, + replayed: committed.replayed, + confirmed_call_ids: committed.confirmed_call_ids, + adopted_checkpoint_id: committed.checkpoint_accepted.then(|| { + request + .checkpoint + .expect("accepted checkpoint evidence") + .checkpoint_id + .to_owned() + }), + fault: fault.map(|(_, fault)| fault), + plan, + }); + } + } + + fn actions(&self, step: usize) -> &[CanonicalAction] { + let action = &self.spec.steps[step].action; + match action { + CanonicalAction::ParallelBatch(actions) => actions, + _ => std::slice::from_ref(action), + } + } + + fn with_tool_actions( + &self, + session: &Session, + step: usize, + f: impl FnOnce(&[ToolAction<'_>]) -> T, + ) -> T { + use CanonicalAction as Action; + let actions = self.actions(step); + let generated: Vec<_> = actions + .iter() + .enumerate() + .map(|(slot, action)| { + let Action::LargeOutput { fixture, bytes } = action else { + return None; + }; + let FixtureDef::LargeOutput { pattern } = &self.spec.fixtures[fixture] else { + unreachable!("validated generator reference"); + }; + Some(large_output_command( + pattern, + *bytes, + self.workload_seed(session, step, slot), + )) + }) + .collect(); + let actions: Vec<_> = actions + .iter() + .zip(&generated) + .enumerate() + .map(|(slot, (action, output))| match action { + Action::ReadFile { path, .. } => ToolAction::Read { path }, + Action::WriteFile { path, content } => ToolAction::Write { path, content }, + Action::EditFile { path, old, new } => ToolAction::Edit { + path, + old, + new, + hunk: &self.compiled.edit_hunks[step][&slot], + }, + Action::Shell { command_id, .. } => { + let FixtureDef::Command { command } = &self.spec.fixtures[command_id] else { + unreachable!("validated command reference"); + }; + ToolAction::Shell { + command, + title: command_id, + } + } + Action::LargeOutput { fixture, .. } => ToolAction::Shell { + command: output.as_deref().expect("generated large-output command"), + title: fixture, + }, + _ => unreachable!("tool action"), + }) + .collect(); + f(&actions) + } + + fn workload_seed(&self, session: &Session, step: usize, slot: usize) -> u64 { + // Length prefixes make the tuple unambiguous across hosts and Rust versions. + let mut seed = 0xcbf29ce484222325u64; + for part in [ + self.spec.seed.to_le_bytes().as_slice(), + session.logical_lane.as_bytes(), + self.spec.steps[step].id.as_bytes(), + (slot as u64).to_le_bytes().as_slice(), + ] { + for byte in (part.len() as u64) + .to_le_bytes() + .into_iter() + .chain(part.iter().copied()) + { + seed = (seed ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + } + seed + } + + pub fn spec(&self) -> &ScenarioSpec { + &self.spec + } + + fn prepare_decision( + &self, + session: &Session, + request: &ScenarioRequest<'_>, + step: usize, + revision: Revision, + key: &RequestKey, + ) -> Result<(Arc, TurnPlan), ScenarioError> { + use CanonicalAction as Action; + let mut plan = None; + let kind = match &self.spec.steps[step].action { + Action::FinalAnswer { .. } => PlanKind::Final, + Action::TriggerCompaction { mode, .. } => { + if matches!(mode, CompactionMode::Native) && !request.native_compaction { + return Err(ToolBindError::UnsupportedAction { + action: "native compaction".into(), + differences: vec!["request has no native compaction support".into()], + } + .into()); + } + PlanKind::Checkpoint + } + Action::BadToolCall { mode, .. } => { + let catalog = request.catalog.with_tool_choice(request.tool_choice)?; + let binding = catalog.bind_bad( + &self.validators, + *mode, + self.workload_seed(session, step, 0), + )?; + PlanKind::BadTool(binding) + } + Action::UnknownTool { name, .. } => { + if request + .catalog + .declarations() + .iter() + .any(|tool| tool.name == *name) + { + return Err( + ToolBindError::InvalidAction(format!("tool {name:?} is declared")).into(), + ); + } + PlanKind::UnknownTool + } + _ => { + let catalog = request.catalog.with_tool_choice(request.tool_choice)?; + let bound = self.with_tool_actions(session, step, |actions| { + catalog.bind( + &self.validators, + self.spec.track, + &session.workspace, + actions, + ) + })?; + if !request.allow_parallel_tools && bound.len() > 1 { + return Err(ToolBindError::UnsupportedAction { + action: "parallel batch".into(), + differences: vec!["request disallows multiple tool calls".into()], + } + .into()); + } + let (bindings, payloads): (Vec<_>, Vec<_>) = bound + .into_iter() + .map(|call| (call.recipe, call.payload)) + .unzip(); + plan = Some(payloads); + PlanKind::Tools(bindings) + } + }; + let call = |index, name: &str, namespace: Option<&str>, slots: Vec| IssuedCall { + call_id: format!("call_{}_{}_{}", session.id_scope, revision.0, index), + item_id: format!("fc_{}_{}_{}", session.id_scope, revision.0, index), + tool_name: name.into(), + namespace: namespace.map(str::to_owned), + slots, + }; + let calls = match &kind { + PlanKind::Tools(bindings) => bindings + .iter() + .enumerate() + .map(|(index, binding)| { + call( + index, + &binding.name, + binding.namespace.as_deref(), + binding.slots.clone(), + ) + }) + .collect(), + PlanKind::BadTool(binding) => { + vec![call( + 0, + &binding.name, + binding.namespace.as_deref(), + vec![0], + )] + } + PlanKind::UnknownTool => { + let Action::UnknownTool { name, .. } = &self.spec.steps[step].action else { + unreachable!("unknown tool recipe"); + }; + vec![call(0, name, None, vec![0])] + } + PlanKind::Checkpoint | PlanKind::Final => Vec::new(), + }; + let decision = Arc::new(IssuedDecision { + revision, + request_key: key.clone(), + response_id: format!("resp_{}_{}", session.id_scope, revision.0), + calls, + recipe: PlanRecipe { step, kind }, + }); + let plan = if let Some(payloads) = plan { + decision + .calls + .iter() + .zip(payloads) + .fold(TurnPlan::new(), |plan, (call, payload)| { + plan.push(tool_call(call, payload)) + }) + } else { + let outstanding = (0..decision.calls.len()).collect::>(); + self.materialize(session, &decision, &outstanding, request.protocol)? + }; + Ok((decision, plan)) + } + + fn materialize( + &self, + session: &Session, + decision: &IssuedDecision, + outstanding: &[usize], + protocol: Protocol, + ) -> Result { + use CanonicalAction as Action; + let step = decision.recipe.step; + let action = &self.spec.steps[step].action; + match &decision.recipe.kind { + PlanKind::Tools(bindings) if !outstanding.is_empty() => { + self.with_tool_actions(session, step, |actions| { + let mut plan = TurnPlan::new(); + for &index in outstanding { + let payload = bindings[index].encode(&session.workspace, actions)?; + plan = plan.push(tool_call(&decision.calls[index], payload)); + } + Ok(plan) + }) + } + PlanKind::BadTool(binding) if !outstanding.is_empty() => { + Ok(TurnPlan::new().push(tool_call( + &decision.calls[0], + binding.encode(self.workload_seed(session, step, 0)), + ))) + } + PlanKind::UnknownTool if !outstanding.is_empty() => { + Ok(TurnPlan::new().push(tool_call( + &decision.calls[0], + CallPayload::Function(Value::Object(Default::default())), + ))) + } + PlanKind::Checkpoint => { + let Action::TriggerCompaction { mode, proof_marker } = action else { + unreachable!("checkpoint recipe"); + }; + let id = checkpoint_id(decision); + Ok(match mode { + CompactionMode::Native => TurnPlan::new().push_compaction(CompactionOutput { + encrypted_content: format!("mock:{proof_marker}"), + summary: format!("{id} {proof_marker}"), + id, + signature: None, + pause_after_compaction: protocol == Protocol::AnthropicMessages, + }), + CompactionMode::ContextOverflow { + actual_bytes, + limit_bytes, + } => TurnPlan::http_error(context_overflow_error( + protocol, + *actual_bytes, + *limit_bytes, + )), + CompactionMode::Prompt => TurnPlan::text(checkpoint_prompt(&id, proof_marker)), + }) + } + PlanKind::Final => { + let Action::FinalAnswer { text, .. } = action else { + unreachable!("final recipe"); + }; + Ok(TurnPlan::text(text)) + } + _ => Ok(TurnPlan::new().finish(FinishReason::Stop)), + } + } + + fn check_receipt( + &self, + decision: &IssuedDecision, + index: usize, + receipt: ToolReceipt<'_>, + ) -> Result<(), ScenarioError> { + use CanonicalAction as Action; + let step = decision.recipe.step; + let actions = self.actions(step); + let call = &decision.calls[index]; + let fail = |reason: String| ScenarioError::UnexpectedReceipt { + call_id: call.call_id.clone(), + reason, + }; + let mut code_results = None; + let code_mode = matches!(&decision.recipe.kind, PlanKind::Tools(bindings) if bindings[index].is_code_mode()); + for (index, &slot) in call.slots.iter().enumerate() { + let action = &actions[slot]; + let expected = match action { + Action::BadToolCall { + expect_handling, .. + } + | Action::UnknownTool { + expect_handling, .. + } => { + if expect_handling.runner_observation().is_some() { + return Err(fail(format!("slot {slot}: expected a runner observation"))); + } + ReceiptOutcome::ToolError + } + _ => ReceiptOutcome::Success, + }; + if receipt.outcome != expected { + return Err(fail(format!( + "slot {slot}: expected {expected:?}, got {:?}", + receipt.outcome + ))); + } + let result = if code_mode { + let results = code_results.get_or_insert_with(|| code_results_from(receipt.result)); + let result = results + .as_ref() + .and_then(|results| results.get(index)) + .ok_or_else(|| fail(format!("slot {slot}: missing Code Mode result")))?; + if result["slot"].as_u64() != Some(slot as u64) || result.get("result").is_none() { + return Err(fail(format!("slot {slot}: invalid Code Mode result"))); + } + &result["result"] + } else { + receipt.result + }; + if expected == ReceiptOutcome::Success && result_failed(result) { + return Err(fail(format!("slot {slot}: tool reported failure"))); + } + if let Action::ReadFile { expect_marker, .. } = action + && !value_contains(result, expect_marker) + { + return Err(fail(format!( + "slot {slot}: missing read marker {expect_marker:?}" + ))); + } + } + Ok(()) + } +} + +fn result_failed(result: &Value) -> bool { + result["kind"] == "failed" + || result["is_error"] == true + || [ + &result["exit_code"], + &result["exitCode"], + &result["value"]["exitCode"], + ] + .iter() + .any(|code| code.as_i64().is_some_and(|exit| exit != 0)) +} + +fn code_results_from(result: &Value) -> Option> { + match result { + Value::String(text) => serde_json::from_str(text).ok().map(Cow::Owned), + Value::Array(items) if items.iter().all(|item| item.get("slot").is_some()) => { + Some(Cow::Borrowed(items)) + } + Value::Array(items) => items.iter().find_map(code_results_from), + Value::Object(_) => result.get("text").and_then(code_results_from), + _ => None, + } +} + +fn checkpoint_id(decision: &IssuedDecision) -> String { + format!( + "cmp_{}", + decision + .response_id + .strip_prefix("resp_") + .expect("scenario response ID") + ) +} + +fn checkpoint_prompt(id: &str, marker: &str) -> String { + format!("Compact the conversation and preserve {id} {marker}.") +} + +fn tool_call(call: &IssuedCall, payload: CallPayload) -> ToolCallSpec { + let payload = match payload { + CallPayload::Function(value) => ToolCallPayload::FunctionArgs(value), + CallPayload::Freeform(text) => ToolCallPayload::FreeformInput(text), + CallPayload::MalformedJson(text) => ToolCallPayload::MalformedRaw(text), + }; + let mut spec = ToolCallSpec::with_payload(&call.call_id, &call.tool_name, payload); + spec.item_id = Some(call.item_id.clone()); + spec.namespace.clone_from(&call.namespace); + spec +} + +fn hex(id: &str) -> String { + let mut encoded = String::with_capacity(id.len() * 2); + for byte in id.bytes() { + write!(encoded, "{byte:02x}").expect("writing to String"); + } + encoded +} + +fn large_output_command(pattern: &str, bytes: usize, seed: u64) -> String { + let pattern = format!("{seed:016x}:{pattern}\n"); + let repetitions_per_block = (4096 / pattern.len()).max(1); + let block_size = repetitions_per_block * pattern.len(); + let blocks = bytes / block_size; + let remainder = bytes % block_size; + let repetitions = remainder / pattern.len(); + let mut tail_bytes = remainder % pattern.len(); + while !pattern.is_char_boundary(tail_bytes) { + tail_bytes -= 1; + } + let tail = format!( + "{}{}", + &pattern[..tail_bytes], + " ".repeat(remainder % pattern.len() - tail_bytes) + ); + format!( + "BENCH_PATTERN={} BENCH_TAIL={} LC_ALL=C awk 'BEGIN {{ p = ENVIRON[\"BENCH_PATTERN\"]; for (i = 0; i < {repetitions_per_block}; i++) block = block p; for (i = 0; i < {blocks}; i++) printf \"%s\", block; for (i = 0; i < {repetitions}; i++) printf \"%s\", p; printf \"%s\", ENVIRON[\"BENCH_TAIL\"] }}'", + shell_quote(&pattern), + shell_quote(&tail), + ) +} + +fn value_contains(value: &Value, marker: &str) -> bool { + match value { + Value::String(text) => text.contains(marker), + Value::Array(values) => values.iter().any(|value| value_contains(value, marker)), + Value::Object(values) => values.values().any(|value| value_contains(value, marker)), + _ => false, + } +} + +fn fault_plan(fault: FaultKind, protocol: Protocol, parent: Option<&str>) -> TurnPlan { + match fault { + FaultKind::Http429 => TurnPlan::http_error(rate_limit_error(protocol, Some(0))), + FaultKind::Http503 => TurnPlan::http_error(overloaded_error(protocol)), + FaultKind::PayloadTooLarge => TurnPlan::http_error(payload_too_large_error(protocol)), + FaultKind::PreviousResponseNotFound => TurnPlan::http_error( + previous_response_not_found_error(protocol, parent.unwrap_or_default()), + ), + FaultKind::Eof => TurnPlan::new() + .push(TurnEvent::StreamStart) + .push(TurnEvent::TruncateEof), + FaultKind::Disconnect => TurnPlan::new().push(TurnEvent::DropConnection), + } +} + +fn after_first_call(mut plan: TurnPlan, fault: FaultKind) -> TurnPlan { + if let Some(index) = plan + .events + .iter() + .position(|event| matches!(event, TurnEvent::ToolCall(_))) + { + plan.events.truncate(index + 1); + plan.events.push(TurnEvent::Flush); + plan.events.push(match fault { + FaultKind::Eof => TurnEvent::TruncateEof, + FaultKind::Disconnect => TurnEvent::DropConnection, + _ => unreachable!("validated streaming fault"), + }); + } + plan +} + +#[derive(Clone, Copy)] +struct PreparedReceipt<'a> { + receipt: ToolReceipt<'a>, + digest: u64, +} + +fn prepare_receipts<'a>( + receipts: &[ToolReceipt<'a>], +) -> Result>, ScenarioError> { + let mut entries = HashMap::new(); + let mut unique = Vec::new(); + for &receipt in receipts { + let digest = digest(&(receipt.result, receipt.outcome)); + if let Some(previous) = entries.insert(receipt.call_id, digest) { + if previous != digest { + return Err(ScenarioError::ChangedReceipt(receipt.call_id.into())); + } + } else { + unique.push(PreparedReceipt { receipt, digest }); + } + } + Ok(unique) +} + +struct NewReceipt<'a> { + decision: Arc, + slot: usize, + receipt: ToolReceipt<'a>, + digest: u64, +} + +struct Proposal<'a> { + epoch: u64, + key: RequestKey, + next: Next, + receipts: Vec>, + checkpoint_accepted: bool, +} + +enum Next { + Issue { step: usize, revision: Revision }, + Replay(Revision), +} + +struct Committed { + decision: Arc, + outstanding: Vec, + attempt: u32, + allow_fault: bool, + replayed: bool, + confirmed_call_ids: Vec, + checkpoint_accepted: bool, +} + +impl SessionData { + fn decision(&self, revision: Revision) -> &Arc { + &self.decisions[revision.0 - 1].decision + } + + fn outstanding(&self, decision: &IssuedDecision, incoming: &HashSet<&str>) -> Vec { + if self.decisions[decision.revision.0 - 1] + .runner_observation + .is_some() + { + return Vec::new(); + } + decision + .calls + .iter() + .enumerate() + .filter_map(|(index, call)| { + (!self.accepted.contains_key(&call.call_id) + && !incoming.contains(call.call_id.as_str())) + .then_some(index) + }) + .collect() + } + + fn propose<'a>( + &self, + session: &Session, + request: &ScenarioRequest<'_>, + receipts: &[PreparedReceipt<'a>], + turn_boundary_key: u64, + constraint_digest: u64, + ) -> Result, ScenarioError> { + let mut parent = request + .parent_response_id + .map(|id| { + self.by_response + .get(id) + .copied() + .ok_or_else(|| ScenarioError::UnknownParent(id.into())) + }) + .transpose()? + .unwrap_or_default(); + + let mut incoming = HashSet::new(); + let mut new_receipts = Vec::new(); + for &PreparedReceipt { receipt, digest } in receipts { + let id = receipt.call_id; + let Some(&(revision, slot)) = self.by_call.get(id) else { + if let Some(scope) = call_scope(id) + && scope != session.id_scope + { + return Err(ScenarioError::ForeignCall(id.into())); + } + return Err(ScenarioError::UnknownCall(id.into())); + }; + if request.parent_response_id.is_none() { + parent = parent.max(revision); + } + if let Some(&existing) = self.accepted.get(id) { + if existing != digest { + return Err(ScenarioError::ChangedReceipt(id.into())); + } + } else { + incoming.insert(id); + new_receipts.push(NewReceipt { + decision: Arc::clone(self.decision(revision)), + slot, + receipt, + digest, + }); + } + } + + let mut checkpoint_accepted = false; + if let Some(checkpoint) = request.checkpoint { + let (revision, marker, kind) = self + .checkpoints + .get(checkpoint.checkpoint_id) + .ok_or(ScenarioError::InvalidCheckpoint)?; + if marker != checkpoint.proof_marker || *kind != checkpoint.kind { + return Err(ScenarioError::InvalidCheckpoint); + } + if request.parent_response_id.is_none() { + parent = parent.max(*revision); + } + checkpoint_accepted = matches!(&self.state, + ScenarioSessionState::AwaitingCheckpoint(pending) if pending.revision == *revision); + } + + let pending_call_ids_digest = if parent == Revision::default() { + digest(&Vec::<&str>::new()) + } else { + let decision = self.decision(parent); + digest( + &self + .outstanding(decision, &incoming) + .iter() + .map(|&index| decision.calls[index].call_id.as_str()) + .collect::>(), + ) + }; + let key = RequestKey { + parent_revision: parent, + turn_boundary_key, + pending_call_ids_digest, + constraint_digest, + }; + + let issue = |step| Next::Issue { + step, + revision: Revision(self.decisions.len() + 1), + }; + let replay = |current| Next::Replay(self.by_request.get(&key).copied().unwrap_or(current)); + let next = match &self.state { + ScenarioSessionState::AwaitingInput => issue(self.step), + ScenarioSessionState::AwaitingReceipts(batch) + if batch.outstanding == new_receipts.len() => + { + issue(self.step + 1) + } + ScenarioSessionState::AwaitingReceipts(batch) if !new_receipts.is_empty() => { + Next::Replay(batch.revision) + } + ScenarioSessionState::AwaitingReceipts(batch) => replay(batch.revision), + ScenarioSessionState::AwaitingRunnerObservation { revision, .. } => replay(*revision), + ScenarioSessionState::AwaitingCheckpoint(_) if checkpoint_accepted => { + issue(self.step + 1) + } + ScenarioSessionState::AwaitingCheckpoint(checkpoint) => replay(checkpoint.revision), + ScenarioSessionState::FinalIssued(final_receipt) => replay(final_receipt.revision), + ScenarioSessionState::Verified(_) => replay(Revision(self.decisions.len())), + ScenarioSessionState::RunnerTerminated { .. } => { + return Err(ScenarioError::RunnerTerminated); + } + }; + + Ok(Proposal { + epoch: self.epoch, + key, + next, + receipts: new_receipts, + checkpoint_accepted, + }) + } + + fn accept_progress(&mut self, proposal: Proposal<'_>) { + if proposal.receipts.is_empty() && !proposal.checkpoint_accepted { + return; + } + let Next::Issue { step, .. } = proposal.next else { + unreachable!("only new issuance can fail to bind"); + }; + self.accept_receipts(proposal.receipts); + self.step = step; + self.epoch += 1; + self.state = ScenarioSessionState::AwaitingInput; + } + + fn accept_receipts(&mut self, receipts: Vec>) { + for receipt in receipts { + self.accepted + .insert(receipt.receipt.call_id.into(), receipt.digest); + } + } + + fn commit( + &mut self, + proposal: Proposal<'_>, + decision: Option>, + spec: &ScenarioSpec, + ) -> Committed { + let Proposal { + key, + next, + receipts, + checkpoint_accepted, + .. + } = proposal; + let has_progress = !receipts.is_empty() || checkpoint_accepted; + let constraint_digest = key.constraint_digest; + let confirmed_call_ids = receipts + .iter() + .map(|receipt| receipt.receipt.call_id.to_owned()) + .collect(); + self.accept_receipts(receipts); + + let (revision, replayed) = match next { + Next::Issue { step, revision } => { + let decision = decision.expect("prepared issuance"); + self.step = step; + self.by_request.insert(key, revision); + self.by_response + .insert(decision.response_id.clone(), revision); + self.by_call.extend( + decision + .calls + .iter() + .enumerate() + .map(|(slot, call)| (call.call_id.clone(), (revision, slot))), + ); + self.state = match &spec.steps[step].action { + CanonicalAction::TriggerCompaction { mode, proof_marker } => { + let checkpoint_id = checkpoint_id(&decision); + let evidence_kind = (*mode).into(); + self.checkpoints.insert( + checkpoint_id.clone(), + (revision, proof_marker.clone(), evidence_kind), + ); + ScenarioSessionState::AwaitingCheckpoint(PendingCheckpoint { + revision, + checkpoint_id, + proof_marker: proof_marker.clone(), + evidence_kind, + }) + } + CanonicalAction::FinalAnswer { .. } => { + ScenarioSessionState::FinalIssued(FinalReceipt { + revision, + response_id: decision.response_id.clone(), + }) + } + CanonicalAction::BadToolCall { + expect_handling, .. + } + | CanonicalAction::UnknownTool { + expect_handling, .. + } if let Some(kind) = expect_handling.runner_observation() => { + ScenarioSessionState::AwaitingRunnerObservation { revision, kind } + } + _ => ScenarioSessionState::AwaitingReceipts(PendingBatch { + revision, + outstanding: decision.calls.len(), + }), + }; + self.decisions.push(Publication { + decision, + attempt: 0, + runner_observation: None, + }); + (revision, false) + } + Next::Replay(revision) => (revision, true), + }; + + let decision = Arc::clone(self.decision(revision)); + let outstanding = self.outstanding(&decision, &HashSet::new()); + if let ScenarioSessionState::AwaitingReceipts(batch) = &mut self.state + && batch.revision == revision + { + batch.outstanding = outstanding.len(); + } + + // Replaying an older boundary must never re-inject faults into a later step. + let same_constraints = constraint_digest == decision.request_key.constraint_digest; + let allow_fault = same_constraints + && decision.recipe.step == self.step + && !matches!(self.state, ScenarioSessionState::Verified(_)); + let publication = &mut self.decisions[revision.0 - 1]; + if same_constraints { + publication.attempt = publication.attempt.saturating_add(1); + } + if !replayed || has_progress { + self.epoch += 1; + } + Committed { + decision, + outstanding, + attempt: publication.attempt, + allow_fault, + replayed, + confirmed_call_ids, + checkpoint_accepted, + } + } +} + +fn call_scope(id: &str) -> Option<&str> { + let (prefix, slot) = id.strip_prefix("call_")?.rsplit_once('_')?; + let (scope, revision) = prefix.rsplit_once('_')?; + let (owner, generation) = scope.rsplit_once('_')?; + let (run, session) = owner.split_once('_')?; + let is_hex = |part: &str| { + !part.is_empty() + && part.len().is_multiple_of(2) + && part.bytes().all(|b| b.is_ascii_hexdigit()) + }; + (is_hex(run) + && is_hex(session) + && u64::from_str_radix(generation, 16).is_ok() + && revision.parse::().is_ok() + && slot.parse::().is_ok()) + .then_some(scope) +} + +impl ScenarioEngine { + pub(crate) fn compaction_output( + &self, + session_id: &str, + ) -> Option<(Revision, CompactionOutput)> { + let session = self.session(session_id).ok()?; + let data = session.inner.lock().unwrap(); + let ScenarioSessionState::AwaitingCheckpoint(checkpoint) = &data.state else { + return None; + }; + Some(( + checkpoint.revision, + CompactionOutput { + id: checkpoint.checkpoint_id.clone(), + encrypted_content: format!("mock:{}", checkpoint.proof_marker), + summary: format!("{} {}", checkpoint.checkpoint_id, checkpoint.proof_marker), + signature: None, + pause_after_compaction: true, + }, + )) + } + + /// Use an identity already resolved by the caller's routing layer. + pub fn evaluate_normalized( + &self, + session_id: &str, + request: &NormalizedRequest, + ) -> Result { + let session = self.session(session_id)?; + self.evaluate_wire(&session, request, request.previous_response_id.as_deref()) + } + + pub(crate) fn evaluate_with_parent_revision( + &self, + session_id: &str, + request: &NormalizedRequest, + revision: Revision, + ) -> Result { + let session = self.session(session_id)?; + let decision = if let Some(index) = revision.0.checked_sub(1) { + let data = session.inner.lock().unwrap(); + Some(Arc::clone( + &data + .decisions + .get(index) + .ok_or_else(|| { + ScenarioError::UnknownParent( + request.previous_response_id.clone().unwrap_or_default(), + ) + })? + .decision, + )) + } else { + None + }; + self.evaluate_wire( + &session, + request, + decision + .as_deref() + .map(|decision| decision.response_id.as_str()), + ) + } + + fn evaluate_wire( + &self, + session: &Session, + request: &NormalizedRequest, + parent: Option<&str>, + ) -> Result { + let catalog = ToolCatalog::from_request(request); + let mut input = ScenarioRequest::new(&catalog, request.protocol); + let (receipts, checkpoint) = wire_evidence(request)?; + let pending_summary = { + let data = session.inner.lock().unwrap(); + match &data.state { + ScenarioSessionState::AwaitingCheckpoint(pending) + if pending.evidence_kind == CheckpointEvidenceKind::ClientSummary => + { + Some(pending.clone()) + } + _ => None, + } + }; + input.receipts = &receipts; + input.checkpoint = pending_summary + .as_ref() + .and_then(|pending| client_summary_receipt(request, pending)) + .or(checkpoint); + input.parent_response_id = parent; + input.turn_boundary = request + .headers + .get("x-maka-bench-turn") + .map(String::as_str) + .or_else(|| { + request + .messages + .iter() + .rev() + .find(|msg| msg.role == NormalizedRole::User) + .map(|msg| msg.text.as_str()) + }); + input.tool_choice = request.options.tool_choice.as_ref().unwrap_or(&Value::Null); + input.allow_parallel_tools = request.options.parallel_tool_calls.unwrap_or(true); + input.native_compaction = + request.protocol.is_responses() || request.anthropic_compaction_enabled; + self.evaluate(session, input) + } +} + +fn client_summary_receipt<'a>( + request: &NormalizedRequest, + pending: &'a PendingCheckpoint, +) -> Option> { + let prompt = checkpoint_prompt(&pending.checkpoint_id, &pending.proof_marker); + let texts = request.system_text.iter().chain( + request + .messages + .iter() + .filter(|message| { + message.kind == NormalizedMessageKind::Message + && message.role != NormalizedRole::Tool + }) + .map(|message| &message.text), + ); + let has_token = |text: &str, token: &str| { + let continues = |c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'); + let has_start_boundary = token.starts_with(continues); + let has_end_boundary = token.ends_with(continues); + text.match_indices(token).any(|(start, matched)| { + (!has_start_boundary || !text[..start].ends_with(continues)) + && (!has_end_boundary || !text[start + matched.len()..].starts_with(continues)) + }) + }; + // A retained copy of the assistant's compaction instruction is not a returned summary. + texts + .flat_map(|text| text.split(prompt.as_str())) + .any(|text| { + has_token(text, &pending.checkpoint_id) && has_token(text, &pending.proof_marker) + }) + .then_some(CheckpointReceipt { + checkpoint_id: &pending.checkpoint_id, + proof_marker: &pending.proof_marker, + kind: CheckpointEvidenceKind::ClientSummary, + }) +} + +type WireEvidence<'a> = (Vec>, Option>); + +fn wire_evidence<'a>(request: &'a NormalizedRequest) -> Result, ScenarioError> { + let mut receipts = Vec::new(); + let mut checkpoint = None; + let items = |key: &str| request.raw_body[key].as_array().into_iter().flatten(); + let mut receipt = |id: &'a Value, result: &'a Value, is_error: bool| { + let id = id + .as_str() + .filter(|id| !id.is_empty()) + .ok_or_else(|| ScenarioError::UnknownCall(String::new()))?; + let outcome = if is_error || result_failed(result) || result["handling"] == "tool_error" { + ReceiptOutcome::ToolError + } else { + ReceiptOutcome::Success + }; + receipts.push(ToolReceipt { + call_id: id, + result, + outcome, + }); + Ok::<_, ScenarioError>(()) + }; + match request.protocol { + Protocol::AnthropicMessages => { + for block in items("messages") + .flat_map(|message| message["content"].as_array().into_iter().flatten()) + { + match block["type"].as_str() { + Some("tool_result") => receipt( + &block["tool_use_id"], + &block["content"], + block["is_error"] == true, + )?, + Some("compaction") => { + if let Some((id, marker)) = + block["content"].as_str().and_then(|s| s.split_once(' ')) + && id.starts_with("cmp_") + { + checkpoint = Some(CheckpointReceipt { + checkpoint_id: id, + proof_marker: marker, + kind: CheckpointEvidenceKind::NativeCompaction, + }); + } + } + _ => {} + } + } + } + Protocol::OpenaiChatCompletions => { + for item in items("messages").filter(|item| item["role"] == "tool") { + receipt( + &item["tool_call_id"], + &item["content"], + item["is_error"] == true, + )?; + } + } + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { + for item in items("input") { + match item["type"].as_str() { + Some("function_call_output" | "custom_tool_call_output") => { + receipt(&item["call_id"], &item["output"], item["is_error"] == true)?; + } + Some("compaction") => { + if let (Some(id), Some(marker)) = ( + item["id"].as_str(), + item["encrypted_content"] + .as_str() + .and_then(|s| s.strip_prefix("mock:")), + ) { + checkpoint = Some(CheckpointReceipt { + checkpoint_id: id, + proof_marker: marker, + kind: CheckpointEvidenceKind::NativeCompaction, + }); + } + } + _ => {} + } + } + } + } + Ok((receipts, checkpoint)) +} + +impl TurnHandler for ScenarioEngine { + fn handle<'a>( + &'a self, + request: &'a NormalizedRequest, + _: &'a TurnContext, + ) -> HandlerFuture<'a> { + Box::pin(async move { + let route = + crate::routing::parse_route("POST", &request.path, None, false, &BTreeMap::new()); + let session_id = if let Some(scope) = route.scope.as_ref() { + if scope.run_id.0 != self.run_id { + return None; + } + scope.session_id.0.as_str() + } else { + request + .headers + .get("x-maka-bench-session") + .unwrap_or(&request.session_key) + }; + let session = self.session(session_id).ok()?; + let plan = match self.evaluate_wire( + &session, + request, + request.previous_response_id.as_deref(), + ) { + Ok(evaluation) => evaluation.plan, + Err(error) => { + tracing::warn!(session_id, %error, "scenario request rejected"); + match error { + ScenarioError::UnknownParent(id) => TurnPlan::http_error( + previous_response_not_found_error(request.protocol, &id), + ), + _ => TurnPlan::http_error(HttpErrorSpec::new( + 400, + "invalid_request_error", + error.to_string(), + )), + } + } + }; + Some(TurnDecision::Plan(plan)) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Transport, normalize_request}; + use serde_json::json; + + fn spec() -> ScenarioSpec { + ScenarioSpec::new("files", 73, "files-v1", BenchmarkTrack::Native) + .with_fixture( + "a", + FixtureDef::File { + path: "a.txt".into(), + content: "alpha\n".into(), + }, + ) + .with_fixture( + "b", + FixtureDef::File { + path: "b.txt".into(), + content: "beta\n".into(), + }, + ) + } + + fn read(path: &str, marker: &str) -> CanonicalAction { + CanonicalAction::ReadFile { + path: path.into(), + expect_marker: marker.into(), + } + } + + fn final_answer() -> CanonicalAction { + CanonicalAction::FinalAnswer { + text: "proof: files complete".into(), + expect_markers: vec!["files complete".into()], + } + } + + fn engine(spec: ScenarioSpec) -> ScenarioEngine { + let engine = ScenarioEngine::new(spec, "run-a").unwrap(); + engine + .register_session("session-a", "lane-1", "/bench/work") + .unwrap(); + engine + } + + fn read_decl() -> Value { + json!({"type": "function", "name": "Read", "parameters": { + "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"], + "additionalProperties": false + }}) + } + + fn normalize(protocol: Protocol, transport: Transport, body: Value) -> NormalizedRequest { + normalize_request( + 0, + protocol, + transport, + "/v1/responses".into(), + BTreeMap::from([("x-maka-session-id".into(), "session-a".into())]), + Default::default(), + body, + ) + } + + fn read_catalog() -> ToolCatalog { + ToolCatalog::from_request(&normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({"tools": [read_decl()]}), + )) + } + + fn calls(plan: &TurnPlan) -> Vec<&ToolCallSpec> { + plan.events + .iter() + .filter_map(|event| { + let TurnEvent::ToolCall(call) = event else { + return None; + }; + Some(call) + }) + .collect() + } + + fn receipt<'a>(call_id: &'a str, result: &'a Value) -> ToolReceipt<'a> { + ToolReceipt { + call_id, + result, + outcome: ReceiptOutcome::Success, + } + } + + #[test] + fn faults_retry_the_same_publication_across_http_and_ws_until_receipt() { + let engine = engine( + spec() + .with_step("read", read("a.txt", "alpha")) + .with_step("done", final_answer()) + .with_fault(ScheduledFault { + step: "read".into(), + attempt: 1, + at: FaultBoundary::BeforeHeaders, + emit: FaultKind::Http429, + }) + .with_fault(ScheduledFault { + step: "read".into(), + attempt: 2, + at: FaultBoundary::BeforeHeaders, + emit: FaultKind::Http503, + }), + ); + let body = json!({"input": "start", "tools": [read_decl()]}); + let mut http = normalize(Protocol::OpenaiResponsesHttp, Transport::Http, body.clone()); + let first = engine.evaluate_normalized("session-a", &http).unwrap(); + assert!( + matches!(&first.plan.events[..], [TurnEvent::HttpError(error)] if error.status == 429) + ); + http.sequence = 99; + http.headers + .insert("authorization".into(), "Bearer rotated".into()); + let second = engine.evaluate_normalized("session-a", &http).unwrap(); + assert!( + matches!(&second.plan.events[..], [TurnEvent::HttpError(error)] if error.status == 503) + ); + let ws = normalize( + Protocol::OpenaiResponsesWs, + Transport::WebSocket { + connection_id: 7, + turn_on_connection: 1, + }, + body, + ); + let third = engine.evaluate_normalized("session-a", &ws).unwrap(); + let retry = engine.evaluate_normalized("session-a", &http).unwrap(); + for evaluation in [&second, &third, &retry] { + assert_eq!(evaluation.decision.request_key, first.decision.request_key); + assert_eq!(evaluation.plan.response_id, first.plan.response_id); + assert_eq!( + evaluation.decision.calls[0].call_id, + first.decision.calls[0].call_id + ); + assert!(evaluation.replayed); + } + assert_eq!( + [first.attempt, second.attempt, third.attempt, retry.attempt], + [1, 2, 3, 4] + ); + assert_eq!(calls(&third.plan), calls(&retry.plan)); + assert_eq!( + calls(&third.plan)[0].payload, + Some(ToolCallPayload::FunctionArgs(json!({"path": "a.txt"}))) + ); + + let continuation = normalize( + Protocol::OpenaiResponsesWs, + ws.transport, + json!({ + "previous_response_id": third.decision.response_id, + "input": [{"type": "function_call_output", "call_id": third.decision.calls[0].call_id, "output": "alpha\n"}], + "tools": [read_decl()] + }), + ); + let done = engine + .evaluate_normalized("session-a", &continuation) + .unwrap(); + assert_eq!(done.decision.revision, Revision(2)); + assert!( + matches!(&done.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + assert!(matches!( + engine.state("session-a").unwrap(), + ScenarioSessionState::FinalIssued(_) + )); + assert!(matches!( + engine.verify_completion( + "session-a", + CompletionProof { + response_id: done.decision.response_id.clone(), + observed_markers: BTreeSet::new(), + } + ), + Err(ScenarioError::InvalidCompletionProof) + )); + engine + .verify_completion( + "session-a", + CompletionProof { + response_id: done.decision.response_id.clone(), + observed_markers: BTreeSet::from(["files complete".into()]), + }, + ) + .unwrap(); + assert!(matches!( + engine.state("session-a").unwrap(), + ScenarioSessionState::Verified(_) + )); + } + + #[test] + fn parallel_receipts_are_order_independent_and_never_reissue_confirmed_slots() { + let engine = engine( + spec() + .with_step( + "batch", + CanonicalAction::ParallelBatch(vec![ + read("a.txt", "alpha"), + read("b.txt", "beta"), + ]), + ) + .with_step("done", final_answer()) + .with_fault(ScheduledFault { + step: "batch".into(), + attempt: 1, + at: FaultBoundary::AfterFirstCompleteCall, + emit: FaultKind::Eof, + }), + ); + let catalog = read_catalog(); + let request = || ScenarioRequest::new(&catalog, Protocol::OpenaiResponsesHttp); + let first = engine.evaluate_request("session-a", request()).unwrap(); + assert_eq!(calls(&first.plan).len(), 1); + assert!(matches!( + first.plan.events.last(), + Some(TurnEvent::TruncateEof) + )); + let retry = engine.evaluate_request("session-a", request()).unwrap(); + assert_eq!(calls(&retry.plan).len(), 2); + assert_eq!(calls(&first.plan)[0], calls(&retry.plan)[0]); + let [first_call, second_call] = retry.decision.calls.as_slice() else { + panic!("two calls") + }; + let alpha = json!(["alpha\n"]); + let beta = json!({"content": "beta\n"}); + let second_receipt = [receipt(&second_call.call_id, &beta)]; + let partial = engine + .evaluate_request( + "session-a", + ScenarioRequest { + receipts: &second_receipt, + ..request() + }, + ) + .unwrap(); + assert_eq!(partial.decision.revision, Revision(1)); + assert_eq!(calls(&partial.plan), vec![calls(&retry.plan)[0]]); + let stale = engine.evaluate_request("session-a", request()).unwrap(); + assert_eq!(calls(&stale.plan), calls(&partial.plan)); + assert!(matches!( + engine.state("session-a").unwrap(), + ScenarioSessionState::AwaitingReceipts(PendingBatch { outstanding: 1, .. }) + )); + + let both = [ + receipt(&second_call.call_id, &beta), + receipt(&first_call.call_id, &alpha), + ]; + let done = engine + .evaluate_request( + "session-a", + ScenarioRequest { + receipts: &both, + ..request() + }, + ) + .unwrap(); + assert_eq!(done.decision.revision, Revision(2)); + let repeat = engine + .evaluate_request( + "session-a", + ScenarioRequest { + receipts: &both, + ..request() + }, + ) + .unwrap(); + assert_eq!(repeat.decision.response_id, done.decision.response_id); + assert!( + matches!(&repeat.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + + let changed = json!("beta but changed"); + assert!( + matches!(engine.evaluate_request("session-a", ScenarioRequest { + receipts: &[receipt(&second_call.call_id, &changed)], ..request() + }), Err(ScenarioError::ChangedReceipt(id)) if id == second_call.call_id) + ); + engine + .register_session("session-b", "lane-1", "/bench/other") + .unwrap(); + assert!( + matches!(engine.evaluate_request("session-b", ScenarioRequest { receipts: &both, ..request() }), + Err(ScenarioError::ForeignCall(id)) if id == second_call.call_id) + ); + assert!( + matches!(engine.evaluate_request("session-a", ScenarioRequest { + receipts: &[receipt("unknown-id", &alpha)], ..request() + }), Err(ScenarioError::UnknownCall(id)) if id == "unknown-id") + ); + } + + #[test] + fn concurrent_retries_publish_once_and_transfer_fault_attempts() { + let engine = engine( + spec() + .with_step("read", read("a.txt", "alpha")) + .with_step("done", final_answer()) + .with_fault(ScheduledFault { + step: "read".into(), + attempt: 1, + at: FaultBoundary::BeforeHeaders, + emit: FaultKind::Http429, + }), + ); + let catalog = read_catalog(); + let run = || { + engine + .evaluate_request( + "session-a", + ScenarioRequest::new(&catalog, Protocol::OpenaiResponsesHttp), + ) + .unwrap() + }; + let (one, other) = std::thread::scope(|scope| { + let a = scope.spawn(run); + let b = scope.spawn(run); + (a.join().unwrap(), b.join().unwrap()) + }); + assert_eq!(one.decision.response_id, other.decision.response_id); + let (first, second) = if one.attempt == 1 { + (one, other) + } else { + (other, one) + }; + assert_eq!(second.attempt, 2); + assert!( + matches!(&first.plan.events[..], [TurnEvent::HttpError(error)] if error.status == 429) + ); + assert_eq!(calls(&second.plan)[0].id, first.decision.calls[0].call_id); + } + + #[test] + fn failed_next_binding_does_not_forget_a_confirmed_receipt() { + let engine = engine( + spec() + .with_step("read-a", read("a.txt", "alpha")) + .with_step("read-b", read("b.txt", "beta")) + .with_step("done", final_answer()), + ); + let catalog = read_catalog(); + let request = || ScenarioRequest::new(&catalog, Protocol::OpenaiResponsesHttp); + let first = engine.evaluate_request("session-a", request()).unwrap(); + let alpha = json!("alpha"); + assert!(matches!( + engine.evaluate_request( + "session-a", + ScenarioRequest { + catalog: &ToolCatalog::default(), + receipts: &[receipt(&first.decision.calls[0].call_id, &alpha)], + ..request() + } + ), + Err(ScenarioError::Bind(ToolBindError::UnsupportedAction { .. })) + )); + let next = engine.evaluate_request("session-a", request()).unwrap(); + assert_eq!(next.decision.revision, Revision(2)); + assert_eq!( + calls(&next.plan)[0].payload, + Some(ToolCallPayload::FunctionArgs(json!({"path": "b.txt"}))) + ); + } + + #[test] + fn pending_calls_keep_their_identity_if_the_declaration_changes() { + let engine = engine( + spec() + .with_step("read", read("a.txt", "alpha")) + .with_step("done", final_answer()), + ); + let good = read_catalog(); + let initial = engine + .evaluate_request( + "session-a", + ScenarioRequest::new(&good, Protocol::OpenaiResponsesHttp), + ) + .unwrap(); + let mut incompatible = read_decl(); + incompatible["parameters"]["properties"]["path"]["pattern"] = json!("^elsewhere/"); + let incompatible = ToolCatalog::from_request(&normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({ + "tools": [incompatible] + }), + )); + let error = engine + .evaluate_request( + "session-a", + ScenarioRequest::new(&incompatible, Protocol::OpenaiResponsesHttp), + ) + .unwrap_err(); + assert!( + error.to_string().contains("/properties/path/pattern"), + "{error}" + ); + let replay = engine + .evaluate_request( + "session-a", + ScenarioRequest::new(&good, Protocol::OpenaiResponsesHttp), + ) + .unwrap(); + assert_eq!(initial.plan.response_id, replay.plan.response_id); + assert_eq!(calls(&initial.plan), calls(&replay.plan)); + } + + #[test] + fn malformed_arguments_are_wired_as_a_function_call_with_invalid_json() { + let engine = engine( + spec() + .with_step( + "malformed", + CanonicalAction::BadToolCall { + mode: BadToolMode::MalformedJson, + expect_handling: FailureHandling::ToolError, + }, + ) + .with_step("done", final_answer()), + ); + let catalog = read_catalog(); + let issued = engine + .evaluate_request( + "session-a", + ScenarioRequest::new(&catalog, Protocol::OpenaiResponsesHttp), + ) + .unwrap(); + let events = calls(&issued.plan); + assert_eq!(events[0].name, "Read"); + assert!(!events[0].is_freeform()); + let Some(ToolCallPayload::MalformedRaw(raw)) = &events[0].payload else { + panic!("expected malformed wire input") + }; + assert!(serde_json::from_str::(raw).is_err()); + } + + #[test] + fn native_checkpoint_requires_matching_returned_evidence() { + let engine = engine( + spec() + .with_step( + "compact", + CanonicalAction::TriggerCompaction { + mode: CompactionMode::Native, + proof_marker: "checkpoint-proof".into(), + }, + ) + .with_step("done", final_answer()), + ); + let open = normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({"input": "start"}), + ); + let issued = engine.evaluate_normalized("session-a", &open).unwrap(); + let TurnEvent::NativeCompaction(compaction) = &issued.plan.events[0] else { + panic!("compaction expected"); + }; + assert_eq!( + engine + .evaluate_normalized("session-a", &open) + .unwrap() + .decision + .response_id, + issued.decision.response_id + ); + let follow = |marker: &str| { + normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({ + "previous_response_id": issued.decision.response_id, + "input": [{"type": "compaction", "id": compaction.id, "encrypted_content": format!("mock:{marker}")}] + }), + ) + }; + assert!(matches!( + engine.evaluate_normalized("session-a", &follow("wrong")), + Err(ScenarioError::InvalidCheckpoint) + )); + let text = normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({"input": compaction.summary}), + ); + let replay = engine.evaluate_normalized("session-a", &text).unwrap(); + assert_eq!(replay.plan.response_id, issued.plan.response_id); + let final_answer = engine + .evaluate_normalized("session-a", &follow("checkpoint-proof")) + .unwrap(); + assert!( + matches!(&final_answer.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + + #[test] + fn checkpoint_prompt_requires_a_returned_summary_instead_of_its_own_history() { + let marker = "checkpoint-proof"; + for protocol in [ + Protocol::OpenaiChatCompletions, + Protocol::AnthropicMessages, + Protocol::OpenaiResponsesHttp, + ] { + let engine = engine( + spec() + .with_step( + "compact", + CanonicalAction::TriggerCompaction { + mode: CompactionMode::Prompt, + proof_marker: marker.into(), + }, + ) + .with_step("done", final_answer()), + ); + let request = |body| normalize(protocol, Transport::Http, body); + let start = request(if protocol.is_responses() { + json!({"input": "start"}) + } else { + json!({"messages": [{"role": "user", "content": "start"}]}) + }); + let issued = engine.evaluate_normalized("session-a", &start).unwrap(); + let TurnEvent::Text { text: prompt, .. } = &issued.plan.events[0] else { + panic!("expected a compaction prompt"); + }; + let (_, checkpoint) = engine.compaction_output("session-a").unwrap(); + let follow = |summary: &str| { + request(match protocol { + Protocol::OpenaiChatCompletions => json!({"messages": [ + {"role": "assistant", "content": format!("[Conversation summary]\n{summary}")}, + {"role": "user", "content": "continue"} + ]}), + Protocol::AnthropicMessages => json!({ + "system": [{"type": "text", "text": summary}], + "messages": [{"role": "user", "content": "continue"}] + }), + _ => json!({"input": [{"role": "user", "content": summary}]}), + }) + }; + for stale in [ + prompt.clone(), + format!("{}_old {marker}", checkpoint.id), + format!("{} wrong-{marker}", checkpoint.id), + ] { + let replay = engine + .evaluate_normalized("session-a", &follow(&stale)) + .unwrap(); + assert_eq!(replay.plan.response_id, issued.plan.response_id); + } + let next = engine + .evaluate_normalized("session-a", &follow(&checkpoint.summary)) + .unwrap(); + assert_eq!( + next.adopted_checkpoint_id.as_deref(), + Some(checkpoint.id.as_str()) + ); + assert!( + matches!(&next.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + } + + #[test] + fn anthropic_single_tool_choice_disallows_a_parallel_batch() { + let engine = engine( + spec() + .with_step( + "batch", + CanonicalAction::ParallelBatch(vec![ + read("a.txt", "alpha"), + read("b.txt", "beta"), + ]), + ) + .with_step("done", final_answer()), + ); + let request = |disabled| { + normalize( + Protocol::AnthropicMessages, + Transport::Http, + json!({ + "messages": [{"role": "user", "content": "start"}], + "tool_choice": {"type": "auto", "disable_parallel_tool_use": disabled}, + "tools": [{"name": "Read", "input_schema": read_decl()["parameters"]}] + }), + ) + }; + let error = engine + .evaluate_normalized("session-a", &request(true)) + .unwrap_err(); + assert!( + error.to_string().contains("disallows multiple tool calls"), + "{error}" + ); + let batch = engine + .evaluate_normalized("session-a", &request(false)) + .unwrap(); + assert_eq!(calls(&batch.plan).len(), 2); + } + + #[cfg(unix)] + #[test] + fn large_output_uses_lane_seed_and_has_exact_utf8_byte_count() { + let bytes = 1024 * 1024 + 1; + let engine = engine( + spec() + .with_fixture( + "generated", + FixtureDef::LargeOutput { + pattern: "fixture 雪".into(), + }, + ) + .with_step( + "large", + CanonicalAction::LargeOutput { + fixture: "generated".into(), + bytes, + }, + ) + .with_step("done", final_answer()), + ); + engine + .register_session("session-b", "lane-1", "/bench/other") + .unwrap(); + engine + .register_session("session-c", "lane-2", "/bench/third") + .unwrap(); + let tool = |name: &str, key: &str| { + json!({"type": "function", "name": name, "parameters": { + "type": "object", "properties": {key: {"type": "string"}}, "required": [key], + "additionalProperties": false + }}) + }; + let req = |name, key| { + normalize( + Protocol::OpenaiResponsesHttp, + Transport::Http, + json!({"tools": [tool(name, key)]}), + ) + }; + let first = engine + .evaluate_normalized("session-a", &req("Shell", "command")) + .unwrap(); + let peer = engine + .evaluate_normalized("session-b", &req("exec_command", "cmd")) + .unwrap(); + let other = engine + .evaluate_normalized("session-c", &req("Shell", "command")) + .unwrap(); + let command = |plan: &TurnPlan, key: &str| { + let Some(ToolCallPayload::FunctionArgs(args)) = &calls(plan)[0].payload else { + panic!("expected function command"); + }; + args[key].as_str().unwrap().to_owned() + }; + let shell = command(&first.plan, "command"); + assert_eq!(shell, command(&peer.plan, "cmd")); + assert_ne!(shell, command(&other.plan, "command")); + assert_ne!( + first.decision.calls[0].call_id, + peer.decision.calls[0].call_id + ); + assert_ne!(first.decision.response_id, peer.decision.response_id); + let out = std::process::Command::new("sh") + .arg("-c") + .arg(&shell) + .output() + .unwrap(); + assert!(out.status.success(), "{:?}", out.stderr); + assert_eq!(out.stdout.len(), bytes); + assert!( + std::str::from_utf8(&out.stdout) + .unwrap() + .contains("fixture 雪") + ); + assert_eq!( + calls(&first.plan), + calls( + &engine + .evaluate_normalized("session-a", &req("Shell", "command")) + .unwrap() + .plan + ) + ); + } + + #[test] + fn rejected_tool_call_requires_the_configured_failure_evidence() { + let engine = engine( + spec() + .with_step( + "unknown", + CanonicalAction::UnknownTool { + name: "unlisted_fixture_tool".into(), + expect_handling: FailureHandling::ProtocolRejection, + }, + ) + .with_step("done", final_answer()), + ); + let catalog = read_catalog(); + let request = || ScenarioRequest::new(&catalog, Protocol::OpenaiResponsesHttp); + let issued = engine.evaluate_request("session-a", request()).unwrap(); + assert_eq!(calls(&issued.plan)[0].name, "unlisted_fixture_tool"); + let observation = RunnerObservation { + session_id: "session-a".into(), + attempt: issued.attempt, + call_id: issued.decision.calls[0].call_id.clone(), + kind: RunnerObservationKind::ProtocolRejection, + detail: "client rejected the unlisted tool".into(), + }; + for invalid in [ + RunnerObservation { + kind: RunnerObservationKind::HarnessTermination, + ..observation.clone() + }, + RunnerObservation { + attempt: issued.attempt + 1, + ..observation.clone() + }, + RunnerObservation { + call_id: "another-call".into(), + ..observation.clone() + }, + ] { + assert!(matches!( + engine.record_runner_observation("session-a", invalid), + Err(ScenarioError::InvalidRunnerObservation(_)) + )); + } + engine + .record_runner_observation("session-a", observation.clone()) + .unwrap(); + engine + .record_runner_observation("session-a", observation) + .unwrap(); + let done = engine.evaluate_request("session-a", request()).unwrap(); + assert!( + matches!(&done.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + + #[test] + fn validates_serialized_specs_and_parallel_conflicts() { + let spec = spec() + .with_step( + "batch", + CanonicalAction::ParallelBatch(vec![ + read("a.txt", "alpha"), + CanonicalAction::WriteFile { + path: "a.txt".into(), + content: "replacement\n".into(), + }, + ]), + ) + .with_step("done", final_answer()); + let serialized = serde_json::to_string(&spec).unwrap(); + let error = ScenarioSpec::from_json_str(&serialized) + .unwrap_err() + .to_string(); + assert!( + error.contains("parallel file access conflicts at \"a.txt\""), + "{error}" + ); + + #[cfg(feature = "rules")] + { + let parsed = ScenarioSpec::from_yaml_str( + r" +version: 1 +scenario: files +seed: 73 +fixture: files-v1 +track: native +steps: + - id: done + finalAnswer: + text: files complete + expectMarkers: [files complete] +", + ) + .unwrap(); + assert_eq!(parsed.steps[0].id, "done"); + } + } +} diff --git a/tools/mock-ai/src/scenario/tools.rs b/tools/mock-ai/src/scenario/tools.rs new file mode 100644 index 00000000000..c57e51497b1 --- /dev/null +++ b/tools/mock-ai/src/scenario/tools.rs @@ -0,0 +1,1461 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +//! Cross-harness tool catalog and schema-validated action binder. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt::Write as _; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use serde_json::{Value, json}; + +use crate::plan::ToolCallPayload; +use crate::protocol::{ + NormalizedRequest, NormalizedTool, Protocol, ToolDeclKind, tool_declarations, +}; +use crate::schema_synth::{SynthMode, synthesize_tool_arguments}; + +use super::{BadToolMode, BenchmarkTrack, digest, valid_path}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ToolKind { + Function, + Freeform, + ProviderBuiltin, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ToolDeclaration { + pub name: String, + pub namespace: Option, + pub kind: ToolKind, + pub schema: Option>, + pub schema_digest: Option, + pub format: Option, + description: Option, +} + +impl ToolDeclaration { + fn from_wire(value: &Value, namespace: Option<&str>, protocol: Protocol) -> Option { + let tool = value + .get("function") + .or_else(|| value.get("custom")) + .unwrap_or(value); + let kind = value.get("type").and_then(Value::as_str); + let schema = tool.get("parameters").or_else(|| tool.get("input_schema")); + let name = tool.get("name").and_then(Value::as_str).or(kind)?; + Some(Self::new( + name, + if protocol == Protocol::AnthropicMessages && kind == Some("custom") { + None + } else { + kind + }, + schema, + tool.get("format"), + tool.get("description").and_then(Value::as_str), + namespace, + )) + } + + fn new( + name: &str, + kind: Option<&str>, + schema: Option<&Value>, + format: Option<&Value>, + description: Option<&str>, + namespace: Option<&str>, + ) -> Self { + let kind = match kind { + Some("custom" | "freeform") => ToolKind::Freeform, + Some("function") | None => ToolKind::Function, + Some(_) => ToolKind::ProviderBuiltin, + }; + Self { + name: name.into(), + namespace: namespace.map(str::to_owned), + kind, + schema: schema.map(|v| Arc::new(v.clone())), + schema_digest: schema.map(digest), + format: format.cloned(), + description: description.map(str::to_owned), + } + } + + fn base_name(&self) -> &str { + if self.namespace.is_some() { + &self.name + } else { + self.name + .rsplit_once("__") + .map_or(&self.name, |(_, suffix)| suffix) + } + } + + fn has_property(&self, name: &str) -> bool { + self.schema + .as_deref() + .is_some_and(|schema| schema_has(schema, schema, "properties", name, 0)) + } + + fn requires(&self, name: &str) -> bool { + self.schema + .as_deref() + .is_some_and(|schema| schema_has(schema, schema, "required", name, 0)) + } + + fn format_matches(&self, grammar: impl FnOnce(&str) -> bool) -> bool { + match self + .format + .as_ref() + .and_then(|format| format["type"].as_str()) + { + None | Some("text") => true, + Some("grammar") => self.format.as_ref().is_some_and(|format| { + format["syntax"] == "lark" && format["definition"].as_str().is_some_and(grammar) + }), + Some(_) => false, + } + } +} + +fn schema_has(root: &Value, schema: &Value, keyword: &str, name: &str, depth: u8) -> bool { + depth < 8 + && (schema.get(keyword).is_some_and(|value| { + value.get(name).is_some() + || value + .as_array() + .is_some_and(|names| names.iter().any(|v| v == name)) + }) || schema["$ref"] + .as_str() + .and_then(|r| r.strip_prefix('#')) + .and_then(|p| root.pointer(p)) + .is_some_and(|target| schema_has(root, target, keyword, name, depth + 1)) + || ["allOf", "anyOf", "oneOf"].iter().any(|&composition| { + schema[composition].as_array().is_some_and(|branches| { + branches + .iter() + .any(|branch| schema_has(root, branch, keyword, name, depth + 1)) + }) + })) +} + +#[derive(Debug, Clone, Default)] +pub struct ToolCatalog { + declarations: Vec, +} + +impl ToolCatalog { + pub fn from_request(request: &NormalizedRequest) -> Self { + let tools = &request.raw_body["tools"]; + if !tools.is_array() { + return Self::from_normalized(&request.tools); + } + let declarations = tool_declarations(request.protocol, tools) + .filter_map(|(tool, namespace)| { + ToolDeclaration::from_wire(tool, namespace, request.protocol) + }) + .collect(); + Self { declarations } + } + + pub fn from_normalized(tools: &[NormalizedTool]) -> Self { + Self { + declarations: tools + .iter() + .map(|tool| { + let (kind, format) = match &tool.tool_kind { + ToolDeclKind::Function => (None, None), + ToolDeclKind::Freeform { format } => (Some("freeform"), format.as_ref()), + ToolDeclKind::ProviderBuiltin => (Some("builtin"), None), + }; + ToolDeclaration::new( + &tool.name, + kind, + tool.parameters.as_ref(), + format, + None, + tool.namespace.as_deref(), + ) + }) + .collect(), + } + } + + pub fn declarations(&self) -> &[ToolDeclaration] { + &self.declarations + } + + pub(crate) fn constraint_digest(&self, tool_choice: &Value) -> u64 { + let mut declarations: Vec<_> = self + .declarations + .iter() + .map(|tool| { + digest(&( + &tool.name, + &tool.namespace, + tool.kind, + tool.schema_digest, + &tool.format, + &tool.description, + )) + }) + .collect(); + declarations.sort_unstable(); + digest(&(declarations, tool_choice)) + } + + pub(crate) fn with_tool_choice(&self, choice: &Value) -> Result, ToolBindError> { + let kind = choice.as_str().or_else(|| choice["type"].as_str()); + match kind { + None | Some("auto" | "required" | "any") => Ok(Cow::Borrowed(self)), + Some("none") => Err(unsupported("tool call", vec!["tool_choice is none".into()])), + Some("function" | "custom" | "tool") => { + let name = choice["name"] + .as_str() + .or_else(|| choice["function"]["name"].as_str()) + .or_else(|| choice["custom"]["name"].as_str()) + .ok_or_else(|| { + unsupported("tool call", vec!["forced tool choice has no name".into()]) + })?; + let namespace = choice["namespace"].as_str(); + Ok(Cow::Owned(Self { + declarations: self + .declarations + .iter() + .filter(|tool| tool.name == name && tool.namespace.as_deref() == namespace) + .cloned() + .collect(), + })) + } + Some(kind) => Err(unsupported( + "tool call", + vec![format!("unsupported tool_choice {kind:?}")], + )), + } + } + + pub(crate) fn validate_replay( + &self, + cache: &ValidatorCache, + name: &str, + namespace: Option<&str>, + payload: &ToolCallPayload, + ) -> Result<(), ToolBindError> { + let mut matches = self + .declarations + .iter() + .filter(|tool| tool.name == name && tool.namespace.as_deref() == namespace); + let Some(tool) = matches.next().filter(|_| matches.next().is_none()) else { + return Err(unsupported( + name, + vec!["replay requires one matching tool declaration".into()], + )); + }; + match (tool.kind, payload) { + (ToolKind::Function, ToolCallPayload::FunctionArgs(args)) => cache + .validator(tool) + .and_then(|validator| { + validator.validate(args).map_err(|error| { + format!( + "argument {} violates schema {}", + error.instance_path(), + error.schema_path() + ) + }) + }) + .map_err(|error| unsupported(name, vec![error])), + (ToolKind::Freeform, ToolCallPayload::FreeformInput(_)) + if code_mode(tool).is_some() + || tool.base_name() == "apply_patch" + && tool.format_matches(is_patch_grammar) => + { + Ok(()) + } + _ => Err(unsupported( + name, + vec!["tool declaration no longer supports the issued payload".into()], + )), + } + } + + pub fn bind( + &self, + cache: &ValidatorCache, + track: BenchmarkTrack, + workspace: &Path, + actions: &[ToolAction<'_>], + ) -> Result, ToolBindError> { + for action in actions { + action.validate()?; + } + let mut differences = Vec::new(); + if actions.is_empty() { + return Err(ToolBindError::InvalidAction("empty tool batch".into())); + } + if track == BenchmarkTrack::Native { + let mut code = Vec::new(); + for tool in self.declarations.iter().filter(|t| t.base_name() == "exec") { + if let Some(encoding) = code_mode(tool) { + let recipe = Binding { + name: tool.name.clone(), + namespace: tool.namespace.clone(), + encoding, + slots: (0..actions.len()).collect(), + metadata: Metadata::default(), + }; + let payload = recipe.encode(workspace, actions)?; + match cache.validate(tool, &payload) { + Ok(()) => code.push(BoundToolCall { recipe, payload }), + Err(error) => differences.push(format!("{}: {error}", tool.name)), + } + } + } + match code.len() { + 1 => return Ok(code), + 0 => {} + _ => { + return Err(unsupported( + "exec", + vec!["multiple compatible code-mode declarations".into()], + )); + } + } + } + actions + .iter() + .enumerate() + .map(|(slot, action)| { + let mut differences = differences.clone(); + for preference in [Preference::Direct, Preference::Alternate] { + let mut matches = Vec::new(); + for tool in &self.declarations { + let Some(encoding) = direct_encoding(tool, track, *action, preference) + else { + continue; + }; + let recipe = Binding { + name: tool.name.clone(), + namespace: tool.namespace.clone(), + encoding, + slots: vec![slot], + metadata: Metadata { + title: tool.requires("title") + || (tool.base_name() == "exec" && tool.has_property("title")), + description: tool.requires("description"), + workdir: tool.requires("workdir"), + }, + }; + match recipe.encode(workspace, actions).and_then(|payload| { + cache + .validate(tool, &payload) + .map_err(|error| unsupported(action.label(), vec![error]))?; + Ok(payload) + }) { + Ok(payload) => matches.push(BoundToolCall { recipe, payload }), + Err(error) => differences + .push(format!("{} ({:?}): {error}", tool.name, tool.schema_digest)), + } + } + match matches.len() { + 1 => return Ok(matches.pop().expect("one match")), + 0 => {} + _ => { + return Err(unsupported( + action.label(), + vec![format!( + "multiple schema matches: {}", + matches + .iter() + .map(|m| m.recipe.name.as_str()) + .collect::>() + .join(", ") + )], + )); + } + } + } + if differences.is_empty() { + differences.extend(self.declarations.iter().map(|tool| { + let properties = tool + .schema + .as_ref() + .and_then(|s| s["properties"].as_object()) + .map(|props| props.keys().map(String::as_str).collect::>()) + .unwrap_or_default(); + format!("{} {:?} properties {properties:?}", tool.name, tool.kind) + })); + } + Err(unsupported(action.label(), differences)) + }) + .collect() + } + + pub(crate) fn bind_bad( + &self, + cache: &ValidatorCache, + mode: BadToolMode, + seed: u64, + ) -> Result { + let mut candidates: Vec<_> = self + .declarations + .iter() + .filter(|tool| tool.kind == ToolKind::Function && tool.schema.is_some()) + .collect(); + candidates.sort_by(|a, b| a.name.cmp(&b.name)); + for tool in candidates { + let schema = tool.schema.as_ref().expect("candidate has schema"); + let validator = cache + .validator(tool) + .map_err(|error| unsupported("bad tool call", vec![error]))?; + let mut rng = fastrand::Rng::with_seed(seed); + let valid = synthesize_tool_arguments(schema, &mut rng, SynthMode::Valid); + if !valid.is_object() || !validator.is_valid(&valid) { + continue; + } + let recipe = BadBinding { + name: tool.name.clone(), + namespace: tool.namespace.clone(), + schema: Arc::clone(schema), + mode, + }; + let payload = recipe.encode(seed); + if mode == BadToolMode::MalformedJson || !validator.is_valid(&payload.into_value()) { + return Ok(recipe); + } + } + Err(unsupported( + "bad tool call", + vec!["no function schema supports the requested violation".into()], + )) + } +} + +type CachedValidators = HashMap, Arc)>>; + +#[derive(Default)] +pub struct ValidatorCache { + validators: Mutex, +} + +impl ValidatorCache { + fn validator(&self, tool: &ToolDeclaration) -> Result, String> { + let schema = tool.schema.as_ref().ok_or("missing JSON Schema")?; + let digest = tool.schema_digest.expect("schema digest"); + let get = |validators: &Vec<(Arc, Arc)>| { + validators + .iter() + .find(|(cached, _)| cached == schema) + .map(|(_, validator)| Arc::clone(validator)) + }; + if let Some(validator) = self.validators.lock().unwrap().get(&digest).and_then(get) { + return Ok(validator); + } + let validator = Arc::new(jsonschema::validator_for(schema).map_err(|err| err.to_string())?); + let mut cache = self.validators.lock().unwrap(); + let bucket = cache.entry(digest).or_default(); + if let Some(existing) = get(bucket) { + return Ok(existing); + } + bucket.push((Arc::clone(schema), Arc::clone(&validator))); + Ok(validator) + } + + fn validate(&self, tool: &ToolDeclaration, payload: &CallPayload) -> Result<(), String> { + match payload { + CallPayload::Function(value) => self.validator(tool)?.validate(value).map_err(|err| { + format!( + "argument {} violates schema {}", + err.instance_path(), + err.schema_path() + ) + }), + CallPayload::Freeform(_) => Ok(()), + CallPayload::MalformedJson(_) => unreachable!("intentional violation uses bind_bad"), + } + } +} + +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ToolBindError { + #[error("unsupported {action}: {differences:?}")] + UnsupportedAction { + action: String, + differences: Vec, + }, + #[error("invalid action: {0}")] + InvalidAction(String), +} + +fn unsupported(action: &str, differences: Vec) -> ToolBindError { + ToolBindError::UnsupportedAction { + action: action.into(), + differences, + } +} + +#[derive(Clone, Copy, Debug)] +pub enum ToolAction<'a> { + Read { + path: &'a str, + }, + Write { + path: &'a str, + content: &'a str, + }, + Edit { + path: &'a str, + old: &'a str, + new: &'a str, + hunk: &'a EditHunk, + }, + Shell { + command: &'a str, + title: &'a str, + }, +} + +impl ToolAction<'_> { + fn label(self) -> &'static str { + match self { + Self::Read { .. } => "read file", + Self::Write { .. } => "write file", + Self::Edit { .. } => "edit file", + Self::Shell { .. } => "shell", + } + } + + fn validate(self) -> Result<(), ToolBindError> { + match self { + Self::Read { path } | Self::Write { path, .. } | Self::Edit { path, .. } + if !valid_path(path) => + { + Err(ToolBindError::InvalidAction(format!( + "invalid fixture path {path:?}" + ))) + } + Self::Edit { old, new, .. } if old.is_empty() || old == new => Err( + ToolBindError::InvalidAction("edit requires a nonempty changing match".into()), + ), + Self::Shell { command, title } + if command.trim().is_empty() + || command.contains('\0') + || title.trim().is_empty() => + { + Err(ToolBindError::InvalidAction( + "shell command and title must be nonempty".into(), + )) + } + _ => Ok(()), + } + } +} + +/// Complete lines touched by a unique edit. Native edit tools still receive the exact substrings. +#[derive(Debug)] +pub struct EditHunk { + before: String, + after: String, + ends_with_newline: bool, +} + +impl EditHunk { + pub fn new(content: &str, old: &str, new: &str) -> Result { + let mut matches = content.match_indices(old); + let Some((start, _)) = matches.next().filter(|_| !old.is_empty() && old != new) else { + return Err(ToolBindError::InvalidAction( + "edit has no changing match".into(), + )); + }; + if matches.next().is_some() + || content[start + + content[start..] + .chars() + .next() + .expect("nonempty match") + .len_utf8()..] + .contains(old) + { + return Err(ToolBindError::InvalidAction( + "edit matches more than once".into(), + )); + } + let end = start + old.len(); + let first = content[..start].rfind('\n').map_or(0, |i| i + 1); + let last = if old.ends_with('\n') && (new.is_empty() || new.ends_with('\n')) { + end + } else { + content[end..] + .find('\n') + .map_or(content.len(), |i| end + i + 1) + }; + Ok(Self { + before: content[first..last].into(), + after: format!("{}{}{}", &content[first..start], new, &content[end..last]), + ends_with_newline: content.ends_with('\n'), + }) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum CallPayload { + Function(Value), + Freeform(String), + MalformedJson(String), +} + +impl CallPayload { + pub(crate) fn into_value(self) -> Value { + match self { + Self::Function(value) => value, + Self::Freeform(text) | Self::MalformedJson(text) => Value::String(text), + } + } +} + +#[derive(Debug)] +pub struct BoundToolCall { + pub recipe: Binding, + pub payload: CallPayload, +} + +#[derive(Debug)] +pub struct Binding { + pub name: String, + pub namespace: Option, + pub slots: Vec, + encoding: Encoding, + metadata: Metadata, +} + +#[derive(Clone, Copy, Debug)] +enum Encoding { + Read(PathKey), + Write(PathKey), + Edit(PathKey, EditKeys), + Command(&'static str), + Patch(Option<&'static str>), + Code { freeform: bool }, +} + +#[derive(Clone, Copy, Debug)] +enum PathKey { + Path, + FilePath, +} + +#[derive(Clone, Copy, Debug)] +enum EditKeys { + Snake, + Camel, + Text, + List, +} + +#[derive(Debug, Default)] +struct Metadata { + title: bool, + description: bool, + workdir: bool, +} + +impl Binding { + pub(crate) fn is_code_mode(&self) -> bool { + matches!(self.encoding, Encoding::Code { .. }) + } + + pub(crate) fn encode( + &self, + workspace: &Path, + actions: &[ToolAction<'_>], + ) -> Result { + if let Encoding::Code { freeform } = self.encoding { + let code = code_mode_source(actions); + return Ok(if freeform { + CallPayload::Freeform(code) + } else { + CallPayload::Function(json!({ "code": code })) + }); + } + let action = actions[self.slots[0]]; + let path_arg = |path: &str, key| -> Result<(_, _), ToolBindError> { + match key { + PathKey::Path => Ok(("path", path.to_owned())), + PathKey::FilePath => Ok(("file_path", absolute_path(workspace, path)?)), + } + }; + let value = match (self.encoding, action) { + (Encoding::Read(key), ToolAction::Read { path }) => { + let (key, path) = path_arg(path, key)?; + json!({ key: path }) + } + (Encoding::Write(key), ToolAction::Write { path, content }) => { + let (key, path) = path_arg(path, key)?; + json!({ key: path, "content": content }) + } + (Encoding::Edit(path_key, edit_keys), ToolAction::Edit { path, old, new, .. }) => { + let (key, path) = path_arg(path, path_key)?; + match edit_keys { + EditKeys::Snake => json!({ key: path, "old_string": old, "new_string": new }), + EditKeys::Camel => json!({ key: path, "oldString": old, "newString": new }), + EditKeys::Text => json!({ key: path, "oldText": old, "newText": new }), + EditKeys::List => { + json!({ key: path, "edits": [{ "oldText": old, "newText": new }] }) + } + } + } + (Encoding::Command(key), ToolAction::Shell { command, title }) => { + self.command(workspace, key, command, title)? + } + (Encoding::Command(key), ToolAction::Read { path }) => self.command( + workspace, + key, + &format!("cat -- {}", shell_quote(path)), + "Read fixture file", + )?, + (Encoding::Patch(key), ToolAction::Write { .. } | ToolAction::Edit { .. }) => { + let patch = patch_text(action)?; + let Some(key) = key else { + return Ok(CallPayload::Freeform(patch)); + }; + json!({ key: patch }) + } + _ => unreachable!("binding selected for action"), + }; + Ok(CallPayload::Function(value)) + } + + fn command( + &self, + workspace: &Path, + key: &str, + command: &str, + title: &str, + ) -> Result { + let mut args = json!({ key: command }); + if self.metadata.title { + args["title"] = json!(title); + } + if self.metadata.description { + args["description"] = json!(title); + } + if self.metadata.workdir { + args["workdir"] = json!(absolute_path(workspace, "")?); + } + Ok(args) + } +} + +fn absolute_path(workspace: &Path, path: &str) -> Result { + if workspace.is_absolute() + && let Some(path) = workspace.join(path).to_str() + { + return Ok(path.into()); + } + Err(ToolBindError::InvalidAction( + "tool requires an absolute UTF-8 workspace path".into(), + )) +} + +pub(crate) fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Preference { + Direct, + Alternate, +} + +fn direct_encoding( + tool: &ToolDeclaration, + track: BenchmarkTrack, + action: ToolAction<'_>, + preference: Preference, +) -> Option { + let name = tool.base_name().to_ascii_lowercase(); + let path_key = if tool.has_property("path") { + Some(PathKey::Path) + } else if tool.has_property("file_path") { + Some(PathKey::FilePath) + } else { + None + }; + let edit_keys = if tool.has_property("edits") { + Some(EditKeys::List) + } else if tool.has_property("old_string") && tool.has_property("new_string") { + Some(EditKeys::Snake) + } else if tool.has_property("oldString") && tool.has_property("newString") { + Some(EditKeys::Camel) + } else if tool.has_property("oldText") && tool.has_property("newText") { + Some(EditKeys::Text) + } else { + None + }; + if track == BenchmarkTrack::SharedMcp { + if tool.kind != ToolKind::Function || preference != Preference::Direct { + return None; + } + let shared_name = if tool.name.starts_with("bench_") || name.starts_with("bench_") { + Some(name.trim_start_matches("bench_")) + } else if tool + .namespace + .as_deref() + .or_else(|| tool.name.rsplit_once("__").map(|(prefix, _)| prefix)) + .is_some_and(|ns| ns == "bench" || ns == "mcp__bench") + { + Some(name.as_str()) + } else { + None + }; + return match (shared_name?, action) { + ("read_file", ToolAction::Read { .. }) => Some(Encoding::Read(path_key?)), + ("write_file", ToolAction::Write { .. }) if tool.has_property("content") => { + Some(Encoding::Write(path_key?)) + } + ("edit_file", ToolAction::Edit { .. }) => Some(Encoding::Edit(path_key?, edit_keys?)), + ("exec_shell", ToolAction::Shell { .. }) if tool.has_property("command") => { + Some(Encoding::Command("command")) + } + _ => None, + }; + } + + if preference == Preference::Alternate { + return match (name.as_str(), tool.kind, action) { + ("exec_command", ToolKind::Function, ToolAction::Read { .. }) + if tool.has_property("cmd") => + { + Some(Encoding::Command("cmd")) + } + ("shell_command", ToolKind::Function, ToolAction::Read { .. }) + if tool.has_property("command") => + { + Some(Encoding::Command("command")) + } + ( + "apply_patch" | "applypatch", + ToolKind::Function, + ToolAction::Edit { .. } | ToolAction::Write { .. }, + ) if tool.has_property("patch") => Some(Encoding::Patch(Some("patch"))), + ( + "apply_patch" | "applypatch", + ToolKind::Function, + ToolAction::Edit { .. } | ToolAction::Write { .. }, + ) if tool.has_property("input") => Some(Encoding::Patch(Some("input"))), + ( + "apply_patch", + ToolKind::Freeform, + ToolAction::Edit { .. } | ToolAction::Write { .. }, + ) if tool.format_matches(|grammar| { + grammar.contains("*** Begin Patch") && grammar.contains("*** End Patch") + }) => + { + Some(Encoding::Patch(None)) + } + _ => None, + }; + } + if tool.kind != ToolKind::Function { + return None; + } + match (name.as_str(), action) { + ("read", ToolAction::Read { .. }) => Some(Encoding::Read(path_key?)), + ("write", ToolAction::Write { .. }) if tool.has_property("content") => { + Some(Encoding::Write(path_key?)) + } + ("edit", ToolAction::Edit { .. }) => Some(Encoding::Edit(path_key?, edit_keys?)), + ("bash" | "shell" | "shell_command", ToolAction::Shell { .. }) + if tool.has_property("command") => + { + Some(Encoding::Command("command")) + } + ("exec_command", ToolAction::Shell { .. }) if tool.has_property("cmd") => { + Some(Encoding::Command("cmd")) + } + ("exec", ToolAction::Shell { .. }) + if tool.has_property("command") && !tool.has_property("code") => + { + Some(Encoding::Command("command")) + } + _ => None, + } +} + +fn is_patch_grammar(grammar: &str) -> bool { + grammar.contains("*** Begin Patch") && grammar.contains("*** End Patch") +} + +fn code_mode(tool: &ToolDeclaration) -> Option { + if tool + .description + .as_deref() + .is_some_and(|s| s.contains("Python") && !s.contains("JavaScript")) + { + return None; + } + match tool.kind { + ToolKind::Function if tool.has_property("code") && !tool.has_property("command") => { + Some(Encoding::Code { freeform: false }) + } + ToolKind::Freeform + if (tool + .format + .as_ref() + .is_some_and(|format| format["type"] == "grammar") + || tool + .description + .as_deref() + .is_some_and(|description| description.contains("JavaScript"))) + && tool.format_matches(|grammar| { + grammar.contains("plain_source: SOURCE") && grammar.contains(r"\/\/ @exec:") + }) => + { + Some(Encoding::Code { freeform: true }) + } + _ => None, + } +} + +fn code_mode_source(actions: &[ToolAction<'_>]) -> String { + let mut code = String::from("text(JSON.stringify(await Promise.all([\n"); + for (slot, action) in actions.iter().enumerate() { + let (tool, input) = match *action { + ToolAction::Read { path } => ("Read", json!({ "path": path })), + ToolAction::Write { path, content } => { + ("Write", json!({ "path": path, "content": content })) + } + ToolAction::Edit { path, old, new, .. } => ( + "Edit", + json!({ "path": path, "old_string": old, "new_string": new }), + ), + ToolAction::Shell { command, title } => { + ("Shell", json!({ "command": command, "title": title })) + } + }; + writeln!( + code, + " (async () => ({{slot:{slot}, result:await tools.{tool}({input})}}))()," + ) + .expect("writing to String"); + } + code.push_str("])));"); + code +} + +fn patch_text(action: ToolAction<'_>) -> Result { + let preserves_line_endings = match action { + ToolAction::Write { content, .. } => content.is_empty() || content.ends_with('\n'), + ToolAction::Edit { hunk, .. } => { + hunk.ends_with_newline && (hunk.after.is_empty() || hunk.after.ends_with('\n')) + } + _ => unreachable!("patch action"), + }; + if !preserves_line_endings { + return Err(unsupported( + action.label(), + vec!["apply_patch cannot preserve the requested missing final newline".into()], + )); + } + let mut patch = String::from("*** Begin Patch\n"); + match action { + ToolAction::Write { path, content } => { + writeln!(patch, "*** Add File: {path}").expect("writing to String"); + patch_lines(&mut patch, '+', content); + } + ToolAction::Edit { path, hunk, .. } => { + writeln!(patch, "*** Update File: {path}\n@@").expect("writing to String"); + patch_lines(&mut patch, '-', &hunk.before); + patch_lines(&mut patch, '+', &hunk.after); + } + _ => unreachable!("patch action"), + } + patch.push_str("*** End Patch"); + if valid_patch(&patch) { + Ok(patch) + } else { + Err(unsupported( + action.label(), + vec!["generated patch does not match apply_patch grammar".into()], + )) + } +} + +fn patch_lines(patch: &mut String, prefix: char, content: &str) { + for line in content.split_terminator('\n') { + writeln!(patch, "{prefix}{line}").expect("writing to String"); + } +} + +// This is the Add/Update subset of Codex's grammar that the binder emits. +fn valid_patch(patch: &str) -> bool { + let Some(body) = patch + .strip_prefix("*** Begin Patch\n") + .and_then(|s| s.strip_suffix("\n*** End Patch")) + else { + return false; + }; + let mut lines = body.split('\n'); + let Some(header) = lines.next() else { + return false; + }; + if let Some(path) = header.strip_prefix("*** Add File: ") { + return valid_path(path) && lines.all(|line| line.starts_with('+')); + } + if let Some(path) = header.strip_prefix("*** Update File: ") { + return valid_path(path) + && lines.next() == Some("@@") + && lines.clone().next().is_some() + && lines.all(|line| line.starts_with(['-', '+'])); + } + false +} + +#[derive(Debug)] +pub(crate) struct BadBinding { + pub(crate) name: String, + pub(crate) namespace: Option, + schema: Arc, + mode: BadToolMode, +} + +impl BadBinding { + pub(crate) fn encode(&self, seed: u64) -> CallPayload { + let mode = match self.mode { + BadToolMode::MissingRequired => SynthMode::MissingRequired, + BadToolMode::WrongType => SynthMode::WrongType, + BadToolMode::MalformedJson => SynthMode::MalformedJson, + }; + let value = + synthesize_tool_arguments(&self.schema, &mut fastrand::Rng::with_seed(seed), mode); + match (self.mode, value) { + (BadToolMode::MalformedJson, Value::String(raw)) => CallPayload::MalformedJson(raw), + (_, value) => CallPayload::Function(value), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Transport, normalize_request}; + + fn function(name: &str, properties: Value, required: &[&str]) -> Value { + json!({"type": "function", "name": name, "parameters": { + "type": "object", "properties": properties, "required": required, "additionalProperties": false + }}) + } + + fn catalog(tools: Vec) -> ToolCatalog { + let request = normalize_request( + 0, + Protocol::OpenaiResponsesHttp, + Transport::Http, + "/v1/responses".into(), + Default::default(), + Default::default(), + json!({"tools": tools}), + ); + ToolCatalog::from_request(&request) + } + + #[test] + fn binds_native_file_and_shell_shapes() { + struct Harness { + name: &'static str, + tools: [&'static str; 4], + path_key: &'static str, + edit: EditKeys, + shell_metadata: Option<&'static str>, + } + use EditKeys::{Camel, List, Snake, Text}; + let harnesses = [ + Harness { + name: "Maka Direct", + tools: ["Read", "Write", "Edit", "Shell"], + path_key: "path", + edit: Snake, + shell_metadata: Some("title"), + }, + Harness { + name: "Claude Code", + tools: ["Read", "Write", "Edit", "Bash"], + path_key: "file_path", + edit: Snake, + shell_metadata: Some("description"), + }, + Harness { + name: "OpenCode v2", + tools: ["read", "write", "edit", "shell"], + path_key: "path", + edit: Camel, + shell_metadata: Some("description"), + }, + Harness { + name: "Pi 1.0", + tools: ["read", "write", "edit", "bash"], + path_key: "path", + edit: List, + shell_metadata: None, + }, + Harness { + name: "Pi-Durable", + tools: ["read", "write", "edit", "bash"], + path_key: "path", + edit: List, + shell_metadata: None, + }, + Harness { + name: "Dim", + tools: ["read", "write", "edit", "exec"], + path_key: "path", + edit: Text, + shell_metadata: None, + }, + Harness { + name: "DeepSeek Harness", + tools: ["read", "write", "edit", "bash"], + path_key: "file_path", + edit: Snake, + shell_metadata: Some("description"), + }, + Harness { + name: "ZCode", + tools: ["Read", "Write", "Edit", "Bash"], + path_key: "file_path", + edit: Snake, + shell_metadata: None, + }, + Harness { + name: "Kimi Code TS", + tools: ["Read", "Write", "Edit", "Shell"], + path_key: "path", + edit: Snake, + shell_metadata: None, + }, + ]; + let cache = ValidatorCache::default(); + let workspace = Path::new("/bench/work"); + let hunk = EditHunk::new("marker\n", "marker", "changed").unwrap(); + for h in harnesses { + let [read, write, edit, shell] = h.tools; + let key = h.path_key; + let file = if key == "file_path" { + "/bench/work/src/a.txt" + } else { + "src/a.txt" + }; + let string = json!({"type": "string"}); + let mut read_props = json!({key: string}); + if h.name == "Kimi Code TS" { + read_props["line_offset"] = json!({"type": "integer"}); + read_props["n_lines"] = json!({"type": "integer"}); + } + let (edit_props, required, expected) = match h.edit { + Snake => ( + json!({key: string, "old_string": string, "new_string": string}), + vec![key, "old_string", "new_string"], + json!({key: file, "old_string": "marker", "new_string": "changed"}), + ), + Camel => ( + json!({key: string, "oldString": string, "newString": string}), + vec![key, "oldString", "newString"], + json!({key: file, "oldString": "marker", "newString": "changed"}), + ), + Text => ( + json!({key: string, "oldText": string, "newText": string}), + vec![key, "oldText", "newText"], + json!({key: file, "oldText": "marker", "newText": "changed"}), + ), + List => ( + json!({key: string, "edits": {"type": "array", "minItems": 1, "items": { + "type": "object", "required": ["oldText", "newText"], + "properties": {"oldText": string, "newText": string}, "additionalProperties": false + }}}), + vec![key, "edits"], + json!({key: file, "edits": [{"oldText": "marker", "newText": "changed"}]}), + ), + }; + let mut shell_props = json!({"command": string}); + let mut shell_expected = json!({"command": "printf ok"}); + let mut shell_required = vec!["command"]; + if let Some(metadata) = h.shell_metadata { + shell_props[metadata] = json!({"type": "string", "minLength": 1}); + if h.name == "OpenCode v2" { + shell_required.push(metadata); + shell_expected[metadata] = json!("fixture"); + } + } + let catalog = catalog(vec![ + function(read, read_props, &[key]), + function( + write, + json!({key: string, "content": string}), + &[key, "content"], + ), + function(edit, edit_props, &required), + function(shell, shell_props, &shell_required), + ]); + let actions = [ + ToolAction::Read { path: "src/a.txt" }, + ToolAction::Write { + path: "src/a.txt", + content: "data\n", + }, + ToolAction::Edit { + path: "src/a.txt", + old: "marker", + new: "changed", + hunk: &hunk, + }, + ToolAction::Shell { + command: "printf ok", + title: "fixture", + }, + ]; + let actual = catalog + .bind(&cache, BenchmarkTrack::Native, workspace, &actions) + .unwrap_or_else(|error| panic!("{}: {error}", h.name)); + assert_eq!( + actual + .into_iter() + .map(|call| (call.recipe.name, call.payload)) + .collect::>(), + h.tools + .into_iter() + .zip([ + json!({key: file}), + json!({key: file, "content": "data\n"}), + expected, + shell_expected, + ]) + .map(|(name, value)| (name.to_owned(), CallPayload::Function(value))) + .collect::>(), + "{}", + h.name + ); + } + } + + #[test] + fn maka_exec_wraps_slots_and_dim_exec_stays_a_shell_tool() { + let string = json!({"type": "string"}); + let shell = function("exec", json!({"command": string}), &["command"]); + let ambiguous_exec = function( + "exec", + json!({"command": string, "code": string}), + &["command"], + ); + let function_exec = function("exec", json!({"code": string}), &["code"]); + let freeform_exec = json!({"type": "custom", "name": "exec", "format": { + "type": "grammar", "syntax": "lark", + "definition": r"start: pragma_source | plain_source +plain_source: SOURCE +PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/ +SOURCE: /[\s\S]+/" + }}); + let read = ToolAction::Read { path: "src/a.txt" }; + let run = ToolAction::Shell { + command: "printf ok", + title: "fixture", + }; + let validators = ValidatorCache::default(); + let workspace = Path::new("/bench/work"); + let dim = catalog(vec![shell]); + assert!(matches!( + dim.bind(&validators, BenchmarkTrack::Native, workspace, &[read]), + Err(ToolBindError::UnsupportedAction { .. }) + )); + assert_eq!( + dim.bind(&validators, BenchmarkTrack::Native, workspace, &[run]) + .unwrap()[0] + .payload, + CallPayload::Function(json!({"command": "printf ok"})) + ); + assert!(matches!( + catalog(vec![ambiguous_exec]).bind( + &validators, + BenchmarkTrack::Native, + workspace, + &[run] + ), + Err(ToolBindError::UnsupportedAction { .. }) + )); + for (tool, freeform) in [(function_exec, false), (freeform_exec, true)] { + let maka = catalog(vec![tool]); + let bound = maka + .bind(&validators, BenchmarkTrack::Native, workspace, &[read, run]) + .unwrap(); + let [only] = bound.as_slice() else { + panic!("expected one Code Mode call") + }; + assert_eq!(only.recipe.slots, [0, 1]); + let code = concat!( + "text(JSON.stringify(await Promise.all([\n", + " (async () => ({slot:0, result:await tools.Read({\"path\":\"src/a.txt\"})}))(),\n", + " (async () => ({slot:1, result:await tools.Shell({\"command\":\"printf ok\",\"title\":\"fixture\"})}))(),\n", + "])));", + ); + assert_eq!( + only.payload, + if freeform { + CallPayload::Freeform(code.into()) + } else { + CallPayload::Function(json!({"code": code})) + } + ); + } + } + + #[test] + fn codex_patch_preserves_literal_line_prefixes_and_read_uses_shell_schema() { + let codex = catalog(vec![ + json!({"type": "custom", "name": "apply_patch", "format": { + "type": "grammar", "syntax": "lark", + "definition": "start: \"*** Begin Patch\" hunk \"*** End Patch\"" + }}), + function("exec_command", json!({"cmd": {"type": "string"}}), &["cmd"]), + ]); + let hunk = EditHunk::new("prefix old\nend\n", "old", "new\n*** End Patch").unwrap(); + let actions = [ + ToolAction::Edit { + path: "src/a.txt", + old: "old", + new: "new\n*** End Patch", + hunk: &hunk, + }, + ToolAction::Write { + path: "a.txt", + content: "---\n", + }, + ToolAction::Read { path: "a'b.txt" }, + ]; + let calls = codex + .bind( + &ValidatorCache::default(), + BenchmarkTrack::Native, + Path::new("/repo"), + &actions, + ) + .unwrap(); + assert_eq!(calls[0].payload, CallPayload::Freeform( + "*** Begin Patch\n*** Update File: src/a.txt\n@@\n-prefix old\n+prefix new\n+*** End Patch\n*** End Patch".into() + )); + assert_eq!( + calls[1].payload, + CallPayload::Freeform( + "*** Begin Patch\n*** Add File: a.txt\n+---\n*** End Patch".into() + ) + ); + assert_eq!( + calls[2].payload, + CallPayload::Function(json!({"cmd": "cat -- 'a'\\''b.txt'"})) + ); + assert!(!valid_patch( + "*** Begin Patch\n*** Update File: a.txt\n@@\n*** End Patch" + )); + } + + #[test] + fn shared_mcp_matches_prefix_and_rejects_schema_incompatible_arguments() { + let catalog = catalog(vec![ + function("Read", json!({"path": {"type": "string"}}), &["path"]), + function( + "mcp__bench__read_file", + json!({"path": {"type": "string", "pattern": "^src/"}}), + &["path"], + ), + function( + "bench_write_file", + json!({"path": {"type": "string"}, "content": {"type": "string"}}), + &["path", "content"], + ), + function( + "bench_edit_file", + json!({"path": {"type": "string"}, "old_string": {"type": "string"}, "new_string": {"type": "string"}}), + &["path", "old_string", "new_string"], + ), + function( + "mcp__bench__exec_shell", + json!({"command": {"type": "string"}}), + &["command"], + ), + ]); + let cache = ValidatorCache::default(); + let hunk = EditHunk::new("old\n", "old", "new").unwrap(); + let good = catalog + .bind( + &cache, + BenchmarkTrack::SharedMcp, + Path::new("/repo"), + &[ + ToolAction::Read { path: "src/a.txt" }, + ToolAction::Write { + path: "a.txt", + content: "", + }, + ToolAction::Edit { + path: "src/a.txt", + old: "old", + new: "new", + hunk: &hunk, + }, + ToolAction::Shell { + command: "printf ok", + title: "fixture", + }, + ], + ) + .unwrap(); + assert_eq!(good[0].recipe.name, "mcp__bench__read_file"); + assert_eq!(good[1].recipe.name, "bench_write_file"); + assert_eq!(good[2].recipe.name, "bench_edit_file"); + assert_eq!( + good[2].payload, + CallPayload::Function( + json!({"path": "src/a.txt", "old_string": "old", "new_string": "new"}) + ) + ); + assert_eq!(good[3].recipe.name, "mcp__bench__exec_shell"); + assert_eq!( + good[3].payload, + CallPayload::Function(json!({"command": "printf ok"})) + ); + let error = catalog + .bind( + &cache, + BenchmarkTrack::SharedMcp, + Path::new("/repo"), + &[ToolAction::Read { + path: "other/a.txt", + }], + ) + .unwrap_err(); + assert!( + error.to_string().contains("/properties/path/pattern"), + "{error}" + ); + assert!(matches!( + EditHunk::new("aaa", "aa", "b"), + Err(ToolBindError::InvalidAction(_)) + )); + } +} diff --git a/tools/mock-ai/src/schema_synth.rs b/tools/mock-ai/src/schema_synth.rs index b88af9906f7..076f0ffe1c0 100644 --- a/tools/mock-ai/src/schema_synth.rs +++ b/tools/mock-ai/src/schema_synth.rs @@ -61,6 +61,7 @@ impl WirePoisonConfig { /// /// For `SynthMode::MalformedJson`, returns a `Value::String` containing intentionally broken JSON /// (which `ToolCallSpec::arguments_string()` transmits verbatim on the wire). +const MAX_SYNTH_DEPTH: usize = 16; const MAX_SYNTH_NODES: usize = 512; const MAX_SYNTH_BYTES: usize = 256 * 1024; @@ -101,15 +102,13 @@ impl SynthBudget { fn charge_value(&mut self, val: &Value) -> bool { let (nodes, bytes) = value_cost(val); let extra_nodes = nodes.saturating_sub(1); - if extra_nodes > self.nodes || bytes > self.bytes { - self.nodes = self.nodes.saturating_sub(extra_nodes); - self.bytes = 0; + if extra_nodes > self.nodes { + self.nodes = 0; self.exceeded = true; return false; } self.nodes -= extra_nodes; - self.bytes -= bytes; - true + self.charge_bytes(bytes) } } @@ -127,6 +126,10 @@ pub fn try_synthesize_tool_arguments( "schema exceeded synthesis budget (nodes={MAX_SYNTH_NODES}, bytes={MAX_SYNTH_BYTES})" )); } + if matches!(mode, SynthMode::Valid) { + let validator = jsonschema::validator_for(schema).map_err(|e| e.to_string())?; + validator.validate(&val).map_err(|e| e.to_string())?; + } Ok(val) } @@ -146,8 +149,8 @@ fn synthesize_inner( budget: &mut SynthBudget, ) -> Value { if matches!(mode, SynthMode::MalformedJson) { - let mut partial = synthesize_value(schema, None, rng, 0, budget).to_string(); - if partial.len() > 6 { + let mut partial = synthesize_value(schema, schema, None, rng, 0, budget).to_string(); + if partial.starts_with('{') && partial.len() > 6 { let cut = partial.floor_char_boundary(partial.len() / 2); partial.truncate(cut.max(2)); } else { @@ -156,21 +159,22 @@ fn synthesize_inner( return Value::String(partial); } - let mut val = synthesize_value(schema, None, rng, 0, budget); - if !val.is_object() { - let mut obj = Map::new(); - obj.insert("value".into(), val); - val = Value::Object(obj); - } - + let mut val = synthesize_value(schema, schema, None, rng, 0, budget); match mode { SynthMode::Valid | SynthMode::MalformedJson => val, SynthMode::MissingRequired => { if let Value::Object(ref mut map) = val { - if let Some(req) = schema.get("required").and_then(Value::as_array) - && let Some(first_req) = req.first().and_then(Value::as_str) + if let Ok(validator) = jsonschema::validator_for(schema) + && let Some(key) = map + .keys() + .find(|key| { + let mut without = map.clone(); + without.remove(*key); + !validator.is_valid(&Value::Object(without)) + }) + .cloned() { - map.remove(first_req); + map.remove(&key); return val; } if let Some(first_key) = map.keys().next().cloned() { @@ -180,19 +184,26 @@ fn synthesize_inner( val } SynthMode::WrongType => { - if let Value::Object(ref mut map) = val { - if let Some((_, first_val)) = map.iter_mut().next() { - *first_val = match first_val { - Value::String(_) => json!(999_999), - Value::Number(_) => Value::String("not_a_number".into()), - Value::Bool(_) => Value::String("not_a_bool".into()), - Value::Array(_) => json!({"unexpected": "object"}), - Value::Object(_) => json!(["unexpected_array"]), - Value::Null => json!(true), - }; - } else { - map.insert("invalid_field".into(), json!(12345)); + let Some(map) = val.as_object() else { + return wrong_type(&val); + }; + let validator = jsonschema::validator_for(schema).ok(); + let keys: Vec<_> = map.keys().cloned().collect(); + for key in &keys { + let replacement = wrong_type(&val[key]); + let previous = std::mem::replace(&mut val[key], replacement); + if validator + .as_ref() + .is_none_or(|validator| !validator.is_valid(&val)) + { + return val; } + val[key] = previous; + } + if let Some(first) = keys.first() { + val[first] = wrong_type(&val[first]); + } else { + val["invalid_field"] = json!(12345); } val } @@ -210,41 +221,130 @@ fn synthesize_inner( } } +fn wrong_type(value: &Value) -> Value { + match value { + Value::String(_) => json!(999_999), + Value::Number(_) => json!("not_a_number"), + Value::Bool(_) => json!("not_a_bool"), + Value::Array(_) => json!({"unexpected": "object"}), + Value::Object(_) => json!(["unexpected_array"]), + Value::Null => json!(true), + } +} + fn value_cost(val: &Value) -> (usize, usize) { match val { - Value::String(s) => (1, s.len() + 2), - Value::Array(a) => a.iter().fold((1usize, 2usize), |(n, b), item| { - let (in_, ib) = value_cost(item); - ( - n.saturating_add(in_), - b.saturating_add(ib).saturating_add(1), - ) - }), - Value::Object(m) => m.iter().fold((1usize, 2usize), |(n, b), (k, v)| { - let (vn, vb) = value_cost(v); - ( - n.saturating_add(vn), - b.saturating_add(k.len()) - .saturating_add(vb) - .saturating_add(4), - ) - }), - _ => (1, 8), + Value::String(s) => (1, escaped_string_bytes(s) + 2), + Value::Array(a) => { + a.iter() + .fold((1usize, 2 + a.len().saturating_sub(1)), |(n, b), item| { + let (in_, ib) = value_cost(item); + (n.saturating_add(in_), b.saturating_add(ib)) + }) + } + Value::Object(m) => { + m.iter() + .fold((1usize, 2 + m.len().saturating_sub(1)), |(n, b), (k, v)| { + let (vn, vb) = value_cost(v); + ( + n.saturating_add(vn), + b.saturating_add(escaped_string_bytes(k)) + .saturating_add(vb) + .saturating_add(3), + ) + }) + } + Value::Number(number) => (1, number.to_string().len()), + Value::Bool(false) => (1, 5), + Value::Bool(true) | Value::Null => (1, 4), } } +fn escaped_string_bytes(text: &str) -> usize { + text.bytes().fold(text.len(), |bytes, byte| { + bytes + + match byte { + b'"' | b'\\' | b'\x08' | b'\t' | b'\n' | b'\x0c' | b'\r' => 1, + 0..=0x1f => 5, + _ => 0, + } + }) +} + fn synthesize_value( + root: &Value, schema: &Value, prop_name: Option<&str>, rng: &mut fastrand::Rng, depth: usize, budget: &mut SynthBudget, ) -> Value { - if depth >= 8 || !budget.charge_node() { + if depth >= MAX_SYNTH_DEPTH || !budget.charge_node() { budget.exceeded = true; return Value::String("budget_cap".into()); } + let resolved = resolve_composition(root, schema, depth, budget); + let schema = resolved.as_ref(); + + if let Some(alts) = schema + .get("oneOf") + .or_else(|| schema.get("anyOf")) + .and_then(Value::as_array) + && !alts.is_empty() + { + let mut base = schema.as_object().expect("composition object").clone(); + let keyword = if base.contains_key("oneOf") { + "oneOf" + } else { + "anyOf" + }; + base.remove(keyword); + let base = Value::Object(base); + let candidates = (0..alts.len()) + .cycle() + .skip(rng.usize(..alts.len())) + .take(alts.len()); + let validation_schema = schema_with_definitions(root, schema); + let validator = jsonschema::validator_for(&validation_schema).ok(); + let output_bytes = budget.bytes; + let mut fallback = (Value::Null, output_bytes); + let mut branch_exceeded = false; + for i in candidates { + if budget.exceeded || budget.bytes == 0 || !budget.charge_node() { + break; + } + let branch = resolve_composition(root, &alts[i], depth + 1, budget); + let combined = intersect(&base, &branch); + if combined != Value::Bool(false) { + let mut candidate = + synthesize_value(root, &combined, prop_name, rng, depth + 1, budget); + if let Some(validator) = &validator + && !budget.exceeded + && (validator.is_valid(&candidate) + || vary_enum( + root, + &combined, + &mut candidate, + validator, + budget, + depth + 1, + )) + { + return candidate; + } + fallback = (candidate, budget.bytes); + } + // Rejected output is discarded, but its search work still counts. + branch_exceeded |= std::mem::take(&mut budget.exceeded); + budget.bytes = output_bytes; + } + budget.exceeded |= branch_exceeded; + let (fallback, fallback_bytes) = fallback; + budget.bytes = fallback_bytes; + return fallback; + } + if let Some(c) = schema.get("const") { if !budget.charge_value(c) { return Value::String("budget_cap".into()); @@ -260,46 +360,16 @@ fn synthesize_value( } return chosen.clone(); } - if let Some(alts) = schema - .get("anyOf") - .or_else(|| schema.get("oneOf")) - .and_then(Value::as_array) - { - let non_null: Vec<&Value> = alts - .iter() - .filter(|v| v.get("type").and_then(Value::as_str) != Some("null")) - .collect(); - let pool = if non_null.is_empty() { - alts.iter().collect::>() - } else { - non_null - }; - if !pool.is_empty() { - let chosen = pool[rng.usize(0..pool.len())]; - return synthesize_value(chosen, prop_name, rng, depth + 1, budget); - } - } - if let Some(all_of) = schema.get("allOf").and_then(Value::as_array) { - let mut merged = Map::new(); - for sub in all_of { - if budget.nodes == 0 || budget.bytes == 0 { - budget.exceeded = true; - break; - } - if let Value::Object(m) = synthesize_value(sub, prop_name, rng, depth + 1, budget) { - for (k, v) in m { - merged.insert(k, v); - } - } - } - if !merged.is_empty() { - return Value::Object(merged); - } - } - - let ty = resolve_schema_type(schema); + let ty = if schema == &Value::Bool(false) { + "null" + } else { + resolve_schema_type(schema) + }; match ty { "object" => { + if !budget.charge_bytes(2) { + return Value::String("budget_cap".into()); + } let mut out = Map::new(); let required: Vec<&str> = schema .get("required") @@ -309,90 +379,311 @@ fn synthesize_value( if let Some(props) = schema.get("properties").and_then(Value::as_object) { for (key, prop_schema) in props { let is_req = required.contains(&key.as_str()); - if is_req { - if budget.nodes == 0 || budget.bytes == 0 { - budget.exceeded = true; - break; - } - let _ = budget.charge_bytes(key.len() + 4); - out.insert( - key.clone(), - synthesize_value(prop_schema, Some(key), rng, depth + 1, budget), - ); - } else if rng.f64() < 0.35 && budget.nodes > 0 && budget.bytes > 0 { - let _ = budget.charge_bytes(key.len() + 4); - out.insert( - key.clone(), - synthesize_value(prop_schema, Some(key), rng, depth + 1, budget), - ); + if !is_req && !(rng.f64() < 0.35 && budget.nodes > 0 && budget.bytes > 0) { + continue; } + if !budget + .charge_bytes(escaped_string_bytes(key) + 3 + usize::from(!out.is_empty())) + { + break; + } + let value = + synthesize_value(root, prop_schema, Some(key), rng, depth + 1, budget); + if budget.exceeded { + break; + } + out.insert(key.clone(), value); } } for req_key in required { if !out.contains_key(req_key) { - if !budget.charge_node() { + if budget.exceeded + || !budget.charge_node() + || !budget.charge_bytes( + escaped_string_bytes(req_key) + 3 + usize::from(!out.is_empty()), + ) + { + break; + } + let val = synthesize_string(&Value::Null, Some(req_key), rng, budget); + if budget.exceeded { break; } - let val = synthesize_string(&json!({}), Some(req_key), rng); - let _ = budget.charge_bytes(req_key.len() + val.to_string().len() + 4); out.insert(req_key.to_string(), val); } } Value::Object(out) } "array" => { - let min_items = schema.get("minItems").and_then(Value::as_u64).unwrap_or(1) as usize; + let min_items = schema.get("minItems").and_then(Value::as_u64).unwrap_or(0) as usize; let max_items = schema .get("maxItems") .and_then(Value::as_u64) - .unwrap_or((min_items + 2) as u64) as usize; + .unwrap_or(min_items.saturating_add(2) as u64) as usize; let lo = min_items.min(64); let hi = max_items.clamp(lo, lo.clamp(4, 64)); let count = if hi > lo { rng.usize(lo..=hi) } else { lo }; - let item_schema = schema - .get("items") - .cloned() - .unwrap_or_else(|| json!({"type": "string"})); + if !budget.charge_bytes(2 + count.saturating_sub(1)) { + return Value::String("budget_cap".into()); + } + let default_item = Value::Null; + let item_schema = schema.get("items").unwrap_or(&default_item); let mut items = Vec::with_capacity(count); for _ in 0..count { if budget.nodes == 0 || budget.bytes == 0 { budget.exceeded = true; break; } - items.push(synthesize_value( - &item_schema, - prop_name, - rng, - depth + 1, - budget, - )); + let item = synthesize_value(root, item_schema, prop_name, rng, depth + 1, budget); + if budget.exceeded { + break; + } + items.push(item); } Value::Array(items) } - "integer" => { - let lo = schema.get("minimum").and_then(Value::as_i64).unwrap_or(0); - let hi = schema - .get("maximum") - .and_then(Value::as_i64) - .unwrap_or(lo.saturating_add(100)); - let hi = hi.max(lo); - let v = if hi > lo { rng.i64(lo..=hi) } else { lo }; - json!(v) + "integer" | "number" | "boolean" | "null" => { + let scalar = match ty { + "integer" => { + let lo = schema.get("minimum").and_then(Value::as_i64).unwrap_or(0); + let hi = schema + .get("maximum") + .and_then(Value::as_i64) + .unwrap_or(lo.saturating_add(100)); + json!(if hi > lo { rng.i64(lo..=hi) } else { lo }) + } + "number" => { + let lo = schema.get("minimum").and_then(Value::as_f64).unwrap_or(0.0); + let hi = schema + .get("maximum") + .and_then(Value::as_f64) + .unwrap_or(lo + 100.0) + .max(lo); + let v = lo + (hi - lo) * rng.f64(); + json!((v * 100.0).round() / 100.0) + } + "boolean" => Value::Bool(rng.bool()), + _ => Value::Null, + }; + if budget.charge_value(&scalar) { + scalar + } else { + Value::String("budget_cap".into()) + } + } + _ => synthesize_string(schema, prop_name, rng, budget), + } +} + +// A discriminator's sampled enum value can satisfy two oneOf branches. Try +// the other members against the entire composed schema before abandoning it. +fn vary_enum( + root: &Value, + schema: &Value, + candidate: &mut Value, + validator: &jsonschema::Validator, + budget: &mut SynthBudget, + depth: usize, +) -> bool { + if let Some(values) = schema["enum"].as_array() { + for value in values { + if !budget.charge_node() { + return false; + } + if validator.is_valid(value) && budget.charge_value(value) { + *candidate = value.clone(); + return true; + } } - "number" => { - let lo = schema.get("minimum").and_then(Value::as_f64).unwrap_or(0.0); - let hi = schema - .get("maximum") - .and_then(Value::as_f64) - .unwrap_or(lo + 100.0) - .max(lo); - let v = lo + (hi - lo) * rng.f64(); - json!((v * 100.0).round() / 100.0) + } + let Some(properties) = schema["properties"].as_object() else { + return false; + }; + if !candidate.is_object() { + return false; + } + for (name, property) in properties { + if candidate.get(name).is_none() { + continue; } - "boolean" => Value::Bool(rng.bool()), - "null" => Value::Null, - _ => synthesize_string(schema, prop_name, rng), + let property = resolve_composition(root, property, depth, budget); + let Some(values) = property["enum"].as_array() else { + continue; + }; + let original = std::mem::take(&mut candidate[name]); + for value in values { + if !budget.charge_value(value) { + break; + } + candidate[name] = value.clone(); + if validator.is_valid(candidate) { + return true; + } + } + candidate[name] = original; } + false +} + +fn schema_with_definitions(root: &Value, schema: &Value) -> Value { + let mut schema = schema.clone(); + for key in ["$defs", "definitions", "$schema"] { + if let Some(value) = root.get(key) { + schema[key] = value.clone(); + } + } + schema +} + +fn resolve_composition<'a>( + root: &'a Value, + schema: &'a Value, + depth: usize, + budget: &mut SynthBudget, +) -> std::borrow::Cow<'a, Value> { + use std::borrow::Cow; + + if schema.get("$ref").is_none() && schema.get("allOf").is_none() { + return Cow::Borrowed(schema); + } + if depth >= MAX_SYNTH_DEPTH || !budget.charge_node() { + budget.exceeded = true; + return Cow::Owned(Value::Null); + } + let mut base = schema.as_object().expect("composition object").clone(); + let reference = base.remove("$ref"); + let all_of = base.remove("allOf"); + let mut merged = Value::Object(base); + if let Some(reference) = reference { + if let Some(target) = reference + .as_str() + .and_then(|s| s.strip_prefix('#')) + .and_then(|p| root.pointer(p)) + { + let target = resolve_composition(root, target, depth + 1, budget); + merged = intersect(&merged, &target); + } else { + budget.exceeded = true; + } + } + if let Some(Value::Array(branches)) = all_of { + for branch in &branches { + if budget.exceeded { + break; + } + let branch = resolve_composition(root, branch, depth + 1, budget); + merged = intersect(&merged, &branch); + } + } + Cow::Owned(merged) +} + +// Build a candidate schema. The original schema still decides whether an instance is valid. +fn intersect(left: &Value, right: &Value) -> Value { + if left == &Value::Bool(false) || right == &Value::Bool(false) { + return Value::Bool(false); + } + let Some(left_map) = left.as_object() else { + return right.clone(); + }; + let Some(right_map) = right.as_object() else { + return left.clone(); + }; + let mut merged = left_map.clone(); + for (key, right) in right_map { + let value = match (key.as_str(), merged.get(key)) { + ("properties", Some(Value::Object(left))) => { + let mut properties = left.clone(); + if let Some(right) = right.as_object() { + for (name, schema) in right { + properties + .entry(name.clone()) + .and_modify(|previous| { + *previous = json!({"allOf": [previous, schema]}); + }) + .or_insert_with(|| schema.clone()); + } + } + Value::Object(properties) + } + ("oneOf" | "anyOf", Some(Value::Array(left))) => { + let Some(right) = right.as_array() else { + return Value::Bool(false); + }; + let pairs = left + .iter() + .flat_map(|first| right.iter().map(move |second| (first, second))); + let mut alternatives = SynthBudget::new(); + Value::Array( + pairs + .map_while(|(first, second)| { + (alternatives.charge_value(first) && alternatives.charge_value(second)) + .then(|| json!({"allOf": [first, second]})) + }) + .collect(), + ) + } + ("const", Some(left)) if left != right => return Value::Bool(false), + ("type", Some(left)) if left != right => { + let names = |value: &Value| { + value + .as_array() + .cloned() + .unwrap_or_else(|| vec![value.clone()]) + }; + let left = names(left); + let right = names(right); + let mut common: Vec<_> = left + .iter() + .filter(|ty| right.contains(ty)) + .cloned() + .collect(); + let number = json!("number"); + let integer = json!("integer"); + if ((left.contains(&number) && right.contains(&integer)) + || (right.contains(&number) && left.contains(&integer))) + && !common.contains(&integer) + { + common.push(integer); + } + if common.is_empty() { + return Value::Bool(false); + } + Value::Array(common) + } + ("required", Some(Value::Array(left))) => { + let mut required = left.clone(); + if let Some(right) = right.as_array() { + for name in right { + if !required.contains(name) { + required.push(name.clone()); + } + } + } + Value::Array(required) + } + ("enum", Some(Value::Array(left))) => Value::Array( + left.iter() + .filter(|v| right.as_array().is_some_and(|r| r.contains(v))) + .cloned() + .collect(), + ), + ("minimum" | "minLength" | "minItems", Some(left)) + if left.as_f64() > right.as_f64() => + { + left.clone() + } + ("maximum" | "maxLength" | "maxItems", Some(left)) + if left.as_f64() < right.as_f64() => + { + left.clone() + } + ("items", Some(left)) => json!({"allOf": [left, right]}), + _ => right.clone(), + }; + merged.insert(key.clone(), value); + } + Value::Object(merged) } fn resolve_schema_type(schema: &Value) -> &str { @@ -408,9 +699,12 @@ fn resolve_schema_type(schema: &Value) -> &str { return s; } } + if arr.iter().any(|value| value == "null") { + return "null"; + } } } - if schema.get("properties").is_some() { + if schema.get("properties").is_some() || schema.get("required").is_some() { "object" } else if schema.get("items").is_some() { "array" @@ -419,51 +713,74 @@ fn resolve_schema_type(schema: &Value) -> &str { } } -fn synthesize_string(schema: &Value, prop_name: Option<&str>, rng: &mut fastrand::Rng) -> Value { - if let Some(default) = schema.get("default").and_then(Value::as_str) { - return Value::String(default.to_string()); +fn synthesize_string( + schema: &Value, + prop_name: Option<&str>, + rng: &mut fastrand::Rng, + budget: &mut SynthBudget, +) -> Value { + if let Some(default @ Value::String(_)) = schema.get("default") { + return if budget.charge_value(default) { + default.clone() + } else { + Value::String("budget_cap".into()) + }; } let format = schema.get("format").and_then(Value::as_str).unwrap_or(""); let name_lower = prop_name.unwrap_or("").to_ascii_lowercase(); let n = rng.u32(1..9999); - - let mut s = match format { - "uri" | "url" => format!("https://example.invalid/resource/{n}"), - "email" => format!("bench{n}@example.invalid"), - "date-time" => "2026-11-20T12:00:00Z".into(), - "date" => "2026-11-20".into(), - "uuid" => format!("00000000-0000-4000-8000-{n:012}"), + let digits = n.to_string(); + let suffix; + let mut parts = match format { + "uri" | "url" => ["https://example.invalid/resource/", &digits, ""], + "email" => ["bench", &digits, "@example.invalid"], + "date-time" => ["2026-11-20T12:00:00Z", "", ""], + "date" => ["2026-11-20", "", ""], + "uuid" => { + suffix = format!("{n:012}"); + ["00000000-0000-4000-8000-", &suffix, ""] + } _ => { if name_lower.contains("path") || name_lower.contains("file") { - format!("src/module_{n}.rs") + ["src/module_", &digits, ".rs"] } else if name_lower.contains("command") || name_lower == "cmd" { - format!("echo synthetic_check_{n}") + ["echo synthetic_check_", &digits, ""] } else if name_lower.contains("query") || name_lower.contains("search") { - format!("maka benchmark query {n}") + ["maka benchmark query ", &digits, ""] } else if name_lower.contains("url") || name_lower.contains("uri") { - format!("https://example.invalid/item/{n}") + ["https://example.invalid/item/", &digits, ""] } else if name_lower.contains("id") { - format!("id_{n}") + ["id_", &digits, ""] } else { - format!("synthetic_{name_lower}_{n}") + suffix = format!("_{n}"); + ["synthetic_", name_lower.as_str(), &suffix] } } }; - if let Some(min_len) = schema.get("minLength").and_then(Value::as_u64) { - let min_len = (min_len as usize).min(2048); - while s.len() < min_len { - s.push_str("_pad"); - } + let min_len = schema["minLength"].as_u64().unwrap_or(0).min(2048) as usize; + let base_len = parts.iter().map(|part| part.len()).sum(); + let pad = min_len.saturating_sub(base_len).div_ceil(4) * 4; + let mut remaining = schema["maxLength"].as_u64().unwrap_or(u64::MAX) as usize; + for part in &mut parts { + let cut = part.floor_char_boundary(remaining); + remaining = if cut < part.len() { 0 } else { remaining - cut }; + *part = &part[..cut]; } - if let Some(max_len) = schema.get("maxLength").and_then(Value::as_u64) { - let max_len = max_len as usize; - if s.len() > max_len { - let cut = s.floor_char_boundary(max_len); - s.truncate(cut); - } + let pad = pad.min(remaining); + let bytes = parts.iter().map(|s| escaped_string_bytes(s)).sum::() + pad + 2; + if !budget.charge_bytes(bytes) { + return Value::String("budget_cap".into()); + } + let mut text = String::with_capacity(parts.iter().map(|part| part.len()).sum::() + pad); + for part in parts { + text.push_str(part); + } + for _ in 0..pad / 4 { + text.push_str("_pad"); } - Value::String(s) + text.push_str(&"_pad"[..pad % 4]); + Value::String(text) } fn generate_large_code_blob(target_bytes: usize, rng: &mut fastrand::Rng) -> String { @@ -556,3 +873,229 @@ pub fn context_overflow_error( }; HttpErrorSpec::raw(400, body) } + +pub fn payload_too_large_error(protocol: Protocol) -> HttpErrorSpec { + provider_error( + protocol, + 413, + "payload_too_large", + None, + "Request payload is too large", + ) +} + +pub fn rate_limit_error(protocol: Protocol, retry_after_secs: Option) -> HttpErrorSpec { + let mut spec = provider_error( + protocol, + 429, + "rate_limit_error", + None, + "Rate limit exceeded", + ); + spec.retry_after_secs = retry_after_secs; + spec +} + +pub fn overloaded_error(protocol: Protocol) -> HttpErrorSpec { + provider_error( + protocol, + 503, + "overloaded_error", + None, + "Service is overloaded", + ) +} + +pub fn previous_response_not_found_error(protocol: Protocol, response_id: &str) -> HttpErrorSpec { + provider_error( + protocol, + 400, + "invalid_request_error", + Some("previous_response_not_found"), + &format!("previous_response_id '{response_id}' not found"), + ) +} + +fn provider_error( + protocol: Protocol, + status: u16, + error_type: &str, + code: Option<&str>, + message: &str, +) -> HttpErrorSpec { + let body = if protocol == Protocol::AnthropicMessages { + json!({"type": "error", "error": {"type": error_type, "message": message}}) + } else { + json!({"error": {"type": error_type, "message": message, "code": code}}) + }; + let mut spec = HttpErrorSpec::new(status, error_type, message); + spec.code = code.map(str::to_owned); + spec.raw_body = Some(body); + spec +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn oversized_alternative_leaves_room_for_a_short_candidate() { + let large = "x".repeat(270 * 1024); + for keyword in ["anyOf", "oneOf"] { + let schema = json!({keyword: [{"const": large}, {"const": "ok"}]}); + for seed in 0..16 { + let value = try_synthesize_tool_arguments( + &schema, + &mut fastrand::Rng::with_seed(seed), + SynthMode::Valid, + ) + .unwrap_or_else(|error| panic!("{keyword}, seed {seed}: {error}")); + assert_eq!(value, json!("ok"), "{keyword}, seed {seed}"); + } + } + } + + #[test] + fn repeated_defaults_and_generated_strings_share_the_byte_budget() { + let mut rng = fastrand::Rng::with_seed(42); + let default = "x".repeat(8 * 1024); + let schema = |count| { + json!({ + "type": "array", "minItems": count, "maxItems": count, + "items": {"type": "string", "default": default} + }) + }; + let fits = try_synthesize_tool_arguments(&schema(31), &mut rng, SynthMode::Valid).unwrap(); + assert_eq!(fits, json!(vec![default.clone(); 31])); + + let generated = json!({ + "type": "array", "minItems": 2, "maxItems": 2, + "items": { + "type": "array", "minItems": 64, "maxItems": 64, + "items": {"type": "string", "minLength": 2048, "maxLength": 2048} + } + }); + for too_large in [schema(64), generated] { + let error = + try_synthesize_tool_arguments(&too_large, &mut rng, SynthMode::Valid).unwrap_err(); + assert!( + error.contains("schema exceeded synthesis budget"), + "{error}" + ); + } + + let target = 300 * 1024; + let explicit = try_synthesize_tool_arguments( + &json!({"type": "object"}), + &mut rng, + SynthMode::HugePayload(target), + ) + .unwrap(); + assert!(explicit["content"].as_str().unwrap().len() >= target); + } + + #[test] + fn synthesizes_intersections_and_exclusive_alternatives_through_local_refs() { + let schema = json!({ + "$defs": {"base": {"type": "object", "required": ["mode"], "properties": { + "mode": {"enum": ["shared", "read", "write"]} + }}}, + "definitions": {"file": {"const": "src/file.rs"}}, + "allOf": [ + {"$ref": "#/$defs/base"}, + {"type": "object", "required": ["path"], "properties": { + "path": {"$ref": "#/definitions/file"} + }}, + {"oneOf": [ + {"properties": {"mode": {"enum": ["shared", "read"]}}}, + {"properties": {"mode": {"enum": ["shared", "write"]}}} + ]} + ] + }); + for seed in 0..16 { + let value = try_synthesize_tool_arguments( + &schema, + &mut fastrand::Rng::with_seed(seed), + SynthMode::Valid, + ) + .unwrap(); + assert_eq!(value["path"], "src/file.rs"); + assert!(matches!(value["mode"].as_str(), Some("read" | "write"))); + } + } + + #[test] + fn recursive_branch_has_a_bounded_exit() { + let schema = json!({ + "$defs": {"node": {"anyOf": [ + {"type": "object", "properties": {"child": {"$ref": "#/$defs/node"}}, "required": ["child"]}, + {"type": "null"} + ]}}, + "$ref": "#/$defs/node" + }); + let validator = jsonschema::validator_for(&schema).unwrap(); + for seed in 0..16 { + let value = try_synthesize_tool_arguments( + &schema, + &mut fastrand::Rng::with_seed(seed), + SynthMode::Valid, + ) + .unwrap(); + assert!(validator.is_valid(&value), "{value}"); + } + + let cycle = json!({"$defs": {"loop": {"$ref": "#/$defs/loop"}}, "$ref": "#/$defs/loop"}); + assert!( + try_synthesize_tool_arguments( + &cycle, + &mut fastrand::Rng::with_seed(0), + SynthMode::Valid + ) + .unwrap_err() + .contains("synthesis budget") + ); + } + + #[test] + fn transport_size_rejection_is_distinct_from_model_context_overflow() { + let openai = Protocol::OpenaiResponsesHttp; + let anthropic = Protocol::AnthropicMessages; + for protocol in [openai, anthropic] { + let overflow = context_overflow_error(protocol, 4096, 2048); + assert_eq!(overflow.status, 400); + let body = overflow.raw_body.unwrap(); + assert_eq!(body["error"]["type"], "invalid_request_error"); + if protocol == openai { + assert_eq!(body["error"]["code"], "context_length_exceeded"); + } else { + assert_eq!(body["type"], "error"); + assert_eq!( + body["error"]["message"], + "prompt is too long: 1024 tokens > 512 maximum" + ); + } + let too_large = payload_too_large_error(protocol); + assert_eq!(too_large.status, 413); + assert_eq!( + too_large.raw_body.unwrap()["error"]["type"], + "payload_too_large" + ); + } + let limit = rate_limit_error(anthropic, Some(3)); + assert_eq!(limit.status, 429); + assert_eq!(limit.retry_after_secs, Some(3)); + assert_eq!(limit.raw_body.unwrap()["error"]["type"], "rate_limit_error"); + let overloaded = overloaded_error(openai); + assert_eq!(overloaded.status, 503); + assert_eq!( + overloaded.raw_body.unwrap()["error"]["type"], + "overloaded_error" + ); + let parent = previous_response_not_found_error(openai, "resp_missing"); + assert_eq!(parent.status, 400); + assert_eq!( + parent.raw_body.unwrap()["error"]["code"], + "previous_response_not_found" + ); + } +} diff --git a/tools/mock-ai/src/server.rs b/tools/mock-ai/src/server.rs index 8b88322b2bc..ee3c495ca62 100644 --- a/tools/mock-ai/src/server.rs +++ b/tools/mock-ai/src/server.rs @@ -21,34 +21,45 @@ mod admin; mod http; mod ws; -use crate::codec::format_http_error_body; +use crate::codec::{WireEncoder, create_encoder_with_options, format_http_error_body_for_profile}; use crate::control::{ControlPlaneConfig, CustomRouteFn, StoredResponses}; use crate::handler::{ AsyncFnHandler, ChainHandler, FilterHandler, FnHandler, InteractiveHandler, ScriptedHandler, - SessionTracker, TurnContext, TurnHandle, TurnHandler, + SessionTracker, TurnContext, TurnDecision, TurnHandle, TurnHandler, }; +use crate::metrics::SessionTelemetryStore; use crate::metrics::{ - MetricsSnapshot, RecordedControlRequest, RecordedRequest, RecorderMode, RequestRecorder, - ServerMetrics, + AttemptOutcome, AttemptSpan, MetricsSnapshot, RecordedControlRequest, RecordedRequest, + RecorderMode, RequestPurpose, RequestRecorder, RunClock, ServerMetrics, }; use crate::pacing::{ DynamicProfileManager, LatencyProfile, ProfileSnapshot, RuntimeProfile, ScenarioSchedule, }; -use crate::plan::{HttpErrorSpec, TurnEvent, TurnPlan, Usage}; -use crate::protocol::{AuthPolicy, NormalizedRequest, Protocol}; +use crate::plan::{ + CompactionOutput, HttpErrorSpec, ProviderDialectProfile, TurnEvent, TurnPlan, Usage, +}; +use crate::protocol::{AuthPolicy, NormalizedRequest, Protocol, Transport}; #[cfg(feature = "proxy")] use crate::proxy::{CassetteReplayer, ProxyRecordConfig, ProxyRecorder, ReplayConfig}; use crate::ratelimit::{RateLimitConfig, RateLimiter}; +use crate::routing::{ + CompactKind, EndpointKind, IdentityError, IdentityRequest, LineageStore, ParsedRoute, + PrincipalId, RequestClassifier, RequestUse, ResponseId, ResponseLineage, Revision, RouteScope, + RunId, SessionId, SessionIdentityResolver, SessionRegistry, SideKind, +}; #[cfg(feature = "rules")] use crate::rules::{ConfigError, RuleEngine, RuleSpec}; +use crate::scenario::{ScenarioEngine, ScenarioSpec}; #[cfg(feature = "tls")] use crate::tls::TlsServerConfig; -use crate::watchdog::{ProtocolWatchdog, WatchdogConfig, WatchdogSnapshot}; +use crate::watchdog::{ + HistorySize, ProtocolWatchdog, StreamCloseReason, WatchdogConfig, WatchdogSnapshot, +}; use bytes::Bytes; use futures_util::FutureExt; use http_body_util::combinators::UnsyncBoxBody; -use http_body_util::{BodyExt, Full, StreamBody}; -use hyper::body::{Frame, Incoming}; +use http_body_util::{BodyExt, Full}; +use hyper::body::Incoming; use hyper::header::{self, HeaderName, HeaderValue}; use hyper::server::conn::http1; use hyper::service::service_fn; @@ -56,14 +67,14 @@ use hyper::{Request, Response, StatusCode}; use hyper_util::rt::TokioIo; use serde_json::{Value, json}; use std::any::Any; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::future::Future; use std::hash::{Hash, Hasher}; use std::io; use std::net::SocketAddr; use std::panic::AssertUnwindSafe; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; use tokio::net::TcpListener; use tokio::sync::{Notify, mpsc}; @@ -137,9 +148,32 @@ pub(crate) struct ServerState { pub next_seq: AtomicU64, pub next_conn_id: AtomicU64, pub shutdown: CancellationToken, + benchmark: RwLock, + classifier: RequestClassifier, + telemetry: SessionTelemetryStore, + scenario: Option, + strict_benchmark: bool, + dialect: Option, + clock: RunClock, + unknown_routes: AtomicU64, } impl ServerState { + fn render_prometheus(&self) -> String { + use std::fmt::Write; + let mut output = self + .metrics + .render_prometheus(self.watchdog.total_violations()); + writeln!(output, "# TYPE mock_ai_unknown_routes_total counter").unwrap(); + writeln!( + output, + "mock_ai_unknown_routes_total {}", + self.unknown_routes.load(Ordering::Relaxed) + ) + .unwrap(); + output + } + pub(super) fn next_sequence(&self) -> u64 { self.next_seq.fetch_add(1, Ordering::AcqRel) + 1 } @@ -156,14 +190,20 @@ impl ServerState { .push(message); } - pub(super) fn reset(&self) { + pub(super) fn reset(&self) -> bool { + let mut benchmark = self.benchmark.write().unwrap(); + if !benchmark.sessions.is_empty() { + return false; + } self.metrics.reset(); + self.unknown_routes.store(0, Ordering::Relaxed); + benchmark.lineage = LineageStore::default(); self.recorder.clear(); self.stored_responses.clear(); self.sessions.clear(); self.profile.reset_clock(); self.rate_limiter.reset(); - self.watchdog.clear(); + self.watchdog.reset_all(); #[cfg(feature = "proxy")] if let Some(replayer) = &self.cassette_replayer { replayer.reset(); @@ -174,6 +214,7 @@ impl ServerState { .clear(); self.next_seq.store(0, Ordering::Release); self.handler.reset(); + true } fn ws_config(&self) -> WebSocketConfig { @@ -186,6 +227,1094 @@ impl ServerState { } } +#[derive(Default)] +struct BenchmarkRouting { + registry: SessionRegistry, + lineage: LineageStore, + responses: HashMap, + sessions: HashMap>, + runs: HashMap, +} + +#[derive(Default)] +struct ResponseBodies { + order: VecDeque, + entries: HashMap, usize)>, + bytes: usize, +} + +impl ResponseBodies { + fn insert( + &mut self, + id: ResponseId, + value: Value, + bytes: usize, + capacity: usize, + max_bytes: usize, + ) -> Vec> { + let mut retired = Vec::new(); + while self.order.len() >= capacity || (max_bytes > 0 && self.bytes > max_bytes - bytes) { + let id = self + .order + .pop_front() + .expect("full response bucket has a head"); + let (response, bytes) = self.entries.remove(&id).expect("queued response exists"); + self.bytes -= bytes; + retired.push(response); + } + self.order.push_back(id.clone()); + self.entries.insert(id, (Arc::new(value), bytes)); + self.bytes += bytes; + retired + } + + fn remove(&mut self, id: &ResponseId) -> Option> { + let (response, bytes) = self.entries.remove(id)?; + self.order.retain(|entry| entry != id); + self.bytes -= bytes; + Some(response) + } +} + +struct SessionActivity { + attempts: AtomicUsize, + run_start_ns: u64, + registered_ns: u64, + finalized_ns: AtomicU64, +} + +impl ServerState { + fn resolve_identity( + &self, + attempt: &Attempt, + scope: Option<&RouteScope>, + headers: &BTreeMap, + body: &Value, + previous: Option<&ResponseId>, + bind_connection: bool, + ) -> Result<(), Box> { + if !self.strict_benchmark && !self.control.enable_admin_api && scope.is_none() { + return Ok(()); + } + let principal = match &self.auth { + AuthPolicy::ApiKey { token } => Some(token.as_str()), + AuthPolicy::Header { name, .. } => { + headers.get(&name.to_ascii_lowercase()).map(String::as_str) + } + _ => headers + .get("authorization") + .and_then(|value| value.trim().split_once(' ')) + .filter(|(scheme, _)| scheme.eq_ignore_ascii_case("bearer")) + .map(|(_, value)| value) + .or_else(|| headers.get("x-api-key").map(String::as_str)) + .or_else(|| headers.get("api-key").map(String::as_str)), + } + .filter(|value| !value.is_empty()) + .map(|value| PrincipalId(value.into())); + let connection_id = attempt.connection_id(); + let routing = self.benchmark.read().unwrap(); + if routing.sessions.is_empty() && !self.strict_benchmark && scope.is_none() { + return Ok(()); + } + let result = SessionIdentityResolver::new(&routing.registry, &routing.lineage).resolve( + IdentityRequest { + scope, + principal: principal.as_ref(), + headers, + body, + previous_response_id: previous, + connection_id, + }, + ); + match result { + Ok(session) => { + let session_id = session.session_id.clone(); + attempt.attach(session, &routing.sessions[&session_id]); + drop(routing); + if bind_connection && let Some(conn) = connection_id { + self.benchmark + .write() + .unwrap() + .registry + .bind_connection(conn, &session_id) + .map_err(identity_error)?; + } + Ok(()) + } + Err(IdentityError::Unroutable) if !self.strict_benchmark => Ok(()), + Err(error) => Err(identity_error(error)), + } + } + + fn classify( + &self, + route: &ParsedRoute<'_>, + request: &mut NormalizedRequest, + attempt: &Attempt, + ) -> RequestUse { + let data = attempt.0.data.lock().unwrap(); + if let Some(span) = &data.span { + request.session_key.clone_from(&span.session_id.0); + } + let purpose = self + .classifier + .classify(route, request, data.harness.as_deref()); + if data.span.is_none() + && matches!( + purpose, + RequestUse::Compact(CompactKind::ResponsesTrigger | CompactKind::AnthropicNative) + ) + { + // Existing interactive scripts handle in-band compaction themselves. + return RequestUse::Main; + } + purpose + } + + fn check_parent( + &self, + req: &NormalizedRequest, + attempt: &Attempt, + legacy_baseline: Option<&str>, + ) -> Result, Box> { + let Some(parent) = req + .previous_response_id + .as_ref() + .filter(|_| req.protocol.is_responses()) + else { + return Ok(None); + }; + if let Some(owner) = attempt.owner() { + return self + .benchmark + .read() + .unwrap() + .lineage + .resolve_parent(&owner, &ResponseId(parent.clone()), attempt.connection_id()) + .cloned() + .map(Some) + .map_err(|_| { + Box::new(crate::schema_synth::previous_response_not_found_error( + req.protocol, + parent, + )) + }); + } + if !self.tuning.strict_previous_response_id + || legacy_baseline == Some(parent) + || self.stored_responses.contains(parent) + { + return Ok(None); + } + Err(Box::new( + crate::schema_synth::previous_response_not_found_error(req.protocol, parent), + )) + } + + fn publish_response( + &self, + req: &NormalizedRequest, + attempt: &Attempt, + id: String, + response: Value, + store: bool, + history: HistorySize, + ) { + if !req.protocol.is_responses() || !attempt.can_publish() { + return; + } + let (owner, parent_id, revision) = { + let data = attempt.0.data.lock().unwrap(); + let owner = data.span.as_ref().map(|span| span.session_id.clone()); + let parent_id = data.admitted_parent_id.clone(); + let revision = data + .span + .as_ref() + .and_then(|span| span.revision.clone()) + .unwrap_or(Revision(0)); + (owner, parent_id, revision) + }; + let size = store + .then(|| self.stored_responses.admitted_size(&response)) + .flatten(); + let Some(owner) = owner else { + if let Some(bytes) = size { + attempt.record(|_| { + self.stored_responses + .insert_sized(None, id, response, bytes) + }); + } + return; + }; + let id = ResponseId(id); + let mut routing = self.benchmark.write().unwrap(); + if let Some(previous) = routing.lineage.owner(&id) { + // A scenario retry can materialize the same logical response on a new connection. + if previous != &owner { + tracing::error!(response_id = %id, "response ID belongs to another session"); + } else if let Some(conn) = attempt.connection_id() { + routing.lineage.observe_on_connection(conn, &id); + } + return; + } + let lineage = ResponseLineage { + response_id: id.clone(), + owner_session: owner.clone(), + parent_id, + logical_revision: revision, + effective_context_tokens: history.tokens, + effective_context_bytes: history.bytes, + resumable: store, + store_readable: store, + created_on_conn: attempt.connection_id(), + }; + if let Err(error) = routing.lineage.insert_admitted(lineage) { + tracing::warn!(%error, "response lineage publication failed"); + return; + } + let retired = if let Some(bytes) = size { + routing.responses.entry(owner).or_default().insert( + id, + response, + bytes, + self.control.stored_responses_capacity, + self.control.stored_responses_max_bytes, + ) + } else { + Vec::new() + }; + drop(routing); + drop(retired); + } + + fn dialect_for(&self, protocol: Protocol) -> ProviderDialectProfile { + use ProviderDialectProfile::*; + match protocol { + Protocol::AnthropicMessages => AnthropicMessages, + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => OpenAiResponses, + Protocol::OpenaiChatCompletions => self.dialect.unwrap_or(if self.strict_benchmark { + StandardOpenAi + } else { + DeepSeekChat + }), + } + } + + fn encoder(&self, req: &NormalizedRequest, id: String, model: String) -> Box { + let dialect = self.dialect_for(req.protocol); + if !self.strict_benchmark && self.dialect.is_none() { + let mut options = req.options.clone(); + if req.protocol == Protocol::OpenaiChatCompletions + && req.raw_body.get("stream_options").is_none() + { + options.stream_include_usage = true; + } + if req.protocol.is_responses() && req.raw_body.get("include").is_none() { + options.include.push("reasoning.encrypted_content".into()); + } + return create_encoder_with_options( + req.protocol, + id, + model, + req.stream, + &options, + dialect, + ); + } + create_encoder_with_options(req.protocol, id, model, req.stream, &req.options, dialect) + } + + async fn decide( + &self, + req: &NormalizedRequest, + purpose: &RequestUse, + profile: &RuntimeProfile, + attempt: &Attempt, + parent: Option<&ResponseLineage>, + ) -> Result> { + if let RequestUse::Side(kind) = purpose { + let summary = || self.compaction(req, None).summary; + let text = match kind { + SideKind::Title if req.protocol == Protocol::AnthropicMessages => { + r#"{"title":"Benchmark task"}"#.into() + } + SideKind::Title => "Benchmark task".into(), + SideKind::Probe => "OK".into(), + SideKind::SummaryAux => summary(), + SideKind::Custom(name) => format!("Mock {name}"), + }; + return Ok(TurnDecision::Plan(TurnPlan::text(text))); + } + if purpose == &RequestUse::Control { + return Ok(TurnDecision::Plan(TurnPlan::text("OK"))); + } + if let RequestUse::Compact(kind) = purpose { + let output = self.compaction(req, Some(attempt)); + let plan = match kind { + CompactKind::ClientSummary => { + attempt.0.data.lock().unwrap().summary_checkpoint = Some(output.id); + attempt.buffering(output.summary.len()); + TurnPlan::text(output.summary) + } + _ => TurnPlan::new().push_compaction(output), + }; + return Ok(TurnDecision::Plan(plan)); + } + if let Some(scenario) = &self.scenario { + let evaluation = match parent { + Some(parent) => scenario.evaluate_with_parent_revision( + &req.session_key, + req, + crate::scenario::Revision(parent.logical_revision.0 as usize), + ), + None => scenario.evaluate_normalized(&req.session_key, req), + } + .map_err(|err| { + Box::new(match err { + crate::scenario::ScenarioError::UnknownParent(id) => { + crate::schema_synth::previous_response_not_found_error(req.protocol, &id) + } + _ => HttpErrorSpec::new(422, "scenario_request_error", err.to_string()), + }) + })?; + if let Some(checkpoint) = &evaluation.adopted_checkpoint_id { + attempt.checkpoint_adopted(req, checkpoint, parent); + } + attempt.scenario(scenario, &evaluation); + return Ok(TurnDecision::Plan(evaluation.plan)); + } + if let Some(spec) = self + .handler + .reject_before_turn(req, profile.chaos_override.as_ref()) + { + return Ok(TurnDecision::Plan(TurnPlan::http_error(spec))); + } + let mut session_turn = 0; + if !attempt.record(|_| session_turn = self.sessions.next_turn(&req.session_key)) { + return Err(Box::new(HttpErrorSpec::new( + 503, + "server_error", + "mock server was reset during admission", + ))); + } + let ctx = TurnContext { + global_turn: req.sequence, + session_turn, + chaos_override: profile.chaos_override.clone(), + }; + self.handler + .handle_admitted(req, &ctx) + .await + .ok_or_else(|| { + Box::new(HttpErrorSpec::new( + 500, + "mock_handler_exhausted", + "no handler matched or scripted queue was exhausted", + )) + }) + } + + fn compaction(&self, req: &NormalizedRequest, attempt: Option<&Attempt>) -> CompactionOutput { + if let Some((revision, output)) = self + .scenario + .as_ref() + .and_then(|scenario| scenario.compaction_output(&req.session_key)) + { + if let Some(attempt) = attempt { + attempt.with_span(|span, _| span.revision = Some(Revision(revision.0 as u64))); + } + return output; + } + let id = format!("cmp_{}", req.sequence); + let summary = match req.last_user_text() { + Some(text) => format!( + "Continue the task: {}", + text.chars().take(160).collect::() + ), + None => "Continue the benchmark task.".into(), + }; + CompactionOutput { + encrypted_content: format!("mock:{id}"), + summary, + id, + signature: None, + pause_after_compaction: req.protocol == Protocol::AnthropicMessages, + } + } +} + +fn identity_error(error: IdentityError) -> Box { + let (status, code) = match error { + IdentityError::Conflict { .. } => (400, "session_identity_conflict"), + IdentityError::PrincipalMismatch(_) => (400, "session_principal_mismatch"), + _ => (422, "session_unroutable"), + }; + let mut spec = HttpErrorSpec::new(status, "invalid_request_error", error.to_string()); + spec.code = Some(code.into()); + Box::new(spec) +} + +fn endpoint_protocol(endpoint: &EndpointKind) -> Option { + match endpoint { + EndpointKind::ChatCompletions => Some(Protocol::OpenaiChatCompletions), + EndpointKind::AnthropicMessages | EndpointKind::AnthropicCountTokens => { + Some(Protocol::AnthropicMessages) + } + EndpointKind::ResponsesCreate + | EndpointKind::ResponsesCompact + | EndpointKind::GetResponse(_) + | EndpointKind::DeleteResponse(_) => Some(Protocol::OpenaiResponsesHttp), + EndpointKind::ResponsesWs => Some(Protocol::OpenaiResponsesWs), + _ => None, + } +} + +#[derive(Clone)] +struct Attempt(Arc); + +struct AttemptInner { + state: Arc, + started: Instant, + headers_ns: u64, + generation: u64, + protocol: Protocol, + transport: Transport, + data: Mutex, +} + +#[derive(Default)] +struct AttemptData { + activity: Option>, + span: Option, + harness: Option, + purpose: RequestPurpose, + model: Option, + status: Option, + outcome: AttemptOutcome, + body_read_ns: Option, + wire_bytes: usize, + audit: Option>, + compaction_before: Option, + compacted_bytes: Option, + admitted_parent_id: Option, + summary_checkpoint: Option, + response_bytes: u64, + first_delta_elapsed: Option, + usage: Usage, + pacer_seed: Option, +} + +impl Attempt { + fn new( + state: &Arc, + protocol: Protocol, + transport: Transport, + started: Instant, + headers_ns: u64, + ) -> Self { + Self(Arc::new(AttemptInner { + state: state.clone(), + started, + headers_ns, + generation: state.metrics.generation(), + protocol, + transport, + data: Mutex::default(), + })) + } + + fn rejected_ws_message(&self, bytes: usize) -> Self { + let state = &self.0.state; + let rejection = Self::new( + state, + self.0.protocol, + self.0.transport.clone(), + Instant::now(), + state.clock.elapsed_ns(), + ); + let active = self.0.data.lock().unwrap(); + if let (Some(span), Some(activity)) = (&active.span, &active.activity) { + let mut data = rejection.0.data.lock().unwrap(); + let mut rejected_span = AttemptSpan::new( + span.run_id.clone(), + span.session_id.clone(), + span.protocol, + span.transport.clone(), + rejection.0.headers_ns.saturating_sub(activity.run_start_ns), + ); + rejected_span.lane.clone_from(&span.lane); + data.span = Some(rejected_span); + data.activity = Some(activity.clone()); + activity.attempts.fetch_add(1, Ordering::Relaxed); + } + rejection.body_read(bytes); + rejection.outcome(AttemptOutcome::Rejected, Some(400)); + rejection + } + + fn attach( + &self, + registration: &crate::routing::SessionRegistration, + activity: &Arc, + ) { + let mut data = self.0.data.lock().unwrap(); + if data.span.is_some() { + return; + } + let mut span = AttemptSpan::new( + registration.run_id.clone(), + registration.session_id.clone(), + self.0.protocol, + self.0.transport.clone(), + self.0.headers_ns.saturating_sub(activity.run_start_ns), + ); + span.lane = Some(registration.logical_lane.clone()); + span.body_read_ns = data + .body_read_ns + .map(|time| time.saturating_sub(activity.run_start_ns)); + span.request_wire_bytes = data.wire_bytes as u64; + activity.attempts.fetch_add(1, Ordering::Relaxed); + data.activity = Some(activity.clone()); + data.harness = Some(registration.harness.clone()); + data.span = Some(span); + } + + fn owner(&self) -> Option { + self.0 + .data + .lock() + .unwrap() + .span + .as_ref() + .map(|span| span.session_id.clone()) + } + + fn record(&self, record: impl FnOnce(&ServerMetrics)) -> bool { + self.0 + .state + .metrics + .record_for_generation(self.0.generation, record) + } + + fn connection_id(&self) -> Option { + match self.0.transport { + Transport::Http => None, + Transport::WebSocket { connection_id, .. } => Some(connection_id), + } + } + + fn with_span(&self, update: impl FnOnce(&mut AttemptSpan, u64)) { + let mut data = self.0.data.lock().unwrap(); + let start = data + .activity + .as_ref() + .map_or(0, |activity| activity.run_start_ns); + if let Some(span) = &mut data.span { + update(span, self.0.state.clock.elapsed_ns().saturating_sub(start)); + } + } + + fn body_read(&self, bytes: usize) { + let mut data = self.0.data.lock().unwrap(); + let now = self.0.state.clock.elapsed_ns(); + data.body_read_ns = Some(now); + data.wire_bytes = bytes; + let start = data + .activity + .as_ref() + .map_or(0, |activity| activity.run_start_ns); + if let Some(span) = &mut data.span { + span.body_read_ns = Some(now.saturating_sub(start)); + span.request_wire_bytes = bytes as u64; + } + } + + fn classified(&self, req: &NormalizedRequest, purpose: RequestPurpose) { + let mut data = self.0.data.lock().unwrap(); + data.purpose = purpose; + data.model = Some(req.model.clone()); + data.usage.input_tokens = req.estimated_input_tokens; + let start = data + .activity + .as_ref() + .map_or(0, |activity| activity.run_start_ns); + if let Some(span) = &mut data.span { + span.parsed_ns = Some(self.0.state.clock.elapsed_ns().saturating_sub(start)); + span.parent_response_id = req.previous_response_id.clone().map(ResponseId); + span.effective_context_bytes = req.size_breakdown.history_bytes as u64; + } + } + + fn admitted(&self, parent: Option<&ResponseLineage>) { + let mut data = self.0.data.lock().unwrap(); + data.admitted_parent_id = parent.map(|parent| parent.response_id.clone()); + let start = data + .activity + .as_ref() + .map_or(0, |activity| activity.run_start_ns); + let warmup = data.purpose == RequestPurpose::Warmup; + if let Some(span) = &mut data.span { + span.admitted_ns = Some(self.0.state.clock.elapsed_ns().saturating_sub(start)); + if let Some(parent) = parent { + span.effective_context_bytes += parent.effective_context_bytes as u64; + if warmup { + span.revision = Some(parent.logical_revision.clone()); + } + } + } + } + + fn ready(&self, id: Option<&str>) { + self.with_span(|span, now| { + span.plan_ready_ns.get_or_insert(now); + if let Some(id) = id { + span.response_id = Some(ResponseId(id.into())); + } + }); + } + + fn scenario( + &self, + scenario: &ScenarioEngine, + evaluation: &crate::scenario::ScenarioEvaluation, + ) { + let mut data = self.0.data.lock().unwrap(); + let step = &scenario.spec().steps[evaluation.decision.recipe.step_index()].id; + if let Some(span) = &mut data.span { + span.confirmed_call_ids = evaluation + .confirmed_call_ids + .iter() + .cloned() + .map(crate::routing::CallId) + .collect(); + if let Some(fault) = evaluation.fault { + span.fault_id = Some(format!("{step}/{}:{fault:?}", evaluation.attempt)); + } + span.step_id = Some(crate::routing::StepId(step.clone())); + span.revision = Some(Revision(evaluation.decision.revision.0 as u64)); + span.attempt = Some(crate::routing::AttemptId(u64::from(evaluation.attempt))); + if evaluation.replayed { + span.retry_reason = Some("scenario_replay".into()); + } + } + if let Some(lane) = data.span.as_ref().and_then(|span| span.lane.as_ref()) { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + scenario.spec().seed.hash(&mut hash); + lane.hash(&mut hash); + step.hash(&mut hash); + evaluation.attempt.hash(&mut hash); + data.pacer_seed = Some(hash.finish()); + } + } + + fn seed(&self, req: &NormalizedRequest) -> u64 { + self.0 + .data + .lock() + .unwrap() + .pacer_seed + .unwrap_or_else(|| pacer_seed_for(req)) + } + + fn usage(&self, usage: Usage) { + self.0.data.lock().unwrap().usage = usage; + } + + fn outcome(&self, outcome: AttemptOutcome, status: Option) { + let mut data = self.0.data.lock().unwrap(); + data.outcome = outcome; + data.status = status.or(data.status); + } + + fn frame(&self, bytes: usize, semantic: bool) { + let mut data = self.0.data.lock().unwrap(); + data.response_bytes += bytes as u64; + if semantic && data.first_delta_elapsed.is_none() { + data.first_delta_elapsed = Some(self.0.started.elapsed()); + } + let start = data + .activity + .as_ref() + .map_or(0, |activity| activity.run_start_ns); + if let Some(span) = &mut data.span { + let now = self.0.state.clock.elapsed_ns().saturating_sub(start); + span.first_byte_ns.get_or_insert(now); + if semantic { + span.first_semantic_delta_ns.get_or_insert(now); + } + span.last_frame_consumed_ns = Some(now); + span.response_wire_bytes += bytes as u64; + } + } + + fn buffering(&self, bytes: usize) { + self.0.data.lock().unwrap().compacted_bytes = Some(bytes); + } + + fn sleep_recorded(&self, requested: Duration, elapsed: Duration) { + self.with_span(|span, _| { + span.simulated_delay_ns += requested.as_nanos() as u64; + span.actual_sleep_ns += elapsed.as_nanos() as u64; + }); + } + + fn audit(&self, req: Arc, purpose: &RequestUse, before: HistorySize) { + let state = &self.0.state; + state + .metrics + .record_for_generation(self.0.generation, |_| match purpose { + RequestUse::Main => { + state.watchdog.inspect_request(&req); + self.0.data.lock().unwrap().audit = Some(req); + } + RequestUse::Compact(_) => { + state.watchdog.on_compaction_requested(&req, before); + self.0.data.lock().unwrap().compaction_before = Some(before); + } + _ => {} + }); + } + + fn call(&self, id: &str, delivered: bool) { + self.0 + .state + .metrics + .record_for_generation(self.0.generation, |_| { + let data = self.0.data.lock().unwrap(); + if let Some(req) = &data.audit { + if delivered { + self.0.state.watchdog.on_call_delivered_complete(req, id); + } else { + self.0.state.watchdog.on_call_issued(req, id); + } + } + }); + } + + fn compaction(&self, id: String) { + self.with_span(|span, _| span.checkpoint_id = Some(id)); + } + + fn checkpoint_adopted( + &self, + req: &NormalizedRequest, + id: &str, + parent: Option<&ResponseLineage>, + ) { + let after = parent + .filter(|parent| parent.response_id.0.starts_with("resp_compact_")) + .map(|parent| HistorySize { + bytes: parent.effective_context_bytes, + tokens: parent.effective_context_tokens, + }); + self.record(|_| self.0.state.watchdog.on_compaction_adopted(req, id, after)); + self.with_span(|span, _| span.adopted_checkpoint_id = Some(id.into())); + } + + fn compaction_delivered(&self, req: &NormalizedRequest, id: &str) { + let before = self.0.data.lock().unwrap().compaction_before; + self.0 + .state + .metrics + .record_for_generation(self.0.generation, |_| { + let watchdog = &self.0.state.watchdog; + if self.owner().is_some() { + watchdog.on_compaction_issued( + req, + id, + before.unwrap_or_else(|| HistorySize::from_request(req)), + ); + } else { + watchdog.record_turn_outcome(req, &[], true, true); + } + }); + self.compaction(id.into()); + } +} + +impl Drop for AttemptInner { + fn drop(&mut self) { + let data = self.data.get_mut().unwrap(); + let outcome = match data.outcome { + AttemptOutcome::Unclassified if self.state.shutdown.is_cancelled() => { + AttemptOutcome::ServerShutdown + } + AttemptOutcome::Unclassified => AttemptOutcome::ClientDisconnected, + outcome => outcome, + }; + let duration_ms = self.started.elapsed().as_millis() as u64; + let ttft_ms = data + .first_delta_elapsed + .map(|elapsed| elapsed.as_millis() as u64); + self.state + .metrics + .record_for_generation(self.generation, |metrics| { + metrics + .bytes_sent + .fetch_add(data.response_bytes, Ordering::Relaxed); + if let Some(ttft) = ttft_ms { + metrics.ttft_ms.record(ttft); + } + if let Some(req) = &data.audit { + if matches!(outcome, AttemptOutcome::ClientDisconnected) { + metrics.abandoned_streams.fetch_add(1, Ordering::Relaxed); + } + let reason = match outcome { + AttemptOutcome::Completed => StreamCloseReason::Completed, + AttemptOutcome::InjectedFault => StreamCloseReason::InjectedFault, + AttemptOutcome::ServerShutdown => StreamCloseReason::ServerShutdown, + AttemptOutcome::ClientDisconnected => StreamCloseReason::ClientDisconnected, + _ => StreamCloseReason::InjectedFault, + }; + self.state.watchdog.on_stream_closed(req, reason); + } + if let Some(model) = &data.model { + metrics.turn_duration_ms.record(duration_ms); + if let Some(first) = data.first_delta_elapsed + && data.usage.output_tokens > 0 + { + let seconds = self + .started + .elapsed() + .saturating_sub(first) + .as_secs_f64() + .max(0.001); + metrics.effective_tps.record( + (data.usage.output_tokens as f64 / seconds).round().max(1.0) as u64, + ); + } + metrics.record_dimension_with_labels( + self.protocol, + model, + data.status, + data.purpose, + outcome, + data.usage.input_tokens, + data.usage.output_tokens, + data.usage.cache_read_tokens.unwrap_or(0), + ttft_ms, + Some(duration_ms), + ); + } + }); + if let (Some(mut span), Some(activity)) = (data.span.take(), data.activity.take()) { + span.outcome = outcome; + span.purpose = data.purpose; + let finished = self + .state + .clock + .elapsed_ns() + .saturating_sub(activity.run_start_ns); + span.finished_ns = Some(finished); + if span.connection_id.is_some() && span.first_byte_ns.is_some() { + span.body_dropped_ns.get_or_insert(finished); + } + span.input_tokens = data.usage.input_tokens; + span.output_tokens = data.usage.output_tokens; + span.cache_read_tokens = data.usage.cache_read_tokens.unwrap_or(0); + span.cache_creation_tokens = data.usage.cache_creation_tokens.unwrap_or(0); + span.reasoning_tokens = data.usage.reasoning_tokens.unwrap_or(0); + if let Err(error) = self.state.telemetry.record(span) { + tracing::error!(%error, "could not record benchmark attempt"); + } + activity.attempts.fetch_sub(1, Ordering::Release); + } + } +} + +fn effective_history(req: &NormalizedRequest, parent: Option<&ResponseLineage>) -> HistorySize { + let mut history = HistorySize::from_request(req); + if let Some(parent) = parent { + history.bytes = history.bytes.saturating_add(parent.effective_context_bytes); + history.tokens = history + .tokens + .saturating_add(parent.effective_context_tokens); + } + history +} + +fn turn_pacer( + req: &NormalizedRequest, + plan: &TurnPlan, + usage: &Usage, + attempt: &Attempt, + profile: LatencyProfile, + in_flight: usize, +) -> crate::pacing::TurnPacer { + let mut pacer = crate::pacing::TurnPacer::new( + profile, + attempt.seed(req), + in_flight, + plan.ttft_ms, + (plan.chunk_delay_ms > 0).then_some(plan.chunk_delay_ms), + ); + let cached = usage.cache_read_tokens.unwrap_or(0); + pacer.compute_ttft(usage.input_tokens.saturating_sub(cached), cached); + pacer +} + +#[derive(Clone)] +enum DeliveredItem { + Tool(String), + Compaction { id: String, bytes: usize }, +} + +impl DeliveredItem { + fn from_event(event: &TurnEvent) -> Option { + match event { + TurnEvent::ToolCall(call) => Some(Self::Tool(call.id.clone())), + TurnEvent::NativeCompaction(output) => Some(Self::Compaction { + id: output.id.clone(), + bytes: output.summary.len().max(output.encrypted_content.len()), + }), + _ => None, + } + } + + fn issued(&self, attempt: &Attempt) { + if let Self::Tool(id) = self { + attempt.call(id, false); + } + } + + fn deliver(self, attempt: &Attempt, req: &NormalizedRequest) { + match self { + Self::Tool(id) => attempt.call(&id, true), + Self::Compaction { mut id, bytes } => { + attempt.record(|metrics| { + metrics + .native_compactions_emitted + .fetch_add(1, Ordering::Relaxed); + }); + if id.is_empty() { + id = format!("cmp_{}", req.sequence); + } + attempt.compaction_delivered(req, &id); + attempt.0.data.lock().unwrap().compacted_bytes = Some(bytes); + } + } + } +} + +impl Attempt { + #[cfg(feature = "proxy")] + fn lane(&self) -> Option { + self.0 + .data + .lock() + .unwrap() + .span + .as_ref() + .and_then(|span| span.lane.clone()) + } + + #[cfg(feature = "proxy")] + fn replay_lane( + &self, + headers: &BTreeMap, + ) -> Option { + self.lane().or_else(|| { + headers + .get(crate::proxy::SCOPE_LANE_HEADER) + .cloned() + .map(crate::routing::LogicalLane) + }) + } + + fn can_publish(&self) -> bool { + matches!( + self.0.data.lock().unwrap().purpose, + RequestPurpose::Main | RequestPurpose::Compact | RequestPurpose::Warmup + ) + } + + fn has_summary(&self) -> bool { + self.0.data.lock().unwrap().summary_checkpoint.is_some() + } + + fn deliver_summary(&self, req: &NormalizedRequest) { + let checkpoint = self.0.data.lock().unwrap().summary_checkpoint.take(); + if let Some(id) = checkpoint { + self.compaction_delivered(req, &id); + } + } + + fn http_status(&self, status: u16) { + let mut data = self.0.data.lock().unwrap(); + data.status.get_or_insert(status); + if data.outcome == AttemptOutcome::Unclassified { + data.outcome = match status { + 101 => AttemptOutcome::Completed, + 429 => AttemptOutcome::RateLimited, + 503 if self.0.state.shutdown.is_cancelled() => AttemptOutcome::ServerShutdown, + 400..=599 => AttemptOutcome::Rejected, + _ => return, + }; + } + } + + fn body_completed(&self) { + let mut data = self.0.data.lock().unwrap(); + if data.outcome == AttemptOutcome::Unclassified { + data.outcome = AttemptOutcome::Completed; + } + } + + fn expects_semantic_body(&self) -> bool { + let data = self.0.data.lock().unwrap(); + data.status == Some(200) + && matches!( + data.purpose, + RequestPurpose::Main + | RequestPurpose::Title + | RequestPurpose::Probe + | RequestPurpose::SummaryAux + | RequestPurpose::Side + | RequestPurpose::Compact + ) + } + + fn response_history(&self, mut history: HistorySize, output: usize) -> HistorySize { + if let Some(compacted) = self.0.data.lock().unwrap().compacted_bytes { + return HistorySize { + bytes: compacted, + tokens: (compacted as u64).div_ceil(4), + }; + } + history.bytes = history.bytes.saturating_add(output); + history.tokens = history.tokens.saturating_add((output as u64).div_ceil(4)); + history + } + + fn backpressure(&self, elapsed: Duration) { + self.with_span(|span, _| span.backpressure_wait_ns += elapsed.as_nanos() as u64); + } + + async fn wait(&self, delay: Duration, closed: impl Future) -> bool { + self.wait_until(tokio::time::Instant::now() + delay, closed) + .await + } + + async fn wait_until( + &self, + deadline: tokio::time::Instant, + closed: impl Future, + ) -> bool { + let now = tokio::time::Instant::now(); + if deadline <= now { + return !self.0.state.shutdown.is_cancelled(); + } + let started = Instant::now(); + let completed = tokio::select! { + _ = self.0.state.shutdown.cancelled() => false, + _ = closed => false, + _ = tokio::time::sleep_until(deadline) => true, + }; + self.sleep_recorded(deadline - now, started.elapsed()); + completed + } +} + pub(super) fn panic_payload_to_string(payload: Box) -> String { if let Some(s) = payload.downcast_ref::<&'static str>() { (*s).to_owned() @@ -324,7 +1453,10 @@ impl MockAiServer { } pub fn reset(&self) { - self.state.reset(); + assert!( + self.state.reset(), + "export and delete benchmark sessions before resetting" + ); } #[cfg(feature = "rules")] @@ -357,13 +1489,11 @@ impl MockAiServer { } pub fn clear_violations(&self) { - self.state.watchdog.clear(); + self.state.watchdog.clear_violations(); } pub fn render_prometheus(&self) -> String { - self.state - .metrics - .render_prometheus(self.state.watchdog.total_violations()) + self.state.render_prometheus() } pub fn shutdown_token(&self) -> CancellationToken { @@ -440,6 +1570,11 @@ pub struct MockAiBuilder { rule_engine: Option>, custom_route: Option, interactive_rx: Option>, + scenario: Option, + strict_benchmark: bool, + dialect: Option, + classifier: RequestClassifier, + has_workload: bool, } impl Default for MockAiBuilder { @@ -471,6 +1606,11 @@ impl MockAiBuilder { rule_engine: None, custom_route: None, interactive_rx: None, + scenario: None, + strict_benchmark: false, + dialect: None, + classifier: RequestClassifier::default(), + has_workload: false, } } @@ -535,10 +1675,37 @@ impl MockAiBuilder { Ok(self) } - pub fn workload(self, config: crate::workload::WorkloadConfig) -> Self { + pub fn workload(mut self, config: crate::workload::WorkloadConfig) -> Self { + self.has_workload = true; self.handler(Arc::new(crate::workload::WorkloadGenerator::new(config))) } + #[cfg(feature = "rules")] + pub(crate) fn with_workload_flag(mut self, has_workload: bool) -> Self { + self.has_workload = has_workload; + self + } + + pub fn scenario(mut self, spec: ScenarioSpec) -> Self { + self.scenario = Some(spec); + self + } + + pub fn strict_benchmark(mut self, enabled: bool) -> Self { + self.strict_benchmark = enabled; + self + } + + pub fn provider_dialect(mut self, dialect: ProviderDialectProfile) -> Self { + self.dialect = Some(dialect); + self + } + + pub fn request_classifier(mut self, classifier: RequestClassifier) -> Self { + self.classifier = classifier; + self + } + pub fn interactive(mut self, capacity: usize) -> Self { let (handler, rx) = InteractiveHandler::channel(capacity); self.handler = Some(handler); @@ -622,6 +1789,32 @@ impl MockAiBuilder { } pub async fn start_with_listener(mut self, listener: TcpListener) -> io::Result { + if self.scenario.is_some() && self.has_workload { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "scenario and workload are mutually exclusive", + )); + } + #[cfg(feature = "proxy")] + if self.scenario.is_some() + && (self.proxy_recorder.is_some() || self.cassette_replayer.is_some()) + { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "scenario cannot be combined with proxy or replay", + )); + } + let strict_benchmark = self.strict_benchmark || self.scenario.is_some(); + let scenario = self + .scenario + .map(|spec| ScenarioEngine::new(spec, "mock-ai")) + .transpose() + .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; + if strict_benchmark { + self.control.enable_admin_api = true; + } + let telemetry = + SessionTelemetryStore::new(self.tuning.max_tracked_sessions, 4096, 8 * 1024 * 1024); let handler: Arc = self.handler.take().unwrap_or_else(|| { Arc::new(FnHandler(|req: &NormalizedRequest, ctx: &TurnContext| { TurnPlan::text(format!( @@ -670,6 +1863,14 @@ impl MockAiBuilder { next_seq: AtomicU64::new(0), next_conn_id: AtomicU64::new(0), shutdown: CancellationToken::new(), + benchmark: RwLock::default(), + classifier: self.classifier, + telemetry, + scenario, + strict_benchmark, + dialect: self.dialect, + clock: RunClock::default(), + unknown_routes: AtomicU64::new(0), }); MockAiServer::spawn(listener, state, self.interactive_rx).await @@ -749,6 +1950,9 @@ impl TurnCloseGuard { pub(super) struct PendingWsUpgrade { pub on_upgrade: hyper::upgrade::OnUpgrade, pub path: String, + pub scope: Option, + pub canonical_offset: usize, + pub query: Option, #[cfg(feature = "proxy")] pub path_and_query: String, pub headers: BTreeMap, @@ -851,6 +2055,9 @@ where ws_stream, conn_id, upgrade.path, + upgrade.scope, + upgrade.canonical_offset, + upgrade.query, upgrade.headers, state, ) @@ -887,46 +2094,44 @@ pub(super) fn full_json(status: StatusCode, value: &Value) -> Response .unwrap() } -pub(super) fn error_http_response( +fn error_http_response( protocol: Protocol, spec: &HttpErrorSpec, - metrics: &ServerMetrics, + attempt: &Attempt, ) -> Response { - metrics.http_errors_emitted.fetch_add(1, Ordering::Relaxed); - if spec.status == 429 { - metrics.rate_limits_emitted.fetch_add(1, Ordering::Relaxed); - } - if spec.status == 400 - && (spec.code.as_deref() == Some("context_length_exceeded") - || spec.raw_body.as_ref().is_some_and(|v| { - let s = v.to_string(); - s.contains("context_length_exceeded") || s.contains("prompt is too long") - }) - || spec.raw_text.as_ref().is_some_and(|s| { - s.contains("context_length_exceeded") || s.contains("prompt is too long") - })) - { - metrics - .context_overflows_emitted - .fetch_add(1, Ordering::Relaxed); - } - + let state = &attempt.0.state; + attempt.record(|metrics| { + metrics.http_errors_emitted.fetch_add(1, Ordering::Relaxed); + if spec.status == 429 { + metrics.rate_limits_emitted.fetch_add(1, Ordering::Relaxed); + } + if spec.status == 400 + && (spec.code.as_deref() == Some("context_length_exceeded") + || spec.raw_body.as_ref().is_some_and(|v| { + let s = v.to_string(); + s.contains("context_length_exceeded") || s.contains("prompt is too long") + }) + || spec.raw_text.as_ref().is_some_and(|s| { + s.contains("context_length_exceeded") || s.contains("prompt is too long") + })) + { + metrics + .context_overflows_emitted + .fetch_add(1, Ordering::Relaxed); + } + }); let (content_type, bytes) = if let Some(raw_text) = &spec.raw_text { ( spec.content_type.as_deref().unwrap_or("text/plain"), Bytes::from(raw_text.clone()), ) } else { - let body = format_http_error_body(protocol, spec); + let body = format_http_error_body_for_profile(state.dialect_for(protocol), spec); ( spec.content_type.as_deref().unwrap_or("application/json"), Bytes::from(body.to_string()), ) }; - metrics - .bytes_sent - .fetch_add(bytes.len() as u64, Ordering::Relaxed); - let status = StatusCode::from_u16(spec.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); let mut builder = Response::builder() .status(status) @@ -981,13 +2186,10 @@ pub(super) fn format_ws_error_frame(spec: &HttpErrorSpec) -> Value { } pub(super) fn sse_response( - rx: mpsc::Receiver, io::Error>>, + body: BoxBody, extra_headers: &BTreeMap, close_connection: bool, ) -> Response { - let stream = futures_util::stream::unfold(rx, |mut rx| async move { - rx.recv().await.map(|item| (item, rx)) - }); let mut builder = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "text/event-stream") @@ -1003,21 +2205,15 @@ pub(super) fn sse_response( builder = builder.header(name, val); } } - builder - .body(StreamBody::new(stream).boxed_unsync()) - .unwrap() + builder.body(body).unwrap() } pub(super) fn json_with_headers( - value: Value, + value: &Value, extra_headers: &BTreeMap, close_connection: bool, - metrics: &ServerMetrics, ) -> Response { let bytes = Bytes::from(value.to_string()); - metrics - .bytes_sent - .fetch_add(bytes.len() as u64, Ordering::Relaxed); let mut builder = Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "application/json") @@ -1042,50 +2238,11 @@ pub(super) fn json_with_headers( .unwrap() } -pub(super) struct TtftTracker<'a> { - pub turn_started: Instant, - pub first_delta_at: &'a mut Option, - pub recorded_ttft_ms: &'a mut Option, -} - -impl TtftTracker<'_> { - pub fn record_once(&mut self, metrics: &ServerMetrics) { - if self.first_delta_at.is_none() { - *self.first_delta_at = Some(Instant::now()); - let ttft = self.turn_started.elapsed().as_millis() as u64; - metrics.ttft_ms.record(ttft); - *self.recorded_ttft_ms = Some(ttft); - } - } -} - pub(super) struct FlushStatus { pub all_wire_frames_sent: bool, pub continued: bool, } -pub(super) fn is_semantic_delta_frame(raw: &str) -> bool { - let json_str = raw - .lines() - .find_map(|line| line.strip_prefix("data:").map(str::trim)) - .unwrap_or_else(|| raw.trim()); - let Ok(val) = serde_json::from_str::(json_str) else { - return true; - }; - if let Some(ev_type) = val.get("type").and_then(Value::as_str) { - return !matches!( - ev_type, - "response.created" - | "response.in_progress" - | "response.output_item.added" - | "response.content_part.added" - | "message_start" - | "content_block_start" - ); - } - true -} - pub(super) fn pacer_seed_for(req: &NormalizedRequest) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); req.session_key.hash(&mut h); @@ -1093,13 +2250,20 @@ pub(super) fn pacer_seed_for(req: &NormalizedRequest) -> u64 { h.finish() } -pub(super) fn plan_usage_hint(plan: &TurnPlan, req: &NormalizedRequest) -> Usage { - for ev in &plan.events { - if let TurnEvent::Usage(u) = ev { - return u.clone(); - } +fn event_usage(event: &TurnEvent) -> Option<&Usage> { + match event { + TurnEvent::Usage(usage) => Some(usage), + TurnEvent::UsageWithIterations(usage) => Some(&usage.totals), + _ => None, } - Usage::new(req.estimated_input_tokens.max(1), 0) +} + +fn initial_usage(events: &[TurnEvent], req: &NormalizedRequest) -> TurnEvent { + events + .iter() + .find(|event| event_usage(event).is_some()) + .cloned() + .unwrap_or_else(|| TurnEvent::Usage(Usage::new(req.estimated_input_tokens.max(1), 0))) } pub(super) fn semantic_event_bytes(ev: &TurnEvent) -> usize { @@ -1113,33 +2277,6 @@ pub(super) fn semantic_event_bytes(ev: &TurnEvent) -> usize { } } -pub(super) fn classify_protocol(path: &str) -> Option { - if path.ends_with("/chat/completions") { - Some(Protocol::OpenaiChatCompletions) - } else if is_responses_path(path) { - Some(Protocol::OpenaiResponsesHttp) - } else if path.ends_with("/messages") { - Some(Protocol::AnthropicMessages) - } else { - None - } -} - -pub(super) fn is_responses_path(path: &str) -> bool { - path == "/responses" || path == "/v1/responses" || path.ends_with("/responses") -} - -pub(super) fn extract_stored_response_id(path: &str) -> Option<&str> { - let rest = path - .strip_prefix("/v1/responses/") - .or_else(|| path.strip_prefix("/responses/"))?; - if rest.is_empty() || rest.contains('/') { - None - } else { - Some(rest) - } -} - pub(super) fn default_response_id(protocol: Protocol, seq: u64) -> String { match protocol { Protocol::OpenaiChatCompletions => format!("chatcmpl_mock_{seq}"), diff --git a/tools/mock-ai/src/server/admin.rs b/tools/mock-ai/src/server/admin.rs index c33f2b324a1..063582499f2 100644 --- a/tools/mock-ai/src/server/admin.rs +++ b/tools/mock-ai/src/server/admin.rs @@ -17,16 +17,20 @@ * under the License. */ -use super::{BoxBody, ServerState, full_json}; +use super::{BoxBody, ServerState, SessionActivity, full_json}; +use crate::metrics::compute_attribution; use crate::pacing::{RuntimeProfile, ScenarioSchedule}; use crate::ratelimit::RateLimitConfig; +use crate::routing::{SessionId, SessionRegistration}; #[cfg(feature = "rules")] use crate::rules::RuleSpec; +use crate::scenario::{CompletionProof, RunnerObservation}; use http_body_util::{BodyExt, Limited}; use hyper::body::Incoming; use hyper::{Method, Request, Response, StatusCode}; use serde_json::json; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; pub(super) async fn handle_admin( method: Method, @@ -37,14 +41,35 @@ pub(super) async fn handle_admin( match (method, path) { (Method::GET, "/admin/health") => full_json(StatusCode::OK, &json!({ "ok": true })), (Method::GET, "/admin/metrics") => { - full_json(StatusCode::OK, &json!(state.metrics.snapshot())) + let mut snapshot = json!(state.metrics.snapshot()); + snapshot["unknownRoutes"] = json!(state.unknown_routes.load(Ordering::Relaxed)); + full_json(StatusCode::OK, &snapshot) } (Method::GET, "/admin/requests") => { full_json(StatusCode::OK, &json!(state.recorder.snapshot())) } (Method::POST, "/admin/reset") => { - state.reset(); - full_json(StatusCode::OK, &json!({ "reset": true })) + if state.reset() { + full_json(StatusCode::OK, &json!({ "reset": true })) + } else { + problem( + StatusCode::CONFLICT, + "export and delete benchmark sessions before resetting", + ) + } + } + (Method::POST, "/admin/sessions") => register_session(req, &state).await, + (Method::GET, "/admin/sessions") => match SessionQuery::parse(req.uri().query()) { + Ok(query) => { + let page = state + .telemetry + .list_sessions(query.run, query.cursor, query.limit()); + full_json(StatusCode::OK, &json!(page)) + } + Err(error) => problem(StatusCode::BAD_REQUEST, error), + }, + (method, path) if path.starts_with("/admin/sessions/") => { + session_route(method, &path["/admin/sessions/".len()..], req, &state).await } #[cfg(feature = "rules")] (Method::GET, "/admin/rules") => { @@ -169,7 +194,7 @@ pub(super) async fn handle_admin( full_json(StatusCode::OK, &json!(state.watchdog.snapshot())) } (Method::DELETE, "/admin/violations") => { - state.watchdog.clear(); + state.watchdog.clear_violations(); full_json(StatusCode::OK, &json!({ "cleared": true })) } _ => full_json( @@ -178,3 +203,829 @@ pub(super) async fn handle_admin( ), } } + +#[derive(serde::Deserialize)] +struct RegisterSession { + #[serde(flatten)] + registration: SessionRegistration, + workspace: Option, +} + +#[derive(Default)] +struct SessionQuery<'a> { + run: Option<&'a str>, + cursor: Option, + after: Option, + limit: Option, +} + +impl<'a> SessionQuery<'a> { + fn parse(query: Option<&'a str>) -> Result { + let mut parsed = Self::default(); + for pair in query.into_iter().flat_map(|q| q.split('&')) { + let (key, value) = pair + .split_once('=') + .ok_or("expected key=value query parameters")?; + match key { + "run" => parsed.run = Some(value), + "cursor" => parsed.cursor = Some(value.parse().map_err(|_| "invalid cursor")?), + "after" | "through" => { + parsed.after = Some(value.parse().map_err(|_| "invalid after cursor")?) + } + "limit" => { + let limit = value.parse().map_err(|_| "invalid limit")?; + if !(1..=1000).contains(&limit) { + return Err("limit must be between 1 and 1000"); + } + parsed.limit = Some(limit); + } + _ => return Err("unrecognized query parameter"), + } + } + Ok(parsed) + } + + fn limit(&self) -> usize { + self.limit.unwrap_or(100) + } +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct FinalizeProof { + response_id: String, + observed_markers: std::collections::BTreeSet, +} + +async fn read_json(req: Request) -> Result { + let bytes = read_admin_body(req).await?; + serde_json::from_slice(&bytes).map_err(|error| format!("invalid JSON body: {error}")) +} + +async fn read_admin_body(req: Request) -> Result { + Limited::new(req.into_body(), 1024 * 1024) + .collect() + .await + .map(|body| body.to_bytes()) + .map_err(|error| format!("body read failed: {error}")) +} + +fn problem(status: StatusCode, message: impl std::fmt::Display) -> Response { + full_json(status, &json!({"error": message.to_string()})) +} + +async fn register_session(req: Request, state: &ServerState) -> Response { + let RegisterSession { + registration, + workspace, + } = match read_json(req).await { + Ok(data) => data, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + }; + let id = registration.session_id.clone(); + let run = registration.run_id.clone(); + let lane = registration.logical_lane.clone(); + if lane.0.trim().is_empty() + || registration.harness.trim().is_empty() + || registration.scenario.trim().is_empty() + { + return problem( + StatusCode::UNPROCESSABLE_ENTITY, + "harness, logical_lane and scenario are required", + ); + } + if let Some(scenario) = &state.scenario { + if registration.scenario != scenario.spec().scenario { + return problem( + StatusCode::UNPROCESSABLE_ENTITY, + "registration scenario does not match server scenario", + ); + } + if workspace + .as_ref() + .is_none_or(|path| !path.is_absolute() || path.to_str().is_none()) + { + return problem( + StatusCode::UNPROCESSABLE_ENTITY, + "scenario sessions require an absolute workspace path", + ); + } + } + let mut routing = state.benchmark.write().unwrap(); + if let Err(error) = routing.registry.register(registration) { + return problem(StatusCode::CONFLICT, error); + } + if let Some(scenario) = &state.scenario + && let Err(error) = scenario.register_session(&id.0, lane.0, workspace.unwrap()) + { + routing.registry.remove_session(&id); + return problem(StatusCode::UNPROCESSABLE_ENTITY, error); + } + if let Err(error) = state.telemetry.register_session(&run, &id) { + routing.registry.remove_session(&id); + if let Some(scenario) = &state.scenario { + scenario.remove_session(&id.0); + } + return problem(StatusCode::CONFLICT, error); + } + let now = state.clock.elapsed_ns(); + let (run_start, count) = routing.runs.entry(run.clone()).or_insert((now, 0)); + *count += 1; + let run_start_ns = *run_start; + routing.sessions.insert( + id.clone(), + Arc::new(SessionActivity { + attempts: AtomicUsize::new(0), + run_start_ns, + registered_ns: now - run_start_ns, + finalized_ns: AtomicU64::new(u64::MAX), + }), + ); + full_json(StatusCode::CREATED, &json!({"runId": run, "sessionId": id})) +} + +async fn session_route( + method: Method, + suffix: &str, + req: Request, + state: &ServerState, +) -> Response { + let (id, action) = suffix.split_once('/').unwrap_or((suffix, "")); + if id.is_empty() { + return problem(StatusCode::NOT_FOUND, "session ID is required"); + } + let id = SessionId(id.into()); + match (method, action) { + (Method::GET, "") => { + let query = match SessionQuery::parse(req.uri().query()) { + Ok(query) => query, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + }; + session_detail(state, &id, query) + } + (Method::POST, "observations") => { + let observation = match read_json::(req).await { + Ok(observation) => observation, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + }; + let routing = state.benchmark.read().unwrap(); + let Some(record) = routing.registry.get(&id) else { + return problem(StatusCode::NOT_FOUND, "unknown session"); + }; + if !record.active { + return problem(StatusCode::CONFLICT, "session is finalized"); + } + let Some(scenario) = &state.scenario else { + return problem( + StatusCode::UNPROCESSABLE_ENTITY, + "runner observation requires a configured scenario", + ); + }; + match scenario.record_runner_observation(&id.0, observation) { + Ok(()) => full_json(StatusCode::OK, &json!({"recorded": true})), + Err(error) => problem(StatusCode::UNPROCESSABLE_ENTITY, error), + } + } + (Method::POST, "finalize") => { + let body = match read_admin_body(req).await { + Ok(body) => body, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + }; + let proof = if body.is_empty() { + None + } else { + match serde_json::from_slice::>(&body) { + Ok(proof) => proof, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + } + }; + let mut routing = state.benchmark.write().unwrap(); + let Some(activity) = routing.sessions.get(&id) else { + return problem(StatusCode::NOT_FOUND, "unknown session"); + }; + if activity.attempts.load(Ordering::Acquire) != 0 { + return problem(StatusCode::CONFLICT, "session still has in-flight attempts"); + } + if let Some(proof) = proof { + let Some(scenario) = &state.scenario else { + return problem( + StatusCode::UNPROCESSABLE_ENTITY, + "completion proof requires a configured scenario", + ); + }; + if let Err(error) = scenario.verify_completion( + &id.0, + CompletionProof { + response_id: proof.response_id, + observed_markers: proof.observed_markers, + }, + ) { + return problem(StatusCode::UNPROCESSABLE_ENTITY, error); + } + } + let _ = activity.finalized_ns.compare_exchange( + u64::MAX, + state.clock.elapsed_ns() - activity.run_start_ns, + Ordering::Relaxed, + Ordering::Relaxed, + ); + routing.registry.finalize(&id); + let summary = state + .telemetry + .finalize(&id.0) + .expect("registered telemetry"); + full_json(StatusCode::OK, &json!(summary)) + } + (Method::DELETE, "") => { + let query = match SessionQuery::parse(req.uri().query()) { + Ok(query) => query, + Err(error) => return problem(StatusCode::BAD_REQUEST, error), + }; + let mut routing = state.benchmark.write().unwrap(); + let Some(record) = routing.registry.get(&id) else { + return problem(StatusCode::NOT_FOUND, "unknown session"); + }; + if record.active { + return problem( + StatusCode::CONFLICT, + "finalize the session before deleting it", + ); + } + let Some((cursor, through)) = query.cursor.zip(query.after) else { + return problem( + StatusCode::BAD_REQUEST, + "export acknowledgement requires cursor and after", + ); + }; + let run = record.run_id.clone(); + if !state.telemetry.acknowledge_export(&id.0, cursor, through) { + return problem( + StatusCode::CONFLICT, + "acknowledge the finalized session and its final attempt cursor", + ); + } + routing.registry.remove_session(&id); + let activity = routing.sessions.remove(&id); + routing.lineage.remove_owner(&id); + if let Some((_, count)) = routing.runs.get_mut(&run) { + *count -= 1; + if *count == 0 { + routing.runs.remove(&run); + } + } + let retired = routing.responses.remove(&id); + state.watchdog.remove_session(&id.0); + state.sessions.remove(&id.0); + if let Some(scenario) = &state.scenario { + scenario.remove_session(&id.0); + } + drop(routing); + drop((retired, activity)); + full_json(StatusCode::OK, &json!({"deleted": true})) + } + _ => problem(StatusCode::NOT_FOUND, "unknown session route"), + } +} + +fn session_detail( + state: &ServerState, + id: &SessionId, + query: SessionQuery<'_>, +) -> Response { + let (activity, metadata) = { + let routing = state.benchmark.read().unwrap(); + let Some(activity) = routing.sessions.get(id) else { + return problem(StatusCode::NOT_FOUND, "unknown session"); + }; + let record = routing.registry.get(id).expect("registered session"); + ( + activity.clone(), + json!({ + "harness": record.harness, "logicalLane": record.logical_lane, + "scenario": record.scenario, "launchMode": record.launch_mode, + }), + ) + }; + let Some(mut detail) = state.telemetry.session_detail(&id.0, None, usize::MAX) else { + return problem(StatusCode::NOT_FOUND, "unknown session"); + }; + let after = query.after.unwrap_or(0); + let all_items = std::mem::take(&mut detail.items); + let compactions: Vec<_> = all_items.iter().filter(|item| item.span.checkpoint_id.is_some() || item.span.adopted_checkpoint_id.is_some()) + .map(|item| json!({ + "cursor":item.cursor, "checkpointId":item.span.checkpoint_id, + "adoptedCheckpointId":item.span.adopted_checkpoint_id, "purpose":item.span.purpose, + "outcome":item.span.outcome, "effectiveContextBytes":item.span.effective_context_bytes, + })).collect(); + let spans: Vec<_> = all_items.iter().map(|item| item.span.clone()).collect(); + let end = activity + .finalized_ns + .load(Ordering::Relaxed) + .min(state.clock.elapsed_ns() - activity.run_start_ns); + let attribution = compute_attribution(activity.registered_ns, end, &spans); + let mut items = all_items.into_iter().filter(|item| item.cursor > after); + detail.items = items.by_ref().take(query.limit()).collect(); + if items.next().is_some() { + detail.next_cursor = detail.items.last().map_or(after, |item| item.cursor); + } else { + detail.next_cursor = after.max(detail.summary.attempts); + } + let mut response = json!(detail); + response["registration"] = metadata; + response["compactions"] = json!(compactions); + response["attribution"] = json!(attribution); + response["audit"] = json!(state.watchdog.session_audit(&id.0)); + response["violations"] = json!(state.watchdog.violations_for_session(&id.0)); + full_json(StatusCode::OK, &response) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MockAiBuilder; + use crate::plan::TurnPlan; + use crate::routing::{RequestClassifier, RequestUse, SideKind}; + use crate::scenario::{ + BenchmarkTrack, CanonicalAction, CompactionMode, FaultKind, ScenarioSpec, ScheduledFault, + }; + use futures_util::{SinkExt, StreamExt}; + use reqwest::{Client, Response as ClientResponse, StatusCode}; + use serde_json::Value; + use tokio_tungstenite::{connect_async, tungstenite::Message}; + + async fn post(client: &Client, url: &str, body: Value) -> ClientResponse { + client + .post(url) + .header("content-type", "application/json") + .body(body.to_string()) + .send() + .await + .unwrap() + } + + async fn body(response: ClientResponse, status: StatusCode) -> Value { + let actual = response.status(); + let text = response.text().await.unwrap(); + assert_eq!(actual, status, "{text}"); + serde_json::from_str(&text).unwrap() + } + + async fn register(client: &Client, origin: &str, session: &str, harness: &str) { + let response = post( + client, + &format!("{origin}/admin/sessions"), + json!({ + "run_id": "run", "session_id": session, "harness": harness, + "logical_lane": session, "scenario": "fixture", + "workspace": std::env::current_dir().unwrap(), + }), + ) + .await; + body(response, StatusCode::CREATED).await; + } + + #[tokio::test] + async fn runner_can_report_harness_termination_without_a_followup_model_turn() { + let scenario = ScenarioSpec::new("fixture", 42, "fixture", BenchmarkTrack::Native) + .with_step( + "unknown", + CanonicalAction::UnknownTool { + name: "unlisted_fixture_tool".into(), + expect_handling: crate::scenario::FailureHandling::HarnessTermination, + }, + ) + .with_step( + "finish", + CanonicalAction::FinalAnswer { + text: "scenario continued".into(), + expect_markers: Vec::new(), + }, + ); + let server = MockAiBuilder::new() + .scenario(scenario) + .start() + .await + .unwrap(); + let client = Client::new(); + let origin = server.origin_url(); + register(&client, &origin, "one", "opencode").await; + let responses = format!("{origin}/s/run/one/v1/responses"); + let request = json!({"input": "begin"}); + let issued = body( + post(&client, &responses, request.clone()).await, + StatusCode::OK, + ) + .await; + let call = &issued["output"][0]; + assert_eq!(call["name"], "unlisted_fixture_tool"); + let observations = format!("{origin}/admin/sessions/one/observations"); + let observation = json!({ + "sessionId": "one", + "attempt": 1, + "callId": call["call_id"], + "kind": "harnessTermination", + "detail": "harness exited after the unknown call" + }); + let mut foreign = observation.clone(); + foreign["sessionId"] = json!("two"); + body( + post(&client, &observations, foreign).await, + StatusCode::UNPROCESSABLE_ENTITY, + ) + .await; + assert_eq!( + body( + post(&client, &observations, observation).await, + StatusCode::OK + ) + .await, + json!({"recorded": true}) + ); + let after = body( + post(&client, &responses, request).await, + StatusCode::UNPROCESSABLE_ENTITY, + ) + .await; + assert_eq!( + after["error"]["message"], + "the runner reported harness termination" + ); + } + + #[tokio::test] + async fn context_overflow_advances_after_the_client_returns_its_summary() { + let scenario = ScenarioSpec::new("fixture", 42, "fixture", BenchmarkTrack::Native) + .with_step( + "compact", + CanonicalAction::TriggerCompaction { + mode: CompactionMode::ContextOverflow { + actual_bytes: 8_000, + limit_bytes: 4_000, + }, + proof_marker: "overflow-proof".into(), + }, + ) + .with_step( + "finish", + CanonicalAction::FinalAnswer { + text: "continued after compaction".into(), + expect_markers: Vec::new(), + }, + ); + let server = MockAiBuilder::new() + .scenario(scenario) + .start() + .await + .unwrap(); + let client = Client::new(); + let origin = server.origin_url(); + register(&client, &origin, "one", "codex").await; + let responses = format!("{origin}/s/run/one/v1/responses"); + + let overflow = body( + post(&client, &responses, json!({"input": "begin"})).await, + StatusCode::BAD_REQUEST, + ) + .await; + assert_eq!(overflow["error"]["code"], "context_length_exceeded"); + let summary = post(&client, &responses, json!({ + "model": "gpt-5", "stream": true, "store": false, + "input": [ + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "begin"}]}, + {"type": "message", "role": "user", "content": [{"type": "input_text", + "text": "You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task."}]}, + {"type": "message", "role": "developer", "content": [{"type": "input_text", "text": "Executed tools: shell_command"}]} + ] + })).await; + assert_eq!(summary.status(), StatusCode::OK); + let stream = summary.text().await.unwrap(); + let summary = stream + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .map(|data| serde_json::from_str::(data).unwrap()) + .find(|event| event["type"] == "response.completed") + .unwrap()["response"] + .clone(); + let summary_text = summary["output"][0]["content"][0]["text"].as_str().unwrap(); + let (checkpoint_id, marker) = summary_text.split_once(' ').unwrap(); + assert_eq!(marker, "overflow-proof"); + + let continued = body( + post(&client, &responses, json!({ + "input": [ + {"type": "message", "role": "user", "content": [{"type": "input_text", + "text": format!("Here is the summary produced by the other language model:\n{summary_text}")}]}, + {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "continue"}]} + ] + })).await, + StatusCode::OK, + ).await; + assert_eq!( + continued["output"][0]["content"][0]["text"], + "continued after compaction" + ); + let detail = body( + client + .get(format!("{origin}/admin/sessions/one")) + .send() + .await + .unwrap(), + StatusCode::OK, + ) + .await; + let compactions = detail["compactions"].as_array().unwrap(); + assert!(compactions.iter().any(|event| { + event["purpose"] == "compact" && event["checkpointId"] == checkpoint_id + })); + assert!( + compactions + .iter() + .any(|event| event["adoptedCheckpointId"] == checkpoint_id) + ); + } + + #[tokio::test] + async fn scenario_retry_compaction_and_export_stay_inside_registered_session() { + let scenario = ScenarioSpec::new("fixture", 42, "fixture", BenchmarkTrack::Native) + .with_step( + "compact", + CanonicalAction::TriggerCompaction { + mode: CompactionMode::Native, + proof_marker: "proof-token".into(), + }, + ) + .with_step( + "finish", + CanonicalAction::FinalAnswer { + text: "verified result".into(), + expect_markers: vec!["verified".into()], + }, + ) + .with_fault(ScheduledFault { + step: "compact".into(), + attempt: 1, + at: Default::default(), + emit: FaultKind::Http429, + }); + let server = MockAiBuilder::new() + .scenario(scenario) + .start() + .await + .unwrap(); + let origin = server.origin_url(); + let client = Client::new(); + register(&client, &origin, "one", "opencode").await; + register(&client, &origin, "two", "opencode").await; + let scoped = format!("{origin}/s/run/one/v1"); + let responses = format!("{scoped}/responses"); + + let forbidden = client + .get(format!("{origin}/s/run/one/metrics")) + .send() + .await + .unwrap(); + assert_eq!(forbidden.status(), StatusCode::FORBIDDEN); + let unknown = client + .get(format!("{scoped}/unknown")) + .send() + .await + .unwrap(); + let unknown = body(unknown, StatusCode::NOT_FOUND).await; + assert!(unknown.to_string().contains("/s/run/one/v1/unknown")); + + let count = post( + &client, + &format!("{scoped}/messages/count_tokens"), + json!({ + "system": "sys", "messages": [{"role": "user", "content": "hello"}] + }), + ) + .await; + assert_eq!(body(count, StatusCode::OK).await, json!({"input_tokens":4})); + + let title = client + .post(&responses) + .header("x-maka-bench-request-use", "title") + .body(json!({"input":"title only","stream":true}).to_string()) + .send() + .await + .unwrap(); + assert!(title.text().await.unwrap().contains("Benchmark task")); + assert_eq!(server.request_count(), 0); + + let request = json!({"model":"gpt-5", "input":"explore"}); + let conflict = client + .post(&responses) + .header("x-maka-bench-session", "two") + .body(request.to_string()) + .send() + .await + .unwrap(); + assert_eq!( + body(conflict, StatusCode::BAD_REQUEST).await["error"]["code"], + "session_identity_conflict" + ); + let fault = body( + post(&client, &responses, request.clone()).await, + StatusCode::TOO_MANY_REQUESTS, + ) + .await; + assert_eq!(fault["error"]["type"], "rate_limit_error"); + let issued = body(post(&client, &responses, request).await, StatusCode::OK).await; + let previous = issued["id"].as_str().unwrap(); + let compact = body( + post( + &client, + &format!("{responses}/compact"), + json!({ + "model":"gpt-5", "previous_response_id": previous, + "input":[{"role":"user","content":"explore"}] + }), + ) + .await, + StatusCode::OK, + ) + .await; + assert_eq!(compact["object"], "response.compaction"); + assert_eq!( + compact["output"][1]["encrypted_content"], + "mock:proof-token" + ); + let finished = body( + post( + &client, + &responses, + json!({ + "model":"gpt-5", "previous_response_id": compact["id"], + "input":[compact["output"][1].clone()] + }), + ) + .await, + StatusCode::OK, + ) + .await; + assert_eq!( + finished["output"][0]["content"][0]["text"], + "verified result" + ); + let id = finished["id"].as_str().unwrap(); + let own = client + .get(format!("{responses}/{id}")) + .send() + .await + .unwrap(); + assert_eq!(body(own, StatusCode::OK).await["id"], id); + let foreign = client + .get(format!("{origin}/s/run/two/v1/responses/{id}")) + .send() + .await + .unwrap(); + assert_eq!(foreign.status(), StatusCode::NOT_FOUND); + + let endpoint = format!("{origin}/admin/sessions/one"); + let detail = body(client.get(&endpoint).send().await.unwrap(), StatusCode::OK).await; + let items = detail["items"].as_array().unwrap(); + let main: Vec<_> = items + .iter() + .filter(|span| span["purpose"] == "main") + .collect(); + assert_eq!(main.len(), 3); + assert_eq!(main[0]["outcome"], "injected_fault"); + assert_eq!(main[0]["revision"], main[1]["revision"]); + assert_ne!(main[0]["attempt"], main[1]["attempt"]); + assert_eq!(main[2]["adoptedCheckpointId"], compact["output"][1]["id"]); + assert!(items.iter().any(|span| span["purpose"] == "title" + && span["firstSemanticDeltaNs"].as_u64().unwrap() + >= span["firstByteNs"].as_u64().unwrap())); + assert!(detail["attribution"]["mockUnionNs"].as_u64().unwrap() > 0); + + let reset = client + .post(format!("{origin}/admin/reset")) + .send() + .await + .unwrap(); + assert_eq!(reset.status(), StatusCode::CONFLICT); + let summary = body( + post( + &client, + &format!("{endpoint}/finalize"), + json!({ + "responseId":id, "observedMarkers":["verified"], + }), + ) + .await, + StatusCode::OK, + ) + .await; + assert_eq!(summary["finalized"], true); + let deleted = client + .delete(format!( + "{endpoint}?cursor={}&after={}", + summary["cursor"], summary["attempts"] + )) + .send() + .await + .unwrap(); + assert_eq!(body(deleted, StatusCode::OK).await, json!({"deleted":true})); + assert_eq!( + client.get(&endpoint).send().await.unwrap().status(), + StatusCode::NOT_FOUND + ); + server.shutdown().await; + } + + #[tokio::test] + async fn websocket_warmup_and_side_turn_leave_transient_main_baseline_intact() { + let mut classifier = RequestClassifier::default(); + classifier + .model_aliases + .insert("title".into(), RequestUse::Side(SideKind::Title)); + let server = MockAiBuilder::new() + .strict_benchmark(true) + .request_classifier(classifier) + .scripted([ + TurnPlan::text("first").with_response_id("r1"), + TurnPlan::text("second").with_response_id("r2"), + ]) + .start() + .await + .unwrap(); + let origin = server.origin_url(); + let client = Client::new(); + register(&client, &origin, "one", "codex").await; + let url = format!("ws://{}/s/run/one/v1/responses", server.addr()); + + async fn reply( + ws: &mut tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, + request: Value, + ) -> Value { + ws.send(Message::text(request.to_string())).await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(2), async { + let mut created = None; + loop { + let message = ws.next().await.unwrap().unwrap(); + if let Message::Text(text) = message { + let event: Value = serde_json::from_str(&text).unwrap(); + match event["type"].as_str() { + Some("response.created") => { + assert!(created.replace(event["response"]["id"].clone()).is_none()); + } + Some("response.completed") => { + assert_eq!(created, Some(event["response"]["id"].clone())); + return event; + } + Some("error") => return event, + _ => {} + } + } + } + }) + .await + .unwrap() + } + + let (mut ws, _) = connect_async(&url).await.unwrap(); + let warmup = reply( + &mut ws, + json!({"type":"response.create", "model":"gpt-5", "generate":false}), + ) + .await; + assert_eq!(warmup["response"]["output"], json!([])); + assert_eq!(warmup["response"]["usage"]["input_tokens"], 0); + assert_eq!(warmup["response"]["usage"]["output_tokens"], 0); + let warmup_id = warmup["response"]["id"].as_str().unwrap(); + assert_eq!(server.metrics().responses_ws_turns, 0); + let first = reply( + &mut ws, + json!({"type":"response.create", "model":"gpt-5", "input":"first","store":false, + "previous_response_id":warmup_id}), + ) + .await; + assert_eq!(first["response"]["id"], "r1"); + let side = reply( + &mut ws, + json!({"type":"response.create", "model":"title","input":"title"}), + ) + .await; + assert_eq!( + side["response"]["output"][0]["content"][0]["text"], + "Benchmark task" + ); + + let (mut other, _) = connect_async(&url).await.unwrap(); + let continuation = json!({"type":"response.create", "model":"gpt-5", "previous_response_id":"r1", "input":"next"}); + let rejected = reply(&mut other, continuation.clone()).await; + assert_eq!(rejected["error"]["code"], "previous_response_not_found"); + let second = reply(&mut ws, continuation).await; + assert_eq!(second["response"]["id"], "r2"); + let transient = client + .get(format!("{origin}/s/run/one/v1/responses/r1")) + .send() + .await + .unwrap(); + assert_eq!(transient.status(), StatusCode::NOT_FOUND); + server.shutdown().await; + } +} diff --git a/tools/mock-ai/src/server/http.rs b/tools/mock-ai/src/server/http.rs index 72bd95c17a1..2adfbf97d61 100644 --- a/tools/mock-ai/src/server/http.rs +++ b/tools/mock-ai/src/server/http.rs @@ -19,23 +19,26 @@ use super::admin::handle_admin; use super::{ - ActiveStreamGuard, BoxBody, FlushStatus, PendingWsUpgrade, ServerState, TtftTracker, - TurnCloseGuard, classify_protocol, collect_headers, default_response_id, error_http_response, - extract_stored_response_id, full_json, is_responses_path, is_semantic_delta_frame, jitter_ms, - json_with_headers, pacer_seed_for, plan_usage_hint, semantic_event_bytes, spawn_tracked, - sse_response, + ActiveStreamGuard, Attempt, BoxBody, DeliveredItem, PendingWsUpgrade, ServerState, + TurnCloseGuard, collect_headers, default_response_id, effective_history, endpoint_protocol, + error_http_response, event_usage, full_json, initial_usage, jitter_ms, json_with_headers, + spawn_tracked, }; -use crate::codec::{WireFrame, create_encoder}; -use crate::handler::{CloseSignalGuard, InteractiveCommand, TurnContext, TurnDecision}; +use crate::codec::{EncodedFrame, FrameKind, WireFrame}; +use crate::handler::{CloseSignalGuard, InteractiveCommand, TurnDecision}; +use crate::metrics::{AttemptOutcome, RequestPurpose}; use crate::pacing::{LatencyProfile, TurnPacer}; use crate::plan::{CloseSignal, FinishReason, HttpErrorSpec, TurnEvent, Usage}; use crate::protocol::{NormalizedRequest, Protocol, Transport, normalize_request}; #[cfg(feature = "proxy")] -use crate::proxy::{ReplayConfig, fingerprint_from_normalized}; +use crate::proxy::{ + ExchangeKind, ReplayConfig, compute_fingerprint_for_lane, fingerprint_from_route, +}; use crate::ratelimit::{RateLimitDecision, RateLimitHeaders, RateLimitLease}; +use crate::routing::{CompactKind, EndpointKind, ParsedRoute, RequestUse, ResponseId, parse_route}; use crate::schema_synth::{WirePoisonConfig, poison_sse_frame}; +use crate::watchdog::HistorySize; use bytes::Bytes; -#[cfg(feature = "proxy")] use http_body_util::StreamBody; use http_body_util::{BodyExt, Full, Limited}; use hyper::body::{Frame, Incoming}; @@ -55,85 +58,175 @@ pub(super) async fn handle_http_request( state: Arc, pending_upgrade: Arc>>, ) -> Response { + let started = Instant::now(); + let headers_ns = state.clock.elapsed_ns(); let method = req.method().clone(); - let path = req.uri().path().to_owned(); - let query = req.uri().query().map(str::to_owned); - #[cfg(feature = "proxy")] - let path_and_query = req - .uri() - .path_and_query() - .map(|pq| pq.as_str().to_owned()) - .unwrap_or_else(|| path.clone()); + let uri = req.uri().clone(); let headers = collect_headers(req.headers()); + let is_ws_upgrade = headers + .get("upgrade") + .is_some_and(|v| v.eq_ignore_ascii_case("websocket")); + let route = parse_route( + method.as_str(), + uri.path(), + uri.query(), + is_ws_upgrade, + &state.control.extra_get_routes, + ); - // 1) Prometheus /metrics and Admin routes (do not require provider API key) - if method == Method::GET && path == "/metrics" { - let body = state - .metrics - .render_prometheus(state.watchdog.total_violations()); - let bytes = Bytes::from(body); - return Response::builder() - .status(StatusCode::OK) - .header( - header::CONTENT_TYPE, - "text/plain; version=0.0.4; charset=utf-8", - ) - .header(header::CONTENT_LENGTH, bytes.len()) - .body( - Full::new(bytes) - .map_err(|never| match never {}) - .boxed_unsync(), - ) - .unwrap(); + match route.endpoint { + EndpointKind::ScopedForbidden => { + return full_json( + StatusCode::FORBIDDEN, + &json!({"error": format!("admin and metrics are unavailable under session scope: {}", route.raw_path)}), + ); + } + EndpointKind::Metrics => { + let body = state.render_prometheus(); + let bytes = Bytes::from(body); + return Response::builder() + .header( + header::CONTENT_TYPE, + "text/plain; version=0.0.4; charset=utf-8", + ) + .header(header::CONTENT_LENGTH, bytes.len()) + .body( + Full::new(bytes) + .map_err(|never| match never {}) + .boxed_unsync(), + ) + .unwrap(); + } + EndpointKind::Admin => { + return if state.control.enable_admin_api { + state + .metrics + .control_plane_requests + .fetch_add(1, Ordering::Relaxed); + handle_admin(method, route.canonical_path, req, state).await + } else { + unknown_route(&state, &method, route.raw_path) + }; + } + _ => {} } - if state.control.enable_admin_api && path.starts_with("/admin/") { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - return handle_admin(method, &path, req, state).await; + + let protocol = endpoint_protocol(&route.endpoint).unwrap_or(Protocol::OpenaiChatCompletions); + let attempt = Attempt::new(&state, protocol, Transport::Http, started, headers_ns); + let mut response = handle_provider_request( + &mut req, + &state, + pending_upgrade, + &method, + &route, + headers, + &attempt, + ) + .await; + let status = response.status().as_u16(); + attempt.http_status(status); + if status == 101 { + return response; } + let sse = response.extensions().get::().is_some(); + let semantic = !sse && attempt.expects_semantic_body(); + let delivery = response.extensions_mut().remove::(); + response.map(|inner| { + AttemptBody { + inner, + attempt, + sse, + semantic, + delivery, + } + .boxed_unsync() + }) +} - // 2) Auth check for provider endpoints - if !state.auth.verify(&headers) { - let proto = classify_protocol(&path).unwrap_or(Protocol::OpenaiChatCompletions); +#[allow(clippy::too_many_arguments)] +async fn handle_provider_request( + req: &mut Request, + state: &Arc, + pending_upgrade: Arc>>, + method: &Method, + route: &ParsedRoute<'_>, + headers: BTreeMap, + attempt: &Attempt, +) -> Response { + #[cfg(feature = "proxy")] + let mut headers = headers; + let protocol = attempt.0.protocol; + // Attach early when headers suffice so an interrupted upload still has a session. + if state.auth.verify(&headers) { + let _ = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ); + } else { return error_http_response( - proto, + protocol, &HttpErrorSpec::new(401, "authentication_error", "invalid API key"), - &state.metrics, + attempt, ); } - // 3) Responses WebSocket Upgrade on GET /v1/responses or /responses - let is_ws_upgrade = headers - .get("upgrade") - .is_some_and(|v| v.eq_ignore_ascii_case("websocket")); - if is_ws_upgrade && is_responses_path(&path) { + #[cfg(feature = "proxy")] + let path_and_query = req + .uri() + .path_and_query() + .map_or(route.raw_path, |pq| pq.as_str()) + .to_owned(); + #[cfg(feature = "proxy")] + if let Some(lane) = attempt.lane() { + headers.insert(crate::proxy::SCOPE_LANE_HEADER.into(), lane.0); + } + + if route.endpoint == EndpointKind::ResponsesWs { if let Some(reject_status) = state.tuning.reject_websocket_upgrade_status { return error_http_response( - Protocol::OpenaiResponsesWs, + protocol, &HttpErrorSpec::new( reject_status, "websocket_unavailable", "WebSocket upgrade rejected by mock server configuration", ), - &state.metrics, + attempt, ); } + let require_identity = route.scope.is_some(); + #[cfg(feature = "proxy")] + let require_identity = + require_identity || (state.strict_benchmark && state.proxy_recorder.is_some()); + if require_identity + && let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ) + { + return error_http_response(protocol, &spec, attempt); + } let Some(ws_key) = headers.get("sec-websocket-key") else { return full_json( StatusCode::BAD_REQUEST, - &json!({ "error": { "message": "missing Sec-WebSocket-Key" } }), + &json!({"error": {"message":"missing Sec-WebSocket-Key"}}), ); }; #[cfg(feature = "proxy")] - let proxied_upstream = if let Some(ref proxy) = state.proxy_recorder { + let proxied_upstream = if let Some(proxy) = &state.proxy_recorder { match proxy.connect_upstream_ws(&path_and_query, &headers).await { - Ok(upstream_ws) => Some(upstream_ws), - Err(err) => { + Ok(stream) => Some(stream), + Err(error) => { return full_json( StatusCode::BAD_GATEWAY, - &json!({ "error": { "type": "proxy_error", "message": err } }), + &json!({"error": {"type":"proxy_error", "message":error}}), ); } } @@ -142,8 +235,11 @@ pub(super) async fn handle_http_request( }; let accept = derive_accept_key(ws_key.as_bytes()); *pending_upgrade.lock().unwrap() = Some(PendingWsUpgrade { - on_upgrade: hyper::upgrade::on(&mut req), - path, + on_upgrade: hyper::upgrade::on(req), + path: route.raw_path.into(), + scope: route.scope.clone(), + canonical_offset: route.raw_path.len() - route.canonical_path.len(), + query: route.query.map(str::to_owned), #[cfg(feature = "proxy")] path_and_query, headers, @@ -164,103 +260,178 @@ pub(super) async fn handle_http_request( .unwrap(); } - // 4) Read request body (supports chunked/streaming upload without requiring Content-Length) - let body_bytes = match Limited::new(req.into_body(), state.tuning.max_request_bytes) + let body_bytes = match Limited::new(req.body_mut(), state.tuning.max_request_bytes) .collect() .await { - Ok(collected) => collected.to_bytes(), - Err(err) => { - return full_json( - StatusCode::PAYLOAD_TOO_LARGE, - &json!({ "error": { "message": format!("request body read error: {err}") } }), + Ok(body) => body.to_bytes(), + Err(error) if error.is::() => { + return error_http_response( + protocol, + &crate::schema_synth::payload_too_large_error(protocol), + attempt, + ); + } + Err(error) => { + attempt.outcome(AttemptOutcome::TransportError, Some(400)); + return error_http_response( + protocol, + &HttpErrorSpec::new( + 400, + "invalid_request_error", + format!("request body read error: {error}"), + ), + attempt, ); } }; + attempt.body_read(body_bytes.len()); - // 4b) Transparent HTTP proxy-record mode (forwards all provider endpoints to upstream & records cassette) #[cfg(feature = "proxy")] - if let Some(ref proxy) = state.proxy_recorder { + if let Some(proxy) = &state.proxy_recorder { + if state.strict_benchmark || route.scope.is_some() { + let body = match serde_json::from_slice::(&body_bytes) { + Ok(body) => body, + Err(_) if body_bytes.is_empty() => Value::Null, + Err(error) => { + return error_http_response( + protocol, + &HttpErrorSpec::new(400, "invalid_request_error", error.to_string()), + attempt, + ); + } + }; + let parent = body["previous_response_id"] + .as_str() + .map(|id| ResponseId(id.into())); + if let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &body, + parent.as_ref(), + false, + ) { + return error_http_response(protocol, &spec, attempt); + } + if let Some(lane) = attempt.lane() { + headers.insert(crate::proxy::SCOPE_LANE_HEADER.into(), lane.0); + } + } state.metrics.proxy_requests.fetch_add(1, Ordering::Relaxed); - let proto = (method == Method::POST) - .then(|| classify_protocol(&path)) - .flatten(); - match proxy + let proxied = match proxy .forward_http( method.as_str(), &path_and_query, - proto, + (*method == Method::POST) + .then(|| endpoint_protocol(&route.endpoint)) + .flatten(), &headers, body_bytes, state.shutdown.clone(), ) .await { - Ok(proxied) => { - let metrics = state.metrics.clone(); - let rx = proxied.rx; - let stream = futures_util::stream::unfold(rx, move |mut rx| { - let metrics = metrics.clone(); - async move { - let item = rx.recv().await?; - let mapped = match item { - Ok(bytes) => { - metrics - .bytes_sent - .fetch_add(bytes.len() as u64, Ordering::Relaxed); - Ok(Frame::data(bytes)) - } - Err(msg) => Err(io::Error::other(msg)), - }; - Some((mapped, rx)) - } - }); - let mut builder = Response::builder().status( - StatusCode::from_u16(proxied.status).unwrap_or(StatusCode::BAD_GATEWAY), - ); - for (k, v) in proxied.headers { - if let (Ok(name), Ok(val)) = ( - HeaderName::from_bytes(k.as_bytes()), - HeaderValue::from_str(&v), - ) { - builder = builder.header(name, val); - } - } - return builder - .body(StreamBody::new(stream).boxed_unsync()) - .unwrap(); - } - Err(err) => { + Ok(proxied) => proxied, + Err(error) => { return full_json( StatusCode::BAD_GATEWAY, - &json!({ "error": { "type": "proxy_error", "message": err } }), + &json!({"error": {"type":"proxy_error", "message":error}}), ); } + }; + let stream = futures_util::stream::unfold(proxied.rx, |mut rx| async move { + let item = rx.recv().await?.map(Frame::data).map_err(io::Error::other); + Some((item, rx)) + }); + let mut builder = Response::builder() + .status(StatusCode::from_u16(proxied.status).unwrap_or(StatusCode::BAD_GATEWAY)); + for (k, v) in proxied.headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::from_bytes(k.as_bytes()), + HeaderValue::from_str(&v), + ) { + builder = builder.header(name, value); + } } + return builder + .body(StreamBody::new(stream).boxed_unsync()) + .unwrap(); } - // 5) Custom dynamic route hook (runs BEFORE built-in control-plane & generation routes so - // tests can override /v1/models, add static scripts, or emit custom status/headers) - if let Some(custom) = &state.custom_route - && let Some(resp) = custom(method.as_str(), &path, &headers, &body_bytes) - { + let record_control = || { state .metrics .control_plane_requests .fetch_add(1, Ordering::Relaxed); state .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); + .record_control(method.as_str(), route.raw_path, route.query, &headers); + }; + if route.scope.is_some() + && !matches!( + route.endpoint, + EndpointKind::Unknown + | EndpointKind::GetResponse(_) + | EndpointKind::DeleteResponse(_) + | EndpointKind::ChatCompletions + | EndpointKind::AnthropicMessages + | EndpointKind::AnthropicCountTokens + | EndpointKind::ResponsesCreate + | EndpointKind::ResponsesCompact + ) + && let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ) + { + return error_http_response(protocol, &spec, attempt); + } + if let Some(custom) = &state.custom_route + && let Some(resp) = custom(method.as_str(), route.canonical_path, &headers, &body_bytes) + { + if state.strict_benchmark || route.scope.is_some() { + let body = match serde_json::from_slice::(&body_bytes) { + Ok(body) => body, + Err(_) if body_bytes.is_empty() => Value::Null, + Err(error) => { + attempt.outcome(AttemptOutcome::ParseFailed, Some(400)); + return error_http_response( + protocol, + &HttpErrorSpec::new(400, "invalid_request_error", error.to_string()), + attempt, + ); + } + }; + let parent = body["previous_response_id"] + .as_str() + .map(|id| ResponseId(id.into())); + if let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &body, + parent.as_ref(), + false, + ) { + return error_http_response(protocol, &spec, attempt); + } + } + record_control(); let bytes = Bytes::from(resp.body); let mut builder = Response::builder() .status(StatusCode::from_u16(resp.status).unwrap_or(StatusCode::OK)) .header(header::CONTENT_LENGTH, bytes.len()); for (k, v) in &resp.headers { - if let (Ok(name), Ok(val)) = ( + if let (Ok(name), Ok(value)) = ( HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v), ) { - builder = builder.header(name, val); + builder = builder.header(name, value); } } return builder @@ -272,285 +443,518 @@ pub(super) async fn handle_http_request( .unwrap(); } - // 6) Control plane GET/DELETE endpoints - if method == Method::GET { - if path == "/v1/models" || path == "/models" || path.ends_with("/models") { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - let page = state.control.render_models_page(query.as_deref()); - return full_json(StatusCode::OK, &page); - } - if let Some(id) = extract_stored_response_id(&path) { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - return match state.stored_responses.get(id) { - Some(resp) => full_json(StatusCode::OK, &resp), - None => full_json( - StatusCode::NOT_FOUND, - &json!({ "error": { "type": "not_found", "message": format!("response '{id}' not found") } }), - ), - }; - } - if (path == "/api/usage/token/" || path == "/api/usage/token") - && let Some(payload) = &state.control.relay_token_usage - { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - return full_json(StatusCode::OK, payload); - } - if path == "/v1/usage" - && let Some(payload) = &state.control.v1_usage + #[cfg(feature = "proxy")] + if let Some(replayer) = &state.cassette_replayer + && (matches!( + route.endpoint, + EndpointKind::GetResponse(_) | EndpointKind::DeleteResponse(_) + ) || ((replayer.config().strict_replay || state.strict_benchmark) + && matches!( + route.endpoint, + EndpointKind::Models + | EndpointKind::ModelById(_) + | EndpointKind::RelayTokenUsage + | EndpointKind::V1Usage + | EndpointKind::ExtraGet(_) + ))) + { + if let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ) && (state.strict_benchmark || route.scope.is_some()) { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - return full_json(StatusCode::OK, payload); + return error_http_response(protocol, &spec, attempt); } - if let Some(payload) = state.control.extra_get_routes.get(&path) { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - return full_json(StatusCode::OK, payload); + let body = serde_json::from_slice::(&body_bytes).unwrap_or(Value::Null); + let lane = attempt.replay_lane(&headers); + let fingerprint = compute_fingerprint_for_lane( + ExchangeKind::Http, + method.as_str(), + &route.canonical_path_and_query(), + body["model"].as_str().unwrap_or(""), + &body, + lane.as_ref(), + ); + match replayer.try_next_http_if(&fingerprint, |candidate| { + candidate.fingerprint == fingerprint + }) { + Ok(exchange) => { + record_control(); + attempt.record(|metrics| { + metrics.replay_hits.fetch_add(1, Ordering::Relaxed); + }); + attempt.ready(None); + return execute_http_replay( + exchange.clone(), + replayer.config().clone(), + RateLimitHeaders::default(), + None, + attempt.clone(), + state.clone(), + ); + } + Err(error) if replayer.config().strict_replay || state.strict_benchmark => { + return error_http_response(protocol, &replay_miss(error), attempt); + } + Err(_) => {} } } - if method == Method::DELETE - && let Some(id) = extract_stored_response_id(&path) - { - state - .metrics - .control_plane_requests - .fetch_add(1, Ordering::Relaxed); - state - .recorder - .record_control(method.as_str(), &path, query.as_deref(), &headers); - let deleted = state.stored_responses.delete(id); - return if deleted { - full_json( + match &route.endpoint { + EndpointKind::Models => { + record_control(); + return full_json( StatusCode::OK, - &json!({ "id": id, "object": "response.deleted", "deleted": true }), - ) - } else { - full_json( - StatusCode::NOT_FOUND, - &json!({ "error": { "type": "not_found", "message": format!("response '{id}' not found") } }), - ) - }; + &state.control.render_models_page(route.query), + ); + } + EndpointKind::ModelById(id) => { + record_control(); + return match state.control.find_model(id) { + Some(model) => full_json(StatusCode::OK, &model), + None => error_http_response( + protocol, + &HttpErrorSpec::new(404, "not_found", format!("model '{id}' not found")), + attempt, + ), + }; + } + EndpointKind::GetResponse(id) | EndpointKind::DeleteResponse(id) => { + record_control(); + let not_found = || { + full_json( + StatusCode::NOT_FOUND, + &json!({"error": {"type": "not_found", "message": format!("response '{id}' not found")}}), + ) + }; + if state + .resolve_identity( + attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ) + .is_err() + { + return not_found(); + } + let owner = attempt.owner(); + let response_id = ResponseId(id.clone()); + if matches!(route.endpoint, EndpointKind::GetResponse(_)) { + return if let Some(owner) = owner { + let response = state + .benchmark + .read() + .unwrap() + .responses + .get(&owner) + .and_then(|bucket| bucket.entries.get(&response_id)) + .map(|(response, _)| response.clone()); + response.map_or_else(not_found, |response| { + full_json(StatusCode::OK, response.as_ref()) + }) + } else { + state + .stored_responses + .get(id) + .map_or_else(not_found, |response| full_json(StatusCode::OK, &response)) + }; + } + let deleted = if let Some(owner) = owner { + let mut routing = state.benchmark.write().unwrap(); + let deleted = routing.lineage.delete_owned(&owner, &response_id); + let retired = if deleted { + routing + .responses + .get_mut(&owner) + .and_then(|bucket| bucket.remove(&response_id)) + } else { + None + }; + drop(routing); + drop(retired); + deleted + } else { + state.stored_responses.delete(id) + }; + return if deleted { + full_json( + StatusCode::OK, + &json!({"id": id, "object":"response.deleted", "deleted":true}), + ) + } else { + not_found() + }; + } + EndpointKind::RelayTokenUsage | EndpointKind::V1Usage | EndpointKind::ExtraGet(_) => { + let payload = match &route.endpoint { + EndpointKind::RelayTokenUsage => state.control.relay_token_usage.as_ref(), + EndpointKind::V1Usage => state.control.v1_usage.as_ref(), + EndpointKind::ExtraGet(path) => state.control.extra_get_routes.get(path), + _ => unreachable!(), + }; + if let Some(payload) = payload { + record_control(); + return full_json(StatusCode::OK, payload); + } + return unknown_route(state, method, route.raw_path); + } + EndpointKind::Unknown => return unknown_route(state, method, route.raw_path), + _ => {} } - // 7) Generation routes (POST /v1/chat/completions, /v1/responses, /v1/messages) - let Some(protocol) = (method == Method::POST) - .then(|| classify_protocol(&path)) - .flatten() - else { - return full_json( - StatusCode::NOT_FOUND, - &json!({ "error": { "type": "not_found", "message": format!("unknown route: {method} {path}") } }), - ); - }; - - let raw_body: Value = match serde_json::from_slice(&body_bytes) { - Ok(val) => val, - Err(err) => { + let raw_body = match serde_json::from_slice::(&body_bytes) { + Ok(body) if body.is_object() => body, + result => { + let detail = result + .err() + .map_or_else(|| "expected a JSON object".into(), |err| err.to_string()); + attempt.outcome(AttemptOutcome::ParseFailed, Some(400)); return error_http_response( protocol, - &HttpErrorSpec::new( - 400, - "invalid_request_error", - format!("malformed JSON request body: {err}"), - ), - &state.metrics, + &HttpErrorSpec::new(400, "invalid_request_error", detail), + attempt, ); } }; - - let seq = state.next_sequence(); - let normalized = normalize_request( - seq, + let mut normalized = normalize_request( + state.next_sequence(), protocol, Transport::Http, - path, + route.raw_path.into(), headers, body_bytes, raw_body, ); - let turn_started = Instant::now(); - state - .metrics - .record_protocol(protocol, normalized.prompt_bytes); - state.recorder.record(&normalized); - state.watchdog.inspect_request(&normalized); - - let effective_profile = state.profile.effective(); - - // Stateful rate-limit admission (RPM, ITPM, concurrency slots) - let (rl_headers, rl_lease) = match state.rate_limiter.check_and_acquire( - normalized.api_key(), - &normalized.model, - normalized.estimated_input_tokens, - effective_profile.rate_limit_override.as_ref(), + let parent_id = normalized.previous_response_id.clone().map(ResponseId); + attempt.classified(&normalized, RequestPurpose::Unclassified); + if let Err(spec) = state.resolve_identity( + attempt, + route.scope.as_ref(), + &normalized.headers, + &normalized.raw_body, + parent_id.as_ref(), + false, ) { - RateLimitDecision::Allowed { headers, lease } => (headers, lease), - RateLimitDecision::Rejected { - retry_after_ms, - reason, - headers, - } => { - let mut spec = HttpErrorSpec::rate_limit( - Some(retry_after_ms.div_ceil(1000).max(1)), - format!("rate limit exceeded ({reason})"), - ) - .with_retry_after_ms(retry_after_ms); - for (k, v) in headers.to_header_pairs() { - spec.headers.insert(k.to_string(), v); + return error_http_response(protocol, &spec, attempt); + } + let purpose = state.classify(route, &mut normalized, attempt); + let metric_purpose = if route.endpoint == EndpointKind::AnthropicCountTokens { + RequestPurpose::CountTokens + } else { + RequestPurpose::from(&purpose) + }; + attempt.classified(&normalized, metric_purpose); + + let main = purpose == RequestUse::Main; + let profile = state.profile.effective(); + let (rl_headers, rl_lease) = if main { + attempt.record(|metrics| { + metrics.record_protocol(protocol, normalized.prompt_bytes); + state.recorder.record(&normalized); + }); + match state.rate_limiter.check_and_acquire( + normalized.api_key(), + &normalized.model, + normalized.estimated_input_tokens, + profile.rate_limit_override.as_ref(), + ) { + RateLimitDecision::Allowed { headers, lease } => (headers, lease), + RateLimitDecision::Rejected { + retry_after_ms, + reason, + headers, + } => { + let mut spec = HttpErrorSpec::rate_limit( + Some(retry_after_ms.div_ceil(1000).max(1)), + format!("rate limit exceeded ({reason})"), + ) + .with_retry_after_ms(retry_after_ms); + for (key, value) in headers.to_header_pairs() { + spec.headers.insert(key.into(), value); + } + return error_http_response(protocol, &spec, attempt); } - state.metrics.record_dimension( - protocol, - &normalized.model, - "429", - normalized.estimated_input_tokens, - 0, - 0, - None, - Some(turn_started.elapsed().as_millis() as u64), - ); - return error_http_response(protocol, &spec, &state.metrics); } + } else { + (RateLimitHeaders::default(), None) }; - // Cassette replay mode (checked before strict previous_response_id so multi-turn recorded - // Responses HTTP cassettes replay faithfully without pre-populating stored_responses, while - // still rejecting requests whose previous_response_id disagrees with the recorded exchange). #[cfg(feature = "proxy")] - if let Some(ref replayer) = state.cassette_replayer { - let fp = fingerprint_from_normalized(&normalized); - let strict_prev = - protocol == Protocol::OpenaiResponsesHttp && state.tuning.strict_previous_response_id; - let expected_prev = normalized.previous_response_id.as_deref(); - if let Some(ex) = replayer - .next_http_if(&fp, |candidate| { - !strict_prev - || expected_prev == candidate.request_body["previous_response_id"].as_str() - }) - .cloned() - { - state.metrics.replay_hits.fetch_add(1, Ordering::Relaxed); - return execute_http_replay( - normalized, - ex, - replayer.config().clone(), - rl_headers, - rl_lease, - turn_started, - state, - ); + if let Some(replayer) = &state.cassette_replayer { + let lane = attempt.lane(); + let fingerprint = + fingerprint_from_route(&normalized, method.as_str(), route, lane.as_ref()); + let strict_prev = protocol.is_responses() && state.tuning.strict_previous_response_id; + match replayer.try_next_http_if(&fingerprint, |candidate| { + !strict_prev + || normalized.previous_response_id.as_deref() + == candidate.request_body["previous_response_id"].as_str() + }) { + Ok(exchange) => { + state.metrics.replay_hits.fetch_add(1, Ordering::Relaxed); + attempt.admitted(None); + attempt.ready(None); + return execute_http_replay( + exchange.clone(), + replayer.config().clone(), + rl_headers, + rl_lease, + attempt.clone(), + state.clone(), + ); + } + Err(error) if replayer.config().strict_replay => { + return error_http_response(protocol, &replay_miss(error), attempt); + } + Err(_) => {} } } - // Strict previous_response_id check for HTTP Responses - if protocol == Protocol::OpenaiResponsesHttp - && state.tuning.strict_previous_response_id - && let Some(prev_id) = &normalized.previous_response_id - && !state.stored_responses.contains(prev_id) - { + if route.endpoint == EndpointKind::AnthropicCountTokens { state - .watchdog - .record_invalid_previous_response_id(&normalized, prev_id); - state.metrics.record_dimension( - protocol, - &normalized.model, - "400", - normalized.estimated_input_tokens, - 0, - 0, - None, - Some(turn_started.elapsed().as_millis() as u64), - ); - return error_http_response( - protocol, - &HttpErrorSpec { - status: 400, - error_type: "invalid_request_error".into(), - code: Some("previous_response_not_found".into()), - message: format!("previous_response_id '{prev_id}' not found"), - retry_after_secs: None, - retry_after_ms: None, - headers: BTreeMap::new(), - raw_body: None, - raw_text: None, - content_type: None, - }, - &state.metrics, + .metrics + .control_plane_requests + .fetch_add(1, Ordering::Relaxed); + state.recorder.record_control( + method.as_str(), + route.raw_path, + route.query, + &normalized.headers, ); + let size = &normalized.size_breakdown; + let tokens = size.estimated_history_tokens + + (size.tools_bytes as u64).div_ceil(4) + + (size.system_bytes as u64).div_ceil(4); + attempt.usage(Usage::new(tokens, 0)); + attempt.admitted(None); + return full_json(StatusCode::OK, &crate::control::render_count_tokens(tokens)); } - let session_turn = state.sessions.next_turn(&normalized.session_key); - let ctx = TurnContext { - global_turn: seq, - session_turn, - chaos_override: effective_profile.chaos_override.clone(), - }; - - let decision = match state.handler.handle(&normalized, &ctx).await { - Some(d) => d, - None => { - return error_http_response( - protocol, - &HttpErrorSpec::new( - 500, - "mock_handler_exhausted", - "no handler matched or scripted queue was exhausted", - ), - &state.metrics, - ); + let parent = match state.check_parent(&normalized, attempt, None) { + Ok(parent) => parent, + Err(spec) => { + if main { + attempt.record(|_| { + state.watchdog.record_invalid_previous_response_id( + &normalized, + normalized.previous_response_id.as_deref().unwrap(), + ) + }); + } + return error_http_response(protocol, &spec, attempt); } }; + attempt.admitted(parent.as_ref()); + let history = effective_history(&normalized, parent.as_ref()); + let normalized = Arc::new(normalized); + + if purpose == RequestUse::Compact(CompactKind::ResponsesEndpoint) { + attempt.audit(normalized.clone(), &purpose, history); + let output = state.compaction(&normalized, Some(attempt)); + let id = format!("resp_compact_{}", normalized.sequence); + let retained: Vec<_> = match &normalized.raw_body["input"] { + Value::String(text) => vec![json!({"type":"message", "role":"user", + "content":[{"type":"input_text", "text":text}]})], + input => input + .as_array() + .into_iter() + .flatten() + .filter(|item| item["role"] == "user") + .cloned() + .collect(), + }; + let retained_bytes = retained + .iter() + .map(|value| value.to_string().len()) + .sum::(); + let usage = Usage::new( + normalized.estimated_input_tokens + + parent.as_ref().map_or(0, |p| p.effective_context_tokens), + (output.encrypted_content.len() as u64).div_ceil(4), + ); + let compacted_bytes = retained_bytes + output.encrypted_content.len(); + let result = crate::control::render_responses_compact( + &id, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + &output.id, + &output.encrypted_content, + retained, + &usage, + ); + attempt.ready(Some(&id)); + attempt.usage(usage); + let mut response = full_json(StatusCode::OK, &result); + response.extensions_mut().insert(NonStreamDelivery { + items: vec![DeliveredItem::Compaction { + id: output.id, + bytes: compacted_bytes, + }], + response: Some(ResponsePublication { + id, + value: result, + store: normalized.options.store.unwrap_or(true), + history: HistorySize { + bytes: compacted_bytes, + tokens: (compacted_bytes as u64).div_ceil(4), + }, + }), + request: normalized, + }); + return response; + } - let store_flag = normalized.raw_body["store"].as_bool().unwrap_or(true); + let decision = match state + .decide(&normalized, &purpose, &profile, attempt, parent.as_ref()) + .await + { + Ok(decision) => decision, + Err(spec) => return error_http_response(protocol, &spec, attempt), + }; + if main || matches!(purpose, RequestUse::Compact(_)) { + attempt.audit(normalized.clone(), &purpose, history); + } + let store = normalized.options.store.unwrap_or(true); execute_http_turn( normalized, decision, - store_flag, - effective_profile.latency, + store, + if main { + profile.latency + } else { + LatencyProfile::default() + }, rl_headers, rl_lease, - turn_started, - state, + history, + attempt.clone(), + state.clone(), ) .await } +fn unknown_route(state: &ServerState, method: &Method, path: &str) -> Response { + state.unknown_routes.fetch_add(1, Ordering::Relaxed); + full_json( + StatusCode::NOT_FOUND, + &json!({"error": {"type":"not_found", + "message": format!("unknown route: {method} {path}")}}), + ) +} + +#[derive(Clone)] +struct TrackedSse; + +struct AttemptBody { + inner: BoxBody, + attempt: Attempt, + sse: bool, + semantic: bool, + delivery: Option, +} + +#[derive(Clone)] +struct NonStreamDelivery { + request: Arc, + items: Vec, + response: Option, +} + +#[derive(Clone)] +struct ResponsePublication { + id: String, + value: Value, + store: bool, + history: HistorySize, +} + +impl NonStreamDelivery { + fn deliver(self, attempt: &Attempt) { + for item in self.items { + item.deliver(attempt, &self.request); + } + attempt.deliver_summary(&self.request); + if let Some(response) = self.response { + attempt.0.state.publish_response( + &self.request, + attempt, + response.id, + response.value, + response.store, + response.history, + ); + } + } +} + +impl hyper::body::Body for AttemptBody { + type Data = Bytes; + type Error = io::Error; + + fn poll_frame( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll, io::Error>>> { + let result = std::pin::Pin::new(&mut self.inner).poll_frame(cx); + if !self.sse + && let std::task::Poll::Ready(Some(Ok(frame))) = &result + && let Some(data) = frame.data_ref() + { + self.attempt.frame(data.len(), self.semantic); + if let Some(delivery) = self.delivery.take() { + delivery.deliver(&self.attempt); + } + } + if matches!(result, std::task::Poll::Ready(Some(Err(_)))) && !self.sse { + self.attempt.outcome(AttemptOutcome::TransportError, None); + } + if !self.sse + && (self.inner.is_end_stream() || matches!(result, std::task::Poll::Ready(None))) + { + self.attempt.body_completed(); + } + result + } + + fn size_hint(&self) -> hyper::body::SizeHint { + self.inner.size_hint() + } + + fn is_end_stream(&self) -> bool { + self.inner.is_end_stream() + } +} + +impl Drop for AttemptBody { + fn drop(&mut self) { + self.attempt + .with_span(|span, now| span.body_dropped_ns = Some(now)); + } +} + +#[cfg(feature = "proxy")] +fn replay_miss(error: crate::proxy::ReplayError) -> HttpErrorSpec { + let mut spec = HttpErrorSpec::new(422, "invalid_request_error", error.to_string()); + spec.code = Some("cassette_replay_miss".into()); + spec +} + #[cfg(feature = "proxy")] fn execute_http_replay( - req: NormalizedRequest, exchange: crate::proxy::RecordedExchange, replay_cfg: ReplayConfig, rl_headers: RateLimitHeaders, rl_lease: Option, - turn_started: Instant, + attempt: Attempt, state: Arc, ) -> Response { let (tx, rx) = mpsc::channel::, io::Error>>(16); @@ -560,6 +964,7 @@ fn execute_http_replay( } let status = StatusCode::from_u16(exchange.status).unwrap_or(StatusCode::OK); let state_clone = state.clone(); + let replay_attempt = attempt.clone(); spawn_tracked(state, async move { let _lease = rl_lease; @@ -568,43 +973,23 @@ fn execute_http_replay( .active_streams .fetch_add(1, Ordering::Relaxed); let _guard = ActiveStreamGuard(state_clone.metrics.clone()); - let mut first_recorded: Option = None; - for chunk in exchange.chunks { - let delay = replay_cfg.scaled_delay(chunk.delay_ms); - if !delay.is_zero() { - tokio::select! { - _ = state_clone.shutdown.cancelled() => break, - _ = tx.closed() => break, - _ = tokio::time::sleep(delay) => {} - } - } - let bytes = chunk.to_bytes(); - let len = bytes.len(); - if tx.send(Ok(Frame::data(bytes))).await.is_err() { - break; - } - if first_recorded.is_none() { - let ttft = turn_started.elapsed().as_millis() as u64; - state_clone.metrics.ttft_ms.record(ttft); - first_recorded = Some(ttft); + if !replay_attempt + .wait(replay_cfg.scaled_delay(chunk.delay_ms), tx.closed()) + .await + || tx.send(Ok(Frame::data(chunk.to_bytes()))).await.is_err() + { + return; } - state_clone - .metrics - .bytes_sent - .fetch_add(len as u64, Ordering::Relaxed); } - let dur = turn_started.elapsed().as_millis() as u64; - state_clone.metrics.turn_duration_ms.record(dur); - state_clone.metrics.record_dimension( - req.protocol, - &req.model, - &status.as_u16().to_string(), - req.estimated_input_tokens, - 0, - 0, - first_recorded, - Some(dur), + let completed = exchange.outcome == crate::proxy::ExchangeOutcome::Completed; + replay_attempt.outcome( + if completed { + AttemptOutcome::Completed + } else { + AttemptOutcome::InjectedFault + }, + Some(status.as_u16()), ); }); @@ -637,6 +1022,14 @@ enum HttpEventFeed { } impl HttpEventFeed { + fn initial_usage(&self, req: &NormalizedRequest) -> TurnEvent { + let events = match self { + Self::Plan { events, .. } => events.as_slice(), + Self::Interactive { .. } => &[], + }; + initial_usage(events, req) + } + fn is_plan(&self) -> bool { matches!(self, Self::Plan { .. }) } @@ -653,7 +1046,7 @@ impl HttpEventFeed { async fn next_event( &mut self, shutdown: &tokio_util::sync::CancellationToken, - tx_closed: Option<&mpsc::Sender, io::Error>>>, + tx_closed: Option<&SseSender>, ) -> FeedStep { match self { Self::Plan { events, .. } => { @@ -695,7 +1088,7 @@ impl HttpEventFeed { async fn wait_stall( &mut self, shutdown: &tokio_util::sync::CancellationToken, - tx_closed: Option<&mpsc::Sender, io::Error>>>, + tx_closed: Option<&SseSender>, ) -> StallOutcome { match self { Self::Plan { .. } => { @@ -781,17 +1174,16 @@ enum ResolvedHttpDecision { #[allow(clippy::too_many_arguments)] async fn execute_http_turn( - req: NormalizedRequest, + req: Arc, decision: TurnDecision, store_flag: bool, latency_profile: LatencyProfile, rl_headers: RateLimitHeaders, - mut rl_lease: Option, - turn_started: Instant, + rl_lease: Option, + history: HistorySize, + attempt: Attempt, state: Arc, ) -> Response { - // Unwrap interactive turns that reply with a full TurnPlan so they share 100% of - // the Plan execution path (leading Delay+HttpError, TTFT/pacing, on_close, headers, etc.). let resolved = match decision { TurnDecision::Plan(mut plan) => { let close_guard = TurnCloseGuard::new(CloseSignalGuard(plan.on_close.take())); @@ -801,20 +1193,22 @@ async fn execute_http_turn( } } TurnDecision::Interactive(mut stream) => { - // Hold stream.closed in an RAII guard BEFORE the first await so client disconnect - // (Hyper dropping this future) or server shutdown always wakes TurnHandle::wait_closed(). let mut close_guard = TurnCloseGuard::new(CloseSignalGuard(Some(CloseSignal(stream.closed.clone())))); let first = tokio::select! { - _ = state.shutdown.cancelled() => { - return full_json( - StatusCode::SERVICE_UNAVAILABLE, - &json!({ "error": { "message": "server shutting down" } }), - ); - } - ev = stream.events.recv() => ev, + _ = state.shutdown.cancelled() => return shutdown_response(&attempt, req.protocol), + event = stream.events.recv() => event, }; match first { + Some(InteractiveCommand::Plan { plan, on_close }) => { + close_guard.attach(on_close); + ResolvedHttpDecision::Plan { plan, close_guard } + } + Some(InteractiveCommand::Event(first)) => ResolvedHttpDecision::Interactive { + first, + stream, + close_guard, + }, None => { return finish_http_error( &req, @@ -824,776 +1218,560 @@ async fn execute_http_turn( "interactive TurnHandle dropped before reply", ), &rl_headers, - turn_started, - &state, + &attempt, ); } - Some(InteractiveCommand::Plan { plan, on_close }) => { - close_guard.attach(on_close); - ResolvedHttpDecision::Plan { plan, close_guard } - } - Some(InteractiveCommand::Event(first_event)) => { - if let TurnEvent::HttpError(spec) = *first_event { - return finish_http_error(&req, &spec, &rl_headers, turn_started, &state); - } - ResolvedHttpDecision::Interactive { - first: first_event, - stream, - close_guard, - } - } } } }; - - let ( - mut feed, - response_id_override, - model_override, - mut response_headers, - close_connection, - wire_poison, - pre_usage, - usage_hint, - mut pacer, - ttft_dur, - close_guard, - ) = match resolved { + let (feed, plan, close_guard) = match resolved { ResolvedHttpDecision::Plan { plan, close_guard } => { - let plan = *plan; - // Handle pre-stream HTTP error (including optional leading Delay before HttpError). - // Only sleep here when the prefix ends in HttpError so normal Delay -> Text plans - // sleep once inside the event loop. - match plan.events.as_slice() { - [TurnEvent::HttpError(spec), ..] => { - return finish_http_error(&req, spec, &rl_headers, turn_started, &state); - } - [TurnEvent::Delay { ms }, TurnEvent::HttpError(spec), ..] => { - tokio::select! { - _ = state.shutdown.cancelled() => { - return full_json( - StatusCode::SERVICE_UNAVAILABLE, - &json!({ "error": { "message": "server shutting down" } }), - ); - } - _ = tokio::time::sleep(Duration::from_millis(*ms)) => {} - } - return finish_http_error(&req, spec, &rl_headers, turn_started, &state); - } - _ => {} + let mut plan = *plan; + attempt.ready(plan.response_id.as_deref()); + if let [TurnEvent::Delay { ms }, TurnEvent::HttpError(_), ..] = plan.events.as_slice() + && !attempt + .wait(Duration::from_millis(*ms), std::future::pending()) + .await + { + return shutdown_response(&attempt, req.protocol); + } + if let [TurnEvent::HttpError(spec), ..] + | [TurnEvent::Delay { .. }, TurnEvent::HttpError(spec), ..] = plan.events.as_slice() + { + return finish_http_error(&req, spec, &rl_headers, &attempt); } - let inferred_finish = plan.inferred_finish_reason(); - let usage_hint = plan_usage_hint(&plan, &req); - let cached_tokens = usage_hint.cache_read_tokens.unwrap_or(0); - let uncached_tokens = usage_hint.input_tokens.saturating_sub(cached_tokens); - let in_flight_sample = state.metrics.active_streams.load(Ordering::Relaxed) + 1; - let mut pacer = TurnPacer::new( - latency_profile, - pacer_seed_for(&req), - in_flight_sample, - plan.ttft_ms, - (plan.chunk_delay_ms > 0).then_some(plan.chunk_delay_ms), - ); - let ttft_dur = pacer.compute_ttft(uncached_tokens, cached_tokens); - let pre_usage = plan.events.iter().find_map(|ev| match ev { - TurnEvent::Usage(u) => Some(u.clone()), - _ => None, - }); let feed = HttpEventFeed::Plan { - events: plan.events.into_iter(), + events: std::mem::take(&mut plan.events).into_iter(), inferred_finish, }; - ( - feed, - plan.response_id, - plan.model_override, - plan.response_headers, - plan.close_connection, - plan.wire_poison, - pre_usage, - usage_hint, - Some(pacer), - ttft_dur, - close_guard, - ) + (feed, plan, close_guard) } ResolvedHttpDecision::Interactive { first, stream, close_guard, } => { - let response_id = stream.response_id.lock().unwrap().clone(); - let usage_hint = Usage::new(req.estimated_input_tokens.max(1), 0); + if let TurnEvent::HttpError(spec) = &*first { + return finish_http_error(&req, spec, &rl_headers, &attempt); + } + let id = stream.response_id.lock().unwrap().clone(); let feed = HttpEventFeed::Interactive { pending: Some(first), rx: stream.events, }; ( feed, - response_id, - None, - BTreeMap::new(), - false, - WirePoisonConfig::default(), - None, - usage_hint, - None, - Duration::ZERO, + crate::plan::TurnPlan { + response_id: id, + ..Default::default() + }, close_guard, ) } }; - - let response_id = - response_id_override.unwrap_or_else(|| default_response_id(req.protocol, req.sequence)); - let model = model_override.unwrap_or_else(|| req.model.clone()); - for (k, v) in rl_headers.to_header_pairs() { - response_headers.entry(k.to_string()).or_insert(v); + let mut plan = plan; + let id = plan + .response_id + .take() + .unwrap_or_else(|| default_response_id(req.protocol, req.sequence)); + attempt.ready(Some(&id)); + let model = plan + .model_override + .take() + .unwrap_or_else(|| req.model.clone()); + let usage_event = feed.initial_usage(&req); + let usage = event_usage(&usage_event).unwrap().clone(); + attempt.usage(usage.clone()); + let mut pacer = feed.is_plan().then(|| { + let active = state.metrics.active_streams.load(Ordering::Relaxed) + 1; + super::turn_pacer(&req, &plan, &usage, &attempt, latency_profile, active) + }); + let wire_poison = plan.wire_poison; + let close_connection = plan.close_connection; + let mut headers = plan.response_headers; + for (key, value) in rl_headers.to_header_pairs() { + headers.entry(key.into()).or_insert(value); } + let mut encoder = state.encoder(&req, id, model); + for _ in encoder.encode_event(usage_event) {} - // 1) Non-streaming JSON HTTP response (unified for both Plan and Interactive!) if !req.stream { let _close_guard = close_guard; - if !ttft_dur.is_zero() { - tokio::select! { - _ = state.shutdown.cancelled() => {} - _ = tokio::time::sleep(ttft_dur) => {} - } - } - let mut encoder = create_encoder(req.protocol, response_id, model.clone(), false); - let mut scratch = Vec::new(); - if let Some(u) = pre_usage { - encoder.push_event(TurnEvent::Usage(u), &mut scratch); - } - let mut emitted_tool_ids = Vec::new(); - let mut emitted_compaction = false; - let mut semantic_output_bytes = 0usize; - let mut final_usage = usage_hint; - - loop { - match feed.next_event(&state.shutdown, None).await { - FeedStep::Aborted | FeedStep::Ended => break, - FeedStep::Event(ev) => { - let ev = *ev; - semantic_output_bytes += semantic_event_bytes(&ev); - match ev { - TurnEvent::Delay { ms } => { - tokio::select! { - _ = state.shutdown.cancelled() => break, - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} - } - } - TurnEvent::JitterDelay { min_ms, max_ms } => { - let ms = jitter_ms(min_ms, max_ms); - if ms > 0 { - tokio::select! { - _ = state.shutdown.cancelled() => break, - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} - } - } - } - TurnEvent::Stall => { - state.metrics.stalls_entered.fetch_add(1, Ordering::Relaxed); - if matches!( - feed.wait_stall(&state.shutdown, None).await, - StallOutcome::Ended - ) { - break; - } - } - TurnEvent::HttpError(spec) => { - return finish_http_error( - &req, - &spec, - &rl_headers, - turn_started, - &state, - ); - } - TurnEvent::Usage(u) => { - final_usage = u.clone(); - encoder.push_event(TurnEvent::Usage(u), &mut scratch); - } - TurnEvent::ToolCall(tc) => { - emitted_tool_ids.push(tc.id.clone()); - encoder.push_event(TurnEvent::ToolCall(tc), &mut scratch); - } - TurnEvent::NativeCompaction(c) => { - emitted_compaction = true; - state - .metrics - .native_compactions_emitted - .fetch_add(1, Ordering::Relaxed); - encoder.push_event(TurnEvent::NativeCompaction(c), &mut scratch); - } - TurnEvent::Finish { reason } => { - let completion = encoder.finish(reason, &mut scratch); - return complete_non_streaming( - &req, - &model, - completion, - store_flag, - &final_usage, - semantic_output_bytes, - &emitted_tool_ids, - emitted_compaction, - &response_headers, - close_connection, - &mut rl_lease, - turn_started, - &state, - ); - } - TurnEvent::DropConnection | TurnEvent::TruncateEof => { - return finish_http_error( - &req, - &HttpErrorSpec::new(500, "connection_error", "connection aborted"), - &rl_headers, - turn_started, - &state, - ); + let mut lease = rl_lease; + let mut feed = feed; + let mut usage = usage; + let mut semantic_bytes = 0; + let mut delivered = Vec::new(); + let reason = loop { + let event = match feed.next_event(&state.shutdown, None).await { + FeedStep::Aborted => return shutdown_response(&attempt, req.protocol), + FeedStep::Ended => break feed.auto_finish_reason().unwrap_or(FinishReason::Stop), + FeedStep::Event(event) => *event, + }; + match event { + TurnEvent::Delay { ms } => { + if !attempt + .wait(Duration::from_millis(ms), std::future::pending()) + .await + { + return shutdown_response(&attempt, req.protocol); + } + } + TurnEvent::JitterDelay { min_ms, max_ms } => { + let ms = pacer.as_mut().map_or_else( + || jitter_ms(min_ms, max_ms), + |pacer| pacer.jitter_ms(min_ms, max_ms), + ); + if !attempt + .wait(Duration::from_millis(ms), std::future::pending()) + .await + { + return shutdown_response(&attempt, req.protocol); + } + } + TurnEvent::Stall => { + attempt.record(|metrics| { + metrics.stalls_entered.fetch_add(1, Ordering::Relaxed); + }); + if matches!( + feed.wait_stall(&state.shutdown, None).await, + StallOutcome::Ended + ) { + return shutdown_response(&attempt, req.protocol); + } + } + TurnEvent::HttpError(spec) => { + return finish_http_error(&req, &spec, &rl_headers, &attempt); + } + TurnEvent::DropConnection + | TurnEvent::TruncateEof + | TurnEvent::MidStreamError(_) => { + return finish_http_error( + &req, + &HttpErrorSpec::new(500, "connection_error", "connection aborted"), + &rl_headers, + &attempt, + ); + } + TurnEvent::Finish { reason } => break reason, + event => { + if let Some(value) = event_usage(&event) { + usage = value.clone(); + attempt.usage(usage.clone()); + } + if let Some(item) = DeliveredItem::from_event(&event) { + item.issued(&attempt); + if let DeliveredItem::Compaction { bytes, .. } = item { + attempt.buffering(bytes); } - other => encoder.push_event(other, &mut scratch), + delivered.push(item); } + semantic_bytes += super::semantic_event_bytes(&event); + for _ in encoder.encode_event(event) {} } } + }; + if let Some(pacer) = pacer + && !attempt + .wait( + pacer.non_streaming_total_delay(semantic_bytes), + std::future::pending(), + ) + .await + { + return shutdown_response(&attempt, req.protocol); } - - let finish_reason = feed.auto_finish_reason().unwrap_or(FinishReason::Stop); - let completion = encoder.finish(finish_reason, &mut scratch); - return complete_non_streaming( - &req, - &model, - completion, - store_flag, - &final_usage, - semantic_output_bytes, - &emitted_tool_ids, - emitted_compaction, - &response_headers, - close_connection, - &mut rl_lease, - turn_started, - &state, - ); + let completion = encoder.finish_encoded(reason, &mut |_| {}); + usage.output_tokens = usage.output_tokens.max((semantic_bytes as u64) / 4); + if let Some(lease) = &mut lease { + lease.debit_output_tokens(usage.output_tokens); + } + attempt.usage(usage); + let mut response = json_with_headers(&completion.response_json, &headers, close_connection); + let publication = + if !completion.errored && req.protocol.is_responses() && attempt.can_publish() { + Some(ResponsePublication { + id: completion.response_id, + value: completion.response_json, + store: store_flag, + history: attempt.response_history(history, semantic_bytes), + }) + } else { + None + }; + if !delivered.is_empty() || publication.is_some() || attempt.has_summary() { + response.extensions_mut().insert(NonStreamDelivery { + items: delivered, + response: publication, + request: req, + }); + } + return response; } - // 2) Streaming SSE HTTP response (unified for both Plan and Interactive!) - let (tx, rx) = mpsc::channel::, io::Error>>(16); - let protocol = req.protocol; - let state_clone = state.clone(); - let ping_interval = pacer.as_ref().and_then(TurnPacer::sse_ping_interval); - + let (tx, rx) = mpsc::channel(16); + let producer_attempt = attempt.clone(); + let producer_state = state.clone(); + let producer_request = req.clone(); spawn_tracked(state, async move { + let state = producer_state; + let req = producer_request; + let attempt = producer_attempt; let mut lease = rl_lease; - state_clone - .metrics - .active_streams - .fetch_add(1, Ordering::Relaxed); - let _guard = ActiveStreamGuard(state_clone.metrics.clone()); let _close_guard = close_guard; - - let mut encoder = create_encoder(protocol, response_id, model.clone(), true); - let mut frames = Vec::new(); - let mut frame_seq = 0usize; - let mut first_delta_at: Option = None; - let mut recorded_ttft_ms: Option = None; - let mut emitted_semantic_bytes = 0usize; - let mut emitted_tool_ids: Vec = Vec::new(); - let mut emitted_compaction = false; - let mut final_usage = usage_hint; - - // Dynamic TTFT wait with optional SSE keep-alive ping comments. - let mut aborted = false; - if !ttft_dur.is_zero() { - let deadline = tokio::time::Instant::now() + ttft_dur; - loop { - let now = tokio::time::Instant::now(); - if now >= deadline { - break; + state.metrics.active_streams.fetch_add(1, Ordering::Relaxed); + let _stream = ActiveStreamGuard(state.metrics.clone()); + let mut feed = feed; + let mut usage = usage; + let mut writer = SseWriter { + tx, + attempt: &attempt, + req: &req, + pacer, + poison: wire_poison, + frame_index: 0, + semantic_bytes: 0, + }; + if !writer.prefill().await { + return; + } + let finish = loop { + let event = match feed.next_event(&state.shutdown, Some(&writer.tx)).await { + FeedStep::Aborted => return, + FeedStep::Ended => { + let Some(reason) = feed.auto_finish_reason() else { + attempt.outcome(AttemptOutcome::TransportError, Some(200)); + return; + }; + break reason; } - let remaining = deadline - now; - let step = ping_interval.map_or(remaining, |p| remaining.min(p)); - tokio::select! { - _ = state_clone.shutdown.cancelled() => { aborted = true; break; } - _ = tx.closed() => { aborted = true; break; } - _ = tokio::time::sleep(step) => { - if ping_interval.is_some() && tokio::time::Instant::now() < deadline { - let ping = if wire_poison.crlf_line_endings { - Bytes::from_static(b": keep-alive\r\n\r\n") - } else { - Bytes::from_static(b": keep-alive\n\n") - }; - if tx.send(Ok(Frame::data(ping))).await.is_err() { - aborted = true; - break; - } - } + FeedStep::Event(event) => *event, + }; + match event { + TurnEvent::Delay { ms } => { + if !writer.wait(ms).await { + return; } } - } - } - - // Pre-feed Usage so Anthropic message_start has exact input/cache tokens. - if !aborted && let Some(u) = pre_usage { - encoder.push_event(TurnEvent::Usage(u), &mut frames); - } - - let mut explicit_finish = false; - let mut intentional_fault = false; - - if !aborted { - loop { - let ev = match feed.next_event(&state_clone.shutdown, Some(&tx)).await { - FeedStep::Event(ev) => *ev, - FeedStep::Ended => break, - FeedStep::Aborted => { - aborted = true; - break; - } - }; - let ev_sem_bytes = semantic_event_bytes(&ev); - match ev { - TurnEvent::Delay { ms } => { - tokio::select! { - _ = state_clone.shutdown.cancelled() => { aborted = true; break; } - _ = tx.closed() => { aborted = true; break; } - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} - } - } - TurnEvent::JitterDelay { min_ms, max_ms } => { - let ms = jitter_ms(min_ms, max_ms); - if ms > 0 { - tokio::select! { - _ = state_clone.shutdown.cancelled() => { aborted = true; break; } - _ = tx.closed() => { aborted = true; break; } - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} - } - } + TurnEvent::JitterDelay { min_ms, max_ms } => { + let ms = writer.pacer.as_mut().map_or_else( + || jitter_ms(min_ms, max_ms), + |pacer| pacer.jitter_ms(min_ms, max_ms), + ); + if !writer.wait(ms).await { + return; } - TurnEvent::Stall => { - state_clone - .metrics - .stalls_entered - .fetch_add(1, Ordering::Relaxed); - match feed.wait_stall(&state_clone.shutdown, Some(&tx)).await { - StallOutcome::Resumed => continue, - StallOutcome::Ended => { - intentional_fault = true; - aborted = true; - break; - } + } + TurnEvent::Stall => { + attempt.record(|metrics| { + metrics.stalls_entered.fetch_add(1, Ordering::Relaxed); + }); + if matches!( + feed.wait_stall(&state.shutdown, Some(&writer.tx)).await, + StallOutcome::Ended + ) { + if feed.is_plan() && !state.shutdown.is_cancelled() { + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); } + return; } - TurnEvent::DropConnection => { - state_clone - .metrics + } + TurnEvent::DropConnection => { + attempt.record(|metrics| { + metrics .connection_drops_emitted .fetch_add(1, Ordering::Relaxed); - intentional_fault = true; - let _ = tx - .send(Err(io::Error::new( - io::ErrorKind::ConnectionReset, - "mock-ai simulated connection drop", - ))) - .await; - aborted = true; - break; - } - TurnEvent::TruncateEof => { - intentional_fault = true; - aborted = true; - break; - } - TurnEvent::MidStreamError(err) => { - state_clone - .metrics + }); + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); + let _ = writer + .tx + .send(Err(io::Error::new( + io::ErrorKind::ConnectionReset, + "mock-ai simulated connection drop", + ))) + .await; + return; + } + TurnEvent::TruncateEof => { + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); + return; + } + TurnEvent::HttpError(spec) => { + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); + let _ = writer + .send(encoder.encode_event(TurnEvent::HttpError(spec)), None) + .await; + return; + } + TurnEvent::MidStreamError(error) => { + attempt.record(|metrics| { + metrics .mid_stream_errors_emitted .fetch_add(1, Ordering::Relaxed); - intentional_fault = true; - encoder.push_event(TurnEvent::MidStreamError(err), &mut frames); - if !flush_http_frames( - &tx, - &mut frames, - None, - 0, - None, - &wire_poison, - &mut frame_seq, - &state_clone, - ) - .await - { - aborted = true; - break; - } - explicit_finish = true; - break; - } - TurnEvent::Finish { reason } => { - let completion = encoder.finish(reason, &mut frames); - if protocol.is_responses() && store_flag { - state_clone - .stored_responses - .put(completion.response_id, completion.response_json); - } - if !flush_http_frames( - &tx, - &mut frames, - None, - 0, - None, - &wire_poison, - &mut frame_seq, - &state_clone, - ) - .await - { - aborted = true; - break; - } - explicit_finish = true; - break; - } - TurnEvent::NativeCompaction(c) => { - state_clone - .metrics - .native_compactions_emitted - .fetch_add(1, Ordering::Relaxed); - encoder.push_event(TurnEvent::NativeCompaction(c), &mut frames); - let mut ttft = TtftTracker { - turn_started, - first_delta_at: &mut first_delta_at, - recorded_ttft_ms: &mut recorded_ttft_ms, - }; - let status = flush_http_frames_detailed( - &tx, - &mut frames, - pacer.as_mut(), - ev_sem_bytes, - Some(&mut ttft), - &wire_poison, - &mut frame_seq, - &state_clone, - ) + }); + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); + let _ = writer + .send(encoder.encode_event(TurnEvent::MidStreamError(error)), None) .await; - if status.all_wire_frames_sent { - emitted_compaction = true; - emitted_semantic_bytes += ev_sem_bytes; - } - if !status.continued { - aborted = true; - break; - } + return; + } + TurnEvent::Finish { reason } => break reason, + event => { + if let Some(value) = event_usage(&event) { + usage = value.clone(); + attempt.usage(usage.clone()); } - TurnEvent::Usage(u) => { - final_usage = u.clone(); - encoder.push_event(TurnEvent::Usage(u), &mut frames); + let delivered = DeliveredItem::from_event(&event); + if let Some(item) = &delivered { + item.issued(&attempt); + if let DeliveredItem::Compaction { bytes, .. } = item { + attempt.buffering(*bytes); + } } - other => { - let maybe_tool_id = match &other { - TurnEvent::ToolCall(tc) => Some(tc.id.clone()), - _ => None, - }; - encoder.push_event(other, &mut frames); - let mut ttft = TtftTracker { - turn_started, - first_delta_at: &mut first_delta_at, - recorded_ttft_ms: &mut recorded_ttft_ms, - }; - let status = flush_http_frames_detailed( - &tx, - &mut frames, - pacer.as_mut(), - ev_sem_bytes, - Some(&mut ttft), - &wire_poison, - &mut frame_seq, - &state_clone, + if !writer + .send( + encoder.encode_event(event), + delivered.map(SseDelivery::Item), ) - .await; - if status.all_wire_frames_sent { - if let Some(tid) = maybe_tool_id { - emitted_tool_ids.push(tid); - } - emitted_semantic_bytes += ev_sem_bytes; - } - if !status.continued { - aborted = true; - break; - } + .await + { + return; } } } + }; + let mut tail = Vec::new(); + let completion = encoder.finish_encoded(finish, &mut |frame| tail.push(frame)); + usage.output_tokens = usage.output_tokens.max((writer.semantic_bytes as u64) / 4); + if let Some(lease) = &mut lease { + lease.debit_output_tokens(usage.output_tokens); } - - if !aborted - && !explicit_finish - && !intentional_fault - && !encoder.is_finished() - && let Some(reason) = feed.auto_finish_reason() - { - let completion = encoder.finish(reason, &mut frames); - if protocol.is_responses() && store_flag { - state_clone - .stored_responses - .put(completion.response_id, completion.response_json); - } - if !flush_http_frames( - &tx, - &mut frames, - None, - 0, - None, - &wire_poison, - &mut frame_seq, - &state_clone, + attempt.usage(usage); + let effective = attempt.response_history(history, writer.semantic_bytes); + let _ = writer + .send( + tail.into_iter(), + Some(SseDelivery::Finish { + completion, + history: effective, + store: store_flag, + }), ) - .await - { - aborted = true; - } - } - - let dur = turn_started.elapsed().as_millis() as u64; - let out_toks = final_usage - .output_tokens - .max((emitted_semantic_bytes as u64) / 4); - let cached_tokens = final_usage.cache_read_tokens.unwrap_or(0); - if aborted && !intentional_fault { - state_clone - .metrics - .abandoned_streams - .fetch_add(1, Ordering::Relaxed); - state_clone.watchdog.record_turn_outcome( - &req, - &emitted_tool_ids, - emitted_compaction, - false, - ); - state_clone.metrics.record_dimension( - protocol, - &model, - "aborted", - final_usage.input_tokens, - out_toks, - cached_tokens, - recorded_ttft_ms, - Some(dur), - ); - } else { - state_clone.metrics.turn_duration_ms.record(dur); - if let Some(first_at) = first_delta_at - && out_toks > 0 - { - let tps = ((out_toks as f64) / first_at.elapsed().as_secs_f64().max(0.001)) - .round() - .max(1.0) as u64; - state_clone.metrics.effective_tps.record(tps); - } - if let Some(ref mut l) = lease { - l.debit_output_tokens(out_toks); - } - let status_label = if intentional_fault { "fault" } else { "200" }; - state_clone.metrics.record_dimension( - protocol, - &model, - status_label, - final_usage.input_tokens, - out_toks, - cached_tokens, - recorded_ttft_ms, - Some(dur), - ); - let completed_cleanly = !intentional_fault && (explicit_finish || feed.is_plan()); - state_clone.watchdog.record_turn_outcome( - &req, - &emitted_tool_ids, - emitted_compaction, - completed_cleanly, - ); - } + .await; }); - sse_response(rx, &response_headers, close_connection) + let stream = + futures_util::stream::unfold((rx, attempt, req), |(mut rx, attempt, req)| async move { + let chunk = rx.recv().await?; + let frame = chunk.map(|chunk: SseChunk| { + attempt.frame(chunk.bytes.len(), chunk.semantic); + if let Some(delivery) = chunk.delivery { + match delivery { + SseDelivery::Item(item) => item.deliver(&attempt, &req), + SseDelivery::Finish { + completion, + store, + history, + } => { + if completion.errored { + attempt.outcome(AttemptOutcome::InjectedFault, Some(200)); + } else { + attempt.deliver_summary(&req); + attempt.0.state.publish_response( + &req, + &attempt, + completion.response_id, + completion.response_json, + store, + history, + ); + attempt.outcome(AttemptOutcome::Completed, Some(200)); + } + } + } + } + Frame::data(chunk.bytes) + }); + Some((frame, (rx, attempt, req))) + }); + let mut response = super::sse_response( + StreamBody::new(stream).boxed_unsync(), + &headers, + close_connection, + ); + response.extensions_mut().insert(TrackedSse); + response } -fn finish_http_error( - req: &NormalizedRequest, - spec: &HttpErrorSpec, - rl_headers: &RateLimitHeaders, - turn_started: Instant, - state: &ServerState, -) -> Response { - let status_label = spec.status.to_string(); - let mut enriched = spec.clone(); - for (k, v) in rl_headers.to_header_pairs() { - enriched.headers.entry(k.to_string()).or_insert(v); - } - state.metrics.record_dimension( - req.protocol, - &req.model, - &status_label, - req.estimated_input_tokens, - 0, - 0, - None, - Some(turn_started.elapsed().as_millis() as u64), - ); - error_http_response(req.protocol, &enriched, &state.metrics) +type SseSender = mpsc::Sender>; + +struct SseChunk { + bytes: Bytes, + semantic: bool, + delivery: Option, } -#[allow(clippy::too_many_arguments)] -fn complete_non_streaming( - req: &NormalizedRequest, - model: &str, - completion: crate::codec::TurnCompletion, - store_flag: bool, - usage: &Usage, - semantic_output_bytes: usize, - emitted_tool_ids: &[String], - emitted_compaction: bool, - response_headers: &BTreeMap, - close_connection: bool, - rl_lease: &mut Option, - turn_started: Instant, - state: &ServerState, -) -> Response { - if req.protocol.is_responses() && store_flag { - state.stored_responses.put( - completion.response_id.clone(), - completion.response_json.clone(), - ); - } - let dur = turn_started.elapsed().as_millis() as u64; - state.metrics.ttft_ms.record(dur); - state.metrics.turn_duration_ms.record(dur); - let out_toks = usage.output_tokens.max((semantic_output_bytes as u64) / 4); - if let Some(lease) = rl_lease.as_mut() { - lease.debit_output_tokens(out_toks); - } - state.metrics.record_dimension( - req.protocol, - model, - "200", - usage.input_tokens, - out_toks, - usage.cache_read_tokens.unwrap_or(0), - Some(dur), - Some(dur), - ); - state - .watchdog - .record_turn_outcome(req, emitted_tool_ids, emitted_compaction, true); - json_with_headers( - completion.response_json, - response_headers, - close_connection, - &state.metrics, - ) +enum SseDelivery { + Item(DeliveredItem), + Finish { + completion: crate::codec::TurnCompletion, + history: HistorySize, + store: bool, + }, } -#[allow(clippy::too_many_arguments)] -async fn flush_http_frames( - tx: &mpsc::Sender, io::Error>>, - frames: &mut Vec, - pacer: Option<&mut TurnPacer>, +struct SseWriter<'a> { + tx: SseSender, + attempt: &'a Attempt, + req: &'a NormalizedRequest, + pacer: Option, + poison: WirePoisonConfig, + frame_index: usize, semantic_bytes: usize, - ttft: Option<&mut TtftTracker<'_>>, - wire_poison: &WirePoisonConfig, - frame_seq: &mut usize, - state: &ServerState, -) -> bool { - flush_http_frames_detailed( - tx, - frames, - pacer, - semantic_bytes, - ttft, - wire_poison, - frame_seq, - state, - ) - .await - .continued } -#[allow(clippy::too_many_arguments)] -async fn flush_http_frames_detailed( - tx: &mpsc::Sender, io::Error>>, - frames: &mut Vec, - mut pacer: Option<&mut TurnPacer>, - semantic_bytes: usize, - mut ttft: Option<&mut TtftTracker<'_>>, - wire_poison: &WirePoisonConfig, - frame_seq: &mut usize, - state: &ServerState, -) -> FlushStatus { - let total_frames = frames.len(); - let per_frame_sem_bytes = if semantic_bytes > 0 { - (semantic_bytes / total_frames.max(1)).max(1) - } else { - 0 - }; - let mut sent_frames = 0usize; - for frame in frames.drain(..) { - let raw_bytes = match frame { - WireFrame::Sse(b) | WireFrame::Raw(b) => b, - WireFrame::WsText(s) => Bytes::from(format!("data: {s}\n\n")), +impl SseWriter<'_> { + async fn wait(&self, ms: u64) -> bool { + self.attempt + .wait(Duration::from_millis(ms), self.tx.closed()) + .await + } + + async fn prefill(&self) -> bool { + let Some(pacer) = &self.pacer else { + return true; }; - let is_delta = - semantic_bytes > 0 && is_semantic_delta_frame(&String::from_utf8_lossy(&raw_bytes)); - let chunks = if wire_poison.is_active() { - let s = String::from_utf8_lossy(&raw_bytes).into_owned(); - poison_sse_frame(s, wire_poison, *frame_seq) - } else { - vec![raw_bytes] + let delay = pacer.initial_delay(); + let Some(ping) = pacer.sse_ping_interval() else { + return self.attempt.wait(delay, self.tx.closed()).await; }; - *frame_seq = frame_seq.wrapping_add(1); - - for chunk in chunks { - let len = chunk.len(); - if tx.send(Ok(Frame::data(chunk))).await.is_err() { - return FlushStatus { - all_wire_frames_sent: false, - continued: false, - }; + let deadline = tokio::time::Instant::now() + delay; + loop { + let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); + if !self + .attempt + .wait(remaining.min(ping), self.tx.closed()) + .await + { + return false; + } + if tokio::time::Instant::now() >= deadline { + return true; + } + let bytes = if self.poison.crlf_line_endings { + Bytes::from_static(b": keep-alive\r\n\r\n") + } else { + Bytes::from_static(b": keep-alive\n\n") + }; + if !self.chunk(bytes, false, None).await { + return false; } - state - .metrics - .bytes_sent - .fetch_add(len as u64, Ordering::Relaxed); } - sent_frames += 1; + } - // Record TTFT right after first actual semantic delta frame is sent, BEFORE pacing sleep. - if is_delta && let Some(ref mut tracker) = ttft { - tracker.record_once(&state.metrics); + async fn chunk(&self, bytes: Bytes, semantic: bool, delivery: Option) -> bool { + let chunk = SseChunk { + bytes, + semantic, + delivery, + }; + match self.tx.try_send(Ok(chunk)) { + Ok(()) => true, + Err(mpsc::error::TrySendError::Closed(_)) => false, + Err(mpsc::error::TrySendError::Full(chunk)) => { + let start = Instant::now(); + let sent = tokio::select! { + _ = self.attempt.0.state.shutdown.cancelled() => false, + result = self.tx.send(chunk) => result.is_ok(), + }; + self.attempt.backpressure(start.elapsed()); + sent + } } + } - if is_delta - && let Some(ref mut p) = pacer - && per_frame_sem_bytes > 0 - { - let delay = p.next_chunk_delay(per_frame_sem_bytes); - if !delay.is_zero() { - tokio::select! { - _ = state.shutdown.cancelled() => return FlushStatus { - all_wire_frames_sent: sent_frames == total_frames, - continued: false, - }, - _ = tx.closed() => return FlushStatus { - all_wire_frames_sent: sent_frames == total_frames, - continued: false, - }, - _ = tokio::time::sleep(delay) => {} + async fn send( + &mut self, + frames: impl Iterator, + mut delivery: Option, + ) -> bool { + let mut frames = frames.peekable(); + while let Some(frame) = frames.next() { + let last = if delivery.is_some() { + frames.peek().is_none() + } else { + false + }; + let EncodedFrame { + wire, + kind, + semantic_bytes, + } = frame; + let raw = match wire { + WireFrame::Sse(bytes) | WireFrame::Raw(bytes) => bytes, + WireFrame::WsText(text) => Bytes::from(format!("data: {text}\n\n")), + }; + let semantic = kind == FrameKind::SemanticDelta; + if self.poison.is_active() { + let chunks = poison_sse_frame( + String::from_utf8_lossy(&raw).into_owned(), + &self.poison, + self.frame_index, + ); + let count = chunks.len(); + for (index, chunk) in chunks.into_iter().enumerate() { + let final_chunk = index + 1 == count; + let delivered = if last && final_chunk { + delivery.take() + } else { + None + }; + if !self.chunk(chunk, semantic && final_chunk, delivered).await { + return false; + } } + self.frame_index = self.frame_index.wrapping_add(1); + } else if !self + .chunk(raw, semantic, if last { delivery.take() } else { None }) + .await + { + return false; + } + self.semantic_bytes += semantic_bytes; + if let Some(deadline) = self.pacer.as_mut().and_then(|pacer| { + pacer.next_frame_deadline(kind, semantic_bytes, tokio::time::Instant::now()) + }) && !self.attempt.wait_until(deadline, self.tx.closed()).await + { + return false; } } + if let Some(SseDelivery::Item(item)) = delivery { + // Some protocol events update only the terminal JSON. + item.deliver(self.attempt, self.req); + } + true } - FlushStatus { - all_wire_frames_sent: true, - continued: true, +} + +fn shutdown_response(attempt: &Attempt, protocol: Protocol) -> Response { + error_http_response( + protocol, + &HttpErrorSpec::new(503, "server_error", "server shutting down"), + attempt, + ) +} + +fn finish_http_error( + req: &NormalizedRequest, + spec: &HttpErrorSpec, + rl_headers: &RateLimitHeaders, + attempt: &Attempt, +) -> Response { + let mut enriched = spec.clone(); + for (key, value) in rl_headers.to_header_pairs() { + enriched.headers.entry(key.into()).or_insert(value); } + attempt.outcome(AttemptOutcome::InjectedFault, Some(spec.status)); + error_http_response(req.protocol, &enriched, attempt) } diff --git a/tools/mock-ai/src/server/ws.rs b/tools/mock-ai/src/server/ws.rs index 30d4ce1c24f..5a425dcebd5 100644 --- a/tools/mock-ai/src/server/ws.rs +++ b/tools/mock-ai/src/server/ws.rs @@ -18,302 +18,525 @@ */ use super::{ - ActiveStreamGuard, FlushStatus, ServerState, TtftTracker, TurnCloseGuard, default_response_id, - format_ws_error_frame, is_semantic_delta_frame, jitter_ms, pacer_seed_for, plan_usage_hint, - semantic_event_bytes, -}; -use crate::codec::{WireFrame, create_encoder}; -use crate::handler::{ - CloseSignalGuard, InteractiveCommand, InteractiveStream, TurnContext, TurnDecision, + ActiveStreamGuard, Attempt, DeliveredItem, FlushStatus, ServerState, TurnCloseGuard, + default_response_id, effective_history, event_usage, format_ws_error_frame, initial_usage, + jitter_ms, }; +use crate::codec::{EncodedFrame, FrameKind, WireFrame}; +use crate::handler::{CloseSignalGuard, InteractiveCommand, TurnDecision}; +use crate::metrics::{AttemptOutcome, RequestPurpose}; use crate::pacing::{LatencyProfile, TurnPacer}; -use crate::plan::{CloseSignal, FinishReason, TurnEvent, TurnPlan, Usage}; +use crate::plan::{CloseSignal, FinishReason, HttpErrorSpec, TurnEvent, TurnPlan, Usage}; use crate::protocol::{NormalizedRequest, Protocol, Transport, normalize_request}; #[cfg(feature = "proxy")] -use crate::proxy::fingerprint_from_normalized; +use crate::proxy::fingerprint_from_route; use crate::ratelimit::{RateLimitDecision, RateLimitLease}; +use crate::routing::{EndpointKind, ParsedRoute, RequestUse, ResponseId, RouteScope}; +use crate::schema_synth::WirePoisonConfig; +use crate::watchdog::HistorySize; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; -use serde_json::{Value, json}; +use serde_json::Value; use std::collections::BTreeMap; +use std::future::Future; use std::sync::Arc; use std::sync::atomic::Ordering; use std::time::{Duration, Instant}; use tokio::sync::mpsc; use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::tungstenite::Message as WsMessage; -use tokio_util::sync::CancellationToken; +#[allow(clippy::too_many_arguments)] pub(super) async fn handle_responses_websocket( mut ws: WebSocketStream, conn_id: u64, path: String, + scope: Option, + canonical_offset: usize, + query: Option, headers: BTreeMap, state: Arc, ) where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, { - // Single latest continuable response ID on this WS connection for `store: false` turns. - // Mirrors Maka's confirmed baseline semantics: continuing from a superseded ID or another - // connection is rejected when `strict_previous_response_id == true`. - let mut current_baseline_id: Option = None; - let mut turn_on_connection = 0usize; - + let mut connection = WsBinding { + state: &state, + id: conn_id, + bound: false, + }; + let route = ParsedRoute { + canonical_path: &path[canonical_offset..], + raw_path: &path, + scope, + query: query.as_deref(), + endpoint: EndpointKind::ResponsesWs, + }; + let mut legacy_baseline = None; + let mut turn_on_connection = 0; + let mut warmups = 0_u64; loop { - let frame = tokio::select! { + let message = tokio::select! { _ = state.shutdown.cancelled() => break, - msg = ws.next() => msg, + message = ws.next() => message, }; - let Some(Ok(msg)) = frame else { + let Some(Ok(message)) = message else { break; }; - match msg { - WsMessage::Ping(payload) => { - if ws.send(WsMessage::Pong(payload)).await.is_err() { + match message { + WsMessage::Ping(bytes) => { + if ws.send(WsMessage::Pong(bytes)).await.is_err() { break; } - continue; } - WsMessage::Pong(_) => continue, - WsMessage::Close(_) => break, + WsMessage::Pong(_) => {} WsMessage::Text(text) => { - turn_on_connection += 1; - let raw_body: Value = match serde_json::from_str(&text) { - Ok(v) => v, - Err(err) => { - let _ = ws - .send(WsMessage::text( - json!({ - "type": "error", - "error": { - "type": "invalid_request_error", - "message": format!("invalid WS JSON frame: {err}"), - } - }) - .to_string(), - )) - .await; + let transport = Transport::WebSocket { + connection_id: conn_id, + turn_on_connection: turn_on_connection + 1, + }; + let attempt = Attempt::new( + &state, + Protocol::OpenaiResponsesWs, + transport, + Instant::now(), + state.clock.elapsed_ns(), + ); + attempt.body_read(text.len()); + let _ = state.resolve_identity( + &attempt, + route.scope.as_ref(), + &headers, + &Value::Null, + None, + false, + ); + let raw_body = match serde_json::from_str::(&text) { + Ok(body) => body, + Err(error) => { + let spec = HttpErrorSpec::new( + 400, + "invalid_request_error", + format!("invalid WS JSON frame: {error}"), + ); + attempt.outcome(AttemptOutcome::ParseFailed, Some(400)); + let _ = send_error(&mut ws, &attempt, &spec).await; + continue; + } + }; + attempt.with_span(|span, now| span.parsed_ns = Some(now)); + if raw_body["type"] != "response.create" { + let spec = HttpErrorSpec::new( + 400, + "invalid_request_error", + "expected a response.create event", + ); + attempt.outcome(AttemptOutcome::Rejected, Some(400)); + if !send_error(&mut ws, &attempt, &spec).await { break; } + continue; + } + let sequence = if raw_body["generate"] == false { + 0 + } else { + state.next_sequence() }; - let raw_wire_bytes = Bytes::from(text); - - let seq = state.next_sequence(); - let normalized = normalize_request( - seq, + let mut req = normalize_request( + sequence, Protocol::OpenaiResponsesWs, - Transport::WebSocket { - connection_id: conn_id, - turn_on_connection, - }, + attempt.0.transport.clone(), path.clone(), headers.clone(), - raw_wire_bytes, + Bytes::from(text), raw_body, ); - let turn_started = Instant::now(); - state - .metrics - .record_protocol(Protocol::OpenaiResponsesWs, normalized.prompt_bytes); - state.recorder.record(&normalized); - state.watchdog.inspect_request(&normalized); - - let effective_profile = state.profile.effective(); - - // Stateful rate-limit admission on WS turns - let rl_lease = match state.rate_limiter.check_and_acquire( - normalized.api_key(), - &normalized.model, - normalized.estimated_input_tokens, - effective_profile.rate_limit_override.as_ref(), + let parent_id = req.previous_response_id.clone().map(ResponseId); + if let Err(spec) = state.resolve_identity( + &attempt, + route.scope.as_ref(), + &req.headers, + &req.raw_body, + parent_id.as_ref(), + !connection.bound, ) { - RateLimitDecision::Allowed { lease, .. } => lease, - RateLimitDecision::Rejected { - retry_after_ms, - reason, - .. - } => { - state - .metrics - .http_errors_emitted - .fetch_add(1, Ordering::Relaxed); - state - .metrics - .rate_limits_emitted - .fetch_add(1, Ordering::Relaxed); - state.metrics.record_dimension( - Protocol::OpenaiResponsesWs, - &normalized.model, - "429", - normalized.estimated_input_tokens, - 0, - 0, - None, - Some(turn_started.elapsed().as_millis() as u64), - ); - let err_frame = json!({ - "type": "error", - "status": 429, - "error": { - "type": "rate_limit_error", - "code": "rate_limit_exceeded", - "message": format!("rate limit exceeded ({reason})"), - "retry_after_ms": retry_after_ms, - } - }); - let _ = ws.send(WsMessage::text(err_frame.to_string())).await; + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { break; } - }; - - if state.tuning.strict_previous_response_id - && let Some(prev_id) = &normalized.previous_response_id - && current_baseline_id.as_deref() != Some(prev_id.as_str()) - && !state.stored_responses.contains(prev_id) - { - state - .watchdog - .record_invalid_previous_response_id(&normalized, prev_id); - state.metrics.record_dimension( - Protocol::OpenaiResponsesWs, - &normalized.model, - "400", - normalized.estimated_input_tokens, - 0, - 0, + continue; + } + if !connection.bound { + connection.bound = attempt.owner().is_some(); + } + let purpose = state.classify(&route, &mut req, &attempt); + if req.options.generate == Some(false) { + attempt.classified(&req, RequestPurpose::Warmup); + let parent = + match state.check_parent(&req, &attempt, legacy_baseline.as_deref()) { + Ok(parent) => parent, + Err(spec) => { + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { + break; + } + continue; + } + }; + attempt.admitted(parent.as_ref()); + warmups += 1; + req.options.store = Some(false); + let plan = TurnPlan::new() + .with_response_id(format!("resp_warmup_{conn_id}_{warmups}")) + .with_usage(Usage::new(0, 0)) + .finish(FinishReason::Stop); + let history = effective_history(&req, parent.as_ref()); + let Some(id) = execute_ws_turn( + &mut ws, + &req, + TurnDecision::Plan(plan), + LatencyProfile::default(), None, - Some(turn_started.elapsed().as_millis() as u64), - ); - let err_frame = json!({ - "type": "error", - "error": { - "type": "invalid_request_error", - "code": "previous_response_not_found", - "message": format!("previous_response_id '{prev_id}' is not valid on this connection"), - } - }); - let _ = ws.send(WsMessage::text(err_frame.to_string())).await; - break; + history, + &attempt, + ) + .await + else { + break; + }; + legacy_baseline = Some(id); + continue; } + turn_on_connection += 1; + attempt.classified(&req, RequestPurpose::from(&purpose)); + let main = purpose == RequestUse::Main; + let profile = state.profile.effective(); + let lease = if main { + attempt.record(|metrics| { + metrics.record_protocol(req.protocol, req.prompt_bytes); + state.recorder.record(&req); + }); + match state.rate_limiter.check_and_acquire( + req.api_key(), + &req.model, + req.estimated_input_tokens, + profile.rate_limit_override.as_ref(), + ) { + RateLimitDecision::Allowed { lease, .. } => lease, + RateLimitDecision::Rejected { + retry_after_ms, + reason, + .. + } => { + let spec = HttpErrorSpec::rate_limit( + Some(retry_after_ms.div_ceil(1000).max(1)), + format!("rate limit exceeded ({reason})"), + ) + .with_retry_after_ms(retry_after_ms); + attempt.outcome(AttemptOutcome::RateLimited, Some(429)); + if !send_error(&mut ws, &attempt, &spec).await { + break; + } + continue; + } + } + } else { + None + }; - // Cassette WS replay mode (when configured and matched) #[cfg(feature = "proxy")] - if let Some(ref replayer) = state.cassette_replayer { - let fp = fingerprint_from_normalized(&normalized); - if let Some(ex) = replayer.next_ws(&fp) { - state.metrics.replay_hits.fetch_add(1, Ordering::Relaxed); - state.metrics.active_streams.fetch_add(1, Ordering::Relaxed); - let _stream_guard = ActiveStreamGuard(state.metrics.clone()); - let _lease = rl_lease; - let mut ok = true; - let mut first_ttft: Option = None; - let mut last_resp_id: Option = None; - for chunk in &ex.chunks { - let delay = replayer.config().scaled_delay(chunk.delay_ms); - if !delay.is_zero() { - tokio::select! { - _ = state.shutdown.cancelled() => { ok = false; break; } - _ = tokio::time::sleep(delay) => {} + if let Some(replayer) = &state.cassette_replayer { + let parent = if replayer.config().strict_replay || attempt.owner().is_some() { + match state.check_parent(&req, &attempt, legacy_baseline.as_deref()) { + Ok(parent) => parent, + Err(spec) => { + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { + break; } + continue; } - let msg = if chunk.is_binary { - WsMessage::Binary(chunk.to_bytes()) - } else { - if let Ok(v) = serde_json::from_str::(&chunk.data) - && let Some(id) = - v.pointer("/response/id").and_then(Value::as_str) + } + } else { + None + }; + let lane = attempt.replay_lane(&req.headers); + let fp = fingerprint_from_route(&req, "GET", &route, lane.as_ref()); + match replayer.try_next_ws_if(&fp, |candidate| { + !state.tuning.strict_previous_response_id + || req.previous_response_id.as_deref() + == candidate.request_body["previous_response_id"].as_str() + }) { + Ok(exchange) => { + attempt.record(|metrics| { + metrics.replay_hits.fetch_add(1, Ordering::Relaxed); + }); + attempt.admitted(parent.as_ref()); + attempt.ready(None); + let mut complete = true; + for chunk in &exchange.chunks { + if !wait_ws( + &mut ws, + &attempt, + replayer.config().scaled_delay(chunk.delay_ms), + ) + .await { - last_resp_id = Some(id.to_string()); + complete = false; + break; } - WsMessage::text(chunk.data.clone()) - }; - let byte_len = chunk.data.len(); - if ws.send(msg).await.is_err() { - ok = false; + let message = if chunk.is_binary { + WsMessage::Binary(chunk.to_bytes()) + } else { + WsMessage::text(chunk.data.clone()) + }; + if !send_ws(&mut ws, &attempt, message).await { + complete = false; + break; + } + attempt.frame(chunk.data.len(), false); + } + if !complete { + break; + } + if exchange.outcome != crate::proxy::ExchangeOutcome::Completed { + attempt + .outcome(AttemptOutcome::InjectedFault, Some(exchange.status)); break; } - if first_ttft.is_none() { - let ttft = turn_started.elapsed().as_millis() as u64; - state.metrics.ttft_ms.record(ttft); - first_ttft = Some(ttft); + if let Some(response) = replayed_response(exchange) + && let Some(id) = response["id"].as_str().map(str::to_owned) + { + attempt.ready(Some(&id)); + if purpose == RequestUse::Main + || matches!(purpose, RequestUse::Compact(_)) + { + legacy_baseline = Some(id.clone()); + } + state.publish_response( + &req, + &attempt, + id, + response, + req.options.store.unwrap_or(false), + effective_history(&req, parent.as_ref()), + ); } - state - .metrics - .bytes_sent - .fetch_add(byte_len as u64, Ordering::Relaxed); + attempt.outcome(AttemptOutcome::Completed, Some(exchange.status)); + continue; } - let dur = turn_started.elapsed().as_millis() as u64; - state.metrics.turn_duration_ms.record(dur); - state.metrics.record_dimension( - Protocol::OpenaiResponsesWs, - &normalized.model, - if ok { "200" } else { "aborted" }, - normalized.estimated_input_tokens, - 0, - 0, - first_ttft, - Some(dur), - ); - if ok { - current_baseline_id = last_resp_id; + Err(error) if replayer.config().strict_replay => { + let mut spec = + HttpErrorSpec::new(422, "invalid_request_error", error.to_string()); + spec.code = Some("cassette_replay_miss".into()); + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { + break; + } continue; - } else { - break; } + Err(_) => {} } } - let session_turn = state.sessions.next_turn(&normalized.session_key); - let ctx = TurnContext { - global_turn: seq, - session_turn, - chaos_override: effective_profile.chaos_override.clone(), + let parent = match state.check_parent(&req, &attempt, legacy_baseline.as_deref()) { + Ok(parent) => parent, + Err(spec) => { + if main { + attempt.record(|_| { + state.watchdog.record_invalid_previous_response_id( + &req, + req.previous_response_id.as_deref().unwrap(), + ) + }); + } + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { + break; + } + continue; + } }; - let store_flag = normalized.raw_body["store"].as_bool().unwrap_or(false); - - let decision = match state.handler.handle(&normalized, &ctx).await { - Some(d) => d, - None => { - let _ = ws - .send(WsMessage::text( - json!({ - "type": "error", - "error": { - "type": "server_error", - "message": "mock handler exhausted", - } - }) - .to_string(), - )) - .await; - break; + attempt.admitted(parent.as_ref()); + let history = effective_history(&req, parent.as_ref()); + let req = Arc::new(req); + let decision = match state + .decide(&req, &purpose, &profile, &attempt, parent.as_ref()) + .await + { + Ok(decision) => decision, + Err(spec) => { + attempt.outcome(AttemptOutcome::Rejected, Some(spec.status)); + if !send_error(&mut ws, &attempt, &spec).await { + break; + } + continue; } }; - + attempt.audit(req.clone(), &purpose, history); state.metrics.active_streams.fetch_add(1, Ordering::Relaxed); - let _stream_guard = ActiveStreamGuard(state.metrics.clone()); - - let (reusable, completed_id) = execute_ws_turn( + let _stream = ActiveStreamGuard(state.metrics.clone()); + let Some(response_id) = execute_ws_turn( &mut ws, - &normalized, + &req, decision, - store_flag, - effective_profile.latency, - rl_lease, - turn_started, - &state, + if main { + profile.latency + } else { + LatencyProfile::default() + }, + lease, + history, + &attempt, ) - .await; - - if reusable { - current_baseline_id = completed_id; - } else { + .await + else { break; + }; + if main || matches!(purpose, RequestUse::Compact(_)) { + legacy_baseline = Some(response_id); } } - WsMessage::Binary(_) | WsMessage::Frame(_) => break, + WsMessage::Binary(_) | WsMessage::Frame(_) | WsMessage::Close(_) => break, + } + } +} + +#[cfg(feature = "proxy")] +fn replayed_response(exchange: &crate::proxy::RecordedExchange) -> Option { + // Recorded messages are opaque bytes until the last provider terminal event. + exchange + .chunks + .iter() + .rev() + .filter(|chunk| !chunk.is_binary) + .find_map(|chunk| { + let mut event: Value = serde_json::from_str(&chunk.data).ok()?; + matches!( + event["type"].as_str(), + Some("response.completed" | "response.incomplete") + ) + .then(|| event["response"].take()) + }) +} + +struct WsBinding<'a> { + state: &'a ServerState, + id: u64, + bound: bool, +} + +impl Drop for WsBinding<'_> { + fn drop(&mut self) { + if !self.bound { + return; } + let mut routing = self.state.benchmark.write().unwrap(); + routing.registry.unbind_connection(self.id); + routing.lineage.close_connection(self.id); + } +} + +async fn send_ws(ws: &mut WebSocketStream, attempt: &Attempt, message: WsMessage) -> bool +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let mut send = std::pin::pin!(ws.send(message)); + let mut waiting = None; + let result = tokio::select! { + _ = attempt.0.state.shutdown.cancelled() => false, + result = std::future::poll_fn(|cx| { + let result = send.as_mut().poll(cx); + if result.is_pending() && waiting.is_none() { + waiting = Some(Instant::now()); + } + result + }) => result.is_ok(), + }; + if let Some(start) = waiting { + attempt.backpressure(start.elapsed()); } + result +} + +async fn send_error(ws: &mut WebSocketStream, attempt: &Attempt, spec: &HttpErrorSpec) -> bool +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + attempt.record(|metrics| { + metrics.http_errors_emitted.fetch_add(1, Ordering::Relaxed); + if spec.status == 429 { + metrics.rate_limits_emitted.fetch_add(1, Ordering::Relaxed); + } + }); + let message = format_ws_error_frame(spec).to_string(); + let len = message.len(); + if send_ws(ws, attempt, WsMessage::text(message)).await { + attempt.frame(len, false); + true + } else { + false + } +} + +async fn busy_message( + ws: &mut WebSocketStream, + message: Option>, + attempt: &Attempt, +) -> bool +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + match message { + Some(Ok(WsMessage::Ping(payload))) => ws.send(WsMessage::Pong(payload)).await.is_ok(), + Some(Ok(WsMessage::Pong(_))) => true, + Some(Ok(message @ (WsMessage::Text(_) | WsMessage::Binary(_)))) => { + let rejection = attempt.rejected_ws_message(message.len()); + let mut error = HttpErrorSpec::new( + 400, + "invalid_request_error", + "a response is already in progress on this connection", + ); + error.code = Some("response_already_in_progress".into()); + send_error(ws, &rejection, &error).await + } + _ => false, + } +} + +async fn wait_ws(ws: &mut WebSocketStream, attempt: &Attempt, delay: Duration) -> bool +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + wait_ws_until(ws, attempt, tokio::time::Instant::now() + delay).await +} + +async fn wait_ws_until( + ws: &mut WebSocketStream, + attempt: &Attempt, + deadline: tokio::time::Instant, +) -> bool +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let now = tokio::time::Instant::now(); + if deadline <= now { + return !attempt.0.state.shutdown.is_cancelled(); + } + let started = Instant::now(); + let mut sleep = std::pin::pin!(tokio::time::sleep_until(deadline)); + let completed = loop { + tokio::select! { + _ = attempt.0.state.shutdown.cancelled() => break false, + _ = &mut sleep => break true, + msg = ws.next() => { + if !busy_message(ws, msg, attempt).await { + break false; + } + } + } + }; + attempt.sleep_recorded(deadline - now, started.elapsed()); + completed } enum WsEventFeed { @@ -348,14 +571,11 @@ impl WsEventFeed { } } - async fn next_event( - &mut self, - ws: &mut WebSocketStream, - shutdown: &CancellationToken, - ) -> WsFeedStep + async fn next_event(&mut self, ws: &mut WebSocketStream, attempt: &Attempt) -> WsFeedStep where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, { + let shutdown = &attempt.0.state.shutdown; match self { Self::Plan { events, .. } => { if shutdown.is_cancelled() { @@ -382,18 +602,7 @@ impl WsEventFeed { } None => return WsFeedStep::Ended, }, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - if ws.send(WsMessage::Pong(p)).await.is_err() { - return WsFeedStep::Aborted; - } - } - Some(Ok(WsMessage::Pong(_))) => {} - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - return WsFeedStep::Aborted; - } - _ => {} - } + msg = ws.next() => if !busy_message(ws, msg, attempt).await { return WsFeedStep::Aborted; } } } } @@ -403,24 +612,17 @@ impl WsEventFeed { async fn wait_stall( &mut self, ws: &mut WebSocketStream, - shutdown: &CancellationToken, + attempt: &Attempt, ) -> WsStallOutcome where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, { + let shutdown = &attempt.0.state.shutdown; match self { Self::Plan { .. } => loop { tokio::select! { _ = shutdown.cancelled() => return WsStallOutcome::Ended, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - let _ = ws.send(WsMessage::Pong(p)).await; - } - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - return WsStallOutcome::Ended; - } - _ => {} - } + msg = ws.next() => if !busy_message(ws, msg, attempt).await { return WsStallOutcome::Ended; } } }, Self::Interactive { pending, rx } => { @@ -439,34 +641,12 @@ impl WsEventFeed { } None => rx_open = false, }, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - if ws.send(WsMessage::Pong(p)).await.is_err() { - return WsStallOutcome::Ended; - } - } - Some(Ok(WsMessage::Pong(_))) => {} - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - return WsStallOutcome::Ended; - } - _ => {} - } + msg = ws.next() => if !busy_message(ws, msg, attempt).await { return WsStallOutcome::Ended; } } } else { tokio::select! { _ = shutdown.cancelled() => return WsStallOutcome::Ended, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - if ws.send(WsMessage::Pong(p)).await.is_err() { - return WsStallOutcome::Ended; - } - } - Some(Ok(WsMessage::Pong(_))) => {} - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - return WsStallOutcome::Ended; - } - _ => {} - } + msg = ws.next() => if !busy_message(ws, msg, attempt).await { return WsStallOutcome::Ended; } } } } @@ -475,543 +655,326 @@ impl WsEventFeed { } } -enum ResolvedWsDecision { - Plan { - plan: Box, - close_guard: TurnCloseGuard, - }, - Interactive { - first: Box, - stream: InteractiveStream, - close_guard: TurnCloseGuard, - }, -} - #[allow(clippy::too_many_arguments)] async fn execute_ws_turn( ws: &mut WebSocketStream, req: &NormalizedRequest, decision: TurnDecision, - store_flag: bool, latency_profile: LatencyProfile, - mut rl_lease: Option, - turn_started: Instant, - state: &Arc, -) -> (bool, Option) + mut lease: Option, + history: HistorySize, + attempt: &Attempt, +) -> Option where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, { - let resolved = match decision { - TurnDecision::Plan(mut plan) => { - let close_guard = TurnCloseGuard::new(CloseSignalGuard(plan.on_close.take())); - ResolvedWsDecision::Plan { - plan: Box::new(plan), - close_guard, - } - } + let state = &attempt.0.state; + let (mut plan, mut feed, _close_guard) = match decision { + TurnDecision::Plan(plan) => resolve_ws_plan(plan, None), TurnDecision::Interactive(mut stream) => { - // Hold stream.closed in an RAII guard BEFORE the first await so abort_all() - // during shutdown or client disconnect always wakes TurnHandle::wait_closed(). - let mut close_guard = + let guard = TurnCloseGuard::new(CloseSignalGuard(Some(CloseSignal(stream.closed.clone())))); let first = loop { tokio::select! { - _ = state.shutdown.cancelled() => return (false, None), - ev = stream.events.recv() => break ev, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - if ws.send(WsMessage::Pong(p)).await.is_err() { - return (false, None); - } - } - Some(Ok(WsMessage::Pong(_))) => {} - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - return (false, None); - } - _ => {} - } + _ = state.shutdown.cancelled() => return None, + event = stream.events.recv() => break event?, + msg = ws.next() => if !busy_message(ws, msg, attempt).await { return None; }, } }; match first { - None => return (false, None), - Some(InteractiveCommand::Plan { plan, on_close }) => { - close_guard.attach(on_close); - ResolvedWsDecision::Plan { plan, close_guard } + InteractiveCommand::Plan { mut plan, on_close } => { + let mut guard = guard; + guard.attach(on_close); + plan.on_close = None; + resolve_ws_plan(*plan, Some(guard)) + } + InteractiveCommand::Event(first) => { + let id = stream.response_id.lock().unwrap().clone(); + ( + TurnPlan { + response_id: id, + ..Default::default() + }, + WsEventFeed::Interactive { + pending: Some(first), + rx: stream.events, + }, + guard, + ) } - Some(InteractiveCommand::Event(first_event)) => ResolvedWsDecision::Interactive { - first: first_event, - stream, - close_guard, - }, } } }; - - let ( - mut feed, - response_id_override, - model_override, - usage_hint, - mut pacer, - ttft_dur, - _close_guard, - ) = match resolved { - ResolvedWsDecision::Plan { plan, close_guard } => { - let plan = *plan; - let inferred_finish = plan.inferred_finish_reason(); - let usage_hint = plan_usage_hint(&plan, req); - let cached_tokens = usage_hint.cache_read_tokens.unwrap_or(0); - let uncached_tokens = usage_hint.input_tokens.saturating_sub(cached_tokens); - let in_flight_sample = state.metrics.active_streams.load(Ordering::Relaxed).max(1); - let mut pacer = TurnPacer::new( - latency_profile, - pacer_seed_for(req), - in_flight_sample, - plan.ttft_ms, - (plan.chunk_delay_ms > 0).then_some(plan.chunk_delay_ms), - ); - let ttft_dur = pacer.compute_ttft(uncached_tokens, cached_tokens); - let feed = WsEventFeed::Plan { - events: plan.events.into_iter(), - inferred_finish, - }; - ( - feed, - plan.response_id, - plan.model_override, - usage_hint, - Some(pacer), - ttft_dur, - close_guard, - ) - } - ResolvedWsDecision::Interactive { - first, - stream, - close_guard, - } => { - let response_id = stream.response_id.lock().unwrap().clone(); - let usage_hint = Usage::new(req.estimated_input_tokens.max(1), 0); - let feed = WsEventFeed::Interactive { - pending: Some(first), - rx: stream.events, - }; - ( - feed, - response_id, - None, - usage_hint, - None, - Duration::ZERO, - close_guard, - ) - } - }; - - let response_id = response_id_override - .unwrap_or_else(|| default_response_id(Protocol::OpenaiResponsesWs, req.sequence)); - let model = model_override.unwrap_or_else(|| req.model.clone()); - let mut final_usage = usage_hint; - - let mut encoder = create_encoder( - Protocol::OpenaiResponsesWs, - response_id, - model.clone(), - true, + let response_id = plan + .response_id + .take() + .unwrap_or_else(|| default_response_id(req.protocol, req.sequence)); + attempt.ready(Some(&response_id)); + let model = plan + .model_override + .take() + .unwrap_or_else(|| req.model.clone()); + let usage_event = initial_usage( + match &feed { + WsEventFeed::Plan { events, .. } => events.as_slice(), + WsEventFeed::Interactive { .. } => &[], + }, + req, ); - let mut frames = Vec::new(); - let mut first_delta_at: Option = None; - let mut recorded_ttft_ms: Option = None; - let mut emitted_semantic_bytes = 0usize; - let mut emitted_tool_ids: Vec = Vec::new(); - let mut emitted_compaction = false; - - if !ttft_dur.is_zero() { - let deadline = tokio::time::Instant::now() + ttft_dur; - loop { - let now = tokio::time::Instant::now(); - if now >= deadline { - break; - } - tokio::select! { - _ = state.shutdown.cancelled() => return (false, None), - _ = tokio::time::sleep(deadline - now) => break, - msg = ws.next() => match msg { - Some(Ok(WsMessage::Ping(p))) => { - if ws.send(WsMessage::Pong(p)).await.is_err() { - return (false, None); - } - } - None | Some(Ok(WsMessage::Close(_))) | Some(Err(_)) => { - state.metrics.abandoned_streams.fetch_add(1, Ordering::Relaxed); - state.watchdog.record_turn_outcome(req, &emitted_tool_ids, emitted_compaction, false); - return (false, None); - } - _ => {} - } - } - } + let mut usage = event_usage(&usage_event).unwrap().clone(); + attempt.usage(usage.clone()); + let mut pacer = matches!(feed, WsEventFeed::Plan { .. }).then(|| { + let active = state.metrics.active_streams.load(Ordering::Relaxed).max(1); + super::turn_pacer(req, &plan, &usage, attempt, latency_profile, active) + }); + let mut encoder = state.encoder(req, response_id, model); + for _ in encoder.encode_event(usage_event) {} + let mut semantic_bytes = 0; + if let Some(pacer) = &pacer + && !wait_ws(ws, attempt, pacer.initial_delay()).await + { + return None; } - - loop { - let ev = match feed.next_event(ws, &state.shutdown).await { - WsFeedStep::Event(ev) => *ev, - WsFeedStep::Ended => break, - WsFeedStep::Aborted => { - state - .metrics - .abandoned_streams - .fetch_add(1, Ordering::Relaxed); - state.watchdog.record_turn_outcome( - req, - &emitted_tool_ids, - emitted_compaction, - false, - ); - return (false, None); - } + let close_reason = loop { + let event = match feed.next_event(ws, attempt).await { + WsFeedStep::Aborted => return None, + WsFeedStep::Ended => break feed.auto_finish_reason()?, + WsFeedStep::Event(event) => *event, }; - let ev_sem_bytes = semantic_event_bytes(&ev); - match ev { + match event { TurnEvent::Delay { ms } => { - tokio::select! { - _ = state.shutdown.cancelled() => return (false, None), - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} + if !wait_ws(ws, attempt, Duration::from_millis(ms)).await { + return None; } } TurnEvent::JitterDelay { min_ms, max_ms } => { - let ms = jitter_ms(min_ms, max_ms); - if ms > 0 { - tokio::select! { - _ = state.shutdown.cancelled() => return (false, None), - _ = tokio::time::sleep(Duration::from_millis(ms)) => {} - } + let ms = pacer.as_mut().map_or_else( + || jitter_ms(min_ms, max_ms), + |pacer| pacer.jitter_ms(min_ms, max_ms), + ); + if !wait_ws(ws, attempt, Duration::from_millis(ms)).await { + return None; } } TurnEvent::Stall => { - state.metrics.stalls_entered.fetch_add(1, Ordering::Relaxed); - match feed.wait_stall(ws, &state.shutdown).await { - WsStallOutcome::Resumed => continue, - WsStallOutcome::Ended => return (false, None), + attempt.record(|metrics| { + metrics.stalls_entered.fetch_add(1, Ordering::Relaxed); + }); + if matches!(feed.wait_stall(ws, attempt).await, WsStallOutcome::Ended) { + if matches!(feed, WsEventFeed::Plan { .. }) && !state.shutdown.is_cancelled() { + attempt.outcome(AttemptOutcome::InjectedFault, None); + } + return None; } } TurnEvent::HttpError(spec) => { - state - .metrics - .http_errors_emitted - .fetch_add(1, Ordering::Relaxed); - if spec.status == 429 { - state - .metrics - .rate_limits_emitted - .fetch_add(1, Ordering::Relaxed); - } - let err_frame = format_ws_error_frame(&spec); - let _ = ws.send(WsMessage::text(err_frame.to_string())).await; - state.metrics.record_dimension( - Protocol::OpenaiResponsesWs, - &model, - &spec.status.to_string(), - final_usage.input_tokens, - 0, - final_usage.cache_read_tokens.unwrap_or(0), - None, - Some(turn_started.elapsed().as_millis() as u64), - ); - return (false, None); + attempt.outcome(AttemptOutcome::InjectedFault, Some(spec.status)); + let _ = send_error(ws, attempt, &spec).await; + return None; } TurnEvent::DropConnection => { - state - .metrics - .connection_drops_emitted - .fetch_add(1, Ordering::Relaxed); - return (false, None); + attempt.record(|metrics| { + metrics + .connection_drops_emitted + .fetch_add(1, Ordering::Relaxed); + }); + attempt.outcome(AttemptOutcome::InjectedFault, None); + return None; } TurnEvent::TruncateEof => { + attempt.outcome(AttemptOutcome::InjectedFault, None); let _ = ws.close(None).await; - return (false, None); - } - TurnEvent::MidStreamError(err) => { - state - .metrics - .mid_stream_errors_emitted - .fetch_add(1, Ordering::Relaxed); - encoder.push_event(TurnEvent::MidStreamError(err), &mut frames); - let _ = flush_ws_frames(ws, &mut frames, None, 0, None, state).await; - return (false, None); + return None; } - TurnEvent::Finish { reason } => { - let completion = encoder.finish(reason, &mut frames); - if store_flag { - state - .stored_responses - .put(completion.response_id.clone(), completion.response_json); - } - if !flush_ws_frames(ws, &mut frames, None, 0, None, state).await { - state - .metrics - .abandoned_streams + TurnEvent::MidStreamError(error) => { + attempt.record(|metrics| { + metrics + .mid_stream_errors_emitted .fetch_add(1, Ordering::Relaxed); - state.watchdog.record_turn_outcome( - req, - &emitted_tool_ids, - emitted_compaction, - false, - ); - return (false, None); - } - record_ws_completion( - req, - &model, - &final_usage, - emitted_semantic_bytes, - &emitted_tool_ids, - emitted_compaction, - first_delta_at, - recorded_ttft_ms, - &mut rl_lease, - turn_started, - state, - ); - return (completion.ws_reusable, Some(completion.response_id)); - } - TurnEvent::NativeCompaction(c) => { - state - .metrics - .native_compactions_emitted - .fetch_add(1, Ordering::Relaxed); - encoder.push_event(TurnEvent::NativeCompaction(c), &mut frames); - let mut ttft = TtftTracker { - turn_started, - first_delta_at: &mut first_delta_at, - recorded_ttft_ms: &mut recorded_ttft_ms, - }; - let status = flush_ws_frames_detailed( + }); + attempt.outcome(AttemptOutcome::InjectedFault, None); + let _ = flush_ws_frames( ws, - &mut frames, + encoder.encode_event(TurnEvent::MidStreamError(error)), pacer.as_mut(), - ev_sem_bytes, - Some(&mut ttft), - state, + &plan.wire_poison, + attempt, + &mut semantic_bytes, ) .await; - if status.all_wire_frames_sent { - emitted_compaction = true; - emitted_semantic_bytes += ev_sem_bytes; + return None; + } + TurnEvent::Finish { reason } => break reason, + event => { + if let Some(value) = event_usage(&event) { + usage = value.clone(); + attempt.usage(usage.clone()); } - if !status.continued { - state - .metrics - .abandoned_streams - .fetch_add(1, Ordering::Relaxed); - state.watchdog.record_turn_outcome( - req, - &emitted_tool_ids, - emitted_compaction, - false, - ); - return (false, None); + let item = DeliveredItem::from_event(&event); + if let Some(item) = &item { + item.issued(attempt); } - } - TurnEvent::Usage(u) => { - final_usage = u.clone(); - encoder.push_event(TurnEvent::Usage(u), &mut frames); - } - other => { - let maybe_tool_id = match &other { - TurnEvent::ToolCall(tc) => Some(tc.id.clone()), - _ => None, - }; - encoder.push_event(other, &mut frames); - let mut ttft = TtftTracker { - turn_started, - first_delta_at: &mut first_delta_at, - recorded_ttft_ms: &mut recorded_ttft_ms, - }; - let status = flush_ws_frames_detailed( + let sent = flush_ws_frames( ws, - &mut frames, + encoder.encode_event(event), pacer.as_mut(), - ev_sem_bytes, - Some(&mut ttft), - state, + &plan.wire_poison, + attempt, + &mut semantic_bytes, ) .await; - if status.all_wire_frames_sent { - if let Some(tid) = maybe_tool_id { - emitted_tool_ids.push(tid); - } - emitted_semantic_bytes += ev_sem_bytes; + if sent.all_wire_frames_sent + && let Some(item) = item + { + item.deliver(attempt, req); } - if !status.continued { - state - .metrics - .abandoned_streams - .fetch_add(1, Ordering::Relaxed); - state.watchdog.record_turn_outcome( - req, - &emitted_tool_ids, - emitted_compaction, - false, - ); - return (false, None); + if !sent.continued { + return None; } } } - } - - if !encoder.is_finished() - && let Some(reason) = feed.auto_finish_reason() + }; + let mut tail = Vec::new(); + let completion = encoder.finish_encoded(close_reason, &mut |frame| tail.push(frame)); + if !flush_ws_frames( + ws, + tail.into_iter(), + None, + &plan.wire_poison, + attempt, + &mut semantic_bytes, + ) + .await + .continued { - let completion = encoder.finish(reason, &mut frames); - if store_flag { - state - .stored_responses - .put(completion.response_id.clone(), completion.response_json); - } - if !flush_ws_frames(ws, &mut frames, None, 0, None, state).await { - state - .metrics - .abandoned_streams - .fetch_add(1, Ordering::Relaxed); - state - .watchdog - .record_turn_outcome(req, &emitted_tool_ids, emitted_compaction, false); - return (false, None); - } - record_ws_completion( - req, - &model, - &final_usage, - emitted_semantic_bytes, - &emitted_tool_ids, - emitted_compaction, - first_delta_at, - recorded_ttft_ms, - &mut rl_lease, - turn_started, - state, - ); - return (completion.ws_reusable, Some(completion.response_id)); + return None; } - - (false, None) -} - -#[allow(clippy::too_many_arguments)] -fn record_ws_completion( - req: &NormalizedRequest, - model: &str, - usage: &Usage, - emitted_semantic_bytes: usize, - emitted_tool_ids: &[String], - emitted_compaction: bool, - first_delta_at: Option, - recorded_ttft_ms: Option, - rl_lease: &mut Option, - turn_started: Instant, - state: &ServerState, -) { - let dur = turn_started.elapsed().as_millis() as u64; - state.metrics.turn_duration_ms.record(dur); - let out_toks = usage.output_tokens.max((emitted_semantic_bytes as u64) / 4); - if let Some(first_at) = first_delta_at - && out_toks > 0 - { - let tps = ((out_toks as f64) / first_at.elapsed().as_secs_f64().max(0.001)) - .round() - .max(1.0) as u64; - state.metrics.effective_tps.record(tps); + usage.output_tokens = usage.output_tokens.max((semantic_bytes as u64) / 4); + if let Some(lease) = &mut lease { + lease.debit_output_tokens(usage.output_tokens); } - if let Some(lease) = rl_lease.as_mut() { - lease.debit_output_tokens(out_toks); + attempt.usage(usage); + attempt.with_span(|span, now| span.body_dropped_ns = Some(now)); + if completion.errored { + attempt.outcome(AttemptOutcome::InjectedFault, None); + return None; } - state.metrics.record_dimension( - Protocol::OpenaiResponsesWs, - model, - "200", - usage.input_tokens, - out_toks, - usage.cache_read_tokens.unwrap_or(0), - recorded_ttft_ms, - Some(dur), + attempt.outcome(AttemptOutcome::Completed, Some(200)); + attempt.deliver_summary(req); + let id = completion.response_id; + state.publish_response( + req, + attempt, + id.clone(), + completion.response_json, + req.options.store.unwrap_or(false), + attempt.response_history(history, semantic_bytes), ); - state - .watchdog - .record_turn_outcome(req, emitted_tool_ids, emitted_compaction, true); + completion.ws_reusable.then_some(id) } -async fn flush_ws_frames( - ws: &mut WebSocketStream, - frames: &mut Vec, - pacer: Option<&mut TurnPacer>, - semantic_bytes: usize, - ttft: Option<&mut TtftTracker<'_>>, - state: &ServerState, -) -> bool -where - S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, -{ - flush_ws_frames_detailed(ws, frames, pacer, semantic_bytes, ttft, state) - .await - .continued +fn resolve_ws_plan( + mut plan: TurnPlan, + guard: Option, +) -> (TurnPlan, WsEventFeed, TurnCloseGuard) { + let guard = + guard.unwrap_or_else(|| TurnCloseGuard::new(CloseSignalGuard(plan.on_close.take()))); + let inferred_finish = plan.inferred_finish_reason(); + let feed = WsEventFeed::Plan { + events: std::mem::take(&mut plan.events).into_iter(), + inferred_finish, + }; + (plan, feed, guard) } -async fn flush_ws_frames_detailed( +async fn flush_ws_frames( ws: &mut WebSocketStream, - frames: &mut Vec, + frames: impl Iterator, mut pacer: Option<&mut TurnPacer>, - semantic_bytes: usize, - mut ttft: Option<&mut TtftTracker<'_>>, - state: &ServerState, + poison: &WirePoisonConfig, + attempt: &Attempt, + total_semantic_bytes: &mut usize, ) -> FlushStatus where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send, { - let total_frames = frames.len(); - let per_frame_sem_bytes = if semantic_bytes > 0 { - (semantic_bytes / total_frames.max(1)).max(1) - } else { - 0 - }; - let mut sent_frames = 0usize; - for frame in frames.drain(..) { - let text = match frame { - WireFrame::WsText(s) => s, - WireFrame::Sse(b) | WireFrame::Raw(b) => String::from_utf8_lossy(&b).into_owned(), + let mut frames = frames.peekable(); + while let Some(EncodedFrame { + wire, + kind, + semantic_bytes, + }) = frames.next() + { + let mut text = match wire { + WireFrame::WsText(text) => text, + WireFrame::Raw(bytes) | WireFrame::Sse(bytes) => { + String::from_utf8_lossy(&bytes).into_owned() + } }; - let is_delta = semantic_bytes > 0 && is_semantic_delta_frame(&text); + if poison.crlf_line_endings { + text.push_str("\r\n"); + } let len = text.len(); - if ws.send(WsMessage::text(text)).await.is_err() { + if poison.inject_sse_comments && !send_ws(ws, attempt, WsMessage::Ping(Bytes::new())).await + { return FlushStatus { all_wire_frames_sent: false, continued: false, }; } - state - .metrics - .bytes_sent - .fetch_add(len as u64, Ordering::Relaxed); - sent_frames += 1; - - if is_delta && let Some(ref mut tracker) = ttft { - tracker.record_once(&state.metrics); + let split = poison + .split_utf8_boundaries + .then(|| { + text.as_bytes() + .iter() + .position(|byte| byte & 0b1100_0000 == 0b1000_0000) + }) + .flatten(); + let sent = if let Some(split) = split { + use tokio_tungstenite::tungstenite::protocol::frame::{ + Frame, + coding::{Data, OpCode}, + }; + let bytes = Bytes::from(text); + send_ws( + ws, + attempt, + WsMessage::Frame(Frame::message( + bytes.slice(..split), + OpCode::Data(Data::Text), + false, + )), + ) + .await + && send_ws( + ws, + attempt, + WsMessage::Frame(Frame::message( + bytes.slice(split..), + OpCode::Data(Data::Continue), + true, + )), + ) + .await + } else { + send_ws(ws, attempt, WsMessage::text(text)).await + }; + if !sent { + return FlushStatus { + all_wire_frames_sent: false, + continued: false, + }; } - - if is_delta - && let Some(ref mut p) = pacer - && per_frame_sem_bytes > 0 + attempt.frame(len, kind == FrameKind::SemanticDelta); + *total_semantic_bytes += semantic_bytes; + if let Some(deadline) = pacer.as_mut().and_then(|pacer| { + pacer.next_frame_deadline(kind, semantic_bytes, tokio::time::Instant::now()) + }) && !wait_ws_until(ws, attempt, deadline).await { - let delay = p.next_chunk_delay(per_frame_sem_bytes); - if !delay.is_zero() { - tokio::select! { - _ = state.shutdown.cancelled() => return FlushStatus { - all_wire_frames_sent: sent_frames == total_frames, - continued: false, - }, - _ = tokio::time::sleep(delay) => {} - } - } + return FlushStatus { + all_wire_frames_sent: frames.peek().is_none(), + continued: false, + }; } } FlushStatus { diff --git a/tools/mock-ai/src/watchdog.rs b/tools/mock-ai/src/watchdog.rs index 0ea30cbc0ec..79eb6f830c5 100644 --- a/tools/mock-ai/src/watchdog.rs +++ b/tools/mock-ai/src/watchdog.rs @@ -17,11 +17,13 @@ * under the License. */ -use crate::protocol::{NormalizedRequest, NormalizedRole, Protocol}; +use crate::protocol::{NormalizedRequest, Protocol}; use serde::{Deserialize, Serialize}; +use serde_json::Value; use std::collections::{HashMap, HashSet, VecDeque}; -use std::sync::Mutex; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::{SystemTime, UNIX_EPOCH}; /// Configuration for the inline protocol-invariant watchdog. @@ -64,7 +66,10 @@ impl Default for WatchdogConfig { pub enum ViolationKind { CompactionNotApplied, CompactionNotReplayed, + /// A previously observed call ID was replayed with different result content. DuplicateToolResult, + CrossSessionToolResult, + ToolResultBeforeDelivery, UnknownToolResult, MissingToolResult, UnboundedPromptGrowth, @@ -97,41 +102,168 @@ pub struct WatchdogSnapshot { pub recent: Vec, } -struct SessionAuditState { - last_sequence: u64, - turns_observed: u64, - /// Tool call IDs emitted by mock-ai in the most recent turn. - pending_tool_calls: HashSet, - /// Bounded FIFO ring of tool call IDs emitted in this session. - known_tool_calls: HashSet, - known_tool_order: VecDeque, - known_tool_evicted: bool, - /// Set when mock-ai just emitted a server-side compaction item/block. - awaiting_compaction_replay: Option, - /// Peak prompt bytes observed before last shrink. - last_prompt_bytes: usize, - consecutive_growth_turns: u32, +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StreamCloseReason { + Completed, + InjectedFault, + ClientDisconnected, + ServerShutdown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HistorySize { + pub bytes: usize, + pub tokens: u64, +} + +impl HistorySize { + /// For full requests only. Continuations need the effective history of their accepted prefix. + pub fn from_request(req: &NormalizedRequest) -> Self { + Self { + bytes: req.size_breakdown.history_bytes, + tokens: req.size_breakdown.estimated_history_tokens, + } + } + + fn shrank_from(self, before: Self) -> bool { + (self.tokens, self.bytes) < (before.tokens, before.bytes) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "stage", rename_all = "snake_case")] +pub enum CompactionAudit { + Requested { + before: HistorySize, + }, + Issued { + before: HistorySize, + checkpoint_id: Option, + }, + Adopted { + before: HistorySize, + checkpoint_id: Option, + after: Option, + }, + Effective { + before: HistorySize, + checkpoint_id: Option, + after: HistorySize, + }, } -struct CompactionExpectation { - pre_compaction_bytes: usize, - pre_compaction_messages: usize, +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionAuditSnapshot { + pub audit_incomplete: bool, + pub compaction: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct ResultDigest(u64); + +#[derive(Clone, Copy)] +enum CallState { + Issued, + DeliveredComplete, + ReceiptObserved(ResultDigest), +} + +#[derive(Default)] +struct SessionAuditState { + calls: HashMap, CallState>, + call_order: VecDeque>, + pending_tool_calls: HashSet>, + audit_incomplete: bool, + compaction: Option, } -const MAX_GLOBAL_TOOL_CALLS: usize = 65_536; +const MAX_SESSION_TOOL_CALLS: usize = 4096; +#[derive(Default)] struct WatchdogInner { sessions: HashMap, order: VecDeque, - /// Bounded FIFO ring of call_ids legitimately emitted by this server across any session/WS conn, - /// so WS reconnects and post-compaction key changes never falsely trigger UnknownToolResult. - global_tool_calls: HashSet, - global_tool_order: VecDeque, + // Used to diagnose foreign receipts. Only the session's own call state can accept one. + call_owners: HashMap, usize>, violations: VecDeque, by_kind: HashMap, } -/// Lightweight inline invariant checker that captures only violating evidence even in `MetricsOnly` mode. +impl WatchdogInner { + fn session(&mut self, key: &str, max_sessions: usize) -> &mut SessionAuditState { + if !self.sessions.contains_key(key) { + if self.sessions.len() >= max_sessions + && let Some(oldest) = self.order.pop_front() + && let Some(old) = self.sessions.remove(&oldest) + { + for call_id in old.call_order { + remove_owner(&mut self.call_owners, &call_id); + } + } + self.order.push_back(key.to_owned()); + self.sessions + .insert(key.to_owned(), SessionAuditState::default()); + } + self.sessions.get_mut(key).expect("audit session exists") + } + + fn register_call( + &mut self, + session_key: &str, + call_id: &str, + update: CallState, + check_missing: bool, + ) { + let state = self + .sessions + .get_mut(session_key) + .expect("audit session exists"); + if let Some(existing) = state.calls.get_mut(call_id) { + if matches!( + (*existing, update), + (CallState::Issued, CallState::DeliveredComplete) + ) { + *existing = update; + } else { + return; + } + } else { + if state.calls.len() == MAX_SESSION_TOOL_CALLS + && let Some(evicted) = state.call_order.pop_front() + { + state.calls.remove(&evicted); + state.pending_tool_calls.remove(&evicted); + remove_owner(&mut self.call_owners, &evicted); + state.audit_incomplete = true; + } + let id: Arc = Arc::from(call_id); + *self.call_owners.entry(id.clone()).or_default() += 1; + state.call_order.push_back(id.clone()); + state.calls.insert(id, update); + } + if check_missing && matches!(update, CallState::DeliveredComplete) { + let (id, _) = state + .calls + .get_key_value(call_id) + .expect("registered call exists"); + state.pending_tool_calls.insert(id.clone()); + } + } +} + +fn remove_owner(owners: &mut HashMap, usize>, call_id: &str) { + let count = owners + .get_mut(call_id) + .expect("registered call has an owner"); + *count -= 1; + if *count == 0 { + owners.remove(call_id); + } +} + +/// Lightweight inline invariant checker that captures only violating evidence even in MetricsOnly mode. pub struct ProtocolWatchdog { config: WatchdogConfig, next_id: AtomicU64, @@ -145,14 +277,7 @@ impl ProtocolWatchdog { config, next_id: AtomicU64::new(1), total_violations: AtomicU64::new(0), - inner: Mutex::new(WatchdogInner { - sessions: HashMap::new(), - order: VecDeque::new(), - global_tool_calls: HashSet::new(), - global_tool_order: VecDeque::new(), - violations: VecDeque::new(), - by_kind: HashMap::new(), - }), + inner: Mutex::new(WatchdogInner::default()), } } @@ -161,216 +286,333 @@ impl ProtocolWatchdog { } pub fn inspect_request(&self, req: &NormalizedRequest) { + self.inspect_request_with_verified_history(req, 0); + } + + /// `verified_items` counts matching items from the already accepted history prefix. + pub fn inspect_request_with_verified_history( + &self, + req: &NormalizedRequest, + verified_items: usize, + ) { if !self.config.enabled { return; } - let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - let max_sessions = self.config.max_tracked_sessions.max(1); - if !inner.sessions.contains_key(&req.session_key) { - if inner.sessions.len() >= max_sessions - && let Some(old) = inner.order.pop_front() - { - inner.sessions.remove(&old); - } - inner.order.push_back(req.session_key.clone()); - inner.sessions.insert( - req.session_key.clone(), - SessionAuditState { - last_sequence: req.sequence, - turns_observed: 0, - pending_tool_calls: HashSet::new(), - known_tool_calls: HashSet::new(), - known_tool_order: VecDeque::new(), - known_tool_evicted: false, - awaiting_compaction_replay: None, - last_prompt_bytes: 0, - consecutive_growth_turns: 0, - }, - ); - } - let mut pending_violations: Vec<(ViolationKind, String)> = Vec::new(); - let has_replayed_compaction = request_contains_compaction_replay(req); - let is_incremental_ws = req.previous_response_id.is_some(); + let receipts = if self.config.check_tool_accounting { + result_receipts(req) + } else { + Vec::new() + }; + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + inner.session(&req.session_key, self.config.max_tracked_sessions.max(1)); let WatchdogInner { sessions, - global_tool_calls, + call_owners, .. } = &mut *inner; + let state = sessions + .get_mut(&req.session_key) + .expect("audit session exists"); + let mut violations = Vec::new(); - if let Some(state) = sessions.get_mut(&req.session_key) { - state.last_sequence = req.sequence; - state.turns_observed = state.turns_observed.saturating_add(1); - - // 1. Check compaction effectiveness on the first non-trigger turn after compaction. - if self.config.check_compaction_effectiveness - && !req.has_compaction_trigger - && let Some(exp) = state.awaiting_compaction_replay.take() + if self.config.check_compaction_effectiveness { + if req.has_compaction_trigger { + if req.previous_response_id.is_none() { + state.compaction = Some(CompactionAudit::Requested { + before: HistorySize::from_request(req), + }); + } + } else if req.previous_response_id.is_none() + && let Some(CompactionAudit::Issued { + before, + checkpoint_id: None, + }) = state.compaction { - if !has_replayed_compaction { - pending_violations.push(( - ViolationKind::CompactionNotReplayed, - format!( - "post-compaction turn did not replay compaction item/block (prev_bytes={}, cur_bytes={})", - exp.pre_compaction_bytes, req.prompt_bytes - ), - )); - } else if !is_incremental_ws - && exp.pre_compaction_messages > 4 - && req.messages.len() >= exp.pre_compaction_messages - && req.prompt_bytes >= exp.pre_compaction_bytes + if req + .messages + .iter() + .any(|message| message.is_compaction_item) { - pending_violations.push(( - ViolationKind::CompactionNotApplied, - format!( - "history did not shrink after compaction (messages {} -> {}, bytes {} -> {})", - exp.pre_compaction_messages, - req.messages.len(), - exp.pre_compaction_bytes, - req.prompt_bytes - ), - )); - } - } - - // 2. Check tool_result accounting. - if self.config.check_tool_accounting && !req.has_compaction_trigger { - let mut seen_in_req: HashSet<&str> = HashSet::new(); - for msg in &req.messages { - if msg.role == NormalizedRole::Tool - && let Some(ref call_id) = msg.tool_call_id + if let Some(detail) = + adopt_compaction(state, None, before, Some(HistorySize::from_request(req))) { - if !seen_in_req.insert(call_id.as_str()) { - pending_violations.push(( - ViolationKind::DuplicateToolResult, - format!( - "duplicate tool_result for call_id '{call_id}' in same request" - ), - )); - } - if !state.known_tool_evicted && !state.known_tool_calls.contains(call_id) { - if state.turns_observed == 1 && global_tool_calls.contains(call_id) { - // Legitimate history replay on a reconnected WS socket or post-compaction session key. - if state.known_tool_calls.insert(call_id.clone()) { - state.known_tool_order.push_back(call_id.clone()); - } - } else { - pending_violations.push(( - ViolationKind::UnknownToolResult, - format!("tool_result references unknown call_id '{call_id}' never emitted in this session"), - )); - } - } - } - } - if self.config.check_missing_tool_results && !state.pending_tool_calls.is_empty() { - let missing: Vec<&String> = state - .pending_tool_calls - .iter() - .filter(|id| !seen_in_req.contains(id.as_str())) - .collect(); - if !missing.is_empty() { - pending_violations.push(( - ViolationKind::MissingToolResult, - format!( - "missing tool_result(s) for previously emitted call_ids: {:?}", - missing - ), - )); + violations.push((ViolationKind::CompactionNotApplied, detail)); } + } else { + violations.push(( + ViolationKind::CompactionNotReplayed, + "full post-compaction request omitted the compaction item".into(), + )); } - state.pending_tool_calls.clear(); } + } - // 3. Check unbounded prompt byte growth. - if req.prompt_bytes > state.last_prompt_bytes { - state.consecutive_growth_turns = state.consecutive_growth_turns.saturating_add(1); - } else { - state.consecutive_growth_turns = 0; + if self.config.check_tool_accounting { + let mut seen = HashSet::new(); + for (index, id, digest) in receipts { + if index < verified_items + && state.audit_incomplete + && !state.calls.contains_key(id) + && !call_owners.contains_key(id) + { + continue; + } + if !seen.insert((id, digest)) { + continue; + } + let (kind, detail) = match state.calls.get_mut(id) { + Some(call @ CallState::DeliveredComplete) => { + *call = CallState::ReceiptObserved(digest); + if self.config.check_missing_tool_results { + state.pending_tool_calls.remove(id); + } + continue; + } + Some(CallState::ReceiptObserved(previous)) if *previous == digest => continue, + Some(CallState::ReceiptObserved(_)) => ( + ViolationKind::DuplicateToolResult, + "changed the result digest for", + ), + Some(CallState::Issued) => ( + ViolationKind::ToolResultBeforeDelivery, + "referenced an issued but incompletely delivered", + ), + None if call_owners.contains_key(id) => ( + ViolationKind::CrossSessionToolResult, + "referenced another session's", + ), + None => ( + ViolationKind::UnknownToolResult, + "referenced an unrecognized", + ), + }; + violations.push((kind, format!("tool_result {detail} call_id '{id}'"))); } - state.last_prompt_bytes = req.prompt_bytes; - - if let Some(limit) = self.config.max_session_prompt_bytes - && req.prompt_bytes > limit + if self.config.check_missing_tool_results + && !req.has_compaction_trigger + && !state.pending_tool_calls.is_empty() { - pending_violations.push(( - ViolationKind::UnboundedPromptGrowth, + let mut missing: Vec<&str> = + state.pending_tool_calls.iter().map(AsRef::as_ref).collect(); + missing.sort_unstable(); + violations.push(( + ViolationKind::MissingToolResult, format!( - "prompt_bytes {} exceeded watchdog limit {} (consecutive_growth_turns={})", - req.prompt_bytes, limit, state.consecutive_growth_turns + "missing tool_result(s) for previously delivered call_ids: {missing:?}" ), )); + state.pending_tool_calls.clear(); } } - for (kind, detail) in pending_violations { - self.push_violation_locked(&mut inner, kind, req, detail); + if let Some(limit) = self.config.max_session_prompt_bytes + && req.prompt_bytes > limit + { + violations.push(( + ViolationKind::UnboundedPromptGrowth, + format!( + "prompt_bytes {} exceeded watchdog limit {limit}", + req.prompt_bytes + ), + )); } + self.push_violations_locked(&mut inner, req, violations); } + pub fn on_call_issued(&self, req: &NormalizedRequest, call_id: &str) { + self.on_call(req, call_id, CallState::Issued); + } + + /// Record a complete call as soon as its last required frame is consumed by the transport. + pub fn on_call_delivered_complete(&self, req: &NormalizedRequest, call_id: &str) { + self.on_call(req, call_id, CallState::DeliveredComplete); + } + + fn on_call(&self, req: &NormalizedRequest, call_id: &str, state: CallState) { + if !self.config.enabled || !self.config.check_tool_accounting { + return; + } + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + inner.session(&req.session_key, self.config.max_tracked_sessions.max(1)); + inner.register_call( + &req.session_key, + call_id, + state, + self.config.check_missing_tool_results, + ); + } + + pub fn on_stream_closed(&self, req: &NormalizedRequest, reason: StreamCloseReason) { + if self.config.enabled && reason == StreamCloseReason::ClientDisconnected { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + self.push_violations_locked( + &mut inner, + req, + [( + ViolationKind::AbandonedStream, + "client disconnected before terminal stream event completed".into(), + )], + ); + } + } + + /// The legacy call site knows which items were delivered. Its boolean conflates all close causes. pub fn record_turn_outcome( &self, req: &NormalizedRequest, emitted_tool_call_ids: &[String], emitted_compaction: bool, - completed_cleanly: bool, + _completed_cleanly: bool, ) { if !self.config.enabled { return; } let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - for id in emitted_tool_call_ids { - if inner.global_tool_calls.insert(id.clone()) { - inner.global_tool_order.push_back(id.clone()); - if inner.global_tool_order.len() > MAX_GLOBAL_TOOL_CALLS - && let Some(evicted) = inner.global_tool_order.pop_front() - { - inner.global_tool_calls.remove(&evicted); - } + let state = inner.session(&req.session_key, self.config.max_tracked_sessions.max(1)); + if self.config.check_compaction_effectiveness && emitted_compaction { + let before = match state.compaction { + Some(CompactionAudit::Requested { before }) => Some(before), + _ if req.previous_response_id.is_none() => Some(HistorySize::from_request(req)), + _ => None, + }; + if let Some(before) = before { + state.compaction = Some(CompactionAudit::Issued { + before, + checkpoint_id: None, + }); } } - if let Some(state) = inner.sessions.get_mut(&req.session_key) { - state.pending_tool_calls.clear(); + if self.config.check_tool_accounting { for id in emitted_tool_call_ids { - state.pending_tool_calls.insert(id.clone()); - if state.known_tool_calls.insert(id.clone()) { - state.known_tool_order.push_back(id.clone()); - if state.known_tool_order.len() > 4096 - && let Some(evicted) = state.known_tool_order.pop_front() - { - state.known_tool_calls.remove(&evicted); - state.known_tool_evicted = true; - } - } + inner.register_call( + &req.session_key, + id, + CallState::DeliveredComplete, + self.config.check_missing_tool_results, + ); } - if emitted_compaction { - state.awaiting_compaction_replay = Some(CompactionExpectation { - pre_compaction_bytes: req.prompt_bytes, - pre_compaction_messages: req.messages.len(), - }); + } + } + + pub fn on_compaction_requested(&self, req: &NormalizedRequest, before: HistorySize) { + if self.config.enabled && self.config.check_compaction_effectiveness { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + inner + .session(&req.session_key, self.config.max_tracked_sessions.max(1)) + .compaction = Some(CompactionAudit::Requested { before }); + } + } + + pub fn on_compaction_issued( + &self, + req: &NormalizedRequest, + checkpoint_id: &str, + before: HistorySize, + ) { + if self.config.enabled && self.config.check_compaction_effectiveness { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let state = inner.session(&req.session_key, self.config.max_tracked_sessions.max(1)); + if matches!(&state.compaction, + Some(CompactionAudit::Issued { checkpoint_id: Some(id), .. } + | CompactionAudit::Adopted { checkpoint_id: Some(id), .. } + | CompactionAudit::Effective { checkpoint_id: Some(id), .. }) if id == checkpoint_id) + { + return; } + state.compaction = Some(CompactionAudit::Issued { + before, + checkpoint_id: Some(checkpoint_id.into()), + }); + } + } + + /// Supply the size of the same effective history prefix excluding system, tools and new input. + /// An incremental request can establish adoption before a comparable history size is available. + pub fn on_compaction_adopted( + &self, + req: &NormalizedRequest, + checkpoint_id: &str, + after: Option, + ) { + if !self.config.enabled || !self.config.check_compaction_effectiveness { + return; } - if !completed_cleanly { - self.push_violation_locked( + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let Some(state) = inner.sessions.get_mut(&req.session_key) else { + return; + }; + let before = match &state.compaction { + Some( + CompactionAudit::Issued { + before, + checkpoint_id: Some(id), + } + | CompactionAudit::Adopted { + before, + checkpoint_id: Some(id), + after: None, + }, + ) if id == checkpoint_id => *before, + _ => return, + }; + if let Some(detail) = adopt_compaction(state, Some(checkpoint_id.into()), before, after) { + self.push_violations_locked( &mut inner, - ViolationKind::AbandonedStream, req, - "client disconnected before terminal stream event completed".into(), + [(ViolationKind::CompactionNotApplied, detail)], ); } } pub fn record_invalid_previous_response_id(&self, req: &NormalizedRequest, prev_id: &str) { - if !self.config.enabled { - return; + if self.config.enabled { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + self.push_violations_locked( + &mut inner, + req, + [( + ViolationKind::InvalidPreviousResponseId, + format!( + "previous_response_id '{prev_id}' not found on this connection or store" + ), + )], + ); } + } + + pub fn session_audit(&self, session_id: &str) -> Option { + let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + inner + .sessions + .get(session_id) + .map(|state| SessionAuditSnapshot { + audit_incomplete: state.audit_incomplete, + compaction: state.compaction.clone(), + }) + } + + pub(crate) fn remove_session(&self, session_id: &str) { let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - self.push_violation_locked( - &mut inner, - ViolationKind::InvalidPreviousResponseId, - req, - format!("previous_response_id '{prev_id}' not found on this connection or store"), - ); + if let Some(session) = inner.sessions.remove(session_id) { + inner.order.retain(|key| key != session_id); + for call_id in session.call_order { + remove_owner(&mut inner.call_owners, &call_id); + } + } + inner + .violations + .retain(|record| record.session_key != session_id); + } + + pub fn violations_for_session(&self, session_id: &str) -> Vec { + let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + inner + .violations + .iter() + .filter(|record| record.session_key == session_id) + .cloned() + .collect() } pub fn snapshot(&self) -> WatchdogSnapshot { @@ -382,86 +624,366 @@ impl ProtocolWatchdog { } } + /// Legacy reset entry point. Use clear_violations for the diagnostics-only operation. pub fn clear(&self) { + self.reset_all(); + } + + pub fn clear_violations(&self) { let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); - inner.sessions.clear(); - inner.order.clear(); - inner.global_tool_calls.clear(); - inner.global_tool_order.clear(); inner.violations.clear(); inner.by_kind.clear(); self.total_violations.store(0, Ordering::Relaxed); } - fn push_violation_locked( + pub fn reset_all(&self) { + let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let previous = std::mem::take(&mut *inner); + self.total_violations.store(0, Ordering::Relaxed); + drop(inner); + drop(previous); + } + + fn push_violations_locked( &self, inner: &mut WatchdogInner, - kind: ViolationKind, req: &NormalizedRequest, - detail: String, + violations: impl IntoIterator, ) { - let id = self.next_id.fetch_add(1, Ordering::Relaxed); - self.total_violations.fetch_add(1, Ordering::Relaxed); - *inner.by_kind.entry(kind).or_insert(0) += 1; + let mut excerpt = None; + for (kind, detail) in violations { + let id = self.next_id.fetch_add(1, Ordering::Relaxed); + self.total_violations.fetch_add(1, Ordering::Relaxed); + *inner.by_kind.entry(kind).or_insert(0) += 1; + if self.config.max_violations == 0 { + continue; + } + let request_excerpt = excerpt.get_or_insert_with(|| wire_excerpt(req)).clone(); + if inner.violations.len() == self.config.max_violations { + inner.violations.pop_front(); + } + let timestamp_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64); + inner.violations.push_back(ViolationRecord { + id, + kind, + protocol: req.protocol, + session_key: req.session_key.clone(), + model: req.model.clone(), + sequence: req.sequence, + timestamp_ms, + prompt_bytes: req.prompt_bytes, + detail, + request_excerpt, + }); + } + } +} - let max_keep = self.config.max_violations; - if max_keep == 0 { - return; +fn adopt_compaction( + state: &mut SessionAuditState, + checkpoint_id: Option, + before: HistorySize, + after: Option, +) -> Option { + if let Some(after) = after.filter(|size| size.shrank_from(before)) { + state.compaction = Some(CompactionAudit::Effective { + before, + checkpoint_id, + after, + }); + return None; + } + state.compaction = Some(CompactionAudit::Adopted { + before, + checkpoint_id, + after, + }); + after.map(|after| { + format!( + "compaction did not shrink comparable history (bytes {} -> {}, tokens {} -> {})", + before.bytes, after.bytes, before.tokens, after.tokens + ) + }) +} + +fn wire_excerpt(req: &NormalizedRequest) -> Option { + const MAX_BYTES: usize = 2048; + let wire = &req.raw_wire_bytes; + if wire.is_empty() { + return None; + } + if wire.len() <= MAX_BYTES { + return Some(String::from_utf8_lossy(wire).into_owned()); + } + // Truncate at a UTF-8 boundary without inspecting the rest of the request. + let end = (0..=MAX_BYTES) + .rev() + .find(|&i| wire[i] & 0b1100_0000 != 0b1000_0000) + .unwrap_or(0); + let mut excerpt = String::from_utf8_lossy(&wire[..end]).into_owned(); + excerpt.push_str("...[truncated]"); + Some(excerpt) +} + +fn result_receipts<'a>(req: &'a NormalizedRequest) -> Vec<(usize, &'a str, ResultDigest)> { + let mut receipts = Vec::new(); + let mut add = |index, id: Option<&'a str>, payload: &Value, is_error: bool| { + if let Some(id) = id { + let mut hasher = DefaultHasher::new(); + (payload, is_error).hash(&mut hasher); + receipts.push((index, id, ResultDigest(hasher.finish()))); } - while inner.violations.len() >= max_keep { - inner.violations.pop_front(); + }; + let body = &req.raw_body; + match req.protocol { + Protocol::OpenaiChatCompletions => { + for (index, message) in body["messages"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + if message["role"] == "tool" { + add( + index, + message["tool_call_id"].as_str(), + &message["content"], + false, + ); + } + } } - let mut excerpt = req.raw_body.to_string(); - if excerpt.len() > 2048 { - let cut = excerpt.floor_char_boundary(2048); - excerpt.truncate(cut); - excerpt.push_str("...[truncated]"); + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { + for (index, item) in body["input"].as_array().into_iter().flatten().enumerate() { + if matches!( + item["type"].as_str(), + Some("function_call_output" | "custom_tool_call_output") + ) { + add(index, item["call_id"].as_str(), &item["output"], false); + } + } + } + Protocol::AnthropicMessages => { + for (index, message) in body["messages"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + for block in message["content"].as_array().into_iter().flatten() { + if block["type"] == "tool_result" { + add( + index, + block["tool_use_id"].as_str(), + &block["content"], + block["is_error"].as_bool().unwrap_or(false), + ); + } + } + } } - let timestamp_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_millis() as u64) - .unwrap_or(0); - inner.violations.push_back(ViolationRecord { - id, - kind, - protocol: req.protocol, - session_key: req.session_key.clone(), - model: req.model.clone(), - sequence: req.sequence, - timestamp_ms, - prompt_bytes: req.prompt_bytes, - detail, - request_excerpt: Some(excerpt), - }); } + receipts } -fn request_contains_compaction_replay(req: &NormalizedRequest) -> bool { - match req.protocol { - Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => req - .raw_body - .get("input") - .and_then(|v| v.as_array()) - .is_some_and(|items| { - items - .iter() - .any(|item| item.get("type").and_then(|v| v.as_str()) == Some("compaction")) +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::{Transport, normalize_request}; + use serde_json::json; + + fn request(session_id: &str, protocol: Protocol, body: Value) -> NormalizedRequest { + let transport = if protocol == Protocol::OpenaiResponsesWs { + Transport::WebSocket { + connection_id: 1, + turn_on_connection: 2, + } + } else { + Transport::Http + }; + normalize_request( + 1, + protocol, + transport, + "/v1/responses".into(), + [("x-session-id".into(), session_id.into())].into(), + body.to_string().into(), + body, + ) + } + + fn tool_request(session_id: &str, results: &[(&str, &str)]) -> NormalizedRequest { + let input: Vec<_> = results.iter().map(|(id, output)| { + json!({"type": "function_call_output", "call_id": id, "output": output}) + }).collect(); + request( + session_id, + Protocol::OpenaiResponsesHttp, + json!({"input": input}), + ) + } + + fn kinds(watchdog: &ProtocolWatchdog, session_id: &str) -> Vec { + watchdog + .violations_for_session(session_id) + .into_iter() + .map(|record| record.kind) + .collect() + } + + #[test] + fn receipts_require_own_delivered_call_and_identical_history_is_replay() { + let watchdog = ProtocolWatchdog::new(WatchdogConfig::default()); + let issued = tool_request("owner", &[]); + watchdog.on_call_issued(&issued, "call"); + watchdog.inspect_request(&tool_request("owner", &[("call", "ok")])); + assert_eq!( + kinds(&watchdog, "owner"), + [ViolationKind::ToolResultBeforeDelivery] + ); + + watchdog.on_call_delivered_complete(&issued, "call"); + watchdog.inspect_request(&tool_request("intruder", &[("call", "ok")])); + watchdog.inspect_request(&tool_request("intruder", &[("call", "ok")])); + assert_eq!( + kinds(&watchdog, "intruder"), + [ViolationKind::CrossSessionToolResult; 2] + ); + + watchdog.clear_violations(); + watchdog.inspect_request(&tool_request("owner", &[("call", "ok"), ("call", "ok")])); + watchdog.inspect_request(&tool_request("owner", &[("call", "ok")])); + assert_eq!(watchdog.total_violations(), 0); + + watchdog.inspect_request(&tool_request( + "owner", + &[("call", "edited"), ("unknown", "ok")], + )); + assert_eq!( + kinds(&watchdog, "owner"), + [ + ViolationKind::DuplicateToolResult, + ViolationKind::UnknownToolResult, + ] + ); + watchdog.reset_all(); + assert!(watchdog.session_audit("owner").is_none()); + watchdog.inspect_request(&tool_request("owner", &[("call", "ok")])); + assert_eq!( + kinds(&watchdog, "owner"), + [ViolationKind::UnknownToolResult] + ); + } + + #[test] + fn close_diagnostics_distinguish_injected_faults_from_client_disconnects() { + let watchdog = ProtocolWatchdog::new(WatchdogConfig::default()); + let req = tool_request("session", &[]); + watchdog.on_call_issued(&req, "partial"); + watchdog.on_stream_closed(&req, StreamCloseReason::InjectedFault); + watchdog.on_stream_closed(&req, StreamCloseReason::ServerShutdown); + watchdog.on_stream_closed(&req, StreamCloseReason::Completed); + assert_eq!(watchdog.total_violations(), 0); + watchdog.on_stream_closed(&req, StreamCloseReason::ClientDisconnected); + assert_eq!( + kinds(&watchdog, "session"), + [ViolationKind::AbandonedStream] + ); + } + + #[test] + fn overflowing_audit_still_checks_new_calls_and_unknown_receipts() { + let watchdog = ProtocolWatchdog::new(WatchdogConfig::default()); + let req = tool_request("session", &[]); + watchdog.on_call_delivered_complete(&req, "call-0"); + watchdog.inspect_request(&tool_request("session", &[("call-0", "original")])); + for index in 1..=MAX_SESSION_TOOL_CALLS { + watchdog.on_call_delivered_complete(&req, &format!("call-{index}")); + } + assert!(watchdog.session_audit("session").unwrap().audit_incomplete); + let latest_call = format!("call-{MAX_SESSION_TOOL_CALLS}"); + watchdog.inspect_request_with_verified_history( + &tool_request("session", &[("call-0", "original"), (&latest_call, "ok")]), + 1, + ); + assert_eq!(watchdog.total_violations(), 0); + watchdog.inspect_request(&tool_request( + "session", + &[(&latest_call, "edited"), ("never-issued", "ok")], + )); + assert_eq!( + kinds(&watchdog, "session"), + [ + ViolationKind::DuplicateToolResult, + ViolationKind::UnknownToolResult, + ] + ); + } + + #[test] + fn compaction_requires_comparable_history_after_adoption() { + let watchdog = ProtocolWatchdog::new(WatchdogConfig::default()); + let before_req = request( + "session", + Protocol::OpenaiResponsesHttp, + json!({ + "instructions": "fixed".repeat(500), + "tools": [{"type": "function", "name": "example", "description": "fixed".repeat(200)}], + "input": [{"role": "user", "content": "history".repeat(30)}] }), - Protocol::AnthropicMessages => req - .raw_body - .get("messages") - .and_then(|v| v.as_array()) - .is_some_and(|msgs| { - msgs.iter().any(|m| { - m.get("content") - .and_then(|c| c.as_array()) - .is_some_and(|blocks| { - blocks.iter().any(|b| { - b.get("type").and_then(|v| v.as_str()) == Some("compaction") - }) - }) - }) + ); + let before = HistorySize::from_request(&before_req); + assert!(before.bytes < before_req.prompt_bytes / 2); + watchdog.on_compaction_requested(&before_req, before); + assert!(matches!( + watchdog.session_audit("session").unwrap().compaction, + Some(CompactionAudit::Requested { .. }) + )); + watchdog.on_compaction_issued(&before_req, "checkpoint", before); + + let delta = request( + "session", + Protocol::OpenaiResponsesWs, + json!({ + "previous_response_id": "parent", "input": "next" }), - Protocol::OpenaiChatCompletions => false, + ); + watchdog.inspect_request(&delta); + assert!(matches!( + watchdog.session_audit("session").unwrap().compaction, + Some(CompactionAudit::Issued { .. }) + )); + watchdog.on_compaction_adopted( + &delta, + "older-candidate", + Some(HistorySize { + bytes: 10, + tokens: 2, + }), + ); + watchdog.on_compaction_adopted(&delta, "checkpoint", None); + assert!(matches!( + watchdog.session_audit("session").unwrap().compaction, + Some(CompactionAudit::Adopted { after: None, .. }) + )); + + let after = HistorySize { + bytes: 80, + tokens: 16, + }; + watchdog.on_compaction_adopted(&delta, "checkpoint", Some(after)); + assert!( + matches!(watchdog.session_audit("session").unwrap().compaction, Some(CompactionAudit::Effective { after: got, .. }) if got == after) + ); + assert_eq!(watchdog.total_violations(), 0); + + watchdog.on_compaction_issued(&before_req, "ineffective-checkpoint", before); + watchdog.on_compaction_adopted(&delta, "ineffective-checkpoint", Some(before)); + assert_eq!( + kinds(&watchdog, "session"), + [ViolationKind::CompactionNotApplied] + ); } } diff --git a/tools/mock-ai/src/workload.rs b/tools/mock-ai/src/workload.rs index 4d23e43a980..70f6b6a3468 100644 --- a/tools/mock-ai/src/workload.rs +++ b/tools/mock-ai/src/workload.rs @@ -20,8 +20,9 @@ use crate::handler::{HandlerFuture, TurnContext, TurnDecision, TurnHandler}; use crate::plan::{ Citation, CompactionOutput, FinishReason, HttpErrorSpec, MidStreamErrorSpec, NativeToolEvent, - ToolCallSpec, TurnEvent, TurnPlan, Usage, WebSearchResult, + ToolCallPayload, ToolCallSpec, TurnEvent, TurnPlan, Usage, WebSearchResult, }; +use crate::protocol::ToolDeclKind; use crate::protocol::{NormalizedRequest, NormalizedTool}; use crate::schema_synth::{ SynthMode, WirePoisonConfig, context_overflow_error, synthesize_tool_arguments, @@ -142,9 +143,17 @@ pub struct ChaosConfig { #[serde(rename_all = "camelCase")] pub struct SyntheticToolTemplate { pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub namespace: Option, pub arguments: Value, } +impl SyntheticToolTemplate { + fn matches(&self, tool: &NormalizedTool) -> bool { + self.name == tool.name && self.namespace == tool.namespace + } +} + fn default_seed() -> u64 { 42 } @@ -334,37 +343,49 @@ impl WorkloadGenerator { } } - fn build_plan(&self, req: &NormalizedRequest, ctx: &TurnContext) -> TurnPlan { - let mut rng = self.turn_rng(req, ctx); - let chaos = ctx.chaos_override.as_ref().unwrap_or(&self.config.chaos); - - // 0) Context overflow ceiling (exercises Maka's emergency compaction & retry path) + fn admission_error( + &self, + req: &NormalizedRequest, + chaos: &ChaosConfig, + ) -> Option { if let Some(limit_bytes) = self.config.context_overflow_bytes && !req.has_compaction_trigger && req.prompt_bytes > limit_bytes { - return TurnPlan::http_error(context_overflow_error( + return Some(context_overflow_error( req.protocol, req.prompt_bytes, limit_bytes, )); } - - // 1) Pre-stream chaos faults - let roll = rng.f64(); + if chaos.rate_limit_rate + chaos.server_error_rate <= 0.0 { + return None; + } + // Transport attempts sample admission independently of the logical workload turn. + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + self.config.seed.hash(&mut hasher); + req.session_key.hash(&mut hasher); + req.sequence.hash(&mut hasher); + let roll = fastrand::Rng::with_seed(hasher.finish()).f64(); if roll < chaos.rate_limit_rate { - return TurnPlan::http_error( + Some( HttpErrorSpec::rate_limit(None, "synthetic rate limit") .with_retry_after_ms(chaos.rate_limit_retry_after_ms), - ); - } - if roll < chaos.rate_limit_rate + chaos.server_error_rate { - return TurnPlan::http_error(HttpErrorSpec::new( + ) + } else if roll < chaos.rate_limit_rate + chaos.server_error_rate { + Some(HttpErrorSpec::new( 503, "overloaded_error", "synthetic upstream overload", - )); + )) + } else { + None } + } + + fn build_plan(&self, req: &NormalizedRequest, ctx: &TurnContext) -> TurnPlan { + let mut rng = self.turn_rng(req, ctx); + let chaos = ctx.chaos_override.as_ref().unwrap_or(&self.config.chaos); let mut plan = TurnPlan::new() .with_chunk_delay_ms(self.config.chunk_delay_ms) @@ -465,11 +486,18 @@ impl WorkloadGenerator { } // 7) Multi-step tool chain (with JSON Schema synthesis & bad-tool chaos) - let want_tools = ctx.session_turn <= self.config.tool_turns_per_session; - let candidates = self.select_tool_candidates(req, chaos, &mut rng); - if want_tools && !candidates.is_empty() { - let lo = self.config.min_parallel_tools.max(1); - let hi = self.config.max_parallel_tools.max(lo); + let candidates = if ctx.session_turn <= self.config.tool_turns_per_session { + self.select_tool_candidates(req, chaos, &mut rng) + } else { + Vec::new() + }; + if !candidates.is_empty() { + let (lo, hi) = if req.options.parallel_tool_calls == Some(false) { + (1, 1) + } else { + let lo = self.config.min_parallel_tools.max(1); + (lo, self.config.max_parallel_tools.max(lo)) + }; let count = if hi > lo { rng.usize(lo..=hi) } else { lo }; let mut total_arg_chars = 0; for idx in 0..count { @@ -482,9 +510,24 @@ impl WorkloadGenerator { } else { tpl.name.clone() }; - let mut spec = ToolCallSpec::new(call_id, tool_name, tpl.arguments.clone()) - .with_chunk_chars(self.config.chunk_chars); + let spec = if req.tools.iter().any(|tool| { + tpl.matches(tool) && matches!(tool.tool_kind, ToolDeclKind::Freeform { .. }) + }) { + let input = tpl + .arguments + .as_str() + .map_or_else(|| tpl.arguments.to_string(), str::to_owned); + ToolCallSpec::with_payload( + call_id, + tool_name, + ToolCallPayload::FreeformInput(input), + ) + } else { + ToolCallSpec::new(call_id, tool_name, tpl.arguments.clone()) + }; + let mut spec = spec.with_chunk_chars(self.config.chunk_chars); spec.item_id = Some(item_id); + spec.namespace.clone_from(&tpl.namespace); total_arg_chars += spec.arguments_string().len(); plan = plan.push(TurnEvent::ToolCall(spec)); } @@ -549,7 +592,7 @@ impl WorkloadGenerator { .config .tool_templates .iter() - .filter(|t| req.has_tool(&t.name)) + .filter(|t| req.tools.iter().any(|tool| t.matches(tool))) .cloned() .collect(); } @@ -599,6 +642,7 @@ impl WorkloadGenerator { Some(SyntheticToolTemplate { name: tool.name.clone(), + namespace: tool.namespace.clone(), arguments: args, }) } @@ -625,6 +669,25 @@ fn fallback_tool_args(tool: &NormalizedTool, rng: &mut fastrand::Rng, mode: Synt impl TurnHandler for WorkloadGenerator { fn handle<'a>(&'a self, req: &'a NormalizedRequest, ctx: &'a TurnContext) -> HandlerFuture<'a> { + if let Some(spec) = self.reject_before_turn(req, ctx.chaos_override.as_ref()) { + return Box::pin(async move { Some(TurnDecision::Plan(TurnPlan::http_error(spec))) }); + } + self.handle_admitted(req, ctx) + } + + fn reject_before_turn( + &self, + req: &NormalizedRequest, + chaos: Option<&ChaosConfig>, + ) -> Option { + self.admission_error(req, chaos.unwrap_or(&self.config.chaos)) + } + + fn handle_admitted<'a>( + &'a self, + req: &'a NormalizedRequest, + ctx: &'a TurnContext, + ) -> HandlerFuture<'a> { let plan = self.build_plan(req, ctx); Box::pin(async move { Some(TurnDecision::Plan(plan)) }) } @@ -648,3 +711,103 @@ fn synth_text(rng: &mut fastrand::Rng, target_chars: usize, prefix: &str) -> Str } out } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{MockAiBuilder, RuntimeProfile}; + + #[tokio::test] + async fn requests_can_disable_parallel_tool_calls_under_stress() { + let server = MockAiBuilder::new() + .workload(WorkloadConfig { + min_parallel_tools: 3, + ..WorkloadConfig::stress_preset(42) + }) + .start() + .await + .unwrap(); + let client = reqwest::Client::new(); + let anthropic = json!({ + "model": "test", + "max_tokens": 128, + "messages": [{"role": "user", "content": "run fixture"}], + "tools": [{"name": "fixture", "input_schema": {"type": "object"}}], + "tool_choice": {"type": "auto", "disable_parallel_tool_use": true} + }); + let openai = json!({ + "model": "test", + "messages": [{"role": "user", "content": "run fixture"}], + "tools": [{"type": "function", "function": { + "name": "fixture", "parameters": {"type": "object"} + }}], + "parallel_tool_calls": false + }); + for (route, request, calls_pointer) in [ + ("messages", anthropic, "/content"), + ("chat/completions", openai, "/choices/0/message/tool_calls"), + ] { + let response = client + .post(format!("{}/{route}", server.base_url())) + .body(request.to_string()) + .send() + .await + .unwrap() + .error_for_status() + .unwrap(); + let response: Value = serde_json::from_slice(&response.bytes().await.unwrap()).unwrap(); + let calls = response + .pointer(calls_pointer) + .and_then(Value::as_array) + .unwrap() + .iter() + .filter(|part| matches!(part["type"].as_str(), Some("tool_use" | "function"))) + .count(); + assert_eq!(calls, 1, "{route}: {response}"); + } + server.shutdown().await; + } + + #[tokio::test] + async fn rejected_workload_attempt_keeps_the_first_freeform_tool_turn() { + let server = MockAiBuilder::new() + .workload(WorkloadConfig { + tool_turns_per_session: 1, + ..WorkloadConfig::default() + }) + .start() + .await + .unwrap(); + server.set_runtime_profile(Some(RuntimeProfile { + chaos_override: Some(ChaosConfig { + rate_limit_rate: 1.0, + ..ChaosConfig::default() + }), + ..RuntimeProfile::default() + })); + let client = reqwest::Client::new(); + let model = format!("{}/responses", server.base_url()); + let request = json!({ + "input": "run fixture", + "tools": [{ + "type": "namespace", "name": "bench", "tools": [{"type": "custom", "name": "fixture"}], + }], + }); + let send = || client.post(&model).body(request.to_string()).send(); + assert_eq!( + send().await.unwrap().status(), + reqwest::StatusCode::TOO_MANY_REQUESTS + ); + + server.set_runtime_profile(None); + let response: Value = + serde_json::from_slice(&send().await.unwrap().bytes().await.unwrap()).unwrap(); + let call = &response["output"][0]; + assert_eq!(call["type"], "custom_tool_call"); + assert_eq!(call["name"], "fixture"); + assert_eq!(call["namespace"], "bench"); + assert_eq!(call["call_id"], "call_t1_0"); + assert!(call["input"].is_string()); + server.shutdown().await; + } +} diff --git a/tools/mock-ai/tests/advanced_simulation.rs b/tools/mock-ai/tests/advanced_simulation.rs index e8c37a47383..7edf81b8f6d 100644 --- a/tools/mock-ai/tests/advanced_simulation.rs +++ b/tools/mock-ai/tests/advanced_simulation.rs @@ -35,13 +35,14 @@ use std::time::{Duration, Instant}; use tokio_tungstenite::tungstenite::Message as WsMessage; async fn post_json(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::Response { + json_request(client, url, body).send().await.unwrap() +} + +fn json_request(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::RequestBuilder { client .post(url) .header("content-type", "application/json") .body(body.to_string()) - .send() - .await - .unwrap() } async fn post_json_headers( @@ -76,6 +77,449 @@ async fn parse_json(resp: reqwest::Response) -> Value { serde_json::from_str(&txt).unwrap_or_else(|e| panic!("invalid JSON ({e}): {txt}")) } +async fn benchmark_json(request: reqwest::RequestBuilder, status: u16) -> Value { + let response = request.send().await.unwrap(); + let actual = response.status(); + let body = parse_json(response).await; + assert_eq!(actual, status, "{body}"); + body +} + +async fn register_benchmark(client: &reqwest::Client, origin: &str, scenario: &str) { + benchmark_json( + json_request( + client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId":"bench", "sessionId":"lane", "harness":"codex", "logicalLane":"lane", + "scenario":scenario, "workspace":std::env::current_dir().unwrap(), + }), + ), + 201, + ) + .await; +} + +#[tokio::test] +async fn http_and_ws_decode_duration_is_independent_of_delta_count() { + let payload = "a".repeat(800); + let reply = payload.clone(); + let server = MockAiBuilder::new() + .latency_profile(LatencyProfile { + tokens_per_sec: 1_000.0, + ..Default::default() + }) + .handler_fn(move |request, _| { + let chunk_chars = if request.last_user_text() == Some("fragmented") { + 4 + } else { + 800 + }; + TurnPlan::new().push_text_chunked(reply.clone(), chunk_chars) + }) + .start() + .await + .unwrap(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(3)) + .build() + .unwrap(); + let url = format!("{}/responses", server.base_url()); + let (mut ws, _) = tokio_tungstenite::connect_async(server.responses_ws_url()) + .await + .unwrap(); + + let mut sse_durations = Vec::new(); + let mut ws_durations = Vec::new(); + for (input, count) in [("single", 1), ("fragmented", 200)] { + let start = Instant::now(); + let response = post_json( + &client, + &url, + &json!({ + "model":"gpt-5", "input":input, "stream":true + }), + ) + .await; + assert_eq!(response.status(), 200); + let stream = response.text().await.unwrap(); + sse_durations.push(start.elapsed()); + let chunks: Vec<_> = stream + .lines() + .filter_map(|line| line.strip_prefix("data: ")) + .map(|data| serde_json::from_str::(data).unwrap()) + .collect(); + assert_eq!( + chunks + .iter() + .filter(|event| event["type"] == "response.output_text.delta") + .count(), + count + ); + let completed = chunks.last().unwrap(); + assert_eq!(completed["type"], "response.completed"); + assert_eq!( + completed["response"]["output"][0]["content"][0]["text"], + payload + ); + + let start = Instant::now(); + ws.send(WsMessage::text( + json!({ + "type":"response.create", "model":"gpt-5", "input":input + }) + .to_string(), + )) + .await + .unwrap(); + let (completion, deltas) = tokio::time::timeout(Duration::from_secs(3), async { + let mut deltas = 0; + loop { + let event: Value = + serde_json::from_str(ws.next().await.unwrap().unwrap().to_text().unwrap()) + .unwrap(); + match event["type"].as_str() { + Some("response.output_text.delta") => deltas += 1, + Some("response.completed") => break (event, deltas), + _ => {} + } + } + }) + .await + .unwrap(); + ws_durations.push(start.elapsed()); + assert_eq!(deltas, count); + assert_eq!( + completion["response"]["output"][0]["content"][0]["text"], + payload + ); + } + for (transport, durations) in [("SSE", sse_durations), ("WS", ws_durations)] { + assert!( + durations + .iter() + .all(|elapsed| *elapsed >= Duration::from_millis(190)), + "{transport} fell short of the 200ms decode budget: {durations:?}" + ); + assert!( + durations[0].abs_diff(durations[1]) < Duration::from_millis(100), + "{transport} accumulated per-frame drift: {durations:?}" + ); + } + server.shutdown().await; +} + +#[tokio::test] +async fn responses_retry_keeps_call_identity_across_transports_until_all_receipts_arrive() { + use maka_mock_ai::scenario::{ + BenchmarkTrack, CanonicalAction, FaultBoundary, FaultKind, FixtureDef, ScenarioSpec, + ScheduledFault, + }; + + let read = |path: &str, marker: &str| CanonicalAction::ReadFile { + path: path.into(), + expect_marker: marker.into(), + }; + let mut spec = ScenarioSpec::new("retry", 42, "sources", BenchmarkTrack::Native) + .with_fixture( + "first", + FixtureDef::File { + path: "src/first.txt".into(), + content: "first marker".into(), + }, + ) + .with_fixture( + "second", + FixtureDef::File { + path: "src/second.txt".into(), + content: "second marker".into(), + }, + ) + .with_step( + "read-batch", + CanonicalAction::ParallelBatch(vec![ + read("src/first.txt", "first marker"), + read("src/second.txt", "second marker"), + ]), + ) + .with_step( + "finish", + CanonicalAction::FinalAnswer { + text: "Both files read.".into(), + expect_markers: vec!["Both files read.".into()], + }, + ); + for (attempt, at, emit) in [ + (1, FaultBoundary::BeforeHeaders, FaultKind::Http429), + (2, FaultBoundary::BeforeHeaders, FaultKind::Http503), + (3, FaultBoundary::AfterFirstCompleteCall, FaultKind::Eof), + ] { + spec = spec.with_fault(ScheduledFault { + step: "read-batch".into(), + attempt, + at, + emit, + }); + } + let server = MockAiBuilder::new().scenario(spec).start().await.unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(); + register_benchmark(&client, &origin, "retry").await; + let path = "/s/bench/lane/v1/responses"; + let url = format!("{origin}{path}"); + let ws_url = format!("ws://{}{path}", server.addr()); + let mut turn = json!({ + "model":"gpt-4.1", "stream":true, "store":true, "input":"Read both sources.", + "tools":[{"type":"function","name":"Read","parameters":{ + "type":"object","properties":{"path":{"type":"string"}},"required":["path"], + "additionalProperties":false, + }}], + }); + let rejected = benchmark_json(json_request(&client, &url, &turn), 429).await; + assert_eq!(rejected["error"]["type"], "rate_limit_error"); + + let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.unwrap(); + let mut create = turn.clone(); + create["type"] = json!("response.create"); + ws.send(WsMessage::text(create.to_string())).await.unwrap(); + let frame = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let overloaded: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + assert_eq!(overloaded["type"], "error"); + assert_eq!(overloaded["status"], 503); + drop(ws); + + let truncated = post_json(&client, &url, &turn) + .await + .error_for_status() + .unwrap() + .bytes() + .await + .unwrap(); + let mut sse = responses::sse::Sse::default(); + let mut decoder = + responses::decode::Decoder::new(responses::ReasoningMode::PlaintextSummary, None); + let mut partial = Vec::new(); + for &byte in &truncated { + if let Some(event) = sse.push(byte).unwrap() { + if event["type"] == "response.output_item.done" { + partial.push(event["item"].clone()); + } + decoder.push(event).unwrap(); + } + } + assert!(decoder.end().is_err(), "EOF incorrectly completed the turn"); + let [first] = partial.as_slice() else { + panic!("expected the first complete call, got {partial:?}") + }; + + let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await.unwrap(); + ws.send(WsMessage::text(create.to_string())).await.unwrap(); + let completed = tokio::time::timeout(Duration::from_secs(5), async { + let mut done = Vec::new(); + loop { + let frame = ws.next().await.unwrap().unwrap(); + let event: Value = serde_json::from_str(frame.to_text().unwrap()).unwrap(); + match event["type"].as_str().unwrap() { + "response.output_item.done" => done.push(event["item"].clone()), + "response.completed" => { + assert_eq!(event["response"]["output"], json!(done)); + break event["response"].clone(); + } + "error" | "response.failed" => panic!("WS retry failed: {event}"), + _ => {} + } + } + }) + .await + .unwrap(); + let [a, b] = completed["output"].as_array().unwrap().as_slice() else { + panic!("expected both calls on retry: {completed}") + }; + assert_eq!(first, a); + assert_ne!(a["call_id"], b["call_id"]); + for (call, path) in [(a, "src/first.txt"), (b, "src/second.txt")] { + assert_eq!(call["name"], "Read"); + assert_eq!( + serde_json::from_str::(call["arguments"].as_str().unwrap()).unwrap(), + json!({"path":path}) + ); + } + ws.close(None).await.unwrap(); + + turn["stream"] = json!(false); + let replay = benchmark_json(json_request(&client, &url, &turn), 200).await; + assert_eq!(replay["id"], completed["id"]); + assert_eq!(replay["output"], completed["output"]); + turn["previous_response_id"] = completed["id"].clone(); + turn["input"] = + json!([{"type":"function_call_output", "call_id":b["call_id"], "output":"second marker"}]); + let pending = benchmark_json(json_request(&client, &url, &turn), 200).await; + assert_eq!( + pending["output"], + json!([a]), + "acknowledging B must leave A outstanding" + ); + + turn["input"] = + json!([{"type":"function_call_output", "call_id":a["call_id"], "output":"first marker"}]); + let final_answer = benchmark_json(json_request(&client, &url, &turn), 200).await; + assert_eq!( + final_answer["output"][0]["content"][0]["text"], + "Both files read." + ); + let timeline = benchmark_json(client.get(format!("{origin}/admin/sessions/lane")), 200).await; + let main: Vec<_> = timeline["items"] + .as_array() + .unwrap() + .iter() + .filter(|item| item["purpose"] == "main") + .collect(); + assert_eq!(main.len(), 7); + for item in &main[..6] { + assert_eq!(item["stepId"], "read-batch"); + assert_eq!(item["revision"], main[0]["revision"]); + } + assert_eq!(main[6]["stepId"], "finish"); + assert_eq!(main[5]["confirmedCallIds"], json!([b["call_id"]])); + assert_eq!(main[6]["confirmedCallIds"], json!([a["call_id"]])); + server.shutdown().await; +} + +#[tokio::test] +async fn admin_attributes_overlapping_attempts_and_requires_final_export_before_reclaim() { + let mut server = MockAiBuilder::new() + .strict_benchmark(true) + .rate_limit(RateLimitConfig { + enabled: true, + max_concurrent: Some(1), + ..Default::default() + }) + .interactive(1) + .start() + .await + .unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(); + register_benchmark(&client, &origin, "overlap").await; + let url = format!("{origin}/s/bench/lane/v1/responses"); + let detail = format!("{origin}/admin/sessions/lane"); + let finalize = format!("{detail}/finalize"); + let reset = format!("{origin}/admin/reset"); + let main = tokio::spawn(benchmark_json( + json_request( + &client, + &url, + &json!({"model":"mock-model","input":"main request"}), + ), + 200, + )); + let turn = tokio::time::timeout(Duration::from_secs(5), server.next_turn()) + .await + .unwrap() + .unwrap(); + let title = benchmark_json( + json_request( + &client, + &url, + &json!({"model":"mock-model","input":"title request"}), + ) + .header("x-maka-bench-request-use", "title"), + 200, + ) + .await; + assert_eq!(title["output"][0]["content"][0]["text"], "Benchmark task"); + let in_flight = benchmark_json(client.post(&finalize), 409).await; + assert_eq!(in_flight["error"], "session still has in-flight attempts"); + assert_eq!(client.delete(&detail).send().await.unwrap().status(), 409); + turn.reply_text("main released"); + let main = main.await.unwrap(); + assert_eq!(main["output"][0]["content"][0]["text"], "main released"); + + let protected = benchmark_json(client.post(&reset), 409).await; + assert_eq!( + protected["error"], + "export and delete benchmark sessions before resetting" + ); + let summary = benchmark_json(client.post(&finalize), 200).await; + assert_eq!(summary["finalized"], true); + assert_eq!(summary["attempts"], 2); + let page = benchmark_json(client.get(format!("{detail}?limit=1")), 200).await; + let next = &page["nextCursor"]; + assert_eq!(next, 1); + let rest = benchmark_json(client.get(format!("{detail}?limit=1&after={next}")), 200).await; + assert_eq!(rest["nextCursor"], 2); + for page in [&page, &rest] { + assert_eq!(page["items"].as_array().unwrap().len(), 1); + assert_eq!(page["items"][0]["cursor"], page["nextCursor"]); + } + let attempts = [&page["items"][0], &rest["items"][0]]; + let main = attempts + .iter() + .find(|item| item["purpose"] == "main") + .unwrap(); + let title = attempts + .iter() + .find(|item| item["purpose"] == "title") + .unwrap(); + let timestamp = |item: &Value, field: &str| item[field].as_u64().unwrap(); + assert!(timestamp(main, "headersReceivedNs") < timestamp(title, "headersReceivedNs")); + assert!(timestamp(title, "lastFrameConsumedNs") < timestamp(main, "lastFrameConsumedNs")); + let attribution = &page["attribution"]; + assert_eq!(attribution, &rest["attribution"]); + assert_eq!(attribution["overlappingIntervalsCount"], 1); + assert!(attribution["outsideMockWallNs"].as_u64().is_some()); + let by_purpose = &attribution["mockServiceSumByPurposeNs"]; + let main_ns = by_purpose["main"].as_u64().unwrap(); + let title_ns = by_purpose["title"].as_u64().unwrap(); + let sum = attribution["mockServiceSumNs"].as_u64().unwrap(); + let union = attribution["mockUnionNs"].as_u64().unwrap(); + assert_eq!(sum, main_ns + title_ns); + assert_eq!(union, main_ns); + assert!(union < sum); + + let cursor = &summary["cursor"]; + assert_eq!(client.delete(&detail).send().await.unwrap().status(), 400); + assert_eq!( + client + .delete(format!("{detail}?cursor={cursor}&after={next}")) + .send() + .await + .unwrap() + .status(), + 409 + ); + assert_eq!(client.post(&reset).send().await.unwrap().status(), 409); + let through = &rest["nextCursor"]; + let deleted = benchmark_json( + client.delete(format!("{detail}?cursor={cursor}&after={through}")), + 200, + ) + .await; + assert_eq!(deleted, json!({"deleted":true})); + assert_eq!(client.get(&detail).send().await.unwrap().status(), 404); + let list = benchmark_json( + client.get(format!("{origin}/admin/sessions?run=bench")), + 200, + ) + .await; + assert_eq!(list["items"], json!([])); + assert_eq!( + benchmark_json(client.post(&reset), 200).await, + json!({"reset":true}) + ); + server.shutdown().await; +} + #[tokio::test] async fn dynamic_ttft_tps_hot_tuning_and_ping_disconnect_hygiene() { let server = MockAiBuilder::new() @@ -799,6 +1243,79 @@ async fn per_model_histograms_and_prometheus_metrics() { server.shutdown().await; } +#[tokio::test] +async fn prometheus_exports_unique_samples_for_mixed_statuses_on_one_model() { + use maka_mock_ai::HttpErrorSpec; + use std::collections::{BTreeMap, BTreeSet}; + + let server = MockAiBuilder::new() + .scripted([ + TurnPlan::text("ok"), + TurnPlan::http_error(HttpErrorSpec::rate_limit(Some(1), "slow down")), + TurnPlan::http_error(HttpErrorSpec::new(503, "overloaded_error", "busy")), + ]) + .start() + .await + .unwrap(); + let client = reqwest::Client::new(); + let endpoint = format!("{}/chat/completions", server.base_url()); + let request = json!({ + "model":"mixed-model","stream":true,"messages":[{"role":"user","content":"ping"}], + }); + for expected in [200, 429, 503] { + let response = post_json(&client, &endpoint, &request).await; + let status = response.status(); + let body = response.text().await.unwrap(); + assert_eq!(status, expected, "{body}"); + } + let exposition = client + .get(format!("{}/metrics", server.origin_url())) + .send() + .await + .unwrap() + .error_for_status() + .unwrap() + .text() + .await + .unwrap(); + + let mut series = BTreeSet::new(); + let mut requests_by_status = BTreeMap::new(); + for line in exposition + .lines() + .filter(|line| !line.is_empty() && !line.starts_with('#')) + { + let (key, sample) = line.rsplit_once(' ').unwrap(); + let (name, mut labels) = key + .split_once('{') + .map_or((key, Vec::new()), |(name, labels)| { + (name, labels.strip_suffix('}').unwrap().split(',').collect()) + }); + labels.sort_unstable(); + if name == "mock_ai_dimension_requests_total" && labels.contains(&r#"model="mixed-model""#) + { + let status = labels + .iter() + .find_map(|label| label.strip_prefix("status=\"")) + .unwrap(); + assert!( + requests_by_status + .insert(status.trim_end_matches('"'), sample) + .is_none() + ); + } + assert!( + series.insert((name, labels)), + "duplicate Prometheus sample: {line}" + ); + } + assert_eq!( + requests_by_status, + BTreeMap::from([("200", "1"), ("429", "1"), ("503", "1")]) + ); + server.shutdown().await; +} + #[tokio::test] async fn transparent_proxy_record_redaction_and_speed_scaled_replay() { // 1. Start upstream simulated provider @@ -1388,6 +1905,11 @@ async fn astra_audit_regressions() { assert_eq!(p1.status(), 200); let p1_json = parse_json(p1).await; let prev_id = p1_json["id"].as_str().unwrap().to_string(); + let proxied_parent = format!("{}/responses/{prev_id}", chain_proxy.base_url()); + assert_eq!( + benchmark_json(client.get(&proxied_parent), 200).await, + p1_json + ); let p2 = post_json( &client, &format!("{}/responses", chain_proxy.base_url()), @@ -1396,43 +1918,57 @@ async fn astra_audit_regressions() { .await; assert_eq!(p2.status(), 200); let p2_text = p2.text().await.unwrap(); + let deleted = benchmark_json(client.delete(&proxied_parent), 200).await; + assert_eq!(deleted["deleted"], true); chain_proxy.shutdown().await; chain_up.shutdown().await; - // Verify Sequential mode does NOT advance cursor when a wrong previous_response_id is rejected! - let chain_replayer = MockAiBuilder::new() - .replay( - ReplayConfig::new(&chain_cassette) - .with_speed(0.0) - .with_match_mode(ReplayMatchMode::Sequential), + for strict in [false, true] { + let mut replay = ReplayConfig::new(&chain_cassette) + .with_speed(0.0) + .with_match_mode(ReplayMatchMode::Sequential); + replay.strict_replay = strict; + let chain_replayer = MockAiBuilder::new() + .replay(replay) + .unwrap() + .start() + .await + .unwrap(); + let url = format!("{}/responses", chain_replayer.base_url()); + let replayed_parent = format!("{url}/{prev_id}"); + let rp1 = benchmark_json( + json_request( + &client, + &url, + &json!({"model": "gpt-5", "stream": false, "store": true, "input": "turn1"}), + ), + 200, ) - .unwrap() - .start() - .await - .unwrap(); - let rp1 = post_json( - &client, - &format!("{}/responses", chain_replayer.base_url()), - &json!({"model": "gpt-5", "stream": false, "store": true, "input": "turn1"}), - ) - .await; - assert_eq!(rp1.status(), 200); - // Bogus previous_response_id MUST be rejected with 400 under strict mode even in replay! - let rp_bad = post_json( - &client, - &format!("{}/responses", chain_replayer.base_url()), - &json!({"model": "gpt-5", "stream": false, "store": true, "previous_response_id": "resp_wrong_id", "input": "turn2"}), - ) - .await; - assert_eq!(rp_bad.status(), 400); - let rp2 = post_json( - &client, - &format!("{}/responses", chain_replayer.base_url()), - &json!({"model": "gpt-5", "stream": false, "store": true, "previous_response_id": prev_id, "input": "turn2"}), - ) - .await; - assert_eq!(rp2.status(), 200); - assert_eq!(rp2.text().await.unwrap(), p2_text); - chain_replayer.shutdown().await; + .await; + assert_eq!(rp1, p1_json); + assert_eq!( + benchmark_json(client.get(&replayed_parent), 200).await, + p1_json + ); + let rp_bad = post_json( + &client, + &url, + &json!({"model": "gpt-5", "stream": false, "store": true, "previous_response_id": "resp_wrong_id", "input": "turn2"}), + ).await; + assert_eq!(rp_bad.status(), if strict { 422 } else { 400 }); + let rp2 = post_json( + &client, + &url, + &json!({"model": "gpt-5", "stream": false, "store": true, "previous_response_id": prev_id, "input": "turn2"}), + ).await; + assert_eq!(rp2.status(), 200); + assert_eq!(rp2.text().await.unwrap(), p2_text); + assert_eq!( + benchmark_json(client.delete(&replayed_parent), 200).await, + deleted + ); + assert_eq!(chain_replayer.metrics().replay_hits, 4); + chain_replayer.shutdown().await; + } let _ = std::fs::remove_file(&chain_cassette); } diff --git a/tools/mock-ai/tests/protocol_conformance.rs b/tools/mock-ai/tests/protocol_conformance.rs index 95a461f714b..dee82ec95a2 100644 --- a/tools/mock-ai/tests/protocol_conformance.rs +++ b/tools/mock-ai/tests/protocol_conformance.rs @@ -22,8 +22,8 @@ use futures_util::{SinkExt, StreamExt}; use maka_mock_ai::{ - Citation, CompactionOutput, FinishReason, MockAiBuilder, NativeToolEvent, ToolCallSpec, - TurnEvent, TurnPlan, Usage, WebSearchResult, + Citation, CompactionOutput, ControlPlaneConfig, FinishReason, MidStreamErrorSpec, + MockAiBuilder, NativeToolEvent, ToolCallSpec, TurnEvent, TurnPlan, Usage, WebSearchResult, }; use maka_provider_protocol::{ anthropic, chat_completions, @@ -34,13 +34,817 @@ use serde_json::{Value, json}; use tokio_tungstenite::tungstenite::Message as WsMessage; async fn post_json(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::Response { + json_request(client, url, body).send().await.unwrap() +} + +fn json_request(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::RequestBuilder { client .post(url) .header("content-type", "application/json") .body(body.to_string()) - .send() +} + +async fn json_status(request: reqwest::RequestBuilder, status: u16) -> Value { + let response = request.send().await.unwrap(); + let actual = response.status(); + let body = response.text().await.unwrap(); + assert_eq!(actual, status, "{body}"); + serde_json::from_str(&body).unwrap() +} + +fn sse_events(body: &str) -> impl Iterator + '_ { + body.lines() + .filter_map(|line| line.strip_prefix("data: ")) + .filter(|data| *data != "[DONE]") + .map(|data| serde_json::from_str(data).unwrap()) +} + +#[tokio::test] +async fn deleting_a_parent_after_child_stream_start_keeps_the_completed_child_resumable() { + let mut server = MockAiBuilder::new() + .strict_benchmark(true) + .interactive(1) + .start() + .await + .unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(3)) + .build() + .unwrap(); + json_status( + json_request( + &client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId": "run", "sessionId": "owner", "logicalLane": "owner", + "harness": "codex", "scenario": "lineage", + }), + ), + 201, + ) + .await; + let url = format!("{origin}/s/run/owner/v1/responses"); + let parent = tokio::spawn(json_status( + json_request(&client, &url, &json!({"input":"first", "store":true})), + 200, + )); + server + .next_turn() .await .unwrap() + .send_plan(TurnPlan::text("parent").with_response_id("parent")); + assert_eq!(parent.await.unwrap()["id"], "parent"); + + let child = tokio::spawn( + json_request( + &client, + &url, + &json!({ + "input":"next", "stream":true, "store":true, "previous_response_id":"parent", + }), + ) + .send(), + ); + let turn = server.next_turn().await.unwrap(); + turn.set_response_id("child"); + assert!(turn.send(TurnEvent::StreamStart).await); + let mut child = child.await.unwrap().unwrap(); + assert_eq!(child.status(), 200); + let mut opening = Vec::new(); + while !opening.ends_with(b"\n\n") { + opening.extend(child.chunk().await.unwrap().unwrap()); + } + let event = sse_events(std::str::from_utf8(&opening).unwrap()) + .next() + .unwrap(); + assert_eq!(event["type"], "response.created"); + assert_eq!(event["response"]["id"], "child"); + + assert_eq!( + json_status(client.delete(format!("{url}/parent")), 200).await["deleted"], + true + ); + assert!(turn.delta("child reply").await); + turn.finish().await; + let stream = child.text().await.unwrap(); + let completed = sse_events(&stream) + .find(|event| event["type"] == "response.completed") + .unwrap(); + let saved = json_status(client.get(format!("{url}/child")), 200).await; + assert_eq!(saved, completed["response"]); + + let resumed = tokio::spawn(json_status( + json_request( + &client, + &url, + &json!({ + "input":"continue", "previous_response_id":"child", + }), + ), + 200, + )); + server + .next_turn() + .await + .unwrap() + .reply_text("resumed child"); + assert_eq!( + resumed.await.unwrap()["output"][0]["content"][0]["text"], + "resumed child" + ); + server.shutdown().await; +} + +#[tokio::test] +async fn reset_excludes_faults_from_in_flight_http_and_ws_turns() { + use std::time::Duration; + + let mut server = MockAiBuilder::new() + .control(ControlPlaneConfig { + enable_admin_api: true, + ..Default::default() + }) + .interactive(2) + .start() + .await + .unwrap(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(3)) + .build() + .unwrap(); + let response = tokio::spawn( + json_request( + &client, + &format!("{}/responses", server.base_url()), + &json!({"input": "HTTP", "stream":true}), + ) + .send(), + ); + let http = server.next_turn().await.unwrap(); + assert!(http.send(TurnEvent::StreamStart).await); + let mut response = response.await.unwrap().unwrap(); + assert_eq!(response.status(), 200); + assert!(response.chunk().await.unwrap().is_some()); + + let (mut socket, _) = tokio_tungstenite::connect_async(server.responses_ws_url()) + .await + .unwrap(); + socket + .send(WsMessage::text( + json!({"type":"response.create", "input":"WS"}).to_string(), + )) + .await + .unwrap(); + let ws = server.next_turn().await.unwrap(); + assert!(ws.send(TurnEvent::StreamStart).await); + let open = tokio::time::timeout(Duration::from_secs(3), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event: Value = serde_json::from_str(open.to_text().unwrap()).unwrap(); + assert_eq!(event["type"], "response.created"); + assert_eq!( + json_status( + client.post(format!("{}/admin/reset", server.origin_url())), + 200 + ) + .await, + json!({"reset":true}) + ); + + http.drop_connection().await; + ws.mid_stream_error(MidStreamErrorSpec { + error_type: "server_error".into(), + code: Some("old_generation_fault".into()), + message: "injected WS failure".into(), + retryable: None, + }) + .await; + assert!(response.text().await.is_err()); + let failure = tokio::time::timeout(Duration::from_secs(3), socket.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let event: Value = serde_json::from_str(failure.to_text().unwrap()).unwrap(); + assert_eq!(event["type"], "response.failed"); + assert_eq!(event["response"]["error"]["code"], "old_generation_fault"); + let metrics = server.metrics(); + assert_eq!(metrics.connection_drops_emitted, 0); + assert_eq!(metrics.mid_stream_errors_emitted, 0); + server.shutdown().await; +} + +#[tokio::test] +async fn scoped_control_routes_enforce_response_ownership_and_storage() { + let server = MockAiBuilder::new() + .strict_benchmark(true) + .scripted([TurnPlan::text("saved"), TurnPlan::text("transient")]) + .start() + .await + .unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::new(); + for session in ["owner", "other"] { + json_status( + json_request( + &client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId": "run", "sessionId": session, "logicalLane": session, + "harness": "codex", "scenario": "control", + }), + ), + 201, + ) + .await; + } + let scope = format!("{origin}/s/run/owner"); + for path in ["/admin/health", "/metrics"] { + let error = json_status(client.get(format!("{scope}{path}")), 403).await; + assert!( + error["error"] + .as_str() + .unwrap() + .contains("unavailable under session scope") + ); + } + let model = json_status(client.get(format!("{scope}/v1/models/gpt-4.1")), 200).await; + assert_eq!(model["id"], "gpt-4.1"); + assert_eq!(model["object"], "model"); + assert_eq!( + json_status( + json_request( + &client, + &format!("{scope}/v1/messages/count_tokens"), + &json!({ + "model": "claude-sonnet-4-5", "system": "sys", + "messages": [{"role": "user", "content": "hello"}], + }) + ), + 200 + ) + .await, + json!({"input_tokens":4}) + ); + + let responses = format!("{scope}/v1/responses"); + let saved = json_status( + json_request( + &client, + &responses, + &json!({ + "model": "gpt-4.1", "input": "first", "store": true, + }), + ), + 200, + ) + .await; + assert_eq!(saved["output"][0]["content"][0]["text"], "saved"); + let retained = + json!({"type":"message", "role":"user", "content":[{"type":"input_text","text":"first"}]}); + let compact = json_status( + json_request( + &client, + &format!("{responses}/compact"), + &json!({ + "model":"gpt-4.1", "previous_response_id":saved["id"], "input":[retained], + }), + ), + 200, + ) + .await; + assert_eq!(compact["object"], "response.compaction"); + assert_eq!(compact["output"][0], retained); + let checkpoint = &compact["output"][1]; + assert_eq!(checkpoint["type"], "compaction"); + assert_eq!( + checkpoint["encrypted_content"], + format!("mock:{}", checkpoint["id"].as_str().unwrap()) + ); + + let transient = json_status(json_request(&client, &responses, &json!({ + "model":"gpt-4.1", "previous_response_id":compact["id"], "input":[checkpoint], "store":false, + })), 200).await; + assert_eq!(transient["output"][0]["content"][0]["text"], "transient"); + let id = saved["id"].as_str().unwrap(); + let own_url = format!("{responses}/{id}"); + let foreign_url = format!("{origin}/s/run/other/v1/responses/{id}"); + assert_eq!( + client + .get(format!("{responses}/{}", transient["id"].as_str().unwrap())) + .send() + .await + .unwrap() + .status(), + 404 + ); + assert_eq!(client.get(&foreign_url).send().await.unwrap().status(), 404); + assert_eq!( + client.delete(&foreign_url).send().await.unwrap().status(), + 404 + ); + assert_eq!(json_status(client.get(&own_url), 200).await, saved); + assert_eq!( + json_status(client.delete(&own_url), 200).await, + json!({"id":id, "object":"response.deleted", "deleted":true}) + ); + assert_eq!(client.get(&own_url).send().await.unwrap().status(), 404); + server.shutdown().await; +} + +#[tokio::test] +async fn chat_sse_usage_and_reasoning_follow_independent_wire_options() { + use maka_mock_ai::ProviderDialectProfile::{DeepSeekChat, StandardOpenAi}; + + let client = reqwest::Client::new(); + for (dialect, expected_reasoning) in [(StandardOpenAi, ""), (DeepSeekChat, "draft 🦀")] { + let plan = TurnPlan::new() + .push_reasoning("draft 🦀") + .push_text_chunked("answer", 2) + .with_usage(Usage::new(7, 2)) + .finish(FinishReason::Stop); + let server = MockAiBuilder::new() + .provider_dialect(dialect) + .scripted([plan.clone(), plan]) + .start() + .await + .unwrap(); + for include_usage in [true, false] { + let response = post_json(&client, &format!("{}/chat/completions", server.base_url()), &json!({ + "model":"gpt-4.1", "stream":true, "stream_options":{"include_usage":include_usage}, + "messages":[{"role":"user", "content":"answer this"}], + })).await.error_for_status().unwrap().text().await.unwrap(); + assert!(response.ends_with("data: [DONE]\n\n")); + let mut chunks: Vec<_> = sse_events(&response).collect(); + if include_usage { + let tail = chunks.pop().unwrap(); + assert_eq!(tail["choices"], json!([])); + assert_eq!( + tail["usage"], + json!({"prompt_tokens":7,"completion_tokens":2,"total_tokens":9}) + ); + } + assert_eq!( + chunks.last().unwrap()["choices"][0]["finish_reason"], + "stop" + ); + let mut reasoning = String::new(); + let mut text = String::new(); + for chunk in chunks { + assert_eq!(chunk.get("usage"), include_usage.then_some(&Value::Null)); + assert_eq!(chunk["choices"].as_array().unwrap().len(), 1); + let delta = &chunk["choices"][0]["delta"]; + if expected_reasoning.is_empty() { + assert!(delta.get("reasoning_content").is_none()); + } + reasoning.extend(delta["reasoning_content"].as_str()); + text.extend(delta["content"].as_str()); + } + assert_eq!(reasoning, expected_reasoning); + assert_eq!(text, "answer"); + } + server.shutdown().await; + } +} + +#[tokio::test] +async fn responses_text_and_refusal_fold_to_json_and_stored_response() { + let plan = TurnPlan::new() + .with_response_id("resp_mixed") + .push_text_chunked("Visible 🦀", 2) + .push(TurnEvent::Refusal { + text: "Cannot share that.".into(), + }) + .push_text_chunked("Try this.", 3) + .with_usage(Usage::new(17, 8)) + .finish(FinishReason::Stop); + let server = MockAiBuilder::new() + .scripted([plan.clone(), plan]) + .start() + .await + .unwrap(); + let client = reqwest::Client::new(); + let url = format!("{}/responses", server.base_url()); + let mut request = json!({"model":"gpt-4.1","input":"mixed reply","stream":true,"store":true}); + let body = post_json(&client, &url, &request) + .await + .error_for_status() + .unwrap() + .text() + .await + .unwrap(); + let mut sequence = None; + let mut parts = Vec::::new(); + let mut done_indexes = Vec::new(); + let mut folded = None; + let mut completed = None; + for event in sse_events(&body) { + let next = event["sequence_number"].as_u64().unwrap(); + assert!(sequence.is_none_or(|previous| previous < next)); + sequence = Some(next); + match event["type"].as_str().unwrap() { + "response.output_item.added" => { + assert_eq!(event["output_index"], 0); + assert_eq!(event["item"]["status"], "in_progress"); + assert_eq!(event["item"]["content"], json!([])); + assert!(folded.replace(event["item"].clone()).is_none()); + } + "response.content_part.added" => { + assert_eq!(event["output_index"], 0); + assert_eq!(event["content_index"], parts.len()); + parts.push(event["part"].clone()); + } + "response.output_text.delta" | "response.refusal.delta" => { + assert_eq!(event["output_index"], 0); + let index = event["content_index"].as_u64().unwrap() as usize; + let (kind, field) = if event["type"] == "response.output_text.delta" { + ("output_text", "text") + } else { + ("refusal", "refusal") + }; + let part = &mut parts[index]; + assert_eq!(part["type"], kind); + part[field] = json!(format!( + "{}{}", + part[field].as_str().unwrap(), + event["delta"].as_str().unwrap() + )); + } + "response.content_part.done" => { + assert_eq!(event["output_index"], 0); + let index = event["content_index"].as_u64().unwrap() as usize; + assert_eq!(event["part"], parts[index]); + done_indexes.push(index); + } + "response.output_item.done" => { + assert_eq!(event["output_index"], 0); + let item = folded.as_mut().unwrap(); + item["content"] = json!(parts); + item["status"] = json!("completed"); + assert_eq!(&event["item"], item); + } + "response.completed" => assert!(completed.replace(event["response"].clone()).is_none()), + _ => {} + } + } + assert_eq!(done_indexes, [0, 1, 2]); + assert_eq!( + parts, + [ + json!({"type":"output_text","text":"Visible 🦀","annotations":[]}), + json!({"type":"refusal","refusal":"Cannot share that."}), + json!({"type":"output_text","text":"Try this.","annotations":[]}), + ] + ); + let completed = completed.unwrap(); + assert_eq!(completed["output"], json!([folded.unwrap()])); + assert_eq!(completed["usage"]["total_tokens"], 25); + let stored = json_status(client.get(format!("{url}/resp_mixed")), 200).await; + assert_eq!(completed, stored); + + request["stream"] = json!(false); + let mut standalone = json_status(json_request(&client, &url, &request), 200).await; + // Independent requests can start on different wall-clock seconds. + assert!(standalone["created_at"].as_u64().is_some()); + standalone["created_at"] = completed["created_at"].clone(); + assert_eq!(completed, standalone); + server.shutdown().await; +} + +#[tokio::test] +async fn anthropic_ping_signed_thinking_and_compaction_survive_stream_and_replay() { + let server = MockAiBuilder::new() + .handler_fn(|request, _| { + if request.last_user_text() == Some("resume") { + let prior = &request.raw_body["messages"][1]["content"]; + if prior + == &json!([ + {"type":"thinking", "thinking":"check 🦀", "signature":"opaque-signature"}, + {"type":"compaction", "content":"checkpoint summary"}, + ]) + { + return TurnPlan::text("resumed from checkpoint"); + } + return TurnPlan::http_error(maka_mock_ai::HttpErrorSpec::new( + 422, + "invalid_request_error", + "signed checkpoint was not replayed", + )); + } + TurnPlan::new() + .push(TurnEvent::Ping) + .push(TurnEvent::Reasoning { + text: "check 🦀".into(), + chunk_chars: 2, + signature: Some("opaque-signature".into()), + encrypted_content: None, + }) + .push_compaction( + CompactionOutput::new("checkpoint summary") + .with_pause(request.options.anthropic_pause_after_compaction), + ) + .push_text("continued in the same response") + .finish(FinishReason::Stop) + }) + .start() + .await + .unwrap(); + let client = reqwest::Client::new(); + let url = format!("{}/messages", server.base_url()); + let mut request = json!({ + "model":"claude-sonnet-4-5", "max_tokens":512, "stream":true, + "context_management":{"edits":[{"type":"compact_20260112"}]}, + "messages":[{"role":"user","content":"compact history"}], + }); + for (pause, stop, expected_text) in [ + (true, "compaction", "checkpoint summary"), + ( + false, + "end_turn", + "checkpoint summarycontinued in the same response", + ), + ] { + request["context_management"]["edits"][0]["pause_after_compaction"] = json!(pause); + let raw = post_json(&client, &url, &request) + .await + .error_for_status() + .unwrap() + .bytes() + .await + .unwrap(); + let wire = std::str::from_utf8(&raw).unwrap(); + assert!( + wire.split("\n\n") + .any(|frame| frame == "event: ping\ndata: {\"type\":\"ping\"}") + ); + let mut decoder = anthropic::stream::Stream::new(anthropic::response::Options::default()); + let mut sequence = 0; + let mut next_id = || { + sequence += 1; + format!("part_{sequence}") + }; + let mut events = decoder.push(&raw, &mut next_id, |_| {}).unwrap(); + events.extend(decoder.finish()); + let mut thinking = String::new(); + let mut signature = None; + let mut text = String::new(); + let mut finish = None; + for event in events { + match event { + WireEvent::TextDelta { + kind: TextKind::Reasoning, + text, + extensions, + .. + } => { + thinking.push_str(&text); + if let Some(extensions) = extensions { + let signed = extensions["anthropic"]["signature"].as_str().unwrap(); + assert!(signature.replace(signed.to_owned()).is_none()); + } + } + WireEvent::TextDelta { + kind: TextKind::Text, + text: delta, + .. + } => text.push_str(&delta), + WireEvent::Finish(event) => assert!(finish.replace(event.raw_reason).is_none()), + WireEvent::Error(error) => panic!("Anthropic decoder rejected the stream: {error}"), + _ => {} + } + } + assert_eq!(finish.flatten().as_deref(), Some(stop)); + assert_eq!(text, expected_text); + assert_eq!(thinking, "check 🦀"); + assert_eq!(signature.as_deref(), Some("opaque-signature")); + if pause { + let resumed = json_status( + json_request( + &client, + &url, + &json!({ + "model":"claude-sonnet-4-5", "max_tokens":512, + "messages":[ + {"role":"user","content":"compact history"}, + {"role":"assistant","content":[ + {"type":"thinking","thinking":thinking,"signature":signature}, + {"type":"compaction","content":text}, + ]}, + {"role":"user","content":"resume"}, + ], + }), + ), + 200, + ) + .await; + assert_eq!(resumed["content"][0]["text"], "resumed from checkpoint"); + } + } + server.shutdown().await; +} + +#[tokio::test] +async fn responses_replays_a_namespaced_mcp_call_until_its_receipt() { + use maka_mock_ai::scenario::{BenchmarkTrack, CanonicalAction, FixtureDef, ScenarioSpec}; + + let spec = ScenarioSpec::new("mcp-read", 17, "note", BenchmarkTrack::SharedMcp) + .with_fixture( + "note", + FixtureDef::File { + path: "note.txt".into(), + content: "fixture marker\n".into(), + }, + ) + .with_step( + "read", + CanonicalAction::ReadFile { + path: "note.txt".into(), + expect_marker: "fixture marker".into(), + }, + ) + .with_step( + "done", + CanonicalAction::FinalAnswer { + text: "Read verified.".into(), + expect_markers: vec!["Read verified.".into()], + }, + ); + let server = MockAiBuilder::new().scenario(spec).start().await.unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::new(); + json_status( + json_request( + &client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId": "run", "sessionId": "lane", "logicalLane": "lane", "harness": "codex", + "scenario": "mcp-read", "workspace": std::env::current_dir().unwrap(), + }), + ), + 201, + ) + .await; + let url = format!("{origin}/s/run/lane/v1/responses"); + let read = json!({ + "type": "function", "name": "bench_read_file", "defer_loading": true, + "parameters": { + "type": "object", "properties": { "path": { "type": "string" } }, + "required": ["path"], "additionalProperties": false, + } + }); + let namespace = |name: &str| json!({"type": "namespace", "name": name, "tools": [read]}); + let user = json!({"role": "user", "content": "Read the note."}); + let mut request = json!({ + "input": [user], "tools": [namespace("mcp__bench")], "stream": true, "store": true, + }); + let sse = post_json(&client, &url, &request) + .await + .error_for_status() + .unwrap() + .text() + .await + .unwrap(); + let events: Vec<_> = sse_events(&sse).collect(); + let event = |kind| events.iter().find(|event| event["type"] == kind).unwrap(); + let completed = &event("response.completed")["response"]; + let done = &event("response.output_item.done")["item"]; + assert_eq!(completed["output"], json!([done])); + assert_eq!(done["type"], "function_call"); + assert_eq!(done["name"], "bench_read_file"); + assert_eq!(done["namespace"], "mcp__bench"); + assert_eq!(done["arguments"], r#"{"path":"note.txt"}"#); + let mut added = done.clone(); + added["status"] = json!("in_progress"); + added["arguments"] = json!(""); + assert_eq!(event("response.output_item.added")["item"], added); + let id = completed["id"].as_str().unwrap(); + let stored = json_status(client.get(format!("{url}/{id}")), 200).await; + assert_eq!(stored["output"], completed["output"]); + + request["stream"] = json!(false); + request["tools"] = json!([namespace("other"), read]); + let rejected = json_status(json_request(&client, &url, &request), 422).await; + assert_eq!( + rejected["error"]["message"], + r#"unsupported bench_read_file: ["replay requires one matching tool declaration"]"# + ); + request["tools"] + .as_array_mut() + .unwrap() + .push(namespace("mcp__bench")); + let replay = json_status(json_request(&client, &url, &request), 200).await; + assert_eq!(replay["id"], id); + assert_eq!(replay["output"], completed["output"]); + + request["input"] = json!([ + user, done, { + "type": "function_call_output", "call_id": done["call_id"], "output": "fixture marker\n", + } + ]); + let next = json_status(json_request(&client, &url, &request), 200).await; + assert_ne!(next["id"], id); + assert_eq!(next["output"][0]["content"][0]["text"], "Read verified."); + server.shutdown().await; +} + +#[tokio::test] +async fn harness_titles_take_the_side_path_and_user_title_requests_complete_the_scenario() { + use maka_mock_ai::scenario::{ + BenchmarkTrack, CanonicalAction, FaultKind, ScenarioSpec, ScheduledFault, + }; + + let spec = ScenarioSpec::new("user-title", 7, "article", BenchmarkTrack::Native) + .with_step( + "answer", + CanonicalAction::FinalAnswer { + text: "潮汐之后".into(), + expect_markers: vec!["潮汐之后".into()], + }, + ) + .with_fault(ScheduledFault { + step: "answer".into(), + attempt: 1, + at: Default::default(), + emit: FaultKind::Http429, + }); + let server = MockAiBuilder::new().scenario(spec).start().await.unwrap(); + let origin = server.origin_url(); + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap(); + for harness in ["opencode", "claude-code"] { + json_status( + json_request( + &client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId":"run","sessionId":harness,"logicalLane":harness,"harness":harness, + "scenario":"user-title","workspace":std::env::current_dir().unwrap(), + }), + ), + 201, + ) + .await; + let (path, system, side_text, text_pointer) = if harness == "opencode" { + ( + "chat/completions", + "You are a title generator. You output ONLY a thread title.", + "Benchmark task", + "/choices/0/message/content", + ) + } else { + ( + "messages", + "Generate a concise, sentence-case title (3-7 words). Return JSON with a single \"title\" field.", + r#"{"title":"Benchmark task"}"#, + "/content/0/text", + ) + }; + let url = format!("{origin}/s/run/{harness}/v1/{path}"); + let user = json!({"role":"user","content":"帮这篇文章起个标题"}); + let main = json!({"model":"mock-model","max_tokens":256,"messages":[user]}); + let mut side = main.clone(); + if harness == "opencode" { + side["messages"] + .as_array_mut() + .unwrap() + .insert(0, json!({"role":"system","content":system})); + } else { + side["system"] = json!(system); + } + let title = json_status(json_request(&client, &url, &side), 200).await; + assert_eq!(title.pointer(text_pointer).unwrap(), side_text); + let rejected = json_status(json_request(&client, &url, &main), 429).await; + assert_eq!(rejected["error"]["type"], "rate_limit_error"); + let answer = json_status(json_request(&client, &url, &main), 200).await; + assert_eq!(answer.pointer(text_pointer).unwrap(), "潮汐之后"); + let detail = format!("{origin}/admin/sessions/{harness}"); + let summary = json_status( + json_request( + &client, + &format!("{detail}/finalize"), + &json!({ + "responseId":answer["id"], "observedMarkers":["潮汐之后"], + }), + ), + 200, + ) + .await; + assert_eq!(summary["finalized"], true); + let timeline = json_status(client.get(&detail), 200).await; + let purposes: Vec<_> = timeline["items"] + .as_array() + .unwrap() + .iter() + .map(|item| item["purpose"].as_str().unwrap()) + .collect(); + assert_eq!(purposes, ["title", "main", "main"]); + } + server.shutdown().await; } #[tokio::test] diff --git a/tools/mock-ai/tests/stress_and_scenarios.rs b/tools/mock-ai/tests/stress_and_scenarios.rs index b6dbadb5153..e0c15fd2769 100644 --- a/tools/mock-ai/tests/stress_and_scenarios.rs +++ b/tools/mock-ai/tests/stress_and_scenarios.rs @@ -23,17 +23,19 @@ use maka_mock_ai::{ ModelEntry, RecorderMode, ServerTuning, TurnPlan, WorkloadConfig, builder_from_config, }; use serde_json::{Value, json}; +use std::collections::HashSet; use std::time::Duration; use tokio_tungstenite::tungstenite::Message as WsMessage; async fn post_json(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::Response { + json_request(client, url, body).send().await.unwrap() +} + +fn json_request(client: &reqwest::Client, url: &str, body: &Value) -> reqwest::RequestBuilder { client .post(url) .header("content-type", "application/json") .body(body.to_string()) - .send() - .await - .unwrap() } async fn read_json(resp: reqwest::Response) -> Value { @@ -41,6 +43,508 @@ async fn read_json(resp: reqwest::Response) -> Value { serde_json::from_slice(&bytes).unwrap() } +#[derive(Clone, Copy)] +enum LaneWire { + Responses, + Messages, + Chat, +} + +impl LaneWire { + fn path(self) -> &'static str { + match self { + Self::Responses => "responses", + Self::Messages => "messages", + Self::Chat => "chat/completions", + } + } + + fn function(self, name: &str, required: &[&str]) -> Value { + let properties: serde_json::Map<_, _> = required + .iter() + .map(|&key| (key.to_owned(), json!({"type":"string"}))) + .collect(); + let schema = json!({ + "type":"object", "properties":properties, "required":required, + "additionalProperties":false, + }); + match self { + Self::Responses => json!({"type":"function","name":name,"parameters":schema}), + Self::Messages => json!({"name":name,"input_schema":schema}), + Self::Chat => json!({"type":"function","function":{"name":name,"parameters":schema}}), + } + } + + fn tool_call(self, reply: &Value) -> (&Value, &Value, Value) { + match self { + Self::Responses => { + let item = &reply["output"][0]; + let args = if item["type"] == "custom_tool_call" { + item["input"].clone() + } else { + assert_eq!(item["type"], "function_call"); + serde_json::from_str(item["arguments"].as_str().unwrap()).unwrap() + }; + assert_eq!(reply["output"].as_array().unwrap().len(), 1); + (&item["call_id"], &item["name"], args) + } + Self::Messages => { + let blocks = reply["content"].as_array().unwrap(); + assert_eq!(blocks.len(), 1); + let item = &blocks[0]; + assert_eq!(item["type"], "tool_use"); + (&item["id"], &item["name"], item["input"].clone()) + } + Self::Chat => { + let calls = reply["choices"][0]["message"]["tool_calls"] + .as_array() + .unwrap(); + assert_eq!(calls.len(), 1); + let item = &calls[0]; + assert_eq!(item["type"], "function"); + ( + &item["id"], + &item["function"]["name"], + serde_json::from_str(item["function"]["arguments"].as_str().unwrap()).unwrap(), + ) + } + } + } + + fn acknowledge(self, request: &mut Value, reply: &Value, id: &Value, output: &str) { + match self { + Self::Responses => { + let kind = if reply["output"][0]["type"] == "custom_tool_call" { + "custom_tool_call_output" + } else { + "function_call_output" + }; + request["previous_response_id"] = reply["id"].clone(); + request["input"] = json!([{"type":kind,"call_id":id,"output":output}]); + } + Self::Messages => request["messages"].as_array_mut().unwrap().extend([ + json!({"role":"assistant","content":reply["content"]}), + json!({"role":"user","content":[{"type":"tool_result","tool_use_id":id,"content":output}]}), + ]), + Self::Chat => request["messages"].as_array_mut().unwrap().extend([ + reply["choices"][0]["message"].clone(), + json!({"role":"tool","tool_call_id":id,"content":output}), + ]), + } + } + + fn text(self, reply: &Value) -> &Value { + match self { + Self::Responses => &reply["output"][0]["content"][0]["text"], + Self::Messages => &reply["content"][0]["text"], + Self::Chat => &reply["choices"][0]["message"]["content"], + } + } +} + +#[derive(Clone, Copy)] +enum LaneHarness { + Maka, + Claude, + Codex, + Dim, + Kimi, + Shared, +} + +impl LaneHarness { + fn fixture(self) -> (&'static str, LaneWire, [&'static str; 3], Vec) { + use LaneWire::{Chat, Messages, Responses}; + let patch = |name, grammar| { + json!({"type":"custom","name":name,"format":{ + "type":"grammar","syntax":"lark","definition":grammar, + }}) + }; + let (harness, wire, names, params): (_, _, _, [&[&str]; 3]) = match self { + Self::Maka => { + let exec = patch( + "exec", + r"start: pragma_source | plain_source +plain_source: SOURCE +PRAGMA_LINE: /[ \t]*\/\/ @exec:[^\r\n]*/ +SOURCE: /[\s\S]+/", + ); + return ("maka", Responses, ["exec"; 3], vec![exec]); + } + Self::Codex => { + let apply_patch = patch( + "apply_patch", + "start: \"*** Begin Patch\" hunk \"*** End Patch\"", + ); + return ( + "codex", + Responses, + ["exec_command", "apply_patch", "exec_command"], + vec![Responses.function("exec_command", &["cmd"]), apply_patch], + ); + } + Self::Claude => ( + "claude-code", + Messages, + ["Read", "Edit", "Bash"], + [ + &["file_path"], + &["file_path", "old_string", "new_string"], + &["command", "description"], + ], + ), + Self::Dim => ( + "dim", + Chat, + ["read", "edit", "exec"], + [&["path"], &["path", "oldText", "newText"], &["command"]], + ), + Self::Kimi => ( + "kimi", + Chat, + ["Read", "Edit", "Shell"], + [ + &["path"], + &["path", "old_string", "new_string"], + &["command"], + ], + ), + Self::Shared => ( + "shared-mcp", + Responses, + [ + "mcp__bench__read_file", + "mcp__bench__edit_file", + "mcp__bench__exec_shell", + ], + [ + &["path"], + &["path", "old_string", "new_string"], + &["command"], + ], + ), + }; + let tools = names + .into_iter() + .zip(params) + .map(|(name, required)| wire.function(name, required)) + .collect(); + (harness, wire, names, tools) + } + + fn check_args(self, round: usize, args: &Value, workspace: &std::path::Path) { + let expected = match (self, round) { + (Self::Maka, _) => { + let (tool, ref expected) = [ + ("Read", json!({"path":"fixture.txt"})), + ( + "Edit", + json!({"path":"fixture.txt","old_string":"marker","new_string":"changed"}), + ), + ( + "Shell", + json!({"command":"printf checked","title":"verify"}), + ), + ][round]; + let source = args.as_str().unwrap(); + let (_, input) = source.split_once(&format!("tools.{tool}(")).unwrap(); + let (input, _) = input.split_once(')').unwrap(); + assert_eq!(&serde_json::from_str::(input).unwrap(), expected); + return; + } + (Self::Codex, 0) => json!({"cmd":"cat -- 'fixture.txt'"}), + (Self::Codex, 1) => json!( + "*** Begin Patch\n*** Update File: fixture.txt\n@@\n-marker\n+changed\n*** End Patch" + ), + (Self::Codex, 2) => json!({"cmd":"printf checked"}), + (Self::Claude, 0) => json!({"file_path":workspace.join("fixture.txt")}), + (Self::Claude, 1) => { + json!({"file_path":workspace.join("fixture.txt"),"old_string":"marker","new_string":"changed"}) + } + (Self::Claude, 2) => json!({"command":"printf checked","description":"verify"}), + (Self::Dim, 1) => { + json!({"path":"fixture.txt","oldText":"marker","newText":"changed"}) + } + (_, 0) => json!({"path":"fixture.txt"}), + (_, 1) => json!({"path":"fixture.txt","old_string":"marker","new_string":"changed"}), + (_, 2) => json!({"command":"printf checked"}), + _ => unreachable!("three tool rounds"), + }; + assert_eq!(*args, expected); + } +} + +async fn checked_json(request: reqwest::RequestBuilder, status: u16) -> Value { + let response = request.send().await.unwrap(); + let actual = response.status(); + let body = response.text().await.unwrap(); + assert_eq!(actual, status, "{body}"); + serde_json::from_str(&body).unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn sixty_four_scoped_lanes_finish_equal_tool_chains_with_bounded_recording() { + use maka_mock_ai::WatchdogConfig; + use maka_mock_ai::scenario::{BenchmarkTrack, CanonicalAction, FixtureDef, ScenarioSpec}; + use std::sync::Arc; + use tokio::sync::Barrier; + + const LANES: usize = 64; + const RING_ENTRIES: usize = 8; + const ENTRY_LIMIT_BYTES: usize = 128 * 1024; + const BYTE_LIMIT_BYTES: usize = 16 * 1024; + const LONG_OUTPUT_BYTES: usize = 10 * 1024; + let scenario = |track| { + ScenarioSpec::new("tool-chain", 17, "fixture", track) + .with_fixture( + "file", + FixtureDef::File { + path: "fixture.txt".into(), + content: "marker\n".into(), + }, + ) + .with_fixture( + "verify", + FixtureDef::Command { + command: "printf checked".into(), + }, + ) + .with_step( + "read", + CanonicalAction::ReadFile { + path: "fixture.txt".into(), + expect_marker: "marker".into(), + }, + ) + .with_step( + "edit", + CanonicalAction::EditFile { + path: "fixture.txt".into(), + old: "marker".into(), + new: "changed".into(), + }, + ) + .with_step( + "verify", + CanonicalAction::Shell { + command_id: "verify".into(), + command: "printf checked".into(), + }, + ) + .with_step( + "finish", + CanonicalAction::FinalAnswer { + text: "Fixture verified.".into(), + expect_markers: vec!["Fixture verified.".into()], + }, + ) + }; + let start = |track, max_bytes| { + MockAiBuilder::new() + .scenario(scenario(track)) + .recorder(RecorderMode::Ring { + capacity: RING_ENTRIES, + max_bytes, + }) + .watchdog(WatchdogConfig { + check_missing_tool_results: true, + ..Default::default() + }) + .start() + }; + let native = start(BenchmarkTrack::Native, ENTRY_LIMIT_BYTES) + .await + .unwrap(); + let shared = start(BenchmarkTrack::SharedMcp, BYTE_LIMIT_BYTES) + .await + .unwrap(); + + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap(); + let workspace = std::env::current_dir().unwrap(); + let launch = Arc::new(Barrier::new(LANES)); + let mut tasks = tokio::task::JoinSet::new(); + let harnesses = [ + LaneHarness::Maka, + LaneHarness::Claude, + LaneHarness::Codex, + LaneHarness::Dim, + LaneHarness::Kimi, + LaneHarness::Shared, + ]; + for lane in 0..LANES { + let harness = harnesses[lane % harnesses.len()]; + let origin = if matches!(harness, LaneHarness::Shared) { + shared.origin_url() + } else { + native.origin_url() + }; + let session = format!("lane-{lane:02}"); + let (name, wire, names, tools) = harness.fixture(); + checked_json( + json_request( + &client, + &format!("{origin}/admin/sessions"), + &json!({ + "runId":"stress","sessionId":session,"logicalLane":session,"harness":name, + "scenario":"tool-chain","workspace":workspace, + }), + ), + 201, + ) + .await; + let (client, workspace, launch) = (client.clone(), workspace.clone(), launch.clone()); + tasks.spawn(async move { + let url = format!("{origin}/s/stress/{session}/v1/{}", wire.path()); + let first = "Read, edit and verify the fixture."; + let mut request = match wire { + LaneWire::Responses => json!({"model":"mock-model","input":first,"tools":tools}), + _ => json!({"model":"mock-model","max_tokens":512, + "messages":[{"role":"user","content":first}],"tools":tools}), + }; + let mut side = request.clone(); + side.as_object_mut().unwrap().remove("tools"); + launch.wait().await; + let (mut reply, title) = tokio::join!( + checked_json(json_request(&client, &url, &request), 200), + checked_json( + json_request(&client, &url, &side).header("x-maka-bench-request-use", "title"), + 200 + ), + ); + let expected = if matches!(wire, LaneWire::Messages) { + r#"{"title":"Benchmark task"}"# + } else { + "Benchmark task" + }; + assert_eq!(wire.text(&title), expected); + let mut call_ids = Vec::new(); + let mut response_ids = Vec::new(); + let shell_output = format!("checked\n{}", "x".repeat(LONG_OUTPUT_BYTES)); + for (round, (name, output)) in names + .into_iter() + .zip(["marker\n", "edited", &shell_output]) + .enumerate() + { + response_ids.push(reply["id"].as_str().unwrap().to_owned()); + let (id, actual, args) = wire.tool_call(&reply); + assert_eq!(actual, name, "{session} round {round}"); + harness.check_args(round, &args, &workspace); + call_ids.push(id.as_str().unwrap().to_owned()); + let code_output; + let output = if matches!(harness, LaneHarness::Maka) { + code_output = json!([{"slot":0,"result":output}]).to_string(); + &code_output + } else { + output + }; + wire.acknowledge(&mut request, &reply, id, output); + reply = checked_json(json_request(&client, &url, &request), 200).await; + } + assert_eq!(wire.text(&reply), "Fixture verified."); + response_ids.push(reply["id"].as_str().unwrap().to_owned()); + let summary = checked_json( + json_request( + &client, + &format!("{origin}/admin/sessions/{session}/finalize"), + &json!({ + "responseId":reply["id"],"observedMarkers":["Fixture verified."], + }), + ), + 200, + ) + .await; + assert_eq!(summary["sessionId"], session); + assert_eq!(summary["attempts"], 5); + (session, call_ids, response_ids) + }); + } + let mut completed = HashSet::new(); + let mut calls = HashSet::new(); + let mut responses = HashSet::new(); + while let Some(task) = tasks.join_next().await { + let (session, call_ids, response_ids) = task.unwrap(); + for id in call_ids { + assert!(calls.insert(id.clone()), "call ID collision: {id}"); + } + for id in response_ids { + assert!(responses.insert(id.clone()), "response ID collision: {id}"); + } + assert!(completed.insert(session)); + } + assert_eq!( + (completed.len(), calls.len(), responses.len()), + (LANES, LANES * 3, LANES * 4) + ); + + let mut exported = HashSet::new(); + let mut attempts = 0; + for (server, max_bytes) in [(native, ENTRY_LIMIT_BYTES), (shared, BYTE_LIMIT_BYTES)] { + let origin = server.origin_url(); + let mut cursor = 0; + loop { + let page = checked_json( + client.get(format!( + "{origin}/admin/sessions?run=stress&limit=7&cursor={cursor}" + )), + 200, + ) + .await; + let items = page["items"].as_array().unwrap(); + assert!(!items.is_empty() && items.len() <= 7); + for item in items { + let next = item["cursor"].as_u64().unwrap(); + assert!(cursor < next); + cursor = next; + assert!(exported.insert(item["sessionId"].as_str().unwrap().to_owned())); + assert_eq!(item["finalized"], true); + assert_eq!(item["attempts"], 5); + assert_eq!(item["retained"], 5); + assert_eq!(item["dropped"], 0); + attempts += item["attempts"].as_u64().unwrap(); + } + if page["nextCursor"].is_null() { + break; + } + assert_eq!(page["nextCursor"], cursor); + } + let watchdog = checked_json(client.get(format!("{origin}/admin/violations")), 200).await; + assert_eq!(watchdog["totalViolations"], 0, "{watchdog}"); + let history = checked_json(client.get(format!("{origin}/admin/requests")), 200).await; + let entries = history.as_array().unwrap(); + let retained_bytes = entries + .iter() + .map(|entry| { + entry["rawBody"] + .to_string() + .len() + .max(entry["promptBytes"].as_u64().unwrap() as usize) + }) + .collect::>(); + assert!( + retained_bytes.iter().sum::() <= max_bytes, + "{retained_bytes:?}" + ); + if max_bytes == ENTRY_LIMIT_BYTES { + assert_eq!(entries.len(), RING_ENTRIES); + } else { + assert!(entries.len() < RING_ENTRIES, "{retained_bytes:?}"); + assert_eq!( + retained_bytes + .iter() + .filter(|&&bytes| bytes >= LONG_OUTPUT_BYTES) + .count(), + 1 + ); + } + server.shutdown().await; + } + assert_eq!(exported, completed); + assert_eq!(attempts, LANES as u64 * 5); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn high_concurrency_deterministic_workload_with_metrics_only() { let config = WorkloadConfig::stress_preset(1337); From 7e16c00815c5bc071ed015f6b05666377b37acec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CM4n5ter=E2=80=9D?= Date: Sat, 28 Nov 2026 15:19:11 +0800 Subject: [PATCH 2/4] fix(mock-ai): compact call IDs, Code Mode ApplyPatch/envelope receipts, and short macOS TMPDIR --- tools/harness-bench/adapters.mjs | 3 +++ tools/mock-ai/src/scenario/mod.rs | 34 +++++++++++++++++++---------- tools/mock-ai/src/scenario/tools.rs | 30 +++++++++++++++++++------ 3 files changed, 49 insertions(+), 18 deletions(-) diff --git a/tools/harness-bench/adapters.mjs b/tools/harness-bench/adapters.mjs index f12aa47caeb..9cf101cce2d 100644 --- a/tools/harness-bench/adapters.mjs +++ b/tools/harness-bench/adapters.mjs @@ -65,6 +65,9 @@ async function isolatedEnv(directory, source) { ['XDG_CACHE_HOME', 'cache'], ['XDG_STATE_HOME', 'state'], ['XDG_RUNTIME_DIR', 'runtime'], ['TMPDIR', 'tmp'], ['APPDATA', 'app-data'], ['LOCALAPPDATA', 'local-app-data'], ].map(([name, leaf]) => [name, join(directory, leaf)])); + if (process.platform === 'darwin' && dirs.TMPDIR.length > 48) { + dirs.TMPDIR = join('/tmp', 'hb-' + randomBytes(4).toString('hex')); + } await Promise.all(Object.values(dirs).map(dir => mkdir(dir, { recursive: true, mode: 0o700 }))); const path = (source.PATH ?? source.Path ?? '/usr/bin:/bin').split(delimiter) .filter(isAbsolute).join(delimiter); diff --git a/tools/mock-ai/src/scenario/mod.rs b/tools/mock-ai/src/scenario/mod.rs index 78b1732c98b..a13bdbbc076 100644 --- a/tools/mock-ai/src/scenario/mod.rs +++ b/tools/mock-ai/src/scenario/mod.rs @@ -23,7 +23,6 @@ pub mod tools; use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; -use std::fmt::Write as _; use std::hash::{Hash, Hasher}; use std::path::PathBuf; use std::sync::atomic::{AtomicU64, Ordering}; @@ -788,7 +787,7 @@ impl ScenarioEngine { Ok(Self { spec, compiled, - run_scope: hex(run_id.as_ref()), + run_scope: compact_hex(run_id.as_ref()), run_id: run_id.as_ref().into(), sessions: Mutex::new(HashMap::new()), registrations: AtomicU64::new(0), @@ -819,7 +818,7 @@ impl ScenarioEngine { id_scope: format!( "{}_{}_{:x}", self.run_scope, - hex(session_id), + compact_hex(session_id), self.registrations.fetch_add(1, Ordering::Relaxed) ), logical_lane, @@ -1423,7 +1422,19 @@ fn result_failed(result: &Value) -> bool { fn code_results_from(result: &Value) -> Option> { match result { - Value::String(text) => serde_json::from_str(text).ok().map(Cow::Owned), + Value::String(text) => serde_json::from_str::>(text) + .ok() + .filter(|items| items.iter().all(|item| item.get("slot").is_some())) + .or_else(|| { + text.lines().rev().find_map(|line| { + serde_json::from_str::>(line.trim()) + .ok() + .filter(|items| { + !items.is_empty() && items.iter().all(|item| item.get("slot").is_some()) + }) + }) + }) + .map(Cow::Owned), Value::Array(items) if items.iter().all(|item| item.get("slot").is_some()) => { Some(Cow::Borrowed(items)) } @@ -1459,12 +1470,8 @@ fn tool_call(call: &IssuedCall, payload: CallPayload) -> ToolCallSpec { spec } -fn hex(id: &str) -> String { - let mut encoded = String::with_capacity(id.len() * 2); - for byte in id.bytes() { - write!(encoded, "{byte:02x}").expect("writing to String"); - } - encoded +fn compact_hex(id: &str) -> String { + format!("{:08x}", (digest(id) & 0xffff_ffff) as u32) } fn large_output_command(pattern: &str, bytes: usize, seed: u64) -> String { @@ -1492,7 +1499,12 @@ fn large_output_command(pattern: &str, bytes: usize, seed: u64) -> String { fn value_contains(value: &Value, marker: &str) -> bool { match value { - Value::String(text) => text.contains(marker), + Value::String(text) => { + text.contains(marker) + || serde_json::from_str::(text) + .ok() + .is_some_and(|parsed| value_contains(&parsed, marker)) + } Value::Array(values) => values.iter().any(|value| value_contains(value, marker)), Value::Object(values) => values.values().any(|value| value_contains(value, marker)), _ => false, diff --git a/tools/mock-ai/src/scenario/tools.rs b/tools/mock-ai/src/scenario/tools.rs index c57e51497b1..bef60dfbd00 100644 --- a/tools/mock-ai/src/scenario/tools.rs +++ b/tools/mock-ai/src/scenario/tools.rs @@ -653,7 +653,7 @@ enum Encoding { Edit(PathKey, EditKeys), Command(&'static str), Patch(Option<&'static str>), - Code { freeform: bool }, + Code { freeform: bool, use_patch: bool }, } #[derive(Clone, Copy, Debug)] @@ -687,8 +687,12 @@ impl Binding { workspace: &Path, actions: &[ToolAction<'_>], ) -> Result { - if let Encoding::Code { freeform } = self.encoding { - let code = code_mode_source(actions); + if let Encoding::Code { + freeform, + use_patch, + } = self.encoding + { + let code = code_mode_source(actions, use_patch)?; return Ok(if freeform { CallPayload::Freeform(code) } else { @@ -912,9 +916,15 @@ fn code_mode(tool: &ToolDeclaration) -> Option { { return None; } + let use_patch = tool.description.as_deref().is_some_and(|d| { + (d.contains("ApplyPatch(") || d.contains("apply_patch(")) && !d.contains("Edit(") + }); match tool.kind { ToolKind::Function if tool.has_property("code") && !tool.has_property("command") => { - Some(Encoding::Code { freeform: false }) + Some(Encoding::Code { + freeform: false, + use_patch, + }) } ToolKind::Freeform if (tool @@ -929,17 +939,23 @@ fn code_mode(tool: &ToolDeclaration) -> Option { grammar.contains("plain_source: SOURCE") && grammar.contains(r"\/\/ @exec:") }) => { - Some(Encoding::Code { freeform: true }) + Some(Encoding::Code { + freeform: true, + use_patch, + }) } _ => None, } } -fn code_mode_source(actions: &[ToolAction<'_>]) -> String { +fn code_mode_source(actions: &[ToolAction<'_>], use_patch: bool) -> Result { let mut code = String::from("text(JSON.stringify(await Promise.all([\n"); for (slot, action) in actions.iter().enumerate() { let (tool, input) = match *action { ToolAction::Read { path } => ("Read", json!({ "path": path })), + ToolAction::Write { .. } | ToolAction::Edit { .. } if use_patch => { + ("ApplyPatch", json!({ "patch": patch_text(*action)? })) + } ToolAction::Write { path, content } => { ("Write", json!({ "path": path, "content": content })) } @@ -958,7 +974,7 @@ fn code_mode_source(actions: &[ToolAction<'_>]) -> String { .expect("writing to String"); } code.push_str("])));"); - code + Ok(code) } fn patch_text(action: ToolAction<'_>) -> Result { From 78177a6f8a7e4772237693a46d14fb91bb9490c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CM4n5ter=E2=80=9D?= Date: Sat, 28 Nov 2026 15:48:10 +0800 Subject: [PATCH 3/4] feat(harness-bench): add extreme breaking-point stress suites, shared-daemon mode, and fair cross-protocol error/overflow handling --- tools/harness-bench/README.md | 37 +- tools/harness-bench/adapters.mjs | 502 +++++++++++++++++++-------- tools/harness-bench/bench.test.mjs | 139 ++++++++ tools/harness-bench/proc-monitor.mjs | 255 ++++++++++---- tools/harness-bench/report.mjs | 71 +++- tools/harness-bench/run.mjs | 342 ++++++++++++++---- tools/harness-bench/stress.mjs | 120 +++++++ tools/mock-ai/src/main.rs | 18 +- tools/mock-ai/src/routing.rs | 9 +- tools/mock-ai/src/scenario/mod.rs | 436 +++++++++++++++++++---- tools/mock-ai/src/schema_synth.rs | 91 +++-- tools/mock-ai/src/server.rs | 20 +- 12 files changed, 1654 insertions(+), 386 deletions(-) create mode 100644 tools/harness-bench/stress.mjs diff --git a/tools/harness-bench/README.md b/tools/harness-bench/README.md index 291e44f5e78..590acc5f541 100644 --- a/tools/harness-bench/README.md +++ b/tools/harness-bench/README.md @@ -24,11 +24,13 @@ Run coding agents against the same deterministic, loopback mock model and check ## Build and run ```sh -cargo build -p maka-mock-ai --bin maka-mock-ai +cargo build --release -p maka-mock-ai --bin maka-mock-ai node tools/harness-bench/run.mjs preflight node tools/harness-bench/run.mjs preflight --harnesses ref-agent,codex-http --json node tools/harness-bench/run.mjs run --scenario smoke-edit --harnesses ref-agent --lanes 4 --runs 2 node tools/harness-bench/run.mjs calibrate --lanes 16 +node tools/harness-bench/run.mjs stress --suite deep-grind --harnesses ref-agent --turns 300 --output-bytes 65536 +node tools/harness-bench/run.mjs stress --suite cliff-ramp --harnesses pi-durable-shared,opencode-serve --steps 4,8,16,32,64,128 node tools/harness-bench/run.mjs matrix --harnesses ref-agent,codex-http --scenarios mcp-smoke-edit node --test tools/harness-bench/bench.test.mjs ``` @@ -39,7 +41,7 @@ The runner searches `target/release` and then `target/debug` for `maka-mock-ai`. `--timeout-ms` sets a process deadline per segment and defaults to `120000`. `--sigkill-after-ms` kills the first client process group after the given delay. Add `--resume-after-kill` to launch a second client against the same workspace, isolated config and mock session. The reference agent checkpoints completed tool batches and compaction state in this mode. Other adapters relaunch their configured CLI with its existing state and may fail to recover. A kill during a tool write can leave incomplete work. A kill during a stream can produce an `abandoned_stream` watchdog violation and a nonzero exit even when the restarted client finishes the task. -`calibrate` uses `ref-agent` with `instant`, one batch and 16 lanes by default. Compare median mock union time, median outside-mock time, verified lanes per second and the before/after `/admin/metrics` snapshots across lane counts. Union time measures the overlap-adjusted mock service intervals during a session. Outside-mock time covers the rest of the registration-to-finalization window, including runner and client overhead. Process wall time uses the measured CLI segments. A warm daemon lives outside the CLI process tree. The calibration measures the local benchmark workload at the chosen lane count. +`calibrate` uses `ref-agent` with `instant`, one batch and 16 lanes by default. Compare median mock union time, median outside-mock time, verified lanes per second and the before/after `/admin/metrics` snapshots across lane counts. Union time measures the overlap-adjusted mock service intervals during a session. Outside-mock time covers the rest of the registration-to-finalization window, including runner and client overhead. Process wall time uses the measured CLI segments. Warm and shared daemons contribute to the concurrent batch RSS. The calibration measures the local benchmark workload at the chosen lane count. `matrix` runs all five built-ins by default. Use `--scenarios a,b` to select scenarios. It writes `matrix-report.md` with links to each exercised scenario. Unsupported tracks show `N/A`. An adapter that supports the track but fails to launch or verify is a failed result. @@ -53,6 +55,20 @@ The runner searches `target/release` and then `target/debug` for `maka-mock-ai`. | `chaos-recovery` | Native | Recover from HTTP 429, HTTP 503 and a mid-stream disconnect, and report errors for malformed and unknown calls. | | `mcp-smoke-edit` | Shared MCP | Perform the smoke edit over the benchmark stdio MCP tools and reconcile their audit with the workspace and mock receipts. | +## Stress suites + +Generated scenarios are deterministic. The exact input is written as `/scenario.json`. Use `--suite all` to run all five suites. `--lanes`, `--turns` and `--output-bytes` override suite defaults where applicable. Stress accepts `--latency-profile instant|frontier` and uses `instant` by default. + +| Suite | Default | Workload and controls | +| --- | --- | --- | +| `deep-grind` | 60 turns, 1 lane | Read, write, edit and verify a file, then emit 16 KiB of real shell output every fifth round. Use 150 or 300 turns and 64 KiB per output to grow the retained history into multiple MiB. | +| `burst-flood` | 6 turns, 1 lane | 16 independent tool calls per turn, including reads, writes, simultaneous `sleep 0.1` probes and a 256 KiB UTF-8 output. Set `--parallel 8\|16\|32` and `--output-bytes` up to 1048576. Compare the tool-round interval with the serialized sleep budget. | +| `cliff-ramp` | 12 turns per lane | Run each harness at `--steps 4,8,16,32,64,128`. Each harness advances independently after a fully verified stage. Its first failed stage and highest passing stage are in `leaderboard.md` and `leaderboard.json`. A failed stage yields a nonzero exit after the leaderboard is written. | +| `chaos-storm` | 10 turns, 8 lanes | Scheduled 429, 503 and a disconnect after the first complete tool call. The scenario also tests invalid arguments and an undeclared tool. Native wire poisoning is enabled. HTTP clients receive `Retry-After-Ms: 80` through a loopback proxy. The WebSocket adapter receives the mock's protocol-native 429. | +| `firehose` | 25 turns, 8 lanes | Write multibyte content from streamed tool arguments and reassemble a multibyte final answer. Always uses instant pacing. Tune chunk size with `--chunk-chars` (16 by default) and add `--wire-poison` to exercise framing boundaries. | + +Use a freshly built mock with `--chunk-chars` and `--wire-poison` support. Wire poisoning applies the mock's native SSE or WebSocket framing perturbations. An instant profile still includes codec, transport and scheduling time. + ## Adapters | Adapter | Model protocol | Tracks | @@ -60,13 +76,17 @@ The runner searches `target/release` and then `target/debug` for `maka-mock-ai`. | `ref-agent` | Chat Completions | Native, Shared MCP | | `maka-direct` | Chat Completions | Native, Shared MCP | | `maka-codemode` | Chat Completions | Native | +| `maka-host-direct` | Chat Completions | Native, Shared MCP | +| `maka-host-codemode` | Chat Completions | Native | | `claude` | Anthropic Messages | Native, Shared MCP | | `codex-ws` | Responses WebSocket | Native, Shared MCP | | `codex-http` | Responses HTTP | Native, Shared MCP | | `opencode-cold` | Chat Completions | Native, Shared MCP | | `opencode-attach` | Chat Completions | Native, Shared MCP | +| `opencode-serve` | Chat Completions | Native | | `pi` | Chat Completions | Native | | `pi-durable` | Chat Completions | Native | +| `pi-durable-shared` | Chat Completions | Native | | `dim` | Chat Completions | Native, Shared MCP | | `dsh` | Chat Completions | Native, Shared MCP | | `zcode` | Chat Completions | Native, Shared MCP | @@ -74,12 +94,21 @@ The runner searches `target/release` and then `target/debug` for `maka-mock-ai`. | `kimi-responses` | Responses HTTP | Native, Shared MCP | | `kimi-anthropic` | Anthropic Messages | Native, Shared MCP | -Use `preflight` for installation hints and environment requirements. For either Maka adapter, use a disposable OS account or container and point `HARNESS_BENCH_MAKA_ACCOUNT_HOME` at that account's home. `MAKA_BENCH_BINARY` can select the Maka binary. +Use `preflight` for installation hints and environment requirements. For the Maka adapters, use a disposable OS account or container and point `HARNESS_BENCH_MAKA_ACCOUNT_HOME` at that account's home. `MAKA_BENCH_BINARY` can select the Maka binary. ## Isolation and artifacts -Each run starts a strict scenario server on `127.0.0.1:0`. Each lane has a unique scoped model endpoint and test credential, its own fixture workspace and private HOME, XDG, config, cache and temp directories. The adapter supplies these settings to the client. Native tools operate with the OS permissions of the benchmark account. Use a disposable account or container when you need OS-level file or network isolation. The Shared MCP server restricts benchmark tools to each lane's workspace and structured commands. Warm Maka and OpenCode attach adapters start a daemon per lane so their workspaces and session routes stay independent. +Each run starts a strict scenario server on `127.0.0.1:0`. Each lane has a unique scoped model endpoint and test credential, its own fixture workspace and private HOME, XDG, config, cache and temp directories. The adapter supplies these settings to the client. Native tools operate with the OS permissions of the benchmark account. Use a disposable account or container when you need OS-level file or network isolation. The Shared MCP server restricts benchmark tools to each lane's workspace and structured commands. Maka starts one Host per candidate batch with one connection per lane. Its ACP clients select the lane's connection using `session/set_config_option` and attach the stdio MCP server with `session/new`. Shared MCP runs issue a real `tool_search` discovery call through the loopback adapter before the canonical calls. The discovery call belongs to the adapter and stays outside the mock's canonical receipts. Both `maka-host-*` IDs use the same shared topology as their `maka-*` counterparts. + +`opencode-serve` and native `opencode-attach` use one OpenCode v2 server, with `lane-N/gpt-4.1` providers and one `run --server` client per lane. Shared MCP `opencode-attach` retains a server per lane to keep the server-owned MCP workspace and audit distinct. `pi-durable-shared` opens one Node process, Harness and SQLite database and runs ownerless conversations concurrently. Each conversation has its own pinned provider and workspace. `pi-durable` keeps one process and database per lane. + +A single process snapshot per batch samples descendant and daemon RSS and process count every 100 ms. Shared processes are counted once in the batch total. `--max-cluster-rss-gib` defaults to 32 GiB. The sampler aborts the batch with `cluster_rss_limit_exceeded` when it observes a sample above the threshold. Timeouts and SIGINT/SIGTERM also stop the process groups and tracked descendants. The cap is sampled, so short-lived spikes between samples can exceed it. The runner and mock model run outside the candidate's RSS accounting. Use `--output` with a new or empty directory. With no flag, the runner creates a temp directory and prints its path. The output retains the fixtures and final files, per-segment process samples and log tails, mock session exports, and MCP audit logs where applicable. `manifest.json` records candidate order and options. `results.json` contains lane outcomes and mock metrics. `report.md` summarizes comparisons and failures. Timing and RSS/CPU samples cover each CLI and its live descendants. The monitor keeps up to 256 KiB each of stdout and stderr per segment and records truncation in `lane.json`. A successful lane has a clean CLI result, independent workspace proof and a finalized mock session with a verified final response. The runner exports telemetry before acknowledging its cursor and deleting the session. A failed lane or run error makes the command exit nonzero after writing diagnostics. + + +Each batch in `results.json` reports `peakClusterRssMib`, `peakClusterProcessCount` and `throughputTurnsPerSec`. Throughput divides verified tool-round receipts by the wall-clock window from the first client start to the last exit, including any restart gaps. Daemon setup, evidence export and cleanup happen outside that window. `diskStateMib` reports peak logical bytes under each isolated state directory and the batch's `shared-state` directory. Workspace files and runner logs have separate artifacts. + +Each lane's `turnLatencyCurve` measures time between successive canonical main requests from `mock-session.json`. It includes streaming, tools, persistence and retry delay. The ratio compares the last five intervals with the first five and is available after ten intervals. diff --git a/tools/harness-bench/adapters.mjs b/tools/harness-bench/adapters.mjs index 9cf101cce2d..22f98994036 100644 --- a/tools/harness-bench/adapters.mjs +++ b/tools/harness-bench/adapters.mjs @@ -18,6 +18,8 @@ */ import { execFile, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { createServer, request } from 'node:http'; import { randomBytes } from 'node:crypto'; import { text as consumeText } from 'node:stream/consumers'; import { constants } from 'node:fs'; @@ -28,6 +30,7 @@ import { createInterface } from 'node:readline'; import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; +import { killProcessGroup, runMonitoredProcess } from './proc-monitor.mjs'; import { parseBenchmarkCommand, replaceUnique, resolveWorkspaceFile } from './fixtures.mjs'; const exec = promisify(execFile); @@ -59,14 +62,15 @@ function jsonFile(path, value) { return privateFile(path, JSON.stringify(value, null, 2) + '\n'); } -async function isolatedEnv(directory, source) { +async function isolatedEnv(directory, source, tempDirs) { const dirs = Object.fromEntries([ ['HOME', 'home'], ['XDG_CONFIG_HOME', 'config'], ['XDG_DATA_HOME', 'data'], ['XDG_CACHE_HOME', 'cache'], ['XDG_STATE_HOME', 'state'], ['XDG_RUNTIME_DIR', 'runtime'], ['TMPDIR', 'tmp'], ['APPDATA', 'app-data'], ['LOCALAPPDATA', 'local-app-data'], ].map(([name, leaf]) => [name, join(directory, leaf)])); - if (process.platform === 'darwin' && dirs.TMPDIR.length > 48) { - dirs.TMPDIR = join('/tmp', 'hb-' + randomBytes(4).toString('hex')); + if (tempDirs && process.platform === 'darwin' && dirs.TMPDIR.length > 48) { + dirs.TMPDIR = await mkdtemp('/tmp/hb-'); + tempDirs.add(dirs.TMPDIR); } await Promise.all(Object.values(dirs).map(dir => mkdir(dir, { recursive: true, mode: 0o700 }))); const path = (source.PATH ?? source.Path ?? '/usr/bin:/bin').split(delimiter) @@ -136,9 +140,9 @@ function mcpServer({ mcpServerCmd, mcpAuditPath, workspace, resumeAfterKill }) { } function adapter({ id, harness = id, binary = harness, protocol = chat, supportedTracks = native, - defaultModel = 'gpt-4.1', installHint, versionArgs = ['--version'], prepare, start, locate, version }) { + defaultModel = 'gpt-4.1', installHint, versionArgs = ['--version'], prepare, start, shared, batch, locate, version }) { const commandPath = locate ?? ((env, repoRoot) => findBinary(binary, env, repoRoot)); - const launchMode = start ? 'warm-daemon' : 'cold'; + const launchMode = shared || batch ? 'shared-daemon' : start ? 'warm-daemon' : 'cold'; const requireCommand = async (env, repoRoot) => { const command = await commandPath(env, repoRoot); if (!command) throw new Error(`${id}: could not locate ${binary}. ${installHint}`); @@ -160,12 +164,12 @@ function adapter({ id, harness = id, binary = harness, protocol = chat, supporte if (harness === 'maka' && source.HARNESS_BENCH_MAKA_ACCOUNT_HOME !== userInfo().homedir) { throw new Error(makaIsolation); } - const env = await isolatedEnv(isolatedDir, source); + const env = await isolatedEnv(isolatedDir, source, options.tempDirs); const mcp = track === 'sharedMcp' ? mcpServer({ ...options, workspace }) : undefined; return { ...options, model, base, v1: base + '/v1', isolatedDir, workspace, repoRoot, source, command, env, mcp }; } return Object.freeze({ - id, harness, protocol, launchMode, supportedTracks, defaultModel, + id, harness, protocol, launchMode, supportedTracks, defaultModel, shared: shared ?? (batch ? supportedTracks : []), async probe({ env = process.env, repoRoot = defaultRepoRoot } = {}) { const result = { id, available: false, installHint }; let scratch; @@ -188,111 +192,282 @@ function adapter({ id, harness = id, binary = harness, protocol = chat, supporte if (scratch) await rm(scratch, { recursive: true, force: true }); } }, - async prepareInvocation(options) { + ...(prepare ? { async prepareInvocation(options) { const ctx = await context(options); return { command: ctx.command, cwd: ctx.workspace, env: ctx.env, ...await prepare(ctx) }; - }, + } } : {}), ...(start ? { - async startDaemon(options) { - return start(await context(options)); + async startDaemon(options, lanes) { + return start(await context(options), lanes?.map(lane => ({ + ...lane, model: lane.model ?? defaultModel, + v1: scopedUrl(lane.scopedOrigin, lane.runId, lane.sessionId) + '/v1', + }))); }, stopDaemon, } : {}), + ...(batch ? { async prepareBatch(options, lanes) { + const ctx = await context(options); + return { command: ctx.command, cwd: ctx.workspace, env: ctx.env, ...await batch(ctx, lanes) }; + } } : {}), }); } -function startChild(command, args, { env, workspace }, ready) { +async function startChild(command, args, { env, workspace, monitor, abortBatch }, ready) { + monitor?.signal.throwIfAborted(); const child = spawn(command, args, { - env, cwd: workspace, detached: process.platform !== 'win32', - stdio: ['ignore', 'pipe', 'pipe'], + env, cwd: workspace, detached: true, stdio: ['ignore', 'pipe', 'pipe'], }); + const observation = monitor?.watch(child.pid); let stderr = ''; child.stderr.setEncoding('utf8').on('data', chunk => { stderr = (stderr + chunk).slice(-8192); }); - const state = { child, exited: new Promise(resolveExit => { - child.once('error', error => resolveExit({ error })); - child.once('exit', (code, signal) => resolveExit({ code, signal })); - }) }; + let spawnError; + child.once('error', error => { spawnError = error; }); + child.once('exit', () => { + if (monitor) monitor.release(observation); + else killProcessGroup(child.pid); + }); + const exited = new Promise(resolve => child.once('close', (code, signal) => resolve({ code, signal }))); + const state = { child, exited, monitor, observation }; const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); - const timeout = AbortSignal.timeout(30_000); - const started = new Promise((resolveReady, reject) => { - timeout.addEventListener('abort', () => reject(new Error('Daemon readiness timed out')), { once: true }); - lines.on('line', line => { - const value = ready(line); - if (value) resolveReady(value); + const signal = monitor?.signal; + let timer; + let abort; + try { + const started = new Promise((resolve, reject) => { + abort = () => reject(signal.reason); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + timer = setTimeout(() => { + reject(new Error('Daemon readiness timed out: ' + stderr)); + abortBatch?.(); + }, 30_000); + lines.on('line', line => { + const value = ready(line); + if (value) resolve(value); + }); }); - }); - return Promise.race([started, state.exited.then(({ error, code, signal }) => { - throw error ?? new Error(`Daemon exited before ready (${signal ?? code}): ${stderr}`); - })]).then(value => ({ ...state, value }), async error => { + const value = await Promise.race([started, exited.then(({ code, signal }) => { + throw spawnError ?? new Error(`Daemon exited before ready (${signal ?? code}): ${stderr}`); + })]); + return { ...state, value }; + } catch (error) { await stopDaemon(state); throw error; - }); + } finally { + clearTimeout(timer); + signal?.removeEventListener('abort', abort); + } } -async function stopDaemon({ child, exited }) { - if (child.pid && child.exitCode === null && child.signalCode === null) { - const target = process.platform === 'win32' ? child.pid : -child.pid; - const sending = signal => { - try { - process.kill(target, signal); - } catch (error) { - if (error.code !== 'ESRCH') throw error; - } - }; - sending('SIGTERM'); +async function stopDaemon({ child, exited, monitor, observation }) { + if (child.pid && !observation?.killed && child.exitCode === null && child.signalCode === null) { + killProcessGroup(child.pid, 'SIGTERM'); if (!await Promise.race([exited.then(() => true), delay(3000, false, { ref: false })])) { - sending('SIGKILL'); + if (monitor) monitor.terminate(observation); + else killProcessGroup(child.pid); } } await exited; } async function runSetup(ctx, args, stdinText) { - if (stdinText === undefined) { - await exec(ctx.command, args, { env: ctx.env, cwd: ctx.workspace, timeout: 30_000 }); - return; + const result = await runMonitoredProcess({ + command: ctx.command, args, env: ctx.env, cwd: ctx.workspace, stdinText, + timeoutMs: 30_000, monitor: ctx.monitor, onTimeout: ctx.abortBatch, + }); + if (result.code !== 0 || result.termination || result.stdinError) { + throw new Error(`Setup ${args.slice(0, 2).join(' ')} failed (${result.termination ?? result.signal ?? result.code}): ${result.stderr}`); } - await new Promise((resolveRun, reject) => { - const child = execFile(ctx.command, args, { - env: ctx.env, cwd: ctx.workspace, timeout: 30_000, - }, error => error ? reject(error) : resolveRun()); - child.stdin.on('error', reject); - child.stdin.end(stdinText); +} + +function mcpDiscovery(body, path) { + const callId = 'bench-discovery-' + path.split('/')[3]; + const tools = body.tools ?? []; + const ready = tools.some(tool => tool.function?.name.startsWith('mcp__bench__')); + const isDiscoveryCall = call => call.id === callId && call.function?.name === 'tool_search'; + const hasReceipt = body.messages.some(message => message.role === 'tool' && message.tool_call_id === callId); + if (ready) { + // This adapter-owned call never entered the canonical scenario or its receipt journal. + body.messages = body.messages.filter(message => + !(message.role === 'tool' && message.tool_call_id === callId) + && !(message.role === 'assistant' && message.tool_calls?.length === 1 && isDiscoveryCall(message.tool_calls[0]))); + return { forwarded: JSON.stringify(body) }; + } + if (hasReceipt || !tools.some(tool => tool.function?.name === 'tool_search')) { + throw new Error('Maka did not expose the benchmark MCP tools after discovery'); + } + const call = { + id: callId, type: 'function', + function: { name: 'tool_search', arguments: JSON.stringify({ query: 'bench', limit: 20 }) }, + }; + const response = { id: 'resp_' + callId, model: body.model, created: 0 }; + return body.stream ? { + contentType: 'text/event-stream', + reply: [ + { delta: { role: 'assistant', tool_calls: [{ index: 0, ...call }] }, finish_reason: null }, + { delta: {}, finish_reason: 'tool_calls' }, + ].map(choice => 'data: ' + JSON.stringify({ + ...response, object: 'chat.completion.chunk', choices: [{ index: 0, ...choice }], + }) + '\n\n').join('') + 'data: [DONE]\n\n', + } : { + contentType: 'application/json', + reply: JSON.stringify({ ...response, object: 'chat.completion', + choices: [{ index: 0, message: { role: 'assistant', tool_calls: [call] }, finish_reason: 'tool_calls' }], + }), + }; +} + +export async function startProviderProxy(origin, { discoverMcp, retryAfterMs } = {}) { + const upstreamUrl = new URL(origin); + const server = createServer(async (incoming, outgoing) => { + if (!incoming.url.startsWith('/s/')) { + outgoing.writeHead(404).end(); + return; + } + const headers = { ...incoming.headers, host: upstreamUrl.host }; + let forwarded; + if (discoverMcp && incoming.method === 'POST' && incoming.url.endsWith('/chat/completions')) { + try { + const result = mcpDiscovery(JSON.parse(await consumeText(incoming)), incoming.url); + if (result.reply) { + outgoing.writeHead(200, { 'content-type': result.contentType }).end(result.reply); + return; + } + forwarded = result.forwarded; + delete headers['transfer-encoding']; + headers['content-length'] = Buffer.byteLength(forwarded); + } catch (error) { + outgoing.writeHead(422, { 'content-type': 'application/json' }).end(JSON.stringify({ + error: { message: error.message }, + })); + return; + } + } + const upstream = request(upstreamUrl, { path: incoming.url, method: incoming.method, headers }, reply => { + const replyHeaders = { ...reply.headers }; + if (reply.statusCode === 429 && retryAfterMs !== undefined) { + replyHeaders['retry-after-ms'] = String(retryAfterMs); + replyHeaders['retry-after'] = String(Math.ceil(retryAfterMs / 1000)); + } + outgoing.writeHead(reply.statusCode, replyHeaders); + outgoing.flushHeaders(); + reply.on('error', error => outgoing.destroy(error)); + reply.pipe(outgoing); + }); + outgoing.once('close', () => upstream.destroy()); + upstream.on('error', error => outgoing.destroy(error)); + incoming.on('error', error => upstream.destroy(error)); + if (forwarded !== undefined) upstream.end(forwarded); + else incoming.pipe(upstream); }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + return { + origin: 'http://127.0.0.1:' + server.address().port, + async stop() { + const closed = once(server, 'close'); + server.close(); + server.closeAllConnections(); + await closed; + }, + }; } function makaAdapter(id, codeMode) { - const rootPath = ctx => join(ctx.isolatedDir, 'maka-root'); + const tracks = codeMode ? native : both; return adapter({ - id, harness: 'maka', supportedTracks: codeMode ? native : both, + id, harness: 'maka', supportedTracks: tracks, shared: tracks, installHint: 'cargo build --release -p maka-cli', - async start(ctx) { - const root = rootPath(ctx); - if (ctx.mcp) await jsonFile(join(ctx.env.HOME, '.maka/mcp.json'), { - mcpServers: { bench: { ...ctx.mcp, cwd: ctx.workspace } }, - }); + async start(ctx, lanes = [ctx]) { + const root = join(ctx.isolatedDir, 'maka-root'); + const connections = lanes.map(lane => ({ + slug: lane.logicalLane, name: lane.logicalLane, provider: 'openai-compatible', + configuration: { baseUrl: lane.v1 }, apiKey: lane.apiKey, enabledModelIds: [lane.model], + modelOverrides: { + [lane.model]: { codeMode, apiProtocol: chat, ...(codeMode ? { codeModeLanguage: 'javascript' } : {}) }, + }, + })); await runSetup(ctx, ['host', 'init', '--root', root, '--settings-stdin'], JSON.stringify({ - connections: [{ - slug: 'benchmark', provider: 'openai-compatible', - configuration: { baseUrl: ctx.v1 }, apiKey: ctx.apiKey, enabledModelIds: [ctx.model], - modelOverrides: { - [ctx.model]: { codeMode, apiProtocol: chat, ...(codeMode ? { codeModeLanguage: 'javascript' } : {}) }, - }, - }], - defaultTarget: { slug: 'benchmark', modelId: ctx.model }, - projectDirectoryRoots: [{ label: 'Benchmark workspace', path: ctx.workspace }], + connections, + defaultTarget: { slug: connections[0].slug, modelId: lanes[0].model }, + chatDefaults: { sandboxMode: 'danger-full-access' }, + projectDirectoryRoots: lanes.map(lane => ({ label: lane.logicalLane, path: lane.workspace })), })); - return startChild(ctx.command, ['host', 'serve', '--root', root], ctx, + const host = await startChild(ctx.command, ['host', 'serve', '--root', root], ctx, line => line.startsWith('{"kind":"ready",') && root); + return { ...host, tempDir: ctx.env.TMPDIR }; }, prepare(ctx) { - const root = rootPath(ctx); - if (ctx.daemonState?.value !== root) throw new Error(`${id} requires its isolated Host`); - return { args: ['run', '--root', root, '--workspace', ctx.workspace], stdinText: ctx.prompt }; + const host = ctx.daemonState; + if (!host) throw new Error(`${id} requires a shared Host`); + return { + command: process.execPath, args: [script, '--maka-acp'], + env: { ...ctx.env, TMPDIR: host.tempDir }, + stdinText: JSON.stringify({ + command: ctx.command, root: host.value, lane: ctx.logicalLane, prompt: ctx.prompt, mcp: ctx.mcp, + }), + }; }, }); } +async function runMakaAcp() { + const { command, root, lane, prompt, mcp } = JSON.parse(await consumeText(process.stdin)); + const child = spawn(command, ['acp', '--root', root], { stdio: ['pipe', 'pipe', 'inherit'] }); + let failure; + child.once('error', error => { failure = error; }); + child.stdin.on('error', error => { failure ??= error; }); + const closed = new Promise(resolve => child.once('close', (code, signal) => resolve({ code, signal }))); + const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); + const messages = lines[Symbol.asyncIterator](); + let id = 0; + let answer = ''; + async function rpc(method, params) { + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params }) + '\n'); + for (;;) { + const { done, value } = await messages.next(); + if (done) throw failure ?? new Error('Maka ACP closed while awaiting ' + method); + const message = JSON.parse(value); + if (message.id === id && !message.method) { + if (message.error) throw new Error(method + ': ' + JSON.stringify(message.error)); + return message.result; + } + if (message.method === 'session/update') { + const { update } = message.params; + if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') { + answer += update.content.text; + } + } else if (message.method && message.id !== undefined) { + child.stdin.write(JSON.stringify({ + jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Unsupported benchmark ACP client method' }, + }) + '\n'); + } + } + } + try { + await rpc('initialize', { protocolVersion: 1, clientCapabilities: {} }); + const { sessionId, configOptions } = await rpc('session/new', { + cwd: process.cwd(), mcpServers: mcp ? [{ name: 'bench', ...mcp, env: [] }] : [], + }); + const selected = configOptions.find(option => option.id === 'model')?.options + .find(option => option.name.endsWith(' (' + lane + ')')); + if (!selected) throw new Error('Maka ACP did not advertise the provider for ' + lane); + await rpc('session/set_config_option', { sessionId, configId: 'model', type: 'id', value: selected.value }); + const result = await rpc('session/prompt', { sessionId, prompt: [{ type: 'text', text: prompt }] }); + if (result.stopReason !== 'end_turn' || !answer.trim()) { + throw new Error('Maka ACP prompt did not return an answer: ' + JSON.stringify(result)); + } + process.stdout.write(answer + '\n'); + } finally { + child.stdin.end(); + lines.close(); + child.stdout.resume(); + const { code, signal } = await closed; + if (failure) throw failure; + if (code !== 0) throw new Error('Maka ACP exited: ' + (signal ?? code)); + } +} + const claude = adapter({ id: 'claude', protocol: anthropic, supportedTracks: both, installHint: 'Install Claude Code (claude on PATH).', @@ -343,52 +518,55 @@ function codexAdapter(ws) { }); } -async function configureOpencode(ctx) { +async function configureOpencode(ctx, lanes) { const config = join(ctx.isolatedDir, 'opencode.json'); Object.assign(ctx.env, { OPENCODE_CONFIG: config, OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_MODELS_FETCH: '1', - OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENAI_API_KEY: ctx.apiKey, + OPENCODE_DISABLE_PROJECT_CONFIG: '1', }); + const providers = lanes ?? [{ ...ctx, logicalLane: 'mock' }]; await jsonFile(config, { - model: `mock/${ctx.model}`, - providers: { mock: { - name: 'Benchmark mock', package: '@opencode/ai/providers/openai-compatible', - settings: { baseURL: ctx.v1, apiKey: '{env:OPENAI_API_KEY}' }, - models: { [ctx.model]: { name: ctx.model } }, - } }, + model: `${providers[0].logicalLane}/${providers[0].model}`, + providers: Object.fromEntries(providers.map(lane => [lane.logicalLane, { + name: 'Benchmark ' + lane.logicalLane, package: '@opencode/ai/providers/openai-compatible', + settings: { baseURL: lane.v1, apiKey: lane.apiKey }, + models: { [lane.model]: { name: lane.model } }, + }])), permissions: [{ action: '*', resource: '*', effect: 'allow' }], - ...(ctx.mcp ? { mcp: { servers: { bench: { + ...(!lanes && ctx.mcp ? { mcp: { servers: { bench: { type: 'local', codemode: false, command: [ctx.mcp.command, ...ctx.mcp.args], } } } } : {}), }); } -function opencodeAdapter(attach) { +function opencodeAdapter(id, tracks) { + const attach = id !== 'opencode-cold'; return adapter({ - id: attach ? 'opencode-attach' : 'opencode-cold', harness: 'opencode', supportedTracks: both, + id, harness: 'opencode', supportedTracks: tracks, installHint: 'Install OpenCode v2 (opencode on PATH).', ...(attach ? { - async start(ctx) { - await configureOpencode(ctx); + shared: native, + async start(ctx, lanes) { + await configureOpencode(ctx, lanes); const password = randomBytes(24).toString('hex'); ctx.env.OPENCODE_PASSWORD = password; const state = await startChild(ctx.command, ['serve', '--hostname', '127.0.0.1', '--port', '0'], ctx, line => /https?:\/\/127\.0\.0\.1:[1-9][0-9]*/.exec(line)?.[0]); - return { ...state, isolatedDir: ctx.isolatedDir, password }; + return { ...state, shared: Boolean(lanes), password }; }, } : {}), async prepare(ctx) { let server = ['--standalone']; + let provider = 'mock'; if (attach) { - if (ctx.daemonState?.isolatedDir !== ctx.isolatedDir) { - throw new Error('opencode-attach requires its isolated daemon'); - } + if (!ctx.daemonState) throw new Error(id + ' requires its daemon'); ctx.env.OPENCODE_PASSWORD = ctx.daemonState.password; server = ['--server', ctx.daemonState.value]; + if (ctx.daemonState.shared) provider = ctx.logicalLane; } else { await configureOpencode(ctx); } - return { args: ['run', ...server, '--model', `mock/${ctx.model}`, '--format', 'json', '--', ctx.prompt] }; + return { args: ['run', ...server, '--model', `${provider}/${ctx.model}`, '--format', 'json', '--', ctx.prompt] }; }, }); } @@ -432,22 +610,17 @@ async function durableEntries(env, repoRoot, invocation) { return JSON.parse(stdout); } -const piDurable = adapter({ - id: 'pi-durable', locate: () => process.execPath, - installHint: `Install ${durablePackages.join(' ')} in a directory and set HARNESS_BENCH_PI_DURABLE_DIR to it.`, - async version(env, repoRoot, invocation) { - const entries = await durableEntries(env, repoRoot, invocation); - const path = join(dirname(fileURLToPath(entries.Harness)), '../package.json'); - return JSON.parse(await readFile(path, 'utf8')).version; - }, - async prepare(ctx) { - const entries = await durableEntries(ctx.source, ctx.repoRoot, { - env: ctx.env, timeout: 8_000, - }); - const path = join(ctx.isolatedDir, 'pi-durable-driver.mjs'); - ctx.env.OPENAI_API_KEY = ctx.apiKey; - const { model, v1, sessionId, workspace, isolatedDir } = ctx; - await privateFile(path, `import { readFileSync } from 'node:fs'; +async function prepareDurable(ctx, batchLanes) { + const lanes = batchLanes ?? [ctx]; + const entries = await durableEntries(ctx.source, ctx.repoRoot, { env: ctx.env, timeout: 8_000 }); + const path = join(ctx.isolatedDir, 'pi-durable-driver.mjs'); + const configs = lanes.map(({ model, sessionId, workspace, logicalLane, v1, runId, scopedOrigin, apiKey }, index) => { + const keyEnv = 'HARNESS_BENCH_PI_KEY_' + index; + ctx.env[keyEnv] = apiKey; + return { model: model ?? ctx.model, sessionId, workspace, logicalLane, keyEnv, + baseUrl: v1 ?? scopedUrl(scopedOrigin, runId, sessionId) + '/v1' }; + }); + await privateFile(path, `import { readFileSync } from 'node:fs'; import { Harness, AssistantEntry, createRegistry } from ${toml(entries.Harness)}; import { openNodeSqliteStorage } from ${toml(entries.sqlite)}; import { createCodingTools } from ${toml(entries.tools)}; @@ -456,47 +629,75 @@ import { createModels, createProvider, envApiKeyAuth } from ${toml(entries.ai)}; import { openAICompletionsApi } from ${toml(entries.completions)}; import { BACKGROUND_CONTEXT as context } from ${toml(entries.context)}; -const modelId = ${toml(model)}; -const baseUrl = ${toml(v1)}; +const lanes = ${toml(configs)}; +const emit = ${Boolean(batchLanes)} + ? row => console.log(JSON.stringify(row)) + : row => { + if (row.error) throw new Error(row.error); + console.log(row.answer); + }; const models = createModels(); -models.setProvider(createProvider({ - id: 'mock', name: 'Benchmark mock', baseUrl, - auth: { apiKey: envApiKeyAuth('Benchmark mock', ['OPENAI_API_KEY']) }, - api: openAICompletionsApi(), - models: [{ - id: modelId, name: modelId, api: 'openai-completions', provider: 'mock', baseUrl, - reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, - contextWindow: 128000, maxTokens: 8192, - }], -})); +for (const { logicalLane: id, model, baseUrl, keyEnv } of lanes) { + models.setProvider(createProvider({ + id, name: id, baseUrl, + auth: { apiKey: envApiKeyAuth(id, [keyEnv]) }, + api: openAICompletionsApi(), + models: [{ + id: model, name: model, api: 'openai-completions', provider: id, baseUrl, + reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + contextWindow: 128000, maxTokens: 8192, + }], + })); +} const registry = createRegistry(); registry.install(createCodingTools()); -const cwd = ${toml(workspace)}; -const harness = await Harness.open(await openNodeSqliteStorage(${toml(join(isolatedDir, 'pi-durable.sqlite'))}), { - models, registry, env: () => new NodeExecutionEnv({ cwd }), +const storage = await openNodeSqliteStorage(${toml(join(ctx.isolatedDir, 'pi-durable.sqlite'))}); +const harness = await Harness.open(storage, { models, registry, + env: ({ cwd }) => new NodeExecutionEnv({ cwd }), }, context); try { - const root = await harness.root(context, { agent: { model: { provider: 'mock', modelId }, cwd } }); - const submission = await root.submit({ - type: 'input', content: readFileSync(0, 'utf8'), requestId: ${toml(sessionId)}, - }, context); + const prompt = readFileSync(0, 'utf8'); harness.resume(); - const settled = await submission.wait(context); - if (settled.status !== 'done' || settled.type !== 'input') { - throw new Error('pi-durable did not produce an answer: ' + JSON.stringify(settled)); - } - const answer = await root.commit(tx => tx.entry(AssistantEntry, settled.answer), context); - const text = answer?.model?.flatMap(message => message.content ?? []) - .filter(block => block.type === 'text').map(block => block.text).join(''); - if (!text) throw new Error('pi-durable returned an empty answer'); - console.log(text); + await Promise.all(lanes.map(async ({ logicalLane, model, sessionId, workspace }) => { + const startNs = process.hrtime.bigint(); + let result; + try { + const options = { agent: { model: { provider: logicalLane, modelId: model }, cwd: workspace } }; + const root = await harness.createConversation({ ...options, ownership: { kind: 'ownerless' } }, context); + const submission = await root.submit({ type: 'input', content: prompt, requestId: sessionId }, context); + const settled = await submission.wait(context); + if (settled.status !== 'done' || settled.type !== 'input') { + throw new Error('pi-durable did not produce an answer: ' + JSON.stringify(settled)); + } + const answer = await root.commit(tx => tx.entry(AssistantEntry, settled.answer), context); + const text = answer?.model?.flatMap(message => message.content ?? []) + .filter(block => block.type === 'text').map(block => block.text).join(''); + if (!text) throw new Error('pi-durable returned an empty answer'); + result = { answer: text }; + } catch (error) { + result = { error: error.message }; + } + emit({ logicalLane, ...result, wallMs: Number(process.hrtime.bigint() - startNs) / 1e6 }); + })); } finally { await harness.close(context); } `); - return { args: [path], stdinText: ctx.prompt }; - }, -}); + return { args: [path], stdinText: ctx.prompt }; +} + +function piDurableAdapter(shared) { + return adapter({ + id: shared ? 'pi-durable-shared' : 'pi-durable', locate: () => process.execPath, + installHint: `Install ${durablePackages.join(' ')} in a directory and set HARNESS_BENCH_PI_DURABLE_DIR to it.`, + async version(env, repoRoot, invocation) { + const entries = await durableEntries(env, repoRoot, invocation); + const path = join(dirname(fileURLToPath(entries.Harness)), '../package.json'); + return JSON.parse(await readFile(path, 'utf8')).version; + }, + ...(shared ? { batch: prepareDurable } : { prepare: prepareDurable }), + }); +} const dim = adapter({ id: 'dim', binary: 'dimcode', supportedTracks: both, versionArgs: ['version'], @@ -618,11 +819,13 @@ const refAgent = adapter({ const adapters = [ refAgent, makaAdapter('maka-direct', false), makaAdapter('maka-codemode', true), claude, - codexAdapter(true), codexAdapter(false), opencodeAdapter(false), opencodeAdapter(true), - pi, piDurable, dim, dsh, zcode, + codexAdapter(true), codexAdapter(false), opencodeAdapter('opencode-cold', both), opencodeAdapter('opencode-attach', both), + pi, piDurableAdapter(false), dim, dsh, zcode, kimiAdapter('kimi-openai', chat, 'openai'), kimiAdapter('kimi-responses', responses, 'openai_responses'), kimiAdapter('kimi-anthropic', anthropic, 'anthropic'), + makaAdapter('maka-host-direct', false), makaAdapter('maka-host-codemode', true), + opencodeAdapter('opencode-serve', native), piDurableAdapter(true), ]; export function getAdapter(id) { @@ -676,6 +879,13 @@ async function referenceNative(workspace, name, args) { }); return { text: stdout }; } + const sleep = /^sleep 0\.1 && printf '(burst-probe-[0-9]+-[0-9]+)'$/.exec(args.command); + if (sleep) { + const { stdout } = await exec('/bin/sh', ['-c', 'sleep 0.1 && printf "%s" "$1"', 'bench', sleep[1]], { + cwd: workspace, env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, timeout: 10_000, + }); + return { text: stdout }; + } const parsed = parseBenchmarkCommand(args.command); const argv = parsed.kind === 'grep' ? ['exec grep -Fx -- "$1" "$2"', parsed.marker, await resolveWorkspaceFile(workspace, parsed.path)] @@ -771,11 +981,12 @@ async function connectReferenceMcp(mcp, workspace) { } class RefRequestError extends Error { - constructor(message, { status, provider, retryAfter, cause, disconnected } = {}) { + constructor(message, { status, provider, retryAfter, retryAfterMs, cause, disconnected } = {}) { super(message, { cause }); this.status = status; this.provider = provider; this.retryAfter = retryAfter; + this.retryAfterMs = retryAfterMs; this.disconnected = disconnected; } @@ -918,6 +1129,7 @@ async function refRequest(config, messages, tools, summary = false) { if (response.headers.get('content-type')?.includes('json')) provider = JSON.parse(raw).error; throw new RefRequestError(provider?.message ?? raw, { status: response.status, provider, retryAfter: response.headers.get('retry-after'), + retryAfterMs: response.headers.get('retry-after-ms'), }); } if (response.headers.get('content-type')?.includes('text/event-stream')) { @@ -932,8 +1144,10 @@ async function refRequest(config, messages, tools, summary = false) { } catch (error) { if (!error.retryable || attempt >= 4) throw error; const seconds = Number(error.retryAfter); - const retryAfter = !error.retryAfter ? 0 : Number.isFinite(seconds) - ? seconds * 1000 : Date.parse(error.retryAfter) - Date.now(); + const retryAfter = error.retryAfterMs !== null && error.retryAfterMs !== undefined + ? Number(error.retryAfterMs) + : !error.retryAfter ? 0 : Number.isFinite(seconds) + ? seconds * 1000 : Date.parse(error.retryAfter) - Date.now(); await delay(Math.max(50 * 2 ** attempt, Number.isFinite(retryAfter) ? retryAfter : 0)); } } @@ -995,7 +1209,7 @@ export async function runRefAgentCli() { const invoke = shared?.call ?? ((name, args) => referenceNative(workspace, name, args)); const isAnthropic = config.protocol === anthropic; try { - for (let round = 0; round < 100; round++) { + for (let round = 0; round < 1024; round++) { let message; try { message = await refRequest(config, history, tools); @@ -1041,15 +1255,15 @@ export async function runRefAgentCli() { process.stdout.write(text + '\n'); return; } - throw new Error('Reference agent exceeded its 100-turn budget'); + throw new Error('Reference agent exceeded its 1024-turn budget'); } finally { await shared?.close(); } } -if (process.argv[2] === '--ref-agent' && process.argv[1] && resolve(process.argv[1]) === script) { +if (['--ref-agent', '--maka-acp'].includes(process.argv[2]) && process.argv[1] && resolve(process.argv[1]) === script) { try { - await runRefAgentCli(); + await (process.argv[2] === '--maka-acp' ? runMakaAcp() : runRefAgentCli()); } catch (error) { console.error(error); process.exitCode = 1; diff --git a/tools/harness-bench/bench.test.mjs b/tools/harness-bench/bench.test.mjs index 2ecb04e0d7c..b991cf00ca8 100644 --- a/tools/harness-bench/bench.test.mjs +++ b/tools/harness-bench/bench.test.mjs @@ -20,12 +20,14 @@ import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; import { createHash } from 'node:crypto'; +import { ClusterMonitor, runMonitoredProcess } from './proc-monitor.mjs'; import { access, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { before, test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; +import { generateStressScenario } from './stress.mjs'; import { resolveMockAiBinary } from './mock-client.mjs'; const cli = fileURLToPath(new URL('run.mjs', import.meta.url)); @@ -118,6 +120,7 @@ test('preflight reports all adapters and runs the version probe in isolated HOME 'ref-agent', 'maka-direct', 'maka-codemode', 'claude', 'codex-ws', 'codex-http', 'opencode-cold', 'opencode-attach', 'pi', 'pi-durable', 'dim', 'dsh', 'zcode', 'kimi-openai', 'kimi-responses', 'kimi-anthropic', + 'maka-host-direct', 'maka-host-codemode', 'opencode-serve', 'pi-durable-shared', ]); const claude = probes.find(probe => probe.id === 'claude'); assert.equal(claude.binaryPath, join(bin, 'claude')); @@ -275,3 +278,139 @@ test('SIGKILL restarts the reference client with one workspace, session and MCP ['edit/1:Http429', 'edit/2:Http429', 'edit/3:Http429', 'edit/4:Http429']); await assertCleanServer(results); }); + + +async function runStress(t, suite, args, { harnesses = 'ref-agent', ...options } = {}) { + const output = join(await scratch(t), 'output'); + const result = await invoke([ + 'stress', '--suite', suite, '--harnesses', harnesses, + '--mock-bin', mockBinary, '--output', output, ...args, + ], options); + return { output: join(output, suite), result }; +} + +test('deep-grind generates real filesystem work and measures history growth', async t => { + const { output } = await runStress(t, 'deep-grind', ['--turns', '10', '--output-bytes', '16384']); + const { version, fixture, steps } = await readJson(join(output, 'scenario.json')); + assert.equal(version, 1); + assert.equal(fixture, 'deep-grind-v1'); + assert.deepEqual(steps.filter(step => step.largeOutput).map(step => step.id), ['turn-5', 'turn-10']); + assert.deepEqual(generateStressScenario('deep-grind', { turns: 10 }), + await readJson(join(output, 'scenario.json'))); + const results = await readJson(join(output, 'results.json')); + const [lane] = results.lanes; + const { dir } = await laneEvidence(output, lane, ['DEEP_GRIND_OK']); + assert.equal(await readFile(join(dir, 'workspace', 'state-6.txt'), 'utf8'), 'state=edited-8\n'); + assert.equal(lane.completedToolRounds, 10); + assert.ok(lane.promptBytesFinal > 32_768); + const { intervalsMs, headMedianMs, tailMedianMs, degradationRatio } = lane.turnLatencyCurve; + assert.equal(intervalsMs.length, 10); + assert.equal(degradationRatio, tailMedianMs / headMedianMs); + await assertCleanServer(results); +}); + +test('burst-flood runs independent calls with UTF-8 output and samples the live cluster', async t => { + const { output } = await runStress(t, 'burst-flood', ['--turns', '2', '--parallel', '8', '--lanes', '2']); + const results = await readJson(join(output, 'results.json')); + const [batch] = results.batches; + assert.equal(batch.completedToolRounds, 4); + assert.equal(batch.throughputTurnsPerSec, 4_000 / batch.wallMs); + assert.ok(batch.peakClusterRssMib > 0); + assert.ok(batch.peakClusterProcessCount >= 2); + assert.deepEqual(Object.keys(batch.diskStateMib).sort(), ['lane-1', 'lane-2']); + for (const lane of results.lanes) { + const { dir, detail } = await laneEvidence(output, lane, ['BURST_FLOOD_OK']); + assert.equal(new Set(detail.items.flatMap(item => item.confirmedCallIds)).size, 16); + assert.ok(lane.promptBytesFinal >= 2 * 262_144); + assert.ok(lane.turnLatencyCurve.intervalsMs.every(ms => ms >= 95)); + assert.equal(await readFile(join(dir, 'workspace', 'burst-output-2-6.txt'), 'utf8'), 'burst-result=2-6\n'); + } + await assertCleanServer(results); +}); + +test('firehose reassembles fragmented multibyte JSON and final SSE text', async t => { + const { output } = await runStress(t, 'firehose', [ + '--turns', '2', '--lanes', '2', '--chunk-chars', '16', '--wire-poison', '--latency-profile', 'frontier', + ]); + const results = await readJson(join(output, 'results.json')); + const spec = await readJson(join(output, 'scenario.json')); + for (const lane of results.lanes) { + const { dir, detail } = await laneEvidence(output, lane, ['FIREHOSE_OK']); + const { path, content } = spec.steps[0].writeFile; + assert.equal(await readFile(join(dir, 'workspace', path), 'utf8'), content); + assert.ok(detail.items[0].responseWireBytes > 4 * Buffer.byteLength(content)); + assert.ok(detail.items.every(item => item.simulatedDelayNs === 0)); + } + await assertCleanServer(results); +}); + +test('cliff-ramp continues passing harnesses and stops at the first failed stage', async t => { + const bin = await scratch(t); + const { output } = await runStress(t, 'cliff-ramp', ['--steps', '1,2'], { + harnesses: 'pi,ref-agent', env: { ...process.env, PATH: bin }, expectedCode: 1, + }); + const [ref, pi] = await readJson(join(output, 'leaderboard.json')); + assert.equal(ref.harness, 'ref-agent'); + assert.equal(ref.maxPassedLanes, 2); + assert.equal(ref.breakingPoint, null); + assert.equal(ref.stages[1].completedToolRounds, 24); + assert.equal(pi.harness, 'pi'); + assert.equal(pi.breakingPoint.lanes, 1); + assert.deepEqual(pi.stages.map(stage => stage.lanes), [1]); + assert.deepEqual(await readdir(join(output, 'lanes-2')), ['ref-agent']); + assert.match(await readFile(join(output, 'leaderboard.md'), 'utf8'), /Breaking-Point Cliff Leaderboard/); + await assertCleanServer(await readJson(join(output, 'lanes-2', 'ref-agent', 'results.json'))); +}); + +test('cliff-ramp records RSS termination and cleans all registered sessions', async t => { + const { output } = await runStress(t, 'cliff-ramp', [ + '--steps', '2,4', '--latency-profile', 'frontier', '--max-cluster-rss-gib', '0.01', + ], { expectedCode: 1 }); + const [row] = await readJson(join(output, 'leaderboard.json')); + assert.equal(row.breakingPoint.lanes, 2); + assert.equal(row.breakingPoint.termination, 'cluster_rss_limit_exceeded'); + assert.ok(row.breakingPoint.peakClusterRssMib > 10.24); + assert.deepEqual(row.stages.map(stage => stage.lanes), [2]); + const results = await readJson(join(output, 'lanes-2', 'ref-agent', 'results.json')); + assert.ok(results.lanes.every(lane => lane.sessionDeleted && !lane.success)); + await assertCleanServer(results); +}); + + +test('chaos-storm routes scheduled failures through poisoned streaming and verifies recovery', async t => { + const { output } = await runStress(t, 'chaos-storm', ['--lanes', '2']); + const results = await readJson(join(output, 'results.json')); + for (const lane of results.lanes) { + const { detail } = await laneEvidence(output, lane, ['CHAOS_STORM_OK']); + assert.deepEqual(detail.items.filter(item => item.faultId).map(item => item.faultId), [ + 'turn-1/1:Http429', 'turn-2/1:Http503', 'turn-3/1:Disconnect', + ]); + assert.equal(lane.completedToolRounds, 10); + } + await assertCleanServer(results); +}); + +test('one cluster abort kills both process groups and their inherited children', async () => { + const controller = new AbortController(); + const monitor = new ClusterMonitor({ signal: controller.signal }); + const descendants = []; + try { + const processes = [1, 2].map(() => runMonitoredProcess({ + command: '/bin/sh', args: ['-c', '/bin/sleep 30 & printf "%s\n" "$!"; wait'], + monitor, timeoutMs: 2000, + onStdoutLine(line) { + descendants.push(Number(line)); + if (descendants.length === 2) controller.abort(new Error('test interruption')); + }, + })); + const results = await Promise.all(processes); + assert.deepEqual(results.map(result => result.termination), ['aborted', 'aborted']); + for (const pid of descendants) { + const { stdout } = await exec('/bin/ps', ['-axo', 'pid=,stat=']); + const row = stdout.split('\n').map(line => line.trim().split(/\s+/)).find(([id]) => Number(id) === pid); + assert.ok(!row || row[1].startsWith('Z'), `Descendant still active: ${row}`); + } + } finally { + await monitor.close(); + } +}); diff --git a/tools/harness-bench/proc-monitor.mjs b/tools/harness-bench/proc-monitor.mjs index 038a1983c66..0a25cd7f8b0 100644 --- a/tools/harness-bench/proc-monitor.mjs +++ b/tools/harness-bench/proc-monitor.mjs @@ -18,6 +18,8 @@ */ import { execFile, spawn } from 'node:child_process'; +import { lstat, readdir } from 'node:fs/promises'; +import { join } from 'node:path'; import { createInterface } from 'node:readline'; import { finished } from 'node:stream/promises'; import { promisify } from 'node:util'; @@ -25,42 +27,174 @@ import { promisify } from 'node:util'; const execFileAsync = promisify(execFile); const logLimit = 256 * 1024; -function killGroup(pid) { +function sendSignal(pid, signal) { try { - process.kill(-pid, 'SIGKILL'); + process.kill(pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; } } -async function sampleTree(rootPid, signal) { - const { stdout } = await execFileAsync('ps', ['-axo', 'pid=,ppid=,rss=,pcpu='], { - signal, - env: { ...process.env, LC_ALL: 'C' }, +export function killProcessGroup(pid, signal = 'SIGKILL') { + if (pid) sendSignal(-pid, signal); +} + +async function processTable() { + const { stdout } = await execFileAsync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,state=,rss=,pcpu='], { + env: { LC_ALL: 'C' }, maxBuffer: 8 * 1024 * 1024, }); - const children = new Map(); - let root; - for (const line of stdout.trim().split('\n')) { - const [pid, parent, rssKib, cpuPercent] = line.trim().split(/\s+/).map(Number); - const entry = { pid, rssKib, cpuPercent }; - if (pid === rootPid) root = entry; - const siblings = children.get(parent); - if (siblings) siblings.push(entry); - else children.set(parent, [entry]); - } - if (!root) return null; - - let rssKib = 0; - let cpuPercent = 0; - const tree = [root]; - for (const entry of tree) { - rssKib += entry.rssKib; - cpuPercent += entry.cpuPercent; - const descendants = children.get(entry.pid); - if (descendants) tree.push(...descendants); - } - return { rssKib, cpuPercent, processCount: tree.length }; + return stdout.trim().split('\n').map(line => { + const [pid, parent, group, state, rssKib, cpuPercent] = line.trim().split(/\s+/); + return { pid: Number(pid), parent: Number(parent), group: Number(group), + live: !state.startsWith('Z'), rssKib: Number(rssKib), cpuPercent: Number(cpuPercent) }; + }); +} + +async function stateBytes(path) { + try { + const entry = await lstat(path); + if (entry.isFile()) return entry.size; + if (!entry.isDirectory()) return 0; + let total = 0; + for (const name of await readdir(path)) total += await stateBytes(join(path, name)); + return total; + } catch (error) { + if (error.code !== 'ENOENT') throw error; + return 0; + } +} + +export class ClusterMonitor { + #roots = new Map(); + #timer; + #sample; + #diskSample; + #peakRssKib = 0; + #peakProcessCount = 0; + #diskPeaks = new Map(); + #controller = new AbortController(); + #closed = false; + #error; + #cleanupErrors = []; + + constructor({ signal, maxClusterRssGib = Infinity, sampleIntervalMs = 100, stateDirs = new Map() } = {}) { + this.signal = signal ? AbortSignal.any([signal, this.#controller.signal]) : this.#controller.signal; + this.limitKib = maxClusterRssGib * 1024 ** 2; + this.stateDirs = stateDirs; + this.abort = () => { + for (const root of this.#roots.values()) this.terminate(root); + }; + this.signal.addEventListener('abort', this.abort, { once: true }); + this.#timer = setInterval(() => this.#tick(), sampleIntervalMs); + } + + terminate(root) { + if (!root || root.killed) return; + root.killed = true; + const targets = [-root.pid, ...root.escaped]; + for (const target of targets) { + try { + sendSignal(target, 'SIGKILL'); + } catch (error) { + this.#cleanupErrors.push(error); + } + } + } + + watch(pid) { + if (!pid) return; + const root = { pid, escaped: [], samples: [], peakRssKib: 0, peakProcessCount: 0, killed: false }; + this.#roots.set(pid, root); + if (this.signal.aborted) this.terminate(root); + else this.#tick(); + return root; + } + + release(root) { + if (!root) return; + this.terminate(root); + this.#roots.delete(root.pid); + } + + #tick() { + if (this.#closed || this.signal.aborted) return; + if (!this.#sample && this.#roots.size) { + this.#sample = this.#sampleProcesses().catch(error => this.#fail(error)) + .finally(() => { this.#sample = undefined; }); + } + if (!this.#diskSample && this.stateDirs.size) { + this.#diskSample = this.#sampleDisk().catch(error => this.#fail(error)) + .finally(() => { this.#diskSample = undefined; }); + } + } + + #fail(error) { + this.#error ??= error; + this.#controller.abort(new Error('cluster_monitor_failed', { cause: error })); + } + + async #sampleProcesses() { + const atNs = process.hrtime.bigint().toString(); + const table = await processTable(); + const children = Map.groupBy(table, row => row.parent); + const groups = Map.groupBy(table, row => row.group); + const byPid = new Map(table.map(row => [row.pid, row])); + const cluster = new Map(); + for (const root of this.#roots.values()) { + const tree = new Map(); + const queue = [...(groups.get(root.pid) ?? []), ...root.escaped.map(pid => byPid.get(pid)).filter(Boolean)]; + for (const row of queue) { + if (tree.has(row.pid)) continue; + tree.set(row.pid, row); + for (const child of children.get(row.pid) ?? []) queue.push(child); + } + root.escaped = []; + let rssKib = 0; + let cpuPercent = 0; + let processCount = 0; + for (const row of tree.values()) { + if (!row.live) continue; + cluster.set(row.pid, row); + if (row.group !== root.pid) root.escaped.push(row.pid); + rssKib += row.rssKib; + cpuPercent += row.cpuPercent; + processCount++; + } + root.samples.push({ atNs, rssKib, cpuPercent, processCount }); + root.peakRssKib = Math.max(root.peakRssKib, rssKib); + root.peakProcessCount = Math.max(root.peakProcessCount, processCount); + } + const rssKib = [...cluster.values()].reduce((total, row) => total + row.rssKib, 0); + this.#peakRssKib = Math.max(this.#peakRssKib, rssKib); + this.#peakProcessCount = Math.max(this.#peakProcessCount, cluster.size); + if (rssKib > this.limitKib) this.#controller.abort(new Error('cluster_rss_limit_exceeded')); + } + + async #sampleDisk() { + await Promise.all([...this.stateDirs].map(async ([name, path]) => { + const bytes = await stateBytes(path); + this.#diskPeaks.set(name, Math.max(bytes, this.#diskPeaks.get(name) ?? 0)); + })); + } + + async close() { + this.#closed = true; + clearInterval(this.#timer); + this.signal.removeEventListener('abort', this.abort); + this.abort(); + await Promise.all([this.#sample, this.#diskSample]); + await this.#sampleDisk(); + if (this.#cleanupErrors.length) { + throw new Error('Could not kill benchmark processes: ' + this.#cleanupErrors.map(error => error.message).join(', ')); + } + if (this.#error) throw this.#error; + return { + peakClusterRssMib: this.#peakRssKib / 1024, + peakClusterProcessCount: this.#peakProcessCount, + diskStateMib: Object.fromEntries([...this.#diskPeaks].map(([name, bytes]) => [name, bytes / 1024 ** 2])), + }; + } } async function collectOutput(stream, onLine) { @@ -92,7 +226,7 @@ async function collectOutput(stream, onLine) { export async function runMonitoredProcess({ command, args = [], cwd, env, stdinText, timeoutMs, sampleIntervalMs = 100, sigkillAfterMs, - onStdoutLine, onStderrLine, signal, + onStdoutLine, onStderrLine, signal, monitor, onTimeout, }) { for (const [name, value, minimum] of [ ['sampleIntervalMs', sampleIntervalMs, 1], @@ -107,6 +241,7 @@ export async function runMonitoredProcess({ throw new TypeError('stdinText must be a string'); } signal?.throwIfAborted(); + monitor?.signal.throwIfAborted(); const startNs = process.hrtime.bigint(); const child = spawn(command, args, { cwd, @@ -114,68 +249,39 @@ export async function runMonitoredProcess({ detached: true, stdio: [stdinText === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], }); - - const samples = []; - const sampling = new AbortController(); - let peakRssKib = 0; - let peakProcessCount = 0; + const ownedMonitor = monitor ? undefined : new ClusterMonitor({ signal, sampleIntervalMs }); + monitor ??= ownedMonitor; + signal = monitor.signal; let endNs; let failure; let stdinError = null; let termination = null; - let sampleTimer; - let sampleInFlight; let timeout; let injection; - function kill() { - if (!child.pid) return; - try { - killGroup(child.pid); - } catch (error) { - failure ??= error; - } - } - function fail(error) { failure ??= error; - if (endNs === undefined) kill(); + monitor.terminate(observation); } function terminate(reason) { if (endNs !== undefined || termination || !child.pid) return; termination = reason; - kill(); + monitor.terminate(observation); } function abort() { - terminate('aborted'); - } - - function sample() { - const atNs = process.hrtime.bigint().toString(); - sampleInFlight = sampleTree(child.pid, sampling.signal).then(tree => { - if (!tree) return; - samples.push({ atNs, ...tree }); - peakRssKib = Math.max(peakRssKib, tree.rssKib); - peakProcessCount = Math.max(peakProcessCount, tree.processCount); - }).catch(error => { - if (!sampling.signal.aborted) fail(new Error('Could not sample child process tree', { cause: error })); - }).finally(() => { - if (!sampling.signal.aborted) sampleTimer = setTimeout(sample, sampleIntervalMs); - }); + const reason = signal.reason?.message; + terminate(['cluster_rss_limit_exceeded', 'timeout'].includes(reason) ? reason : 'aborted'); } child.on('error', fail); - child.once('spawn', sample); + const observation = monitor.watch(child.pid); child.once('exit', () => { endNs = process.hrtime.bigint(); clearTimeout(timeout); clearTimeout(injection); - clearTimeout(sampleTimer); - sampling.abort(); - // Descendants may still own the stdio pipes after the group leader exits. - kill(); + monitor.release(observation); }); const closed = new Promise(resolveClose => { child.once('close', (code, signal) => resolveClose({ code, signal })); @@ -195,14 +301,16 @@ export async function runMonitoredProcess({ }); child.stdin.end(stdinText); } - if (timeoutMs !== undefined) timeout = setTimeout(() => terminate('timeout'), timeoutMs); + if (timeoutMs !== undefined) timeout = setTimeout(() => { + terminate('timeout'); + onTimeout?.(); + }, timeoutMs); if (sigkillAfterMs !== undefined) injection = setTimeout(() => terminate('sigkill'), sigkillAfterMs); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort(); try { const [exit, stdout, stderr] = await Promise.all([closed, ...outputs]); - await sampleInFlight; if (failure) throw failure; return { ...exit, @@ -211,9 +319,9 @@ export async function runMonitoredProcess({ startNs: startNs.toString(), endNs: endNs.toString(), wallMs: Number(endNs - startNs) / 1e6, - peakRssKib, - peakProcessCount, - samples, + peakRssKib: observation?.peakRssKib ?? 0, + peakProcessCount: observation?.peakProcessCount ?? 0, + samples: observation?.samples ?? [], stdout: stdout.text, stderr: stderr.text, stdoutTruncated: stdout.truncated, @@ -222,6 +330,7 @@ export async function runMonitoredProcess({ } finally { clearTimeout(timeout); clearTimeout(injection); - signal?.removeEventListener('abort', abort); + signal.removeEventListener('abort', abort); + await ownedMonitor?.close(); } } diff --git a/tools/harness-bench/report.mjs b/tools/harness-bench/report.mjs index 6d763cd0e9e..b459eb3b06c 100644 --- a/tools/harness-bench/report.mjs +++ b/tools/harness-bench/report.mjs @@ -24,11 +24,15 @@ const sideChannelPurposes = new Set([ function summarizeAttempts(items) { const receiptRevisions = new Set(); let newestRevision = 0; + const turnStarts = new Map(); let completedAttempts = 0; let retries = 0; let sideChannelCalls = 0; for (const item of items) { if (item.revision !== null) newestRevision = Math.max(newestRevision, item.revision); + if (item.purpose === 'main' && Number.isFinite(item.revision) && Number.isFinite(item.headersReceivedNs)) { + turnStarts.set(item.revision, Math.min(turnStarts.get(item.revision) ?? Infinity, item.headersReceivedNs)); + } if (item.outcome === 'completed') completedAttempts++; if (item.retryReason !== null) retries++; if (sideChannelPurposes.has(item.purpose)) sideChannelCalls++; @@ -39,12 +43,17 @@ function summarizeAttempts(items) { receiptRevisions.add(Number(receipt[1])); } } - let completedToolRounds = 0; - for (const revision of receiptRevisions) { - // One receipt from a parallel batch does not advance the scenario. - if (revision < newestRevision) completedToolRounds++; - } - return { completedAttempts, completedToolRounds, retries, sideChannelCalls }; + // One receipt from a parallel batch does not advance the scenario. + const revisions = [...receiptRevisions].filter(revision => revision < newestRevision).sort((a, b) => a - b); + const intervalsMs = revisions.map(revision => (turnStarts.get(revision + 1) - turnStarts.get(revision)) / 1e6) + .filter(value => Number.isFinite(value) && value >= 0); + const headMedianMs = median(intervalsMs.slice(0, 5).sort((a, b) => a - b)); + const tailMedianMs = median(intervalsMs.slice(-5).sort((a, b) => a - b)); + const turnLatencyCurve = { + intervalsMs, headMedianMs, tailMedianMs, + degradationRatio: intervalsMs.length >= 10 && headMedianMs > 0 ? tailMedianMs / headMedianMs : null, + }; + return { completedAttempts, completedToolRounds: revisions.length, retries, sideChannelCalls, turnLatencyCurve }; } function summarizePrompt(trajectory) { @@ -138,16 +147,22 @@ export function reconcileLaneResult({ laneConfig, procResult, workspaceProof, se attempts: mock.attempts ?? null, completedAttempts: mock.completedAttempts ?? null, completedToolRounds: mock.completedToolRounds ?? null, + turnLatencyCurve: mock.turnLatencyCurve ?? null, }; } +function median(sorted) { + if (!sorted.length) return null; + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + function distribution(records, field) { const values = records.map(record => record[field]).filter(Number.isFinite).sort((a, b) => a - b); const count = values.length; if (count === 0) return { median: null, min: null, max: null, p95: null }; - const mid = Math.floor(count / 2); return { - median: count % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2, + median: median(values), min: values[0], max: values[count - 1], p95: values[Math.ceil(count * 0.95) - 1], @@ -188,14 +203,14 @@ function markdownText(value) { } function measurement(value) { - return value === null ? '—' : value.toFixed(1); + return Number.isFinite(value) ? value.toFixed(1) : '—'; } function rate(value) { return `${(value * 100).toFixed(1)}%`; } -export function renderMarkdownReport(manifest, summary, lanes) { +export function renderMarkdownReport(manifest, summary, lanes, batches) { const lines = ['# Harness benchmark', '']; if (manifest.runId !== undefined) lines.push(`Run ${markdownText(manifest.runId)}`, ''); if (summary.length === 0) lines.push('No benchmark runs recorded.'); @@ -217,6 +232,23 @@ export function renderMarkdownReport(manifest, summary, lanes) { } } + if (batches?.length) { + lines.push('', '## Concurrent batches', '', + '| Harness | Repeat | Passed | Wall ms | Tool rounds/s | Peak cluster RSS (MiB) | Peak processes | Max lane disk (MiB) | Shared disk (MiB) | Median degradation ratio | Termination |', + '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |'); + for (const batch of batches) { + const ratios = lanes.filter(lane => lane.harness === batch.harness && lane.artifacts.startsWith('repeat-' + batch.repeat + '/')) + .map(lane => lane.turnLatencyCurve?.degradationRatio).filter(Number.isFinite).sort((a, b) => a - b); + const { shared, ...laneDisk } = batch.diskStateMib ?? {}; + lines.push('| ' + [ + batch.harness, batch.repeat, batch.successfulLanes + '/' + batch.lanes, measurement(batch.wallMs), + measurement(batch.throughputTurnsPerSec), measurement(batch.peakClusterRssMib), + batch.peakClusterProcessCount ?? '—', measurement(Math.max(...Object.values(laneDisk))), + measurement(shared), measurement(median(ratios)), batch.termination ?? '—', + ].map(markdownText).join(' | ') + ' |'); + } + } + const failed = lanes.filter(lane => !lane.success || lane.watchdogViolations?.length > 0); if (failed.length) { lines.push('', '## Failures and violations', ''); @@ -234,3 +266,22 @@ export function renderMarkdownReport(manifest, summary, lanes) { } return `${lines.join('\n')}\n`; } + +export function renderCliffLeaderboard(rows) { + const lines = [ + '# Breaking-Point Cliff Leaderboard', '', + '| Harness | Highest passing stage | First failed stage | Passed lanes | Termination | Tool rounds/s at last stage | Peak RSS MiB at last stage |', + '| --- | ---: | ---: | ---: | --- | ---: | ---: |', + ]; + for (const { harness, maxPassedLanes, breakingPoint, stages } of rows) { + const last = stages.at(-1); + lines.push('| ' + [ + markdownText(harness), maxPassedLanes ?? '—', + breakingPoint ? `[${breakingPoint.lanes}](${breakingPoint.report})` : '—', + last ? (last.successfulLanes ?? 0) + '/' + last.lanes : '—', + breakingPoint ? markdownText(breakingPoint.termination ?? breakingPoint.errors[0] ?? 'lane verification failed') : '—', + measurement(last?.throughputTurnsPerSec), measurement(last?.peakClusterRssMib), + ].join(' | ') + ' |'); + } + return lines.join('\n') + '\n'; +} diff --git a/tools/harness-bench/run.mjs b/tools/harness-bench/run.mjs index bc70d82720e..63fc22f15b1 100644 --- a/tools/harness-bench/run.mjs +++ b/tools/harness-bench/run.mjs @@ -18,17 +18,19 @@ */ import { randomUUID } from 'node:crypto'; -import { mkdir, mkdtemp, readdir, realpath, rmdir, writeFile } from 'node:fs/promises'; +import { mkdir, mkdtemp, readdir, realpath, rm, rmdir, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; import { parseArgs, stripVTControlCharacters } from 'node:util'; -import { getAdapter, listAdapters, probeAllAdapters } from './adapters.mjs'; +import { getAdapter, listAdapters, probeAllAdapters, startProviderProxy } from './adapters.mjs'; import { loadScenario, materializeWorkspace, verifyWorkspace } from './fixtures.mjs'; import { MockAdminClient, resolveMockAiBinary, startMockAi } from './mock-client.mjs'; -import { runMonitoredProcess } from './proc-monitor.mjs'; -import { aggregateComparison, reconcileLaneResult, renderMarkdownReport } from './report.mjs'; +import { ClusterMonitor, runMonitoredProcess } from './proc-monitor.mjs'; +import { aggregateComparison, reconcileLaneResult, renderMarkdownReport, renderCliffLeaderboard } from './report.mjs'; + +import { climbCliff, generateStressScenario, stressSuites } from './stress.mjs'; const directory = dirname(fileURLToPath(import.meta.url)); const repoRoot = resolve(directory, '../..'); @@ -43,12 +45,16 @@ const usage = [ ' calibrate [--scenario smoke-edit] [--lanes 16]', ' matrix --harnesses a,b [--scenarios smoke-edit,concurrency-fanout,long-compaction,chaos-recovery,mcp-smoke-edit]', ' [--lanes 1] [--runs 1]', + ' stress --suite deep-grind|burst-flood|cliff-ramp|chaos-storm|firehose|all --harnesses a,b', + ' [--turns ] [--parallel 16] [--output-bytes ] [--steps 4,8,16,32,64,128]', + ' [--lanes ] [--latency-profile instant|frontier] [--chunk-chars 16] [--wire-poison]', + ' [--max-cluster-rss-gib 32] [--timeout-ms 120000]', ' All commands that run lanes accept --mock-bin and --output .', ].join('\n'); const string = { type: 'string' }; const boolean = { type: 'boolean' }; -const sharedOptions = { output: string, 'mock-bin': string, lanes: string }; +const sharedOptions = { output: string, 'mock-bin': string, lanes: string, 'max-cluster-rss-gib': string }; const commandOptions = { preflight: { harnesses: string, json: boolean }, run: { @@ -56,6 +62,11 @@ const commandOptions = { 'latency-profile': string, 'provider-dialect': string, 'timeout-ms': string, 'sigkill-after-ms': string, 'resume-after-kill': boolean, }, + stress: { + ...sharedOptions, suite: string, harnesses: string, turns: string, parallel: string, + 'output-bytes': string, steps: string, 'chunk-chars': string, 'wire-poison': boolean, + 'latency-profile': string, 'timeout-ms': string, 'provider-dialect': string, + }, calibrate: { ...sharedOptions, scenario: string }, matrix: { ...sharedOptions, harnesses: string, scenarios: string, runs: string }, }; @@ -116,8 +127,8 @@ async function preflight(values) { const adapters = new Map(listAdapters().map(adapter => [adapter.id, adapter])); const probes = await probeAllAdapters({ repoRoot, filter }); const results = probes.map(({ id, binaryPath, version, ...probe }) => { - const { supportedTracks, protocol, launchMode } = adapters.get(id); - return { id, binaryPath: binaryPath ?? null, version: version ?? null, supportedTracks, protocol, launchMode, ...probe }; + const { supportedTracks, protocol, launchMode, shared } = adapters.get(id); + return { id, binaryPath: binaryPath ?? null, version: version ?? null, supportedTracks, protocol, launchMode, sharedTracks: shared, ...probe }; }); if (values.json) console.log(JSON.stringify(results, null, 2)); else { @@ -133,7 +144,7 @@ async function preflight(values) { } } -async function prepareLane({ output, adapter, spec, mock, admin, repeat, laneIndex, runId, options }) { +async function prepareLane({ output, adapter, spec, origin, admin, repeat, laneIndex, runId, options, tempDirs }) { const sessionId = randomUUID(); const logicalLane = 'lane-' + (laneIndex + 1); const artifactDir = join('repeat-' + (repeat + 1), adapter.id, logicalLane); @@ -142,22 +153,21 @@ async function prepareLane({ output, adapter, spec, mock, admin, repeat, laneInd const isolatedDir = join(laneDir, 'isolated'); const mcpAuditPath = spec.track === 'sharedMcp' ? join(laneDir, 'mcp-audit.jsonl') : undefined; const identity = { runId, sessionId, harness: adapter.id, logicalLane, scenario: spec.scenario }; - const lane = { identity, laneDir, artifactDir, workspaceDir, mcpAuditPath, errors: [] }; + const lane = { identity, laneDir, artifactDir, workspaceDir, isolatedDir, mcpAuditPath, errors: [], segments: [] }; try { await mkdir(laneDir, { recursive: true, mode: 0o700 }); lane.initialManifest = await materializeWorkspace(spec, workspaceDir); await mkdir(isolatedDir, { mode: 0o700 }); await admin.registerSession({ - ...identity, launchMode: adapter.launchMode, workspace: workspaceDir, + ...identity, workspace: workspaceDir, + launchMode: adapter.shared.includes(spec.track) ? 'shared-daemon' : adapter.startDaemon ? 'warm-daemon' : 'cold', }); lane.registered = true; - const context = { + lane.context = { ...identity, repoRoot, prompt, track: spec.track, workspace: workspaceDir, isolatedDir, - scopedOrigin: mock.baseUrl, apiKey: 'maka-benchmark-' + sessionId, mcpAuditPath, + scopedOrigin: origin, apiKey: 'maka-benchmark-' + sessionId, mcpAuditPath, tempDirs, resumeAfterKill: options.resumeAfterKill, }; - if (adapter.startDaemon) lane.daemon = await adapter.startDaemon(context); - lane.invocation = await adapter.prepareInvocation({ ...context, daemonState: lane.daemon }); } catch (error) { diagnose(lane.errors, 'Lane setup', error); } @@ -210,39 +220,41 @@ async function exportSession(lane, admin, finalStep, observedMarkers) { } } -async function executeLane(lane, { admin, adapter, spec, options, signal }) { - const { laneDir } = lane; - const segments = []; - let proc; - let agentOutputText = ''; +async function executeLane(lane, { adapter, options, monitor, abortBatch, sharedDaemon }) { + if (!lane.context) return; + let daemon; try { - if (lane.invocation) { - proc = await runMonitoredProcess({ - ...lane.invocation, signal, timeoutMs: options.timeoutMs, sigkillAfterMs: options.sigkillAfterMs, - }); - segments.push(proc); - if (options.sigkillAfterMs !== undefined && proc.termination !== 'sigkill') { - lane.errors.push('Scheduled SIGKILL did not occur'); - } - if (proc.termination === 'sigkill' && options.resumeAfterKill) { - proc = await runMonitoredProcess({ ...lane.invocation, signal, timeoutMs: options.timeoutMs }); - segments.push(proc); - } - // Only the final invocation can supply completion markers after a restart. - agentOutputText = stripVTControlCharacters(proc.stdout); + monitor.signal.throwIfAborted(); + const ctx = { ...lane.context, monitor, abortBatch }; + daemon = !sharedDaemon && adapter.startDaemon ? await adapter.startDaemon(ctx) : undefined; + const invocation = await adapter.prepareInvocation({ ...ctx, daemonState: sharedDaemon ?? daemon }); + const processOptions = { ...invocation, monitor, timeoutMs: options.timeoutMs, onTimeout: abortBatch }; + const proc = await runMonitoredProcess({ ...processOptions, sigkillAfterMs: options.sigkillAfterMs }); + lane.segments.push(proc); + if (options.sigkillAfterMs !== undefined && proc.termination !== 'sigkill') { + lane.errors.push('Scheduled SIGKILL did not occur'); + } + if (proc.termination === 'sigkill' && options.resumeAfterKill) { + lane.segments.push(await runMonitoredProcess(processOptions)); } } catch (error) { - proc = null; diagnose(lane.errors, 'Lane process', error); } finally { - if (lane.daemon) { + if (daemon) { try { - await adapter.stopDaemon(lane.daemon); + await adapter.stopDaemon(daemon); } catch (error) { diagnose(lane.errors, 'Daemon shutdown', error); } } } +} + +async function recordLane(lane, { admin, spec, diskStateMib, termination }) { + const { laneDir, segments } = lane; + const proc = segments.at(-1); + // Only the final invocation can supply completion markers after a restart. + const agentOutputText = stripVTControlCharacters(proc?.stdout ?? ''); const processEvidence = await Promise.all(segments.map(async ({ stdout, stderr, ...metrics }, index) => { const prefix = 'segment-' + (index + 1); const stdoutLog = prefix + '.stdout.log'; @@ -297,25 +309,139 @@ async function executeLane(lane, { admin, adapter, spec, options, signal }) { } } result.failures.push(...lane.errors); + if (termination && !result.success && !result.failures.some(error => error.includes(termination))) { + result.failures.push(termination); + } result.success &&= result.failures.length === 0; const record = { - ...result, artifacts: lane.artifactDir, + ...result, artifacts: lane.artifactDir, diskStateMib, mockCompleted: sessionDetail?.scenarioCompleted === true, sessionDeleted: lane.deletion?.deleted === true, }; await json(join(laneDir, 'lane.json'), { ...record, process: processEvidence, workspaceProof, observedMarkers, completionProof: lane.completionProof, }); - return { - record, - firstStart: segments[0]?.startNs, - lastEnd: segments.at(-1)?.endNs, - }; + return record; +} + +function processWindow(lanes) { + const segments = lanes.flatMap(lane => lane.segments); + if (!segments.length) return null; + const starts = segments.map(segment => BigInt(segment.startNs)); + const ends = segments.map(segment => BigInt(segment.endNs)); + return Number(ends.reduce((a, b) => a > b ? a : b) - starts.reduce((a, b) => a < b ? a : b)) / 1e6; +} + +async function runBatch({ output, adapter, spec, origin, admin, repeat, runId, options, signal, errors }) { + const tempDirs = new Set(); + const lanes = await Promise.all(Array.from({ length: options.lanes }, (_, laneIndex) => + prepareLane({ output, adapter, spec, origin, admin, repeat, laneIndex, runId, options, tempDirs }))); + const batchController = new AbortController(); + const abortBatch = (reason = 'timeout') => batchController.abort(new Error(reason)); + const batchSignal = AbortSignal.any([signal, batchController.signal]); + const shared = adapter.shared.includes(spec.track); + const batchArtifact = join('repeat-' + (repeat + 1), adapter.id); + const sharedDir = join(output, batchArtifact, 'shared-state'); + const stateDirs = new Map(lanes.map(lane => [lane.identity.logicalLane, lane.isolatedDir])); + if (shared) stateDirs.set('shared', sharedDir); + const monitor = new ClusterMonitor({ signal: batchSignal, stateDirs, maxClusterRssGib: options.maxClusterRssGib }); + let daemon; + let stopping = false; + let resources; + let wallMs; + let sharedProcess; + try { + monitor.signal.throwIfAborted(); + const active = lanes.filter(lane => lane.context); + if (shared && active.length) { + const ctx = { ...active[0].context, workspace: sharedDir, isolatedDir: sharedDir, monitor, abortBatch }; + const contexts = active.map(lane => lane.context); + await mkdir(sharedDir); + if (adapter.prepareBatch) { + if (options.sigkillAfterMs !== undefined) throw new Error('SIGKILL injection requires a lane process'); + const invocation = await adapter.prepareBatch(ctx, contexts); + const answers = new Map(); + const proc = await runMonitoredProcess({ + ...invocation, timeoutMs: options.timeoutMs, monitor, onTimeout: abortBatch, + onStdoutLine(line) { + const row = JSON.parse(line); + if (answers.has(row.logicalLane)) throw new Error('Duplicate result from ' + row.logicalLane); + answers.set(row.logicalLane, row); + }, + }); + wallMs = proc.wallMs; + if (!proc.termination && (proc.code !== 0 || proc.stdinError)) { + errors.push(adapter.id + ' shared process failed (' + (proc.stdinError ?? proc.signal ?? proc.code) + ')'); + } + const { stdout, stderr, ...metrics } = proc; + sharedProcess = { ...metrics, stderrLog: join(batchArtifact, 'shared.stderr.log') }; + await writeFile(join(output, sharedProcess.stderrLog), stderr); + for (const lane of active) { + const answer = answers.get(lane.identity.logicalLane); + if (!answer && proc.code === 0) lane.errors.push('Shared process did not return a lane result'); + if (answer?.error) lane.errors.push(answer.error); + lane.segments.push({ + ...proc, stdout: answer?.answer ?? '', stderr: '', wallMs: answer?.wallMs ?? proc.wallMs, + ...(answer ? { code: answer.error ? 1 : 0, signal: null, termination: null } : {}), + stdoutTruncated: false, stderrTruncated: false, + peakRssKib: 0, peakProcessCount: 0, samples: [], + }); + } + } else { + daemon = await adapter.startDaemon(ctx, contexts); + void daemon.exited.then(() => { + if (!stopping) abortBatch('shared_daemon_exited'); + }); + } + } + if (!adapter.prepareBatch) { + await Promise.all(lanes.map(lane => executeLane(lane, { adapter, options, monitor, abortBatch, sharedDaemon: daemon }))); + wallMs = processWindow(lanes); + } + } catch (error) { + for (const lane of lanes) diagnose(lane.errors, 'Batch process', error); + } finally { + stopping = true; + if (daemon) { + try { + await adapter.stopDaemon(daemon); + } catch (error) { + for (const lane of lanes) diagnose(lane.errors, 'Daemon shutdown', error); + } + } + try { + resources = await monitor.close(); + } catch (error) { + diagnose(errors, 'Cluster monitor', error); + } + const cleanup = await Promise.allSettled([...tempDirs].map(path => rm(path, { recursive: true, force: true }))); + for (const result of cleanup) { + if (result.status === 'rejected') diagnose(errors, 'Temporary process directory cleanup', result.reason); + } + } + const termination = monitor.signal.aborted ? monitor.signal.reason.message : null; + const finished = await Promise.allSettled(lanes.map(lane => recordLane(lane, { + admin, spec, termination, diskStateMib: resources?.diskStateMib[lane.identity.logicalLane] ?? null, + }))); + const records = []; + for (const [index, result] of finished.entries()) { + if (result.status === 'fulfilled') records.push(result.value); + else diagnose(errors, 'Could not record ' + lanes[index].artifactDir, result.reason); + } + const successfulLanes = records.filter(row => row.success).length; + const completedToolRounds = records.reduce((sum, lane) => sum + (lane.completedToolRounds ?? 0), 0); + return { records, batch: { + repeat: repeat + 1, harness: adapter.id, lanes: options.lanes, successfulLanes, + successRate: successfulLanes / options.lanes, termination, wallMs: wallMs ?? null, completedToolRounds, + throughputTurnsPerSec: wallMs > 0 ? completedToolRounds * 1000 / wallMs : null, sharedProcess, ...resources, + } }; } async function benchmark({ scenario, adapters, output, options, signal, calibrate }) { const { source: spec, path } = scenario; const runId = randomUUID(); - const candidates = adapters.map(({ id, protocol, launchMode, supportedTracks }) => ({ id, protocol, launchMode, supportedTracks })); + const candidates = adapters.map(({ id, protocol, launchMode, supportedTracks, shared }) => ({ + id, protocol, launchMode, supportedTracks, sharedTracks: shared, + })); const batches = []; for (let repeat = 0; repeat < options.runs; repeat++) { for (let index = 0; index < adapters.length; index++) { @@ -327,48 +453,55 @@ async function benchmark({ scenario, adapters, output, options, signal, calibrat startedAt: new Date().toISOString(), candidates, batches, ...options, mockBinary: null, }; const records = []; + const batchMetrics = []; let calibration; const errors = []; const server = {}; let mock; + let proxy; + let discovery; let admin; try { manifest.mockBinary = resolveMockAiBinary(repoRoot, options.mockBin); mock = await startMockAi({ binary: manifest.mockBinary, scenarioPath: path, latencyProfile: options.latencyProfile, providerDialect: options.providerDialect, + extraArgs: [ + ...(options.wire?.chunkChars ? ['--chunk-chars', String(options.wire.chunkChars)] : []), + ...(options.wire?.wirePoison ? ['--wire-poison'] : []), + ], }); server.origin = mock.baseUrl; admin = new MockAdminClient(mock.baseUrl); + if (options.wire?.retryAfterMs && adapters.some(adapter => adapter.protocol !== 'openai-responses-ws')) { + proxy = await startProviderProxy(mock.baseUrl, { retryAfterMs: options.wire.retryAfterMs }); + } + if (spec.track === 'sharedMcp' && adapters.some(adapter => adapter.harness === 'maka')) { + discovery = await startProviderProxy(mock.baseUrl, { discoverMcp: true }); + } if (calibrate) server.metricsBefore = await admin.metrics(); for (const { repeat, harness } of batches) { signal.throwIfAborted(); const adapter = getAdapter(harness); - const lanes = await Promise.all(Array.from({ length: options.lanes }, (_, laneIndex) => - prepareLane({ output, adapter, spec, mock, admin, repeat, laneIndex, runId, options }))); - const finished = await Promise.allSettled(lanes.map(lane => executeLane(lane, { admin, adapter, spec, options, signal }))); - const starts = []; - const ends = []; - for (const [index, lane] of finished.entries()) { - if (lane.status === 'fulfilled') { - records.push(lane.value.record); - if (lane.value.firstStart) starts.push(BigInt(lane.value.firstStart)); - if (lane.value.lastEnd) ends.push(BigInt(lane.value.lastEnd)); - } else { - diagnose(errors, 'Could not record ' + lanes[index].artifactDir, lane.reason); - } - } - if (calibrate && starts.length) { - const start = starts.reduce((min, ns) => ns < min ? ns : min); - const end = ends.reduce((max, ns) => ns > max ? ns : max); - const wallMs = Number(end - start) / 1e6; - const verifiedLanes = records.filter(row => row.success).length; + const routed = adapter.harness === 'maka' ? discovery ?? proxy : proxy; + const origin = adapter.protocol === 'openai-responses-ws' ? mock.baseUrl : routed?.origin ?? mock.baseUrl; + const { records: batchRecords, batch } = await runBatch({ + output, adapter, spec, origin, admin, repeat, runId, options, signal, errors, + }); + records.push(...batchRecords); + batchMetrics.push(batch); + if (calibrate && batch.wallMs > 0) { + const { wallMs, successfulLanes: verifiedLanes } = batch; calibration = { wallMs, verifiedLanes, verifiedLanesPerSecond: 1000 * verifiedLanes / wallMs }; } } } catch (error) { diagnose(errors, 'Benchmark', error); } finally { + const stopped = await Promise.allSettled([proxy, discovery].filter(Boolean).map(server => server.stop())); + for (const result of stopped) { + if (result.status === 'rejected') diagnose(errors, 'Provider proxy shutdown', result.reason); + } if (admin) { try { [server.metrics, server.sessionsAfterCleanup, server.watchdog] = await Promise.all([ @@ -394,8 +527,8 @@ async function benchmark({ scenario, adapters, output, options, signal, calibrat } const summary = aggregateComparison(records); - const results = { runId, lanes: records, summary, server, errors, calibration }; - let report = renderMarkdownReport(manifest, summary, records); + const results = { runId, lanes: records, batches: batchMetrics, summary, server, errors, calibration }; + let report = renderMarkdownReport(manifest, summary, records, batchMetrics); if (calibrate && calibration) { report += '\n## Calibration\n\n' + calibration.verifiedLanesPerSecond.toFixed(2) + ' verified lanes/s over the ' + calibration.wallMs.toFixed(1) @@ -415,8 +548,9 @@ async function benchmark({ scenario, adapters, output, options, signal, calibrat writeFile(join(output, 'report.md'), report), ]); return { - summary, calibration, - passed: errors.length === 0 && records.length === batches.length * options.lanes && records.every(row => row.success), + summary, calibration, batches: batchMetrics, errors, + passed: errors.length === 0 && records.length === batches.length * options.lanes && records.every(row => row.success) + && batchMetrics.every(batch => !batch.termination), }; } @@ -478,6 +612,73 @@ async function matrix({ scenarios, adapters, output, options, signal }) { return passed; } +function stressConfig(values) { + const suites = values.suite === 'all' ? stressSuites : [values.suite]; + if (suites.some(suite => !stressSuites.includes(suite))) throw new Error('Invalid --suite. See stress --help.'); + const steps = csv(values.steps ?? '4,8,16,32,64,128', 'steps').map(step => integer(step, 'steps')); + if (steps.some((lanes, index) => index > 0 && lanes <= steps[index - 1])) { + throw new Error('--steps must be strictly increasing'); + } + const latency = values['latency-profile'] ?? 'instant'; + if (!['instant', 'frontier'].includes(latency)) throw new Error('Invalid stress --latency-profile'); + const turns = integer(values.turns, 'turns'); + if (turns > 1023) throw new Error('--turns must be at most 1023'); + if (suites.includes('chaos-storm') && turns < 5) throw new Error('chaos-storm needs at least 5 turns'); + const parallel = integer(values.parallel, 'parallel', 16, 4); + if (parallel > 32) throw new Error('--parallel must be at most 32'); + const outputBytes = integer(values['output-bytes'], 'output-bytes'); + if (outputBytes > 1024 ** 2) throw new Error('--output-bytes must be at most 1 MiB (1048576)'); + return { suites, steps, turns, parallel, outputBytes, latency, + chunkChars: integer(values['chunk-chars'], 'chunk-chars', 16), wirePoison: values['wire-poison'] ?? false }; +} + +async function stress({ config, adapters, output, options, signal }) { + let passed = true; + for (const suite of config.suites) { + if (signal.aborted) break; + const suiteDir = join(output, suite); + await mkdir(suiteDir); + const scenario = { path: join(suiteDir, 'scenario.json'), source: generateStressScenario(suite, config) }; + await json(scenario.path, scenario.source); + const wire = suite === 'firehose' || suite === 'chaos-storm' || config.wirePoison ? { + chunkChars: suite === 'firehose' ? config.chunkChars : undefined, + retryAfterMs: suite === 'chaos-storm' ? 80 : undefined, wirePoison: config.wirePoison || suite === 'chaos-storm', + } : undefined; + const settings = { ...options, wire, + latencyProfile: suite === 'firehose' ? 'instant' : config.latency, + lanes: options.lanes ?? (['chaos-storm', 'firehose'].includes(suite) ? 8 : 1), + }; + if (suite === 'cliff-ramp') { + const leaderboard = await climbCliff({ + adapters, steps: config.steps, signal, async runStage(harness, lanes) { + const relative = join('lanes-' + lanes, harness); + const stageDir = join(suiteDir, relative); + await mkdir(stageDir, { recursive: true }); + const result = await benchmark({ + scenario, adapters: [getAdapter(harness)], output: stageDir, options: { ...settings, lanes }, signal, + }); + const [batch] = result.batches; + return { ...batch, lanes, passed: result.passed, errors: result.errors, report: join(relative, 'report.md') }; + }, + }); + const report = renderCliffLeaderboard(leaderboard); + await Promise.all([ + json(join(suiteDir, 'leaderboard.json'), leaderboard), + writeFile(join(suiteDir, 'leaderboard.md'), report), + ]); + console.log(report); + passed &&= leaderboard.every(row => !row.breakingPoint); + } else { + const result = await benchmark({ scenario, adapters, output: suiteDir, options: settings, signal }); + console.log(overview(adapters.map(adapter => overviewRow( + suite, scenario.source.track, adapter.id, result.summary.find(row => row.harness === adapter.id), + )))); + passed &&= result.passed; + } + } + return passed; +} + async function main(args, signal) { const [command, ...tokens] = args; if (!command || ['-h', '--help', 'help'].includes(command)) { @@ -497,8 +698,11 @@ async function main(args, signal) { const calibrate = command === 'calibrate'; const adapters = calibrate ? [getAdapter('ref-agent')] : csv(values.harnesses, 'harnesses').map(getAdapter); + const maxClusterRssGib = Number(values['max-cluster-rss-gib'] ?? 32); + if (!Number.isFinite(maxClusterRssGib) || maxClusterRssGib <= 0) throw new Error('Invalid --max-cluster-rss-gib'); const options = { - lanes: integer(values.lanes, 'lanes', calibrate ? 16 : 1), + maxClusterRssGib, + lanes: integer(values.lanes, 'lanes', command === 'stress' ? undefined : calibrate ? 16 : 1), runs: integer(values.runs, 'runs', 1), timeoutMs: integer(values['timeout-ms'], 'timeout-ms', 120_000), sigkillAfterMs: integer(values['sigkill-after-ms'], 'sigkill-after-ms', undefined, 0), @@ -511,6 +715,10 @@ async function main(args, signal) { throw new Error('--resume-after-kill requires --sigkill-after-ms'); } if (options.sigkillAfterMs >= options.timeoutMs) throw new Error('--sigkill-after-ms must be less than --timeout-ms'); + if (command === 'stress') { + const config = stressConfig(values); + return withOutput(values.output, output => stress({ config, adapters, output, options, signal })); + } if (command === 'matrix') { const names = values.scenarios === undefined ? builtIns : csv(values.scenarios, 'scenarios'); const scenarios = await Promise.all(names.map(scenarioConfig)); diff --git a/tools/harness-bench/stress.mjs b/tools/harness-bench/stress.mjs new file mode 100644 index 00000000000..d687edb160b --- /dev/null +++ b/tools/harness-bench/stress.mjs @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export const stressSuites = ['deep-grind', 'burst-flood', 'cliff-ramp', 'chaos-storm', 'firehose']; + +export function generateStressScenario(suite, { + turns = { 'deep-grind': 60, 'burst-flood': 6, 'cliff-ramp': 12, 'chaos-storm': 10, firehose: 25 }[suite], + parallel = 16, outputBytes = suite === 'burst-flood' ? 262_144 : 16_384, +} = {}) { + const spec = { + version: 1, scenario: suite, seed: 42, fixture: suite + '-v1', track: 'native', + fixtures: {}, steps: [], faults: [], + }; + const marker = suite.toUpperCase().replaceAll('-', '_') + '_OK'; + const step = action => spec.steps.push({ id: 'turn-' + (spec.steps.length + 1), ...action }); + const file = (path, content) => { + spec.fixtures[path] = { kind: 'file', path, content }; + return { readFile: { path, expectMarker: content.trimEnd() } }; + }; + const shell = (commandId, command) => { + spec.fixtures[commandId] = { kind: 'command', command }; + return { shell: { commandId } }; + }; + const large = () => { + spec.fixtures.output = { kind: 'largeOutput', pattern: 'benchmark 東京🦀 résumé 0123456789abcdef\n' }; + return { largeOutput: { fixture: 'output', bytes: outputBytes } }; + }; + const write = (path, content) => ({ writeFile: { path, content } }); + const edit = (path, old, replacement) => ({ editFile: { path, old, new: replacement } }); + + if (suite === 'burst-flood') { + for (let turn = 1; turn <= turns; turn++) { + const actions = [large()]; + for (let i = 1; i < parallel; i++) { + const id = turn + '-' + i; + if (i % 4 === 1) actions.push(file('burst-input-' + id + '.txt', 'burst-source=' + id + '\n')); + else if (i % 4 === 2) actions.push(write('burst-output-' + id + '.txt', 'burst-result=' + id + '\n')); + else actions.push(shell('probe-' + id, "sleep 0.1 && printf 'burst-probe-" + id + "'")); + } + step({ parallelBatch: actions }); + } + } else if (suite === 'firehose') { + const payload = '東京🦀 café \\"quoted\\" \\n '.repeat(32); + for (let turn = 1; turn <= turns; turn++) { + step(write('firehose-' + turn + '.txt', turn + ' ' + payload + '\n')); + } + } else { + let path; + let current; + for (let turn = 1; turn <= turns; turn++) { + if (suite === 'chaos-storm' && turn === 4) { + step({ badToolCall: { mode: 'wrongType', expectHandling: 'toolError' } }); + } else if (suite === 'chaos-storm' && turn === 5) { + step({ unknownTool: { name: 'bench_unknown_chaos_tool', expectHandling: 'toolError' } }); + } else if (suite === 'deep-grind' && turn % 5 === 0) { + step(large()); + } else if (turn === 1 || turn % (suite === 'deep-grind' ? 5 : 4) === 1) { + path = 'state-' + turn + '.txt'; + current = 'state=seed-' + turn; + step(file(path, current + '\n')); + } else if (turn % (suite === 'deep-grind' ? 5 : 4) === 2) { + current = 'state=written-' + turn; + step(write(path, current + '\n')); + } else if (turn % (suite === 'deep-grind' ? 5 : 4) === 3) { + const next = 'state=edited-' + turn; + const action = edit(path, current, next); + current = next; + // The disconnect publishes one complete call from this batch. + step(suite === 'chaos-storm' && turn === 3 ? { parallelBatch: [ + action, file('chaos-disjoint.txt', 'chaos-disjoint\n'), + ] } : action); + } else { + step(shell('verify-' + turn, "grep -Fx -- '" + current + "' '" + path + "'")); + } + } + } + if (suite === 'chaos-storm') { + spec.faults = [ + { step: 'turn-1', attempt: 1, emit: 'http429' }, + { step: 'turn-2', attempt: 1, emit: 'http503' }, + { step: 'turn-3', attempt: 1, at: 'afterFirstCompleteCall', emit: 'disconnect' }, + ]; + } + const text = suite === 'firehose' ? '東京🦀 café '.repeat(128) + marker : marker; + spec.steps.push({ id: 'done', finalAnswer: { text, expectMarkers: [marker] } }); + return spec; +} + +export async function climbCliff({ adapters, steps, runStage, signal }) { + const rows = adapters.map(({ id }) => ({ harness: id, maxPassedLanes: null, breakingPoint: null, stages: [] })); + for (const lanes of steps) { + for (const row of rows) { + if (signal.aborted) return rows; + if (row.breakingPoint) continue; + const stage = await runStage(row.harness, lanes); + row.stages.push(stage); + if (stage.passed) row.maxPassedLanes = lanes; + else row.breakingPoint = stage; + } + } + return rows.sort((a, b) => (b.maxPassedLanes ?? 0) - (a.maxPassedLanes ?? 0) + || (b.breakingPoint?.lanes ?? Infinity) - (a.breakingPoint?.lanes ?? Infinity) + || a.harness.localeCompare(b.harness)); +} diff --git a/tools/mock-ai/src/main.rs b/tools/mock-ai/src/main.rs index cf7b81a03a4..b41cab82a58 100644 --- a/tools/mock-ai/src/main.rs +++ b/tools/mock-ai/src/main.rs @@ -22,7 +22,7 @@ use maka_mock_ai::{ ControlPlaneConfig, LatencyProfile, MockAiBuilder, MockServerConfig, ProviderDialectProfile, ProxyRecordConfig, RateLimitConfig, RateLimitScope, RecorderMode, ReplayConfig, ReplayMatchMode, ScenarioSchedule, ScenarioSpec, ServerTuning, TlsServerConfig, WatchdogConfig, - WorkloadConfig, builder_from_config, + WirePoisonConfig, WorkloadConfig, builder_from_config, }; use std::net::SocketAddr; use std::path::PathBuf; @@ -90,6 +90,14 @@ struct Cli { #[arg(long, conflicts_with_all = ["preset", "proxy_record", "replay"])] scenario: Option, + /// Unicode scalars per scenario text or tool-argument delta (0 sends one delta). + #[arg(long, default_value_t = 0)] + chunk_chars: usize, + + /// Enable scenario stream framing stress (SSE comments, CRLF and split UTF-8). + #[arg(long)] + wire_poison: bool, + /// Require requests to resolve to a registered benchmark session. #[arg(long)] strict_benchmark: bool, @@ -269,6 +277,14 @@ async fn main() -> Result<(), Box> { Preset::ChaosFuzz => b.workload(WorkloadConfig::chaos_fuzz_preset(cli.seed)), } }; + builder = builder.scenario_streaming( + cli.chunk_chars, + WirePoisonConfig { + split_utf8_boundaries: cli.wire_poison, + crlf_line_endings: cli.wire_poison, + inject_sse_comments: cli.wire_poison, + }, + ); match cli.latency_profile { LatencyPreset::Instant => {} diff --git a/tools/mock-ai/src/routing.rs b/tools/mock-ai/src/routing.rs index 495018bd0ef..727bfb66367 100644 --- a/tools/mock-ai/src/routing.rs +++ b/tools/mock-ai/src/routing.rs @@ -702,8 +702,11 @@ impl RequestClassifier { .or_else(|| self.model_aliases.get(&request.model).cloned()); let system = request.system_text.as_deref().unwrap_or(""); - let is_opencode = harness == Some("opencode"); - let is_claude = harness == Some("claude-code") && route.endpoint == AnthropicMessages; + let is_opencode = harness.is_some_and(|h| h == "opencode" || h.starts_with("opencode-")); + let is_claude = harness + .is_some_and(|h| h == "claude" || h == "claude-code" || h.starts_with("claude-")) + && route.endpoint == AnthropicMessages; + let is_codex = harness.is_some_and(|h| h == "codex" || h.starts_with("codex-")); let last_user = request .messages .last() @@ -726,7 +729,7 @@ impl RequestClassifier { && last_user.contains("Your task is to create a detailed summary of the conversation") && last_user.contains("") && last_user.contains(""); - let codex_summary = harness == Some("codex") + let codex_summary = is_codex && matches!(route.endpoint, ResponsesCreate | ResponsesWs) && request.tools.is_empty() && request.last_user_text().is_some_and(|text| { diff --git a/tools/mock-ai/src/scenario/mod.rs b/tools/mock-ai/src/scenario/mod.rs index a13bdbbc076..ffaf6cc1112 100644 --- a/tools/mock-ai/src/scenario/mod.rs +++ b/tools/mock-ai/src/scenario/mod.rs @@ -38,7 +38,7 @@ use crate::plan::{ }; use crate::protocol::{NormalizedMessageKind, NormalizedRequest, NormalizedRole, Protocol}; use crate::schema_synth::{ - context_overflow_error, overloaded_error, payload_too_large_error, + WirePoisonConfig, context_overflow_error, overloaded_error, payload_too_large_error, previous_response_not_found_error, rate_limit_error, }; @@ -743,7 +743,7 @@ struct SessionData { by_response: HashMap, by_call: HashMap, accepted: HashMap, - checkpoints: HashMap, + checkpoints: HashMap, } struct Publication { @@ -776,6 +776,8 @@ pub struct ScenarioEngine { sessions: Mutex>>, registrations: AtomicU64, validators: ValidatorCache, + chunk_chars: usize, + wire_poison: WirePoisonConfig, } impl ScenarioEngine { @@ -792,9 +794,35 @@ impl ScenarioEngine { sessions: Mutex::new(HashMap::new()), registrations: AtomicU64::new(0), validators: ValidatorCache::default(), + chunk_chars: 0, + wire_poison: WirePoisonConfig::default(), }) } + pub(crate) fn with_streaming( + mut self, + chunk_chars: usize, + wire_poison: WirePoisonConfig, + ) -> Self { + self.chunk_chars = chunk_chars; + self.wire_poison = wire_poison; + self + } + + pub(crate) fn configure_streaming(&self, plan: &mut TurnPlan) { + plan.wire_poison = self.wire_poison.clone(); + if self.chunk_chars != 0 { + for event in &mut plan.events { + match event { + TurnEvent::Text { chunk_chars, .. } + | TurnEvent::Reasoning { chunk_chars, .. } => *chunk_chars = self.chunk_chars, + TurnEvent::ToolCall(call) => call.chunk_chars = self.chunk_chars, + _ => {} + } + } + } + } + pub fn register_session( &self, session_id: &str, @@ -936,15 +964,21 @@ impl ScenarioEngine { request: ScenarioRequest<'_>, ) -> Result { let session = self.session(session_id)?; - self.evaluate(&session, request) + let receipts = request.receipts.iter().map(|receipt| ReceiptInput { + call_id: receipt.call_id, + result: receipt.result, + evidence: ReceiptEvidence::Declared(receipt.outcome), + }); + self.evaluate(&session, request, receipts) } - fn evaluate( + fn evaluate<'a>( &self, session: &Session, request: ScenarioRequest<'_>, + receipts: impl IntoIterator>, ) -> Result { - let receipts = prepare_receipts(request.receipts)?; + let receipts = prepare_receipts(receipts)?; let constraint_digest = digest(&( request.catalog.constraint_digest(request.tool_choice), request.allow_parallel_tools, @@ -1041,6 +1075,7 @@ impl ScenarioEngine { plan }; plan.response_id = Some(committed.decision.response_id.clone()); + self.configure_streaming(&mut plan); return Ok(ScenarioEvaluation { decision: committed.decision, attempt: committed.attempt, @@ -1346,7 +1381,7 @@ impl ScenarioEngine { &self, decision: &IssuedDecision, index: usize, - receipt: ToolReceipt<'_>, + receipt: ReceiptInput<'_>, ) -> Result<(), ScenarioError> { use CanonicalAction as Action; let step = decision.recipe.step; @@ -1356,35 +1391,54 @@ impl ScenarioEngine { call_id: call.call_id.clone(), reason, }; - let mut code_results = None; - let code_mode = matches!(&decision.recipe.kind, PlanKind::Tools(bindings) if bindings[index].is_code_mode()); - for (index, &slot) in call.slots.iter().enumerate() { - let action = &actions[slot]; - let expected = match action { - Action::BadToolCall { - expect_handling, .. + let expected = match &self.spec.steps[step].action { + Action::BadToolCall { + expect_handling, .. + } + | Action::UnknownTool { + expect_handling, .. + } => { + if expect_handling.runner_observation().is_some() { + return Err(fail("expected a runner observation".into())); } - | Action::UnknownTool { - expect_handling, .. - } => { - if expect_handling.runner_observation().is_some() { - return Err(fail(format!("slot {slot}: expected a runner observation"))); - } + ReceiptOutcome::ToolError + } + _ => ReceiptOutcome::Success, + }; + let outcome = match receipt.evidence { + ReceiptEvidence::Declared(outcome) => outcome, + ReceiptEvidence::Wire(is_error) => { + // Plain text can be file contents or stdout for successful actions. + let infer_diagnostics = is_error.is_none() && expected == ReceiptOutcome::ToolError; + if is_error == Some(true) || tool_content_failed(receipt.result, infer_diagnostics) + { ReceiptOutcome::ToolError + } else { + ReceiptOutcome::Success } - _ => ReceiptOutcome::Success, - }; - if receipt.outcome != expected { - return Err(fail(format!( - "slot {slot}: expected {expected:?}, got {:?}", - receipt.outcome - ))); } - let result = if code_mode { - let results = code_results.get_or_insert_with(|| code_results_from(receipt.result)); + }; + if outcome != expected { + return Err(fail(format!("expected {expected:?}, got {outcome:?}"))); + } + if expected == ReceiptOutcome::ToolError { + return Ok(()); + } + + let code_mode = matches!(&decision.recipe.kind, PlanKind::Tools(bindings) if bindings[index].is_code_mode()); + let code_results = if code_mode { + Some( + code_results_from(receipt.result) + .ok_or_else(|| fail("missing Code Mode results".into()))?, + ) + } else { + None + }; + for (index, &slot) in call.slots.iter().enumerate() { + let action = &actions[slot]; + let result = if let Some(results) = &code_results { let result = results - .as_ref() - .and_then(|results| results.get(index)) + .get(index) .ok_or_else(|| fail(format!("slot {slot}: missing Code Mode result")))?; if result["slot"].as_u64() != Some(slot as u64) || result.get("result").is_none() { return Err(fail(format!("slot {slot}: invalid Code Mode result"))); @@ -1393,7 +1447,9 @@ impl ScenarioEngine { } else { receipt.result }; - if expected == ReceiptOutcome::Success && result_failed(result) { + if (code_mode || matches!(receipt.evidence, ReceiptEvidence::Declared(_))) + && tool_content_failed(result, false) + { return Err(fail(format!("slot {slot}: tool reported failure"))); } if let Action::ReadFile { expect_marker, .. } = action @@ -1411,6 +1467,16 @@ impl ScenarioEngine { fn result_failed(result: &Value) -> bool { result["kind"] == "failed" || result["is_error"] == true + || result["handling"] == "tool_error" + || result["status"] == "error" + || result["ok"] == false + || result["state"] == "interrupted" + || result["error"] + .as_object() + .is_some_and(|error| !error.is_empty()) + || result["error"] + .as_str() + .is_some_and(|error| !error.trim().is_empty()) || [ &result["exit_code"], &result["exitCode"], @@ -1420,6 +1486,48 @@ fn result_failed(result: &Value) -> bool { .any(|code| code.as_i64().is_some_and(|exit| exit != 0)) } +fn tool_content_failed(result: &Value, infer_diagnostics: bool) -> bool { + let text_failed = |text: &str| { + let text = text.trim(); + if text.starts_with('{') + && let Ok(parsed) = serde_json::from_str(text) + { + return result_failed(&parsed); + } + if !infer_diagnostics { + return false; + } + let text = text.to_ascii_lowercase(); + [ + "error:", + "invalid", + "unknown tool", + "not found", + "validation", + "schema", + "expected ", + "missing required", + "tool failed", + "type error", + "cannot ", + "rejected", + "failed to", + ] + .iter() + .any(|diagnostic| text.contains(diagnostic)) + }; + match result { + Value::String(text) => text_failed(text), + Value::Array(items) => items.iter().any(|item| { + matches!( + item["type"].as_str(), + Some("text" | "input_text" | "output_text") + ) && item["text"].as_str().is_some_and(text_failed) + }), + _ => result_failed(result), + } +} + fn code_results_from(result: &Value) -> Option> { match result { Value::String(text) => serde_json::from_str::>(text) @@ -1543,19 +1651,32 @@ fn after_first_call(mut plan: TurnPlan, fault: FaultKind) -> TurnPlan { plan } +#[derive(Clone, Copy)] +struct ReceiptInput<'a> { + call_id: &'a str, + result: &'a Value, + evidence: ReceiptEvidence, +} + +#[derive(Clone, Copy, Hash)] +enum ReceiptEvidence { + Declared(ReceiptOutcome), + Wire(Option), +} + #[derive(Clone, Copy)] struct PreparedReceipt<'a> { - receipt: ToolReceipt<'a>, + receipt: ReceiptInput<'a>, digest: u64, } fn prepare_receipts<'a>( - receipts: &[ToolReceipt<'a>], + receipts: impl IntoIterator>, ) -> Result>, ScenarioError> { let mut entries = HashMap::new(); let mut unique = Vec::new(); - for &receipt in receipts { - let digest = digest(&(receipt.result, receipt.outcome)); + for receipt in receipts { + let digest = digest(&(receipt.result, receipt.evidence)); if let Some(previous) = entries.insert(receipt.call_id, digest) { if previous != digest { return Err(ScenarioError::ChangedReceipt(receipt.call_id.into())); @@ -1570,7 +1691,7 @@ fn prepare_receipts<'a>( struct NewReceipt<'a> { decision: Arc, slot: usize, - receipt: ToolReceipt<'a>, + receipt: ReceiptInput<'a>, digest: u64, } @@ -1672,11 +1793,14 @@ impl SessionData { let mut checkpoint_accepted = false; if let Some(checkpoint) = request.checkpoint { - let (revision, marker, kind) = self + let (revision, marker, mode) = self .checkpoints .get(checkpoint.checkpoint_id) .ok_or(ScenarioError::InvalidCheckpoint)?; - if marker != checkpoint.proof_marker || *kind != checkpoint.kind { + let accepts_kind = CheckpointEvidenceKind::from(*mode) == checkpoint.kind + || (matches!(mode, CompactionMode::ContextOverflow { .. }) + && checkpoint.kind == CheckpointEvidenceKind::NativeCompaction); + if marker != checkpoint.proof_marker || !accepts_kind { return Err(ScenarioError::InvalidCheckpoint); } if request.parent_response_id.is_none() { @@ -1803,7 +1927,7 @@ impl SessionData { let evidence_kind = (*mode).into(); self.checkpoints.insert( checkpoint_id.clone(), - (revision, proof_marker.clone(), evidence_kind), + (revision, proof_marker.clone(), *mode), ); ScenarioSessionState::AwaitingCheckpoint(PendingCheckpoint { revision, @@ -1975,7 +2099,6 @@ impl ScenarioEngine { _ => None, } }; - input.receipts = &receipts; input.checkpoint = pending_summary .as_ref() .and_then(|pending| client_summary_receipt(request, pending)) @@ -1997,7 +2120,7 @@ impl ScenarioEngine { input.allow_parallel_tools = request.options.parallel_tool_calls.unwrap_or(true); input.native_compaction = request.protocol.is_responses() || request.anthropic_compaction_enabled; - self.evaluate(session, input) + self.evaluate(session, input, receipts) } } @@ -2038,26 +2161,21 @@ fn client_summary_receipt<'a>( }) } -type WireEvidence<'a> = (Vec>, Option>); +type WireEvidence<'a> = (Vec>, Option>); fn wire_evidence<'a>(request: &'a NormalizedRequest) -> Result, ScenarioError> { let mut receipts = Vec::new(); let mut checkpoint = None; let items = |key: &str| request.raw_body[key].as_array().into_iter().flatten(); - let mut receipt = |id: &'a Value, result: &'a Value, is_error: bool| { + let mut receipt = |id: &'a Value, result: &'a Value, is_error: &Value| { let id = id .as_str() .filter(|id| !id.is_empty()) .ok_or_else(|| ScenarioError::UnknownCall(String::new()))?; - let outcome = if is_error || result_failed(result) || result["handling"] == "tool_error" { - ReceiptOutcome::ToolError - } else { - ReceiptOutcome::Success - }; - receipts.push(ToolReceipt { + receipts.push(ReceiptInput { call_id: id, result, - outcome, + evidence: ReceiptEvidence::Wire(is_error.as_bool()), }); Ok::<_, ScenarioError>(()) }; @@ -2067,11 +2185,9 @@ fn wire_evidence<'a>(request: &'a NormalizedRequest) -> Result, .flat_map(|message| message["content"].as_array().into_iter().flatten()) { match block["type"].as_str() { - Some("tool_result") => receipt( - &block["tool_use_id"], - &block["content"], - block["is_error"] == true, - )?, + Some("tool_result") => { + receipt(&block["tool_use_id"], &block["content"], &block["is_error"])? + } Some("compaction") => { if let Some((id, marker)) = block["content"].as_str().and_then(|s| s.split_once(' ')) @@ -2090,18 +2206,14 @@ fn wire_evidence<'a>(request: &'a NormalizedRequest) -> Result, } Protocol::OpenaiChatCompletions => { for item in items("messages").filter(|item| item["role"] == "tool") { - receipt( - &item["tool_call_id"], - &item["content"], - item["is_error"] == true, - )?; + receipt(&item["tool_call_id"], &item["content"], &item["is_error"])?; } } Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => { for item in items("input") { match item["type"].as_str() { Some("function_call_output" | "custom_tool_call_output") => { - receipt(&item["call_id"], &item["output"], item["is_error"] == true)?; + receipt(&item["call_id"], &item["output"], &item["is_error"])?; } Some("compaction") => { if let (Some(id), Some(marker)) = ( @@ -2918,6 +3030,208 @@ mod tests { ); } + #[test] + fn wire_tool_errors_advance_bad_arguments_and_unknown_tools() { + use Protocol::*; + let cases = [ + ( + OpenaiChatCompletions, + json!(r#"{"kind":"failed","message":"bad input"}"#), + false, + ), + ( + OpenaiChatCompletions, + json!(r#"{"error":{"message":"bad input"}}"#), + false, + ), + ( + OpenaiChatCompletions, + json!(r#"{"error":"bad input"}"#), + false, + ), + (OpenaiChatCompletions, json!(r#"{"status":"error"}"#), false), + (OpenaiChatCompletions, json!(r#"{"ok":false}"#), false), + (OpenaiChatCompletions, json!(r#"{"is_error":true}"#), false), + ( + OpenaiChatCompletions, + json!("Invalid arguments: Expected string, received number"), + false, + ), + ( + OpenaiChatCompletions, + json!(r#"{"state":"interrupted","diagnostic":"cell aborted"}"#), + false, + ), + ( + OpenaiResponsesHttp, + json!([{"type":"input_text","text":"Tool Read not found"}]), + false, + ), + ( + AnthropicMessages, + json!([{"type":"text","text":"execution stopped"}]), + true, + ), + ]; + for (protocol, output, explicit_error) in cases { + let engine = engine( + spec() + .with_step( + "bad", + CanonicalAction::BadToolCall { + mode: BadToolMode::MissingRequired, + expect_handling: FailureHandling::ToolError, + }, + ) + .with_step( + "unknown", + CanonicalAction::UnknownTool { + name: "unlisted_tool".into(), + expect_handling: FailureHandling::ToolError, + }, + ) + .with_step("done", final_answer()), + ); + let parameters = json!({ + "type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"] + }); + let body = match protocol { + OpenaiChatCompletions => json!({"tools": [{"type": "function", + "function": {"name": "exec", "parameters": parameters}}]}), + AnthropicMessages => { + json!({"tools": [{"name": "exec", "input_schema": parameters}]}) + } + _ => { + json!({"tools": [{"type": "function", "name": "exec", "parameters": parameters}]}) + } + }; + let evaluate = |body| { + let request = normalize(protocol, Transport::Http, body); + engine.evaluate_normalized("session-a", &request) + }; + let first = evaluate(body).unwrap_or_else(|e| panic!("{protocol:?}: {e}")); + let continuation = |id: &str, result: &Value, is_error: Option| { + let with_flag = |mut item: Value| { + if let Some(is_error) = is_error { + item["is_error"] = json!(is_error); + } + item + }; + match protocol { + OpenaiChatCompletions => json!({"messages": [with_flag(json!({ + "role": "tool", "tool_call_id": id, "content": result + }))]}), + AnthropicMessages => { + json!({"messages": [{"role": "user", "content": [with_flag(json!({ + "type": "tool_result", "tool_use_id": id, "content": result + }))]}]}) + } + _ => json!({"input": [with_flag(json!({ + "type": "function_call_output", "call_id": id, "output": result + }))]}), + } + }; + let first_id = &first.decision.calls[0].call_id; + assert!(matches!( + evaluate(continuation(first_id, &json!("all good"), None)), + Err(ScenarioError::UnexpectedReceipt { .. }) + )); + assert!(matches!( + evaluate(continuation( + first_id, + &json!("Error: missing required argument"), + Some(false) + )), + Err(ScenarioError::UnexpectedReceipt { .. }) + )); + let flag = explicit_error.then_some(true); + let second = evaluate(continuation(first_id, &output, flag)) + .unwrap_or_else(|e| panic!("{protocol:?} {output}: {e}")); + assert_eq!(calls(&second.plan)[0].name, "unlisted_tool"); + let done = evaluate(continuation( + &second.decision.calls[0].call_id, + &output, + flag, + )) + .unwrap(); + assert!( + matches!(&done.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + } + + #[test] + fn wire_read_receipts_require_the_marker_and_allow_diagnostics_in_file_contents() { + let engine = engine( + spec() + .with_step("read", read("a.txt", "alpha")) + .with_step("done", final_answer()), + ); + let evaluate = |body| { + let request = normalize(Protocol::OpenaiChatCompletions, Transport::Http, body); + engine.evaluate_normalized("session-a", &request) + }; + let issued = + evaluate(json!({"tools": [{"type": "function", "function": read_decl()}]})).unwrap(); + let follow = |content| { + evaluate(json!({"messages": [{ + "role": "tool", "tool_call_id": issued.decision.calls[0].call_id, "content": content + }]})) + }; + for bad in [r#"{"error":"alpha file not found"}"#, "another file"] { + assert!(matches!( + follow(bad), + Err(ScenarioError::UnexpectedReceipt { .. }) + )); + } + let done = follow("Error: schema validation example for alpha\n").unwrap(); + assert!( + matches!(&done.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + + #[test] + fn overflow_accepts_returned_responses_compaction_items() { + let engine = engine( + spec() + .with_step( + "compact", + CanonicalAction::TriggerCompaction { + mode: CompactionMode::ContextOverflow { + actual_bytes: 900_000, + limit_bytes: 800_000, + }, + proof_marker: "overflow-proof".into(), + }, + ) + .with_step("done", final_answer()), + ); + let evaluate = |body| { + let request = normalize(Protocol::OpenaiResponsesHttp, Transport::Http, body); + engine.evaluate_normalized("session-a", &request) + }; + let overflow = evaluate(json!({"input": "start"})).unwrap(); + assert!( + matches!(&overflow.plan.events[..], [TurnEvent::HttpError(error)] if error.status == 400) + ); + let (_, checkpoint) = engine.compaction_output("session-a").unwrap(); + let follow = |encrypted_content| { + evaluate(json!({"input": [ + {"type": "compaction", "id": checkpoint.id, "encrypted_content": encrypted_content}, + {"role": "user", "content": "continue"} + ]})) + }; + assert!(matches!( + follow("mock:other"), + Err(ScenarioError::InvalidCheckpoint) + )); + let done = follow(&checkpoint.encrypted_content).unwrap(); + assert_eq!(done.adopted_checkpoint_id, Some(checkpoint.id)); + assert!( + matches!(&done.plan.events[0], TurnEvent::Text { text, .. } if text == "proof: files complete") + ); + } + #[test] fn validates_serialized_specs_and_parallel_conflicts() { let spec = spec() diff --git a/tools/mock-ai/src/schema_synth.rs b/tools/mock-ai/src/schema_synth.rs index 076f0ffe1c0..317912483ff 100644 --- a/tools/mock-ai/src/schema_synth.rs +++ b/tools/mock-ai/src/schema_synth.rs @@ -843,33 +843,39 @@ pub fn poison_sse_frame(frame: String, cfg: &WirePoisonConfig, frame_index: usiz chunks } -/// Build an HTTP 400 `context_length_exceeded` response recognized by Maka's `error/overflow.rs`. +/// Build an HTTP 400 using the provider's context overflow error shape. pub fn context_overflow_error( protocol: Protocol, actual_bytes: usize, limit_bytes: usize, ) -> HttpErrorSpec { - let actual_tokens = (actual_bytes / 4).max(1); - let max_tokens = (limit_bytes / 4).max(1); + let limit_tokens = (limit_bytes / 4).max(1); + let actual_tokens = (actual_bytes / 4).max(limit_tokens + 1024); let body = match protocol { Protocol::AnthropicMessages => json!({ "type": "error", "error": { "type": "invalid_request_error", - "message": format!("prompt is too long: {actual_tokens} tokens > {max_tokens} maximum") + "message": format!("prompt is too long: {actual_tokens} tokens > {limit_tokens} maximum") } }), - Protocol::OpenaiChatCompletions - | Protocol::OpenaiResponsesHttp - | Protocol::OpenaiResponsesWs => json!({ + Protocol::OpenaiChatCompletions => json!({ "error": { "type": "invalid_request_error", "code": "context_length_exceeded", + "param": "messages", "message": format!( - "This model's maximum context length is {max_tokens} tokens. However, your messages resulted in {actual_tokens} tokens." + "This model's maximum context length is {limit_tokens} tokens. However, your messages resulted in {actual_tokens} tokens. Please reduce the length of the messages." ) } }), + Protocol::OpenaiResponsesHttp | Protocol::OpenaiResponsesWs => json!({ + "error": { + "type": "invalid_request_error", + "code": "context_length_exceeded", + "message": "Your input exceeds the context window of this model. Please adjust your input and try again." + } + }), }; HttpErrorSpec::raw(400, body) } @@ -1056,24 +1062,67 @@ mod tests { ); } + #[test] + fn context_overflow_uses_the_provider_error_body() { + for (protocol, expected) in [ + ( + Protocol::AnthropicMessages, + json!({ + "type": "error", + "error": { + "type": "invalid_request_error", + "message": "prompt is too long: 201024 tokens > 200000 maximum" + } + }), + ), + ( + Protocol::OpenaiChatCompletions, + json!({ + "error": { + "type": "invalid_request_error", + "code": "context_length_exceeded", + "param": "messages", + "message": "This model's maximum context length is 200000 tokens. However, your messages resulted in 201024 tokens. Please reduce the length of the messages." + } + }), + ), + ( + Protocol::OpenaiResponsesHttp, + json!({ + "error": { + "type": "invalid_request_error", + "code": "context_length_exceeded", + "message": "Your input exceeds the context window of this model. Please adjust your input and try again." + } + }), + ), + ( + Protocol::OpenaiResponsesWs, + json!({ + "error": { + "type": "invalid_request_error", + "code": "context_length_exceeded", + "message": "Your input exceeds the context window of this model. Please adjust your input and try again." + } + }), + ), + ] { + let overflow = context_overflow_error(protocol, 800_004, 800_000); + assert_eq!(overflow.status, 400); + assert_eq!(overflow.raw_body.unwrap(), expected); + } + let overflow = context_overflow_error(Protocol::AnthropicMessages, 1_000_000, 800_000); + assert_eq!( + overflow.raw_body.unwrap()["error"]["message"], + "prompt is too long: 250000 tokens > 200000 maximum" + ); + } + #[test] fn transport_size_rejection_is_distinct_from_model_context_overflow() { let openai = Protocol::OpenaiResponsesHttp; let anthropic = Protocol::AnthropicMessages; for protocol in [openai, anthropic] { - let overflow = context_overflow_error(protocol, 4096, 2048); - assert_eq!(overflow.status, 400); - let body = overflow.raw_body.unwrap(); - assert_eq!(body["error"]["type"], "invalid_request_error"); - if protocol == openai { - assert_eq!(body["error"]["code"], "context_length_exceeded"); - } else { - assert_eq!(body["type"], "error"); - assert_eq!( - body["error"]["message"], - "prompt is too long: 1024 tokens > 512 maximum" - ); - } let too_large = payload_too_large_error(protocol); assert_eq!(too_large.status, 413); assert_eq!( diff --git a/tools/mock-ai/src/server.rs b/tools/mock-ai/src/server.rs index ee3c495ca62..1f4d909b408 100644 --- a/tools/mock-ai/src/server.rs +++ b/tools/mock-ai/src/server.rs @@ -50,6 +50,7 @@ use crate::routing::{ #[cfg(feature = "rules")] use crate::rules::{ConfigError, RuleEngine, RuleSpec}; use crate::scenario::{ScenarioEngine, ScenarioSpec}; +use crate::schema_synth::WirePoisonConfig; #[cfg(feature = "tls")] use crate::tls::TlsServerConfig; use crate::watchdog::{ @@ -550,7 +551,7 @@ impl ServerState { } if let RequestUse::Compact(kind) = purpose { let output = self.compaction(req, Some(attempt)); - let plan = match kind { + let mut plan = match kind { CompactKind::ClientSummary => { attempt.0.data.lock().unwrap().summary_checkpoint = Some(output.id); attempt.buffering(output.summary.len()); @@ -558,6 +559,9 @@ impl ServerState { } _ => TurnPlan::new().push_compaction(output), }; + if let Some(scenario) = &self.scenario { + scenario.configure_streaming(&mut plan); + } return Ok(TurnDecision::Plan(plan)); } if let Some(scenario) = &self.scenario { @@ -1571,6 +1575,7 @@ pub struct MockAiBuilder { custom_route: Option, interactive_rx: Option>, scenario: Option, + scenario_streaming: (usize, WirePoisonConfig), strict_benchmark: bool, dialect: Option, classifier: RequestClassifier, @@ -1607,6 +1612,7 @@ impl MockAiBuilder { custom_route: None, interactive_rx: None, scenario: None, + scenario_streaming: (0, WirePoisonConfig::default()), strict_benchmark: false, dialect: None, classifier: RequestClassifier::default(), @@ -1691,6 +1697,12 @@ impl MockAiBuilder { self } + /// Configure chunking and wire framing for scenario responses. + pub fn scenario_streaming(mut self, chunk_chars: usize, poison: WirePoisonConfig) -> Self { + self.scenario_streaming = (chunk_chars, poison); + self + } + pub fn strict_benchmark(mut self, enabled: bool) -> Self { self.strict_benchmark = enabled; self @@ -1805,9 +1817,13 @@ impl MockAiBuilder { )); } let strict_benchmark = self.strict_benchmark || self.scenario.is_some(); + let (chunk_chars, wire_poison) = self.scenario_streaming; let scenario = self .scenario - .map(|spec| ScenarioEngine::new(spec, "mock-ai")) + .map(|spec| { + ScenarioEngine::new(spec, "mock-ai") + .map(|engine| engine.with_streaming(chunk_chars, wire_poison)) + }) .transpose() .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; if strict_benchmark { From 32cb5d37ed12c0a63fba2474339fc8ead78a599d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9CM4n5ter=E2=80=9D?= Date: Sat, 28 Nov 2026 16:02:56 +0800 Subject: [PATCH 4/4] fix(harness-bench): align 1M context window across adapters and support ApplyPatch file overwrites --- tools/harness-bench/adapters.mjs | 6 ++--- tools/mock-ai/src/scenario/tools.rs | 40 +++++++++++++++++++++-------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/tools/harness-bench/adapters.mjs b/tools/harness-bench/adapters.mjs index 22f98994036..345efd34699 100644 --- a/tools/harness-bench/adapters.mjs +++ b/tools/harness-bench/adapters.mjs @@ -645,7 +645,7 @@ for (const { logicalLane: id, model, baseUrl, keyEnv } of lanes) { models: [{ id: model, name: model, api: 'openai-completions', provider: id, baseUrl, reasoning: false, input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, - contextWindow: 128000, maxTokens: 8192, + contextWindow: 1047576, maxTokens: 32768, }], })); } @@ -764,7 +764,7 @@ const zcode = adapter({ }, }] }, modelConfigRules: { - providerModelRules: [{ ...selection, config: { enabled: true, properties: { contextWindow: 128000 } } }], + providerModelRules: [{ ...selection, config: { enabled: true, properties: { contextWindow: 1047576 } } }], manualProviderModelRules: [], }, defaultModelSelection: selection, @@ -789,7 +789,7 @@ function kimiAdapter(id, protocol, type) { 'default_model = "mock"', 'telemetry = false', '[providers.mock]', `type = ${toml(type)}`, `base_url = ${toml(type === 'anthropic' ? ctx.base : ctx.v1)}`, `api_key = ${toml(ctx.apiKey)}`, '[models.mock]', 'provider = "mock"', - `model = ${toml(ctx.model)}`, 'max_context_size = 128000', '', + `model = ${toml(ctx.model)}`, 'max_context_size = 1047576', '', ].join('\n')); if (ctx.mcp) await jsonFile(join(home, 'mcp.json'), { mcpServers: { bench: { transport: 'stdio', ...ctx.mcp, deferred: false } }, diff --git a/tools/mock-ai/src/scenario/tools.rs b/tools/mock-ai/src/scenario/tools.rs index bef60dfbd00..a8c47b88452 100644 --- a/tools/mock-ai/src/scenario/tools.rs +++ b/tools/mock-ai/src/scenario/tools.rs @@ -692,7 +692,7 @@ impl Binding { use_patch, } = self.encoding { - let code = code_mode_source(actions, use_patch)?; + let code = code_mode_source(workspace, actions, use_patch)?; return Ok(if freeform { CallPayload::Freeform(code) } else { @@ -736,7 +736,7 @@ impl Binding { "Read fixture file", )?, (Encoding::Patch(key), ToolAction::Write { .. } | ToolAction::Edit { .. }) => { - let patch = patch_text(action)?; + let patch = patch_text(workspace, action)?; let Some(key) = key else { return Ok(CallPayload::Freeform(patch)); }; @@ -948,14 +948,19 @@ fn code_mode(tool: &ToolDeclaration) -> Option { } } -fn code_mode_source(actions: &[ToolAction<'_>], use_patch: bool) -> Result { +fn code_mode_source( + workspace: &Path, + actions: &[ToolAction<'_>], + use_patch: bool, +) -> Result { let mut code = String::from("text(JSON.stringify(await Promise.all([\n"); for (slot, action) in actions.iter().enumerate() { let (tool, input) = match *action { ToolAction::Read { path } => ("Read", json!({ "path": path })), - ToolAction::Write { .. } | ToolAction::Edit { .. } if use_patch => { - ("ApplyPatch", json!({ "patch": patch_text(*action)? })) - } + ToolAction::Write { .. } | ToolAction::Edit { .. } if use_patch => ( + "ApplyPatch", + json!({ "patch": patch_text(workspace, *action)? }), + ), ToolAction::Write { path, content } => { ("Write", json!({ "path": path, "content": content })) } @@ -977,9 +982,18 @@ fn code_mode_source(actions: &[ToolAction<'_>], use_patch: bool) -> Result) -> Result { +fn patch_text(workspace: &Path, action: ToolAction<'_>) -> Result { + let existing_write = match action { + ToolAction::Write { path, .. } => std::fs::read_to_string(workspace.join(path)).ok(), + _ => None, + }; let preserves_line_endings = match action { - ToolAction::Write { content, .. } => content.is_empty() || content.ends_with('\n'), + ToolAction::Write { content, .. } => { + (content.is_empty() || content.ends_with('\n')) + && existing_write + .as_deref() + .is_none_or(|old| old.is_empty() || old.ends_with('\n')) + } ToolAction::Edit { hunk, .. } => { hunk.ends_with_newline && (hunk.after.is_empty() || hunk.after.ends_with('\n')) } @@ -994,8 +1008,14 @@ fn patch_text(action: ToolAction<'_>) -> Result { let mut patch = String::from("*** Begin Patch\n"); match action { ToolAction::Write { path, content } => { - writeln!(patch, "*** Add File: {path}").expect("writing to String"); - patch_lines(&mut patch, '+', content); + if let Some(old) = existing_write.as_deref() { + writeln!(patch, "*** Update File: {path}\n@@").expect("writing to String"); + patch_lines(&mut patch, '-', old); + patch_lines(&mut patch, '+', content); + } else { + writeln!(patch, "*** Add File: {path}").expect("writing to String"); + patch_lines(&mut patch, '+', content); + } } ToolAction::Edit { path, hunk, .. } => { writeln!(patch, "*** Update File: {path}\n@@").expect("writing to String");