Skip to content

fix(models): release the extensions a full-catalogue read loads - #1003

Closed
HoloNova wants to merge 2 commits into
agegr:mainfrom
HoloNova:fix/release-model-reads
Closed

HoloNova wants to merge 2 commits into
agegr:mainfrom
HoloNova:fix/release-model-reads

Conversation

@HoloNova

Copy link
Copy Markdown
Contributor

What

Reading the model catalogue (GET /api/models), the provider list
(GET /api/auth/providers), the enabled-models view, the default-preference
check and the catalog refresh all build createAgentSessionServices() — which
imports and runs every configured extension, because that is where
extension-registered providers come from.

Nothing ever unloaded them:

  • AgentSessionServices, ResourceLoader and LoadExtensionsResult expose no
    dispose;
  • the only release path is the session_shutdown event, and only a session's
    extension runner can emit it (the loader's runtime is a throwing stub until
    a runner initializes it).

So every such read left the extension's own resources alive for the life of the
server process — a helper process, for an extension such as AFT — plus whatever
its load allocated until a GC happened to run. Opening the Models panel three
times meant three leftover helper processes.

How

lib/model-runtime.ts now owns the only way to get that runtime:

return withExtensionRuntime(async (modelRuntime) => { ... });          // agent dir
return withExtensionServices({ cwd, agentDir, ...trust }, async ({ settingsManager }) => { ... });

The wrapper builds the services, creates a throwaway in-memory session
(SessionManager.inMemory, noTools: "all" — no session file, no tool can
run), hands the services to the read, and then emits session_shutdown and
disposes the session in a finally.

Callers updated: /api/models, /api/models/enabled, /api/models/default,
/api/auth/providers, /api/auth/api-key/[provider],
/api/auth/login/[provider], /api/auth/logout/[provider],
lib/model-catalog-refresh.ts. createModelRuntimeWithExtensions() is gone:
leaving it in place would leave the leak reachable.

Numbers (deployment host, capped scopes)

path per read extension helper processes after
services only (before) 462-549 ms 0 → 1 → 2 → 3 (one more left alive each round)
wrapper (after) 448-532 ms + 2-41 ms back to baseline every round

Cold start is ~3.6 s; the wrapper's own session, shutdown event and dispose
together add 2-41 ms. Heap and external returned to their pre-read level and
stayed flat across six rounds; loaded extension sets stayed collectable, at most
the two most recent still reachable.

Robustness

  • A plugin that hangs in its handler cannot hang a read: the emit is raced
    against a 5 s timeout and the session is disposed either way (logged).
  • If the throwaway session cannot be created at all, the read still answers; it
    logs that it could not release anything.
  • A read that throws still releases (finally).

Behaviour change

The throwaway session emits session_start (the SDK default for a new session),
so an extension sees one more start/shutdown pair per read. That is the intended
trade: it is also the first time these reads tell an extension that its work is
done.

Verified

Whole suite: 1330 tests, 0 failures; tsc --noEmit and eslint . clean. New
coverage in lib/model-runtime.test.mjs (seven tests, SDK stubbed): in-memory
session with noTools: "all", session_shutdown before dispose, release when
the read throws, dispose when the handler throws, release when the handler
never finishes, read still answered when the session cannot be created, and a
guard that no route calls createAgentSessionServices() directly any more.

Reading the model catalogue or the provider list builds
`createAgentSessionServices()`, which imports and runs every configured
extension. Nothing ever unloaded them: `AgentSessionServices`,
`ResourceLoader` and `LoadExtensionsResult` expose no dispose, and the only
release path is the `session_shutdown` event, which only a *session's*
extension runner can emit (the loader's `runtime` is a throwing stub until a
runner initializes it). So each read left the extension's own resources alive
for the life of the server process — a helper process, for an extension such as
AFT — and the memory its load allocated until a GC happened to reclaim it.

Every read that enumerates models or providers now goes through
`withExtensionServices()` / `withExtensionRuntime()`. They create a throwaway
in-memory session (`SessionManager.inMemory`, `noTools: "all"`, so no session
file and no tool can run), hand the services to the read, and then emit
`session_shutdown` and dispose the session. Extensions that clean up on that
event now get it while the read is still the reason they were loaded.

Measured on the deployment host, three rounds per variant (and six for the
wrapper):

- the load costs 448-532 ms warm (~3.6 s cold); the session, the shutdown event
  and the dispose together add 2-41 ms;
- the wrapper released the extension's helper process every round (the plain
  path left one more alive each round: 0 -> 1 -> 2 -> 3);
- heap and external memory returned to their pre-read level and stayed flat
  across rounds; the loaded extension sets stayed collectable, with at most the
  two most recent still reachable.

A plugin that hangs in its handler cannot hang a read: the emit is raced against
a 5 s timeout and the session is disposed either way. If the throwaway session
cannot be created at all, the read still answers and logs why it could not
release anything.

Behaviour: the throwaway session emits `session_start` (the SDK's default for a
new session), so an extension sees one more start/shutdown pair per read — the
release it never got before is the point.
@HoloNova
HoloNova marked this pull request as ready for review September 30, 2026 04:27
CI runs the release test on a Node version whose MockTimers ExperimentalWarning
reaches console.error, so asserting on the first captured call failed there
while passing here. Assert that the message was logged at all instead.
@agegr

agegr commented Sep 30, 2026

Copy link
Copy Markdown
Owner

Thanks @HoloNova. The leak is real for extensions that start work in their factory: createAgentSessionServices() has no dispose, so a helper spawned at load outlives every catalogue read. I'm closing this approach, though, because the release mechanism conflicts with where pi is going:

  • It turns every read into a session lifecycle. The throwaway session emits session_start before session_shutdown, so each /api/models, /api/auth/providers, enabled-models or default-model read now tells every extension that a session started. Extensions that do their work on session_start (most well-behaved ones) would start it on each Models panel open, and then be torn down.
  • pi 0.99 makes that concrete. Its built-in mcp extension connects every enabled server from mcp.json on session_start (stdio servers spawn processes, HTTP ones may run OAuth). pi-web is moving to 0.99, and with this change each catalogue read would connect and disconnect all of the user's MCP servers. That's more process churn than the leak it fixes, and it has side effects.
  • Extensions can't tell a read from a session. A session_start/session_shutdown pair with no session behind it is observable (telemetry, notifications, state files).

A fix that doesn't pretend to be a session would be welcome. For example, build the extension-backed services once per (cwd, agentDir, trust) and reuse them for reads, so a load-time helper exists once instead of once per read. Or ask upstream for a dispose on the resource loader / LoadExtensionsResult, which is the missing piece you identified.


Generated by Claude Code

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.

2 participants