opencode icon indicating copy to clipboard operation
opencode copied to clipboard

serve: heap grows ~16 MiB per plugin file reload regardless of plugin cleanup timeout

Open HtoZ27 opened this issue 4 days ago • 18 comments

Description

On a restarted, otherwise idle OpenCode Desktop service (RSS ~513 MiB at start), reloading a local plugin file grows the server heap by about 16 MiB per reload. The growth is the same for two plugin builds whose only difference is the timeout applied to the plugin dispose cleanup step (5 s vs 8000 ms).

This is a measurement report, not a fix proposal. The root cause is not identified and no solution is suggested.

Measurement

  • Host: OpenCode Desktop 2.4.2, opencode-cli serve --service, Linux.
  • All other projects were closed before the measurement; a single project was open.
  • Protocol: 24 samples, alternating fixed / baseline, one plugin-file reload per sample, 12 s wait after each reload.
  • GC rule: before every heapUsed sample a WeakRef canary was created and Bun.gc(true) forced until the canary cleared (max 50 attempts x 20 ms). All 24 canaries cleared in 1 attempt; no sample was discarded.
# fixed (MiB) baseline (MiB)
1 220.03 228.20
2 236.83 246.37
3 252.25 261.02
4 270.96 279.94
5 287.34 296.34
6 304.51 311.23
7 317.98 326.17
8 334.11 342.17
9 349.35 357.87
10 365.12 373.13
11 381.17 387.14
12 396.38 403.90
  • Least-squares slope: fixed +15.9956 MiB/sample, baseline +15.8269 MiB/sample (difference ~1%).
  • Cleanup stats: fixed variant abandoned=0 on every reload, baseline abandoned=1 on every reload (~5.0-5.4 s).

Plugins

Only one local plugin was loaded (two builds of the same plugin, alternating). No other plugins were configured.

Steps to reproduce

  1. Close all other projects and start a clean OpenCode Desktop service with one project.
  2. Build two bundles of a local plugin whose only difference is the plugin dispose cleanup timeout.
  3. Alternate writing the two bundles to the plugin file; the host watcher reloads the plugin on each write.
  4. After each reload, wait 12 s, force GC with a WeakRef canary, and record process.memoryUsage().heapUsed.

Notes

  • Two V8 heap snapshots were captured on the earlier, busier host. They contain session text and are therefore not attached here.
  • Related reports: #20695, #52041.

OpenCode version

2.4.2 desktop (opencode-cli serve --service).

Operating System

Linux (Linux Mint 22.3).

HtoZ27 avatar Nov 28 '26 07:11 HtoZ27

Thanks for the careful measurements. I tried to reproduce this on the released 2.4.2 CLI on Linux and the server heap did not grow.

What I tried: opencode serve with one project. The only plugin was a local file at .opencode/plugins/leak/index.js, reloaded by the built-in watcher each time I overwrote it. About 9 s after each setup, the plugin forced Bun.gc(true) and recorded process.memoryUsage() from inside the server. Results, 6–14 reloads each:

  • A minimal plugin: heapUsed stayed between 115 and 118 MiB.
  • The same plugin with 1.7 MB of generated code, either in the same file or in an imported sibling module: flat at about 122–124 MiB.
  • A plugin holding a ~16 MiB array, captured by ctx.tool.transform, ctx.session.hook("fork"), ctx.tool.hook("execute.before") and a ctx.event.subscribe loop: flat at about 133.5 MiB. The array stayed live only once, so the old instance was freed on each reload. This held with a quick cleanup, with a cleanup slow enough to overrun, and with an SSE client connected to /api/event.

So a plain reload doesn't seem to leak by itself. Something specific to your plugin or setup is probably needed. These would help:

  1. Your plugin: which ctx APIs it uses (tools, hooks, event subscriptions, ctx.session.*, storage, providers/models, MCP, etc.), whether it's one bundled file or a directory with a package.json, how it's configured (auto-discovered or in plugins in opencode.json), and roughly how big the bundle is. A trimmed-down plugin that still shows the growth would be ideal.
  2. A minimal plugin: does the growth still happen with one that does nothing (export default { id: "x", setup() {} })? If not, adding your plugin's registrations back one at a time would show which one keeps the old instance alive.
  3. The heap snapshots: a summary of what grows between two snapshots taken a few reloads apart, without any session text. For example, the top constructors by retained size in the comparison view, and the retainer path of one leaked object.
  4. Desktop vs CLI: whether it also happens with a standalone opencode serve (CLI 2.4.2), not only in the Desktop-managed --service process.

Related: #54140 reports plugin instances piling up across config reloads with no teardown, which could be the same mechanism if your setup triggers config reloads too.

You can reply here with the details, or edit the issue and leave a comment once it's updated.

opencodejr[bot] avatar Nov 28 '26 07:11 opencodejr[bot]

I reproduced this and the claim holds. I reloaded a local plugin with a ~1.4 MiB bundle-like entrypoint through the supervisor 6 times, forcing GC (Bun.gc + WeakRef canary) before each sample: heapUsed went 85.9 -> 102.5 MiB, about +1.8 MiB per reload, linear. The old module objects themselves are collected (canaries clear, only the latest generation stays alive), so nothing in the plugin registry or supervisor is keeping the old generations around.

The retention looks like it lives below opencode, in Bun module handling. A minimal Bun repro with no opencode code (plain import() + delete require.cache, new source bytes each reload) grows the same ~2 MiB per reload for the same source. Two things I ruled out:

  • Rewriting the entrypoint with byte-identical content does not grow the heap, so it tracks distinct source content, not reload count alone.
  • Loading each generation under a fresh ?__opencode_reload= specifier (the approach the node loader already uses) does not fix it either: new content still retains roughly its size. Only already-seen content reuses the retained artifact.

So a small patch to the plugin loader cannot address this; it likely needs an upstream Bun fix for retained compiled modules after cache invalidation, or a loader redesign. I have the repro scripts if they are useful.

fanyzp avatar Nov 28 '26 08:11 fanyzp

Independent confirmation from the reporter's setup.

I closed all other projects and restarted the Desktop-managed service (RSS ~513 MiB at start). I then ran a 24-sample alternating A/B (12 per variant), one plugin-file reload per sample, with a 12 s wait after each reload. Before every heapUsed sample a WeakRef canary was created and Bun.gc(true) forced until the canary cleared (max 50 attempts x 20 ms). All 24 canaries cleared in 1 attempt; no sample was discarded.

  • Variant A: 8000 ms timeout for the plugin dispose cleanup step.
  • Variant B: baseline 5 s timeout for that step.
  • Least-squares slope: A +15.9956 MiB/sample, B +15.8269 MiB/sample (difference ~1%).
  • Cleanup stats: A abandoned=0, B abandoned=1 on every reload.

So the growth is independent of plugin cleanup behavior. This agrees with @fanyzp's finding that a minimal Bun repro (plain import() + delete require.cache, new source bytes each reload) grows by roughly the source size, while byte-identical rewrites do not. My earlier in-tree attempts (schema cache, session cap, event dedup, cleanup timeout) all failed the pre-registered slope criterion.

Answers to the bot's questions:

  • Plugin: one self-contained bundled file (~2.4 MB), auto-discovered from .opencode/plugins/, not a directory with a package.json.
  • ctx APIs used: tool.transform / tool.hook, session.get/list/hook, event.subscribe, permission and skill hooks, and storage/state paths. No MCP servers and no provider/model calls initiated by the plugin itself.
  • Observed in the Desktop-managed --service process; standalone opencode serve not yet tested.
  • Heap snapshots were captured but contain session text, so they are not attached. A text-free retained-size comparison could be produced if needed.

@fanyzp: could you share the minimal Bun repro scripts you mentioned, and say whether you opened an issue in oven-sh/bun? That would let us consolidate the upstream report.

This is a measurement report only; no fix is proposed.

HtoZ27 avatar Nov 28 '26 09:11 HtoZ27

Thanks for the extra details, and thanks to @fanyzp for the Bun-level analysis. I tried again, closer to your setup, and couldn't reproduce growth of anything like 16 MiB per reload on 2.4.2.

What I ran: a standalone opencode serve (CLI 2.4.2, Linux) with one project. The only plugin was an auto-discovered file in .opencode/plugins/: a ~1.4 MB bundle built with bun build from lodash, moment, zod, rxjs and acorn, with a unique marker on every write so each reload had new source bytes. About 9 s after each setup, the plugin forced Bun.gc(true) and logged heapUsed from inside the server. I wrote a new version every 12 s.

  • Bundle only, 25 reloads: heapUsed went from 76.2 to about 79 MiB, roughly 0.1–0.2 MiB per reload.
  • Bundle plus tool.transform, tool.hook, session.hook, session.list, storage.set and an event.subscribe loop aborted in cleanup, 10 reloads: 80.1 to 80.6 MiB.
  • Plain Bun 1.4.2, no OpenCode code, same source: re-importing after delete require.cache grew about 0.5 MiB per reload with a plain specifier, and about 2.6 MiB per reload with a fresh ?v= query.

So I do see a small amount kept per distinct compiled source, which fits what @fanyzp describes. Inside the server, though, it came to a tenth of a MiB or so per reload, not 16 MiB.

I haven't tested the process Desktop manages (--service), your actual 2.4 MB bundle, or permission and skill hooks. These would help narrow the gap:

  • Does a standalone opencode serve (CLI 2.4.2) show the same ~16 MiB slope with your bundle?
  • Does it still grow at that rate if you strip the plugin down to export default { id: "x", setup() {} } appended to the same bundled code, so no ctx APIs are used?
  • @fanyzp, if you can share the minimal Bun repro scripts, or link an oven-sh/bun issue if you open one, that would help separate Bun's part from OpenCode's.
  • A text-free retained-size comparison between two heap snapshots a few reloads apart (top constructors by retained size).

You can reply here with any of these.

opencodejr[bot] avatar Nov 28 '26 13:11 opencodejr[bot]

Thanks for the careful replication. A few concrete differences and the text-free snapshot comparison you asked for.

Runtime difference. Our host is the Desktop-managed CLI 2.4.2 running with --service. The Bun available in this lab is 1.3.14, whereas your test used Bun 1.4.2. My own minimal Bun repro on 1.3.14 (plain import() plus delete require.cache with fresh source bytes, and a same-path CJS variant) did not reproduce growth: slopes were -0.04 MiB/generation with a valid WeakRef canary. So the effect may be specific to the older runtime in the Desktop bundle, or to the service wrapper, not to plain Bun 1.4.2.

Our bundle. One auto-discovered .opencode/plugins/tawassul.js, ~2.4 MB, built with bun build, using tool.transform/tool.hook, session.*, event.subscribe, permission and skill hooks, plus local state/storage paths. An isolated standalone opencode serve 2.4.2 run with this exact bundle has not produced an admissible slope yet, so I am not claiming one here.

Text-free constructor comparison. These are two heap snapshots from the same service process, taken during the reload experiments about 1h43m apart. The numbers are aggregated self sizes by constructor name, not retained sizes (I have not computed a dominator tree). String node names are collapsed to <string> so no session text is included.

Constructor Snapshot A Snapshot B Delta
<string> 94.09 MiB 103.86 MiB +9.78
ModuleRecord 95.19 MiB 97.52 MiB +2.33
Object 66.60 MiB 67.96 MiB +1.37
Cell Butterfly 48.37 MiB 49.45 MiB +1.08
Function 35.97 MiB 38.19 MiB +2.22
FunctionCodeBlock 24.06 MiB 32.82 MiB +8.76
ArrayBuffer 0.00 MiB 32.00 MiB +32.00
system / JSLexicalEnvironment 25.17 MiB 25.87 MiB +0.70

Totals: reachable 487.77 -> 545.66 MiB (+57.89); unreachable 285.27 -> 285.31 MiB (+0.04). The unreachable bucket is flat and forcing Bun.gc(true) does not reclaim the 24 old TawassulContext nodes, so I do not treat it as collectable garbage. ModuleRecord remains the largest named contributor, consistent with the module-graph retention you and @fanyzp describe.

Bun version comparison. I downloaded Bun 1.4.2 and ran the same two minimal repro scripts under both runtimes (20 generations, fresh source bytes, valid WeakRef canary every sample):

Runtime Distinct ESM filenames Same-path CJS + cache delete
Bun 1.3.14 -0.040 MiB/generation -0.042 MiB/generation
Bun 1.4.2 +0.013 MiB/generation +0.009 MiB/generation

The 1.4.2 run shows a small positive retention, closer in sign to your ~0.5 MiB/generation observation, but the magnitude is still far below both your result and the ~16 MiB/reload slope in my Desktop service. So the runtime version changes the sign but does not explain the magnitude.

@fanyzp: could you share the minimal repro scripts or link the oven-sh/bun issue if you opened one? That would let us test the exact repro under both Bun versions and settle the version boundary.

This is a measurement report; no fix is proposed.

HtoZ27 avatar Nov 28 '26 14:11 HtoZ27

Thanks for the snapshot comparison and the cross-runtime runs. Here's what stands out.

Your 24 old TawassulContext nodes matter most. If old plugin context objects are still reachable after Bun.gc(true), the old plugin instances themselves are being kept alive. That's a different, much larger effect than the small per-module creep I measured in plain Bun (which your own Bun runs now put at about zero). It would also fit the size of your deltas: +32 MiB of ArrayBuffer, plus FunctionCodeBlock and <string> growth that is several times your bundle size.

What would pin it down is the retainer path of one old TawassulContext in snapshot B, from that node up to a GC root. Only constructor and property names are needed, no string values. It should show whether the context is held by something in OpenCode (a tool or hook registry, an event subscriber, a session or permission/skill hook list, the plugin host) or by something in the plugin (a module-level variable, a timer, an un-aborted stream, a listener on a global).

On the runtime: the Bun you have installed in the lab may not be the runtime the Desktop service runs. The plugin runs inside the opencode-cli binary. Logging Bun.version from inside the plugin would show which runtime that process actually uses. My earlier in-server measurements were also taken in-process, from a plugin running under opencode serve 2.4.2.

Still open: whether a standalone opencode serve 2.4.2 with your bundle shows the slope. If it only happens under the Desktop-managed --service process, that is useful to know too, because then something specific to that process is involved.

If you can share the retainer path, or a stripped-down plugin that still leaves old contexts alive, I'll try again with it.

opencodejr[bot] avatar Nov 28 '26 14:11 opencodejr[bot]

Correction and the two measurements you asked for.

Bun version: my earlier framing was wrong. The plugin does not select or pin a runtime. I logged Bun.version from a small plugin running inside the Desktop-managed opencode-cli 2.4.2 process: it reports 1.4.4 (the CLI binary also contains the string bun-v1.4.4). The 1.3.14 binary in my lab is only the standalone Bun used to build and run the minimal repro scripts; it is not the runtime of the service. So your 1.4.2 run and our service are close, not a version-boundary story.

Standalone opencode serve 2.4.2 with our actual bundle: yes, it grows. I ran an isolated serve with symlinked dependencies so our exact ~2.4 MB auto-discovered bundle loaded, rewrote the plugin file with fresh bytes every 12 s, and forced location.reload() after each write. Twenty reloads, heapUsed logged from inside the server 9 s after each setup: 136.24 -> 289.22 MiB, least-squares slope +7.27 MiB/reload (deltas are noisy, +3 to +10 MiB typical, with two spikes). This is directional, not acceptance-grade: this particular probe had no WeakRef GC canary, so I am not claiming it meets the strict criterion. It is clearly larger than the ~0.1-0.2 MiB/reload you saw with the synthetic bundle, so bundle content/size appears to matter.

Retainer path. In snapshot B, 24 of 26 TawassulContext nodes are unreachable in the heap graph (reachable=0), so they have no path to a GC root at all; there is no retainer path to report for them. The two reachable ones have these text-free paths:

(GC roots) --internal:--> TawassulContext
(GC roots) --internal:--> Function --> system / JSLexicalEnvironment --context:tawaCtx--> TawassulContext

No old tool/hook/permission registry appears as a retainer for a live context, and the old contexts have no retainer at all. Forced Bun.gc(true) does not collect them, which is why I treated them as snapshot-generator overhead rather than a plugin-held leak.

Still open: the stripped-plugin test (bundle only, no ctx APIs). I have not run that yet, so I am not attributing the slope to any particular hook.

Measurement report only; no fix is proposed.

HtoZ27 avatar Nov 28 '26 14:11 HtoZ27

Follow-up on the stripped-plugin test you asked for.

I kept the same ~2.4 MB source bytes but made the host-visible plugin a no-op: the auto-discovered file imports the bundle as core.js and exports export default { id: "stripped", setup() {} }, so no ctx API is called at all. Same isolated opencode serve 2.4.2 setup, 12 s between generations, location.reload() after each rewrite, heapUsed logged from inside the process.

Variant Samples First -> last OLS slope
Full plugin (all ctx APIs) 20 136.24 -> 289.22 MiB +7.27 MiB/reload
Stripped plugin (no ctx APIs) 19 159.62 -> 350.75 MiB +9.65 MiB/reload

So stripping every ctx hook did not stop or reduce the growth in this setup; if anything the stripped run was steeper. That argues against a retained tool/hook/session registry and is consistent with retention of the distinct compiled source itself. Caveats: these are two separate isolated runs with different starting heaps, so compare slopes, not absolute values; and neither probe had a strict WeakRef GC canary, so both are directional rather than acceptance-grade. The earlier Desktop-service A/B with a strict canary remains the stronger measurement: ~16 MiB/sample regardless of cleanup timeout.

Still useful from @fanyzp: the exact repro scripts, or an oven-sh/bun issue link, so we can test the same script under the 1.4.4 runtime that is actually embedded in the CLI.

Measurement report only; no fix is proposed.

HtoZ27 avatar Nov 28 '26 14:11 HtoZ27

Thanks for the extra measurements. They let me match your setup much more closely, but I still can't reproduce growth of several MiB per reload on 2.4.2.

What I ran: a standalone opencode serve 2.4.2. Its embedded runtime reports Bun 1.4.4, the same as your service. I copied your stripped layout:

  • a ~3.4 MB bun build bundle of real libraries (lodash, moment, zod, rxjs, acorn, three, date-fns, @babel/parser), rewritten with new bytes each generation as .opencode/lib/core.js;
  • a thin auto-discovered .opencode/plugins/thin.js that imports it and calls no ctx API. It only logs heapUsed from inside the server after forcing GC.

Results:

  • 12 reloads by rewriting the files: 82.4 → 83.7 MiB, about 0.1 MiB per reload.
  • 10 calls to POST /api/location/reload, plugin unchanged: 83.7 → 96.7 MiB. The first call added about 5.6 MiB, then each call added less (+2.1, +0.7, … +0.2), flattening out rather than growing in a straight line.
  • 12 rounds of rewrite plus location/reload, as in your last runs: 97.4 → 101.1 MiB, about 0.3 MiB per round.

So with the same runtime, the same layout and a larger bundle, I don't see your +7 to +16 MiB per reload. What's left seems specific to the code in your bundle. These would help:

  • A bundle that shows the slope and can be shared. Even your core.js with the business logic replaced by the same third-party dependencies, if those alone still grow, would let someone measure it directly.
  • The list of large third-party packages bundled into core.js, and whether it uses anything unusual at load time: top-level await, WASM, workers, native addons, new Function/eval, or large inline data. The +32 MiB of ArrayBuffer in your snapshot hints at a large binary buffer allocated on each load.
  • A run with the WeakRef canary in the standalone setup, so the standalone slope is as solid as your Desktop one.

You can reply here with any of these.

opencodejr[bot] avatar Nov 28 '26 15:11 opencodejr[bot]

Answering the bundle questions, including a negative result.

What is in core.js. The bundle is our own source plus two bundled third-party packages: web-tree-sitter (with its Emscripten runtime) and confbox. @opencode/plugin, zod and the transitive OpenCode packages stay external, plus node builtins. There are no workers, native addons or new Function in our code; the two eval( sites are Emscripten glue for asm constants, and Parser.init() is lazy rather than called at load.

The 32 MiB ArrayBuffer has a concrete source but is not the slope driver. Inside the bundled Emscripten glue, module evaluation calls initMemory(), which creates new WebAssembly.Memory({ initial: 33554432 / 65536 }) — exactly 32 MiB. That matches the +32 MiB ArrayBuffer delta between our snapshots. To test causality I made a lab-only copy of the stripped layout with that single initMemory(); call replaced by void 0; (verified: no remaining call) and reran the same 20-reload procedure:

Variant OLS slope
Stripped bundle, original core +9.65 MiB/reload
Stripped bundle, initMemory() disabled +9.85 MiB/reload

So the allocation explains the snapshot delta but disabling it does not reduce the per-reload slope. I am not claiming the WASM memory as the cause. This also means I do not have an in-tree fix to propose, and I will not change the build to externalize web-tree-sitter (that would break the self-contained global bundle) without evidence that it helps.

Still outstanding: @fanyzp's exact repro scripts or an oven-sh/bun issue, and a standalone run with the strict WeakRef canary. Our stronger evidence remains the Desktop --service A/B with the canary (~16 MiB/sample, independent of cleanup timeout).

Measurement report only; no fix is proposed.

HtoZ27 avatar Nov 28 '26 16:11 HtoZ27

Thanks for the details on core.js and for testing the initMemory() hypothesis. I tried again with those packages and still can't reproduce the growth.

Plain Bun 1.4.2: I bundled web-tree-sitter (0.27.2, 0.25.10 and 0.22.6) with confbox using bun build --target bun, then re-imported each bundle 12 times with new bytes after delete require.cache.

  • Without init: heapUsed stayed flat for every version, under 1 MiB.
  • With Parser.init() and new Parser() at import, so a 32 MiB WASM memory is created on every load: flat at about 65.5 MiB.
  • Process hooks: process.listenerCount for uncaughtException and unhandledRejection stayed at 0, so the Emscripten glue doesn't seem to add process-level hooks that would keep old copies alive.

Inside opencode serve 2.4.2 (embedded Bun 1.4.4): I used the init variant as .opencode/lib/core.js, rewritten every 12 s, imported by a thin auto-discovered plugin with an empty setup. Over 11 generations heapUsed stayed between 139 and 142 MiB, with no trend.

One difference: in web-tree-sitter 0.27.2, initMemory() runs only inside the async factory that Parser.init() calls, not when the module is imported. You see it run on import, so your build may differ from mine, for example a different web-tree-sitter version, a vendored copy of its glue, or different build options.

So far the slope shows up only with your bundle. What would let someone measure it directly:

  • the web-tree-sitter version and the bun build command or options you use;
  • ideally, a core.js that still shows the slope with your own code stubbed out (just the bundled web-tree-sitter and confbox plus whatever top-level code is left), shared as a file or gist;
  • @fanyzp's minimal repro scripts, if they can be shared.

You can reply here with any of these.

opencodejr[bot] avatar Nov 28 '26 16:11 opencodejr[bot]

The version difference looks important: you tested web-tree-sitter 0.27.2, 0.25.10 and 0.22.6, but our installed version is 0.26.13 (declared ^0.26.13, resolved 0.26.13). That is the one version band you did not test, and it is exactly the glue where initMemory() runs during module evaluation rather than inside Parser.init().

Build used for the live plugin. Entry ./src/index.ts, via bun build-v2.mjs:

  • Bun.build({ target: "node", format: "esm", sourcemap: "none", splitting: false, naming: { entry: "index.js" } }) for the project bundle, with @opencode/plugin, zod and transitive OpenCode packages external.
  • The global/live bundle uses the same options but external: [], plus two plugins: one shims @opencode/plugin to @opencode/plugin/promise/plugin, the other replaces non-English zod locale files with the English one. The auto-discovered .opencode/plugins/tawassul.js is that self-contained global build.

Shareable core. I copied the exact bundle to /home/htoz/.opencode/core-for-upstream.js (2,420,084 bytes). It contains no home-directory paths and no token strings, so it can be attached or pushed as a gist. I cannot publish it from here because the GitHub token expired; the user can do it.

We still do not have a proven in-tree cause: disabling initMemory() in a lab copy left the slope unchanged (+9.85 vs +9.65 MiB/reload). A test with web-tree-sitter 0.26.13, or a run against the shared core.js, is the cleanest next step.

Measurement report only; no fix is proposed.

core-for-upstream.js

HtoZ27 avatar Nov 28 '26 17:11 HtoZ27

Thanks for attaching the bundle. With it I found where the growth comes from, and it's in the plugin code, not in OpenCode.

The cause. When core-for-upstream.js is evaluated, this top-level block runs (around line 45901, next to _firecrawlBreaker / registerTempFile):

if (typeof process !== "undefined") {
  process.once("exit", () => { for (const file of _tempOutputs) { … } })
}

Every reload evaluates a fresh copy of the module, so each reload adds another exit listener on the global process. That listener's closure keeps that copy's whole module graph alive, and nothing ever removes it. OpenCode drops its own references to the old plugin on reload, but it can't free a module that the plugin has attached to the global process.

Measurements:

  • Plain Bun 1.4.2, no OpenCode code, importing your file 10 times with new bytes: heapUsed 21.6 → 66.9 MiB (about +4.7 MiB per import), and process.listenerCount("exit") 1 → 10. With only that block disabled: flat at about 26.4 MiB after the first import, with 0 exit listeners.
  • Inside opencode serve 2.4.2, with your bundle imported by a thin plugin with an empty setup: 83.4 → 103.7 MiB over 6 reloads, with one more exit listener per reload. With the block disabled: flat at 106–108 MiB, and the listener count stopped rising.

This also explains your earlier results: the growth followed new source bytes, didn't depend on ctx APIs or the cleanup timeout, and old TawassulContext objects survived forced GC.

Possible fixes in the plugin:

  • Register the listener once per process, behind a guard on globalThis (for example a Symbol.for(...) key).
  • Or add it in setup and remove it with process.removeListener in the cleanup function you return.
  • registerExitCleanup / unregisterExitCleanup (around lines 4692–4733) has a similar gap: it adds process.on("exit", cleanup) but removes only the SIGTERM/SIGINT handlers.

Since OpenCode is doing what it's designed to do here, I'm not treating this as an OpenCode bug. A warning from OpenCode when a reloaded plugin leaves global listeners behind would be a feature request. If the growth continues after removing those listeners, please reply here with new numbers.

opencodejr[bot] avatar Nov 28 '26 18:11 opencodejr[bot]

Comprehensive status from our side, including the corrections and the negative results. This is a measurement report only; I am not claiming a fix.

1. Runtime correction. The plugin cannot select or pin a runtime. I logged Bun.version from inside the Desktop-managed opencode-cli 2.4.2 process: 1.4.4 (the binary also contains bun-v1.4.4). The Bun 1.3.14 in my lab is only a standalone binary used for build and repro scripts, not the service runtime. My earlier suggestion that the service might be using an old runtime was wrong.

2. Cleanup timeout is not the driver. Clean-host alternating A/B, 24 samples with a strict WeakRef GC canary before every sample (all 24 cleared in one attempt): 8000 ms for the plugin dispose step gave +15.9956 MiB/sample, baseline 5 s gave +15.8269 MiB/sample (~1% difference). Cleanup behavior (abandoned=0 vs abandoned=1) did not change the slope. In-tree attempts (schema cache, session cap, event dedup, timeout change) all failed the pre-registered slope criterion and were reverted.

3. ctx APIs are not the driver. Same isolated opencode serve 2.4.2 setup, 12 s between rewrites of the plugin file, location.reload() after each write, heapUsed logged from inside the process:

Variant Samples First → last OLS slope
Full bundle, all ctx APIs 20 136.24 → 289.22 MiB +7.27 MiB/reload
Same bytes, setup() {} and no ctx call 19 159.62 → 350.75 MiB +9.65 MiB/reload

Stripping every tool/hook/session API did not reduce growth. These two probes had no GC canary, so they are directional; the Desktop A/B in (2) is the stronger measurement.

4. Bundle contents and the 32 MiB ArrayBuffer. The bundle contains our source plus bundled web-tree-sitter 0.26.13 (Emscripten glue) and confbox; @opencode/plugin, zod and transitive OpenCode packages are external. There are no workers, native addons or new Function; the two eval( sites are Emscripten asm constants and Parser.init() is lazy. At module evaluation the glue calls initMemory(), allocating WebAssembly.Memory of 33,554,432 bytes, matching the +32 MiB ArrayBuffer in our snapshot. To test causality I made a lab-only copy with that single initMemory(); call replaced by void 0; (verified no remaining call): slope +9.85 vs +9.65 MiB/reload. So it explains the snapshot delta but not the per-reload slope.

5. Your global-listener finding. You identified a top-level process.once("exit", ...) that adds one listener per reload. I fixed both such sites in-tree: src/tools/web.ts and src/infra/file-lock.ts now register exit cleanup once per process behind Symbol.for(...) keys, and unregisterExitCleanup removes the exit listener during teardown. npm run verify passes. A strict-canary A/B (20 reloads per variant, same procedure) gave:

Variant exit listeners All other process events OLS slope
Before fix 3 → 41 constant +5.0813 MiB/reload
After fix 3 → 3 constant +5.0503 MiB/reload

All 40 canaries cleared. So the listener leak was real and is now fixed, but it does not explain the heap slope (0.6% difference). I am keeping the change as a correctness fix, not as a memory fix.

6. Snapshot facts, text-free. In snapshot B, 24 of 26 TawassulContext nodes are unreachable (no path to a GC root), so no retainer path exists for them. The two reachable contexts are held only by (GC roots) --internal:--> TawassulContext and (GC roots) --internal:--> Function → JSLexicalEnvironment --context:tawaCtx--> TawassulContext. Reachable self size rose 487.77 → 545.66 MiB; unreachable stayed flat (285.27 → 285.31). Forced Bun.gc(true) does not collect the old contexts.

7. Bun version comparison. Identical 20-generation repro (plain import() plus delete require.cache, fresh source bytes, valid canary): Bun 1.3.14 gave -0.040 / -0.042 MiB/generation (ESM/CJS); Bun 1.4.2 gave +0.013 / +0.009. The version changes the sign but not the magnitude, so it does not explain ~16 MiB/reload.

Conclusion. No in-tree change we tested reduced the heap slope. What remains fits @fanyzp's observation that Bun retains a compiled artifact per distinct source content even after module objects are collected. The listener fix is useful but orthogonal. @fanyzp's minimal repro scripts (or an oven-sh/bun issue) would be the most valuable next input so we can test the exact case under Bun 1.4.4.

No fix is proposed and no success is claimed.

HtoZ27 avatar Nov 28 '26 18:11 HtoZ27

Thanks for the thorough summary, and for fixing the two exit-listener sites (41 listeners after 20 reloads, about two per reload, fits those two sites).

One point from my last run matters for what's left. Disabling only the top-level process.once("exit") block made the growth disappear completely in my tests, both in plain Bun 1.4.2 (21.6 → 66.9 MiB over 10 imports before, about 0.01 MiB per import after) and inside opencode serve 2.4.2 (+3.4 MiB per reload before, flat at 106–108 MiB after). In those runs your module was only imported: a thin plugin with an empty setup loaded core.js, so your tawassul setup never ran. So for module evaluation alone I don't see Bun keeping anything per new source. The remaining +5 MiB is most likely something that happens once your plugin is set up.

To narrow it down:

  1. Which variant did the after-fix A/B use: the full plugin with its real setup, or the stripped setup() {}? If it was the full plugin, please run the stripped variant on the fixed bundle. If that one is flat, the leak is in setup or teardown.
  2. Run the plain-Bun loop on the fixed bundle: write new bytes, delete require.cache, import(), Bun.gc(true), log heapUsed. If it's flat, the Bun-artifact explanation is ruled out for your bundle.
  3. Other process-wide registrations created during setup that would keep a generation alive the same way. Check each against your cleanup function:
    • module-level or setup-time setInterval/setTimeout that isn't cleared (for example the attemptRun interval around line 12449, and the 1e4 ms / periodic timers in classes created during setup);
    • listeners on process, process.stdout/stderr, or other global emitters;
    • globalThis properties or Symbol.for(...) registries holding objects created in setup;
    • child processes or sockets left open after cleanup. Logging process.listenerCount for every event, plus the number of active handles (for example process.getActiveResourcesInfo?.() if available), at each reload would show which one rises.
  4. If you can attach the fixed bundle, I can run the same two measurements on it (import-only and full setup) and compare.

@fanyzp's minimal scripts would still help. In my plain-Bun runs, the only sizable per-source growth (about 2.6 MiB per import of a 1.4 MB bundle) came from loading each version under a fresh ?v= specifier. With a plain path, the way OpenCode 2.4.2 loads plugins, it was about 0.5 MiB per import for a 1.4 MB bundle, and none at all for your bundle once the listener was removed.

opencodejr[bot] avatar Nov 28 '26 19:11 opencodejr[bot]

Closing this for now, since the details we were waiting on haven't arrived. Thanks for the careful measurements throughout.

Where things stand: on opencode serve 2.4.2, the growth I could measure with your bundle came from the top-level process.once("exit") listener added each time the module was evaluated. With that listener disabled, the heap stayed flat both in plain Bun and inside the server, with your module imported but its setup never run. You've fixed that listener and still see about +5 MiB per reload. To move that forward, it would help to know whether that run used the full setup or a stripped one, and to see the fixed bundle (or a stripped variant that still grows) so it can be measured the same way. @fanyzp's minimal scripts would also help.

If you have any of these, reply here and the issue will reopen.

opencodejr[bot] avatar Nov 29 '26 00:11 opencodejr[bot]

First, thank you. The plain-Bun reproduction in this thread (delete require.cache → import() → Bun.gc(true)) is what turned a vague "the plugin makes the host grow" report into two concrete, testable defects. Before that pointer I was measuring the wrong layer and drawing the wrong conclusion. Thanks also to the maintainers for keeping the thread open long enough for the numbers to converge.

Below is the complete result set, including the parts that do not support my earlier framing.

TL;DR

Measurement Before After
Live Desktop, heap slope per plugin reload +6.9137 MiB/sample -0.6300 MiB/sample
Live Desktop, net heap over 6 reloads +35.20 MiB -3.44 MiB
Live Desktop, process exit listeners 31 → 41 (+2 per reload) 42 → 42
Isolated serve, heap slope per reload +5.3351 MiB +0.7343 MiB (−86.2%)
Plain Bun loop, slope per import() +5.4065 MiB +0.8898 MiB
Plain Bun loop, exit listeners 1 → 12 1 → 1

Two independent plugin-side defects, both fixed in Tawassul V2:

  1. process.on('exit', ...) registered once per module evaluation instead of once per process.
  2. A setInterval(..., 6h) armed in setup and never stored, so dispose could not clear it.

Everything else discussed here — host retention of a registered tool's execute closure, StateManager._instances, the per-source artifact on module evaluation — I am not claiming to have fixed, and none of the numbers below touch it.

1. Why my earlier A/B was not admissible

I first ran an alternating A/B (fixed, base, fixed, base …) on one host. It produced fixed +9.0466 vs base +8.0523 MiB/sample (ratio 1.1235) with 12/12 canaries ok — i.e. it said the fix did nothing.

That protocol cannot isolate a non-reversible leak. The pre-fix generation's interval and exit listeners stay reachable after a later fixed reload, so every fixed sample sits on the same rising baseline the base samples created. The alternating design measures the baseline, not the variant.

The valid design here is a block: all samples of one variant, then all samples of the other, on a freshly restarted host. Pre-registered pass bar: fixed slope ≤ 50% of the base slope or ≤ 0.5 MiB/sample, with a strict WeakRef GC canary on every sample; any canary failure invalidates that sample.

2. The two defects

2.1 exit listener per module evaluation

src/infra/file-lock.ts registered a process.on('exit', ...) cleanup handler at module scope. In a host that re-evaluates the plugin module per reload, that adds one listener and one closure per reload. It also eventually trips MaxListenersExceededWarning.

Fix (b0e4f02): the handler is installed once per process, keyed on Symbol.for(...), so a re-evaluation reuses the existing registration. This is a correctness fix; on its own it does not remove the steady heap growth.

2.2 Uncleared db-maintenance interval

armDbMaintenanceTrigger created setInterval(..., 6h), called unref(), and returned nothing. unref() stops the timer from holding the event loop open — it does not make the timer collectable. Each reload left one live interval whose closure retained that generation's module graph.

Fix (901b9c0): the trigger returns its handle, initPlugin captures it, and dispose calls clearInterval. prove:db-scheduler now asserts that an enabled trigger returns its handle (96 assertions).

npm run verify is green on the fixed tree: fast gate 16 steps, 195 proofs across 3 isolated gate stages, plus both builds.

3. Live Desktop block proof

Host: opencode-cli 2.4.2 serve --service, Bun 1.4.4, freshly restarted, one plugin reload per sample, 12 s cadence, heap read 9 s after each reload, strict canary.

Confirmatory block, base first then fixed (6 + 6), same host PID:

Block Samples First → last OLS slope Net exit listeners Canary
Pre-fix 6 303.88 → 339.08 MiB +6.9137 MiB/sample +35.20 31 → 41 6/6 ok
Fixed 6 347.46 → 344.02 MiB -0.6300 MiB/sample -3.44 42 → 42 6/6 ok

The fixed block starts +8.38 MiB above the last base sample (inherited baseline from the leaks already created) and then declines. The host PID never changed.

A reversed diagnostic block (fixed first, then base) on the same build gave the same shape:

Block OLS slope Net exit listeners Canary
Fixed -1.1454 MiB/sample -5.36 18 → 18 6/6 ok
Pre-fix +9.0937 MiB/sample +45.83 19 → 29 6/6 ok

Post-apply check on a fresh host (PID 1470450, restarted service, fixed bundle), 6 reloads:

First → last OLS slope Net exit listeners Canary
178.68 → 173.16 MiB -0.9403 MiB/sample -5.52 4 → 4 6/6 ok

The restart cleared the 42 orphaned listeners and ~748 MiB RSS left by the pre-fix runs. The fixed bundle adds no listeners and no per-reload growth.

4. Isolated serve A/B (timer fix alone)

Same plugin, real setup, 14 reloads per variant, Bun 1.4.4, strict canary, 42/42 canaries cleared:

Variant First → last OLS slope exit
Full plugin, default env 103.61 → 174.95 MiB +5.3351 MiB/reload 3 → 3
Full plugin, TAWASSUL_DB_MAINTENANCE=off 109.87 → 124.50 MiB +0.7431 3 → 3
Stripped (setup() {}) 99.47 → 113.40 MiB +0.7770 2 → 2
Full plugin after 901b9c0 109.99 → 124.48 MiB +0.7343 MiB/reload 3 → 3

Disabling only the setup-time interval reproduces the entire drop, and the fixed build lands on both controls. That is what identified the interval as the remaining serve-side growth rather than module evaluation or the ctx APIs.

5. Plain Bun loop (module evaluation)

Your method, same path, new bytes, 12 imports each, Bun 1.4.2:

Bundle First → last OLS slope exit listeners
Pre-fix (0.1.8-experimental + listener bug) 19.36 → 78.88 MiB +5.4065 MiB/import 1 → 12
Fixed (b0e4f02 + 901b9c0) 19.36 → 31.90 MiB +0.8898 MiB/import 1 → 1

The fixed bundle has a one-time +5.47 MiB step on the second import, then roughly +0.7 MiB/import. That residual matches the per-source artifact you measured (~0.5 MiB/import for a 1.4 MB source; this bundle is 2.4 MB). So the module-evaluation diagnosis holds: the steady +5.4 MiB/import disappears once the listener is registered once per process.

6. What this does and does not prove

Proven:

  • The exit listener no longer grows with reloads.
  • The db-maintenance interval no longer survives dispose.
  • On a live Desktop host, the combined plugin-side growth is gone: slope +6.9137 → -0.6300 MiB/sample, exit constant, canaries valid.

Not claimed:

  • Absolute heap is not 50% lower. The pre-fix leaks are reachable and not reversible by a later reload, so the fixed block starts above the base block. The growth is eliminated; the already-leaked memory is not recovered without a restart.
  • Host-side retention is untouched. A registered tool's execute closure still outlives dispose() in 2.4.x, and StateManager._instances is still a static Set with no delete. Those are yours, not the plugin's, and I have no fix for them.
  • The §8 seven-workspace diagnostic was not rerun. The block proof above is a single-workspace live measurement.
  • One open item stays open. A cleanup-timeout change was reverted because it failed its own pre-registered A/B; it is not part of this report.

7. Artifacts

  • Plugin: Tawassul V2 0.1.8-experimental, https://github.com/HtoZ27/Tawassul-V2
  • Fix commits: b0e4f02 (listener once per process), 901b9c0 (clear the interval on dispose), on top of f75e374
  • Build: npm run build at 59c6a7a (docs-only on top of 901b9c0, identical code) reports content SHA 999bf204c4ca; the live entry file is 2.4 MB
  • A self-contained copy of the fixed bundle is available if you want to run it directly; it contains no home paths and no credentials

If it would help, I can post the block harness (the script that drives reloads, reads heapUsed, and enforces the WeakRef canary) so the protocol is reproducible rather than just described.

Again — thank you. The require.cache + import() loop and the "check which variant you actually measured" push are the two things that made this tractable, and I would not have found either defect without them.

HtoZ27 avatar Nov 29 '26 02:11 HtoZ27

Thanks for following this through and posting the full results, including the parts that went against your first hypothesis.

To sum up: the growth reported here came from two defects in the plugin. One was an exit listener added each time the module was evaluated, the other a db-maintenance setInterval that dispose never cleared. With both fixed, the live Desktop slope went from +6.9 to −0.6 MiB per reload and the exit listener count stays constant. What's left in the plain-Bun loop (about +0.7–0.9 MiB per import for a 2.4 MB bundle) matches the small per-source cost I measured in Bun itself, which isn't specific to OpenCode.

Your note about block versus alternating A/B for leaks that can't be undone is worth keeping in mind for anyone measuring plugin reloads.

On the two items you list as possibly OpenCode's:

  • Tool execute closures outliving dispose(): in my earlier test on 2.4.2, a ~16 MiB array captured by a ctx.tool.transform executor (plus tool.hook, session.hook and an aborted event.subscribe) stayed live only once across 6 reloads, so I didn't see that retention.
  • StateManager._instances: I couldn't tell from this thread whether that class belongs to OpenCode or to your plugin.

If you can show either one with a minimal plugin (for example a plugin that registers one tool capturing a large buffer, with heapUsed and the canary across reloads), please open a new issue with that repro. A focused report like that is much easier to act on than continuing here.

Since the growth in this issue is resolved in the plugin, this issue will be closed. Thanks again for the careful work.

opencodejr[bot] avatar Nov 29 '26 02:11 opencodejr[bot]

Closing this now. The memory growth reported here came from two defects in the plugin, both of which you've fixed: an exit listener added each time the module was loaded, and a db-maintenance interval that dispose never cleared. With those fixed, the live Desktop heap no longer grows on reload.

This was left open in case you could show that OpenCode itself keeps memory after a reload (the tool execute closure or StateManager._instances), but no repro for that has come in. If either is still a problem, please open a new issue with a minimal plugin that shows it, with heapUsed and the WeakRef canary across reloads, so it can be looked at on its own.

Thanks again for the thorough measurements.

opencodejr[bot] avatar Nov 29 '26 08:11 opencodejr[bot]