Skip to content

Commit 37298b0

Browse files
author
hzq
committed
Defer pressure-evicted replay retries near capacity
Keep briefly available room for other readers without raising replay budgets. Exercise mixed fast-reader waves and immediate cursor reconnects.
1 parent 747467a commit 37298b0

6 files changed

Lines changed: 231 additions & 38 deletions

File tree

‎bench/replay-pressure.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
import { replayPressureFixture } from '../test/replay-pressure-fixture.js';
1+
import { replayMixedFixture, replayPressureFixture } from '../test/replay-pressure-fixture.js';
2+
3+
const mixed = process.argv.includes('--mixed');
24

35
const samples = [];
4-
for (let trial = 0; trial < 3; trial++) samples.push(await replayPressureFixture());
5-
console.log(JSON.stringify({ samples }));
6+
for (let trial = 0; trial < 3; trial++)
7+
samples.push(await (mixed ? replayMixedFixture() : replayPressureFixture()));
8+
console.log(JSON.stringify({ mixed, samples }));

‎docs/stability.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,12 @@ can disconnect a replay transport whose write queue has made no progress for at
308308
transport closes. A caller-only quota wait never triggers this; progressing responses keep
309309
their leases. Reconnect from the last complete event ID after a disconnect.
310310
`node dist/bench/replay-pressure.js` exercises this case with five paused keys and a fast reader.
311+
For two seconds after a pressure-displaced transport closes, the same caller can reconnect
312+
immediately when the gateway is idle or when its replay would leave room for another ordinary
313+
frame. Otherwise it waits without materializing the page and cannot trigger another pressure
314+
reclaim while deferred. The hard byte budgets are unchanged.
315+
`node dist/bench/replay-pressure.js --mixed` runs waves of fast readers with immediate cursor
316+
retries by the displaced readers and reports the reconnect count.
311317

312318
New HTTP run submissions (including media jobs and workflow drafts) wait for SQLite's writer
313319
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
@@ -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。超出额度的合法单帧可以独占对应预算。等待不读入该页正文,获准后重新核对授权和页大小;断线或等满五秒就退出。排队满或超时返回流容量错误,不推进游标。小页和实时事件不占这份预算,它也不是进程总内存上限。
132132
调用方自身还有预算、却因网关预算等候至少 1.5 秒时,网关可以断开写队列也已至少 1.5 秒没有进展的重放连接。每次只回收一条,连接真正关闭后才归还字节预算。仅受调用方额度限制不会触发回收;有写入进展的连接不受影响。断线后仍从最后完整收到的事件 ID 续读。`node dist/bench/replay-pressure.js` 可复现五个停读密钥与一个快读密钥争用全局预算的场景。
133+
因压力回收的连接关闭后,两秒内如果同一调用方重连会吃掉最后一帧的余量,就先等待,不读入正文,也不触发下一次压力回收。网关空闲或仍有余量时可立即续读,字节硬上限不变。`node dist/bench/replay-pressure.js --mixed` 会分批发起快读请求,并让被断开的连接立即带原游标重试,记录重连次数。
133134

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

‎src/gateway/replay-budget.ts‎

Lines changed: 73 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ type Limits = {
77
waiters: number;
88
waitMs: number;
99
pressureMs?: number;
10+
retryMs?: number;
1011
};
1112
type PressureSource = { stalledSince: () => number | undefined; disconnect: () => void };
1213
type Active = { bytes: number; since: number; source: PressureSource };
@@ -37,8 +38,10 @@ export class ReplayBudget {
3738
private readonly heldBySubject = new Map<string, number>();
3839
private readonly queues = new Map<string, Waiter[]>();
3940
private readonly active = new Set<Active>();
41+
private readonly recentStalls = new Map<string, number>();
4042
private waiting = 0;
41-
private pressureTimer?: NodeJS.Timeout;
43+
private wakeTimer?: NodeJS.Timeout;
44+
private wakeAt = Infinity;
4245
private reclaiming?: Active;
4346

4447
constructor(private readonly limits: Limits = DEFAULT_LIMITS) {}
@@ -54,14 +57,18 @@ export class ReplayBudget {
5457
source?: PressureSource,
5558
): Release | Promise<Release> {
5659
checkAbort(signal);
57-
if (!this.queues.has(subject) && this.fits(subject, bytes))
58-
return this.take(subject, bytes, source);
60+
if (!this.queues.has(subject) && this.fits(subject, bytes)) {
61+
const release = this.take(subject, bytes, source);
62+
if (this.waiting) this.scheduleWake();
63+
return release;
64+
}
5965
if (this.waiting >= this.limits.waiters) throw busy();
6066
return new Promise((resolve, reject) => {
6167
const cancel = (error: unknown) => {
6268
this.remove(subject, waiter);
6369
reject(error);
6470
this.dispatch();
71+
this.scheduleWake();
6572
};
6673
const abort = () => cancel(abortError());
6774
const timeout = setTimeout(() => cancel(busy()), this.limits.waitMs);
@@ -80,13 +87,17 @@ export class ReplayBudget {
8087
else this.queues.set(subject, [waiter]);
8188
this.waiting++;
8289
signal.addEventListener('abort', abort, { once: true });
83-
this.schedulePressure();
90+
this.scheduleWake();
8491
});
8592
}
8693

8794
private fits(subject: string, bytes: number) {
8895
// A legitimate singleton can exceed a budget, but cannot share that budget with another frame.
89-
return this.fitsSubject(subject, bytes) && this.fitsGateway(bytes);
96+
return (
97+
this.fitsSubject(subject, bytes) &&
98+
this.fitsGateway(bytes) &&
99+
this.coolingUntil(subject, bytes) === undefined
100+
);
90101
}
91102
private fitsSubject(subject: string, bytes: number) {
92103
const owned = this.heldBySubject.get(subject) ?? 0;
@@ -95,6 +106,24 @@ export class ReplayBudget {
95106
private fitsGateway(bytes: number, held = this.held) {
96107
return held === 0 || held + bytes <= this.limits.gateway;
97108
}
109+
private coolingUntil(subject: string, bytes: number, now = performance.now()) {
110+
const until = this.recentStalls.get(subject);
111+
if (until === undefined) return undefined;
112+
if (until <= now) {
113+
this.recentStalls.delete(subject);
114+
return undefined;
115+
}
116+
// Keep room for a new ordinary frame only after observed pressure and only near capacity.
117+
const headroom = Math.min(this.limits.subject, this.limits.gateway);
118+
if (this.held && this.held + bytes + headroom > this.limits.gateway) return until;
119+
return undefined;
120+
}
121+
private rememberStall(subject: string) {
122+
this.recentStalls.delete(subject);
123+
this.recentStalls.set(subject, performance.now() + (this.limits.retryMs ?? 2000));
124+
if (this.recentStalls.size > DEFAULT_LIMITS.waiters)
125+
this.recentStalls.delete(this.recentStalls.keys().next().value!);
126+
}
98127

99128
private take(subject: string, bytes: number, source?: PressureSource): Release {
100129
this.held += bytes;
@@ -107,11 +136,15 @@ export class ReplayBudget {
107136
released = true;
108137
this.held -= bytes;
109138
if (active) this.active.delete(active);
110-
if (this.reclaiming === active) this.reclaiming = undefined;
139+
if (active && this.reclaiming === active) {
140+
this.reclaiming = undefined;
141+
this.rememberStall(subject);
142+
}
111143
const remaining = this.heldBySubject.get(subject)! - bytes;
112144
if (remaining) this.heldBySubject.set(subject, remaining);
113145
else this.heldBySubject.delete(subject);
114146
this.dispatch();
147+
this.scheduleWake();
115148
};
116149
}
117150

@@ -140,34 +173,54 @@ export class ReplayBudget {
140173
}
141174
if (!granted) break;
142175
}
143-
this.schedulePressure();
144176
}
145177

146178
private gatewayWaiter() {
147179
for (const [subject, queue] of this.queues) {
148180
const first = queue[0]!;
149-
if (this.fitsSubject(subject, first.bytes) && !this.fitsGateway(first.bytes)) return first;
181+
if (
182+
this.fitsSubject(subject, first.bytes) &&
183+
!this.fitsGateway(first.bytes) &&
184+
this.coolingUntil(subject, first.bytes) === undefined
185+
)
186+
return first;
150187
}
151188
return undefined;
152189
}
153190

154-
private schedulePressure() {
155-
if (this.reclaiming || !this.active.size || !this.gatewayWaiter()) {
156-
clearTimeout(this.pressureTimer);
157-
this.pressureTimer = undefined;
191+
private scheduleWake() {
192+
const now = performance.now();
193+
const pressure = this.limits.pressureMs ?? 1500;
194+
let at =
195+
!this.reclaiming && this.active.size && this.gatewayWaiter()
196+
? now + Math.min(100, pressure)
197+
: Infinity;
198+
for (const [subject, queue] of this.queues) {
199+
const bytes = queue[0]!.bytes;
200+
const cooled = this.coolingUntil(subject, bytes, now);
201+
if (cooled !== undefined) at = Math.min(at, cooled);
202+
else if (this.fitsSubject(subject, bytes) && this.fitsGateway(bytes)) at = now;
203+
}
204+
if (!Number.isFinite(at)) {
205+
clearTimeout(this.wakeTimer);
206+
this.wakeTimer = undefined;
207+
this.wakeAt = Infinity;
158208
return;
159209
}
160-
if (this.pressureTimer) return;
161-
const delay = this.limits.pressureMs ?? 1500;
162-
this.pressureTimer = setTimeout(
210+
if (this.wakeTimer && this.wakeAt <= at) return;
211+
clearTimeout(this.wakeTimer);
212+
this.wakeAt = at;
213+
this.wakeTimer = setTimeout(
163214
() => {
164-
this.pressureTimer = undefined;
215+
this.wakeTimer = undefined;
216+
this.wakeAt = Infinity;
217+
this.dispatch();
165218
const waiting = this.gatewayWaiter();
166-
if (waiting && performance.now() - waiting.since >= delay)
167-
this.reclaimStalled(waiting, delay);
168-
this.schedulePressure();
219+
if (!this.reclaiming && waiting && performance.now() - waiting.since >= pressure)
220+
this.reclaimStalled(waiting, pressure);
221+
this.scheduleWake();
169222
},
170-
Math.min(100, delay),
223+
Math.max(1, Math.ceil(at - now)),
171224
).unref();
172225
}
173226

‎test/replay-budget.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,38 @@ test('gateway pressure interrupts an idle lease, but cannot account those bytes
8181
assert.deepEqual(budget.usage(), { bytes: 0, waiting: 0 });
8282
});
8383

84+
test('a just-displaced caller cannot take the last available budget before a new reader', async () => {
85+
const budget = new ReplayBudget({
86+
gateway: 16,
87+
subject: 8,
88+
waiters: 8,
89+
waitMs: 1000,
90+
pressureMs: 20,
91+
retryMs: 180,
92+
});
93+
const stopped = Promise.withResolvers<void>();
94+
const old = await budget.reserve('paused', 8, signal, {
95+
stalledSince: () => 0,
96+
disconnect: () => stopped.resolve(),
97+
});
98+
const other = await budget.reserve('other stalled', 8, signal);
99+
const first = budget.reserve('first reader', 8, signal);
100+
await wait(stopped.promise);
101+
old();
102+
(await first)();
103+
const again = budget.reserve('paused', 8, signal);
104+
assert.notEqual(typeof again, 'function');
105+
assert.deepEqual(budget.usage(), { bytes: 8, waiting: 1 });
106+
const ready = budget.reserve('later reader', 8, signal);
107+
assert.equal(typeof ready, 'function');
108+
(await ready)();
109+
assert.deepEqual(budget.usage(), { bytes: 8, waiting: 1 });
110+
// Expiration alone wakes the retry even if no writer completes in the meantime.
111+
(await wait(Promise.resolve(again)))();
112+
other();
113+
assert.deepEqual(budget.usage(), { bytes: 0, waiting: 0 });
114+
});
115+
84116
for (const sameSubject of [true, false])
85117
test(`no pressure eviction for ${sameSubject ? 'only a caller cap' : 'a progressing writer'}`, async () => {
86118
const budget = new ReplayBudget({

0 commit comments

Comments
 (0)