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

Take a CPU and heap profile on the stage rig at about 420 cells and name the 1-4 s pause #16122

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16113-take-a-cpu-and-heap-profile-on-the-stage → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/16113-take-a-cpu-and-heap-profile-on-the-stage was merged into main as a5f4072.

Review

Sign in to review this change.
5 files changed +156 −31
docs/features/performance-watcher.md +15
@@ -21,3 +21,18 @@ process with `FORGE_PROFILE=1` — meant for the stage rig, not production. Once
2121 a sample has run the profiler stays attached until the process restarts, and
2222 its traces are drained and discarded every two seconds by the `profiler-drain`
2323 job; a window being sampled keeps its traces until it ends.
24
25 ## The 1-4 s pauses labelled `jobs egress-idle` (#16113)
26
27 Measured with `scripts/pause-rig.ts` (a measurement rig, not run by CI or `bun test`; 420 egress servers with four connections each, a retained heap, a 10 ms loop-lag probe; run under `bun --cpu-prof`). The pause is neither a collection nor the sweep's loop: it is `heapSize()` (bun:jsc), called twice inside every `during()` by the allocation tally (`src/perf/job_alloc.ts`). On Bun 1.4.4 it is not constant time; it costs about 17 ms per GiB of heap, per call:
28
29 | retained heap | `heapSize()` | one `during()` |
30 | --- | --- | --- |
31 | 250 MiB | 2 ms | 4 ms |
32 | 1 GiB | 13 ms | 24 ms |
33 | 4 GiB | 60 ms | 123 ms |
34 | 7.6 GiB | 132 ms | 263 ms |
35
36 In the CPU profile of 420 cells on a 1 GiB heap, `heapSize` held the thread for 47.9 s of 57 s; the sweep's own loop (`egress.ts` line 1006) took 67 ms, `during` 19 ms. A full collection of the same heap took 1.1 to 1.6 s and, being inferred from a heap that fell, was the "no collection seen" the stall line reported as absent. So the sweep's loop is a few lines, as suspected, and what it paid was the tally's size read, per timer, per slice: any job on a big heap, 420 sweeps worst. Each slice that ran across a stall was named, so `egress-idle` took the label. Not reproduced: production's own 8 GiB shape; the rig's heap is millions of small objects, so absolute milliseconds will differ, the growth with heap size will not.
37
38 Fixed by bounding the cost, not removing the count: the tally spends at most 0.5% of wall time (and a first 50 ms) reading the heap's size and runs the remaining slices uncounted. The `memory allocated by jobs` line is therefore a sample on a big heap, and says so: the tally counts the slices it did not read and the line ends `(sampled: N slices not counted)`, left off when N is 0. With the change the rig's 420 cells at 1 GiB showed only collector-sized pauses (0.3 to 0.6 s), none of the 20 s ones. Test: `test/job-alloc.test.ts`. The per-memory-minute `heapSize()` calls in `memory_watch.ts` are once a minute and stay.
scripts/pause-rig.ts added +44
@@ -0,0 +1,44 @@
1 // The stage rig for #16113: 420 egress servers (production's cell count) in one process, a loop-lag
2 // probe, and an optional retained heap, so a 1-4 s main-thread pause can be named as GC, a sweep or
3 // a loop.
4 // bun --cpu-prof --cpu-prof-dir=$TMPDIR/prof scripts/pause-rig.ts [cells=420] [conns=4]
5 // [heapMiB=0] [seconds=20]
6 // Prints each pause over 100 ms with the heap before/after and what ran (the egress sweep is timed
7 // on its own).
8 import { startEgress } from "../src/apps/egress.ts";
9 import { heapStats } from "bun:jsc";
10
11 const [cells = 420, conns = 4, heapMiB = 0, seconds = 20] = process.argv.slice(2).map(Number);
12 const policy = { hosts: [], origins: [] };
13 const servers = Array.from({ length: cells }, (_, i) => startEgress({ tcp: 0 }, { ...policy, label: `app:rig${i}/prod`, idleMs: 300_000 }));
14 const sockets: unknown[] = [];
15 for (const s of servers)
16 for (let c = 0; c < conns; c++)
17 sockets.push(await Bun.connect({ hostname: "127.0.0.1", port: s.port!, socket: { data() {}, open() {}, close() {}, error() {} } }));
18
19 // Retained heap shaped like production's: many small objects and strings, not one big buffer.
20 const keep: unknown[] = [];
21 for (let n = 0; n < heapMiB * 1024 * 1024; n += 200) keep.push({ id: n, name: `row-${n}`, tags: [n, n + 1], at: new Date(n) });
22 Bun.gc(true);
23 console.log(`cells ${cells}, sockets ${sockets.length}, retained ~${heapMiB} MiB, heap ${(process.memoryUsage().heapUsed / 1048576) | 0} MiB`);
24
25 let last = performance.now();
26 const pauses: { ms: number; heapBefore: number; heapAfter: number }[] = [];
27 let heapPrev = process.memoryUsage().heapUsed;
28 const probe = setInterval(() => {
29 const now = performance.now(), late = now - last - 10;
30 const heap = process.memoryUsage().heapUsed;
31 if (late > 100) pauses.push({ ms: Math.round(late), heapBefore: Math.round(heapPrev / 1048576), heapAfter: Math.round(heap / 1048576) });
32 heapPrev = heap; last = now;
33 }, 10);
34
35 // Churn: garbage like a busy forge makes, so the collector has work between probes.
36 const churn = setInterval(() => { let x: unknown[] = []; for (let i = 0; i < 20000; i++) x.push({ i, s: "v" + i }); }, 20);
37
38 setTimeout(() => {
39 clearInterval(probe); clearInterval(churn);
40 console.log(`pauses over 100 ms in ${seconds} s: ${pauses.length}`, pauses.slice(0, 20));
41 const t0 = performance.now(); Bun.gc(true); console.log(`full gc: ${Math.round(performance.now() - t0)} ms`);
42 console.log(`objects ${heapStats().objectCount}, keep ${keep.length}`);
43 process.exit(0);
44 }, seconds * 1000);
src/perf/job_alloc.ts +50 −16
@@ -1,37 +1,67 @@
11 /**
22 * What each background job allocated (#13924): `during` (`jobs.ts`) reads the JS heap's size
3 * (`heapSize()`, constant time) on either side of a job's synchronous slice and adds any growth
4 * to the job's name. A collection inside a slice shows as no growth, so this is a floor, and
5 * what a job allocates after an await is not seen; but a timer that allocates on every tick shows
6 * here by name, which is what a heap that climbs with no request running needs. A `during` nested
7 * in another counts the same growth under both names, so the totals are not additive. The minute
8 * memory line reads and empties it (`allocationLine`). One entry per job name, at most
9 * `MAX_NAMES`; gone on restart.
3 * (`heapSize()`) on either side of a job's synchronous slice and adds any growth
4 * to the job's name. A collection inside a slice shows as no growth, and what a job allocates
5 * after an await is not seen, so the totals undercount; a slice past the read budget (below) is
6 * not counted at all, and `skipped` says how many, so this is a floor only when it is 0. But a
7 * timer that allocates on every tick shows here by name, which is what a heap that climbs with no
8 * request running needs. A `during` nested in another counts the same growth under both names, so
9 * the totals are not additive. The minute memory line reads and empties it (`allocationLine`). One
10 * entry per job name, at most `MAX_NAMES`; gone on restart.
11 *
12 * `heapSize()` is not constant time on Bun 1.4.4: it grows with the heap (about 17 ms per GiB, so
13 * 130 ms at 8 GiB, measured by `scripts/pause-rig.ts`, #16113), and two calls ran inside every
14 * job slice, 420 egress sweeps among them. The tally therefore spends at most `SHARE` of the
15 * time on reading the size, and a slice past that budget runs uncounted and is tallied in
16 * `skipped`, which `allocationLine` prints.
1017 */
1118
1219 import { heapSize } from "bun:jsc";
1320
1421 const MAX_NAMES = 128;
22 /** The share of wall time the tally may spend reading the heap's size. */
23 export const SHARE = 0.005;
24 /** Milliseconds of reading always allowed, so a quiet process counts its first slices. */
25 const ALLOWANCE_MS = 50;
1526
1627 export interface Tally {
1728 /** Run `fn`, counting the heap it grew by against `name`. */
1829 counted<T>(name: string, fn: () => T): T;
1930 /** The jobs that grew the heap since the last call, most first, and forget them. */
20 take(top?: number): Allocation[];
31 take(top?: number): Taken;
2132 }
2233
34 /** What `take` hands over: the top jobs, and the slices that ran uncounted over the budget. */
35 export type Taken = { jobs: Allocation[]; skipped: number };
36
2337 export type Allocation = { name: string; bytes: number; runs: number };
2438
2539 /** One tally per job watch, so a forge's jobs are counted on that forge and not on the process. */
26 export function createTally(size: () => number = heapSize): Tally {
40 export function createTally(
41 size: () => number = heapSize,
42 now: () => number = () => performance.now(),
43 ): Tally {
2744 const seen = new Map<string, { bytes: number; runs: number }>();
45 const born = now();
46 let spent = 0;
47 let skipped = 0;
48 const read = (): number => {
outdated

A slice skipped here leaves no trace, so the allocation line cannot tell a quiet job from an uncounted one. Increment a skipped counter here and report it through take/allocationLine.

49 const t = now();
50 const bytes = size();
51 spent += now() - t;
52 return bytes;
53 };
2854 return {
2955 counted(name, fn) {
30 const before = size();
56 if (spent > ALLOWANCE_MS + SHARE * (now() - born)) {
57 skipped++;
58 return fn();
59 }
60 const before = read();
3161 try {
3262 return fn();
3363 } finally {
34 const grew = size() - before;
64 const grew = read() - before;
3565 const at = seen.get(name);
3666 if (grew > 0 && (at !== undefined || seen.size < MAX_NAMES)) {
3767 if (at === undefined) seen.set(name, { bytes: grew, runs: 1 });
@@ -43,11 +73,13 @@ export function createTally(size: () => number = heapSize): Tally {
4373 }
4474 },
4575 take(top = 5) {
46 const out = [...seen]
76 const jobs = [...seen]
4777 .map(([name, n]) => ({ name, ...n }))
4878 .sort((a, b) => b.bytes - a.bytes)
4979 .slice(0, top);
5080 seen.clear();
81 const out = { jobs, skipped };
82 skipped = 0;
5183 return out;
5284 },
5385 };
@@ -55,10 +87,12 @@ export function createTally(size: () => number = heapSize): Tally {
5587
5688 /**
5789 * `memory allocated by jobs: timers 84.0 MiB in 60 slices, maintain 2.1 MiB in 1 slices`; undefined
58 * when nothing grew by 1 MiB.
90 * when nothing grew by 1 MiB. Slices over the read budget end it with `(sampled: 7 slices not
91 * counted)`, and it is left off when none were.
5992 */
60 export function allocationLine(taken: readonly Allocation[]): string | undefined {
61 const big = taken.filter((t) => t.bytes >= 1_048_576);
93 export function allocationLine(taken: Taken): string | undefined {
94 const big = taken.jobs.filter((t) => t.bytes >= 1_048_576);
6295 if (big.length === 0) return undefined;
63 return `memory allocated by jobs: ${big.map((t) => `${t.name} ${(t.bytes / 1_048_576).toFixed(1)} MiB in ${t.runs} slices`).join(", ")}`;
96 const sampled = taken.skipped > 0 ? ` (sampled: ${taken.skipped} slices not counted)` : "";
97 return `memory allocated by jobs: ${big.map((t) => `${t.name} ${(t.bytes / 1_048_576).toFixed(1)} MiB in ${t.runs} slices`).join(", ")}${sampled}`;
6498 }
src/perf/jobs.ts +9 −5
@@ -13,7 +13,7 @@
1313 */
1414
1515 import { hostOf, noteChildJob } from "./child_time.ts";
16 import { createTally, type Allocation } from "./job_alloc.ts";
16 import { createTally, type Allocation, type Taken } from "./job_alloc.ts";
1717
1818 /** Finished slices kept to match a stall against: a tick a second fills it in about two minutes. */
1919 const KEPT = 256;
@@ -50,7 +50,7 @@ export interface JobWatch {
5050 /**
5151 * What the jobs allocated since the last call, most first; emptied by reading (`job_alloc.ts`).
5252 */
53 allocated(): Allocation[];
53 allocated(): Taken;
5454 }
5555
5656 export function createJobWatch(now: () => number = () => performance.now()): JobWatch {
@@ -187,9 +187,10 @@ export const during = <T>(name: string, fn: () => T, owner?: string, app?: objec
187187 };
188188
189189 /** What the jobs of the thread and of this forge allocated since the last call, most first. */
190 export function allocationsOf(app: object): Allocation[] {
190 export function allocationsOf(app: object): Taken {
191191 const merged = new Map<string, Allocation>();
192 for (const a of [...unowned.allocated(), ...jobWatchOf(app).allocated()]) {
192 const own = [unowned.allocated(), jobWatchOf(app).allocated()];
193 for (const a of own.flatMap((t) => t.jobs)) {
193194 const at = merged.get(a.name);
194195 if (at === undefined) merged.set(a.name, { ...a });
195196 else {
@@ -197,5 +198,8 @@ export function allocationsOf(app: object): Allocation[] {
197198 at.runs += a.runs;
198199 }
199200 }
200 return [...merged.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
201 return {
202 jobs: [...merged.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5),
203 skipped: own.reduce((n, t) => n + t.skipped, 0),
204 };
201205 }
test/job-alloc.test.ts +38 −10
@@ -9,7 +9,8 @@ import { allocationLine, createTally } from "../src/perf/job_alloc.ts";
99 import { allocationsOf, during } from "../src/perf/jobs.ts";
1010
1111 const MIB = 1024 * 1024;
12 const { counted, take: takeAllocations } = createTally();
12 /** A stopped clock, so the real heap's read time never spends the tally's budget here. */
13 const { counted, take: takeAllocations } = createTally(undefined, () => 0);
1314 const keep: unknown[] = [];
1415 /** Grow the JS heap (typed arrays live off it) and keep it, so no collection undoes it. */
1516 const grow = (n = 100_000): number => keep.push(Array.from({ length: n }, (_, i) => ({ i, s: `v${i}` })));
@@ -32,15 +33,17 @@ test("a job that keeps what it allocates is named with its size, and the count i
3233 for (let i = 0; i < 3; i++) grown(counted, "hungry");
3334 counted("quiet", () => 1);
3435 const taken = takeAllocations();
35 expect(taken[0]?.name).toBe("hungry");
36 expect(taken[0]!.bytes).toBeGreaterThan(0);
37 expect(taken[0]!.runs).toBeGreaterThanOrEqual(3);
36 expect(taken.skipped).toBe(0);
37 expect(allocationLine(taken)).not.toContain("sampled");
38 expect(taken.jobs[0]?.name).toBe("hungry");
39 expect(taken.jobs[0]!.bytes).toBeGreaterThan(0);
40 expect(taken.jobs[0]!.runs).toBeGreaterThanOrEqual(3);
3841 expect(allocationLine(taken)).toMatch(/^memory allocated by jobs: hungry \d+\.\d MiB in \d+ slices/);
39 expect(takeAllocations()).toEqual([]);
42 expect(takeAllocations().jobs).toEqual([]);
4043 });
4144
4245 test("a job that grew nothing leaves no line", () => {
43 expect(allocationLine([{ name: "small", bytes: 1000, runs: 1 }])).toBeUndefined();
46 expect(allocationLine({ jobs: [{ name: "small", bytes: 1000, runs: 1 }], skipped: 0 })).toBeUndefined();
4447 });
4548
4649 /** A heap that reads `step` bytes higher each time, so every slice grew by exactly `step`. */
@@ -52,7 +55,7 @@ function steppedHeap(step: number): () => number {
5255 test("a throw is still counted and rethrown", () => {
5356 const tally = createTally(steppedHeap(2 * MIB));
5457 expect(() => tally.counted("boom", () => { throw new Error("x"); })).toThrow("x");
55 expect(tally.take()).toEqual([{ name: "boom", bytes: 2 * MIB, runs: 1 }]);
58 expect(tally.take().jobs).toEqual([{ name: "boom", bytes: 2 * MIB, runs: 1 }]);
5659 });
5760
5861 test("at most 128 names are kept, and a name already kept still counts", () => {
@@ -60,12 +63,37 @@ test("at most 128 names are kept, and a name already kept still counts", () => {
6063 for (let i = 0; i < 130; i++) tally.counted(`job-${i}`, () => 1);
6164 tally.counted("job-0", () => 1);
6265 tally.counted("job-129", () => 1);
63 const taken = tally.take(1000);
66 const taken = tally.take(1000).jobs;
6467 expect(taken.length).toBe(128);
6568 expect(taken.find((t) => t.name === "job-129")).toBeUndefined();
6669 expect(taken.find((t) => t.name === "job-0")?.runs).toBe(2);
6770 });
6871
72 test("a heap that is slow to read is read for a small share of the time, and the rest run uncounted (#16113)", () => {
73 let clock = 0;
74 let reads = 0;
75 const slow = () => { reads++; clock += 100; return reads * MIB; }; // 100 ms a read, like 6 GiB
76 const tally = createTally(slow, () => clock);
77 let ran = 0;
78 for (let i = 0; i < 1000; i++) { tally.counted("sweep", () => ran++); clock += 5; }
79 expect(ran).toBe(1000); // every slice still runs
80 expect(reads).toBeLessThan(200); // 2000 reads would have been 200 s of 5 s
81 expect(reads * 100).toBeLessThan(50 + 0.005 * clock + 200);
82 // Each counted slice reads twice; every other slice ran uncounted, and the tally says so.
83 expect(tally.take().skipped).toBe(1000 - reads / 2);
84 });
85
86 test("a tally over its budget says on the line how many slices it did not count", () => {
87 let clock = 0;
88 const slow = () => { clock += 100; return clock * MIB; };
89 const tally = createTally(slow, () => clock);
90 for (let i = 0; i < 50; i++) { tally.counted("sweep", () => 1); clock += 5; }
91 const taken = tally.take();
92 expect(taken.skipped).toBeGreaterThan(0);
93 expect(allocationLine(taken)).toEndWith(`(sampled: ${taken.skipped} slices not counted)`);
94 expect(tally.take().skipped).toBe(0); // read and emptied
95 });
96
6997 let dataDir: string;
7098 let app: App;
7199 beforeAll(async () => {
@@ -87,12 +115,12 @@ test("allocationsOf merges the unowned and this forge's jobs, most first, five a
87115 for (let i = 0; i < 5; i++) duringGrown(`own-${i}`, MIB, app);
88116 for (let i = 0; i < 2; i++) duringGrown("shared", 16 * MIB);
89117 for (let i = 0; i < 2; i++) duringGrown("shared", 16 * MIB, app);
90 const got = allocationsOf(app);
118 const got = allocationsOf(app).jobs;
91119 expect(got.length).toBe(5);
92120 expect(got[0]!.name).toBe("shared");
93121 expect(got[0]!.runs).toBeGreaterThanOrEqual(2);
94122 expect(got.map((g) => g.bytes)).toEqual([...got.map((g) => g.bytes)].sort((a, b) => b - a));
95 expect(allocationsOf(app)).toEqual([]);
123 expect(allocationsOf(app)).toEqual({ jobs: [], skipped: 0 });
96124 });
97125
98126 test("the memory sampler logs what the jobs allocated, by name", () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs