perf(docker): stop loading ssh2, which allocates a 16 MiB WASM heap nobody uses

Profiling at the memory high-water mark - not at idle, which is what every earlier
round measured - found the largest single retainer in every snapshot was one V8
Context holding a 16.00 MiB ArrayBuffer. Expanding it through the dominator tree
named it: ssh2's crypto module, whose POLY1305_WASM_MODULE instantiates a
WebAssembly memory for ChaCha20-Poly1305 as soon as it is required.

Homarr has no SSH feature and does not depend on ssh2. The chain is
dockerode -> docker-modem -> ssh2, and docker-modem/lib/modem.js requires './ssh'
at module scope while using it in exactly one place, already guarded by
`protocol === 'ssh'`. A pnpm patch moves the require inside that branch. SSH-based
Docker hosts still work - require() is cached, so they pay it once - and every
socket-based install, which is everyone else, never loads it.

Measured over four alternated runs on a restored real backup, external memory:

                     before        after
  board loaded    25.4, 25.1    8.3, 11.2
  nav-01          28.5, 25.4   10.1,  8.6
  multi-tab       31.1, 35.8   13.0, 10.0
  post-soak       21.4, 21.5    5.5,  7.2

Consistently -15 to -18 MiB, ranges non-overlapping, and 30 fewer files loaded
(1470 -> 1440).

Peak RSS does NOT improve, and that is worth stating plainly: V8 sizes its heap
against available headroom, so freeing native memory lets it grow further before
collecting. What changes is the composition - a fixed 16 MiB of unusable WASM
buffer becomes headroom the app can actually use, which matters under a container
memory limit but does not move the peak number.

Also adds the instruments this needed. A heap snapshot can never explain a peak,
because V8 runs a full GC before serialising one and reports only survivors:

  - memory-probe.cjs gains in-process allocation sampling, on-demand snapshots via
    v8.writeHeapSnapshot, an smaps endpoint, and require-graph recording.
  - analyze-allocations.mjs diffs two stages to isolate what one stage allocated.
  - analyze-smaps-stages.mjs splits each stage's RSS into JS heap, JIT, native and
    file-backed pages.
  - analyze-heap-dominators.mjs can now expand the largest retainer, which is what
    identified ssh2. A plain graph walk escapes through __proto__ and is useless.

One trap recorded in the findings: taking the peak snapshot over CDP delivers it as
JS string chunks and added ~134 MiB of ArrayBuffers to the process being measured,
producing a fake 693 MiB reading. v8.writeHeapSnapshot streams from C++ instead, and
the probe now reports its own observerCostMiB so the cost of looking is visible.
This commit is contained in:
Thomas Camlong committed 2026-08-09 22:17:25 +02:00
1 parent 3bc25509cf
commit 3cc6ff33df
9 files changed
+598 -32

No files matched your search

+55
View File
@@ -46,6 +46,10 @@ const soakIntervalMs = Number(process.env.STRESS_SOAK_INTERVAL_MS ?? 20_000);
const keepContainer = process.env.STRESS_KEEP_CONTAINER === "true";
/** Dump a browser heap snapshot here (analyse with analyze-react-fibers.mjs). */
const clientSnapshotPath = process.env.STRESS_CLIENT_SNAPSHOT;
/** Dump a *server* heap snapshot taken at peak, with all tabs still open. */
const peakSnapshotPath = process.env.STRESS_PEAK_SNAPSHOT
? path.resolve(process.env.STRESS_PEAK_SNAPSHOT)
: undefined;
/**
* Extra `docker run` wiring, so a diagnostics-only preload can be injected into a
* shipped image without rebuilding it. Used to mount scripts/benchmarks at /probe and
@@ -115,6 +119,54 @@ const captureProbeAsync = async (name: string) => {
if (!fetches.includes('"disabled"')) {
await writeFile(path.join(outputDirectory, `${name}.fetches.json`), fetches);
}
// Allocation totals are cumulative since boot, so a single capture cannot separate "the
// app loaded its code" from "four tabs churned through memory". Capturing at every stage
// makes those subtractable.
const allocations = await fetchProbeAsync("/allocations");
if (!allocations.includes('"disabled"')) {
await writeFile(path.join(outputDirectory, `${name}.allocations.json`), allocations);
}
// The address-space map is the only place JS heap, JIT code, native malloc and file-backed
// pages are distinguishable, and `rss - heapTotal - external` grew by ~85 MiB between boot
// and peak with no JS-side explanation. Captured every stage because which stage is the
// true high-water mark is not known in advance — it is not always the multi-tab one.
const maps = await fetchProbeAsync("/maps");
if (!maps.includes('"error"')) {
await writeFile(path.join(outputDirectory, `${name}.smaps.json`), maps);
}
};
/**
* Grabs the two artefacts that only make sense at the high-water mark, with load still on:
* a heap snapshot (what peak memory *retains*) and the cumulative allocation profile (what
* peak memory *churned through*, which no snapshot can show because V8 GCs before it
* serialises one). Set STRESS_PEAK_SNAPSHOT to a host path to keep the snapshot.
*/
const capturePeakAsync = async () => {
if (!probePort) return;
// Mappings first, and before any snapshot: this is the only reading that separates JS heap
// from native, JIT and file-backed pages, and it must reflect the loaded process rather
// than the process plus whatever the act of snapshotting allocated.
const maps = await fetchProbeAsync("/maps");
if (!maps.includes('"error"')) {
await writeFile(path.join(outputDirectory, "peak.smaps.json"), maps);
log("peak: address-space map captured");
}
const allocations = await fetchProbeAsync("/allocations");
if (!allocations.includes('"disabled"')) {
await writeFile(path.join(outputDirectory, "peak.allocations.json"), allocations);
log("peak: allocation profile captured");
}
if (!peakSnapshotPath) return;
const inContainer = "/tmp/peak.heapsnapshot";
const result = await fetchProbeAsync(`/snapshot?path=${encodeURIComponent(inContainer)}`);
if (result.includes('"error"')) {
log(`peak: snapshot failed — ${result.slice(0, 160)}`);
return;
}
await execFileAsync("docker", ["cp", `${containerName}:${inContainer}`, peakSnapshotPath]);
await execFileAsync("docker", ["exec", containerName, "rm", "-f", inContainer]).catch(() => undefined);
log(`peak: heap snapshot saved to ${peakSnapshotPath}`);
};
const captureAsync = async (name: string) => {
@@ -512,6 +564,9 @@ const main = async () => {
}
log(`multi-tab: clicked ${widgetInteractions.clicked}/${widgetInteractions.available} widget controls`);
await captureAsync("07-multi-tab");
// Taken here, with every tab still open, because this is the high-water mark. Every
// earlier snapshot was of a drained process and could not show what peak memory holds.
await capturePeakAsync();
}
if (clientSnapshotPath) await captureClientSnapshotAsync(freshPage, clientSnapshotPath);