Skip to content

Commit 040801c

Browse files
author
hzq
committed
Bound retained run output and protect settlement readback
Remove the unused event ring and cap cached output projections without letting completed reads displace writers. Preserve runs with an unsettled receipt across online maintenance and verify reconstruction after eviction.
1 parent f41e8e8 commit 040801c

13 files changed

Lines changed: 350 additions & 142 deletions

‎bench/event-retention.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ try {
6060
]),
6161
);
6262

63-
const terminalIds = ids.map((id, i) => {
63+
const cursors = ids.map((id, i) => {
6464
const row = s.store
6565
.prepare("SELECT id FROM events WHERE run_id=? AND type='response.completed'")
6666
.get(id)!;
@@ -78,11 +78,24 @@ try {
7878
const passes = 50;
7979
for (let pass = 0; pass < passes; pass++)
8080
for (const [i, id] of ids.entries()) {
81-
const page = s.store.planReplayHistory(id, terminalIds[i]!, 500, REPLAY_PAGE_BYTES);
81+
const page = s.store.planReplayHistory(id, cursors[i]!, 500, REPLAY_PAGE_BYTES);
8282
assert.equal(page.count, 1);
8383
assert.ok(page.bytes > REPLAY_PAGE_BYTES);
8484
planned += page.bytes;
8585
}
86+
const planMs = performance.now() - planStart;
87+
const read = (id: string, expected: string) => {
88+
const start = performance.now();
89+
const output = s.store.runOutput(id, 'owner').output;
90+
const ms = performance.now() - start;
91+
assert.equal(sha(output[0]!.text), expected);
92+
return ms;
93+
};
94+
const recent = sha(text(runs + 1));
95+
let recentMs = 0;
96+
for (let i = 0; i < 12; i++) recentMs += read(ids.at(-1)!, recent);
97+
const older = ids.slice(0, 12);
98+
const olderMs = older.reduce((ms, id, i) => ms + read(id, sha(text(i + 2))), 0);
8699
console.log(
87100
JSON.stringify({
88101
runs,
@@ -92,7 +105,12 @@ try {
92105
replay_plan: {
93106
calls: passes * runs,
94107
observed_bytes: planned,
95-
total_ms: performance.now() - planStart,
108+
total_ms: planMs,
109+
},
110+
projection_reads: {
111+
newest_12_reads_ms: recentMs,
112+
oldest_count: older.length,
113+
oldest_total_ms: olderMs,
96114
},
97115
}),
98116
);

‎bench/protocol-speed.ts‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import assert from 'node:assert/strict';
12
import { performance } from 'node:perf_hooks';
23
import { setup, agent, FixtureModel, principal } from '../test/helpers.js';
34
import { makeBundle } from '../src/lang/bundle.js';
@@ -22,13 +23,22 @@ async function main() {
2223
}
2324
const authMs = performance.now() - authStart;
2425

25-
// 2. Measure O(1) Protocol Auto-Detector throughput
26+
// 2. Measure protocol detection on identifiable request shapes.
2627
const payloads = [
2728
{ uap: '1.0', target: 'agent/test', input: 'hello' },
2829
{ protocol: 'oaa/1', agent: 'agent/test', input: 'hello' },
2930
{ model: 'agent/test', input: 'hello' },
30-
{ model: 'agent/test', messages: [{ role: 'user', content: 'hello' }] },
31-
{ model: 'agent/test', max_tokens: 512, messages: [{ role: 'user', content: 'hello' }] },
31+
{
32+
model: 'agent/test',
33+
max_completion_tokens: 512,
34+
messages: [{ role: 'user', content: 'hello' }],
35+
},
36+
{
37+
model: 'agent/test',
38+
max_tokens: 512,
39+
top_k: 4,
40+
messages: [{ role: 'user', content: 'hello' }],
41+
},
3242
{ contents: [{ role: 'user', parts: [{ text: 'hello' }] }] },
3343
];
3444
const detectIterations = 100_000;
@@ -38,7 +48,7 @@ async function main() {
3848
}
3949
const detectMs = performance.now() - detectStart;
4050

41-
// 3. Compare HotEventRing recentHistory() vs SQLite history() and UAP-NDJSON vs SSE wire size
51+
// 3. Compare streaming wire sizes and measure durable history reads.
4252
const url = await s.listen();
4353

4454
const uapRes = await fetch(`${url}/v1/uap`, {
@@ -51,6 +61,7 @@ async function main() {
5161
delivery: { stream: true, format: 'uap-ndjson' },
5262
}),
5363
});
64+
assert.equal(uapRes.status, 200);
5465
const runId = uapRes.headers.get('x-run-id')!;
5566
const uapWireBytes = Buffer.byteLength(await uapRes.text());
5667

@@ -63,15 +74,10 @@ async function main() {
6374
messages: [{ role: 'user', content: 'stream test' }],
6475
}),
6576
});
77+
assert.equal(chatRes.status, 200);
6678
const chatWireBytes = Buffer.byteLength(await chatRes.text());
6779

6880
const replayIterations = 2_000;
69-
const ringStart = performance.now();
70-
for (let i = 0; i < replayIterations; i++) {
71-
s.store.recentHistory(runId, 0, 1000);
72-
}
73-
const ringMs = performance.now() - ringStart;
74-
7581
const sqliteStart = performance.now();
7682
for (let i = 0; i < replayIterations; i++) {
7783
s.store.history(runId, 0, 1000);
@@ -84,9 +90,7 @@ async function main() {
8490
uap_ndjson_wire_bytes_2k_output: uapWireBytes,
8591
openai_chat_sse_wire_bytes_2k_output: chatWireBytes,
8692
wire_byte_reduction_percent: Number(((1 - uapWireBytes / chatWireBytes) * 100).toFixed(1)),
87-
hot_event_ring_replay_ms_2000_iters: Number(ringMs.toFixed(2)),
8893
sqlite_history_replay_ms_2000_iters: Number(sqliteMs.toFixed(2)),
89-
replay_speedup_factor: Number((sqliteMs / Math.max(0.01, ringMs)).toFixed(1)),
9094
};
9195

9296
process.stdout.write(JSON.stringify(summary, null, 2) + '\n');

‎bench/slow-sse-replay.ts‎

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -111,29 +111,19 @@ async function trial() {
111111
return result;
112112
};
113113
});
114-
const recent = gw.store.recentHistory.bind(gw.store);
115-
const replay = gw.store.replayHistory?.bind(gw.store);
114+
const replay = gw.store.replayHistory.bind(gw.store);
116115
const ranges: [string, number, number][] = [];
117116
let historyMs = 0,
118117
snapshotReads = 0;
119-
gw.store.recentHistory = (...args) => {
118+
gw.store.replayHistory = (...args) => {
120119
const start = performance.now();
121-
const result = recent(...args);
120+
const result = replay(...args);
122121
historyMs += performance.now() - start;
123-
if (result.length) ranges.push([args[0], result[0]!.id, result.at(-1)!.id]);
122+
const events = result.events;
123+
if (events.length) ranges.push([args[0], events[0]!.id, events.at(-1)!.id]);
124124
profiling?.observeHistory();
125125
return result;
126126
};
127-
if (replay)
128-
gw.store.replayHistory = (...args) => {
129-
const start = performance.now();
130-
const result = replay(...args);
131-
historyMs += performance.now() - start;
132-
const events = result.events;
133-
if (events.length) ranges.push([args[0], events[0]!.id, events.at(-1)!.id]);
134-
profiling?.observeHistory();
135-
return result;
136-
};
137127
const snapshot = gw.store.run.bind(gw.store);
138128
gw.store.run = (...args) => {
139129
snapshotReads++;
@@ -203,8 +193,7 @@ async function trial() {
203193
requests.forEach((request) => request.destroy());
204194
await waitFor(() => streamSlots(gw.store).count(principal).subject === 0);
205195
assert.deepEqual(budget.usage(), { bytes: 0, waiting: 0 });
206-
gw.store.recentHistory = recent;
207-
if (replay) gw.store.replayHistory = replay;
196+
gw.store.replayHistory = replay;
208197
gw.store.run = snapshot;
209198
const bytes = gw.store.prepare(
210199
'SELECT sum(length(CAST(payload AS BLOB))) AS bytes FROM events WHERE run_id=? AND id BETWEEN ? AND ?',

‎docs/stability.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -303,14 +303,20 @@ leave on disconnect or after five seconds. An expired or full replay queue retur
303303
capacity error without advancing the cursor. The size pass uses SQLite's stored byte lengths
304304
without loading each event body. `node --expose-gc dist/bench/event-retention.js --runs 32`
305305
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
307-
256 KiB uses the same cursor and budget even for already-connected readers. It leaves the
306+
process memory. It also compares reads of recent and older output. A native SSE event with a
307+
committed payload above 256 KiB uses the same cursor and budget even for already-connected readers. It leaves the
308308
commit notification before reading the payload, so stalled readers do not make the producer
309309
encode the event separately for each connection. Small pages, ordinary live events, and direct
310310
live delivery in compatibility formats do not use this budget. It is not a process memory cap.
311311
`node --expose-gc dist/bench/live-sse-fanout.js --profile-memory` measures commit latency,
312312
encoding and retained process memory with already-connected readers paused before a large
313313
fixture output. It checks cursor replay after disconnect and does not call a model provider.
314+
Output projections retain at most 128 entries and 16 MiB of estimated bytes per gateway.
315+
Completed-run reads cannot displace an active writer's cached projection. Writers can still
316+
evict other writers at the hard limit. A miss reconstructs the same output from committed
317+
events, so older reads can cost more work. The estimate is not a process memory limit.
318+
Online maintenance also keeps runs whose settlement receipt is still being confirmed,
319+
even if the durable pending marker has already been removed.
314320
The wait queue has 128 places per gateway, at most 32 per key and 96 per owner.
315321
These are wait-slot limits, not changes to byte budgets or connection limits. A caller
316322
that can send immediately without joining a queue does not consume a wait slot.

‎docs/zh-CN/stability.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,9 @@ 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 个模拟大输出运行的生成耗时、保留内存和后续重放规划耗时。
133+
重放规划使用 SQLite 记录的字节长度,不为算大小读入事件正文。`node --expose-gc dist/bench/event-retention.js --runs 32` 分别报告 32 个模拟大输出运行的生成耗时、保留内存、重放规划耗时,以及读取最近和较早结果的成本。
134+
输出投影缓存每网关最多保留 128 个条目,按估算字节最多 16 MiB。读取已完成结果不会挤掉正在写入的投影;写入者互相竞争时仍可淘汰,不突破上限。未命中时从已提交记录重建,较早结果的读取可能更慢。这里限制的是缓存估算值,不是整个进程内存。
135+
在线清理会保留仍在核对结算回执的运行,即使数据库里的待结算标记已经移除。
134136
等待队列每网关最多 128 个名额,其中每密钥最多 32 个、每 owner 最多 96 个。这里只限制等待名额,不改变字节预算或连接数;能直接发送、不进队的请求不占等待名额。`node dist/bench/replay-queue-pressure.js` 会用固定预算占用夹具,让两个密钥各发 64 条本机请求来核对准入。
135137
调用方自身还有预算、却因网关预算等候至少 1.5 秒时,网关可以断开写队列也已至少 1.5 秒没有进展的重放连接。每次只回收一条,连接真正关闭后才归还字节预算。仅受调用方额度限制不会触发回收;有写入进展的连接不受影响。断线后仍从最后完整收到的事件 ID 续读。`node dist/bench/replay-pressure.js` 可复现五个停读密钥与一个快读密钥争用全局预算的场景。
136138
因压力回收的连接关闭后,两秒内如果同一调用方重连会吃掉最后一帧的余量,就先等待,不读入正文,也不触发下一次压力回收。网关空闲或仍有余量时可立即续读,字节硬上限不变。`node dist/bench/replay-pressure.js --mixed` 会分批发起快读请求,并让被断开的连接立即带原游标重试,记录重连次数。

‎src/gateway/retention-routes.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,12 @@ const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
1313

1414
/** The Store keeps per-run caches; evict deleted runs from them. */
1515
function prunable(store: Store): PrunableStore {
16-
const caches = store as unknown as Record<
17-
'projections' | 'runOwners' | 'eventRing',
18-
Map<string, unknown>
19-
>;
2016
return {
2117
db: store.db,
2218
root: store.root,
19+
accountingReadbacks: store.accountingReadbacks,
2320
forget: (ids, owners) => {
24-
for (const runId of ids)
25-
for (const cache of [caches.projections, caches.runOwners, caches.eventRing])
26-
cache?.delete(runId);
21+
store.forgetRunCaches(ids);
2722
// The same notification a run change sends: overview and activity caches recompute.
2823
for (const owner of owners) store.events.emit('summary', { owner });
2924
},

‎src/store/event-replay-size.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export const REPLAY_PAGE_BYTES = 256 * 1024;
44
const oversized = new WeakSet<RunEvent>();
55

66
export function markOversizedEvent<T extends RunEvent>(event: T, payload: string): T {
7-
// Use the serialized payload, including JSON escapes, without retaining it in the hot ring.
7+
// Use the serialized payload, including JSON escapes, without keeping the serialized string.
88
if (payload.length * 3 > REPLAY_PAGE_BYTES && Buffer.byteLength(payload) > REPLAY_PAGE_BYTES)
99
oversized.add(event);
1010
return event;
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { LIMITS } from '../core/limits.js';
2+
import type { Projection } from './output.js';
3+
4+
const CACHE_BYTES = 16 * 1024 * 1024;
5+
type Entry = { projection: Projection; bytes: number };
6+
const group = () => ({ entries: new Map<string, Entry>(), bytes: 0 });
7+
type Group = ReturnType<typeof group>;
8+
9+
function weight(id: string, projection: Projection) {
10+
// Count UTF-16 code units and estimate object overhead without scanning the output text.
11+
let bytes = 128 + 2 * (id.length + projection.baseline.length);
12+
for (const m of projection.messages) {
13+
if (typeof m?.id !== 'string' || typeof m.text !== 'string') return Infinity;
14+
bytes += 64 + 2 * (m.id.length + m.text.length);
15+
}
16+
return bytes;
17+
}
18+
19+
/** Bound retained projections and protect writers from churn in completed-run reads. */
20+
export class OutputProjectionCache {
21+
private readonly writers = group();
22+
private readonly readers = group();
23+
24+
constructor(
25+
private readonly maxBytes = CACHE_BYTES,
26+
private readonly maxEntries: number = LIMITS.projectionCacheRuns,
27+
) {}
28+
29+
get(id: string): Projection | undefined {
30+
const { entries } = this.writers.entries.has(id) ? this.writers : this.readers;
31+
const entry = entries.get(id);
32+
if (!entry) return;
33+
entries.delete(id);
34+
entries.set(id, entry);
35+
return entry.projection;
36+
}
37+
38+
set(id: string, projection: Projection, writing = false): void {
39+
this.delete(id);
40+
const bytes = weight(id, projection);
41+
const { readers, writers } = this;
42+
// A cache miss during a read cannot displace a producer's working projection.
43+
if (
44+
this.maxEntries < 1 ||
45+
bytes > this.maxBytes ||
46+
(!writing &&
47+
(writers.entries.size >= this.maxEntries || writers.bytes + bytes > this.maxBytes))
48+
)
49+
return;
50+
while (
51+
readers.bytes + writers.bytes + bytes > this.maxBytes ||
52+
readers.entries.size + writers.entries.size >= this.maxEntries
53+
) {
54+
const oldest = readers.entries.size ? readers : writers;
55+
this.remove(oldest, oldest.entries.keys().next().value!);
56+
}
57+
const target = writing ? writers : readers;
58+
target.entries.set(id, { projection, bytes });
59+
target.bytes += bytes;
60+
}
61+
62+
private remove(pool: Group, id: string) {
63+
const entry = pool.entries.get(id);
64+
if (!entry) return;
65+
pool.entries.delete(id);
66+
pool.bytes -= entry.bytes;
67+
}
68+
69+
delete(id: string): void {
70+
this.remove(this.writers, id);
71+
this.remove(this.readers, id);
72+
}
73+
74+
clear(): void {
75+
for (const pool of [this.writers, this.readers]) {
76+
pool.entries.clear();
77+
pool.bytes = 0;
78+
}
79+
}
80+
}

‎src/store/step-preparation.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ type Storage = {
3333
type Hooks = {
3434
insert: (runId: string, event: EventInput) => RunEvent;
3535
publish: (runId: string, events: RunEvent[]) => void;
36-
invalidate: (runId: string) => void;
3736
};
3837
export class DispatchStateConflict extends Fault {
3938
constructor() {
@@ -223,7 +222,6 @@ export function prepareDispatchSteps(
223222
.get(facts.run, facts.agent);
224223
const owns = () => !!store.prepare(scope).get(facts);
225224
const conflict = (registered = false) => {
226-
hooks.invalidate(facts.run);
227225
for (const entry of writes)
228226
retainRefusedStep(
229227
run,
@@ -290,16 +288,14 @@ export function prepareDispatchSteps(
290288
} else expected.steps = JSON.stringify(writes.map((w) => [w.id, w.payload]));
291289
const matches = () =>
292290
!!store.prepare(writes.length === 1 ? singleProof : batchProof).get(expected);
293-
const unproved = () => {
294-
hooks.invalidate(facts.run);
295-
return new UnprovedDispatch((id, stored) => {
291+
const unproved = () =>
292+
new UnprovedDispatch((id, stored) => {
296293
const intended = writes.find((w) => w.id === id);
297294
if (!intended) return false;
298295
if (!stored) return !prior.has(id);
299296
const payload = JSON.stringify(stored);
300297
return payload === intended.payload || payload === prior.get(id)?.payload;
301298
}, owns);
302-
};
303299
if (!matches())
304300
throw new Fault(
305301
'persistence_failed',

0 commit comments

Comments
 (0)