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

Sentinel: memory-growth was degraded 31 minutes today: The forge's own memory is 5754 MiB, over twice its first-hour 2064 MiB and past the 2176 MiB more its database caches m… #17108

opened this

Merged 2d 2h ago, live in production

mason/forge:mason/17083-sentinel-memory-growth-was-degraded-31-m → main 0 commits fork

  • Merged. mason/17083-sentinel-memory-growth-was-degraded-31-m was merged into main as e5218fb.

Review

Sign in to review this change.
6 files changed +173 −6
docs/features/memory-growth.md +2
@@ -27,6 +27,8 @@ Since Bun 1.4.4 the serving process has held several GiB after hours. This chang
2727
2828 The sentinel's memory-growth issue quotes the watch's evidence: each VM's heap, the memory outside every heap and the held counts at the first hour, at the trip and now. The trip is kept after RSS falls back (#16801), so a short spike filed an hour later still shows what it saw, and it adds `memory allocated by jobs from the run's start to the trip`: the background jobs that grew main's heap from the first minute past 1.25x to the trip, most first (`perf/job_alloc.ts`). The line ends `(sampled: N slices not counted)` when the tally skipped slices over its read budget, as the minute line does. `none counted` there means the heap grew in a request or after an await, not in a job, and it is said only when no slice was skipped; with some skipped and none measured the line says `none measured … so a job is not ruled out`. The timestamp on the `memory rss` line is the trip's own time, not the filing's: a finding filed hours after a spike quotes that spike. A new run that trips replaces the last trip.
2929
30 **The jobs open at the trip (#17083).** Memory outside every heap that climbs for an hour and falls back (production on 2026-12-01: 1321 MiB to 4536 MiB from 12:26, back to 1442 MiB by 14:07, the main heap flat) is held by work that ended, and neither the heap tally nor the held counts see native bytes. So each minute the sampler also hands the watch the jobs begun under `during` and not yet settled (`runningOf` in `perf/jobs.ts`: the thread's and the forge's, by name, with how many are open and when the oldest began), and the trip keeps them. The finding then says `memory jobs open at the trip: begun since the growth began: snapshot since …; open before it: runner-wait ×3 since …` and `memory jobs open now: …`. "Since the growth began" counts from the last minute RSS was under 1.25x its first hour, so a job begun in the minute before the first sample over the line is named with the growth; a long poll open all day sits apart under `open before it`. A job open at the trip and gone from the `now` line, with RSS fallen back, is the one to read. Five are named; the rest are counted as `and N more`. Test: `test/sentinel-memory-evidence.test.ts`, `test/perf-jobs-per-forge.test.ts`.
31
3032 A restart between the growth and the filing (a release restarts the forge several times a day) leaves a watch that never saw it: the sentence is the stored one of the process that grew, and its own evidence would say `trip none`. So each minute the need is open, the sampler writes the watch's evidence to `memory-kept.json` under the data directory (`perf/memory_kept.ts`, #16872); a finding filed by a later process that has not tripped quotes those lines, kept that day, under `memory kept by the process started …, at its last grown minute …; the forge restarted since`, and ends with one `memory now (process started …)` line for the process reading it.
3133
3234 The need clears by itself once RSS falls under twice the baseline. A process that slept through its first hour has no baseline and raises none.
src/boards/memory.ts +6 −2
@@ -16,7 +16,7 @@
1616 import type { Database } from "bun:sqlite";
1717 import type { App } from "../app.ts";
1818 import { quietly } from "../core/write_clock.ts";
19 import { allocationsOf, during } from "../perf/jobs.ts";
19 import { allocationsOf, during, runningOf } from "../perf/jobs.ts";
2020 import { heldLine, heldNow } from "../perf/held.ts";
2121 import { allocationLine } from "../perf/job_alloc.ts";
2222 import { ceilingOf } from "../kernel/db_ceiling.ts";
@@ -87,7 +87,11 @@ export function startMemorySampler(app: App, everyMs = MEMORY_EVERY_MS, watch: M
8787 // Read once (it empties the tally): the line writes it, the watch sums it up to a trip
8888 // (#16801).
8989 const jobs = allocationsOf(app);
90 watch.note(reading.rss, reading.heap, now, { commit: reading.commit, held, ceiling: reading.dbCeiling, allocated: jobs.jobs, skipped: jobs.skipped });
90 // The jobs open now: a trip keeps them, so native memory held by work that ended names it
91 // (#17083).
92 watch.note(reading.rss, reading.heap, now, {
93 commit: reading.commit, held, ceiling: reading.dbCeiling, allocated: jobs.jobs, skipped: jobs.skipped, running: runningOf(app),
94 });
9195 // A grown minute's evidence outlives this process (#16872): a restart would leave the
9296 // sentinel quoting a fresh watch that never tripped.
9397 keepIfGrown(app.config.dataDir, watch, now);
src/perf/jobs.ts +42
@@ -51,8 +51,17 @@ export interface JobWatch {
5151 * What the jobs allocated since the last call, most first; emptied by reading (`job_alloc.ts`).
5252 */
5353 allocated(): Taken;
54 /**
55 * The jobs begun and not yet settled, by name: how many are open and when the oldest began
56 * (`performance.now`). Native memory a job holds until it ends shows as RSS that falls when it
57 * settles, and no heap tally sees it (#17083).
58 */
59 running(): Running[];
5460 }
5561
62 /** One job name open now: how many of it, and when the oldest began. */
63 export type Running = { name: string; open: number; since: number };
64
5665 export function createJobWatch(now: () => number = () => performance.now()): JobWatch {
5766 const tally = createTally();
5867 const awaiting = new Map<number, { name: string; start: number }>();
@@ -74,6 +83,18 @@ export function createJobWatch(now: () => number = () => performance.now()): Job
7483 ];
7584 return {
7685 allocated: () => tally.take(),
86 running() {
87 const by = new Map<string, Running>();
88 for (const r of awaiting.values()) {
89 const at = by.get(r.name);
90 if (at === undefined) by.set(r.name, { name: r.name, open: 1, since: r.start });
91 else {
92 at.open++;
93 at.since = Math.min(at.since, r.start);
94 }
95 }
96 return [...by.values()];
97 },
7798 during(name, fn) {
7899 const start = now();
79100 let result: ReturnType<typeof fn>;
@@ -203,3 +224,24 @@ export function allocationsOf(app: object): Taken {
203224 skipped: own.reduce((n, t) => n + t.skipped, 0),
204225 };
205226 }
227
228 /** The most job names `runningOf` hands over: a trip keeps them until the next one. */
229 const RUNNING_KEPT = 64;
230
231 /**
232 * The jobs of the thread and of this forge begun and not yet settled, `since` in epoch ms, the
233 * longest open first (#17083): the memory watch keeps them at a trip, so a native climb that ends
234 * with a job names the job.
235 */
236 export function runningOf(app: object, origin: number = performance.timeOrigin): Running[] {
237 const merged = new Map<string, Running>();
238 for (const r of [unowned, jobWatchOf(app)].flatMap((w) => w.running())) {
239 const at = merged.get(r.name);
240 if (at === undefined) merged.set(r.name, { ...r });
241 else merged.set(r.name, { name: r.name, open: at.open + r.open, since: Math.min(at.since, r.since) });
242 }
243 return [...merged.values()]
244 .map((r) => ({ ...r, since: Math.round(origin + r.since) }))
245 .sort((a, b) => a.since - b.since)
246 .slice(0, RUNNING_KEPT);
247 }
src/perf/memory_watch.ts +59 −2
@@ -26,6 +26,9 @@
2626 * (#16801): a twelve-minute spike has passed by the time the sentinel files it, and the trip is
2727 * the only reading that saw it. It also holds what the jobs grew main's heap by from the run's
2828 * start (the first minute past 1.25x) to the trip, by name. A new run that trips replaces it.
29 * And it holds the jobs open at the trip (#17083): memory outside every heap that climbs for an
30 * hour and falls back is held by work that ended, which no heap tally sees, and the job begun as
31 * the growth began is the one to read.
2932 *
3033 * `heapStats()` counts every object on the heap by type and held the loop ~280 ms a
3134 * minute on a 2M-object heap (#11118), so the minute line never calls it: `heapSize()`
@@ -45,6 +48,7 @@ import { heapSize, memoryUsage as jscMemory } from "bun:jsc";
4548 import { createLog } from "../kernel/log.ts";
4649 import { heldLine, threadHeld, type HeldCount } from "./held.ts";
4750 import type { Allocation } from "./job_alloc.ts";
51 import type { Running } from "./jobs.ts";
4852
4953 const MIB = 1048576;
5054 export const FIRST_HOUR_MS = 3_600_000;
@@ -223,6 +227,8 @@ export interface NoteExtra {
223227 readonly allocated?: readonly Allocation[];
224228 /** The slices `allocated` did not measure (`Taken.skipped`): summed and kept beside it. */
225229 readonly skipped?: number;
230 /** The jobs begun and not yet settled, `since` in epoch ms (`runningOf` in `perf/jobs.ts`). */
231 readonly running?: readonly Running[];
226232 }
227233
228234 /** The watch as it stood at the trip: the minute RSS first reached twice its first hour. */
@@ -238,6 +244,13 @@ interface Trip {
238244 readonly jobs: readonly Allocation[];
239245 /** The job slices not measured from the run's start to the trip: jobs are a floor unless 0. */
240246 readonly skipped: number;
247 /**
248 * The last minute RSS was under 1.25x before the run that tripped (or the run's first, when none
249 * was read): the growth began after it, so a job begun since began with the growth.
250 */
251 readonly runStart: number;
252 /** The jobs open at the trip, the longest open first (#17083). */
253 readonly running: readonly Running[];
241254 }
242255
243256 /** How many job names one run above 1.25x sums before the trip; a name past it is not kept. */
@@ -288,11 +301,14 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
288301 let base: number | undefined;
289302 let last: { heap: number; rss: number; at: number } | undefined;
290303 let above: number | undefined;
304 /** The last minute RSS was not above 1.25x its first hour (every first-hour minute is one). */
305 let below: number | undefined;
291306 let latest: number | undefined;
292307 let commitSum = 0;
293308 let commitCount = 0;
294309 let commitNow: number | undefined;
295310 let heldNow: readonly HeldCount[] = [];
311 let runningNow: readonly Running[] | undefined;
296312 let trip: Trip | undefined;
297313 /** What the jobs allocated since the current run above 1.25x began, by name. */
298314 const runJobs = new Map<string, Allocation>();
@@ -327,6 +343,7 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
327343 commitCount++;
328344 }
329345 if (extra.held !== undefined) heldNow = extra.held.slice();
346 runningNow = extra.running === undefined ? undefined : extra.running.filter(isRunning);
330347 // Every fresh worker's heap is its own VM's, inside the process's RSS: not outside.
331348 let others = 0;
332349 for (const w of workers.values()) if (now - w.at <= WORKER_STALE_MS) others += w.heap;
@@ -336,13 +353,17 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
336353 if (now - startedAt < FIRST_HOUR_MS) {
337354 sum += rss;
338355 count++;
356 below = now;
339357 return;
340358 }
341359 if (count < MIN_SAMPLES) return; // the process slept through its first hour: no figure
342360 base = sum / count;
343361 }
344362 if (rss > base * GROWING_RATIO) above ??= now;
345 else above = undefined;
363 else {
364 above = undefined;
365 below = now;
366 }
346367 // The last trip outlives its run (#16801): a short spike has fallen back by the time the
347368 // sentinel files it, and the trip is the only reading that saw it. A new run replaces it.
348369 if (above === undefined) {
@@ -359,7 +380,10 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
359380 const heaps = new Map<string, number>([["main", heap]]);
360381 for (const [name, w] of workers) if (now - w.at <= WORKER_STALE_MS) heaps.set(name, w.heap);
361382 const jobs = [...runJobs.values()].sort((a, b) => b.bytes - a.bytes).slice(0, EVIDENCE_JOBS);
362 trip = { at: now, rss, commit: commitNow, outside: main.latest.outside, heaps, held: heldNow, jobs, skipped: runSkipped };
383 trip = {
384 at: now, rss, commit: commitNow, outside: main.latest.outside, heaps, held: heldNow, jobs, skipped: runSkipped,
385 runStart: below ?? above, running: runningNow ?? [],
386 };
363387 }
364388 }
365389 },
@@ -395,6 +419,8 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
395419 if (fresh.length > EVIDENCE_WORKERS) out.push(`memory heap: ${fresh.length - EVIDENCE_WORKERS} more workers not listed`);
396420 out.push(`memory outside every heap (process): ${three(first(main, "outside"), trip?.outside, main.latest.outside)}`);
397421 if (trip !== undefined) out.push(`memory allocated by jobs from the run's start to the trip: ${jobsWords(trip.jobs, trip.skipped)}`);
422 if (trip !== undefined) out.push(`memory jobs open at the trip: ${openWords(trip.running, trip.runStart)}`);
423 if (runningNow !== undefined) out.push(`memory jobs open now: ${openWords(runningNow)}`);
398424 out.push(`memory mimalloc committed (process): ${three(commitCount > 0 ? commitSum / commitCount : undefined, trip?.commit, commitNow)}`);
399425 const then = new Map((trip?.held ?? []).map((c) => [c.name, c.size]));
400426 const named = heldNow.filter((c) => c.size !== 0).slice(0, EVIDENCE_HELD);
@@ -440,6 +466,37 @@ const jobsWords = (jobs: readonly Allocation[], skipped: number): string => {
440466 return skipped > 0 ? `none measured${sampled}, so a job is not ruled out` : "none counted (a request, or work after an await, is not a job)";
441467 };
442468
469 /** A running job as `note` takes it: a name, a positive count, an instant. */
470 const isRunning = (r: Running): boolean =>
471 typeof r.name === "string" && r.name !== "" && Number.isInteger(r.open) && r.open > 0 && Number.isFinite(r.since);
472
473 /** The open jobs one evidence line names; the rest are counted. */
474 export const EVIDENCE_OPEN = 5;
475
476 /**
477 * `snapshot since 2026-12-01T12:26:10Z, runner-wait ×3 since …`, the longest open first. With the
478 * run's start, the jobs begun since the growth began come first, apart from those open before it
479 * (#17083): native memory that climbed and fell back is held by work, and the job begun with the
480 * climb is its lead, while a long poll open all day is not.
481 */
482 const openWords = (open: readonly Running[], runStart?: number): string => {
483 if (open.length === 0) return "none";
484 const instant = (ms: number): string => `${new Date(ms).toISOString().slice(0, 19)}Z`;
485 const one = (r: Running): string => `${r.name}${r.open > 1 ? ` ×${r.open}` : ""} since ${instant(r.since)}`;
486 const oldest = [...open].sort((a, b) => a.since - b.since);
487 const began = runStart === undefined ? [] : oldest.filter((r) => r.since >= runStart);
488 const before = runStart === undefined ? oldest : oldest.filter((r) => r.since < runStart);
489 const named = [...began, ...before].slice(0, EVIDENCE_OPEN);
490 const words = (list: readonly Running[]): string => list.filter((r) => named.includes(r)).map(one).join(", ");
491 const more = open.length > named.length ? `, and ${open.length - named.length} more` : "";
492 if (runStart === undefined) return `${words(before)}${more}`;
493 const parts = [
494 ...(began.length > 0 ? [`begun since the growth began: ${words(began)}`] : ["none begun since the growth began"]),
495 ...(before.some((r) => named.includes(r)) ? [`open before it: ${words(before)}`] : []),
496 ];
497 return `${parts.join("; ")}${more}`;
498 };
499
443500 /** The needs-you sentence for a grown process: the figure, and whose part grew most (#12951). */
444501 export function grownSentence(g: Grown): string {
445502 const past = g.ceilingBytes === undefined ? "" : ` and past the ${mib(g.ceilingBytes)} more its database caches may fill`;
test/perf-jobs-per-forge.test.ts +18 −1
@@ -10,7 +10,7 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { startMemorySampler } from "../src/boards/memory.ts";
1212 import { childHours, hostChild, noteChildRequest } from "../src/perf/child_time.ts";
13 import { during, jobsOf, jobWatchOf } from "../src/perf/jobs.ts";
13 import { during, jobsOf, jobWatchOf, runningOf } from "../src/perf/jobs.ts";
1414
1515 let dirs: string[] = [];
1616 let one: App;
@@ -74,3 +74,20 @@ test("a forge's own timer, started with no owner, is read on that forge's watch
7474 expect(jobWatchOf(other).held(before, after)).toEqual([]);
7575 expect(jobsOf(one).across(before, after)).toContain("memory-sampler");
7676 });
77
78 test("a job begun and not settled is open on its forge, counted by name, until it settles (#17083)", async () => {
79 const ends: (() => void)[] = [];
80 const begin = () => during("snapshot", () => new Promise<void>((r) => ends.push(r)), undefined, one);
81 const before = Date.now();
82 const first = begin();
83 const second = begin();
84 const open = runningOf(one).find((r) => r.name === "snapshot");
85 expect(open?.open).toBe(2);
86 // Its start is an instant, read on the epoch's clock.
87 expect(open!.since).toBeGreaterThanOrEqual(before - 5);
88 expect(open!.since).toBeLessThanOrEqual(Date.now() + 5);
89 expect(runningOf(other).some((r) => r.name === "snapshot")).toBe(false);
90 for (const end of ends) end();
91 await Promise.all([first, second]);
92 expect(runningOf(one).some((r) => r.name === "snapshot")).toBe(false);
93 });
test/sentinel-memory-evidence.test.ts +46 −1
@@ -9,7 +9,7 @@ import { join } from "node:path";
99 import "./helpers/globals.ts";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { degradedCauses } from "../src/crew/sentinel.ts";
12 import { createMemoryWatch, EVIDENCE_HELD, FIRST_HOUR_MS, type MemoryWatch } from "../src/perf/memory_watch.ts";
12 import { createMemoryWatch, EVIDENCE_HELD, EVIDENCE_OPEN, FIRST_HOUR_MS, type MemoryWatch } from "../src/perf/memory_watch.ts";
1313 import { startMemorySampler } from "../src/boards/memory.ts";
1414 import { keepIfGrown, keptEvidence, KEPT_LINES } from "../src/perf/memory_kept.ts";
1515 import { writeFileSync } from "node:fs";
@@ -165,9 +165,54 @@ test("jobs counted beside sampled-out slices name both", () => {
165165 expect(w.evidence().join("\n")).toContain("memory allocated by jobs from the run's start to the trip: timers 300 MiB in 4 slices (sampled: 2 slices not counted)");
166166 });
167167
168 test("a native spike that fell back names the jobs open at its trip, the one begun with the growth first (#17083)", () => {
169 const start = Date.now() - 3 * FIRST_HOUR_MS;
170 const w = settledWatch(start);
171 const t = start + FIRST_HOUR_MS + MIN;
172 const iso = (ms: number) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
173 const poll = { name: "runner-wait", open: 3, since: start + MIN };
174 // Begun between the last minute under 1.25x and the first over it: with the growth.
175 const snapshot = { name: "snapshot", open: 1, since: t - 30_000 };
176 // The run begins at 1.3x just after the snapshot starts, trips at 2.4x with the heap flat (the
177 // outside grew), and falls back once the snapshot has settled; the long poll is open throughout.
178 w.note(1300 * MIB, 200 * MIB, t, { running: [poll, snapshot] });
179 w.note(2400 * MIB, 210 * MIB, t + MIN, { running: [snapshot, poll] });
180 w.note(1000 * MIB, 200 * MIB, t + 30 * MIN, { running: [poll] });
181
182 const text = w.evidence().join("\n");
183 expect(text).toContain("memory outside every heap (process): first hour 800 MiB, trip 2190 MiB, now 800 MiB");
184 expect(text).toContain(`memory jobs open at the trip: begun since the growth began: snapshot since ${iso(snapshot.since)}; open before it: runner-wait ×3 since ${iso(poll.since)}`);
185 expect(text).toContain(`memory jobs open now: runner-wait ×3 since ${iso(poll.since)}`);
186
187 // A job open since before the last minute under 1.25x did not begin with the growth.
188 const v = settledWatch(start);
189 const early = { name: "drill", open: 1, since: start + FIRST_HOUR_MS - 30_000 };
190 v.note(1300 * MIB, 200 * MIB, t, { running: [poll, early] });
191 v.note(2400 * MIB, 210 * MIB, t + MIN, { running: [poll, early] });
192 expect(v.evidence().join("\n")).toContain(
193 `memory jobs open at the trip: none begun since the growth began; open before it: runner-wait ×3 since ${iso(poll.since)}, drill since ${iso(early.since)}`,
194 );
195 });
196
197 test("the open jobs a trip names are bounded, the rest counted, and nothing open says none", () => {
198 const start = Date.now() - 3 * FIRST_HOUR_MS;
199 const w = settledWatch(start);
200 const t = start + FIRST_HOUR_MS + MIN;
201 const many = Array.from({ length: EVIDENCE_OPEN + 3 }, (_, i) => ({ name: `job${i}`, open: 1, since: start + i * MIN }));
202 w.note(2400 * MIB, 210 * MIB, t, { running: many });
203 w.note(2400 * MIB, 210 * MIB, t + MIN, { running: [] });
204 const lines = w.evidence();
205 const trip = lines.find((l) => l.startsWith("memory jobs open at the trip:")) ?? "";
206 expect(trip).toContain("job0 since");
207 expect(trip).not.toContain(`job${EVIDENCE_OPEN} `);
208 expect(trip.endsWith(", and 3 more")).toBe(true);
209 expect(lines).toContain("memory jobs open now: none");
210 });
211
168212 test("a watch that never tripped names no jobs", () => {
169213 const w = settledWatch(Date.now() - 3 * FIRST_HOUR_MS);
170214 expect(w.evidence().some((l) => l.startsWith("memory allocated by jobs"))).toBe(false);
215 expect(w.evidence().some((l) => l.startsWith("memory jobs open at the trip"))).toBe(false);
171216 });
172217
173218 /**

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs