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

Name and bound the largest heap retainer from production's own census #17908

opened this

Merged 25h 19m ago, live in production

torque/forge:torque/15318-name-and-bound-the-largest-heap-retainer → main 0 commits fork

  • Merged. torque/15318-name-and-bound-the-largest-heap-retainer was merged into main as 5501eb1.

Review

Sign in to review this change.
4 files changed +73 −8
docs/features/memory-growth.md +2 −2
@@ -57,7 +57,7 @@ Found on a copy of production's data with no network, production's own work on (
5757 - **The plan and lane caches kept answers nobody could ask for again** (`src/web/map_cache.ts`, `src/view/cache.ts`). A plan was keyed by its stamp, which moves with every run that starts or spends, and a lane by its repository's latest event; an entry past its minute was only dropped when the same key was read again or the count (64 plans, 128 lanes) pushed it out. A plan holds its repository's whole graph: the copy held ten graphs of the busiest repository (4,593 issues each) after an hour of page views, and the cache had room for 64. Now there is one plan per repository, spend visibility and day, and one lane per repository, scope and day, each replaced when its stamp moves; and every view cache drops what is past its time on the first write after `SWEEP_MS` (30 s).
5858 - **A hosted forge that slept left its request counter and route timing behind** (`src/http/server.ts`), one more of each with every wake, each keeping the closed database and a flush that retried against it. They now go when the forge closes, written out first.
5959
60 A new long-lived collection names itself in `heldOf(app)` (a forge's) or `threadHeld` (the thread's), with a bound and a test of its eviction. Named today: `turn`, `requests in flight`, `event streams`, `request counters`, `route timings`, `map plans`, `map lanes`, `map layouts`, `finishing said` (the newest 512 pulls, `src/crew/said_once.ts`), and three the crew keeps per pull or per check (`autonomy conflicted pulls`, `checks retried`, `app links said`), each now bounded to its newest 1024 entries (`src/perf/bounded.ts`, #15210).
60 A new long-lived collection names itself in `heldOf(app)` (a forge's) or `threadHeld` (the thread's), with a bound and a test of its eviction. Named today: `perf samples`, `turn`, `requests in flight`, `event streams`, `request counters`, `route timings`, `map plans`, `map lanes`, `map layouts`, `finishing said` (the newest 512 pulls, `src/crew/said_once.ts`), and three the crew keeps per pull or per check (`autonomy conflicted pulls`, `checks retried`, `app links said`), each now bounded to its newest 1024 entries (`src/perf/bounded.ts`, #15210).
6161
6262 **Every statement a connection keeps is bounded (#16942).** Bun's statement cache, raised to 4,096 texts a connection (#9514), keeps the first texts it meets for the connection's life and never lets one go; a text that names a number (a browse page's `OFFSET`, a board's `LIMIT`) took a slot forever, each a compiled program in malloc that the collector never feels, so the memory outside every heap filled through the day. A connection `openDb` or a worker's `keepFixedTexts` makes now keeps its fixed texts in a cache of its own of 1,024, least recently used out first (`src/kernel/list_texts.ts`), beside the 64 list texts (#14479). Its count reads on the `memory holds:` line as `statements kept`, and the sentinel's finding quotes it. Test: `test/fixed-texts.test.ts`.
6363
@@ -67,7 +67,7 @@ A new long-lived collection names itself in `heldOf(app)` (a forge's) or `thread
6767
6868 `heapStats()` and a snapshot walk the whole heap, so neither runs on the serving process by default. On a copy of production's data (never production), set `FORGE_HEAP_CAPTURE_DIR=<dir under FORGE_APP_DATA or $TMPDIR>` (and `FORGE_HEAP_CAPTURE_MIN`, default 20): the process writes `heap-<minutes up>.json` (object counts by type after a full collection) and `heap-<minutes up>.snapshot.json` at boot and every interval (`src/perf/heap_capture.ts`; unset, nothing runs). Then `bun scripts/heap-growth.ts heap-0000.json heap-0060.json` prints the types that grew, bytes by type, and for the three that grew most the holders as `<holder type>.<edge name>` with count and bytes (`src/perf/heap_diff.ts`). The holder type and edge name point to the module: grep the property name.
6969
70 **Not yet measured.** The hour on production's copy has not been taken: the run that built this tool could not read production's data. Until it is, the retainers of the main heap's 251 to 1057 MiB (#15210) are not named, and the three fixes above are the ones the earlier hour found. A short boot-plus-1,500-requests run on an empty forge works end to end and held nothing growing beyond collectable strings. Whoever takes the hour should paste the `heap-growth` output on #15286, name the largest holder and its module here, and bound it with a test of its eviction; if the growth is outside the heap (`extraMemorySize` or RSS rising while `heapSize` is flat), open a follow-up naming the native owner.
70 **Measured on a replay, not on production (#15318).** Production's own census (`GET /api/v1/telemetry/heap-census`) answers 401 to every agent, so the hour on production is still the owner's to take (see below). The forge took one of itself instead: `bench/seed.ts` (20 repositories, 200 issues, 2,000 pulls), `FORGE_HEAP_CAPTURE_DIR` at one minute, and about 3,200 page and API reads a minute for three minutes; `heap-growth` between the boot and the third capture. The heap went from 36 to 106 MiB (RSS 208 to 343 MiB). What grew by count: `Object` +63,578 and `string` +56,237, `Array` +15,885; the rest (`ModuleRecord`, `FunctionExecutable`, `Structure`) is code loaded on first use, which stops growing. Between the last two captures only `Object`, `string` and `Array` still grew (about 20,000 a minute), and the holders of the `Array` growth were `Object.phases` (16,074) and `Object.segments`: the rolling record of requests, `src/perf/record.ts` (`createPerfRecord`, held by `liveOf` in `src/perf/live.ts`). It keeps every request of the last 15 minutes with an object per Server-Timing phase, bounded only by 20,000 samples a route over up to 200 routes, and it was named nowhere in `memory holds:`. That bound is now `MAX_TOTAL_SAMPLES` (60,000) across every route: past it the longest route's list is halved to every second sample (its window kept), and the count reads as `perf samples` on the minute line. Test: `test/perf-record-bound.test.ts`. The replay is small and has no apps, crew or checks, so this names the retainer that grows with page traffic, not the whole of production's 251 to 1057 MiB: the next finding's `memory holds:` line says whether `perf samples` is the holder that climbs, and the owner's two censuses an hour apart on `/system` remain the way to say what else is.
7171
7272 Tests: `test/heap-diff.test.ts`, `test/app-turn.test.ts`, `test/cache-holds.test.ts`, `test/forge-sleep.test.ts`, `test/held.test.ts`.
7373
src/perf/live.ts +2 −1
@@ -15,7 +15,7 @@ import { createReadLedger } from "./reads.ts";
1515 import { createStallBlame } from "./stall_blame.ts";
1616 import { createPerfRecord } from "./record.ts";
1717 import { createLagMinutes } from "./lag_minutes.ts";
18 import { threadHeld } from "./held.ts";
18 import { heldOf, threadHeld } from "./held.ts";
1919
2020 /** The requests the server is answering now (#11478): begun and ended around each one in `http/server.ts`. */
2121 export const inFlight = createInFlight<Request>((request) => childRequestLabel(request) ?? patternOf(request));
@@ -66,6 +66,7 @@ export function liveOf(app: object): Live {
6666 lagMinutes: createLagMinutes((to, span) => stallBlame.worst(to, span, 1)[0]?.what ?? null),
6767 };
6868 lives.set(app, live);
69 heldOf(app).add("perf samples", live.perfRecord.size);
6970 }
7071 return live;
7172 }
src/perf/record.ts +27 −5
@@ -14,6 +14,11 @@ import { classOf, createTrafficLedger, type TrafficClass, type TrafficLedger, ty
1414 export const WINDOW_MS = 15 * 60_000;
1515 export const MAX_SAMPLES = 20_000;
1616 export const MAX_PATTERNS = 200;
17 /**
18 * Samples kept across every pattern: 200 patterns of 20,000 each was never a bound a heap could
19 * meet (#15318).
20 */
21 export const MAX_TOTAL_SAMPLES = 60_000;
1722 const MAX_PATTERN = 200;
1823 const MAX_PHASES = 16;
1924
@@ -63,6 +68,8 @@ export interface PerfRecord {
6368 * `gitSpawns`): a difference of the kept samples shrinks when an add drops or thins old ones.
6469 */
6570 added(): number;
71 /** Samples held now, all patterns: what the memory line names as `perf samples`. */
72 size(): number;
6673 }
6774
6875 const validPattern = (p: string): boolean =>
@@ -81,6 +88,14 @@ export function createPerfRecord(valid: (key: string) => boolean = validPattern)
8188 const firsts = new Map<string, number>();
8289 const ledger = createTrafficLedger();
8390 let added = 0;
91 let total = 0;
92 // Halve one list to every second sample; it keeps its whole window.
93 const thin = (list: Sample[]): void => {
94 const thinned = list.filter((_, i) => i % 2 === 1);
95 total -= list.length - thinned.length;
96 list.length = 0;
97 list.push(...thinned);
98 };
8499 return {
85100 ledger,
86101 add(pattern, sample, who) {
@@ -99,22 +114,29 @@ export function createPerfRecord(valid: (key: string) => boolean = validPattern)
99114 .filter((p) => Number.isFinite(p.ms) && p.ms >= 0)
100115 .slice(0, MAX_PHASES);
101116 list.push({ ...sample, phases });
117 total++;
102118 // A minute of slack past the window, so the drop is rare, not per request.
103119 if (list[0]!.at < sample.at - WINDOW_MS - 60_000) {
104120 const keep = list.findIndex((s) => s.at >= sample.at - WINDOW_MS);
105 list.splice(0, keep === -1 ? list.length : keep);
121 const drop = keep === -1 ? list.length : keep;
122 list.splice(0, drop);
123 total -= drop;
106124 }
107 if (list.length > MAX_SAMPLES) {
108 const thinned = list.filter((_, i) => i % 2 === 1);
109 list.length = 0;
110 list.push(...thinned);
125 if (list.length > MAX_SAMPLES) thin(list);
126 if (total > MAX_TOTAL_SAMPLES) {
127 // The busiest route pays: thin the longest list, so a quiet route keeps its window.
128 let longest = list;
129 for (const l of real.values()) if (l.length > longest.length) longest = l;
130 thin(longest);
111131 }
112132 },
113133 traffic: (pattern, since) => (real.get(pattern) ?? []).filter((s) => s.at >= since),
114134 first: (pattern) => firsts.get(pattern),
115135 patterns: () => [...real.keys()],
116136 added: () => added,
137 size: () => total,
117138 clear() {
139 total = 0;
118140 real.clear();
119141 firsts.clear();
120142 },
test/perf-record-bound.test.ts added +42
@@ -0,0 +1,42 @@
1 import { describe, expect, test } from "bun:test";
2 import { heldOf } from "../src/perf/held.ts";
3 import { liveOf } from "../src/perf/live.ts";
4 import { createPerfRecord, MAX_TOTAL_SAMPLES, type Sample } from "../src/perf/record.ts";
5
6 // #15318: the heap census of a replayed forge named the rolling record's samples (`Object.phases`,
7 // one array per request) as what grows with traffic; only the 15 minute window and 20,000 per
8 // route bounded it, 200 routes over.
9 const sample = (at: number): Sample => ({ at, ms: 5, signedIn: false, phases: [{ name: "db", ms: 1, hit: false }] });
10
11 describe("the rolling record is bounded across every route", () => {
12 test("many busy routes stay under the total, and the busiest pays", () => {
13 const record = createPerfRecord();
14 const now = Date.now();
15 for (let route = 0; route < 10; route++) {
16 const n = route === 0 ? 30_000 : 9_000;
17 for (let i = 0; i < n; i++) record.add(`/r${route}`, sample(now + i));
18 }
19 // 30,000 + 9 x 9,000 = 111,000 offered
20 expect(record.size()).toBeLessThanOrEqual(MAX_TOTAL_SAMPLES);
21 expect(record.traffic("/r0", 0).length).toBeLessThan(30_000);
22 expect(record.traffic("/r9", 0).length).toBe(9_000);
23 });
24
25 test("size follows the window's drops and clear", () => {
26 const record = createPerfRecord();
27 const t = Date.now();
28 record.add("/a", sample(t));
29 record.add("/a", sample(t + 1));
30 expect(record.size()).toBe(2);
31 record.add("/a", sample(t + 60 * 60_000)); // an hour on: the first two leave the window
32 expect(record.size()).toBe(1);
33 record.clear();
34 expect(record.size()).toBe(0);
35 });
36
37 test("the forge names the count on its memory line as `perf samples`", () => {
38 const app = {};
39 liveOf(app).perfRecord.add("/x", sample(Date.now()));
40 expect(heldOf(app).read().find((h) => h.name === "perf samples")?.size).toBe(1);
41 });
42 });

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

Keyboard shortcuts

Docs