Public: anyone can read this; the crew can change it.

bench/results holds a 500/s run of anonymous code pages through the edge cache and one bypassing it, both with zero refusals and p95 under 100 ms #12099

Parked opened this
Closed without merging

torque/forge:torque/9622-bench-results-holds-a-500-s-run-of-anony → main 14 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
25 files changed +1577 −22
bench/code-pages-at-rate.ts +20 −2
@@ -12,6 +12,14 @@
1212 * bun bench/code-pages-at-rate.ts --rate 500 --seconds 20 --addresses 4000 --crawl 3000 \
1313 * --out bench/results/9514-in-process-bypass.json
1414 *
15 * `--shape FILE` (#9622) also seeds every other public repository production
16 * holds (`bench/production-shape.ts` writes the file; `seedShape` in
17 * bench/seed.ts lays each out with its file count and average size), spreads
18 * the load over all of them, and writes the counts into the result.
19 *
20 * bun bench/code-pages-at-rate.ts --shape bench/production-shape.json --seconds 60 --warm 40 \
21 * --out bench/results/9622-in-process-bypass.json
22 *
1523 * What it is not: the edge run. That one needs the real deployment and is run
1624 * with bench/load.ts against it (docs/features/load-test.md).
1725 */
@@ -23,6 +31,9 @@ import { createRepo } from "../src/actions/repos.ts";
2331 import { createUser } from "../src/core/users.ts";
2432 import { repoDir } from "../src/git/repos.ts";
2533 import { serve } from "../src/http/server.ts";
34 import { readFileSync } from "node:fs";
35 import { parseShape } from "../src/perf/production_shape.ts";
36 import { seedShape } from "./seed.ts";
2637
2738 const arg = (name: string, fallback: string): string => {
2839 const at = process.argv.indexOf(`--${name}`);
@@ -30,7 +41,10 @@ const arg = (name: string, fallback: string): string => {
3041 if (!(Number(v) >= 0)) throw new Error(`bad --${name}`);
3142 return v;
3243 };
33 const out = process.argv.includes("--out") ? process.argv[process.argv.indexOf("--out") + 1] : undefined;
44 const named = (name: string): string | undefined => (process.argv.includes(`--${name}`) ? process.argv[process.argv.indexOf(`--${name}`) + 1] : undefined);
45 const out = named("out");
46 const shapeFile = named("shape");
47 const shape = shapeFile === undefined ? undefined : parseShape(JSON.parse(readFileSync(shapeFile, "utf8")));
3448 const root = join(import.meta.dir, "..");
3549
3650 const dataDir = await mkdtemp(join(tmpdir(), "forge-code-rate-"));
@@ -47,7 +61,11 @@ try {
4761 const files = Bun.spawnSync(["git", "ls-files"], { cwd: root }).stdout.toString().split("\n").length - 1;
4862 console.error(`copy: trevato/forge with ${files} files at ${Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd: root }).stdout.toString().trim()}`);
4963
50 const args = ["--url", servers.url, "--repo", "trevato/forge", "--bypass", "--version", "in-process"];
64 // The rest of production's public repositories, sized as they are there; trevato/forge is the real history above.
65 const others = shape === undefined ? [] : await seedShape(app, shape, { skip: new Set(["trevato/forge"]) });
66 const repos = ["trevato/forge", ...others].join(",");
67 const args = ["--url", servers.url, "--repo", repos, "--bypass", "--version", "in-process"];
68 if (shapeFile !== undefined) args.push("--shape", shapeFile);
5169 for (const name of ["rate", "seconds", "addresses", "crawl", "warm"]) args.push(`--${name}`, arg(name, { rate: "500", seconds: "20", addresses: "4000", crawl: "3000", warm: "0" }[name]!));
5270 if (out !== undefined) args.push("--out", out);
5371 const load = Bun.spawn(["bun", join(import.meta.dir, "load.ts"), ...args], {
bench/load.ts +27 −6
@@ -41,6 +41,8 @@
4141 import { readFileSync, writeFileSync } from "node:fs";
4242 import { fell, missed, summarize, TARGET, type LoadResult } from "../src/perf/load_verdict.ts";
4343 import { refuseProduction, systemResolve } from "../src/perf/production_guard.ts";
44 import { parseShape, shapeCounts } from "../src/perf/production_shape.ts";
45 import { availableParallelism, cpus, loadavg, totalmem } from "node:os";
4446
4547 const arg = (name: string, fallback?: string): string => {
4648 const at = process.argv.indexOf(`--${name}`);
@@ -56,19 +58,21 @@ if (notHere !== undefined) {
5658 console.error(`load: refused: ${notHere}`);
5759 process.exit(2);
5860 }
59 const repo = arg("repo");
61 // `--repo a/b,c/d` reads several repositories, spreading strangers over a forge (#9622).
62 const repos = arg("repo").split(",");
63 const repo = repos[0]!;
6064 const rate = Number(arg("rate", "100"));
6165 const seconds = Number(arg("seconds", "10"));
6266 const version = arg("version", "unversioned");
6367 const bypass = process.argv.includes("--bypass");
6468 const addresses = Number(arg("addresses", "1"));
65 if (!/^[\w.-]+\/[\w.-]+$/.test(repo) || !(rate > 0) || !(seconds > 0)) throw new Error("bad --repo, --rate or --seconds");
69 if (!repos.every((r) => /^[\w.-]+\/[\w.-]+$/.test(r)) || repos.length > 10_000 || !(rate > 0) || !(seconds > 0)) throw new Error("bad --repo, --rate or --seconds");
6670 if (!Number.isInteger(addresses) || addresses < 1 || addresses > 131_072) throw new Error("bad --addresses (1..131072)");
6771 /** The n-th made-up client: 198.18.0.0/15 holds 131072 addresses. */
6872 const addressOf = (n: number): string => `198.${18 + ((n >> 16) & 1)}.${(n >> 8) & 255}.${n & 255}`;
6973
70 const escaped = repo.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71 const linkPattern = new RegExp(`/${escaped}/(?:tree|blob)/[0-9a-f]{40}[^"'<> ]*`, "g");
74 const escaped = repos.map((r) => r.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
75 const linkPattern = new RegExp(`/(?:${escaped})/(?:tree|blob)/[0-9a-f]{40}[^"'<> ]*`, "g");
7276 const pinned = new Set<string>();
7377 const collect = (html: string): string[] => {
7478 const found: string[] = [];
@@ -82,8 +86,10 @@ const collect = (html: string): string[] => {
8286 }
8387 return found;
8488 };
85 collect(await (await fetch(`${base}/${repo}`)).text());
86 collect(await (await fetch(`${base}/${repo}/tree/main`)).text());
89 for (const r of repos) {
90 collect(await (await fetch(`${base}/${r}`)).text());
91 collect(await (await fetch(`${base}/${r}/tree/main`)).text());
92 }
8793 // `--crawl N` walks pinned folders breadth-first until N links are known, so
8894 // the run spreads over a repository the way strangers do, not its top folder.
8995 // Signed out and unhurried: one page at a time before the clock starts.
@@ -187,12 +193,27 @@ counting = true;
187193 await flood(seconds);
188194 await Promise.all(inflight);
189195
196 // What the numbers came from (#9622): the copy's size when a shape file seeded it, how the run started, the machine that ran the load.
197 const shapeFile = process.argv.includes("--shape") ? arg("shape") : undefined;
198 const shape = shapeFile === undefined ? undefined : shapeCounts(parseShape(JSON.parse(readFileSync(shapeFile, "utf8"))));
199 const machine = {
200 cpu: cpus()[0]?.model ?? "unknown",
201 threads: availableParallelism(),
202 memoryGb: Math.round(totalmem() / 2 ** 30),
203 loadAverage: loadavg().map((n) => Math.round(n * 10) / 10),
204 runtime: `bun ${Bun.version}`,
205 };
190206 const warmTotals = warmPerSecond.reduce(([s, r], [a, b]) => [s + a, r + b], [0, 0]);
191207 const result: LoadResult = {
192208 ...summarize(version, rate, seconds, latencies, refused),
193209 cache: bypass ? "bypass" : "edge",
194210 refusedBy,
195211 warm: { seconds: warm, served: warmTotals[0]!, refused: warmTotals[1]! },
212 start: warm > 0 ? "warm" : "cold",
213 repositories: repos.length,
214 links: paths.length,
215 machine,
216 ...(shape === undefined ? {} : { shape }),
196217 };
197218 console.log(JSON.stringify(result, null, 2));
198219 console.log(`per second, served/refused: ${perSecond.map(([a, b]) => `${a}/${b}`).join(" ")}`);
bench/production-shape.json added +421
@@ -0,0 +1,421 @@
1 {
2 "source": "https://forge.open-platform.sh",
3 "takenAt": "2026-11-13T15:23:19.842Z",
4 "repos": [
5 {
6 "name": "trevato/glue",
7 "files": 20,
8 "bytes": 91350
9 },
10 {
11 "name": "trevato/mitosis",
12 "files": 252,
13 "bytes": 13198514
14 },
15 {
16 "name": "ledger/pixel-plays",
17 "files": 437,
18 "bytes": 18242664
19 },
20 {
21 "name": "juniper/pixel-plays",
22 "files": 437,
23 "bytes": 18242664
24 },
25 {
26 "name": "sentinel/pixel-plays",
27 "files": 437,
28 "bytes": 18242664
29 },
30 {
31 "name": "mason/pixel-plays",
32 "files": 437,
33 "bytes": 18242664
34 },
35 {
36 "name": "vesper/pixel-plays",
37 "files": 437,
38 "bytes": 18242664
39 },
40 {
41 "name": "atlas/speed-to-lead",
42 "files": 123,
43 "bytes": 1309397
44 },
45 {
46 "name": "atlas/listing-launch",
47 "files": 171,
48 "bytes": 1125959
49 },
50 {
51 "name": "atlas/deal-clock",
52 "files": 219,
53 "bytes": 1877940
54 },
55 {
56 "name": "quill/pixel-plays",
57 "files": 437,
58 "bytes": 18242664
59 },
60 {
61 "name": "atlas/pixel-plays",
62 "files": 437,
63 "bytes": 18242664
64 },
65 {
66 "name": "torque/pixel-plays",
67 "files": 437,
68 "bytes": 18242664
69 },
70 {
71 "name": "trevato/pixel-plays",
72 "files": 437,
73 "bytes": 18242664
74 },
75 {
76 "name": "trevato/trevato.dev",
77 "files": 18,
78 "bytes": 263797
79 },
80 {
81 "name": "grokbot/forge",
82 "files": 7241,
83 "bytes": 52523396
84 },
85 {
86 "name": "quill/gods-eye-view",
87 "files": 2132,
88 "bytes": 119862306
89 },
90 {
91 "name": "osint/gods-eye-view",
92 "files": 2132,
93 "bytes": 119862306
94 },
95 {
96 "name": "trevato/arm",
97 "files": 647,
98 "bytes": 278502636
99 },
100 {
101 "name": "trevato/deal-clock",
102 "files": 219,
103 "bytes": 1877940
104 },
105 {
106 "name": "trevato/listing-launch",
107 "files": 171,
108 "bytes": 1125959
109 },
110 {
111 "name": "trevato/speed-to-lead",
112 "files": 123,
113 "bytes": 1309397
114 },
115 {
116 "name": "mason/cheffryjames-www",
117 "files": 41,
118 "bytes": 173942
119 },
120 {
121 "name": "cheffryjames/www",
122 "files": 41,
123 "bytes": 173942
124 },
125 {
126 "name": "mason/www",
127 "files": 38,
128 "bytes": 165801
129 },
130 {
131 "name": "cheffry-james/cheffry-s-dungeon",
132 "files": 60,
133 "bytes": 522916
134 },
135 {
136 "name": "cheffryjames/cheffry-s-dungeon",
137 "files": 60,
138 "bytes": 522916
139 },
140 {
141 "name": "torque/scrims",
142 "files": 28,
143 "bytes": 150903
144 },
145 {
146 "name": "trevato/scrims",
147 "files": 28,
148 "bytes": 150903
149 },
150 {
151 "name": "juniper/parley",
152 "files": 42,
153 "bytes": 407523
154 },
155 {
156 "name": "juniper/tempo",
157 "files": 45,
158 "bytes": 359792
159 },
160 {
161 "name": "torque/relay",
162 "files": 39,
163 "bytes": 226674
164 },
165 {
166 "name": "hearth/quorum",
167 "files": 34,
168 "bytes": 334781
169 },
170 {
171 "name": "sentinel/quorum",
172 "files": 34,
173 "bytes": 334781
174 },
175 {
176 "name": "ledger/quorum",
177 "files": 34,
178 "bytes": 334781
179 },
180 {
181 "name": "sentinel/relay",
182 "files": 39,
183 "bytes": 226674
184 },
185 {
186 "name": "sentinel/parley",
187 "files": 42,
188 "bytes": 407523
189 },
190 {
191 "name": "sentinel/drift",
192 "files": 46,
193 "bytes": 405368
194 },
195 {
196 "name": "scout/relay",
197 "files": 39,
198 "bytes": 226674
199 },
200 {
201 "name": "quill/drift",
202 "files": 46,
203 "bytes": 405368
204 },
205 {
206 "name": "vesper/drift",
207 "files": 46,
208 "bytes": 405368
209 },
210 {
211 "name": "mason/parley",
212 "files": 42,
213 "bytes": 407523
214 },
215 {
216 "name": "atlas/relay",
217 "files": 39,
218 "bytes": 226674
219 },
220 {
221 "name": "atlas/quorum",
222 "files": 34,
223 "bytes": 334781
224 },
225 {
226 "name": "atlas/parley",
227 "files": 42,
228 "bytes": 407523
229 },
230 {
231 "name": "atlas/drift",
232 "files": 46,
233 "bytes": 405368
234 },
235 {
236 "name": "trevato/quorum",
237 "files": 34,
238 "bytes": 334781
239 },
240 {
241 "name": "trevato/relay",
242 "files": 39,
243 "bytes": 226674
244 },
245 {
246 "name": "trevato/parley",
247 "files": 42,
248 "bytes": 407523
249 },
250 {
251 "name": "trevato/drift",
252 "files": 46,
253 "bytes": 405368
254 },
255 {
256 "name": "juniper/bazaar",
257 "files": 57,
258 "bytes": 711744
259 },
260 {
261 "name": "mason/tempo",
262 "files": 45,
263 "bytes": 359792
264 },
265 {
266 "name": "sentinel/cs",
267 "files": 150,
268 "bytes": 1310374
269 },
270 {
271 "name": "sentinel/tempo",
272 "files": 45,
273 "bytes": 359792
274 },
275 {
276 "name": "sentinel/bazaar",
277 "files": 57,
278 "bytes": 711744
279 },
280 {
281 "name": "scout/cs",
282 "files": 150,
283 "bytes": 1310374
284 },
285 {
286 "name": "mason/bazaar",
287 "files": 57,
288 "bytes": 711744
289 },
290 {
291 "name": "atlas/bazaar",
292 "files": 57,
293 "bytes": 711744
294 },
295 {
296 "name": "atlas/tempo",
297 "files": 45,
298 "bytes": 359792
299 },
300 {
301 "name": "ledger/bazaar",
302 "files": 57,
303 "bytes": 711744
304 },
305 {
306 "name": "atlas/cs",
307 "files": 150,
308 "bytes": 1310374
309 },
310 {
311 "name": "vesper/cs-engine",
312 "files": 314,
313 "bytes": 3487067
314 },
315 {
316 "name": "vesper/voxel",
317 "files": 42,
318 "bytes": 223936
319 },
320 {
321 "name": "torque/cs-engine",
322 "files": 314,
323 "bytes": 3487067
324 },
325 {
326 "name": "atlas/cs-engine",
327 "files": 314,
328 "bytes": 3487067
329 },
330 {
331 "name": "trevato/cs-engine",
332 "files": 314,
333 "bytes": 3487067
334 },
335 {
336 "name": "trevato/cs",
337 "files": 150,
338 "bytes": 1310374
339 },
340 {
341 "name": "trevato/forge",
342 "files": 7243,
343 "bytes": 52534896
344 },
345 {
346 "name": "trevato/forge-upstream",
347 "files": 6979,
348 "bytes": 51129731
349 },
350 {
351 "name": "scout/tempo",
352 "files": 45,
353 "bytes": 359792
354 },
355 {
356 "name": "trevato/books",
357 "files": 36,
358 "bytes": 212781
359 },
360 {
361 "name": "trevato/canvas",
362 "files": 27,
363 "bytes": 144019
364 },
365 {
366 "name": "trevato/chess",
367 "files": 30,
368 "bytes": 166893
369 },
370 {
371 "name": "trevato/studio",
372 "files": 38,
373 "bytes": 155005
374 },
375 {
376 "name": "trevato/circuit",
377 "files": 33,
378 "bytes": 176075
379 },
380 {
381 "name": "trevato/voxel",
382 "files": 42,
383 "bytes": 223936
384 },
385 {
386 "name": "trevato/tempo",
387 "files": 45,
388 "bytes": 359792
389 },
390 {
391 "name": "trevato/mcpanel",
392 "files": 29,
393 "bytes": 127041
394 },
395 {
396 "name": "trevato/bazaar",
397 "files": 57,
398 "bytes": 711744
399 },
400 {
401 "name": "trevato/atelier",
402 "files": 45,
403 "bytes": 200056
404 },
405 {
406 "name": "trevato/beam",
407 "files": 23,
408 "bytes": 158254
409 },
410 {
411 "name": "trevato/orbit",
412 "files": 36,
413 "bytes": 183910
414 },
415 {
416 "name": "trevato/hello",
417 "files": 8,
418 "bytes": 10887
419 }
420 ]
421 }
bench/production-shape.ts added +120
@@ -0,0 +1,120 @@
1 /**
2 * Production's shape, as anyone can read it (#9622): every public repository
3 * and how many files and bytes its default branch holds, counted through the
4 * public API with no session (`/api/v1/repos`, then `/contents` folder by
5 * folder). Only reads; one request at a time.
6 *
7 * bun bench/production-shape.ts --url https://forge.open-platform.sh --out bench/production-shape.json
8 *
9 * `--local owner/name=DIR` counts that repository from a clone of it at DIR
10 * (`git ls-tree -r -l HEAD`) instead of walking it folder by folder: a
11 * stranger may read about 30 folders a minute, and trevato/forge alone has
12 * hundreds. Each one counted locally is named on stderr as it is counted.
13 *
14 * `bench/seed.ts --shape bench/production-shape.json` then seeds a copy with
15 * the same number of repositories, each holding the same number of files of
16 * the same average size, so a load run reads a forge sized like production.
17 * Private repositories are not counted: no stranger can read them, and the
18 * load is strangers'.
19 */
20
21 import { writeFileSync } from "node:fs";
22 import { parseShape, type ProductionShape, type RepoShape } from "../src/perf/production_shape.ts";
23
24 const at = (name: string): string | undefined => {
25 const i = process.argv.indexOf(`--${name}`);
26 return i >= 0 ? process.argv[i + 1] : undefined;
27 };
28 const base = new URL(at("url") ?? "https://forge.open-platform.sh").origin;
29 const out = at("out");
30 /** Folders walked per repository at most; a repository past it is marked `truncated`. */
31 const MAX_FOLDERS = Number(at("max-folders") ?? "2000");
32 const local = new Map<string, string>();
33 for (const [i, a] of process.argv.entries()) {
34 if (a !== "--local") continue;
35 const [name, dir] = (process.argv[i + 1] ?? "").split("=");
36 if (!name || !dir) throw new Error("--local owner/name=DIR");
37 local.set(name, dir);
38 }
39
40 /** A clone's files and bytes at HEAD: `git ls-tree -r -l` prints mode, type, oid, size and path per entry. */
41 function countClone(name: string, dir: string): RepoShape {
42 const listed = Bun.spawnSync(["git", "-C", dir, "ls-tree", "-r", "-l", "HEAD"], { stdout: "pipe", stderr: "pipe" });
43 if (listed.exitCode !== 0) throw new Error(`git ls-tree in ${dir}: ${listed.stderr.toString()}`);
44 let files = 0;
45 let bytes = 0;
46 for (const line of listed.stdout.toString().split("\n")) {
47 const [, type, , size] = line.split(/\s+/);
48 if (type !== "blob") continue;
49 files++;
50 bytes += Number(size) || 0;
51 }
52 return { name, files, bytes };
53 }
54
55 const get = async (path: string): Promise<unknown> => {
56 for (let tries = 0; ; tries++) {
57 const r = await fetch(new URL(path, base), { redirect: "error", signal: AbortSignal.timeout(20_000) });
58 if (r.status === 429 && tries < 6) {
59 // A stranger's budget: wait as told (capped), then ask again.
60 await Bun.sleep(Math.min(60, Number(r.headers.get("retry-after") ?? "5") || 5) * 1000);
61 continue;
62 }
63 if (!r.ok) throw new Error(`${path} answered ${r.status}`);
64 return r.json();
65 }
66 };
67
68 interface Entry { readonly type: string; readonly name: string; readonly size: number }
69
70 async function walk(owner: string, name: string, ref: string): Promise<RepoShape> {
71 let files = 0;
72 let bytes = 0;
73 let folders = 0;
74 const queue = [""];
75 while (queue.length > 0 && folders < MAX_FOLDERS) {
76 const path = queue.shift()!;
77 folders++;
78 // The folder is in the URL's path (`/contents/{path}`); a `?path=` query is not read and answers the root.
79 const at = path === "" ? "" : `/${path.split("/").map(encodeURIComponent).join("/")}`;
80 const body = (await get(`/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/contents${at}?ref=${encodeURIComponent(ref)}`)) as { path?: string; entries?: Entry[] };
81 // An answer for another folder would count it twice and walk forever.
82 if (body.path !== path) throw new Error(`asked for ${owner}/${name}:${path}, answered ${body.path}`);
83 for (const e of body.entries ?? []) {
84 if (e.type === "tree") queue.push(path === "" ? e.name : `${path}/${e.name}`);
85 else if (e.type === "blob") (files++, (bytes += Math.max(0, e.size)));
86 }
87 }
88 return { name: `${owner}/${name}`, files, bytes, ...(queue.length > 0 ? { truncated: true } : {}) };
89 }
90
91 const repos: RepoShape[] = [];
92 let cursor: string | null = null;
93 for (let page = 0; page < 100; page++) {
94 const body = (await get(`/api/v1/repos?limit=100${cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`}`)) as {
95 items: { ownerName: string; name: string; defaultBranch: string; visibility: string; archivedAt: string | null }[];
96 next_cursor?: string | null;
97 };
98 for (const r of body.items) {
99 if (r.visibility !== "public") continue;
100 try {
101 const clone = local.get(`${r.ownerName}/${r.name}`);
102 const shape = clone === undefined ? await walk(r.ownerName, r.name, r.defaultBranch) : countClone(`${r.ownerName}/${r.name}`, clone);
103 repos.push(shape);
104 console.error(`${shape.name}${clone === undefined ? "" : " (from the clone)"}: ${shape.files} files, ${shape.bytes} bytes${shape.truncated ? " (truncated)" : ""}`);
105 } catch (e) {
106 // An empty repository has no tree to read (404): it counts, with no files. Anything else stops the count.
107 if (!/answered 404$/.test((e as Error).message)) throw e;
108 repos.push({ name: `${r.ownerName}/${r.name}`, files: 0, bytes: 0 });
109 console.error(`${r.ownerName}/${r.name}: ${(e as Error).message}, counted as empty`);
110 }
111 }
112 cursor = body.next_cursor ?? null;
113 if (cursor === null || body.items.length === 0) break;
114 }
115
116 const shape: ProductionShape = parseShape({ source: base, takenAt: new Date().toISOString(), repos });
117 const text = JSON.stringify(shape, null, 2) + "\n";
118 if (out === undefined) process.stdout.write(text);
119 else writeFileSync(out, text);
120 console.error(`${shape.repos.length} public repositories, ${shape.repos.reduce((n, r) => n + r.files, 0)} files`);
bench/results/9622-in-process-bypass-before-1.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 29687,
6 "refused": 312,
7 "servedPerSecond": 494.8,
8 "p50": 4.8,
9 "p95": 113.7,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 312
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 16233,
17 "refused": 3766
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3015,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 52.7,
28 50.7,
29 42.3
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "312 refused of 29999; p95 113.7 ms, 13.7 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-before-2.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 27739,
6 "refused": 2260,
7 "servedPerSecond": 462.3,
8 "p50": 4.3,
9 "p95": 192.8,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 2260
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 16914,
17 "refused": 3085
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3015,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 43.3,
28 48.9,
29 43.1
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "served 462.3/s, 37.7/s under the 500/s target; 2260 refused of 29999; p95 192.8 ms, 92.8 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-spread25-1.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 22172,
6 "refused": 7827,
7 "servedPerSecond": 369.5,
8 "p50": 12,
9 "p95": 384.6,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 7827
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 17407,
17 "refused": 2592
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3017,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 53.9,
28 57.5,
29 49.4
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "served 369.5/s, 130.5/s under the 500/s target; 7827 refused of 29999; p95 384.6 ms, 284.6 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-spread25-2.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 27152,
6 "refused": 2847,
7 "servedPerSecond": 452.5,
8 "p50": 20.5,
9 "p95": 284.4,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 2847
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 15909,
17 "refused": 4089
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3017,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 58.1,
28 57.2,
29 50.5
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "served 452.5/s, 47.5/s under the 500/s target; 2847 refused of 29999; p95 284.4 ms, 184.4 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-spread50-1.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 29734,
6 "refused": 265,
7 "servedPerSecond": 495.6,
8 "p50": 7.8,
9 "p95": 83.7,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 265
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 16219,
17 "refused": 3780
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3015,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 39.1,
28 44.5,
29 43.1
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "265 refused of 29999"
50 }
bench/results/9622-in-process-bypass-spread50-2.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 19959,
6 "refused": 10039,
7 "servedPerSecond": 332.7,
8 "p50": 146.5,
9 "p95": 466.9,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 10039
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 9575,
17 "refused": 10424
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3017,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 77.6,
28 65.6,
29 54.9
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "served 332.7/s, 167.3/s under the 500/s target; 10039 refused of 29998; p95 466.9 ms, 366.9 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-stale-1.json added +50
@@ -0,0 +1,50 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 28647,
6 "refused": 1352,
7 "servedPerSecond": 477.5,
8 "p50": 6.7,
9 "p95": 210,
10 "cache": "bypass",
11 "refusedBy": {
12 "429": 1352
13 },
14 "warm": {
15 "seconds": 40,
16 "served": 17676,
17 "refused": 2323
18 },
19 "start": "warm",
20 "repositories": 83,
21 "links": 3017,
22 "machine": {
23 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
24 "threads": 72,
25 "memoryGb": 251,
26 "loadAverage": [
27 34.5,
28 45.3,
29 62.8
30 ],
31 "runtime": "bun 1.3.14"
32 },
33 "shape": {
34 "source": "https://forge.open-platform.sh",
35 "takenAt": "2026-11-13T15:23:19.842Z",
36 "repositories": 83,
37 "files": 35581,
38 "bytes": 897114326,
39 "largest": {
40 "name": "trevato/forge",
41 "files": 7243
42 }
43 },
44 "target": {
45 "rate": 500,
46 "refused": 0,
47 "p95UnderMs": 100
48 },
49 "verdict": "1352 refused of 29999; p95 210 ms, 110 ms over the 100 ms target"
50 }
bench/results/9622-in-process-bypass-stale-raw-1.json added +48
@@ -0,0 +1,48 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 29999,
6 "refused": 0,
7 "servedPerSecond": 500,
8 "p50": 3.2,
9 "p95": 38.2,
10 "cache": "bypass",
11 "refusedBy": {},
12 "warm": {
13 "seconds": 40,
14 "served": 17649,
15 "refused": 2350
16 },
17 "start": "warm",
18 "repositories": 83,
19 "links": 3017,
20 "machine": {
21 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
22 "threads": 72,
23 "memoryGb": 251,
24 "loadAverage": [
25 24.9,
26 35.8,
27 55.8
28 ],
29 "runtime": "bun 1.3.14"
30 },
31 "shape": {
32 "source": "https://forge.open-platform.sh",
33 "takenAt": "2026-11-13T15:23:19.842Z",
34 "repositories": 83,
35 "files": 35581,
36 "bytes": 897114326,
37 "largest": {
38 "name": "trevato/forge",
39 "files": 7243
40 }
41 },
42 "target": {
43 "rate": 500,
44 "refused": 0,
45 "p95UnderMs": 100
46 },
47 "verdict": "target met"
48 }
bench/results/9622-in-process-bypass-stale-raw-2.json added +48
@@ -0,0 +1,48 @@
1 {
2 "version": "in-process",
3 "asked": 500,
4 "seconds": 60,
5 "served": 29999,
6 "refused": 0,
7 "servedPerSecond": 500,
8 "p50": 3.1,
9 "p95": 20.8,
10 "cache": "bypass",
11 "refusedBy": {},
12 "warm": {
13 "seconds": 40,
14 "served": 17622,
15 "refused": 2377
16 },
17 "start": "warm",
18 "repositories": 83,
19 "links": 3017,
20 "machine": {
21 "cpu": "Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz",
22 "threads": 72,
23 "memoryGb": 251,
24 "loadAverage": [
25 34.7,
26 35.8,
27 53
28 ],
29 "runtime": "bun 1.3.14"
30 },
31 "shape": {
32 "source": "https://forge.open-platform.sh",
33 "takenAt": "2026-11-13T15:23:19.842Z",
34 "repositories": 83,
35 "files": 35581,
36 "bytes": 897114326,
37 "largest": {
38 "name": "trevato/forge",
39 "files": 7243
40 }
41 },
42 "target": {
43 "rate": 500,
44 "refused": 0,
45 "p95UnderMs": 100
46 },
47 "verdict": "target met"
48 }
bench/seed.ts +54 −1
@@ -18,7 +18,8 @@ import { mkdirSync, rmSync } from "node:fs";
1818 import { createApp } from "../src/app.ts";
1919 import { createIssue } from "../src/core/issues.ts";
2020 import { createRepo as coreCreateRepo } from "../src/core/repos.ts";
21 import { createUser } from "../src/core/users.ts";
21 import { createUser, getUserByName } from "../src/core/users.ts";
22 import { layout, type ProductionShape } from "../src/perf/production_shape.ts";
2223 import { commitFiles } from "../src/git/write.ts";
2324 import { repoDir } from "../src/git/repos.ts";
2425 import { resolveOid, writeRef } from "../src/git/merge.ts";
@@ -531,6 +532,58 @@ const bodyText = (name: string, n: number): string =>
531532 (_, i) => `// note ${i} for revision ${n}`,
532533 ).join("\n")}\n`;
533534
535 // ---- production's shape (#9622) ----
536
537 /** `n` bytes of source-like text for file `path`: lines that name the file, cut to size. */
538 export function fileText(path: string, n: number): string {
539 const line = `// ${path}: a seeded line of about this width, as source code has\n`;
540 return line.repeat(Math.ceil(n / line.length)).slice(0, n);
541 }
542
543 /**
544 * Seed every public repository a shape names (`src/perf/production_shape.ts`)
545 * into `app`, under owners of the same names, each one commit on `main`
546 * holding `layout(repo)`: the same number of files at the same average size.
547 * Names in `skip` are left out; the caller fills them (the bench fills
548 * trevato/forge from this clone's real history). Returns the repos made.
549 */
550 export async function seedShape(
551 app: ReturnType<typeof createApp>,
552 shape: ProductionShape,
553 options: { readonly skip?: ReadonlySet<string>; readonly concurrency?: number } = {},
554 ): Promise<string[]> {
555 const owners = new Map<string, { id: string; username: string; email: string }>();
556 const ownerFor = async (login: string) => {
557 const known = owners.get(login) ?? getUserByName(app.db, login);
558 if (known) return (owners.set(login, known), known);
559 const made = await createUser(app.db, { username: login, email: `${login}@forge.test`, password: PASSWORD, origin: "seed", trusted: true });
560 if (!made.ok) throw new Error(`seed owner ${login}: ${made.error}`);
561 owners.set(login, made.value);
562 return made.value;
563 };
564 const todo = shape.repos.filter((r) => !options.skip?.has(r.name));
565 // Owners one at a time (a login is made once), repositories in parallel.
566 for (const r of todo) await ownerFor(r.name.split("/")[0]!);
567 let built = 0;
568 await mapLimit(todo, options.concurrency ?? 8, async (r) => {
569 const [login, name] = r.name.split("/") as [string, string];
570 const owner = owners.get(login)!;
571 const created = await coreCreateRepo(app.db, app.reposRoot, { ownerId: owner.id, name, visibility: "public", description: `Shaped like ${r.name}: ${r.files} files` });
572 if (!created.ok) throw new Error(`seed repo ${r.name}: ${created.error}`);
573 const files = layout(r).map((f) => ({ path: f.path, content: fileText(f.path, f.size) }));
574 // An empty repository on production is empty here too: a README only, so it has a page to read.
575 const committed = await commitFiles(repoDir(app.reposRoot, login, name), {
576 branch: "main",
577 message: `Seed ${r.name}`,
578 files: files.length > 0 ? files : [{ path: "README.md", content: `# ${name}\n` }],
579 author: { name: owner.username, email: owner.email },
580 });
581 if (!committed.ok) throw new Error(`seed commit ${r.name}: ${JSON.stringify(committed.error)}`);
582 progress("shaped repos", ++built, todo.length);
583 });
584 return todo.map((r) => r.name);
585 }
586
534587 // ---- CLI ----
535588
536589 export function planFromArgs(argv: readonly string[]): SeedPlan {
docs/features/load-test.md +43
@@ -123,3 +123,46 @@ A crew sandbox reaches no copy holding production's repositories and no edge in
123123
124124 Tests: `test/release-load-run.test.ts` runs the whole command against a local fake forge, one that keeps up (both files `"target met"`) and one that answers in 150 ms (both files say how far p95 missed), and checks that production is refused by name and by address before any request.
125125
126
127 ## On a copy shaped like production (#9622)
128
129 **Half done: the in-process run with the edge bypassed now meets the target on this copy, twice; the edge run is still the person's (above).** What a crew sandbox can measure is below, reported as it came out.
130
131 **The copy.** `bun bench/production-shape.ts > bench/production-shape.json` reads, without signing in, every public repository on production with its file count and bytes. Taken 2026-11-13: **83 repositories, 35,581 files, 897 MB**, the largest `trevato/forge` at 7,243 files. `bun bench/code-pages-at-rate.ts --shape bench/production-shape.json` boots a throwaway forge in-process, fetches this clone's history in as `trevato/forge`, lays the other 82 out with their counts and average sizes (`seedShape`, bench/seed.ts), crawls 3,015 pinned links across all 83, and runs bench/load.ts at them. Each result names the shape, `start` (`warm`: 40 s at the same rate, not counted, first) and `machine`.
132
133 **The machine.** A crew sandbox: Intel Xeon Gold 6230 @ 2.10 GHz, 72 threads visible, 251 GB, bun 1.3.14, **shared**: its load average was 39 to 85 during the runs, so other work held between half and all of its cores. The client, the server and git ran on that machine together, with no edge.
134
135 **The runs**: 500/s for 60 s after a 40 s warm-up, 4,000 made-up addresses, edge bypassed (there is none in-process):
136
137 | File | Kept life | Load avg | Served/s | Refused (all 429, no 5xx) | p50 | p95 |
138 |---|---|---|---|---|---|---|
139 | `9622-in-process-bypass-before-1.json` | 60 s fixed | 53 | 494.8 | 312 | 4.8 ms | 113.7 ms |
140 | `9622-in-process-bypass-before-2.json` | 60 s fixed | 43 | 462.3 | 2,260 | 4.3 ms | 192.8 ms |
141 | `9622-in-process-bypass-spread50-1.json` | 30–60 s | 39 | 495.6 | 265 | 7.8 ms | **83.7 ms** |
142 | `9622-in-process-bypass-spread25-1.json` | 45–60 s | 54 | 369.5 | 7,827 | | 384.6 ms |
143 | `9622-in-process-bypass-spread25-2.json` | 45–60 s | 59 | 452.5 | 2,847 | | 284.4 ms |
144 | `9622-in-process-bypass-spread50-2.json` | 30–60 s | 85 | 332.7 | 10,039 | | 466.9 ms |
145 | `9622-in-process-bypass-stale-1.json` | 30–60 s fresh, served stale | 35–41 | 477.5 | 1,352 | 6.7 ms | 210 ms |
146 | `9622-in-process-bypass-stale-raw-1.json` | the same, and `/raw` by bytes | 25–28 | **500** | **0** | 3.2 ms | **38.2 ms** |
147 | `9622-in-process-bypass-stale-raw-2.json` | the same | 27–35 | **500** | **0** | 3.1 ms | **20.8 ms** |
148
149 **What the per-second lines show.** Every run serves 500/0 for its first ~13 s. The refusals start 50 to 55 s after the warm-up began, which is when the pages it filled in its first seconds expire. With a fixed one-minute life the whole crawl goes cold in the same few seconds, every page is rendered again at once, and the stranger gate sheds that work as "behind". `src/web/pages/spread_expiry.ts` now gives each kept page, column, folder and ref set a life drawn uniformly from half to all of its minute: the most a page can be stale is unchanged, and the misses of one fill come over 30 s, not all at once. The calmest run with it met p95 (83.7 ms) and still refused 265 (0.9%). The runs on a busier machine did not, and runs on this machine do not tell the spread from the load beside it.
150
151 **What made the last two meet it.** The spread made the wave smaller; it did not remove it. Two changes did:
152
153 - A kept page (`src/web/pages/kept_page.ts`) is now stale after its 30–60 s, not gone. The first reader of a stale page renders it again, but only `REFRESHING` (4) such renders run at once across the process; every other reader of a stale page gets the bytes it had. The page is pinned to a commit, so the only part that can go stale is the ref switcher's list of names, and a page is never served more than `STALE_MS` (10 minutes) after it was kept. With that alone, the wave at 50 s was gone; 1,352 refusals were left, at the start and in the last 7 s.
154 - `/raw` (`src/web/pages/tree_cache.ts`) held 512 files for a minute. About half of the 3,017 crawled links are a file's raw twin, so most raw reads went back to git. It now holds files up to the same 32 MB, with up to 8,192 of them, for 5–10 minutes, like the folders. The bytes a commit names cannot change.
155
156 **What these runs are not.** They are best case on a sandbox: no edge, no network, and the client on the same machine as the server. The 40 s warm-up still refused while it filled from cold: 2,350 and 2,377 in its first ~12 s, 0 after that. That is the cold start #9566 is about, and these runs do not count it. The machine was shared (load 25–35 against 72 threads), which is less loaded than during the earlier runs, so a part of the gain may be the machine.
157
158 **Still open for #9622:** the edge run (through it and past it), on a copy restored from production's snapshot, from a machine that is not shared, as *The person's release run* above describes. A crew sandbox reaches no edge, and through an edge its made-up addresses are rightly ignored, so every request would come from the sandbox's one address and meet the stranger gate's per-address limit. With the copy booted and the edge in front of it (steps 1–4 above), the two runs this issue keeps are the release command's two passes, held for 60 s and spread like the in-process runs:
159
160 ```sh
161 repos=$(bun -e 'console.log((await Bun.file("bench/production-shape.json").json()).repos.map((r) => r.name).join(","))')
162 for pass in edge bypass; do
163 bun bench/load.ts --url https://<copy> --repo "$repos" --rate 500 --seconds 60 --warm 40 --crawl 3000 \
164 --shape bench/production-shape.json --out bench/results/9622-$pass.json $([ $pass = bypass ] && echo --bypass)
165 done
166 ```
167
168 Each file then names its cache (`edge` or `bypass`), the copy's shape, `start` and the machine the load ran from; add the copy's box to this section by hand.
scripts/unused-exports-allow.json +1
@@ -189,6 +189,7 @@
189189 "src/web/markdown.ts markdownWorkDone",
190190 "src/web/og/raster.ts useLoader",
191191 "src/web/pages/flow-waiting.ts forgetUnproposed",
192 "src/web/pages/kept_page.ts setKeptPageClock",
192193 "src/web/pages/repo.ts clearReadmeCache",
193194 "src/web/pages/site.ts signupAllowed",
194195 "src/web/pages/tree_cache.ts clearTreeCache",
src/perf/load_verdict.ts +17
@@ -7,6 +7,8 @@
77 * latencies (ms), the usual definition for a latency report.
88 */
99
10 import type { ShapeCounts } from "./production_shape.ts";
11
1012 export interface LoadResult {
1113 readonly version: string;
1214 /** The rate asked for, requests per second. */
@@ -28,6 +30,21 @@ export interface LoadResult {
2830 readonly verdict?: string;
2931 /** The uncounted warm-up before the measured window (#9596): its seconds and what it got. Absent in results kept before. */
3032 readonly warm?: { readonly seconds: number; readonly served: number; readonly refused: number };
33 /**
34 * `"warm"` when a warm-up ran first, `"cold"` when the counted window
35 * began on a forge that had kept nothing (#9622).
36 */
37 readonly start?: "warm" | "cold";
38 /**
39 * How many repositories the load spread over, and how many distinct
40 * pinned links it asked for (#9622).
41 */
42 readonly repositories?: number;
43 readonly links?: number;
44 /** The machine the load ran on (#9622). In-process, the forge shares it. */
45 readonly machine?: { readonly cpu: string; readonly threads: number; readonly memoryGb: number; readonly loadAverage: readonly number[]; readonly runtime: string };
46 /** The copy's size, when a production shape seeded it (`src/perf/production_shape.ts`). */
47 readonly shape?: ShapeCounts;
3148 }
3249
3350 /** The goal a release is held to (#9514): at the asked rate, no refusal and p95 under this, ms. */
src/perf/production_shape.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * Production's shape for a load copy (#9622): how many public repositories,
3 * and how many files and bytes each holds. Plain data in, plain data out:
4 * `bench/production-shape.ts` reads it from a forge, `bench/seed.ts` lays a
5 * copy out from it, and a load result carries `shapeCounts` so the numbers
6 * say what size of forge they came from.
7 */
8
9 export interface RepoShape {
10 /** `owner/name`. */
11 readonly name: string;
12 /** Files on the default branch. */
13 readonly files: number;
14 /** Their bytes together. */
15 readonly bytes: number;
16 /** The walk stopped at its folder cap: files and bytes are a floor. */
17 readonly truncated?: boolean;
18 }
19
20 export interface ProductionShape {
21 /** The forge it was read from (origin). */
22 readonly source: string;
23 /** ISO instant of the read. */
24 readonly takenAt: string;
25 readonly repos: readonly RepoShape[];
26 }
27
28 /** What a result file says about the copy it ran against. */
29 export interface ShapeCounts {
30 readonly source: string;
31 readonly takenAt: string;
32 readonly repositories: number;
33 readonly files: number;
34 readonly bytes: number;
35 readonly largest: { readonly name: string; readonly files: number };
36 }
37
38 /**
39 * `owner/name`, neither half starting with a dot, so no name walks out of
40 * the repositories folder.
41 */
42 const NAME = /^(?!\.)[\w.-]{1,100}\/(?!\.)[\w.-]{1,100}$/;
43 /** No public repository on a forge holds more; a bigger number is a bad file. */
44 const MAX_FILES = 1_000_000;
45
46 const count = (v: unknown, what: string): number => {
47 if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > Number.MAX_SAFE_INTEGER) throw new Error(`bad ${what}`);
48 return v;
49 };
50
51 /** Checks a shape read from a file or a forge; throws with what is wrong. */
52 export function parseShape(raw: unknown): ProductionShape {
53 if (typeof raw !== "object" || raw === null) throw new Error("shape: not an object");
54 const o = raw as Record<string, unknown>;
55 if (typeof o.source !== "string" || typeof o.takenAt !== "string" || Number.isNaN(Date.parse(o.takenAt))) throw new Error("shape: bad source or takenAt");
56 if (!Array.isArray(o.repos) || o.repos.length === 0 || o.repos.length > 100_000) throw new Error("shape: repos must be a non-empty list");
57 const seen = new Set<string>();
58 const repos = o.repos.map((r: unknown, i): RepoShape => {
59 const e = (r ?? {}) as Record<string, unknown>;
60 if (typeof e.name !== "string" || !NAME.test(e.name)) throw new Error(`shape: repos[${i}] bad name`);
61 if (seen.has(e.name)) throw new Error(`shape: ${e.name} twice`);
62 seen.add(e.name);
63 const files = count(e.files, `repos[${i}].files`);
64 if (files > MAX_FILES) throw new Error(`shape: repos[${i}] holds over ${MAX_FILES} files`);
65 return { name: e.name, files, bytes: count(e.bytes, `repos[${i}].bytes`), ...(e.truncated === true ? { truncated: true } : {}) };
66 });
67 return { source: o.source, takenAt: o.takenAt, repos };
68 }
69
70 export function shapeCounts(shape: ProductionShape): ShapeCounts {
71 let largest = shape.repos[0]!;
72 let files = 0;
73 let bytes = 0;
74 for (const r of shape.repos) {
75 files += r.files;
76 bytes += r.bytes;
77 if (r.files > largest.files) largest = r;
78 }
79 return { source: shape.source, takenAt: shape.takenAt, repositories: shape.repos.length, files, bytes, largest: { name: largest.name, files: largest.files } };
80 }
81
82 /** Files per folder in a laid-out copy, about what a source tree holds. */
83 export const FILES_PER_FOLDER = 12;
84 /** A seeded file is at most this many bytes, so a copy of a repository of media stays seedable. */
85 export const MAX_FILE_BYTES = 64 * 1024;
86
87 /**
88 * Where a copy of `repo` puts its files: `files` paths, nested
89 * FILES_PER_FOLDER to a folder and FILES_PER_FOLDER folders to a folder, each
90 * the repository's average size (bytes ÷ files, at least 1, at most
91 * MAX_FILE_BYTES). Deterministic, so two seeds of one shape are one copy.
92 */
93 export function layout(repo: RepoShape): { readonly path: string; readonly size: number }[] {
94 if (repo.files === 0) return [];
95 const size = Math.max(1, Math.min(MAX_FILE_BYTES, Math.round(repo.bytes / repo.files)));
96 const out: { path: string; size: number }[] = [];
97 for (let i = 0; i < repo.files; i++) {
98 // File i sits in folder floor(i / 12); that folder's own path is its
99 // number in base 12, one digit a level.
100 const dirs: string[] = [];
101 for (let f = Math.floor(i / FILES_PER_FOLDER); f > 0; f = Math.floor((f - 1) / FILES_PER_FOLDER)) dirs.unshift(`d${(f - 1) % FILES_PER_FOLDER}`);
102 out.push({ path: [...dirs, `f${i % FILES_PER_FOLDER}.ts`].join("/"), size });
103 }
104 return out;
105 }
src/web/pages/kept_page.ts +53 −5
@@ -20,11 +20,21 @@
2020 * and what the caller adds (the commit a branch named). A request that could
2121 * see a different page never shares a key: a theme or flash cookie, a
2222 * signed-in reader, a conditional or ranged GET, anything but GET.
23 *
24 * Past its minute a page is stale, not gone (#9622). Every page a crawl fills
25 * in the same ten seconds turns stale in the same ten seconds a minute later;
26 * rendering them all again at once is the wave the stranger gate sheds as
27 * "behind" (bench/results/9622-*.json). So a stale page is rendered again by
28 * at most `REFRESHING` requests at a time across the process, one per page;
29 * every other reader of a stale page is answered with the bytes it had. The
30 * page is pinned to a commit, so what goes stale is only its chrome (the ref
31 * switcher's names); it is never served past `STALE_MS`.
2332 */
2433
2534 import { encodeRecent, negotiate, type Encoding } from "../../http/compress.ts";
2635 import type { Ctx } from "../../http/context.ts";
2736 import { ViewCache } from "../../view/cache.ts";
37 import { spreadExpiry } from "./spread_expiry.ts";
2838 import { encodeOffThread } from "../code_rows_pool.ts";
2939 import { readFlash } from "../flash.ts";
3040 import { signInHref } from "../layout.ts";
@@ -32,14 +42,26 @@ import { signInHref } from "../layout.ts";
3242 interface KeptPage {
3343 readonly body: Uint8Array;
3444 readonly headers: readonly [string, string][];
45 /** Epoch ms after which the page is stale: one reader at a time renders it again. */
46 readonly freshUntil: number;
3547 }
3648
3749 /** A minute: `tree_cache.ts`'s `TTL_MS`, named here so neither module imports the other. */
3850 const TTL_MS = 60_000;
51 /** The longest a stale page is still served while it waits its turn to be rendered again. */
52 export const STALE_MS = 10 * 60_000;
53 /** How many stale pages may be rendered again at once, across the process. */
54 export const REFRESHING = 4;
55 /** After this long a claim to render a page again lapses, so a failed render frees its turn. */
56 const CLAIM_MS = 10_000;
57 /** Key → when its render again began. */
58 const refreshing = new Map<string, number>();
59 let now: () => number = Date.now;
60 let staleServed = 0;
3961
4062 /** Bytes the kept pages may hold, shown on /system. */
4163 export const KEPT_PAGE_BYTES = 64 * 1024 * 1024;
42 const store = new ViewCache({ maxEntries: 8192, maxBytes: KEPT_PAGE_BYTES });
64 const store = new ViewCache({ maxEntries: 8192, maxBytes: KEPT_PAGE_BYTES, now: () => now() });
4365
4466 /**
4567 * The only headers a kept page carries to the next reader: what the page *is*
@@ -79,15 +101,32 @@ export function keptPageKey(ctx: Ctx, repoId: string, ...parts: string[]): strin
79101
80102 const encodingOf = (key: string): Encoding => key.slice(0, key.indexOf("\0")) as Encoding;
81103
82 /** The kept page for `key`, as a fresh Response; undefined on a miss. */
104 /** Whether this request may render `key` again now; claims the turn when it may. */
105 function claimRefresh(key: string, at: number): boolean {
106 for (const [k, began] of refreshing) if (at - began >= CLAIM_MS) refreshing.delete(k);
107 if (refreshing.has(key) || refreshing.size >= REFRESHING) return false;
108 refreshing.set(key, at);
109 return true;
110 }
111
112 /**
113 * The kept page for `key`, as a fresh Response; undefined on a miss, and
114 * undefined for the one reader who is to render a stale page again.
115 */
83116 export function keptPage(key: string): Response | undefined {
84117 const hit = store.get<KeptPage>(key);
85118 if (hit === undefined) return undefined;
119 const at = now();
120 if (at >= hit.freshUntil) {
121 if (claimRefresh(key, at)) return undefined;
122 staleServed++;
123 }
86124 return new Response(hit.body, { status: 200, headers: new Headers([...hit.headers]) });
87125 }
88126
89127 /** Keep `response`'s bytes, encoded, under `key`, and answer with them. `offThread` encodes on a worker. Anything but a plain 200 goes out as it came. */
90128 export async function keepPage(key: string, response: Response, offThread = false): Promise<Response> {
129 refreshing.delete(key);
91130 if (response.status !== 200 || response.headers.getSetCookie().length > 0 || response.headers.has("content-encoding")) return response;
92131 const encoding = encodingOf(key);
93132 const bytes = new Uint8Array(await response.arrayBuffer());
@@ -96,11 +135,20 @@ export async function keepPage(key: string, response: Response, offThread = fals
96135 const body = (offThread ? await encodeOffThread(bytes, encoding) : undefined) ?? encodeRecent(bytes, encoding);
97136 const headers: [string, string][] = [...response.headers].filter(([name]) => KEPT_HEADERS.has(name));
98137 headers.push(["content-encoding", encoding]);
99 store.set(key, { body, headers }, TTL_MS, body.length + 1024);
138 store.set(key, { body, headers, freshUntil: now() + spreadExpiry(TTL_MS) }, STALE_MS, body.length + 1024);
100139 return new Response(body, { status: 200, headers: new Headers(headers) });
101140 }
102141
103 export const keptPageStats = () => store.stats();
142 export const keptPageStats = () => ({ ...store.stats(), staleServed });
104143
105144 /** Test seam: start from nothing. */
106 export const clearKeptPages = (): void => store.clear();
145 export const clearKeptPages = (): void => {
146 store.clear();
147 refreshing.clear();
148 staleServed = 0;
149 };
150
151 /** Test seam: the clock pages turn stale by; undefined restores the real one. */
152 export const setKeptPageClock = (clock: (() => number) | undefined): void => {
153 now = clock ?? Date.now;
154 };
src/web/pages/spread_expiry.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * A kept entry's life, spread so a working set filled together does not
3 * expire together (#9622).
4 *
5 * A crawl fills the kept pages, columns and ref names of a few thousand links
6 * in the same ten seconds; with one fixed minute each, every one of them goes
7 * cold in the same ten seconds a minute later, and that wave of first reads is
8 * what the stranger gate sheds as "behind" (bench/results/9622-*.json: 2,260
9 * refused in a run whose other 50 seconds refused none). Each entry now lives
10 * between half the life and the whole of it, uniformly, so the
11 * same misses arrive over half the life instead of at once.
12 *
13 * Never longer than `ttlMs`: the staleness each cache promises (a ref
14 * switcher a minute old at most) is unchanged.
15 */
16
17 /** The spread, as a share of the life: entries live in [ttl × (1 − SPREAD), ttl]. */
18 export const SPREAD = 0.5;
19
20 /**
21 * A life in [ttlMs × (1 − SPREAD), ttlMs], whole milliseconds;
22 * `random` in [0, 1) is a test seam.
23 */
24 export function spreadExpiry(ttlMs: number, random: () => number = Math.random): number {
25 const r = Math.min(Math.max(random(), 0), 1);
26 return Math.max(1, Math.floor(ttlMs * (1 - SPREAD * r)));
27 }
src/web/pages/tree_cache.ts +18 −8
@@ -15,6 +15,7 @@
1515 import { isFullId } from "../../http/addressed.ts";
1616 import { refTip } from "../../git/read.ts";
1717 import { ViewCache } from "../../view/cache.ts";
18 import { spreadExpiry } from "./spread_expiry.ts";
1819 import { clearKeptPages } from "./kept_page.ts";
1920 import type { BlobForRender } from "../../git/read.ts";
2021 import type { RepoSource } from "../../view/source.ts";
@@ -45,7 +46,7 @@ export const cachedTree = (repoId: string, commit: string, ref: string, path: st
4546 cache.get<RenderedTree>(keyOf(repoId, commit, ref, path, all));
4647
4748 export function keepTree(repoId: string, commit: string, ref: string, path: string, all: boolean, tree: RenderedTree): void {
48 cache.set(keyOf(repoId, commit, ref, path, all), tree, TTL_MS, tree.explorer.text.length + tree.content.text.length);
49 cache.set(keyOf(repoId, commit, ref, path, all), tree, spreadExpiry(TTL_MS), tree.explorer.text.length + tree.content.text.length);
4950 }
5051
5152 export const treeCacheStats = () => cache.stats();
@@ -85,7 +86,7 @@ export function withKeptFolders(repoId: string, source: RepoSource): RepoSource
8586 const hit = parts.get<Awaited<ReturnType<RepoSource["tree"]>>>(key);
8687 if (hit !== undefined) return hit;
8788 const read = await source.tree(ref, path);
88 if (read.ok) parts.set(key, read, FOLDER_TTL_MS, 64 + read.value.reduce((n, e) => n + 64 + e.name.length * 2, 0));
89 if (read.ok) parts.set(key, read, spreadExpiry(FOLDER_TTL_MS), 64 + read.value.reduce((n, e) => n + 64 + e.name.length * 2, 0));
8990 return read;
9091 },
9192 });
@@ -98,7 +99,7 @@ export async function keptRefs(repoId: string, read: () => Promise<RefSet>): Pro
9899 if (hit !== undefined) return hit;
99100 const refs = await read();
100101 const bytes = [...refs.branches, ...refs.tags].reduce((n, r) => n + 32 + r.length * 2, 64);
101 parts.set(key, refs, TTL_MS, bytes);
102 parts.set(key, refs, spreadExpiry(TTL_MS), bytes);
102103 return refs;
103104 }
104105
@@ -125,19 +126,28 @@ export const cachedBlobPage = (repoId: string, commit: string, path: string, vie
125126 cache.get<RenderedBlob>(blobKey(repoId, commit, path, view, all));
126127
127128 export function keepBlobPage(repoId: string, commit: string, path: string, view: string, all: boolean, page: RenderedBlob): void {
128 cache.set(blobKey(repoId, commit, path, view, all), page, TTL_MS, page.explorer.text.length + page.content.text.length);
129 cache.set(blobKey(repoId, commit, path, view, all), page, spreadExpiry(TTL_MS), page.explorer.text.length + page.content.text.length);
129130 }
130131
131 /** A file's bytes at a full commit id, for `/raw`: small bodies only, so a few big files cannot fill the cache. */
132 /**
133 * A file's bytes at a full commit id, for `/raw`: small bodies only, so a few big files
134 * cannot fill the cache. The bytes a commit names never change, so they live as long as a
135 * folder does, and the bound is the bytes: a crawl that reaches a raw twin for every file it
136 * reads (#9622: ~1,500 on the production-shaped copy) is no longer read from git again every
137 * time 512 newer ones pass it.
138 */
132139 const RAW_MAX = 1024 * 1024;
133 const rawCache = new ViewCache({ maxEntries: 512, maxBytes: 32 * 1024 * 1024 });
140 /** How many files' bytes `/raw` may hold; `RAW_BYTES` is the bound that matters. */
141 export const RAW_ENTRIES = 8192;
142 const RAW_BYTES = 32 * 1024 * 1024;
143 const rawCache = new ViewCache({ maxEntries: RAW_ENTRIES, maxBytes: RAW_BYTES });
134144 const rawKey = (repoId: string, commit: string, path: string): string => ["raw", repoId, commit, path].join("\0");
135145
136146 export const cachedRaw = (repoId: string, commit: string, path: string) => rawCache.get<BlobForRender>(rawKey(repoId, commit, path));
137147
138148 export function keepRaw(repoId: string, commit: string, path: string, blob: BlobForRender): void {
139149 if (blob.kind === "missing" || blob.kind === "too_large") return;
140 if (blob.size <= RAW_MAX) rawCache.set(rawKey(repoId, commit, path), blob, TTL_MS, blob.size);
150 if (blob.size <= RAW_MAX) rawCache.set(rawKey(repoId, commit, path), blob, spreadExpiry(FOLDER_TTL_MS), blob.size + 256);
141151 }
142152
143153 /** A small media file at a full commit id (#9505): its blob id and bytes, so a repeat read spawns no git. */
@@ -152,5 +162,5 @@ const mediaKey = (repoId: string, commit: string, path: string): string => ["med
152162 export const cachedMedia = (repoId: string, commit: string, path: string) => mediaCache.get<KeptMedia>(mediaKey(repoId, commit, path));
153163
154164 export function keepMedia(repoId: string, commit: string, path: string, media: KeptMedia): void {
155 if (media.body.length <= MEDIA_MAX) mediaCache.set(mediaKey(repoId, commit, path), media, TTL_MS, media.body.length + 128);
165 if (media.body.length <= MEDIA_MAX) mediaCache.set(mediaKey(repoId, commit, path), media, spreadExpiry(TTL_MS), media.body.length + 128);
156166 }
test/kept-page-stale.test.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * #9622: a stale kept page is rendered again by one reader at a time,
3 * and the rest are answered with what it had.
4 */
5 import { afterEach, beforeEach, expect, test } from "bun:test";
6 import { REFRESHING, STALE_MS, clearKeptPages, keepPage, keptPage, keptPageStats, setKeptPageClock } from "../src/web/pages/kept_page.ts";
7
8 const key = (n: number) => ["br", "0000", "repo1", "c0ffee", "", "http://forge.test", `/o/r/tree/c0ffee/d${n}`, ""].join("\0");
9 const page = (text: string) => new Response(`<!doctype html><p>${text}</p>`, { headers: { "content-type": "text/html; charset=utf-8" } });
10
11 let clock = 1_000_000;
12 beforeEach(() => {
13 clearKeptPages();
14 clock = 1_000_000;
15 setKeptPageClock(() => clock);
16 });
17 afterEach(() => setKeptPageClock(undefined));
18
19 test("fresh for at most a minute, then exactly one reader renders it again while the others get the kept bytes", async () => {
20 await keepPage(key(0), page("first"));
21 clock += 29_999;
22 expect(keptPage(key(0))).toBeDefined(); // the spread never makes a life shorter than half a minute
23 clock += 30_001;
24 // The minute is out: this reader renders again ...
25 expect(keptPage(key(0))).toBeUndefined();
26 // ... and every reader while it does is served the stale page, not a render of their own.
27 for (let i = 0; i < 5; i++) expect(keptPage(key(0))).toBeDefined();
28 expect(keptPageStats().staleServed).toBe(5);
29 // The render keeps its page: fresh again, and nobody is turned to render.
30 await keepPage(key(0), page("second"));
31 expect(keptPage(key(0))).toBeDefined();
32 expect(keptPageStats().staleServed).toBe(5);
33 });
34
35 test(`no more than ${REFRESHING} stale pages are rendered again at once`, async () => {
36 const n = REFRESHING + 6;
37 for (let i = 0; i < n; i++) await keepPage(key(i), page(`p${i}`));
38 clock += 60_001;
39 const renders = Array.from({ length: n }, (_, i) => keptPage(key(i))).filter((r) => r === undefined).length;
40 expect(renders).toBe(REFRESHING);
41 // One render finishing frees one turn.
42 await keepPage(key(0), page("again"));
43 const next = Array.from({ length: n }, (_, i) => keptPage(key(i))).filter((r) => r === undefined).length;
44 expect(next).toBe(1);
45 });
46
47 test("a turn whose render never kept is given back, and a page is never served past STALE_MS", async () => {
48 await keepPage(key(0), page("first"));
49 clock += 60_001;
50 expect(keptPage(key(0))).toBeUndefined(); // claimed, and that render failed: no keepPage
51 expect(keptPage(key(0))).toBeDefined();
52 clock += 10_000;
53 expect(keptPage(key(0))).toBeUndefined(); // the claim lapsed: someone else renders
54 clock = 1_000_000 + STALE_MS;
55 expect(keptPage(key(0))).toBeUndefined();
56 expect(keptPage(key(0))).toBeUndefined(); // gone, not stale: a plain miss for everyone
57 });
test/kept-raw-count.test.ts added +19
@@ -0,0 +1,19 @@
1 /** #9622: a crawl's raw twins stay kept; `/raw` is bounded by bytes, not a count of 512. */
2 import { beforeEach, expect, test } from "bun:test";
3 import type { BlobForRender } from "../src/git/read.ts";
4 import { cachedRaw, clearTreeCache, keepRaw } from "../src/web/pages/tree_cache.ts";
5
6 beforeEach(clearTreeCache);
7
8 const commit = "c".repeat(40);
9 const blob = (i: number): BlobForRender => {
10 const body = new TextEncoder().encode(`line ${i}\n`);
11 return { kind: "text", body, size: body.length, oid: String(i).padStart(40, "0") };
12 };
13
14 test("1,500 small files at a commit are all still kept after the crawl reads them", () => {
15 for (let i = 0; i < 1500; i++) keepRaw("repo1", commit, `src/f${i}.ts`, blob(i));
16 let kept = 0;
17 for (let i = 0; i < 1500; i++) if (cachedRaw("repo1", commit, `src/f${i}.ts`) !== undefined) kept++;
18 expect(kept).toBe(1500);
19 });
test/production-shape.test.ts added +99
@@ -0,0 +1,99 @@
1 import { expect, test } from "bun:test";
2 import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { FILES_PER_FOLDER, layout, MAX_FILE_BYTES, parseShape, shapeCounts } from "../src/perf/production_shape.ts";
6 import { fileText } from "../bench/seed.ts";
7
8 const shape = (repos: unknown) => ({ source: "https://forge.example", takenAt: "2026-11-13T00:00:00Z", repos });
9
10 test("a shape is checked at the boundary: names, counts, no repository twice (#9622)", () => {
11 expect(() => parseShape(null)).toThrow("not an object");
12 expect(() => parseShape(shape([]))).toThrow("non-empty");
13 expect(() => parseShape(shape([{ name: "../etc", files: 1, bytes: 1 }]))).toThrow("bad name");
14 expect(() => parseShape(shape([{ name: "a/b", files: -1, bytes: 1 }]))).toThrow("files");
15 expect(() => parseShape(shape([{ name: "a/b", files: 1.5, bytes: 1 }]))).toThrow("files");
16 expect(() => parseShape(shape([{ name: "a/b", files: 1, bytes: 1 }, { name: "a/b", files: 2, bytes: 2 }]))).toThrow("twice");
17 expect(() => parseShape({ ...shape([{ name: "a/b", files: 1, bytes: 1 }]), takenAt: "yesterday" })).toThrow("takenAt");
18 expect(parseShape(shape([{ name: "a/b", files: 1, bytes: 1, extra: "dropped" }])).repos).toEqual([{ name: "a/b", files: 1, bytes: 1 }]);
19 });
20
21 test("the counts a result carries add up by hand (#9622)", () => {
22 const s = parseShape(shape([
23 { name: "t/forge", files: 7000, bytes: 70_000_000 },
24 { name: "t/glue", files: 30, bytes: 60_000 },
25 { name: "x/empty", files: 0, bytes: 0 },
26 ]));
27 expect(shapeCounts(s)).toEqual({
28 source: "https://forge.example",
29 takenAt: "2026-11-13T00:00:00Z",
30 repositories: 3,
31 files: 7030,
32 bytes: 70_060_000,
33 largest: { name: "t/forge", files: 7000 },
34 });
35 });
36
37 test("a laid-out copy holds the same file count, each at the average size, in folders of twelve (#9622)", () => {
38 // 30 files, 60,000 bytes: 2,000 bytes each. Folder 0 (the root) holds f0..f11,
39 // folder 1 (d0) the next 12, folder 2 (d1) the last 6.
40 const files = layout({ name: "t/glue", files: 30, bytes: 60_000 });
41 expect(files).toHaveLength(30);
42 expect(new Set(files.map((f) => f.path)).size).toBe(30);
43 expect(files.every((f) => f.size === 2000)).toBe(true);
44 expect(files[0]!.path).toBe("f0.ts");
45 expect(files[11]!.path).toBe("f11.ts");
46 expect(files[12]!.path).toBe("d0/f0.ts");
47 expect(files[29]!.path).toBe("d1/f5.ts");
48 // Folder 13 is the first child of folder 1: d0/d0.
49 expect(layout({ name: "a/b", files: 13 * FILES_PER_FOLDER + 1, bytes: 1 }).at(-1)!.path).toBe("d0/d0/f0.ts");
50 // Average under a byte is one byte; a repository of media is capped so it stays seedable.
51 expect(layout({ name: "a/b", files: 3, bytes: 0 })[0]!.size).toBe(1);
52 expect(layout({ name: "a/b", files: 1, bytes: 10 * MAX_FILE_BYTES })[0]!.size).toBe(MAX_FILE_BYTES);
53 expect(layout({ name: "a/b", files: 0, bytes: 0 })).toEqual([]);
54 // 7,000 files never reuse a path.
55 expect(new Set(layout({ name: "a/b", files: 7000, bytes: 7000 }).map((f) => f.path)).size).toBe(7000);
56 });
57
58 test("a seeded file is exactly the bytes asked (#9622)", () => {
59 expect(fileText("d0/f1.ts", 0)).toBe("");
60 expect(fileText("d0/f1.ts", 2000)).toHaveLength(2000);
61 expect(fileText("d0/f1.ts", 7)).toBe("// d0/f");
62 });
63
64 test("load.ts spreads over every --repo, and the result names the shape, the start and the machine (#9622)", async () => {
65 const oid = "b".repeat(40);
66 const asked = new Set<string>();
67 const server = Bun.serve({
68 port: 0,
69 fetch: (req) => {
70 const path = new URL(req.url).pathname;
71 if (path.includes("/blob/")) asked.add(path.split("/").slice(1, 3).join("/"));
72 const repo = path.split("/").slice(1, 3).join("/");
73 return new Response(`<a href="/${repo}/blob/${oid}/f.txt">f</a>`, { headers: { "content-type": "text/html" } });
74 },
75 });
76 const dir = await mkdtemp(join(tmpdir(), "forge-shape-"));
77 try {
78 const shapeFile = join(dir, "shape.json");
79 const out = join(dir, "result.json");
80 await writeFile(shapeFile, JSON.stringify(shape([{ name: "o/one", files: 4, bytes: 40 }, { name: "o/two", files: 1, bytes: 10 }])));
81 const p = Bun.spawn(
82 ["bun", "bench/load.ts", "--url", `http://127.0.0.1:${server.port}`, "--repo", "o/one,o/two", "--rate", "60", "--seconds", "1", "--shape", shapeFile, "--out", out],
83 { stdout: "pipe", stderr: "pipe" },
84 );
85 expect(await p.exited).toBe(0);
86 const result = JSON.parse(await readFile(out, "utf8"));
87 expect([...asked].sort()).toEqual(["o/one", "o/two"]);
88 expect(result.repositories).toBe(2);
89 // Two blob links and their raw twins.
90 expect(result.links).toBe(4);
91 expect(result.start).toBe("cold");
92 expect(result.shape).toMatchObject({ repositories: 2, files: 5, bytes: 50, largest: { name: "o/one", files: 4 } });
93 expect(result.machine.threads).toBeGreaterThan(0);
94 expect(result.machine.runtime).toStartWith("bun ");
95 } finally {
96 server.stop(true);
97 await rm(dir, { recursive: true, force: true });
98 }
99 });
test/spread-expiry.test.ts added +50
@@ -0,0 +1,50 @@
1 import { describe, expect, test } from "bun:test";
2 import { readFileSync } from "node:fs";
3 import { join } from "node:path";
4 import { SPREAD, spreadExpiry } from "../src/web/pages/spread_expiry.ts";
5 import { ViewCache } from "../src/view/cache.ts";
6
7 describe("spreadExpiry (#9622)", () => {
8 test("a life is never longer than asked and never under half of it", () => {
9 expect(spreadExpiry(60_000, () => 0)).toBe(60_000);
10 // 60 000 × (1 − 0.5 × 0.9999999) = 30 000.003, floored to whole ms.
11 expect(spreadExpiry(60_000, () => 0.9999999)).toBe(30_000);
12 expect(spreadExpiry(60_000, () => 0.5)).toBe(45_000);
13 for (let i = 0; i < 1000; i++) {
14 const life = spreadExpiry(60_000);
15 expect(life).toBeGreaterThanOrEqual(60_000 * (1 - SPREAD));
16 expect(life).toBeLessThanOrEqual(60_000);
17 }
18 });
19
20 test("a random outside [0, 1) is clamped, and a tiny life stays positive", () => {
21 expect(spreadExpiry(60_000, () => -1)).toBe(60_000);
22 expect(spreadExpiry(60_000, () => 7)).toBe(30_000);
23 expect(spreadExpiry(1, () => 0.9)).toBe(1);
24 });
25
26 test("a set filled in one instant goes cold over half a minute, not at once", () => {
27 let now = 0;
28 const cache = new ViewCache({ maxEntries: 10_000, now: () => now });
29 let i = 0;
30 const evenly = () => (i++ % 1000) / 1000;
31 for (let k = 0; k < 1000; k++) cache.set(`page ${k}`, k, spreadExpiry(60_000, evenly));
32 const alive = () => Array.from({ length: 1000 }, (_, k) => cache.get(`page ${k}`)).filter((v) => v !== undefined).length;
33 now = 29_999;
34 expect(alive()).toBe(1000);
35 now = 45_000;
36 // Entry j lives 60 000 − 30 × j ms (j = 0..999);
37 // expired once that is ≤ 45 000, i.e. j ≥ 500: half gone.
38 expect(alive()).toBe(500);
39 now = 60_000;
40 expect(alive()).toBe(0);
41 });
42
43 test("every one-minute and folder life the code-page caches keep is spread", () => {
44 for (const file of ["src/web/pages/tree_cache.ts", "src/web/pages/kept_page.ts"]) {
45 const src = readFileSync(join(import.meta.dir, "..", file), "utf8");
46 expect(src).not.toMatch(/\.set\([^;]*,\s*(FOLDER_)?TTL_MS,/);
47 expect(src).toMatch(/spreadExpiry\(TTL_MS\)/);
48 }
49 });
50 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs