|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import { performance } from 'node:perf_hooks'; |
| 3 | +import { parseArgs } from 'node:util'; |
| 4 | +import type { RunEvent } from '../src/core/contracts.js'; |
| 5 | +import { AGENT_LIMITS } from '../src/core/limits.js'; |
| 6 | +import { sha } from '../src/core/util.js'; |
| 7 | +import { makeBundle } from '../src/lang/bundle.js'; |
| 8 | +import { agent, FixtureModel, setup, token } from '../test/helpers.js'; |
| 9 | + |
| 10 | +const { values } = parseArgs({ |
| 11 | + options: { |
| 12 | + chars: { type: 'string', default: '990000' }, |
| 13 | + 'chunk-chars': { type: 'string', default: '512' }, |
| 14 | + trials: { type: 'string', default: '3' }, |
| 15 | + }, |
| 16 | +}); |
| 17 | +const limit = (v: string | undefined, min: number, max: number) => { |
| 18 | + const n = Number(v); |
| 19 | + assert.ok( |
| 20 | + Number.isSafeInteger(n) && n >= min && n <= max, |
| 21 | + `Expected an integer in [${min}, ${max}]`, |
| 22 | + ); |
| 23 | + return n; |
| 24 | +}; |
| 25 | +const chars = limit(values.chars, 1, AGENT_LIMITS.outputTextChars); |
| 26 | +const chunkChars = limit(values['chunk-chars'], 32, 16_384); |
| 27 | +const trials = limit(values.trials, 1, 10); |
| 28 | +const pattern = 'x\u4e2d\u6587\u{1f600}\n"\\\u0001'; |
| 29 | +const text = |
| 30 | + pattern.repeat(Math.floor(chars / pattern.length)) + 'x'.repeat(chars % pattern.length); |
| 31 | +const expected = sha(text); |
| 32 | +const chunkCount = Math.ceil(chars / chunkChars); |
| 33 | +const pageBytes = 8000; |
| 34 | + |
| 35 | +async function trial() { |
| 36 | + const driver = new FixtureModel(); |
| 37 | + driver.call = async (_agent, _messages, _signal, emit) => { |
| 38 | + driver.calls++; |
| 39 | + for (let offset = 0; offset < chars; offset += chunkChars) |
| 40 | + emit(text.slice(offset, offset + chunkChars)); |
| 41 | + return { |
| 42 | + text, |
| 43 | + calls: [], |
| 44 | + finish: 'stop', |
| 45 | + usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 }, |
| 46 | + }; |
| 47 | + }; |
| 48 | + const s = await setup(driver); |
| 49 | + const db = s.store.db; |
| 50 | + const exec = db.exec.bind(db); |
| 51 | + const phases: Record<string, { count: number; total_ms: number; max_ms: number }> = {}; |
| 52 | + let started: number | undefined; |
| 53 | + let phase: string | undefined; |
| 54 | + try { |
| 55 | + const model = 'agent/large-output-bench'; |
| 56 | + s.store.publish('owner', makeBundle(agent({ id: model }))); |
| 57 | + db.function('sample_large_output', (kind) => { |
| 58 | + if (started !== undefined && (kind !== 'text' || phase === undefined)) phase = String(kind); |
| 59 | + return 1; |
| 60 | + }); |
| 61 | + db.exec(`CREATE TEMP TRIGGER sample_large_output AFTER INSERT ON events |
| 62 | + WHEN NEW.type IN ('response.output_item.added','response.output_text.delta', |
| 63 | + 'response.output_item.done','response.completed') BEGIN |
| 64 | + SELECT sample_large_output(CASE NEW.type WHEN 'response.output_item.added' THEN 'opening' |
| 65 | + WHEN 'response.output_text.delta' THEN 'text' WHEN 'response.output_item.done' THEN 'seal' |
| 66 | + ELSE 'terminal' END); END`); |
| 67 | + db.exec = (sql) => { |
| 68 | + exec(sql); |
| 69 | + if (sql === 'BEGIN IMMEDIATE') { |
| 70 | + started = performance.now(); |
| 71 | + phase = undefined; |
| 72 | + } else if (sql === 'COMMIT' || sql === 'ROLLBACK') { |
| 73 | + if (sql === 'COMMIT' && started !== undefined && phase !== undefined) { |
| 74 | + const elapsed = performance.now() - started; |
| 75 | + const stats = (phases[phase] ??= { count: 0, total_ms: 0, max_ms: 0 }); |
| 76 | + stats.count++; |
| 77 | + stats.total_ms += elapsed; |
| 78 | + stats.max_ms = Math.max(stats.max_ms, elapsed); |
| 79 | + } |
| 80 | + started = undefined; |
| 81 | + phase = undefined; |
| 82 | + } |
| 83 | + }; |
| 84 | + const begin = performance.now(); |
| 85 | + const response = await s.request('POST', '/v1/responses', { model, input: 'fixture' }); |
| 86 | + const generationMs = performance.now() - begin; |
| 87 | + assert.equal(response.statusCode, 200); |
| 88 | + const body = response.json(); |
| 89 | + assert.equal(body.status, 'completed'); |
| 90 | + assert.equal(sha(body.output[0].content[0].text), expected); |
| 91 | + assert.equal(driver.calls, 1); |
| 92 | + const run = String(body.id); |
| 93 | + |
| 94 | + let cursor: string | null = null; |
| 95 | + const parts: string[] = []; |
| 96 | + const firstPage = performance.now(); |
| 97 | + for (let i = 0; i <= 512; i++) { |
| 98 | + const page = await s.request( |
| 99 | + 'GET', |
| 100 | + `/v1/runs/${run}/output?max_bytes=${pageBytes}${cursor === null ? '' : '&cursor=' + cursor}`, |
| 101 | + ); |
| 102 | + assert.equal(page.statusCode, 200); |
| 103 | + const result = page.json(); |
| 104 | + assert.ok(Buffer.byteLength(JSON.stringify(result.text)) <= pageBytes); |
| 105 | + assert.ok(result.done || (result.next_cursor && result.next_cursor !== cursor)); |
| 106 | + parts.push(result.text); |
| 107 | + if (result.done) break; |
| 108 | + cursor = result.next_cursor; |
| 109 | + } |
| 110 | + const paginationMs = performance.now() - firstPage; |
| 111 | + assert.equal(sha(parts.join('')), expected); |
| 112 | + |
| 113 | + const halfway = Math.floor(chunkCount / 2); |
| 114 | + const after = halfway |
| 115 | + ? Number( |
| 116 | + db |
| 117 | + .prepare( |
| 118 | + "SELECT id FROM events WHERE run_id=? AND type='response.output_text.delta' ORDER BY id LIMIT 1 OFFSET ?", |
| 119 | + ) |
| 120 | + .get(run, halfway - 1)!.id, |
| 121 | + ) |
| 122 | + : 0; |
| 123 | + const address = await s.listen(); |
| 124 | + const replayStart = performance.now(); |
| 125 | + const resumed = await fetch(`${address}/v1/runs/${run}/events`, { |
| 126 | + headers: { authorization: 'Bearer ' + token, 'last-event-id': String(after) }, |
| 127 | + signal: AbortSignal.timeout(25000), |
| 128 | + }); |
| 129 | + assert.equal(resumed.status, 200); |
| 130 | + const wire = await resumed.text(); |
| 131 | + const replayMs = performance.now() - replayStart; |
| 132 | + let last = after; |
| 133 | + const suffix: string[] = []; |
| 134 | + let terminal: RunEvent | undefined; |
| 135 | + for (const line of wire.split('\n')) { |
| 136 | + if (!line.startsWith('data: ')) continue; |
| 137 | + const event = JSON.parse(line.slice(6)) as RunEvent; |
| 138 | + assert.ok(event.id > last); |
| 139 | + last = event.id; |
| 140 | + if (event.type === 'response.output_text.delta') suffix.push(String(event.data.delta)); |
| 141 | + if (event.type === 'response.completed') terminal = event; |
| 142 | + } |
| 143 | + assert.equal(suffix.length, chunkCount - halfway); |
| 144 | + assert.equal(sha(suffix.join('')), sha(text.slice(halfway * chunkChars))); |
| 145 | + assert.ok(terminal); |
| 146 | + assert.equal(last, terminal.id); |
| 147 | + const final = terminal.data.response as { output: { content: { text: string }[] }[] }; |
| 148 | + assert.equal(sha(final.output[0]!.content[0]!.text), expected); |
| 149 | + return { |
| 150 | + generation_ms: generationMs, |
| 151 | + writer: phases, |
| 152 | + pagination: { pages: parts.length, ms: paginationMs }, |
| 153 | + replay: { remaining_chunks: suffix.length, bytes: Buffer.byteLength(wire), ms: replayMs }, |
| 154 | + }; |
| 155 | + } finally { |
| 156 | + db.exec = exec; |
| 157 | + await s.cleanup(); |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +const samples = []; |
| 162 | +for (let i = 0; i < trials; i++) samples.push(await trial()); |
| 163 | +console.log(JSON.stringify({ chars, chunk_chars: chunkChars, samples })); |
0 commit comments