Skip to content

Commit f41e8e8

Browse files
author
hzq
committed
Plan SSE replay from stored event byte lengths
Use SQLite column byte lengths to avoid loading event bodies before replay admission. Keep existing encoding and cursor behavior, and exercise it across UTF-8 and UTF-16 databases.
1 parent d49f094 commit f41e8e8

7 files changed

Lines changed: 183 additions & 6 deletions

File tree

‎bench/event-retention.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import assert from 'node:assert/strict';
2+
import { performance } from 'node:perf_hooks';
3+
import { setImmediate as nextTurn } from 'node:timers/promises';
4+
import { parseArgs } from 'node:util';
5+
import { sha } from '../src/core/util.js';
6+
import { makeBundle } from '../src/lang/bundle.js';
7+
import { REPLAY_PAGE_BYTES } from '../src/store/event-replay-size.js';
8+
import { agent, FixtureModel, setup } from '../test/helpers.js';
9+
10+
const { values } = parseArgs({ options: { runs: { type: 'string', default: '32' } } });
11+
const runs = Number(values.runs);
12+
assert.ok(Number.isSafeInteger(runs) && runs >= 1 && runs <= 64);
13+
const gc = global.gc;
14+
assert.ok(gc, 'Run the benchmark with node --expose-gc');
15+
const snapshot = async () => {
16+
await nextTurn();
17+
gc();
18+
const { rss, heapUsed, external, arrayBuffers } = process.memoryUsage();
19+
return { rss, heapUsed, external, arrayBuffers };
20+
};
21+
const text = (n: number) => n + 'x\u4e2d\u6587\u{1f600}\n"\\\u0001'.repeat(109_999);
22+
const driver = new FixtureModel();
23+
driver.call = async (_agent, _messages, _signal, emit) => {
24+
const answer = text(++driver.calls);
25+
emit(answer);
26+
return {
27+
text: answer,
28+
calls: [],
29+
finish: 'stop',
30+
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
31+
};
32+
};
33+
34+
const s = await setup(driver);
35+
try {
36+
s.store.publish('owner', makeBundle(agent()));
37+
const submit = async () => {
38+
const reply = await s.request('POST', '/v1/responses', {
39+
model: 'agent/test',
40+
input: 'fixture',
41+
background: true,
42+
});
43+
assert.equal(reply.statusCode, 200);
44+
const id = String(reply.json().id);
45+
assert.equal((await s.kernel.wait(id)).status, 'completed');
46+
return id;
47+
};
48+
await submit();
49+
const startHeap = await snapshot();
50+
const start = performance.now();
51+
const ids: string[] = [];
52+
for (let i = 0; i < runs; i++) ids.push(await submit());
53+
const generationMs = performance.now() - start;
54+
const retained = await snapshot();
55+
assert.equal(driver.calls, runs + 1);
56+
const delta = Object.fromEntries(
57+
(Object.keys(startHeap) as (keyof typeof startHeap)[]).map((k) => [
58+
k,
59+
retained[k] - startHeap[k],
60+
]),
61+
);
62+
63+
const terminalIds = ids.map((id, i) => {
64+
const row = s.store
65+
.prepare("SELECT id FROM events WHERE run_id=? AND type='response.completed'")
66+
.get(id)!;
67+
const after = Number(row.id) - 1;
68+
const pages = s.store.replayHistory(id, after, 500, REPLAY_PAGE_BYTES, true);
69+
const final = pages.events[0];
70+
assert.equal(final?.id, after + 1);
71+
assert.equal(final?.type, 'response.completed');
72+
const data = final.data.response as { output: [{ content: [{ text: string }] }] };
73+
assert.equal(sha(data.output[0].content[0].text), sha(text(i + 2)));
74+
return after;
75+
});
76+
let planned = 0;
77+
const planStart = performance.now();
78+
const passes = 50;
79+
for (let pass = 0; pass < passes; pass++)
80+
for (const [i, id] of ids.entries()) {
81+
const page = s.store.planReplayHistory(id, terminalIds[i]!, 500, REPLAY_PAGE_BYTES);
82+
assert.equal(page.count, 1);
83+
assert.ok(page.bytes > REPLAY_PAGE_BYTES);
84+
planned += page.bytes;
85+
}
86+
console.log(
87+
JSON.stringify({
88+
runs,
89+
chars: text(1).length,
90+
generation_ms: generationMs,
91+
gc_retained_delta_bytes: delta,
92+
replay_plan: {
93+
calls: passes * runs,
94+
observed_bytes: planned,
95+
total_ms: performance.now() - planStart,
96+
},
97+
}),
98+
);
99+
} finally {
100+
await s.cleanup();
101+
}

‎bench/live-sse-fanout.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,21 @@ async function trial() {
9999
),
100100
);
101101
assert.equal(streamSlots(s.store).count(p).subject, clients);
102-
if (values['profile-memory']) profile = profileSseMemory(new Set([run]));
102+
if (values['profile-memory']) {
103+
profile = profileSseMemory(new Set([run]));
104+
const plan = s.store.planReplayHistory.bind(s.store);
105+
const read = s.store.replayHistory.bind(s.store);
106+
s.store.planReplayHistory = (...args) => {
107+
const result = plan(...args);
108+
profile?.observeReplayPlan();
109+
return result;
110+
};
111+
s.store.replayHistory = (...args) => {
112+
const result = read(...args);
113+
profile?.observeHistory();
114+
return result;
115+
};
116+
}
103117
const start = performance.now();
104118
produce.resolve();
105119
const finished = await s.kernel.wait(run);

‎bench/sse-memory-profile.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,9 @@ export function profileSseMemory(runs: ReadonlySet<string>) {
6868
Buffer.from = from;
6969
};
7070
return {
71+
observeReplayPlan() {
72+
sample('history_plan');
73+
},
7174
observeHistory() {
7275
sample('history_page');
7376
},

‎docs/stability.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,10 @@ Replay pages above 256 KiB reserve stored payload bytes before loading the page:
300300
32 MiB per gateway and 8 MiB per caller. A legal event exceeding a limit can use that budget
301301
alone. Waiters do not materialize the page; they recheck access and size before reading, and
302302
leave on disconnect or after five seconds. An expired or full replay queue returns a stream
303-
capacity error without advancing the cursor. A native SSE event with a committed payload above
303+
capacity error without advancing the cursor. The size pass uses SQLite's stored byte lengths
304+
without loading each event body. `node --expose-gc dist/bench/event-retention.js --runs 32`
305+
measures size planning after 32 large fixture runs, apart from output generation and retained
306+
process memory. A native SSE event with a committed payload above
304307
256 KiB uses the same cursor and budget even for already-connected readers. It leaves the
305308
commit notification before reading the payload, so stalled readers do not make the producer
306309
encode the event separately for each connection. Small pages, ordinary live events, and direct

‎docs/zh-CN/stability.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
130130
大帧只在 HTTP 写入层分块,不改变 SSE 的事件 ID 和内容。写入遇到背压或响应正在关闭时,写队列连续 30 秒没有进展就销毁连接。流名额保留到 Node 完成响应交付给传输层,或者连接关闭;这不代表客户端已收到全部内容。
131131
重放页超过 256 KiB 时,先按存储载荷预留预算,再读入正文:每网关 32 MiB、每调用方 8 MiB。超出额度的合法单帧可以独占对应预算。等待不读入该页正文,获准后重新核对授权和页大小;断线或等满五秒就退出。排队满或超时返回流容量错误,不推进游标。对已经连接的原生 SSE 读者,已落盘且超过 256 KiB 的实时事件也从游标走同一份预算,并在提交通知退出后再读正文,避免停读连接让生产端逐条重复编码。小页、普通实时事件和兼容格式的直接实时发送不占这份预算,它也不是进程总内存上限。
132132
`node --expose-gc dist/bench/live-sse-fanout.js --profile-memory` 让已经连接的读者在模拟大输出前停读,记录运行提交耗时、编码及进程内存保留量,并检查断线后的游标续读。不调用模型服务。
133+
重放规划使用 SQLite 记录的字节长度,不为算大小读入事件正文。`node --expose-gc dist/bench/event-retention.js --runs 32` 分别报告 32 个模拟大输出运行的生成耗时、保留内存和后续重放规划耗时。
133134
等待队列每网关最多 128 个名额,其中每密钥最多 32 个、每 owner 最多 96 个。这里只限制等待名额,不改变字节预算或连接数;能直接发送、不进队的请求不占等待名额。`node dist/bench/replay-queue-pressure.js` 会用固定预算占用夹具,让两个密钥各发 64 条本机请求来核对准入。
134135
调用方自身还有预算、却因网关预算等候至少 1.5 秒时,网关可以断开写队列也已至少 1.5 秒没有进展的重放连接。每次只回收一条,连接真正关闭后才归还字节预算。仅受调用方额度限制不会触发回收;有写入进展的连接不受影响。断线后仍从最后完整收到的事件 ID 续读。`node dist/bench/replay-pressure.js` 可复现五个停读密钥与一个快读密钥争用全局预算的场景。
135136
因压力回收的连接关闭后,两秒内如果同一调用方重连会吃掉最后一帧的余量,就先等待,不读入正文,也不触发下一次压力回收。网关空闲或仍有余量时可立即续读,字节硬上限不变。`node dist/bench/replay-pressure.js --mixed` 会分批发起快读请求,并让被断开的连接立即带原游标重试,记录重连次数。

‎src/store/event-history.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const replayPayloads = new WeakMap<RunEvent, string | Buffer>();
1010
const canonicalReplay = new WeakSet<RunEvent>();
1111
const utf8Stores = new WeakMap<HistoryReader, boolean>();
1212
const markedLargePayload =
13-
"wire_json=1 AND typeof(payload)='text' AND length(CAST(payload AS BLOB))>=131072";
13+
"wire_json=1 AND typeof(payload)='text' AND octet_length(payload)>=131072";
1414
const decode = (payload: string | Buffer): RunEvent['data'] =>
1515
JSON.parse(typeof payload === 'string' ? payload : payload.toString('utf8'));
1616
export const replayPayloadOf = (event: RunEvent) => replayPayloads.get(event);
@@ -92,7 +92,7 @@ export function readEventHistory(
9292
});
9393
}
9494

95-
/** Plan without fetching payloads; a single oversized event can still advance. */
95+
/** Plan using stored byte lengths without loading the SQLite payloads. */
9696
export function planReplayPage(
9797
store: HistoryReader,
9898
runId: string,
@@ -105,7 +105,7 @@ export function planReplayPage(
105105
let more = false;
106106
for (const row of store
107107
.prepare(
108-
'SELECT length(CAST(payload AS BLOB)) AS bytes FROM events WHERE run_id=? AND id>? ORDER BY id LIMIT ?',
108+
'SELECT octet_length(payload) AS bytes FROM events WHERE run_id=? AND id>? ORDER BY id LIMIT ?',
109109
)
110110
.iterate(runId, after, limit + 1)) {
111111
const size = Number(row.bytes);

‎test/native-replay-wire.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,67 @@ import { DatabaseSync } from 'node:sqlite';
33
import test from 'node:test';
44
import { leaseNativeReplayWire, nativeEventWire } from '../src/gateway/native-replay-wire.js';
55
import { makeBundle } from '../src/lang/bundle.js';
6-
import { canonicalReplayPayloadOf, readEventHistory } from '../src/store/event-history.js';
6+
import {
7+
canonicalReplayPayloadOf,
8+
planReplayPage,
9+
readEventHistory,
10+
} from '../src/store/event-history.js';
711
import { agent, setup, secondToken } from './helpers.js';
812

913
const text = 'x\u4e2d\u{1f600}\n"\\\u0001'.repeat(40_000);
1014
const budget = 256 * 1024;
1115

16+
for (const encoding of ['UTF-8', 'UTF-16le', 'UTF-16be'])
17+
test(`replay planning keeps exact stored byte boundaries in ${encoding}`, () => {
18+
const db = new DatabaseSync(':memory:');
19+
try {
20+
db.exec(`PRAGMA encoding='${encoding}'; CREATE TABLE events (
21+
id INTEGER PRIMARY KEY, run_id TEXT, payload TEXT NOT NULL
22+
); CREATE INDEX event_run ON events(run_id,id);`);
23+
const insert = db.prepare('INSERT INTO events(run_id,payload) VALUES(?,?)');
24+
insert.run('one', JSON.stringify({ text: '\u4e2d\u{1f600}\\' }));
25+
insert.run('other', text);
26+
insert.run('one', 'with\0trailing-bytes');
27+
insert.run('one', JSON.stringify({ text }));
28+
insert.run('one', Buffer.from([0, 0xff, 0x80, 0]));
29+
assert.equal(db.prepare('PRAGMA encoding').get()?.encoding, encoding);
30+
const [a, b, c, d] = db
31+
.prepare(
32+
"SELECT length(CAST(payload AS BLOB)) AS bytes FROM events WHERE run_id='one' ORDER BY id",
33+
)
34+
.all()
35+
.map((r) => Number(r.bytes)) as [number, number, number, number];
36+
assert.ok(c > budget);
37+
assert.deepEqual(planReplayPage(db, 'one', 0, 500, a + b - 1), {
38+
count: 1,
39+
bytes: a,
40+
more: true,
41+
});
42+
assert.deepEqual(planReplayPage(db, 'one', 0, 500, a + b), {
43+
count: 2,
44+
bytes: a + b,
45+
more: true,
46+
});
47+
assert.deepEqual(planReplayPage(db, 'one', 3, 500, budget), {
48+
count: 1,
49+
bytes: c,
50+
more: true,
51+
});
52+
assert.deepEqual(planReplayPage(db, 'one', 4, 500, budget), {
53+
count: 1,
54+
bytes: d,
55+
more: false,
56+
});
57+
assert.deepEqual(planReplayPage(db, 'one', 5, 500, budget), {
58+
count: 0,
59+
bytes: 0,
60+
more: false,
61+
});
62+
} finally {
63+
db.close();
64+
}
65+
});
66+
1267
async function fixture() {
1368
const s = await setup();
1469
s.store.publish('owner', makeBundle(agent()));

0 commit comments

Comments
 (0)