Skip to content

Commit 1946e77

Browse files
author
hzq
committed
Keep large cold upload quota reads off the gateway event loop
Count committed file bytes on a bounded read-only worker. Tie each result to the serving lease, file identity and an unchanged scope, then recheck reservations in the writer transaction. Fall back to the original connection when the count cannot be confirmed. Add an alternating restart benchmark and cover revocation, disconnects, concurrent edits and helper outages.
1 parent 827c7e3 commit 1946e77

16 files changed

Lines changed: 1125 additions & 26 deletions

‎bench/upload-cold-start.ts‎

Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
// Restart the gateway process on the same database. The HTTP client and its probe clock stay outside it.
2+
import assert from 'node:assert/strict';
3+
import { fork } from 'node:child_process';
4+
import { once } from 'node:events';
5+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
6+
import os from 'node:os';
7+
import path from 'node:path';
8+
import { DatabaseSync } from 'node:sqlite';
9+
import { pathToFileURL } from 'node:url';
10+
import { setTimeout as delay } from 'node:timers/promises';
11+
import { parseArgs } from 'node:util';
12+
13+
const { values } = parseArgs({
14+
options: {
15+
accounts: { type: 'string', default: '8' },
16+
rows: { type: 'string', default: '64000' },
17+
restarts: { type: 'string', default: '8' },
18+
uncapped: { type: 'boolean' },
19+
compare: { type: 'string' },
20+
out: { type: 'string' },
21+
root: { type: 'string' },
22+
round: { type: 'string' },
23+
},
24+
});
25+
const accounts = Number(values.accounts),
26+
rows = Number(values.rows),
27+
restarts = Number(values.restarts);
28+
assert.ok(Number.isInteger(accounts) && accounts >= 2 && accounts <= 32);
29+
assert.ok(Number.isInteger(rows) && rows >= 0 && rows * accounts <= 4_194_304);
30+
assert.ok(Number.isInteger(restarts) && restarts >= 1 && restarts <= 64);
31+
const owner = (i: number) => 'cold-fixture-' + i;
32+
const token = (i: number) => 'test-cold-quota-local-fixture-only-' + i;
33+
const bytes = 77,
34+
content = 'x'.repeat(128),
35+
probes = 20,
36+
spacing = 2;
37+
async function seed(root: string) {
38+
const { Store } = await import('../src/store/store.js');
39+
const s = new Store(root);
40+
try {
41+
const quiet = await s.addFile(
42+
owner(accounts),
43+
'quiet',
44+
Buffer.from('quiet'),
45+
undefined,
46+
undefined,
47+
'config:' + owner(accounts),
48+
);
49+
s.db.exec('BEGIN IMMEDIATE');
50+
const ins = s.prepare('INSERT INTO files(id,owner,subject,payload) VALUES(?,?,?,?)');
51+
for (let j = 0; j < accounts; j++) {
52+
const o = owner(j);
53+
for (let i = 0; i < rows; i++) {
54+
const hex = (j * rows + i).toString(16),
55+
id = 'file_' + hex.padStart(32, '0');
56+
ins.run(
57+
id,
58+
o,
59+
'config:' + o,
60+
JSON.stringify({
61+
id,
62+
owner: o,
63+
name: 'history',
64+
bytes,
65+
sha256: hex.padStart(64, '0'),
66+
createdAt: 1,
67+
}),
68+
);
69+
}
70+
}
71+
s.db.exec('COMMIT');
72+
return quiet.id;
73+
} finally {
74+
if (s.db.isTransaction) s.db.exec('ROLLBACK');
75+
s.close();
76+
}
77+
}
78+
async function gateway() {
79+
assert.ok(values.root);
80+
const round = Number(values.round);
81+
const { setup }: typeof import('../test/helpers.js') = values.compare
82+
? await import(pathToFileURL(path.resolve(values.compare, 'test/helpers.js')).href)
83+
: await import('../test/helpers.js');
84+
const keys = Array.from({ length: accounts + 1 }, (_, i) => {
85+
const tokenEnv = 'OAA_COLD_FIXTURE_' + i;
86+
process.env[tokenEnv] = token(i);
87+
return { name: owner(i), owner: owner(i), scopes: ['files'], tokenEnv, quota: { rpm: 100000 } };
88+
});
89+
const start = performance.now();
90+
const s = await setup(undefined, {
91+
dataDir: values.root,
92+
keys,
93+
...(!values.uncapped && {
94+
maxStoredBytesPerSubject: rows * bytes + (round + 1) * 2 * content.length,
95+
}),
96+
});
97+
try {
98+
const disconnected = once(process, 'disconnect');
99+
process.send!({ base: await s.listen(), ready: performance.now() - start });
100+
await disconnected;
101+
} finally {
102+
await s.cleanup();
103+
}
104+
}
105+
const stats = (times: number[]) => {
106+
const a = times.toSorted((x, y) => x - y),
107+
at = (p: number) => +a[Math.ceil(p * a.length) - 1]!.toFixed(2);
108+
return { count: a.length, p50: at(0.5), p95: at(0.95), p99: at(0.99), max: at(1) };
109+
};
110+
const sample = () => ({
111+
uploads: [] as number[],
112+
quiet: [] as number[],
113+
lag: [] as number[],
114+
wave: [] as number[],
115+
quietGaps: [] as number[],
116+
lateProbes: 0,
117+
});
118+
const measurements = () => ({ cold: sample(), warm: sample(), startup: [] as number[] });
119+
async function measure() {
120+
const root = await mkdtemp(path.join(os.tmpdir(), 'oaa-cold-quota-'));
121+
try {
122+
const quietId = await seed(root),
123+
current = measurements(),
124+
prior = measurements(),
125+
ids = new Set<string>();
126+
const processes = restarts * (values.compare ? 2 : 1);
127+
for (let round = 0; round < processes; round++) {
128+
// AB, BA: each version sees the first and second position equally often.
129+
const before = !!values.compare && (round % 4 === 0 || round % 4 === 3);
130+
const { cold, warm, startup } = before ? prior : current;
131+
const args = [
132+
'--accounts',
133+
String(accounts),
134+
'--rows',
135+
String(rows),
136+
'--round',
137+
String(round),
138+
'--root',
139+
root,
140+
];
141+
if (values.uncapped) args.push('--uncapped');
142+
if (before) args.push('--compare', values.compare!);
143+
const child = fork(import.meta.filename, args, {
144+
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
145+
});
146+
const ended = once(child, 'exit');
147+
try {
148+
const { base, ready } = await Promise.race([
149+
once(child, 'message', { signal: AbortSignal.timeout(120000) }).then(
150+
([m]) => m as { base: string; ready: number },
151+
),
152+
ended.then(() => {
153+
throw Error('Gateway exited before listening');
154+
}),
155+
]);
156+
startup.push(ready);
157+
const post = (i: number, payload = content) =>
158+
fetch(base + '/v1/files', {
159+
method: 'POST',
160+
headers: { authorization: 'Bearer ' + token(i), 'content-type': 'application/json' },
161+
body: JSON.stringify({ filename: 'burst', content: payload }),
162+
signal: AbortSignal.timeout(30000),
163+
});
164+
const read = async () => {
165+
const r = await fetch(base + '/v1/files/' + quietId + '/content', {
166+
headers: { authorization: 'Bearer ' + token(accounts) },
167+
signal: AbortSignal.timeout(30000),
168+
});
169+
assert.equal(r.status, 200);
170+
assert.equal(await r.text(), 'quiet');
171+
};
172+
// Establish HTTP connections without checking any measured account's upload quota.
173+
await Promise.all(Array.from({ length: accounts + probes }, () => read()));
174+
for (const phase of [cold, warm]) {
175+
const start = performance.now();
176+
let finished = Infinity;
177+
const arrivals: number[] = [];
178+
const probe = async () => {
179+
const at = performance.now();
180+
await read();
181+
const end = performance.now();
182+
phase.quiet.push(end - at);
183+
arrivals.push(end);
184+
};
185+
await Promise.all([
186+
Promise.all(
187+
Array.from({ length: accounts }, async (_, i) => {
188+
const t = performance.now(),
189+
r = await post(i),
190+
j = await r.json();
191+
assert.equal(r.status, 200, JSON.stringify(j));
192+
assert.equal(j.bytes, content.length);
193+
assert.ok(typeof j.id === 'string' && !ids.has(j.id));
194+
ids.add(j.id);
195+
phase.uploads.push(performance.now() - t);
196+
}),
197+
).finally(() => {
198+
finished = performance.now();
199+
phase.wave.push(finished - start);
200+
}),
201+
Promise.all(
202+
Array.from({ length: probes }, async (_, i) => {
203+
const target = start + (i + 1) * spacing;
204+
await delay(Math.max(0, target - performance.now()));
205+
const t = performance.now();
206+
phase.lag.push(Math.max(0, t - target));
207+
await probe();
208+
}),
209+
),
210+
(async () => {
211+
await delay(probes * spacing + spacing);
212+
// Cover slow disks and helper fallback after the initial open-loop burst,
213+
// without adding unbounded load when the gateway is unable to answer.
214+
while (finished === Infinity) {
215+
phase.lateProbes++;
216+
await probe();
217+
await delay(5);
218+
}
219+
})(),
220+
]);
221+
const points = [
222+
start,
223+
...arrivals.filter((n) => n < finished).sort((a, b) => a - b),
224+
finished,
225+
];
226+
phase.quietGaps.push(Math.max(...points.slice(1).map((n, i) => n - points[i]!)));
227+
}
228+
if (!values.uncapped) {
229+
for (let i = 0; i < accounts; i++) {
230+
const r = await post(i, 'x');
231+
assert.equal(r.status, 413);
232+
assert.equal((await r.json()).error.code, 'storage_quota_exceeded');
233+
}
234+
}
235+
} finally {
236+
if (child.connected) child.disconnect();
237+
assert.equal((await ended)[0], 0);
238+
}
239+
}
240+
const db = new DatabaseSync(path.join(root, 'state.sqlite'), { readOnly: true });
241+
try {
242+
const all = db.prepare(
243+
"SELECT count(*) AS n,sum(json_extract(payload,'$.bytes')) AS bytes FROM files WHERE owner=? AND subject=?",
244+
);
245+
for (let i = 0; i < accounts; i++) {
246+
const r = all.get(owner(i), 'config:' + owner(i))!;
247+
assert.equal(r.n, rows + processes * 2);
248+
assert.equal(r.bytes, rows * bytes + processes * 2 * content.length);
249+
}
250+
assert.equal(db.prepare('SELECT count(*) AS n FROM oaa_inline_inputs').get()!.n, 0);
251+
} finally {
252+
db.close();
253+
}
254+
const describe = (p: ReturnType<typeof sample>) => ({
255+
upload_ms: stats(p.uploads),
256+
other_owner_read_ms: stats(p.quiet),
257+
wave_ms: stats(p.wave),
258+
client_timer_lag_ms: stats(p.lag),
259+
max_quiet_response_gap_per_wave_ms: stats(p.quietGaps),
260+
late_probes: p.lateProbes,
261+
wave_samples_ms: p.wave.map((n) => +n.toFixed(2)),
262+
});
263+
const summarize = (x: ReturnType<typeof measurements>) => ({
264+
ready_ms: stats(x.startup),
265+
cold: describe(x.cold),
266+
warm: describe(x.warm),
267+
});
268+
const report = {
269+
fixture:
270+
'Fresh gateway processes, same disk database; synthetic file history, actual HTTP uploads and reads. Host OS disk cache is not flushed. No model calls.',
271+
node: process.version,
272+
accounts,
273+
rows_per_account: rows,
274+
restarts,
275+
quota: !values.uncapped,
276+
per_wave_probes: probes,
277+
probe_interval_ms: spacing,
278+
verified_uploads: ids.size,
279+
verified_one_byte_rejections: values.uncapped ? 0 : accounts * processes,
280+
...(values.compare
281+
? { order: 'AB/BA, shared fixture', before: summarize(prior), after: summarize(current) }
282+
: summarize(current)),
283+
};
284+
const data = JSON.stringify(report, null, 2) + '\n';
285+
if (values.out) await writeFile(values.out, data, { flag: 'wx' });
286+
process.stdout.write(data);
287+
} finally {
288+
await rm(root, { recursive: true, force: true });
289+
}
290+
}
291+
if (process.send) await gateway();
292+
else await measure();

‎docs/stability.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,20 @@ records. Retention subtracts a known file size in the same transaction as deleti
3535
size instead forces a fresh count. In-flight reservations are always read from the database,
3636
including on a cache hit.
3737

38+
For simultaneous first uploads after restart, run
39+
`npm run bench:upload-cold-start -- --accounts 8 --rows 128000 --restarts 16 --out cold.json`.
40+
Each gateway process serves a cold and a warm burst against the same disk database, while a
41+
different caller reads a real file. The report includes upload and reader latency, reader
42+
response gaps through the whole burst, and one-byte over-limit rejections. The OS disk cache is
43+
not cleared. Add `--compare PATH_TO_PRIOR_DIST` to alternate two local builds in AB/BA order.
44+
45+
A capped gateway can prepare one read-only helper when the catalog has at least 4,096 files;
46+
it does not rebuild every caller's total at startup. Only a cold caller with at least that many
47+
files is sent to it. Concurrent requests for the same owner and subject share the count, not
48+
their authorization or reservation. A changed or unavailable snapshot is never used as proof
49+
of room: the serving connection can count again, and still checks outstanding reservations inside
50+
the write transaction. Uncapped gateways start no helper. The thread retires when idle.
51+
3852
`bench/soak.ts` is not part of `npm test`. It:
3953

4054
- starts a **real gateway process** (`node dist/src/cli.js serve`) with a temporary `HOME` and data

‎docs/zh-CN/stability.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
2424
基准对照空目录、已积累大量文件且不开配额、同样规模且开启配额三种情况。独立进程通过 HTTP 计时:并发上传、上传期间另一账户读取文件、配额用满后的拒绝。历史文件记录是合成数据,不访问用户文件或模型账户。
2525
开启配额后,SQLite 连接最多暂存 256 个调用方的已提交文件总量,优先保留经常查询的调用方。这不是可上传的调用方数量上限。其他连接提交后,旧总量不再使用;冷查询按调用方的文件记录重算。保留策略在删除文件的同一事务中扣减已知大小;大小不明确时则重新统计。即使缓存命中,尚在写入的预留字节也始终从数据库读取。
2626

27+
要测重启后多账户同时首次上传,运行
28+
`npm run bench:upload-cold-start -- --accounts 8 --rows 128000 --restarts 16 --out cold.json`。
29+
每次都在同一份磁盘数据库上启动新的网关进程,分别发送冷、热两批上传,另一个调用方同时读取真实文件。结果包含两类请求的延迟、整个上传窗口内读取响应的最长间隔,以及超过配额一个字节的拒绝检查。基准不会清空操作系统的磁盘缓存。传入 `--compare 旧构建的dist目录` 可按 AB/BA 顺序交替对照。
30+
31+
启用存储配额且目录至少有 4,096 个文件时,网关可提前启动一个只读线程,不会在启动时重算所有账户。只有首次需要统计且至少有这么多文件的调用方才交给线程处理。同一所有者、同一调用方的并发请求仅共享统计,不共享授权或字节预留。快照变动或读取失败时不按旧结果放行,必要时由原连接重新统计;实际写入事务仍核对在途预留。未启用配额时不启动线程,线程空闲后会退出。
32+
2733
`bench/soak.ts` 不在 `npm test` 里。它会:
2834

2935
- 在进程外启动一个**真实的网关进程**(`node dist/src/cli.js serve`),使用临时的 `HOME` 和数据目录,监听 `127.0.0.1` 的随机端口。一个很小的预加载模块(`bench/soak-probe.ts`)记录该进程自己的 RSS、堆和活动句柄,进程里别的东西都不改;

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
"bench:fair": "npm run build && node dist/bench/fairness.js",
5959
"bench:webhook-isolation": "npm run build && node dist/bench/webhook-isolation.js",
6060
"bench:upload-quota": "npm run build && node dist/bench/upload-quota.js",
61+
"bench:upload-cold-start": "npm run build && node dist/bench/upload-cold-start.js",
6162
"bench:protocol": "npm run build && node dist/bench/protocol-speed.js",
6263
"bench:queue": "npm run build && node dist/bench/queue-estimate.js",
6364
"bench:paired": "npm run build && node dist/bench/paired/run.js",

‎src/gateway/file-routes.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,18 @@ import type { Auth } from './auth.js';
1010
import { assertUploadRoom } from './upload-quota.js';
1111
import { artifactOriginAgent } from '../store/artifact-origin.js';
1212
import { requestGrant } from './request-grant.js';
13+
import type { ColdUploadReads } from '../store/upload-cold-reads.js';
1314

1415
// 文件上传(multipart 与 JSON 两种)与下载:POST /v1/files、GET /v1/files/:id/content。
1516
// 从 gateway/server.ts 拆出。
1617

17-
export type FileRouteDeps = { auth: Auth; config: GatewayConfig; store: Store; kernel: Kernel };
18+
export type FileRouteDeps = {
19+
auth: Auth;
20+
config: GatewayConfig;
21+
store: Store;
22+
kernel: Kernel;
23+
coldReads?: ColdUploadReads;
24+
};
1825

1926
export function registerFileRoutes(app: FastifyInstance, deps: FileRouteDeps): void {
2027
const { auth, config, store, kernel } = deps;
@@ -53,7 +60,15 @@ export function registerFileRoutes(app: FastifyInstance, deps: FileRouteDeps): v
5360
);
5461
}
5562
if (!uploaded) throw new Fault('file_required', 'A file part is required.');
56-
assertUploadRoom(store, config, req.principal, uploaded.bytes.length);
63+
const quota = assertUploadRoom(
64+
store,
65+
config,
66+
req.principal,
67+
uploaded.bytes.length,
68+
deps.coldReads,
69+
policy.guard,
70+
);
71+
if (quota) await quota;
5772
const f = await store.addFile(
5873
req.principal.owner,
5974
uploaded.name,
@@ -83,7 +98,15 @@ export function registerFileRoutes(app: FastifyInstance, deps: FileRouteDeps): v
8398
.parse(req.body);
8499
relativeName(b.filename);
85100
const bytes = Buffer.from(b.content, b.encoding === 'utf8' ? 'utf8' : 'base64');
86-
assertUploadRoom(store, config, req.principal, bytes.length);
101+
const quota = assertUploadRoom(
102+
store,
103+
config,
104+
req.principal,
105+
bytes.length,
106+
deps.coldReads,
107+
policy.guard,
108+
);
109+
if (quota) await quota;
87110
const file = await store.addFile(
88111
req.principal.owner,
89112
b.filename,

0 commit comments

Comments
 (0)