Skip to content

Commit 04ef9be

Browse files
author
hzq
committed
Reserve bytes before reading large SSE replay pages
Keep waiting requests on metadata only, rotate eligible callers, and hold reservations through transport drain or close. Verify cancellation, authorization and independent readers.
1 parent 7d2bddd commit 04ef9be

10 files changed

Lines changed: 444 additions & 14 deletions

File tree

‎bench/slow-sse-replay.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { AbortableWait } from '../src/core/abortable-wait.js';
88
import type { RunEvent } from '../src/core/contracts.js';
99
import { sha } from '../src/core/util.js';
1010
import { createGateway } from '../src/gateway/server.js';
11+
import { replayBudget } from '../src/gateway/replay-budget.js';
1112
import { streamSlots } from '../src/gateway/stream-slots.js';
1213
import { makeBundle } from '../src/lang/bundle.js';
1314
import { agent, FixtureModel, setup, token, waitFor } from '../test/helpers.js';
@@ -197,8 +198,11 @@ async function trial() {
197198
const timings = await new AbortableWait(report.promise).wait(AbortSignal.timeout(10_000));
198199
const memory = profiling?.finish();
199200
profiling = undefined;
201+
const budget = replayBudget(gw.store);
202+
const pausedBudget = budget.usage();
200203
requests.forEach((request) => request.destroy());
201204
await waitFor(() => streamSlots(gw.store).count(principal).subject === 0);
205+
assert.deepEqual(budget.usage(), { bytes: 0, waiting: 0 });
202206
gw.store.recentHistory = recent;
203207
if (replay) gw.store.replayHistory = replay;
204208
gw.store.run = snapshot;
@@ -244,6 +248,7 @@ async function trial() {
244248
full_run_reads: snapshotReads,
245249
max_response_queue_bytes: Math.max(...queued),
246250
per_connection_queue_bytes: queued,
251+
paused_replay_budget: pausedBudget,
247252
health_under_load: healthSummary(timings, launch, stopped),
248253
health_first_400ms: healthSummary(timings, launch, launch + 400),
249254
...(memory ? { memory } : {}),

‎docs/stability.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,12 @@ write progress without changing event IDs or payloads. A backpressured write or
296296
with no queue progress for 30 seconds destroys the connection. A stream slot
297297
is held until Node finishes handing off the response or the connection closes; this does not
298298
confirm receipt by the client.
299+
Historical replay pages above 256 KiB reserve stored payload bytes before loading the page:
300+
32 MiB per gateway and 8 MiB per caller. A legal event exceeding a limit can use that budget
301+
alone. Waiters do not materialize the page; they recheck access and size before reading, and
302+
leave on disconnect or after five seconds. An expired or full replay queue returns a stream
303+
capacity error without advancing the cursor. Small replay pages and live events do not use
304+
this budget, which is not a limit on all process memory.
299305

300306
New HTTP run submissions (including media jobs and workflow drafts) wait for SQLite's writer
301307
without blocking the gateway. The wait is at most the connection timeout or five seconds,

‎docs/zh-CN/stability.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
128128

129129
`node dist/bench/slow-sse-replay.js --clients 8` 会重启模拟网关,让八条本机 SSE 连接在冷缓存重放期间暂停读取,并由独立线程探测 `/health`。它分别报告历史页的已存载荷字节数和 Node 响应队列,不等同于进程 RSS 或操作系统 TCP 缓冲。历史页按载荷字节分批,合法的大事件独占一页。背压消退后从该连接最后入写队列的事件 ID 继续;客户端重连仍以自己最后完整收到的事件 ID 为准。
130130
大帧只在 HTTP 写入层分块,不改变 SSE 的事件 ID 和内容。写入遇到背压或响应正在关闭时,写队列连续 30 秒没有进展就销毁连接。流名额保留到 Node 完成响应交付给传输层,或者连接关闭;这不代表客户端已收到全部内容。
131+
历史重放页超过 256 KiB 时,先按存储载荷预留预算,再读入正文:每网关 32 MiB、每调用方 8 MiB。超出额度的合法单帧可以独占对应预算。等待不读入该页正文,获准后重新核对授权和页大小;断线或等满五秒就退出。排队满或超时返回流容量错误,不推进游标。小页和实时事件不占这份预算,它也不是进程总内存上限。
131132

132133
`node --expose-gc dist/bench/slow-sse-replay.js --clients 24 --profile-memory` 会记录进程内存采样峰值、停读期间 GC 后仍保留的字节及各编码阶段耗时。原生 SSE 只在存储载荷与事件身份完全匹配时共享仍在发送队列里的大帧;每网关最多缓存四条,编码帧和存储证据保守计入 16 MiB 预算。各连接仍独立接受授权检查。
133134
加上 `--distinct-runs` 可让每条连接续读不同运行,不依赖大帧共享。原生 SSE 的大事件只有在写入时标记为由网关 JSON 序列化、并通过读取校验后,才直接使用存储载荷;旧事件和载荷被改写的事件仍走原来的解析与序列化路径。

‎src/gateway/compat-stream.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { Store } from '../store/store.js';
66
import { terminal, type Run, type RunEvent, type Usage } from '../core/contracts.js';
77
import { chatUsage, responseObject } from './protocol.js';
88
import { claudeDelta, claudeDeltaUsage, claudeMessage } from './claude.js';
9-
import { openEventStream } from './streams.js';
9+
import { openEventStream, revalidateObservation } from './streams.js';
1010
import { writeNativeReplay } from './native-replay-wire.js';
1111
import { attachRunReplay } from './run-replay.js';
1212
import { streamSlots } from './stream-slots.js';
@@ -559,6 +559,8 @@ export function streamEvents(
559559
};
560560
attachRunReplay(store, runId, stream, {
561561
native: mode === 'native',
562+
subject: req.principal.keyId ?? `${req.principal.owner}\n${req.principal.name}`,
563+
revalidate: () => revalidateObservation(auth, req),
562564
cursor: () => last,
563565
event: onEvent,
564566
ready: afterReplay,

‎src/gateway/replay-budget.ts‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { abortError, checkAbort, Fault } from '../core/util.js';
2+
3+
type Release = () => void;
4+
type Limits = { gateway: number; subject: number; waiters: number; waitMs: number };
5+
type Waiter = {
6+
bytes: number;
7+
resolve: (release: Release) => void;
8+
cleanup: () => void;
9+
};
10+
11+
const DEFAULT_LIMITS: Limits = {
12+
gateway: 32 * 1024 * 1024,
13+
subject: 8 * 1024 * 1024,
14+
waiters: 128,
15+
waitMs: 5000,
16+
};
17+
const busy = () =>
18+
new Fault(
19+
'too_many_streams',
20+
'Replay byte capacity is busy. Reconnect from the last complete event.',
21+
429,
22+
);
23+
24+
/** Budget stored payload bytes for large replay writes, not all process or TCP memory. */
25+
export class ReplayBudget {
26+
private held = 0;
27+
private readonly heldBySubject = new Map<string, number>();
28+
private readonly queues = new Map<string, Waiter[]>();
29+
private waiting = 0;
30+
31+
constructor(private readonly limits: Limits = DEFAULT_LIMITS) {}
32+
33+
usage() {
34+
return { bytes: this.held, waiting: this.waiting };
35+
}
36+
37+
reserve(subject: string, bytes: number, signal: AbortSignal): Release | Promise<Release> {
38+
checkAbort(signal);
39+
if (!this.queues.has(subject) && this.fits(subject, bytes)) return this.take(subject, bytes);
40+
if (this.waiting >= this.limits.waiters) throw busy();
41+
return new Promise((resolve, reject) => {
42+
const cancel = (error: unknown) => {
43+
this.remove(subject, waiter);
44+
reject(error);
45+
this.dispatch();
46+
};
47+
const abort = () => cancel(abortError());
48+
const timeout = setTimeout(() => cancel(busy()), this.limits.waitMs);
49+
const waiter = {
50+
bytes,
51+
resolve,
52+
cleanup: () => {
53+
clearTimeout(timeout);
54+
signal.removeEventListener('abort', abort);
55+
},
56+
};
57+
const queue = this.queues.get(subject);
58+
if (queue) queue.push(waiter);
59+
else this.queues.set(subject, [waiter]);
60+
this.waiting++;
61+
signal.addEventListener('abort', abort, { once: true });
62+
});
63+
}
64+
65+
private fits(subject: string, bytes: number) {
66+
const owned = this.heldBySubject.get(subject) ?? 0;
67+
// A legitimate singleton can exceed a budget, but cannot share that budget with another frame.
68+
return (
69+
(owned === 0 || owned + bytes <= this.limits.subject) &&
70+
(this.held === 0 || this.held + bytes <= this.limits.gateway)
71+
);
72+
}
73+
74+
private take(subject: string, bytes: number): Release {
75+
this.held += bytes;
76+
this.heldBySubject.set(subject, (this.heldBySubject.get(subject) ?? 0) + bytes);
77+
let released = false;
78+
return () => {
79+
if (released) return;
80+
released = true;
81+
this.held -= bytes;
82+
const remaining = this.heldBySubject.get(subject)! - bytes;
83+
if (remaining) this.heldBySubject.set(subject, remaining);
84+
else this.heldBySubject.delete(subject);
85+
this.dispatch();
86+
};
87+
}
88+
89+
private remove(subject: string, waiter: Waiter) {
90+
const queue = this.queues.get(subject)!;
91+
queue.splice(queue.indexOf(waiter), 1);
92+
if (!queue.length) this.queues.delete(subject);
93+
this.waiting--;
94+
waiter.cleanup();
95+
}
96+
97+
private dispatch() {
98+
while (this.waiting) {
99+
let granted = false;
100+
for (const [subject, queue] of this.queues) {
101+
const first = queue[0]!;
102+
if (!this.fits(subject, first.bytes)) continue;
103+
this.remove(subject, first);
104+
if (queue.length) {
105+
this.queues.delete(subject);
106+
this.queues.set(subject, queue);
107+
}
108+
first.resolve(this.take(subject, first.bytes));
109+
granted = true;
110+
break;
111+
}
112+
if (!granted) break;
113+
}
114+
}
115+
}
116+
117+
const budgets = new WeakMap<object, ReplayBudget>();
118+
export function replayBudget(store: object) {
119+
let budget = budgets.get(store);
120+
if (!budget) {
121+
budget = new ReplayBudget();
122+
budgets.set(store, budget);
123+
}
124+
return budget;
125+
}

‎src/gateway/run-replay.ts‎

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { setImmediate as nextTurn } from 'node:timers/promises';
22
import type { RunEvent } from '../core/contracts.js';
33
import type { Store } from '../store/store.js';
4+
import type { ReplayPagePlan } from '../store/event-history.js';
5+
import { replayBudget } from './replay-budget.js';
46
import type { openEventStream } from './streams.js';
57

68
const REPLAY_BATCH = 500;
@@ -9,16 +11,18 @@ const REPLAY_HIGH_WATER = 1024 * 1024;
911

1012
type ReplayStream = Pick<
1113
ReturnType<typeof openEventStream>,
12-
'closed' | 'backlog' | 'drained' | 'onClose'
14+
'closed' | 'backlog' | 'drained' | 'onClose' | 'onTransportClose'
1315
>;
1416

1517
/** Reads committed events by cursor; a stalled client never accumulates an in-memory event list. */
1618
export function attachRunReplay(
17-
store: Pick<Store, 'events' | 'replayHistory'>,
19+
store: Pick<Store, 'events' | 'planReplayHistory' | 'replayHistory'>,
1820
runId: string,
1921
stream: ReplayStream,
2022
observer: {
2123
native?: boolean;
24+
subject: string;
25+
revalidate: () => void;
2226
cursor: () => number;
2327
event: (event: RunEvent) => void;
2428
ready: () => void;
@@ -27,13 +31,17 @@ export function attachRunReplay(
2731
) {
2832
let catchingUp = false;
2933
let behind = false;
30-
const sendPage = () => {
34+
const cancellation = new AbortController();
35+
const planPage = (after: number) =>
36+
store.planReplayHistory(runId, after, REPLAY_BATCH, REPLAY_PAGE_BYTES);
37+
const sendPage = (after: number, plan: ReplayPagePlan) => {
3138
const { events, more } = store.replayHistory(
3239
runId,
33-
observer.cursor(),
40+
after,
3441
REPLAY_BATCH,
3542
REPLAY_PAGE_BYTES,
3643
observer.native,
44+
plan,
3745
);
3846
for (const event of events) {
3947
if (stream.closed) return false;
@@ -42,6 +50,45 @@ export function attachRunReplay(
4250
}
4351
return more;
4452
};
53+
const sendLarge = async (after: number, initial: ReplayPagePlan) => {
54+
const reservation = replayBudget(store).reserve(
55+
observer.subject,
56+
initial.bytes,
57+
cancellation.signal,
58+
);
59+
const release = typeof reservation === 'function' ? reservation : await reservation;
60+
if (stream.closed) {
61+
release();
62+
return false;
63+
}
64+
let plan = initial;
65+
if (typeof reservation !== 'function') {
66+
try {
67+
// No payload was loaded while queued. Recheck access and the current page before reading.
68+
observer.revalidate();
69+
plan = planPage(after);
70+
} catch (error) {
71+
release();
72+
throw error;
73+
}
74+
if (plan.bytes > initial.bytes) {
75+
release();
76+
return true;
77+
}
78+
if (plan.bytes <= REPLAY_PAGE_BYTES) {
79+
release();
80+
return sendPage(after, plan);
81+
}
82+
}
83+
const detach = stream.onTransportClose(release);
84+
const more = sendPage(after, plan);
85+
// A conclusively drained stream can release early; a closing response still owns its writes.
86+
if (await stream.drained(0)) {
87+
detach();
88+
release();
89+
}
90+
return more;
91+
};
4592
const pump = async () => {
4693
if (catchingUp) {
4794
behind = true;
@@ -55,8 +102,12 @@ export function attachRunReplay(
55102
if (stream.closed) return;
56103
if (stream.backlog() > REPLAY_HIGH_WATER && !(await stream.drained(REPLAY_HIGH_WATER)))
57104
return;
105+
const after = observer.cursor();
106+
const plan = planPage(after);
58107
// Drop the page before any await: a paused socket only retains its write queue.
59-
if (!sendPage()) break;
108+
const more =
109+
plan.bytes > REPLAY_PAGE_BYTES ? await sendLarge(after, plan) : sendPage(after, plan);
110+
if (!more) break;
60111
if (!stream.closed && stream.backlog() <= REPLAY_HIGH_WATER) await nextTurn();
61112
}
62113
} while (behind && !stream.closed);
@@ -70,6 +121,9 @@ export function attachRunReplay(
70121
else void pump().catch(observer.error);
71122
};
72123
store.events.on(runId, live);
73-
stream.onClose(() => store.events.off(runId, live));
124+
stream.onClose(() => {
125+
store.events.off(runId, live);
126+
cancellation.abort();
127+
});
74128
void pump().then(observer.ready).catch(observer.error);
75129
}

‎src/gateway/streams.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ export function openEventStream(
316316
onTransportClose(dispose: () => void) {
317317
if (transportDone) dispose();
318318
else transportCleanup.add(dispose);
319+
return () => transportCleanup.delete(dispose);
319320
},
320321
};
321322
}

‎src/store/event-history.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,13 @@ export function readEventHistory(
9292
});
9393
}
9494

95-
/** Bound payloads before materializing them; a single oversized event can still advance. */
96-
export function readReplayPage(
95+
/** Plan without fetching payloads; a single oversized event can still advance. */
96+
export function planReplayPage(
9797
store: HistoryReader,
9898
runId: string,
9999
after: number,
100100
limit: number,
101101
maxBytes: number,
102-
native: boolean,
103102
) {
104103
let count = 0;
105104
let bytes = 0;
@@ -121,5 +120,22 @@ export function readReplayPage(
121120
break;
122121
}
123122
}
124-
return { events: count ? readEventHistory(store, runId, after, count, native) : [], more };
123+
return { count, bytes, more };
124+
}
125+
126+
export type ReplayPagePlan = ReturnType<typeof planReplayPage>;
127+
128+
export function readReplayPage(
129+
store: HistoryReader,
130+
runId: string,
131+
after: number,
132+
limit: number,
133+
maxBytes: number,
134+
native: boolean,
135+
plan = planReplayPage(store, runId, after, limit, maxBytes),
136+
) {
137+
return {
138+
events: plan.count ? readEventHistory(store, runId, after, plan.count, native) : [],
139+
more: plan.more,
140+
};
125141
}

‎src/store/store.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,13 @@ import {
2323
type SummaryRow,
2424
} from './run-snapshot.js';
2525
import { readRun } from './run-read.js';
26-
import { installEventWireFormat, readEventHistory, readReplayPage } from './event-history.js';
26+
import {
27+
installEventWireFormat,
28+
planReplayPage,
29+
readEventHistory,
30+
readReplayPage,
31+
type ReplayPagePlan,
32+
} from './event-history.js';
2733
import { installRunStateIndexes, runPendingActions, runStepCounts } from './run-state-rows.js';
2834
import { inputPreview, textPrefix } from './inspection.js';
2935
import { Fault, noAgent, sha, readBounded } from '../core/util.js';
@@ -1248,8 +1254,18 @@ export class Store {
12481254
}
12491255
return this.history(runId, after, limit);
12501256
}
1251-
replayHistory(runId: string, after: number, limit: number, maxBytes: number, native = false) {
1252-
return readReplayPage(this, runId, after, limit, maxBytes, native);
1257+
planReplayHistory(runId: string, after: number, limit: number, maxBytes: number) {
1258+
return planReplayPage(this, runId, after, limit, maxBytes);
1259+
}
1260+
replayHistory(
1261+
runId: string,
1262+
after: number,
1263+
limit: number,
1264+
maxBytes: number,
1265+
native = false,
1266+
plan?: ReplayPagePlan,
1267+
) {
1268+
return readReplayPage(this, runId, after, limit, maxBytes, native, plan);
12531269
}
12541270
history(runId: string, after = 0, limit = 1000): RunEvent[] {
12551271
return readEventHistory(this, runId, after, limit);

0 commit comments

Comments
 (0)