diff --git a/docs/plans/memory-leak-fixes-0.6.0.md b/docs/plans/memory-leak-fixes-0.6.0.md index 04d24df..394b96a 100644 --- a/docs/plans/memory-leak-fixes-0.6.0.md +++ b/docs/plans/memory-leak-fixes-0.6.0.md @@ -25,6 +25,7 @@ Fix every leak in the v0.6.0 static review (four pi agents on GLM 5.3 plus a man | [PROF-EXPORT] | LOW profiler artifacts on disk were never pruned | Keep the newest 32 per extension after each write | `lsp-profiler/src/export/artifact_retention_tests.rs` | | [PROF-UI-LIFETIME] | LOW `FileLogSink` had no dispose and no size cap | `dispose()` closes it; two alternating capped files (8 MiB each) | `lsp-profiler-ui/src/test/unit/file-log-sink.test.ts` | | [PROF-DOTNET-CPU] | LOW `cpu.rs` spawned its forwarder with `drop(tokio::spawn(..))` | `SamplerHandle::own_producer` keeps the task's abort handle; dropping the handle aborts it | `lsp-profiler/src/sampler_lifetime_tests.rs`, plus the forwarder pin in `lsp-profiler-dotnet/src/cpu.rs` | +| [PROF-UI-LIFETIME] | LOW decoration-type maps keyed by colour grew on every palette change: the palette is re-read per render | `pruneToPalette` disposes types whose colour the current palette no longer paints | `lsp-profiler-ui/src/test/suite/decoration-palette.test.ts` (9 types after 8 changes before the fix) | | [PROF-MEMORY-STOP] | LOW Python `stop_tracemalloc` left `gc.garbage`, the baseline snapshot, the `atexit` hook and the signal handlers in the debuggee | The stop script (now `src/memory/scripts/stop_tracemalloc.py`) releases all four | `lsp-profiler-python/tests/python/test_stop_tracemalloc.py`, run by `make test` in a real interpreter | ## [MEM-060-NOT-LEAKS] Checked and left as they are @@ -32,7 +33,6 @@ Fix every leak in the v0.6.0 static review (four pi agents on GLM 5.3 plus a man - **M9 `Symbolizer` `_ids`:** each CPU session runs its own engine process, and the interner is that recording's frame dictionary, mirrored by the Rust relay. It goes when the session's engine exits. - **Other unowned handles (`live/scheduler.rs`, `live/watcher.rs`, `cooperative.rs`):** each ends with its consumer. The scheduler task selects on its consumer's `closed()` (tested); the watcher thread (pinned by `dropping_the_native_watcher_ends_the_forwarder_thread`) exits when its receiver or native watcher drops; the cooperative tail thread exits at its header deadline or when its sink is dropped. - **`forgotten` close queue:** a `HashSet` of URIs, bounded by distinct closed documents and drained by the query that holds the state once it finishes (`pull_forget.rs::forget_returns_while_a_compiler_query_runs_and_the_next_pull_applies_it`). -- **Decoration-type maps:** keyed by palette colours (a handful of heat and confidence levels) and disposed on deactivate. - **Sidecar responses and the example's response frames:** bounded by the requests in flight. Dropping a response would break the protocol. - **One analysis per trigger:** `Session::run` keeps its tested contract (`run_advances_generation_on_each_success`). The scheduler adds no memory: each event lands in exactly one trigger. diff --git a/docs/specs/LSP-PROFILER-SPEC.md b/docs/specs/LSP-PROFILER-SPEC.md index 8a9f956..9164cdc 100644 --- a/docs/specs/LSP-PROFILER-SPEC.md +++ b/docs/specs/LSP-PROFILER-SPEC.md @@ -553,6 +553,7 @@ An editor session runs for days, so nothing the library keeps grows without a bo - `ProfilerUi.dispose()` disposes everything `registerProfilerUi` created, the processes tree view and its provider (with the provider's poll and effects) included. - A debug session's output buffer, stop-state and pending resume requests are dropped when the session terminates. - The memory timeline and the autopilot's capture ledger keep their newest 120 entries, matching the core timeline. +- Heat and memory decoration types are keyed by colour. When the palette changes, the types for colours it no longer uses are disposed. - `FileLogSink` is capped: past its byte limit it continues in `.1`, so at most two capped files stay on disk. `dispose()` closes it. ### [PROF-UI-STATE] Reactive state diff --git a/packages/lsp-profiler-ui/CHANGELOG.md b/packages/lsp-profiler-ui/CHANGELOG.md index 69e8c26..fa54145 100644 --- a/packages/lsp-profiler-ui/CHANGELOG.md +++ b/packages/lsp-profiler-ui/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Changing the profiler palette no longer leaves the previous colours' decoration types allocated. - `ProfilerUi.dispose()` now disposes the processes tree view and its provider, including the provider's poll and effects. - DAP output, stop-state and pending resumes for a debug session are dropped when the session terminates. - The memory timeline and the autopilot capture ledger keep their newest 120 entries. diff --git a/packages/lsp-profiler-ui/src/memory-decorations.ts b/packages/lsp-profiler-ui/src/memory-decorations.ts index cb2b1a1..35ef0e6 100644 --- a/packages/lsp-profiler-ui/src/memory-decorations.ts +++ b/packages/lsp-profiler-ui/src/memory-decorations.ts @@ -8,7 +8,7 @@ * palette's leak, warm or memory colour by confidence ([PROF-UI-PALETTE]). */ -import { profilerPalette } from "./palette"; +import { profilerPalette, pruneToPalette } from "./palette"; import * as vscode from "vscode"; import { Logger } from "./logger"; import { recordApplied } from "./profiler-decorations"; @@ -146,6 +146,7 @@ class MemoryLayer { private typeFor(color: string): vscode.TextEditorDecorationType { const existing = this.types.get(color); if (existing !== undefined) { return existing; } + pruneToPalette(this.types); const created = vscode.window.createTextEditorDecorationType({ overviewRulerColor: color, overviewRulerLane: vscode.OverviewRulerLane.Right, diff --git a/packages/lsp-profiler-ui/src/palette.ts b/packages/lsp-profiler-ui/src/palette.ts index a8a720d..8294de5 100644 --- a/packages/lsp-profiler-ui/src/palette.ts +++ b/packages/lsp-profiler-ui/src/palette.ts @@ -33,6 +33,23 @@ const HEX_COLOR = /^#[0-9a-f]{6}$/iu; let readPalette: () => ProfilerPalette = () => DEFAULT_PALETTE; +/** + * Dispose and drop every keyed entry whose colour the current palette no + * longer paints with (`extra` lists fixed colours outside the palette). The + * palette is re-read on every render, so without this each palette change + * would leave the previous colours' decoration types allocated. + * [PROF-UI-LIFETIME] + */ +export function pruneToPalette(types: Map void }>, extra: readonly string[] = []): void { + const live = new Set([...extra, ...Object.values(profilerPalette()).filter((value) => typeof value === "string")]); + for (const [colour, type] of types) { + if (!live.has(colour)) { + type.dispose(); + types.delete(colour); + } + } +} + /** Bind host configuration; each render reads the current palette. */ export function configurePalette(read: () => ProfilerPalette): void { readPalette = read; } export function profilerPalette(): ProfilerPalette { return readPalette(); } diff --git a/packages/lsp-profiler-ui/src/profiler-decorations.ts b/packages/lsp-profiler-ui/src/profiler-decorations.ts index e630275..4de3111 100644 --- a/packages/lsp-profiler-ui/src/profiler-decorations.ts +++ b/packages/lsp-profiler-ui/src/profiler-decorations.ts @@ -12,7 +12,7 @@ * Cool (1-5%): #4a5468 — muted slate, in every host */ -import { profilerPalette } from "./palette"; +import { profilerPalette, pruneToPalette } from "./palette"; import type { SampledView } from "./sampled-view"; import * as vscode from "vscode"; import { configSection } from "./ids"; @@ -90,11 +90,14 @@ const BAR_LEN_WARM = 6; /** Max bar length for cool heat level. */ const BAR_LEN_COOL = 4; +/** The cool level's fixed colour, outside the configurable palette. */ +const COOL_HEAT_COLOR = "#4a5468"; + const heatLevels = (): HeatLevel[] => [ { minPct: HEAT_CRITICAL_PCT, color: profilerPalette().critical, barChar: "\u2588", barMaxLen: BAR_LEN_CRITICAL }, { minPct: HEAT_HOT_PCT, color: profilerPalette().hot, barChar: "\u2588", barMaxLen: BAR_LEN_HOT }, { minPct: HEAT_WARM_PCT, color: profilerPalette().warm, barChar: "\u2588", barMaxLen: BAR_LEN_WARM }, - { minPct: 1, color: "#4a5468", barChar: "\u2588", barMaxLen: BAR_LEN_COOL }, + { minPct: 1, color: COOL_HEAT_COLOR, barChar: "\u2588", barMaxLen: BAR_LEN_COOL }, ]; function heatLevelFor(pct: number): HeatLevel | undefined { @@ -149,6 +152,7 @@ const decorationTypes = new Map(); function getDecorationTypeForColor(color: string): vscode.TextEditorDecorationType { let existing = decorationTypes.get(color); if (existing !== undefined) { return existing; } + pruneToPalette(decorationTypes, [COOL_HEAT_COLOR]); existing = vscode.window.createTextEditorDecorationType({ overviewRulerColor: color, @@ -165,6 +169,11 @@ function getDecorationTypeForColor(color: string): vscode.TextEditorDecorationTy return existing; } +/** Decoration types currently allocated (e2e seam for [PROF-UI-LIFETIME]). */ +export function profileDecorationTypeCount(): number { + return decorationTypes.size; +} + // ── Public API ──────────────────────────────────────────────────────────── /** diff --git a/packages/lsp-profiler-ui/src/test/suite/decoration-palette.test.ts b/packages/lsp-profiler-ui/src/test/suite/decoration-palette.test.ts new file mode 100644 index 0000000..c8c88c4 --- /dev/null +++ b/packages/lsp-profiler-ui/src/test/suite/decoration-palette.test.ts @@ -0,0 +1,62 @@ +// Tests [PROF-UI-LIFETIME]: heat decorations are keyed by colour, and the +// palette is re-read on every render, so a palette change must not leave the +// previous colours' decoration types allocated for the rest of the session. +import * as assert from "node:assert"; +import * as vscode from "vscode"; +import type { ProfileResult } from "../../profiler-decorations"; +import { applyProfileDecorations, clearProfileDecorations, profileDecorationTypeCount } from "../../profiler-decorations"; +import { closeAllEditors, openSourceFile, setupLspTestSuite, teardownLspTestSuite } from "./test-helpers"; + +/** Palette changes a long session sees. */ +const PALETTE_CHANGES = 8; +/** Heat levels the decorations paint: critical, hot, warm and cool. */ +const HEAT_LEVELS = 4; +/** The user setting the palette is read from. */ +const PALETTE_SECTION = "lspui.profiler"; + +/** A six-digit hex colour unique to `index`. */ +function colour(index: number): string { + return `#0000${index.toString(16).padStart(2, "0")}`; +} + +/** Change the palette and paint `result`, once per change, each landing before the next. */ +async function paintUnderPalettes(result: ProfileResult, index: number): Promise { + if (index >= PALETTE_CHANGES) { return; } + await vscode.workspace + .getConfiguration(PALETTE_SECTION) + .update("palette", { critical: colour(index) }, vscode.ConfigurationTarget.Global); + await applyProfileDecorations(result); + await paintUnderPalettes(result, index + 1); +} + +suite("Profiler — decoration types follow the palette", () => { + let tmpDir = ""; + + suiteSetup(async () => { + ({ tmpDir } = await setupLspTestSuite("lspui-palette-")); + }); + + suiteTeardown(async () => { + await vscode.workspace.getConfiguration(PALETTE_SECTION).update("palette", undefined, vscode.ConfigurationTarget.Global); + clearProfileDecorations(); + await closeAllEditors(); + await teardownLspTestSuite(tmpDir); + }); + + test("palette changes never accumulate decoration types", async () => { + const { uri } = await openSourceFile(tmpDir, "palette_hot.py", "def hot():\n return 1\n"); + const result: ProfileResult = { + sessionId: "palette-session", + duration: 1, + totalSamples: 100, + outputFile: "", + hotFunctions: [], + hotLines: [{ file: uri.fsPath, line: 1, samples: 90, percentage: 90 }], + }; + await paintUnderPalettes(result, 0); + assert.ok( + profileDecorationTypeCount() <= HEAT_LEVELS, + `${String(profileDecorationTypeCount())} decoration types allocated after ${String(PALETTE_CHANGES)} palette changes`, + ); + }); +});