Skip to content

fix(ai): stop leaking opencode serve processes - #1445

Merged
backnotprop merged 2 commits into
mainfrom
fix/opencode-serve-leak
Sep 1, 2026
Merged

backnotprop merged 2 commits into
mainfrom
fix/opencode-serve-leak

Conversation

@backnotprop

Copy link
Copy Markdown
Owner

The leak

Anyone with the opencode CLI on PATH was affected on every Plannotator session, on both runtimes. Server boot eagerly called the opencode provider's fetchModels() just to fill the Ask AI model dropdown, which spawned an opencode serve (or attached to an existing one) on the shared default port 4096. Cleanup only ran on the clean decision path, so a Ctrl-C, crash, or host-killed hook orphaned the child. From there it compounded: the orphan owned 4096, every later session attached to it, and each attach from a new directory created a ~130MB instance inside it that opencode never evicts. Observed in the wild as a 2.7GB opencode serve nobody started on purpose.

The fix

Lazy start (the core). The autolaunch itself was the problem: spawning a whole agent server at boot to populate a dropdown most users never open. opencode model discovery now sits behind the same deferred provider initializer Codex uses (#1144 pattern): nothing spawns until the user activates opencode in Ask AI (?activate= from the model picker via useAIProviderActivation, or the first opencode session). Pre-activation the picker lists the provider with an empty model list, exactly like Codex — both endpoints.ts (models: p.models ?? []) and the UI (provider.models ?? []) already handle that state.

Own server per process. When it does start, it spawns with port: 0 — the SDK parses the real URL from the child's own "listening" line, so the OS assigns a free port — and the attach path is removed entirely: we never connect to a server we didn't spawn, because we can't clean up what we don't own and its instance cache grows without bound. An explicitly configured port is still honored verbatim.

Exit cleanup. A process.once("exit") handler closes the spawned server; the CLI already routes SIGINT/SIGTERM through process.exit, so Ctrl-C now kills the child. Dispose removes the handler. No SIGHUP listener is installed, preserving the nohup contract.

Both runtimes

packages/server/ai-runtime.ts and apps/pi-extension/server/ai-runtime.ts get the same deferral; the provider itself is shared (vendored to Pi by vendor.sh).

Tests

packages/ai/providers/opencode-sdk.test.ts (5 tests): SDK mocked so no real server ever spawns — asserts port 0, exit-handler add/remove symmetry, the exit handler actually closing the server, explicit-port passthrough, and a source-level pin that BOTH runtimes keep opencode discovery behind providerInitializers instead of eager modelDiscovery.

bun run typecheck clean across all 9 projects. bun test packages/ai/ 127 pass. The 6 failures in packages/server/review-workspace.test.ts and 6 in apps/pi-extension/server.test.ts reproduce identically on clean main (sem-sidecar/GitButler environment) and are unrelated.

AI-assisted (Claude) under maintainer direction.

Every server boot with the opencode CLI on PATH eagerly called the
provider's fetchModels() to fill the Ask AI dropdown, which spawned (or
attached to) an 'opencode serve' on the shared default port 4096. Dispose
only ran on the clean decision path, so Ctrl-C orphaned the child, and
every later session attached to the orphan and piled unevictable
per-directory instances into it (multi-GB over a day of normal use).

Three changes:
- Lazy start: opencode model discovery moves onto the same deferred
  provider initializer Codex uses. Nothing spawns until the user
  activates opencode in Ask AI (?activate= from the model picker, or the
  first opencode session). The picker still lists the provider with an
  empty model list pre-activation, exactly like Codex.
- Own server per process: spawn with port 0 (OS-assigned; the SDK reads
  the real URL from the child's listening line) and never attach to a
  server we did not spawn. An explicitly configured port is honored.
- Exit cleanup: a process 'exit' handler closes the spawned server
  (SIGINT/SIGTERM are routed through process.exit by the CLI), removed
  again on dispose. No SIGHUP listener, preserving nohup.

Both runtimes; regression tests mock the SDK so no real server spawns.
Independent review of the leak fix found two holes, both now closed and
regression-tested against the mocked SDK:

- A failure after the spawn (client construction) left the child running
  and its exit handler registered, and because the handler read
  this.server late instead of capturing its own server, a retry's second
  spawn made the first unreachable by any cleanup. doStart now captures
  the server in its handler closure and reaps child + handler on any
  post-spawn failure.
- dispose() during an in-flight spawn was a no-op the completing spawn
  then undid, resurrecting a disposed provider with a live child and a
  fresh exit handler. dispose() now bumps a start epoch; a spawn that
  completes past its epoch reaps its own server and rejects, and the
  provider remains restartable afterwards.

Also documents the OpenCode transport (per-process server, deferred
discovery) beside the Codex note in AGENTS.md.
@backnotprop

Copy link
Copy Markdown
Owner Author

Independent adversarial review ran against this branch (verdict: merge with minor changes) and empirically confirmed the fix end to end: opencode serve --port=0 binds an OS port and the SDK reads the real URL from stdout; plain /api/ai/capabilities spawns nothing while ?activate=opencode-sdk spawns exactly one child and returns the real model list; SIGINT reaps the child through the CLI's exit routing; vendoring, docs, and mock isolation all check out. The empty-model-list UX was chased specifically: no crash, no wrong model — session create resolves models post-activation (endpoints.ts runs beforeProviderSession before model resolution), and the picker simply hides the model select until activation.

The review found two lifecycle holes, closed in 698d97b with tests:

  1. A post-spawn failure (client construction) leaked the child and stacked exit handlers, and the handler read this.server late, so after a retry the first child was unreachable by any cleanup. The handler now captures its own server, and any post-spawn failure reaps child + handler.
  2. dispose() during an in-flight spawn was undone by the completing spawn, resurrecting a disposed provider with a live child. dispose() now bumps a start epoch; a spawn completing past its epoch reaps itself and rejects, and the provider stays restartable.

Known residual, by design: SIGHUP still orphans the child, because the CLI deliberately installs no SIGHUP listener (nohup plannotator review & must survive terminal close). Under the old code that orphan was one shared server; under this fix it is one per process — but each is small, unattachable, and never grows, versus the old single orphan that every later session piled unevictable instances into. The review also found and reclaimed ~6GB of orphaned servers on the dev machine (25 from an intermediate branch state, one from the old shared-port path), which is the leak's severity in miniature.

AI-assisted (Claude) under maintainer direction.

@backnotprop
backnotprop merged commit a79e6b0 into main Sep 1, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant