Skip to content

Commit 70074cc

Browse files
author
hzq
committed
Bound SSE replay pages by payload bytes
Load history only as the socket can consume it and yield between pages. Use a compact identity for native replay, preserve oversized frames and resume cursors, and benchmark cold replay under stalled readers.
1 parent 1e7fe2c commit 70074cc

9 files changed

Lines changed: 470 additions & 51 deletions

File tree

‎bench/slow-sse-replay.ts‎

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

‎docs/stability.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,13 @@ output cursor, and reconnects over loopback SSE after a middle delta. No model s
270270
Add `--profile-pagination` to separate the in-process cursor walk and prefix calculation
271271
from the full HTTP pagination measurement.
272272

273+
`node dist/bench/slow-sse-replay.js --clients 8` restarts the fixture gateway, then pauses eight
274+
loopback SSE consumers during cold replay and probes `/health` from a separate worker. It
275+
reports stored event bytes per replay page and the Node response queue separately, not process
276+
RSS or the operating system's TCP buffers. Replay pages are bounded by stored payload bytes;
277+
an oversized legal event stands alone in its page. After backpressure clears, replay continues
278+
after the last event queued on that connection. Reconnecting clients use the last complete ID they received.
279+
273280
New HTTP run submissions (including media jobs and workflow drafts) wait for SQLite's writer
274281
without blocking the gateway. The wait is at most the connection timeout or five seconds,
275282
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
@@ -126,6 +126,8 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
126126
接近输出上限的压测可运行 `node dist/bench/large-output.js --chars 990000 --chunk-chars 512`。它用混合 Unicode 和 JSON 转义字符的模拟文本测量各写入阶段,遍历输出游标,并通过本机 SSE 从正文中段重连校验,不调用模型服务。
127127
加上 `--profile-pagination` 可以分别测量进程内游标遍历、前缀截断计算和完整 HTTP 分页。
128128

129+
`node dist/bench/slow-sse-replay.js --clients 8` 会重启模拟网关,让八条本机 SSE 连接在冷缓存重放期间暂停读取,并由独立线程探测 `/health`。它分别报告历史页的已存载荷字节数和 Node 响应队列,不等同于进程 RSS 或操作系统 TCP 缓冲。历史页按载荷字节分批,合法的大事件独占一页。背压消退后从该连接最后入写队列的事件 ID 继续;客户端重连仍以自己最后完整收到的事件 ID 为准。
130+
129131
通过 HTTP 创建运行时(包括媒体任务和工作流草稿),网关异步等写锁,不让整个事件循环停下来。等待时间不超过连接超时和 5 秒中的较短者。
130132
等待队列先进先出,每个 owner 最多 8 个请求,全网关最多 64 个;请求体另按每个 owner 32 MiB、全网关 64 MiB 限制。
131133
超时或排满返回 `503 admission_busy` 和 `Retry-After: 1`,不创建任务或预占用量。已有结果的幂等重放不等写锁。

‎src/gateway/compat-stream.ts‎

Lines changed: 26 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { terminal, type Run, type RunEvent, type Usage } from '../core/contracts
77
import { chatUsage, responseObject } from './protocol.js';
88
import { claudeDelta, claudeDeltaUsage, claudeMessage } from './claude.js';
99
import { openEventStream } from './streams.js';
10+
import { attachRunReplay } from './run-replay.js';
1011
import { streamSlots } from './stream-slots.js';
1112
import { sseRequested } from './compat-errors.js';
1213
import * as progress from './progress-stream.js';
@@ -87,7 +88,12 @@ export function streamEvents(
8788
mode === 'uap-sse';
8889
const initial = needsInitial ? (initialRun ?? store.run(runId)) : initialRun;
8990
if (options.progressDefaults) progress.rememberProgressDefaults(store, options.progressDefaults);
90-
const locale = progress.progressFor(store, req, initial ?? store.run(runId), mode);
91+
const locale = progress.progressFor(
92+
store,
93+
req,
94+
mode === 'responses' ? (initial ?? store.run(runId)) : initial,
95+
mode,
96+
);
9197
const lines = locale ? new progress.ProgressLines(locale) : undefined;
9298
const reasoning =
9399
mode === 'responses' && lines ? new progress.ResponsesReasoning(runId) : undefined;
@@ -523,48 +529,14 @@ export function streamEvents(
523529
close();
524530
}
525531
};
526-
// 补发与追赶:积压超过高水位时等客户端读走再继续,事件从已提交的
527-
// 历史按游标重读,所以等待期间到达的实时事件不会排在内存里,也不会乱序或遗漏。没有积压
528-
// 时实时事件照旧同步写出,常规大小的运行线上字节不变。
529-
let catchingUp = false;
530-
let behind = false;
531-
const pump = async () => {
532-
if (catchingUp) {
533-
behind = true;
534-
return;
535-
}
536-
catchingUp = true;
537-
try {
538-
do {
539-
behind = false;
540-
for (;;) {
541-
if (stream.closed) return;
542-
const events = store.recentHistory(runId, last, REPLAY_BATCH);
543-
for (const e of events) {
544-
if (
545-
stream.backlog() > REPLAY_HIGH_WATER &&
546-
!(await stream.drained(REPLAY_HIGH_WATER, REPLAY_STALL_MS))
547-
)
548-
return;
549-
onEvent(e);
550-
}
551-
if (events.length < REPLAY_BATCH) break;
552-
}
553-
} while (behind && !stream.closed);
554-
} finally {
555-
catchingUp = false;
556-
}
557-
};
558-
const live = (e: RunEvent) => {
559-
if (stream.closed || e.id <= last) return;
560-
if (!catchingUp && stream.backlog() <= REPLAY_HIGH_WATER) onEvent(e);
561-
else void pump();
532+
const replayError = (error: unknown) => {
533+
if (!stream.closed)
534+
onUnconfirmed(
535+
error instanceof Fault
536+
? error
537+
: new Fault('persistence_failed', 'The stored event stream could not be read.', 500),
538+
);
562539
};
563-
store.events.on(runId, live);
564-
stream.onClose(() => {
565-
store.events.off(runId, live);
566-
});
567-
void pump().then(() => afterReplay());
568540
const afterReplay = () => {
569541
// 续接时外部智能体已经在等别的调用(晚到的并行调用,通知在游标之前):立即交给调用方。
570542
if (
@@ -577,11 +549,17 @@ export function streamEvents(
577549
onEvent({ id: last + 1, runId, type: 'run.awaiting_caller', time: Date.now(), data: {} });
578550
last = cursorAt;
579551
}
580-
if (!stream.closed && !seenTerminal && terminal(store.run(runId).status)) close();
552+
if (
553+
!stream.closed &&
554+
!seenTerminal &&
555+
terminal(store.runIdentity(runId, req.principal.owner).status)
556+
)
557+
close();
581558
};
559+
attachRunReplay(store, runId, stream, {
560+
cursor: () => last,
561+
event: onEvent,
562+
ready: afterReplay,
563+
error: replayError,
564+
});
582565
}
583-
584-
/** 补发一批读多少条事件;积压超过高水位就等客户端读走;多久一个字节都没读走算慢客户端。 */
585-
const REPLAY_BATCH = 500;
586-
const REPLAY_HIGH_WATER = 1024 * 1024;
587-
const REPLAY_STALL_MS = 30_000;

0 commit comments

Comments
 (0)