Skip to content

Commit 5459abd

Browse files
author
hzq
committed
Bind large output checkpoint events without nested JSON
Compare bounded seal and terminal batches against their exact event rows. Verify byte-level mismatch handling and add a near-limit benchmark covering writes, paging and SSE replay.
1 parent f03b311 commit 5459abd

7 files changed

Lines changed: 298 additions & 16 deletions

File tree

‎bench/large-output.ts‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
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 }));

‎docs/stability.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,10 @@ opening, text and sealing. The opening and already-received first text can share
264264
without merging or reordering public frames. The benchmark reports lock time and the interval
265265
from the first persistence attempt to the first durable delta, not provider or network latency.
266266

267+
For near-limit output, run `node dist/bench/large-output.js --chars 990000 --chunk-chars 512`.
268+
It validates a mixed Unicode and JSON-escaped fixture, times each writer phase, walks the paged
269+
output cursor, and reconnects over loopback SSE after a middle delta. No model service is called.
270+
267271
New HTTP run submissions (including media jobs and workflow drafts) wait for SQLite's writer
268272
without blocking the gateway. The wait is at most the connection timeout or five seconds,
269273
whichever is shorter. One FIFO admits at most eight waiting requests per owner and 64 in total;

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,8 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
123123

124124
`node dist/bench/output-checkpoints.js --runs 512` 分别测量流式输出的开项、正文和封口写入。开项可以和已收到的首段正文一起落盘,但不合并或重排对外事件。压测报告持锁时间以及从第一次尝试落盘到首条增量确认的间隔,不包含模型提供方或网络延迟。
125125

126+
接近输出上限的压测可运行 `node dist/bench/large-output.js --chars 990000 --chunk-chars 512`。它用混合 Unicode 和 JSON 转义字符的模拟文本测量各写入阶段,遍历输出游标,并通过本机 SSE 从正文中段重连校验,不调用模型服务。
127+
126128
通过 HTTP 创建运行时(包括媒体任务和工作流草稿),网关异步等写锁,不让整个事件循环停下来。等待时间不超过连接超时和 5 秒中的较短者。
127129
等待队列先进先出,每个 owner 最多 8 个请求,全网关最多 64 个;请求体另按每个 owner 32 MiB、全网关 64 MiB 限制。
128130
超时或排满返回 `503 admission_busy` 和 `Retry-After: 1`,不创建任务或预占用量。已有结果的幂等重放不等写锁。

‎src/store/checkpoint-proof.ts‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,46 @@ type Evidence =
2222
| { step: ExecutionStep; artifacts: string[] }
2323
| { steps: ExecutionStep[]; approvals?: Map<string, string> }
2424
| { rawSteps: ReadonlyMap<string, string>; approvals: ReadonlyMap<string, string> };
25+
type EventRow = readonly [id: number, type: RunEvent['type'], time: number, payload: string];
26+
type EventRows = string | readonly EventRow[];
2527
const eventRowsMatch = `NOT EXISTS(SELECT 1 FROM json_each($events) j WHERE NOT EXISTS(
2628
SELECT 1 FROM events e WHERE e.id=json_extract(j.value,'$[0]') AND e.run_id=$run
2729
AND e.type=json_extract(j.value,'$[1]') AND e.time=json_extract(j.value,'$[2]') AND e.payload=json_extract(j.value,'$[3]')))`;
2830
const stepRowsMatch = `NOT EXISTS(SELECT 1 FROM json_each($stepRows) j WHERE NOT EXISTS(
2931
SELECT 1 FROM steps s WHERE s.run_id=$run AND s.id=json_extract(j.value,'$[0]') AND s.payload=json_extract(j.value,'$[1]')))`;
32+
function bindEventProof(rows: EventRows, facts: Record<string, string | number>) {
33+
// A short seal/terminal batch may contain megabytes of text. Compare the original serialized
34+
// payloads directly; the fixed bound keeps both SQL shapes and statement bindings bounded.
35+
if (typeof rows !== 'string' && rows.length <= 4)
36+
return rows
37+
.map(([id, type, time, payload], index) => {
38+
const prefix = 'event' + index;
39+
facts[prefix + 'Id'] = id;
40+
facts[prefix + 'Type'] = type;
41+
facts[prefix + 'Time'] = time;
42+
facts[prefix + 'Payload'] = payload;
43+
return (
44+
' AND EXISTS(SELECT 1 FROM events e WHERE e.run_id=$run' +
45+
' AND e.id=$' +
46+
prefix +
47+
'Id AND e.type=$' +
48+
prefix +
49+
'Type' +
50+
' AND e.time=$' +
51+
prefix +
52+
'Time AND e.payload=$' +
53+
prefix +
54+
'Payload)'
55+
);
56+
})
57+
.join('');
58+
facts.events = typeof rows === 'string' ? rows : JSON.stringify(rows);
59+
return ' AND ' + eventRowsMatch;
60+
}
3061
const common = ` FROM runs r JOIN run_summaries m ON m.run_id=r.id AND m.owner=r.owner AND m.subject=r.subject
3162
AND m.agent_id=r.agent_id AND m.status=r.status AND m.ordinal=r.rowid AND m.total_tokens=$tokens AND m.usage_known=$known
3263
WHERE r.id=$run AND r.owner=$owner AND r.subject=$subject AND r.agent_id=$agent AND r.status=$status
33-
AND r.payload=$snapshot AND m.payload=$summary
34-
AND ${eventRowsMatch}`;
64+
AND r.payload=$snapshot AND m.payload=$summary`;
3565
const stepProof =
3666
'SELECT 1 AS confirmed' +
3767
common +
@@ -121,13 +151,12 @@ const outputProof =
121151
')';
122152

123153
/** Freeze the intended values; later verification is one read snapshot, never a write. */
124-
export const encodeCheckpointEvents = (
125-
events: RunEvent[],
126-
prior: readonly [number, string, number, string][] = [],
127-
) =>
128-
JSON.stringify([...prior, ...events.map((e) => [e.id, e.type, e.time, JSON.stringify(e.data)])]);
129-
export function decodeCheckpointEvents(runId: string, encoded: string): RunEvent[] {
130-
const rows = JSON.parse(encoded) as [number, RunEvent['type'], number, string][];
154+
export const freezeCheckpointEvents = (events: RunEvent[]): EventRow[] =>
155+
events.map((e) => [e.id, e.type, e.time, JSON.stringify(e.data)]);
156+
export const encodeCheckpointEvents = (events: RunEvent[], prior: readonly EventRow[] = []) =>
157+
JSON.stringify([...prior, ...freezeCheckpointEvents(events)]);
158+
export function decodeCheckpointEvents(runId: string, encoded: EventRows): RunEvent[] {
159+
const rows = typeof encoded === 'string' ? (JSON.parse(encoded) as EventRow[]) : encoded;
131160
return rows.map(([id, type, time, payload]) => ({
132161
id,
133162
runId,
@@ -141,7 +170,7 @@ export function checkpointProof(
141170
run: Run,
142171
snapshot: string,
143172
summary: string,
144-
events: string,
173+
events: EventRows,
145174
evidence: Evidence,
146175
) {
147176
let sql: string;
@@ -155,8 +184,8 @@ export function checkpointProof(
155184
summary,
156185
tokens: run.usage?.total_tokens ?? 0,
157186
known: run.usage === null ? 0 : run.metadata['oaa.usage_complete'] === 'false' ? 2 : 1,
158-
events,
159187
};
188+
const checkEvents = bindEventProof(events, facts);
160189
if (
161190
evidence === 'model' ||
162191
'start' in evidence ||
@@ -207,6 +236,7 @@ export function checkpointProof(
207236
facts.session = run.sessionId;
208237
facts.start = evidence.event ?? 0;
209238
}
239+
sql += checkEvents;
210240
return (first?: number) =>
211241
first === undefined
212242
? !!store.prepare(sql).get(facts)
@@ -245,5 +275,6 @@ export function checkpointProof(
245275
);
246276
facts.approvals = JSON.stringify(evidence.approvals ? [...evidence.approvals] : []);
247277
}
278+
sql += checkEvents;
248279
return () => !!store.prepare(sql).get(facts);
249280
}

‎src/store/run-checkpoints.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ElapsedRunDeadline, Fault, checkAbort, id, sha } from '../core/util.js'
55
import {
66
checkpointProof,
77
encodeCheckpointEvents,
8+
freezeCheckpointEvents,
89
decodeCheckpointEvents,
910
type StartCursor,
1011
approvalRowsMatch,
@@ -332,13 +333,15 @@ export class RunCheckpoints {
332333
!approvalRowsMatch(store, live, wake.all))
333334
)
334335
throw failure();
335-
const encoded = encodeCheckpointEvents(batch),
336+
const eventRows = batch.some((event) => event.type === 'response.output_item.done')
337+
? freezeCheckpointEvents(batch)
338+
: encodeCheckpointEvents(batch),
336339
matches = checkpointProof(
337340
store,
338341
view,
339342
saved,
340343
summary,
341-
encoded,
344+
eventRows,
342345
wake && before.parked
343346
? { wake: before.parked, event: batch[0]!.id, approved: wake.approved }
344347
: startEvent && before.start
@@ -384,7 +387,7 @@ export class RunCheckpoints {
384387
receipt = store.terminalPublications.hold(id, boundary, inspect, () => {
385388
const restored = JSON.parse(saved) as Run;
386389
restored.output = JSON.parse(output);
387-
publish(restored, decodeCheckpointEvents(id, encoded));
390+
publish(restored, decodeCheckpointEvents(id, eventRows));
388391
});
389392
throw receipt;
390393
}

‎src/store/terminal-publication.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { AbortableWait } from '../core/abortable-wait.js';
55
import { UnconfirmedRunCommit } from './run-creation.js';
66
import {
77
checkpointProof,
8-
encodeCheckpointEvents,
8+
freezeCheckpointEvents,
99
decodeCheckpointEvents,
1010
} from './checkpoint-proof.js';
1111
import { alignSummaryScope } from './run-snapshot.js';
@@ -145,7 +145,7 @@ export class TerminalPublications {
145145
run.status === 'interrupted' ? 'response.incomplete' : 'response.' + run.status;
146146
const terminalEvent =
147147
last === expected || (run.status === 'interrupted' && last === 'run.interrupted');
148-
const eventRows = encodeCheckpointEvents(data.events);
148+
const eventRows = freezeCheckpointEvents(data.events);
149149
const matches = checkpointProof(this.store, run, data.saved, data.summary, eventRows, {
150150
steps: data.failedSteps ?? [],
151151
approvals: data.approvals,

0 commit comments

Comments
 (0)