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

The forge keeps its stall and minute memory lines in its data dir, so its performance history survives a release #17681

opened this

Merged 20h 33m ago, live in production

perf-log-keeps → main 0 commits 3 threads · 3 unresolved

  • Merged. perf-log-keeps was merged into main as d3e188b.

Review

Sign in to review this change.
6 files changed +238 −1
scripts/perf-log.ts added +11
@@ -0,0 +1,11 @@
1 /**
2 * `bun scripts/perf-log.ts [data dir] [text]`: the forge's kept performance lines (`perf/kept_log.ts`),
3 * oldest first, across every boot the files still hold: each event-loop stall and the minute
4 * memory lines. With `text`, only the lines that contain it. The data directory defaults to
5 * FORGE_DATA, as the forge's own.
6 */
7 import { dataDirOf } from "../src/kernel/preflight.ts";
8 import { readKept } from "../src/perf/kept_log.ts";
9
10 const [dir, text] = process.argv.slice(2);
11 for (const line of readKept(dir ?? dataDirOf(process.env))) if (text === undefined || line.includes(text)) console.log(line);
src/kernel/log.ts +9
@@ -296,6 +296,14 @@ export function clearErrors(): void {
296296 for (const ledger of forgeLedgers) ledger.clear();
297297 }
298298
299 /** Where a line also goes once written (`perf/kept_log.ts`): the boot sets it; none by default. */
300 let tee: ((scope: string, message: string, line: string) => void) | undefined;
301
302 /** Send every line written from now on to `sink` as well (undefined stops it). */
303 export function teeLines(sink: ((scope: string, message: string, line: string) => void) | undefined): void {
304 tee = sink;
305 }
306
299307 /** `owner`: the forge whose own logger this is; module loggers have none. */
300308 export function createLog(scope: string, owner?: string): Log {
301309 const emit = (level: LogLevel, message: string, fields?: LogFields) => {
@@ -314,6 +322,7 @@ export function createLog(scope: string, owner?: string): Log {
314322 record(scope, body, Date.now(), owner);
315323 }
316324 console[level === "debug" ? "log" : level](line);
325 tee?.(scope, message, line);
317326 };
318327 return {
319328 debug: (m, f) => emit("debug", m, f),
src/main.ts +11 −1
@@ -123,7 +123,8 @@ import { bootCounts, recordBoot, recordCleanExit } from "./kernel/boots.ts";
123123 import { census, censusWords, processRows } from "./kernel/census.ts";
124124 import { reapLeftoverBridges } from "./crew/leftovers.ts";
125125 import { crewRoot } from "./crew/workdir.ts";
126 import { createLog } from "./kernel/log.ts";
126 import { createLog, teeLines } from "./kernel/log.ts";
127 import { keptLine, keptLog } from "./perf/kept_log.ts";
127128 import { loadOrNone, startService } from "./kernel/start_service.ts";
128129 import { METER_EVERY_MS, newMeterWatch } from "./crew/meter_watch.ts";
129130 import { watchStalls } from "./kernel/loop_lag.ts";
@@ -232,6 +233,15 @@ const edgeToken = (process.env.FORGE_EDGE_TOKEN ?? "").trim();
232233
233234 const dataDir = dataDirOf(process.env);
234235 if (!readOnly) setLedgerDir(join(dataDir, "ledger"));
236 // The stall and minute memory lines outlive the process (`perf/kept_log.ts`): a release replaces
237 // the container and its log every half hour, and these are the forge's performance history.
238 if (!readOnly) {
239 const kept = keptLog(dataDir);
240 teeLines((scope, message, line) => {
241 if (keptLine(scope, message)) kept.add(line);
242 });
243 process.on("exit", () => kept.stop());
244 }
235245 // One answer for boot and `--preflight` (kernel/preflight.ts): the data
236246 // directory is not the tree itself (#622: a database or a host key there is
237247 // one `git add -A` from every clone), FORGE_TRUSTED_PROXIES parses (a typo
src/perf/kept_log.ts added +117
@@ -0,0 +1,117 @@
1 /**
2 * The forge's own performance history, kept across releases (#17547's 30-minute releases replace
3 * the container, and its log with it: the stall lines and the minute memory lines went with every
4 * release, and a fix's before-baseline was lost that way). The lines are written to the log as
5 * before and also appended to `<data>/perf/loop.log`, so they outlive the process:
6 *
7 * - kept: the `[loop]` scope (each event-loop stall, with what ran across it) and the minute
8 * memory lines (`memory main: …`, `memory holds: …`), the serving thread's own; a worker's
9 * lines are its own thread's log and are not kept here;
10 * - cheap: a line is put in a buffer and the buffer is appended at most every `FLUSH_MS`, or at
11 * once past `FLUSH_BYTES`; one append per flush, never one per line;
12 * - bounded: past `MAX_BYTES` the file is renamed to `loop.log.1` (and `.1` to `.2`…), and only
13 * `KEEP` old files stay: `MAX_BYTES * (KEEP + 1)` on disk at most;
14 * - read with `readKept` (the newest files last), or `bun scripts/perf-log.ts [dir]`.
15 *
16 * A write that fails is dropped with the rest of its buffer: the history is a help, never a reason
17 * for the forge to fail.
18 */
19
20 import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
21 import { join } from "node:path";
22 import { during } from "./jobs.ts";
23
24 /** The file the lines go to, under the data directory. */
25 export const KEPT_FILE = join("perf", "loop.log");
26 /** Past this a file is rotated. */
27 export const MAX_BYTES = 8 * 1024 * 1024;
28 /** Old files kept beside the live one: about 54 MiB at most in all. */
29 export const KEEP = 5;
30 /** How long a line may wait in the buffer. */
31 export const FLUSH_MS = 2_000;
32 /** A buffer this big is written at once. */
33 export const FLUSH_BYTES = 64 * 1024;
34
35 /** Whether a log line is one the history keeps: the loop's stalls, and the minute memory lines. */
36 export function keptLine(scope: string, message: string): boolean {
37 return scope === "loop" || ((scope === "forge" || scope === "memory") && /^memory (main|holds)\b/.test(message));
38 }
39
40 export interface KeptLog {
41 /** Put one line in the buffer (a newline is added). */
42 add(line: string): void;
43 /** Append the buffer now. */
44 flush(): void;
45 /** Flush and stop the timer. */
46 stop(): void;
47 }
48
49 /** The kept log of `dataDir`: buffered appends, rotated by size. */
50 export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number } = {}): KeptLog {
51 const maxBytes = o.maxBytes ?? MAX_BYTES;
52 const keep = o.keep ?? KEEP;
53 const file = join(dataDir, KEPT_FILE);
54 let buffer: string[] = [];
55 let bytes = 0;
56 let size: number | undefined;
57 const rotate = (): void => {
58 rmSync(`${file}.${keep}`, { force: true });
59 for (let n = keep - 1; n >= 1; n--) if (existsSync(`${file}.${n}`)) renameSync(`${file}.${n}`, `${file}.${n + 1}`);
60 if (keep >= 1) renameSync(file, `${file}.1`);
61 else rmSync(file, { force: true });
62 size = 0;
63 };
64 const flush = (): void => {
65 if (buffer.length === 0) return;
66 const text = buffer.join("");
67 buffer = [];
68 bytes = 0;
69 try {
70 if (size === undefined) {
71 mkdirSync(join(dataDir, "perf"), { recursive: true });
72 size = existsSync(file) ? statSync(file).size : 0;
73 }
74 const add = Buffer.byteLength(text);
75 if (size > 0 && size + add > maxBytes) rotate();
76 appendFileSync(file, text);
77 size += add;
78 } catch {
79 size = undefined;
80 }
81 };
82 const timer = setInterval(() => during("kept-log-flush", flush), o.flushMs ?? FLUSH_MS);
83 timer.unref?.();
84 return {
85 add(line) {
86 const text = `${line}\n`;
87 buffer.push(text);
88 bytes += Buffer.byteLength(text);
outdated

text.length counts UTF-16 units, but FLUSH_BYTES is a byte threshold. Use Buffer.byteLength(text).

89 if (bytes >= FLUSH_BYTES) flush();
90 },
91 flush,
92 stop() {
93 clearInterval(timer);
94 flush();
95 },
96 };
97 }
98
99 /** Every kept line of `dataDir`, oldest file first, as written; [] when none was kept. */
100 export function readKept(dataDir: string, keep = KEEP): string[] {
101 const file = join(dataDir, KEPT_FILE);
102 const out: string[] = [];
103 for (let n = keep; n >= 0; n--) {
104 const path = n === 0 ? file : `${file}.${n}`;
105 let text: string;
106 try {
107 text = readFileSync(path, "utf8");
108 } catch (error) {
109 // Not kept yet, or rotated away since: that file has no lines. Any other error (an unreadable
outdated

This empty catch hides an unreadable file. Skip it deliberately and say why, or log it once.

110 // file) is the reader's to see, never an empty history.
111 if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
112 throw error;
113 }
114 out.push(...text.split("\n").filter((line) => line !== ""));
115 }
116 return out;
117 }
test/job-slices.test.ts +1
@@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> {
266266 * on.
267267 */
268268 const UNTIMED: Record<string, string> = {
269 "kept-log-flush": "every 2 s: one append of the buffered stall and minute lines to perf/loop.log, rotated past its size (perf/kept_log.ts); perf-kept-log.test.ts drives flush directly",
outdated

The file is perf/loop.log, not perf/kept.log. Fix the reason text.

269270 "snapshot-cut-timeout": "a one-shot timer per file a snapshot cuts (snapshot/cut.ts), fired only when the cutter's worker has not answered within CUT_TIMEOUT_MS: it ends the worker and refuses the jobs it held; snapshot-cut.test.ts drives a silent worker to it",
270271 "advisory-feed": "hourly (and once 30 s after boot): one read of each repository's lockfile and two network fetches, KEV and OSV (core/advisory_feed.ts); the network is not timed here and advisory-feed.test.ts drives listenOnce with a fake fetch",
271272 "series-sampler": "every 30 s: one /metrics render and one batched insert (series/store.ts record), bounded by the rows it keeps; series-explore.test.ts drives tick directly",
test/perf-kept-log.test.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * The forge's stall and minute memory lines outlive the process (`perf/kept_log.ts`): a line
3 * written before a restart is read after it, the file is bounded by size, and a line is a buffer
4 * push, written in batches.
5 */
6 import { afterAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { readdirSync, statSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createLog, teeLines } from "../src/kernel/log.ts";
12 import { KEPT_FILE, keptLine, keptLog, readKept } from "../src/perf/kept_log.ts";
13
14 const dirs: string[] = [];
15 const fresh = async (): Promise<string> => {
16 const dir = await mkdtemp(join(tmpdir(), "forge-kept-log-"));
17 dirs.push(dir);
18 return dir;
19 };
20 afterAll(async () => {
21 teeLines(undefined);
22 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
23 });
24
25 test("only the stall lines and the minute memory lines are kept", () => {
26 expect(keptLine("loop", "event loop blocked 271 ms; running then: no request; heap 10.0 MiB")).toBe(true);
27 expect(keptLine("forge", "memory main: rss 332 MiB, heap 27.4 MiB")).toBe(true);
28 expect(keptLine("forge", "memory holds: statements kept 230")).toBe(true);
29 expect(keptLine("forge", "child forge name=muse")).toBe(false);
30 expect(keptLine("forge", "memory: nothing keeps memory for the forge itself")).toBe(false);
31 expect(keptLine("http", "event loop blocked 1 ms")).toBe(false);
32 });
33
34 test("a stall line written before a restart is read after it, through the log as the boot wires it", async () => {
35 const dir = await fresh();
36 // The first boot: the log tees into the kept file, as main.ts wires it.
37 const first = keptLog(dir);
38 teeLines((scope, message, line) => {
39 if (keptLine(scope, message)) first.add(line);
40 });
41 createLog("loop").warn("event loop blocked 963 ms; running then: no request; heap 10.1 MiB");
42 createLog("forge").info("memory main: rss 332 MiB, heap 27.4 MiB, up 0 min");
43 createLog("forge").info("a line nobody keeps");
44 // The process ends: the exit flushes what the buffer held.
45 first.stop();
46 teeLines(undefined);
47 // The next boot reads it, and its own lines follow.
48 const second = keptLog(dir);
49 second.add("2026-12-02T22:00:00.000Z WARN [loop] event loop blocked 300 ms; running then: GET /");
50 second.stop();
51 const lines = readKept(dir);
52 expect(lines).toHaveLength(3);
53 expect(lines[0]).toMatch(/WARN \[loop\] event loop blocked 963 ms/);
54 expect(lines[1]).toMatch(/\[forge\] memory main: rss 332 MiB/);
55 expect(lines[2]).toContain("blocked 300 ms; running then: GET /");
56 expect(lines.join("\n")).not.toContain("a line nobody keeps");
57 });
58
59 test("past its size the file rotates, and only so many old files stay", async () => {
60 const dir = await fresh();
61 const log = keptLog(dir, { maxBytes: 1_000, keep: 2 });
62 for (let i = 0; i < 100; i++) {
63 log.add(`line ${String(i).padStart(3, "0")} ${"x".repeat(80)}`);
64 if (i % 5 === 4) log.flush();
65 }
66 log.stop();
67 const files = readdirSync(join(dir, "perf")).sort();
68 expect(files).toEqual(["loop.log", "loop.log.1", "loop.log.2"]);
69 for (const f of files) expect(statSync(join(dir, "perf", f)).size).toBeLessThanOrEqual(1_000);
70 const kept = readKept(dir, 2);
71 // The newest line is last, and what fell off the end is gone.
72 expect(kept.at(-1)).toStartWith("line 099");
73 expect(kept[0]).not.toStartWith("line 000");
74 expect(readKept(join(dir, "nowhere"))).toEqual([]);
75 expect(KEPT_FILE).toBe(join("perf", "loop.log"));
76 });
77
78 test("a line is a buffer push, written in FLUSH_BYTES batches: 10,000 lines all land, and the cost is printed", async () => {
79 const dir = await fresh();
80 const log = keptLog(dir, { flushMs: 60_000 });
81 const line = "2026-12-02T21:43:25.432Z WARN [loop] event loop blocked 271 ms; running then: no request; heap 10.0 MiB";
82 const t0 = performance.now();
83 for (let i = 0; i < 10_000; i++) log.add(line);
84 const per = (performance.now() - t0) / 10;
85 log.stop();
86 // Measured, not bound: a wall clock under load proves nothing (test/flake.test.ts).
87 console.log(`kept log: ${per.toFixed(3)} ms per 1,000 lines, flushes included`);
88 expect(readKept(dir)).toHaveLength(10_000);
89 });

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

Keyboard shortcuts

Docs