Skip to content

Commit 8d52b4e

Browse files
authored
feat(desktop): capture heaps on an opt-in signal (anomalyco#58317)
1 parent 64aaf2e commit 8d52b4e

6 files changed

Lines changed: 159 additions & 19 deletions

File tree

‎packages/gui-extensions/src/debug/contract.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@ export const HeapSnapshots = Ipc.define({
2626

2727
/**
2828
* Memory diagnostics, offered only in debug builds (the dev server and Beta) and off until turned on: a JSONL memory
29-
* log in the desktop logs. The debug bar's toggle turns them on and remembers it; `OPENCODE_DESKTOP_MEMORY_LOG=<seconds>`
30-
* turns them on for one launch, and the toggle cannot turn that off.
29+
* log in the desktop logs, and SIGUSR2 heap snapshots when `OPENCODE_DESKTOP_HEAP_DIRECTORY` names an absolute folder.
30+
* The debug bar's toggle turns them on and remembers it; `OPENCODE_DESKTOP_MEMORY_LOG=<seconds>` turns them on for one
31+
* launch, and the toggle cannot turn that off.
3132
*/
3233
export const MemoryDiagnostics = Ipc.define({
3334
id: "debug.memory",

‎packages/gui-extensions/src/debug/main.ts‎

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { app, contentTracing, screen, type BrowserWindow } from "electron"
22
import { Schema } from "effect"
3-
import { mkdir, readFile, writeFile } from "node:fs/promises"
3+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises"
44
import path from "node:path"
55
import { getHeapSpaceStatistics, getHeapStatistics, writeHeapSnapshot } from "node:v8"
66
import type { MainSetup } from "../sdk/main"
@@ -10,6 +10,8 @@ import { summarize, traceConfig } from "./memory-infra"
1010
import { startMemoryLog } from "./memory-log"
1111
import { debugBuild, memoryLogInterval } from "./options"
1212
import { captureServer } from "./server-heap"
13+
import { signalIncludesServer, snapshotDirectory } from "./signal"
14+
import { ProcessSignal } from "@opencode/util/process-signal"
1315

1416
/** A desktop process the manifest lists: the file written, or why there is none. */
1517
type Snapshot = { readonly process: "main" | "window"; readonly pid: number; readonly window?: number } & (
@@ -58,15 +60,12 @@ type Running = { stop?: () => void }
5860
const setup: MainSetup<typeof definition> = (ctx) => {
5961
const queue: Queue = { tail: Promise.resolve() }
6062

61-
const capture = async () => {
62-
const directory = path.join(
63-
app.getPath("downloads"),
64-
`opencode-heap-${new Date().toISOString().replace(/[:.]/g, "")}`,
65-
)
63+
const capture = async (root: string, includeServer: boolean) => {
64+
const directory = path.join(root, `opencode-heap-${new Date().toISOString().replace(/[:.]/g, "")}`)
6665

6766
// Snapshots hold prompts, file contents and credentials. Recursive, because Downloads can be missing on Linux.
6867
await mkdir(directory, { recursive: true, mode: 0o700 })
69-
ctx.log.write("info", "capturing heap snapshots", { directory })
68+
ctx.log.write("info", "capturing heap snapshots", { directory, includeServer })
7069

7170
// Measurements first: writing a heap snapshot raises the memory of the process it serializes.
7271
const before = {
@@ -85,7 +84,7 @@ const setup: MainSetup<typeof definition> = (ctx) => {
8584
// snapshot can double a process's memory, and a leaking app may not have room for every window at once. Main goes
8685
// last: writing its own heap blocks the loop that receives the others.
8786
const [serverSnapshot, windowSnapshots] = await Promise.all([
88-
captureServer(ctx.serverEndpoints.get("sidecar"), directory, ctx.scope.signal),
87+
includeServer ? captureServer(ctx.serverEndpoints.get("sidecar"), directory, ctx.scope.signal) : undefined,
8988
(async () => {
9089
const list: Snapshot[] = []
9190

@@ -102,21 +101,39 @@ const setup: MainSetup<typeof definition> = (ctx) => {
102101
(error: Error): Snapshot => ({ process: "main", pid: process.pid, error: error.message }),
103102
)
104103

105-
const snapshots = [serverSnapshot, ...windowSnapshots, main]
104+
const snapshots = await Promise.all(
105+
[...(serverSnapshot ? [serverSnapshot] : []), ...windowSnapshots, main].map(async (snapshot) => {
106+
if ("error" in snapshot) return snapshot
107+
const file = "file" in snapshot ? path.join(directory, snapshot.file) : snapshot.path
108+
109+
const bytes = await stat(file).then(
110+
(info) => info.size,
111+
() => null,
112+
)
113+
114+
ctx.log.write("info", "heap snapshot written", { file, bytes })
115+
116+
return { ...snapshot, bytes }
117+
}),
118+
)
106119
const gpu = await app.getGPUInfo("basic").catch((error: Error) => ({ error: error.message }))
107120

108121
// One readable answer to "where is the memory", per process, in MiB.
109122
await write(directory, "memory.json", {
110123
unit: "MiB",
111124
native: "summary" in native ? native.summary : native,
112-
server: "error" in serverSnapshot || !serverSnapshot.memory ? undefined : mibs(serverSnapshot.memory),
125+
server:
126+
!serverSnapshot || "error" in serverSnapshot || !serverSnapshot.memory
127+
? undefined
128+
: mibs(serverSnapshot.memory),
113129
pages,
114130
note: "native: Chromium's memory-infra dump per process, before the heap snapshots. Some allocators overlap: cc, skia, gpu and web_cache report memory that malloc, discardable or shared_memory also count. pages: what each app window's page held. server: the server's process.memoryUsage().",
115131
})
116132
await write(directory, "gpu.json", gpu)
117133
// Written last, so a script can wait for it.
118134
await write(directory, "manifest.json", {
119135
created: new Date().toISOString(),
136+
includeServer,
120137
app: {
121138
name: app.getName(),
122139
version: app.getVersion(),
@@ -144,14 +161,16 @@ const setup: MainSetup<typeof definition> = (ctx) => {
144161
return { directory, complete }
145162
}
146163

164+
const enqueue = (directory: string, includeServer: boolean) => {
165+
const run = queue.tail.then(() => capture(directory, includeServer))
166+
queue.tail = run.catch(() => undefined)
167+
168+
return run
169+
}
170+
147171
ctx.provide(HeapSnapshots, {
148172
// A window that closes meanwhile does not cancel the capture.
149-
write: () => {
150-
const run = queue.tail.then(capture)
151-
queue.tail = run.catch(() => undefined)
152-
153-
return run
154-
},
173+
write: () => enqueue(app.getPath("downloads"), true),
155174
})
156175

157176
if (!debugBuild(ctx.build)) return
@@ -160,11 +179,41 @@ const setup: MainSetup<typeof definition> = (ctx) => {
160179
const envInterval = memoryLogInterval(process.env.OPENCODE_DESKTOP_MEMORY_LOG)
161180
const stored = ctx.stores.memory
162181
const running: Running = {}
182+
const directory = process.platform === "win32" ? undefined : snapshotDirectory(process.env)
183+
let capturing = false
184+
185+
const onSignal = () => {
186+
// Signals coalesce while a capture is running; repeated signals must not fill the disk with queued dumps.
187+
if (!directory || capturing || ctx.scope.signal.aborted) return
188+
capturing = true
189+
void enqueue(directory, signalIncludesServer(process.env))
190+
.catch((error: Error) => ctx.log.write("error", "heap snapshot capture failed", { error: error.message }))
191+
.finally(() => {
192+
capturing = false
193+
})
194+
}
195+
196+
const start = () => {
197+
const stopLog = startMemoryLog(envInterval ?? 30_000, ctx.log)
198+
199+
if (!directory) return stopLog
200+
201+
// Installed the first time diagnostics turn on, and kept: a script's late signal while they are off, or while
202+
// the extension reloads, is logged and ignored instead of killing the app.
203+
ProcessSignal.install("SIGUSR2", () => ctx.log.write("warn", "heap snapshot signal ignored: diagnostics are off"))
204+
const unsubscribe = ProcessSignal.subscribe("SIGUSR2", onSignal)
205+
ctx.log.write("info", "heap snapshot signal enabled", { pid: process.pid, signal: "SIGUSR2", directory })
206+
207+
return () => {
208+
unsubscribe()
209+
stopLog()
210+
}
211+
}
163212

164213
const sync = () => {
165214
const on = envInterval !== undefined || stored.value
166215

167-
if (on && !running.stop) running.stop = startMemoryLog(envInterval ?? 30_000, ctx.log)
216+
if (on && !running.stop) running.stop = start()
168217

169218
if (on || !running.stop) return
170219
running.stop()
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { expect, test } from "bun:test"
2+
import path from "node:path"
3+
import { signalIncludesServer, snapshotDirectory } from "./signal"
4+
5+
test.each([
6+
[undefined, false],
7+
["relative", false],
8+
["", false],
9+
[path.resolve("heaps"), true],
10+
] as const)("signal snapshots require an absolute destination (%s)", (directory, enabled) => {
11+
expect(snapshotDirectory({ OPENCODE_DESKTOP_HEAP_DIRECTORY: directory })).toBe(enabled ? directory : undefined)
12+
})
13+
14+
test.each([undefined, "", "0", "true", "1"])("signal server snapshots require the explicit 1 opt-in (%s)", (value) => {
15+
expect(signalIncludesServer({ OPENCODE_DESKTOP_HEAP_INCLUDE_SERVER: value })).toBe(value === "1")
16+
})
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import path from "node:path"
2+
3+
/** Where SIGUSR2 writes heap snapshots while memory diagnostics are on: a caller-chosen absolute folder, or none. */
4+
export function snapshotDirectory(env: NodeJS.ProcessEnv) {
5+
const directory = env.OPENCODE_DESKTOP_HEAP_DIRECTORY
6+
7+
return directory && path.isAbsolute(directory) ? directory : undefined
8+
}
9+
10+
/** Server heap serialization blocks all of its sessions; signal captures require a separate opt-in. */
11+
export function signalIncludesServer(env: NodeJS.ProcessEnv) {
12+
return env.OPENCODE_DESKTOP_HEAP_INCLUDE_SERVER === "1"
13+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { expect, test } from "bun:test"
2+
3+
// Windows does not deliver POSIX user signals.
4+
test.skipIf(process.platform === "win32")(
5+
"an installed signal survives absent and removed subscribers",
6+
async () => {
7+
const child = Bun.spawn(
8+
[
9+
process.execPath,
10+
"-e",
11+
`
12+
import { ProcessSignal } from ${JSON.stringify(new URL("./process-signal.ts", import.meta.url).pathname)};
13+
const deadline = setTimeout(() => process.exit(2), 10000);
14+
let ignored = 0;
15+
ProcessSignal.install("SIGUSR2", () => {
16+
console.log("ignored");
17+
if (++ignored === 2) {
18+
clearTimeout(deadline);
19+
process.exit(0);
20+
}
21+
const remove = ProcessSignal.subscribe("SIGUSR2", () => {
22+
console.log("captured");
23+
remove();
24+
process.kill(process.pid, "SIGUSR2");
25+
});
26+
process.kill(process.pid, "SIGUSR2");
27+
});
28+
process.kill(process.pid, "SIGUSR2");
29+
`,
30+
],
31+
{ stdout: "pipe", stderr: "pipe" },
32+
)
33+
expect(await new Response(child.stderr).text()).toBe("")
34+
expect(await child.exited).toBe(0)
35+
expect((await new Response(child.stdout).text()).trim().split("\n")).toEqual(["ignored", "captured", "ignored"])
36+
},
37+
15000,
38+
)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export * as ProcessSignal from "./process-signal.js"
2+
3+
const handlers = new Map<NodeJS.Signals, Set<() => void>>()
4+
5+
/** Install once at process startup. Removing subscribers never restores the signal's default action. */
6+
export function install(signal: NodeJS.Signals, unavailable: () => void) {
7+
if (handlers.has(signal)) return
8+
const listeners = new Set<() => void>()
9+
handlers.set(signal, listeners)
10+
process.on(signal, () => {
11+
if (!listeners.size) return unavailable()
12+
listeners.forEach((listener) => listener())
13+
})
14+
}
15+
16+
/** Subscribe only to an installed signal. The returned cleanup removes this subscriber, not the process handler. */
17+
export function subscribe(signal: NodeJS.Signals, listener: () => void) {
18+
const listeners = handlers.get(signal)
19+
listeners?.add(listener)
20+
return () => {
21+
listeners?.delete(listener)
22+
}
23+
}

0 commit comments

Comments
 (0)