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
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/16113-take-a-cpu-and-heap-profile-on-the-stage → main 0 commits fork 1 thread · 1 unresolved
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 | ||
| 21 | 21 | a sample has run the profiler stays attached until the process restarts, and |
| 22 | 22 | its traces are drained and discarded every two seconds by the `profiler-drain` |
| 23 | 23 | 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 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * 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. | |
| 10 | 17 | */ |
| 11 | 18 | |
| 12 | 19 | import { heapSize } from "bun:jsc"; |
| 13 | 20 | |
| 14 | 21 | 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; | |
| 15 | 26 | |
| 16 | 27 | export interface Tally { |
| 17 | 28 | /** Run `fn`, counting the heap it grew by against `name`. */ |
| 18 | 29 | counted<T>(name: string, fn: () => T): T; |
| 19 | 30 | /** 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; | |
| 21 | 32 | } |
| 22 | 33 | |
| 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 | ||
| 23 | 37 | export type Allocation = { name: string; bytes: number; runs: number }; |
| 24 | 38 | |
| 25 | 39 | /** 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 { | |
| 27 | 44 | 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 => { | |
| 49 | const t = now(); | |
| 50 | const bytes = size(); | |
| 51 | spent += now() - t; | |
| 52 | return bytes; | |
| 53 | }; | |
| 28 | 54 | return { |
| 29 | 55 | 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(); | |
| 31 | 61 | try { |
| 32 | 62 | return fn(); |
| 33 | 63 | } finally { |
| 34 | const grew = size() - before; | |
| 64 | const grew = read() - before; | |
| 35 | 65 | const at = seen.get(name); |
| 36 | 66 | if (grew > 0 && (at !== undefined || seen.size < MAX_NAMES)) { |
| 37 | 67 | if (at === undefined) seen.set(name, { bytes: grew, runs: 1 }); |
| @@ -43,11 +73,13 @@ export function createTally(size: () => number = heapSize): Tally { | ||
| 43 | 73 | } |
| 44 | 74 | }, |
| 45 | 75 | take(top = 5) { |
| 46 | const out = [...seen] | |
| 76 | const jobs = [...seen] | |
| 47 | 77 | .map(([name, n]) => ({ name, ...n })) |
| 48 | 78 | .sort((a, b) => b.bytes - a.bytes) |
| 49 | 79 | .slice(0, top); |
| 50 | 80 | seen.clear(); |
| 81 | const out = { jobs, skipped }; | |
| 82 | skipped = 0; | |
| 51 | 83 | return out; |
| 52 | 84 | }, |
| 53 | 85 | }; |
| @@ -55,10 +87,12 @@ export function createTally(size: () => number = heapSize): Tally { | ||
| 55 | 87 | |
| 56 | 88 | /** |
| 57 | 89 | * `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. | |
| 59 | 92 | */ |
| 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); | |
| 62 | 95 | 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}`; | |
| 64 | 98 | } |
src/perf/jobs.ts +9 −5
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | */ |
| 14 | 14 | |
| 15 | 15 | 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"; | |
| 17 | 17 | |
| 18 | 18 | /** Finished slices kept to match a stall against: a tick a second fills it in about two minutes. */ |
| 19 | 19 | const KEPT = 256; |
| @@ -50,7 +50,7 @@ export interface JobWatch { | ||
| 50 | 50 | /** |
| 51 | 51 | * What the jobs allocated since the last call, most first; emptied by reading (`job_alloc.ts`). |
| 52 | 52 | */ |
| 53 | allocated(): Allocation[]; | |
| 53 | allocated(): Taken; | |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | 56 | export function createJobWatch(now: () => number = () => performance.now()): JobWatch { |
| @@ -187,9 +187,10 @@ export const during = <T>(name: string, fn: () => T, owner?: string, app?: objec | ||
| 187 | 187 | }; |
| 188 | 188 | |
| 189 | 189 | /** 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 { | |
| 191 | 191 | 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)) { | |
| 193 | 194 | const at = merged.get(a.name); |
| 194 | 195 | if (at === undefined) merged.set(a.name, { ...a }); |
| 195 | 196 | else { |
| @@ -197,5 +198,8 @@ export function allocationsOf(app: object): Allocation[] { | ||
| 197 | 198 | at.runs += a.runs; |
| 198 | 199 | } |
| 199 | 200 | } |
| 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 | }; | |
| 201 | 205 | } |
test/job-alloc.test.ts +38 −10
| @@ -9,7 +9,8 @@ import { allocationLine, createTally } from "../src/perf/job_alloc.ts"; | ||
| 9 | 9 | import { allocationsOf, during } from "../src/perf/jobs.ts"; |
| 10 | 10 | |
| 11 | 11 | 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); | |
| 13 | 14 | const keep: unknown[] = []; |
| 14 | 15 | /** Grow the JS heap (typed arrays live off it) and keep it, so no collection undoes it. */ |
| 15 | 16 | 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 | ||
| 32 | 33 | for (let i = 0; i < 3; i++) grown(counted, "hungry"); |
| 33 | 34 | counted("quiet", () => 1); |
| 34 | 35 | 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); | |
| 38 | 41 | expect(allocationLine(taken)).toMatch(/^memory allocated by jobs: hungry \d+\.\d MiB in \d+ slices/); |
| 39 | expect(takeAllocations()).toEqual([]); | |
| 42 | expect(takeAllocations().jobs).toEqual([]); | |
| 40 | 43 | }); |
| 41 | 44 | |
| 42 | 45 | 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(); | |
| 44 | 47 | }); |
| 45 | 48 | |
| 46 | 49 | /** 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 { | ||
| 52 | 55 | test("a throw is still counted and rethrown", () => { |
| 53 | 56 | const tally = createTally(steppedHeap(2 * MIB)); |
| 54 | 57 | 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 }]); | |
| 56 | 59 | }); |
| 57 | 60 | |
| 58 | 61 | 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", () => { | ||
| 60 | 63 | for (let i = 0; i < 130; i++) tally.counted(`job-${i}`, () => 1); |
| 61 | 64 | tally.counted("job-0", () => 1); |
| 62 | 65 | tally.counted("job-129", () => 1); |
| 63 | const taken = tally.take(1000); | |
| 66 | const taken = tally.take(1000).jobs; | |
| 64 | 67 | expect(taken.length).toBe(128); |
| 65 | 68 | expect(taken.find((t) => t.name === "job-129")).toBeUndefined(); |
| 66 | 69 | expect(taken.find((t) => t.name === "job-0")?.runs).toBe(2); |
| 67 | 70 | }); |
| 68 | 71 | |
| 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 | ||
| 69 | 97 | let dataDir: string; |
| 70 | 98 | let app: App; |
| 71 | 99 | beforeAll(async () => { |
| @@ -87,12 +115,12 @@ test("allocationsOf merges the unowned and this forge's jobs, most first, five a | ||
| 87 | 115 | for (let i = 0; i < 5; i++) duringGrown(`own-${i}`, MIB, app); |
| 88 | 116 | for (let i = 0; i < 2; i++) duringGrown("shared", 16 * MIB); |
| 89 | 117 | for (let i = 0; i < 2; i++) duringGrown("shared", 16 * MIB, app); |
| 90 | const got = allocationsOf(app); | |
| 118 | const got = allocationsOf(app).jobs; | |
| 91 | 119 | expect(got.length).toBe(5); |
| 92 | 120 | expect(got[0]!.name).toBe("shared"); |
| 93 | 121 | expect(got[0]!.runs).toBeGreaterThanOrEqual(2); |
| 94 | 122 | 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 }); | |
| 96 | 124 | }); |
| 97 | 125 | |
| 98 | 126 | test("the memory sampler logs what the jobs allocated, by name", () => { |
new above
offline
A slice skipped here leaves no trace, so the allocation line cannot tell a quiet job from an uncounted one. Increment a
skippedcounter here and report it throughtake/allocationLine.