Skip to content

Commit b264f60

Browse files
author
hzq
committed
Share active native SSE replay frames
Reuse large encoded frames only for exact stored events and authorized scopes. Bound and release the cache with the write queue, and profile process memory and encoding costs under paused readers.
1 parent b8d9bec commit b264f60

12 files changed

Lines changed: 400 additions & 26 deletions

‎bench/slow-sse-replay.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ import { streamSlots } from '../src/gateway/stream-slots.js';
1212
import { makeBundle } from '../src/lang/bundle.js';
1313
import { agent, FixtureModel, setup, token, waitFor } from '../test/helpers.js';
1414
import type { ReadProbeReport } from './caller-cancel-read-probe.js';
15+
import { profileSseMemory } from './sse-memory-profile.js';
1516

1617
const { values } = parseArgs({
1718
options: {
1819
clients: { type: 'string', default: '8' },
1920
trials: { type: 'string', default: '3' },
21+
'profile-memory': { type: 'boolean' },
2022
},
2123
});
2224
const clients = Number(values.clients);
@@ -58,6 +60,7 @@ async function trial() {
5860
const s = await setup(driver);
5961
let next: Awaited<ReturnType<typeof createGateway>> | undefined;
6062
let worker: Worker | undefined;
63+
let profiling: ReturnType<typeof profileSseMemory> | undefined;
6164
const requests: ClientRequest[] = [];
6265
try {
6366
const model = 'agent/slow-replay-fixture';
@@ -88,7 +91,9 @@ async function trial() {
8891
const index = Number(raw);
8992
const write = res.write;
9093
res.write = function (this: typeof res, ...args: unknown[]) {
94+
const start = profiling ? performance.now() : 0;
9195
const result = Reflect.apply(write, this, args) as boolean;
96+
profiling?.observeWrite(performance.now() - start);
9297
queued[index] = Math.max(queued[index]!, this.writableLength);
9398
return result;
9499
};
@@ -135,6 +140,7 @@ async function trial() {
135140
});
136141
void report.promise.catch(() => {});
137142
await new AbortableWait(ready.promise).wait(AbortSignal.timeout(10_000));
143+
if (values['profile-memory']) profiling = profileSseMemory(run);
138144
const launch = Date.now();
139145
await new AbortableWait(
140146
Promise.all(
@@ -172,9 +178,11 @@ async function trial() {
172178
const connected = Date.now();
173179
await sleep(pauseMs);
174180
const stopped = Date.now();
175-
requests.forEach((request) => request.destroy());
176181
worker.postMessage('stop');
177182
const timings = await new AbortableWait(report.promise).wait(AbortSignal.timeout(10_000));
183+
const memory = profiling?.finish();
184+
profiling = undefined;
185+
requests.forEach((request) => request.destroy());
178186
await waitFor(() => streamSlots(gw.store).count(principal).subject === 0);
179187
gw.store.recentHistory = recent;
180188
if (replay) gw.store.replayHistory = replay;
@@ -223,8 +231,10 @@ async function trial() {
223231
per_connection_queue_bytes: queued,
224232
health_under_load: healthSummary(timings, launch, stopped),
225233
health_first_400ms: healthSummary(timings, launch, launch + 400),
234+
...(memory ? { memory } : {}),
226235
};
227236
} finally {
237+
profiling?.dispose();
228238
requests.forEach((request) => request.destroy());
229239
await worker?.terminate();
230240
await next?.app.close();

‎bench/sse-memory-profile.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import assert from 'node:assert/strict';
2+
import { performance } from 'node:perf_hooks';
3+
4+
const memory = () => {
5+
const { rss, heapUsed, external, arrayBuffers } = process.memoryUsage();
6+
return { rss, heapUsed, external, arrayBuffers };
7+
};
8+
type Memory = ReturnType<typeof memory>;
9+
const fields = ['rss', 'heapUsed', 'external', 'arrayBuffers'] as const;
10+
const delta = (end: Memory, start: Memory) =>
11+
Object.fromEntries(fields.map((field) => [field, end[field] - start[field]]));
12+
13+
/** Local fixture instrumentation only; production calls are not patched. */
14+
export function profileSseMemory(run: string) {
15+
const gc = global.gc;
16+
assert.ok(gc, 'Run the benchmark with node --expose-gc for --profile-memory');
17+
gc();
18+
const baseline = memory();
19+
const peak = { ...baseline };
20+
const sample = () => {
21+
const current = memory();
22+
for (const field of fields) peak[field] = Math.max(peak[field], current[field]);
23+
};
24+
const timer = setInterval(sample, 10);
25+
const stringify = JSON.stringify;
26+
const from = Buffer.from;
27+
let stringifyMs = 0;
28+
let serializedEvents = 0;
29+
let fullFrameBufferMs = 0;
30+
let fullFrameBufferBytes = 0;
31+
let writeCalls = 0;
32+
let writeMs = 0;
33+
JSON.stringify = ((value: unknown, ...rest: unknown[]) => {
34+
if (!value || typeof value !== 'object' || !('runId' in value) || value.runId !== run)
35+
return Reflect.apply(stringify, JSON, [value, ...rest]);
36+
const at = performance.now();
37+
const result = Reflect.apply(stringify, JSON, [value, ...rest]);
38+
stringifyMs += performance.now() - at;
39+
serializedEvents++;
40+
return result;
41+
}) as typeof JSON.stringify;
42+
Buffer.from = ((value: unknown, ...rest: unknown[]) => {
43+
if (typeof value !== 'string' || value.length < 128 * 1024 || !value.startsWith('id: '))
44+
return Reflect.apply(from, Buffer, [value, ...rest]);
45+
const at = performance.now();
46+
const result = Reflect.apply(from, Buffer, [value, ...rest]);
47+
fullFrameBufferMs += performance.now() - at;
48+
fullFrameBufferBytes += result.byteLength;
49+
return result;
50+
}) as typeof Buffer.from;
51+
const dispose = () => {
52+
clearInterval(timer);
53+
JSON.stringify = stringify;
54+
Buffer.from = from;
55+
};
56+
return {
57+
observeWrite(ms: number) {
58+
writeCalls++;
59+
writeMs += ms;
60+
},
61+
finish() {
62+
sample();
63+
dispose();
64+
gc();
65+
return {
66+
sampled_peak_delta_bytes: delta(peak, baseline),
67+
paused_after_gc_delta_bytes: delta(memory(), baseline),
68+
encoding: {
69+
serialized_events: serializedEvents,
70+
stringify_ms: stringifyMs,
71+
full_frame_buffer_ms: fullFrameBufferMs,
72+
full_frame_buffer_bytes: fullFrameBufferBytes,
73+
write_calls: writeCalls,
74+
write_ms: writeMs,
75+
},
76+
};
77+
},
78+
dispose,
79+
};
80+
}

‎docs/stability.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,13 @@ reports stored event bytes per replay page and the Node response queue separatel
276276
RSS or the operating system's TCP buffers. Replay pages are bounded by stored payload bytes;
277277
an oversized legal event stands alone in its page. After backpressure clears, replay continues
278278
after the last event queued on that connection. Reconnecting clients use the last complete ID they received.
279+
For process memory and CPU phase measurements, use
280+
`node --expose-gc dist/bench/slow-sse-replay.js --clients 24 --profile-memory`. This reports
281+
sampled peaks and retained bytes after GC while sockets are paused. Native SSE can share a
282+
large encoded replay frame while it is queued only if the freshly read payload and event
283+
identity match exactly. The cache is limited to four entries and 16 MiB per gateway,
284+
counting encoded frames and a conservative UTF-16 size for stored payload evidence.
285+
Each connection still checks its own authorization before replay.
279286
Large SSE frames are split only at the HTTP write boundary, so the gateway can observe partial
280287
write progress without changing event IDs or payloads. A backpressured write or closing response
281288
with no queue progress for 30 seconds destroys the connection. A stream slot

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
129129
`node dist/bench/slow-sse-replay.js --clients 8` 会重启模拟网关,让八条本机 SSE 连接在冷缓存重放期间暂停读取,并由独立线程探测 `/health`。它分别报告历史页的已存载荷字节数和 Node 响应队列,不等同于进程 RSS 或操作系统 TCP 缓冲。历史页按载荷字节分批,合法的大事件独占一页。背压消退后从该连接最后入写队列的事件 ID 继续;客户端重连仍以自己最后完整收到的事件 ID 为准。
130130
大帧只在 HTTP 写入层分块,不改变 SSE 的事件 ID 和内容。写入遇到背压或响应正在关闭时,写队列连续 30 秒没有进展就销毁连接。流名额保留到 Node 完成响应交付给传输层,或者连接关闭;这不代表客户端已收到全部内容。
131131

132+
`node --expose-gc dist/bench/slow-sse-replay.js --clients 24 --profile-memory` 会记录进程内存采样峰值、停读期间 GC 后仍保留的字节及各编码阶段耗时。原生 SSE 只在存储载荷与事件身份完全匹配时共享仍在发送队列里的大帧;每网关最多缓存四条,编码帧和按 UTF-16 保守估算的存储证据合计不超过 16 MiB。各连接仍独立接受授权检查。
133+
132134
通过 HTTP 创建运行时(包括媒体任务和工作流草稿),网关异步等写锁,不让整个事件循环停下来。等待时间不超过连接超时和 5 秒中的较短者。
133135
等待队列先进先出,每个 owner 最多 8 个请求,全网关最多 64 个;请求体另按每个 owner 32 MiB、全网关 64 MiB 限制。
134136
超时或排满返回 `503 admission_busy` 和 `Retry-After: 1`,不创建任务或预占用量。已有结果的幂等重放不等写锁。

‎src/gateway/compat-stream.ts‎

Lines changed: 3 additions & 1 deletion
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 { writeNativeReplay } from './native-replay-wire.js';
1011
import { attachRunReplay } from './run-replay.js';
1112
import { streamSlots } from './stream-slots.js';
1213
import { sseRequested } from './compat-errors.js';
@@ -282,7 +283,7 @@ export function streamEvents(
282283
const terminalEvent = isTerminalEvent(e.type);
283284
if (lines) writeProgress(e, terminalEvent);
284285

285-
if (mode === 'native') write(`id: ${e.id}\nevent: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`);
286+
if (mode === 'native') writeNativeReplay(store, req.principal.owner, e, stream);
286287
else if (mode === 'responses' && e.type.startsWith('response.')) {
287288
writeResponses(e.type, e.data);
288289
} else if (mode === 'responses' && bridged && handOffEvent(e.type)) {
@@ -557,6 +558,7 @@ export function streamEvents(
557558
close();
558559
};
559560
attachRunReplay(store, runId, stream, {
561+
native: mode === 'native',
560562
cursor: () => last,
561563
event: onEvent,
562564
ready: afterReplay,

‎src/gateway/native-replay-wire.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import type { RunEvent } from '../core/contracts.js';
2+
import { replayPayloadOf } from '../store/event-history.js';
3+
import type { Store } from '../store/store.js';
4+
import type { openEventStream } from './streams.js';
5+
6+
const CACHE_BYTES = 16 * 1024 * 1024;
7+
const CACHE_ENTRIES = 4;
8+
type Entry = {
9+
owner: string;
10+
run: string;
11+
type: string;
12+
time: number;
13+
payload: string;
14+
buffer: Buffer;
15+
weight: number;
16+
users: number;
17+
};
18+
type Cache = { entries: Map<number, Entry>; weight: number };
19+
const caches = new WeakMap<Store, Cache>();
20+
21+
export const nativeEventWire = (event: RunEvent) =>
22+
`id: ${event.id}\nevent: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
23+
24+
export function writeNativeReplay(
25+
store: Store,
26+
owner: string,
27+
event: RunEvent,
28+
stream: Pick<ReturnType<typeof openEventStream>, 'write' | 'writeEncoded'>,
29+
) {
30+
if (
31+
replayPayloadOf(event) !== undefined &&
32+
stream.writeEncoded(() => leaseNativeReplayWire(store, owner, event)) !== undefined
33+
)
34+
return;
35+
stream.write(nativeEventWire(event));
36+
}
37+
38+
/** Share only active, large native replay frames whose current stored bytes match exactly. */
39+
export function leaseNativeReplayWire(store: Store, owner: string, event: RunEvent) {
40+
const payload = replayPayloadOf(event);
41+
if (payload === undefined) return;
42+
let cache = caches.get(store);
43+
if (!cache) {
44+
cache = { entries: new Map(), weight: 0 };
45+
caches.set(store, cache);
46+
}
47+
const { entries } = cache;
48+
let entry = entries.get(event.id);
49+
if (entry) {
50+
// This is a byte reuse check, not an authorization check or an independent source of truth.
51+
if (
52+
entry.owner !== owner ||
53+
entry.run !== event.runId ||
54+
entry.type !== event.type ||
55+
entry.time !== event.time ||
56+
entry.payload !== payload
57+
)
58+
return;
59+
} else {
60+
if (entries.size >= CACHE_ENTRIES || cache.weight + payload.length * 2 > CACHE_BYTES) return;
61+
const buffer = Buffer.from(nativeEventWire(event));
62+
const weight = buffer.length + payload.length * 2;
63+
if (cache.weight + weight > CACHE_BYTES) return { buffer, release: () => {} };
64+
entry = {
65+
owner,
66+
run: event.runId,
67+
type: event.type,
68+
time: event.time,
69+
payload,
70+
buffer,
71+
weight,
72+
users: 0,
73+
};
74+
entries.set(event.id, entry);
75+
cache.weight += weight;
76+
}
77+
const active = entry;
78+
const state = cache;
79+
const id = event.id;
80+
active.users++;
81+
let released = false;
82+
return {
83+
buffer: active.buffer,
84+
release: () => {
85+
if (released) return;
86+
released = true;
87+
if (--active.users) return;
88+
entries.delete(id);
89+
state.weight -= active.weight;
90+
},
91+
};
92+
}

‎src/gateway/run-replay.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export function attachRunReplay(
1818
runId: string,
1919
stream: ReplayStream,
2020
observer: {
21+
native?: boolean;
2122
cursor: () => number;
2223
event: (event: RunEvent) => void;
2324
ready: () => void;
@@ -32,6 +33,7 @@ export function attachRunReplay(
3233
observer.cursor(),
3334
REPLAY_BATCH,
3435
REPLAY_PAGE_BYTES,
36+
observer.native,
3537
);
3638
for (const event of events) {
3739
if (stream.closed) return false;

‎src/gateway/streams.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export function openEventStream(
5353
let transportDone = false;
5454
let pendingChunks: string[] = [];
5555
let pendingBytes = 0;
56-
let fragment: { buffer: Buffer; offset: number } | undefined;
56+
let fragment: { buffer: Buffer; offset: number; release?: () => void } | undefined;
5757
let blocked = false;
5858
let flushScheduled = false;
5959
let watchdog: NodeJS.Timeout | undefined;
@@ -72,6 +72,7 @@ export function openEventStream(
7272
const discardWrites = () => {
7373
pendingChunks = [];
7474
pendingBytes = 0;
75+
fragment?.release?.();
7576
fragment = undefined;
7677
blocked = false;
7778
raw.off('drain', resumeWrites);
@@ -104,7 +105,10 @@ export function openEventStream(
104105
const end = Math.min(offset + WRITE_CHUNK_BYTES, buffer.length);
105106
const part = buffer.subarray(offset, end);
106107
pendingBytes -= part.length;
107-
fragment = end === buffer.length ? undefined : { buffer, offset: end };
108+
if (end === buffer.length) {
109+
fragment.release?.();
110+
fragment = undefined;
111+
} else fragment.offset = end;
108112
if (!raw.write(part)) backpressure();
109113
}
110114
if (finishing && !pendingBytes && !raw.writableEnded) raw.end();
@@ -203,6 +207,21 @@ export function openEventStream(
203207
}
204208
return !closed;
205209
};
210+
const writeEncoded = (load: () => { buffer: Buffer; release: () => void } | undefined) => {
211+
if (closed) return false;
212+
// Only take a shared frame when it can enter the queue without copying or overtaking text.
213+
if (pendingBytes) return undefined;
214+
if (backlog() > bufferedBytes) {
215+
abortClose();
216+
return false;
217+
}
218+
const frame = load();
219+
if (!frame) return undefined;
220+
pendingBytes = frame.buffer.length;
221+
fragment = { buffer: frame.buffer, offset: 0, release: frame.release };
222+
flush();
223+
return !closed;
224+
};
206225

207226
const stopAuthorization = observeAuthorization(auth, req, revoke);
208227
const heartbeatFrame =
@@ -269,6 +288,7 @@ export function openEventStream(
269288

270289
return {
271290
write,
291+
writeEncoded,
272292
close,
273293
backlog,
274294
drained,

0 commit comments

Comments
 (0)