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

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

Merged opened this

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

Merged

mason/forge:mason/16872-sentinel-memory-growth-was-degraded-16-m → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/16872-sentinel-memory-growth-was-degraded-16-m was merged into main as a233995.

Review

Sign in to review this change.
6 files changed +221 −8
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 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.
31
3032 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.
3133
3234 ## How it is built
src/boards/memory.ts +11 −4
@@ -20,7 +20,8 @@ import { allocationsOf, during } 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";
23 import { hearWorkers, memoryLine, memoryWatch, readNow } from "../perf/memory_watch.ts";
23 import { keepIfGrown } from "../perf/memory_kept.ts";
24 import { hearWorkers, memoryLine, memoryWatch, readNow, type MemoryWatch } from "../perf/memory_watch.ts";
2425
2526 export const MEMORY_EVERY_MS = 60_000;
2627 export const HOUR_MS = 3_600_000;
@@ -71,8 +72,11 @@ export function memoryHours(db: Database, now: number, hours = 24): MemoryHour[]
7172
7273 export type MemorySampler = { tick(now?: number): void; stop(): void };
7374
74 /** Sample now and every minute until stopped. A failed tick is logged and the next one tries again. */
75 export function startMemorySampler(app: App, everyMs = MEMORY_EVERY_MS): MemorySampler {
75 /**
76 * Sample now and every minute until stopped. A failed tick is logged and the next one tries again.
77 * `watch` is the process's own; a test hands it one already grown (#16872).
78 */
79 export function startMemorySampler(app: App, everyMs = MEMORY_EVERY_MS, watch: MemoryWatch = memoryWatch): MemorySampler {
7680 const tick = (now = Date.now()) => {
7781 try {
7882 const reading = readNow(undefined, ceilingOf(app.db));
@@ -83,7 +87,10 @@ export function startMemorySampler(app: App, everyMs = MEMORY_EVERY_MS): MemoryS
8387 // Read once (it empties the tally): the line writes it, the watch sums it up to a trip
8488 // (#16801).
8589 const jobs = allocationsOf(app);
86 memoryWatch.note(reading.rss, reading.heap, now, { commit: reading.commit, held, ceiling: reading.dbCeiling, allocated: jobs.jobs, skipped: jobs.skipped });
90 watch.note(reading.rss, reading.heap, now, { commit: reading.commit, held, ceiling: reading.dbCeiling, allocated: jobs.jobs, skipped: jobs.skipped });
outdated

No test would fail if this line were removed; both new tests call keepIfGrown directly. Add a sampler-level test that asserts the file appears after a grown minute.

91 // A grown minute's evidence outlives this process (#16872): a restart would leave the
92 // sentinel quoting a fresh watch that never tripped.
93 keepIfGrown(app.config.dataDir, watch, now);
8794 app.log.info(memoryLine(reading, process.uptime() * 1000));
8895 app.log.info(heldLine(held));
8996 const allocated = allocationLine(jobs);
src/crew/sentinel.ts +22 −2
@@ -59,6 +59,7 @@ import { evidenceBlock, type Evidence } from "../maintain/evidence.ts";
5959 import { cloneFailing, foldByCause, closeQuiet } from "./sentinel_causes.ts";
6060 import { seenCause } from "./sentinel_seen.ts";
6161 import { memoryWatch, type MemoryWatch } from "../perf/memory_watch.ts";
62 import { keptEvidence } from "../perf/memory_kept.ts";
6263
6364 const log = createLog("sentinel");
6465
@@ -511,6 +512,25 @@ export function repeatedErrors(now: number, ledger?: ErrorLedger): Finding[] {
511512 return out;
512513 }
513514
515 /**
516 * The evidence a memory-growth finding quotes (#16872): this process's watch when it tripped;
517 * otherwise what an earlier process kept at its last grown minute that day
518 * (`perf/memory_kept.ts`), since a restart since leaves a watch that never saw the growth, with
519 * one line on where this process stands now.
520 */
521 function memoryEvidence(watch: Pick<MemoryWatch, "evidence" | "startedAt" | "tripAt">, dataDir: string | undefined, from: number): string[] {
522 const own = watch.evidence();
523 if (watch.tripAt() !== undefined || dataDir === undefined) return own;
524 const kept = keptEvidence(dataDir);
525 if (kept === undefined || kept.startedAt === watch.startedAt || kept.at < from) return own;
526 const iso = (ms: number): string => new Date(ms).toISOString();
527 return [
528 `memory kept by the process started ${iso(kept.startedAt)}, at its last grown minute ${iso(kept.at)}; the forge restarted since`,
529 ...kept.lines,
530 `memory now (process started ${iso(watch.startedAt)}): ${own[0] ?? "no reading yet"}`,
531 ];
532 }
533
514534 /**
515535 * Each cause whose spans total more than ten minutes in the day ending at
516536 * `now`, quoting its sentence. Shorter totals stay in the history.
@@ -521,7 +541,7 @@ export function degradedCauses(
521541 forgeRepoId?: string,
522542 dataDir?: string,
523543 ceilingUsd: number | null = null,
524 watch: Pick<MemoryWatch, "evidence"> = memoryWatch,
544 watch: Pick<MemoryWatch, "evidence" | "startedAt" | "tripAt"> = memoryWatch,
525545 ): Finding[] {
526546 const from = now - DAY_MS;
527547 const byCause = new Map<
@@ -564,7 +584,7 @@ export function degradedCauses(
564584 ...sharedLines(db, cause, now, forgeRepoId, dataDir),
565585 // /system is admin people only: the finding carries what grew, so a builder can name it
566586 // (#14362).
567 ...(cause === "memory-growth" ? watch.evidence() : []),
587 ...(cause === "memory-growth" ? memoryEvidence(watch, dataDir, from) : []),
568588 ],
569589 pillar: "P0 Trust: the forge says when it is not well, and is well again",
570590 kind: "defect",
src/perf/memory_kept.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * A grown process's memory evidence, kept across its restart (#16872). The watch
3 * (`perf/memory_watch.ts`) lives in process memory, and a release restarts the forge
4 * several times a day: the sentinel then files the stored sentence of the process that
5 * grew beside the evidence of a fresh one that never tripped ("trip none", a heap still
6 * in its first hour). So each minute the need is open, the sampler (`boards/memory.ts`)
7 * writes the watch's evidence lines here, under the data directory, and the sentinel
8 * quotes them when the process reading them is a later one.
9 *
10 * `memory-kept.json`: `{ startedAt, at, lines }`, written by rename (`writePrivate`), read
11 * back on the same terms and validated whole: a file that is not this shape is none.
12 */
13 import { join } from "node:path";
14 import { readPrivate, writePrivate } from "../kernel/file_modes.ts";
15 import type { MemoryWatch } from "./memory_watch.ts";
16
17 /** What one grown process said about its memory, as of its last grown minute. */
18 interface KeptEvidence {
19 /** When the process that wrote it started its watch, ms since the epoch. */
20 readonly startedAt: number;
21 /** The minute it was written, ms since the epoch. */
22 readonly at: number;
23 readonly lines: readonly string[];
24 }
25
26 /** The most lines kept: the finding stays under 40 lines with the two it adds. */
27 export const KEPT_LINES = 36;
28 /** The longest line kept; an evidence line is well under it. */
29 const KEPT_LINE_MAX = 400;
30 /** The file is a few kilobytes; anything larger is not ours. */
31 const FILE_MAX = 64 * 1024;
32
33 const file = (dataDir: string): string => join(dataDir, "memory-kept.json");
34
35 const instant = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
36
37 /**
38 * The sampler's minute: while the watch says the process has grown, keep its evidence; any
39 * other minute writes nothing, so the file holds the last grown minute.
40 */
41 export function keepIfGrown(dataDir: string, watch: Pick<MemoryWatch, "grown" | "evidence" | "startedAt">, now: number): void {
42 if (watch.grown() !== undefined) keepEvidence(dataDir, { startedAt: watch.startedAt, at: now, lines: watch.evidence() });
43 }
44
45 /** Write a grown minute's evidence. Never throws: the minute line is worth more than the file. */
46 function keepEvidence(dataDir: string, kept: KeptEvidence): void {
47 if (!instant(kept.startedAt) || !instant(kept.at)) return;
48 const lines = kept.lines.slice(0, KEPT_LINES).map((l) => String(l).replace(/[\r\n]+/g, " ").slice(0, KEPT_LINE_MAX));
49 try {
50 writePrivate(file(dataDir), JSON.stringify({ startedAt: kept.startedAt, at: kept.at, lines }));
51 } catch {
52 // a read-only data directory keeps nothing; the watch still says what it sees
53 }
54 }
55
56 /** The kept evidence, or undefined when there is none or the file is not its shape. */
57 export function keptEvidence(dataDir: string): KeptEvidence | undefined {
58 let raw: unknown;
59 try {
60 raw = JSON.parse(readPrivate(file(dataDir), FILE_MAX) ?? "");
61 } catch {
62 return undefined;
63 }
64 if (typeof raw !== "object" || raw === null) return undefined;
65 const r = raw as { startedAt?: unknown; at?: unknown; lines?: unknown };
66 if (!instant(r.startedAt) || !instant(r.at) || !Array.isArray(r.lines)) return undefined;
67 if (r.lines.length === 0 || r.lines.length > KEPT_LINES) return undefined;
68 if (!r.lines.every((l): l is string => typeof l === "string" && l.length <= KEPT_LINE_MAX && !/[\r\n]/.test(l))) return undefined;
69 return { startedAt: r.startedAt, at: r.at, lines: r.lines };
70 }
src/perf/memory_watch.ts +6
@@ -253,6 +253,10 @@ export const EVIDENCE_HELD = 10;
253253 export const EVIDENCE_WORKERS = 16;
254254
255255 export interface MemoryWatch {
256 /** When this watch started, ms since the epoch: one process's, told apart from a later one's. */
257 readonly startedAt: number;
258 /** When the last trip was read (RSS first at twice its first hour), or undefined if none. */
259 tripAt(): number | undefined;
256260 /**
257261 * The serving VM's minute reading: the process's RSS and main's own heap, and what `extra` adds.
258262 */
@@ -310,6 +314,8 @@ export function createMemoryWatch(startedAt: number = Date.now()): MemoryWatch {
310314 };
311315 };
312316 return {
317 startedAt,
318 tripAt: () => trip?.at,
313319 note(rss, heap, now = Date.now(), extra = {}) {
314320 if (!Number.isFinite(rss) || rss <= 0) return;
315321 main.ceiling = bytes(extra.ceiling) ? extra.ceiling : 0;
test/sentinel-memory-evidence.test.ts +110 −2
@@ -2,14 +2,17 @@
22 * A memory-growth finding carries its own evidence (#14362): /system is admin people only,
33 * so the issue a builder is handed must name what grew, with its figures, from the watch.
44 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
66 import { mkdtemp, rm } from "node:fs/promises";
77 import { tmpdir } from "node:os";
88 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 } from "../src/perf/memory_watch.ts";
12 import { createMemoryWatch, EVIDENCE_HELD, FIRST_HOUR_MS, type MemoryWatch } from "../src/perf/memory_watch.ts";
13 import { startMemorySampler } from "../src/boards/memory.ts";
14 import { keepIfGrown, keptEvidence, KEPT_LINES } from "../src/perf/memory_kept.ts";
15 import { writeFileSync } from "node:fs";
1316
1417 const MIB = 1048576;
1518 const MIN = 60_000;
@@ -166,3 +169,108 @@ test("a watch that never tripped names no jobs", () => {
166169 const w = settledWatch(Date.now() - 3 * FIRST_HOUR_MS);
167170 expect(w.evidence().some((l) => l.startsWith("memory allocated by jobs"))).toBe(false);
168171 });
172
173 /**
174 * A restart between the growth and the filing (#16872): the sentence is the stored one of the
175 * process that grew, so the evidence must be that process's too, not a fresh watch's "trip none".
176 */
177 test("after a restart, a memory-growth finding quotes what the grown process kept, and where the new one stands", async () => {
178 const kdir = await mkdtemp(join(tmpdir(), "forge-memory-kept-"));
179 const kapp = createApp({ dataDir: kdir, port: 0 });
180 try {
181 const now = Date.now();
182 const { w: old, trip } = grownWatch(now - 4 * FIRST_HOUR_MS);
183 keepIfGrown(kdir, old, trip + MIN);
184 // The fresh process: still in its first hour, never tripped.
185 const fresh = createMemoryWatch(now - 20 * MIN);
186 fresh.note(1600 * MIB, 450 * MIB, now - MIN);
187 kapp.db
188 .query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES ('memory-growth', ?1, '/system', ?2, ?3)")
189 .run("The forge's own memory is 4200 MiB.", now - 2 * FIRST_HOUR_MS, now - 30 * MIN);
190
191 const lines = degradedCauses(kapp.db, now, undefined, kdir, null, fresh).find((f) => f.key === "degraded:memory-growth")!.evidence;
192 const text = lines.join("\n");
193 expect(text).toContain(`memory kept by the process started ${new Date(old.startedAt).toISOString()}, at its last grown minute ${new Date(trip + MIN).toISOString()}; the forge restarted since`);
194 expect(text).toContain(`memory rss: first hour 2000 MiB, trip 4100 MiB at ${new Date(trip).toISOString()}, now 4200 MiB`);
195 expect(text).toContain("memory grew most: worker pages's JS heap, 100 MiB to 2410 MiB");
196 expect(text).toContain(`memory now (process started ${new Date(fresh.startedAt).toISOString()}): memory rss: first hour 1600 MiB, trip none, now 1600 MiB`);
197 expect(lines.length).toBeLessThan(40);
198 expect(text).not.toContain(kdir);
199
200 const memoryLines = (ev: readonly string[]) => ev.filter((l) => l.startsWith("memory "));
201 // The process that grew reads its own watch, never the file.
202 expect(memoryLines(degradedCauses(kapp.db, now, undefined, kdir, null, old).find((f) => f.key === "degraded:memory-growth")!.evidence)).toEqual(old.evidence());
203 // Kept before the day the finding covers: not this day's growth.
204 const later = now + 2 * 86_400_000;
205 kapp.db
206 .query("INSERT INTO degraded_span (cause, sentence, href, opened_at, closed_at) VALUES ('memory-growth', 'Again.', '/system', ?1, NULL)")
207 .run(later - 30 * MIN);
208 const fresher = createMemoryWatch(later - 20 * MIN);
209 fresher.note(1600 * MIB, 450 * MIB, later - MIN);
210 expect(memoryLines(degradedCauses(kapp.db, later, undefined, kdir, null, fresher).find((f) => f.key === "degraded:memory-growth")!.evidence)).toEqual(fresher.evidence());
211 } finally {
212 kapp.db.close();
213 await rm(kdir, { recursive: true, force: true });
214 }
215 });
216
217 test("the kept evidence is written only while grown, and a file not its shape is none", async () => {
218 const kdir = await mkdtemp(join(tmpdir(), "forge-memory-kept-"));
219 try {
220 const start = Date.now() - 3 * FIRST_HOUR_MS;
221 const quiet = createMemoryWatch(start);
222 for (let i = 0; i <= 13; i++) quiet.note(1000 * MIB, 200 * MIB, start + i * 5 * MIN);
223 keepIfGrown(kdir, quiet, start + 70 * MIN);
224 expect(keptEvidence(kdir)).toBeUndefined();
225
226 const { w, trip } = grownWatch(start);
227 keepIfGrown(kdir, w, trip + MIN);
228 expect(keptEvidence(kdir)).toEqual({ startedAt: start, at: trip + MIN, lines: w.evidence() });
229 // A quiet minute after leaves the last grown one in place.
230 keepIfGrown(kdir, quiet, trip + 2 * MIN);
231 expect(keptEvidence(kdir)?.at).toBe(trip + MIN);
232
233 const file = join(kdir, "memory-kept.json");
234 for (const bad of [
235 "not json",
236 JSON.stringify({ startedAt: "x", at: 1, lines: ["a"] }),
237 JSON.stringify({ startedAt: 1, at: 1, lines: [] }),
238 JSON.stringify({ startedAt: 1, at: 1, lines: [3] }),
239 JSON.stringify({ startedAt: 1, at: 1, lines: ["a\nb"] }),
240 JSON.stringify({ startedAt: 1, at: 1, lines: Array.from({ length: KEPT_LINES + 1 }, () => "a") }),
241 ]) {
242 writeFileSync(file, bad);
243 expect(keptEvidence(kdir)).toBeUndefined();
244 }
245 } finally {
246 await rm(kdir, { recursive: true, force: true });
247 }
248 });
249
250 /**
251 * The sampler is what writes the file in production (#16872): its minute must keep a grown
252 * watch's evidence, and a watch that has not grown leaves none. The grown watch ignores the
253 * tick's own reading (this process's real RSS), which would otherwise read as fallen back.
254 */
255 test("the memory sampler's minute keeps a grown watch's evidence under the data directory, and a quiet one keeps none", async () => {
256 const kdir = await mkdtemp(join(tmpdir(), "forge-memory-kept-"));
257 const kapp = createApp({ dataDir: kdir, port: 0 });
258 const info = spyOn(kapp.log, "info").mockImplementation(() => {});
259 try {
260 const quiet = startMemorySampler(kapp, 3_600_000, createMemoryWatch());
261 quiet.stop();
262 expect(keptEvidence(kdir)).toBeUndefined();
263
264 const { w } = grownWatch(Date.now() - 3 * FIRST_HOUR_MS);
265 expect(w.grown()).toBeDefined();
266 const held: MemoryWatch = { ...w, note: () => {} };
267 const sampler = startMemorySampler(kapp, 3_600_000, held);
268 sampler.stop();
269 expect(keptEvidence(kdir)?.startedAt).toBe(w.startedAt);
270 expect(keptEvidence(kdir)?.lines).toEqual(w.evidence());
271 } finally {
272 info.mockRestore();
273 kapp.close();
274 await rm(kdir, { recursive: true, force: true });
275 }
276 });

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

Keyboard shortcuts

Docs