|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import { get, type ClientRequest } from 'node:http'; |
| 3 | +import { performance } from 'node:perf_hooks'; |
| 4 | +import { setTimeout as sleep } from 'node:timers/promises'; |
| 5 | +import { parseArgs } from 'node:util'; |
| 6 | +import { Worker } from 'node:worker_threads'; |
| 7 | +import { AbortableWait } from '../src/core/abortable-wait.js'; |
| 8 | +import type { RunEvent } from '../src/core/contracts.js'; |
| 9 | +import { sha } from '../src/core/util.js'; |
| 10 | +import { createGateway } from '../src/gateway/server.js'; |
| 11 | +import { streamSlots } from '../src/gateway/stream-slots.js'; |
| 12 | +import { makeBundle } from '../src/lang/bundle.js'; |
| 13 | +import { agent, FixtureModel, setup, token, waitFor } from '../test/helpers.js'; |
| 14 | +import type { ReadProbeReport } from './caller-cancel-read-probe.js'; |
| 15 | + |
| 16 | +const { values } = parseArgs({ |
| 17 | + options: { |
| 18 | + clients: { type: 'string', default: '8' }, |
| 19 | + trials: { type: 'string', default: '3' }, |
| 20 | + }, |
| 21 | +}); |
| 22 | +const clients = Number(values.clients); |
| 23 | +const trials = Number(values.trials); |
| 24 | +assert.ok(Number.isInteger(clients) && clients >= 1 && clients <= 24); |
| 25 | +assert.ok(Number.isInteger(trials) && trials >= 1 && trials <= 10); |
| 26 | +const text = 'x\u4e2d\u6587\u{1f600}\n"\\\u0001'.repeat(110_000); |
| 27 | +const chunk = 256; |
| 28 | +const tail = 250; |
| 29 | +const pauseMs = 650; |
| 30 | + |
| 31 | +function healthSummary(report: ReadProbeReport, start: number, end: number) { |
| 32 | + const samples = report.samples.filter((x) => x.at >= start && x.at < end); |
| 33 | + const durations = samples |
| 34 | + .filter((x) => x.ok) |
| 35 | + .map((x) => x.ms) |
| 36 | + .sort((a, b) => a - b); |
| 37 | + return { |
| 38 | + count: samples.length, |
| 39 | + failures: samples.length - durations.length, |
| 40 | + missed_starts: report.missedStarts.filter((at) => at >= start && at < end).length, |
| 41 | + p95_ms: durations[Math.ceil(durations.length * 0.95) - 1] ?? null, |
| 42 | + max_ms: durations.at(-1) ?? null, |
| 43 | + }; |
| 44 | +} |
| 45 | + |
| 46 | +async function trial() { |
| 47 | + const driver = new FixtureModel(); |
| 48 | + driver.call = async (_agent, _messages, _signal, emit) => { |
| 49 | + driver.calls++; |
| 50 | + for (let i = 0; i < text.length; i += chunk) emit(text.slice(i, i + chunk)); |
| 51 | + return { |
| 52 | + text, |
| 53 | + calls: [], |
| 54 | + finish: 'stop', |
| 55 | + usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 }, |
| 56 | + }; |
| 57 | + }; |
| 58 | + const s = await setup(driver); |
| 59 | + let next: Awaited<ReturnType<typeof createGateway>> | undefined; |
| 60 | + let worker: Worker | undefined; |
| 61 | + const requests: ClientRequest[] = []; |
| 62 | + try { |
| 63 | + const model = 'agent/slow-replay-fixture'; |
| 64 | + s.store.publish('owner', makeBundle(agent({ id: model }))); |
| 65 | + const finished = await s.request('POST', '/v1/responses', { model, input: 'fixture' }); |
| 66 | + assert.equal(finished.statusCode, 200); |
| 67 | + const run = String(finished.json().id); |
| 68 | + assert.equal(sha(finished.json().output[0].content[0].text), sha(text)); |
| 69 | + const after = Number( |
| 70 | + s.store |
| 71 | + .prepare( |
| 72 | + "SELECT id FROM events WHERE run_id=? AND type='response.output_text.delta' ORDER BY id DESC LIMIT 1 OFFSET ?", |
| 73 | + ) |
| 74 | + .get(run, tail)!.id, |
| 75 | + ); |
| 76 | + await s.app.close(); |
| 77 | + next = await createGateway(s.config, s.runtime); |
| 78 | + const gw = next; |
| 79 | + const base = await gw.listen(); |
| 80 | + const principal = gw.auth.authenticate('Bearer ' + token); |
| 81 | + const url = `${base}/v1/runs/${run}/events`; |
| 82 | + assert.equal(new URL(url).hostname, '127.0.0.1'); |
| 83 | + |
| 84 | + const queued = Array.from({ length: clients }, () => 0); |
| 85 | + gw.app.server.prependListener('request', (req, res) => { |
| 86 | + const raw = req.headers['x-fixture-client']; |
| 87 | + if (typeof raw !== 'string') return; |
| 88 | + const index = Number(raw); |
| 89 | + const write = res.write; |
| 90 | + res.write = function (this: typeof res, ...args: unknown[]) { |
| 91 | + const result = Reflect.apply(write, this, args) as boolean; |
| 92 | + queued[index] = Math.max(queued[index]!, this.writableLength); |
| 93 | + return result; |
| 94 | + }; |
| 95 | + }); |
| 96 | + const recent = gw.store.recentHistory.bind(gw.store); |
| 97 | + const replay = gw.store.replayHistory?.bind(gw.store); |
| 98 | + const ranges: [number, number][] = []; |
| 99 | + let historyMs = 0, |
| 100 | + snapshotReads = 0; |
| 101 | + gw.store.recentHistory = (...args) => { |
| 102 | + const start = performance.now(); |
| 103 | + const result = recent(...args); |
| 104 | + historyMs += performance.now() - start; |
| 105 | + if (result.length) ranges.push([result[0]!.id, result.at(-1)!.id]); |
| 106 | + return result; |
| 107 | + }; |
| 108 | + if (replay) |
| 109 | + gw.store.replayHistory = (...args) => { |
| 110 | + const start = performance.now(); |
| 111 | + const result = replay(...args); |
| 112 | + historyMs += performance.now() - start; |
| 113 | + const events = result.events; |
| 114 | + if (events.length) ranges.push([events[0]!.id, events.at(-1)!.id]); |
| 115 | + return result; |
| 116 | + }; |
| 117 | + const snapshot = gw.store.run.bind(gw.store); |
| 118 | + gw.store.run = (...args) => { |
| 119 | + snapshotReads++; |
| 120 | + return snapshot(...args); |
| 121 | + }; |
| 122 | + worker = new Worker(new URL('./caller-cancel-read-probe.js', import.meta.url), { |
| 123 | + execArgv: [], |
| 124 | + workerData: { url: base + '/health', token }, |
| 125 | + }); |
| 126 | + const ready = Promise.withResolvers<void>(); |
| 127 | + const report = Promise.withResolvers<ReadProbeReport>(); |
| 128 | + worker.on('message', (message: 'ready' | ReadProbeReport) => { |
| 129 | + if (message === 'ready') ready.resolve(); |
| 130 | + else report.resolve(message); |
| 131 | + }); |
| 132 | + worker.once('error', (error) => { |
| 133 | + ready.reject(error); |
| 134 | + report.reject(error); |
| 135 | + }); |
| 136 | + void report.promise.catch(() => {}); |
| 137 | + await new AbortableWait(ready.promise).wait(AbortSignal.timeout(10_000)); |
| 138 | + const launch = Date.now(); |
| 139 | + await new AbortableWait( |
| 140 | + Promise.all( |
| 141 | + Array.from( |
| 142 | + { length: clients }, |
| 143 | + (_, index) => |
| 144 | + new Promise<void>((resolve, reject) => { |
| 145 | + const request = get( |
| 146 | + url, |
| 147 | + { |
| 148 | + agent: false, |
| 149 | + headers: { |
| 150 | + authorization: 'Bearer ' + token, |
| 151 | + 'last-event-id': String(after), |
| 152 | + 'x-fixture-client': String(index), |
| 153 | + }, |
| 154 | + }, |
| 155 | + (response) => { |
| 156 | + try { |
| 157 | + assert.equal(response.statusCode, 200); |
| 158 | + response.pause(); |
| 159 | + response.socket.pause(); |
| 160 | + resolve(); |
| 161 | + } catch (error) { |
| 162 | + reject(error); |
| 163 | + } |
| 164 | + }, |
| 165 | + ); |
| 166 | + requests.push(request); |
| 167 | + request.on('error', reject); |
| 168 | + }), |
| 169 | + ), |
| 170 | + ), |
| 171 | + ).wait(AbortSignal.timeout(10_000)); |
| 172 | + const connected = Date.now(); |
| 173 | + await sleep(pauseMs); |
| 174 | + const stopped = Date.now(); |
| 175 | + requests.forEach((request) => request.destroy()); |
| 176 | + worker.postMessage('stop'); |
| 177 | + const timings = await new AbortableWait(report.promise).wait(AbortSignal.timeout(10_000)); |
| 178 | + await waitFor(() => streamSlots(gw.store).count(principal).subject === 0); |
| 179 | + gw.store.recentHistory = recent; |
| 180 | + if (replay) gw.store.replayHistory = replay; |
| 181 | + gw.store.run = snapshot; |
| 182 | + const bytes = gw.store.prepare( |
| 183 | + 'SELECT sum(length(CAST(payload AS BLOB))) AS bytes FROM events WHERE run_id=? AND id BETWEEN ? AND ?', |
| 184 | + ); |
| 185 | + const maxPage = ranges.reduce( |
| 186 | + (largest, [first, last]) => |
| 187 | + Math.max(largest, Number(bytes.get(run, first, last)?.bytes ?? 0)), |
| 188 | + 0, |
| 189 | + ); |
| 190 | + |
| 191 | + const resumed = await fetch(url, { |
| 192 | + headers: { authorization: 'Bearer ' + token, 'last-event-id': String(after) }, |
| 193 | + signal: AbortSignal.timeout(10000), |
| 194 | + }); |
| 195 | + assert.equal(resumed.status, 200); |
| 196 | + const suffix: string[] = []; |
| 197 | + let last = after; |
| 198 | + let terminal: RunEvent | undefined; |
| 199 | + for (const line of (await resumed.text()).split('\n')) { |
| 200 | + if (!line.startsWith('data: ')) continue; |
| 201 | + const event = JSON.parse(line.slice(6)) as RunEvent; |
| 202 | + assert.ok(event.id > last); |
| 203 | + last = event.id; |
| 204 | + if (event.type === 'response.output_text.delta') suffix.push(String(event.data.delta)); |
| 205 | + if (event.type === 'response.completed') terminal = event; |
| 206 | + } |
| 207 | + assert.ok(terminal); |
| 208 | + assert.equal(last, terminal.id); |
| 209 | + const result = terminal.data.response as { output: { content: { text: string }[] }[] }; |
| 210 | + assert.equal(sha(result.output[0]!.content[0]!.text), sha(text)); |
| 211 | + assert.equal(suffix.length, tail); |
| 212 | + assert.equal( |
| 213 | + sha(suffix.join('')), |
| 214 | + sha(text.slice((Math.ceil(text.length / chunk) - tail) * chunk)), |
| 215 | + ); |
| 216 | + assert.equal(driver.calls, 1); |
| 217 | + return { |
| 218 | + connect_ms: connected - launch, |
| 219 | + largest_history_page_payload_bytes: maxPage, |
| 220 | + history_ms: historyMs, |
| 221 | + full_run_reads: snapshotReads, |
| 222 | + max_response_queue_bytes: Math.max(...queued), |
| 223 | + per_connection_queue_bytes: queued, |
| 224 | + health_under_load: healthSummary(timings, launch, stopped), |
| 225 | + health_first_400ms: healthSummary(timings, launch, launch + 400), |
| 226 | + }; |
| 227 | + } finally { |
| 228 | + requests.forEach((request) => request.destroy()); |
| 229 | + await worker?.terminate(); |
| 230 | + await next?.app.close(); |
| 231 | + await s.cleanup(); |
| 232 | + } |
| 233 | +} |
| 234 | + |
| 235 | +const samples = []; |
| 236 | +for (let i = 0; i < trials; i++) samples.push(await trial()); |
| 237 | +console.log(JSON.stringify({ clients, chars: text.length, pause_ms: pauseMs, samples })); |
0 commit comments