Repository navigation
fix: unload Ollama models from GPU on provider switch and sandbox stop - #2651
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a best-effort Ollama GPU cleanup: a new Changes
Sequence DiagramsequenceDiagram
participant Service as Service/Sandbox
participant NodeHTTP as Node HTTP
participant Ollama as Ollama API
Service->>NodeHTTP: call unloadOllamaModels()
NodeHTTP->>Ollama: GET /api/ps
Ollama-->>NodeHTTP: { models: [...] }
alt models returned
loop per model
NodeHTTP->>Ollama: POST /api/generate (body: { model, keep_alive: 0 })
Ollama-->>NodeHTTP: 200 / response (best-effort)
end
else no models / errors
NodeHTTP-->>Service: complete (errors suppressed)
end
NodeHTTP-->>Service: unload complete
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/ollama-gpu-cleanup.test.js`:
- Around line 53-106: The tests currently define a local unloadOllamaModels
function instead of exercising the real exported implementation, so replace the
local definition with an import of the real function exported by the
onboard-ollama-proxy module (use the exported name unloadOllamaModels or the
module's default export as appropriate), and adapt the tests to stub/mock the
external HTTP interactions (e.g., using a HTTP mocking utility or spies) rather
than reimplementing logic; apply the same change for the other duplicated blocks
(the other occurrences of the local unload logic) so the test validates the
production function and only mocks network calls.
- Line 230: Replace the empty catch blocks that currently read "catch {}" with
explicit catch handlers that include a named error parameter and an in-block
comment (e.g. catch (err) { /* intentionally ignore cleanup errors */ }) so
ESLint no-empty is satisfied; update both occurrences of the empty catch (the
two "catch {}" instances in the test file) to use the pattern catch (err) { /*
noop / intentionally ignored */ } or optionally log the error with
console.debug(err) inside the block.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: abb8f27c-dc81-4d69-8d0a-5ce17c41bd4b
📒 Files selected for processing (4)
src/lib/onboard-ollama-proxy.tssrc/lib/services.tssrc/nemoclaw.tstest/ollama-gpu-cleanup.test.js
When switching inference providers or stopping/destroying a sandbox, Ollama runners were not being unloaded, holding GPU memory until the user manually restarted Ollama. Add unloadOllamaModels() which calls GET /api/ps to list loaded models, then POST /api/generate with keep_alive:0 for each to free GPU memory. Hook it into three lifecycle points: - cleanupSandboxServices(): when sandbox services are cleaned up - sandboxDestroy(): before sandbox deletion (also kills auth proxy) - stopAll(): when all host services are stopped All calls are best-effort and silently ignore errors when Ollama is not running. Fixes: NVIDIA#2638 Signed-off-by: kagura-agent <[email protected]> Signed-off-by: kagura-agent <[email protected]>
onboard-ollama-proxy.ts uses CJS require('./runner') which doesn't
resolve correctly under vitest's ESM transform (same limitation as
shields.test.ts). Document this and keep the reproduced logic approach
until the module is migrated to ESM imports.
Signed-off-by: kagura-agent <[email protected]>
Signed-off-by: kagura-agent <[email protected]>
d104411 to
664ef06
Compare
jyaunches
left a comment
There was a problem hiding this comment.
LGTM — unit tests sufficient for this change (HTTP client + lifecycle hooks). Rebased onto main to resolve isProxyHealthy export conflict. Follow-up items: deduplicate triple-unload in sandboxDestroy path, add sync comment linking test to source.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/nemoclaw.ts (1)
2942-2971: Run the recommended sandbox E2E suite for these lifecycle-path changes.Since this touches sandbox cleanup/destroy flows, run:
gh workflow run nightly-e2e.yaml --ref <branch> -f jobs=sandbox-survival-e2e,sandbox-operations-e2e,skip-permissions-e2eAs per coding guidelines: "E2E test recommendation: sandbox-survival-e2e, sandbox-operations-e2e, skip-permissions-e2e."
Also applies to: 2990-3042
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/nemoclaw.ts` around lines 2942 - 2971, The change in cleanupSandboxServices (and adjacent lifecycle code around lines ~2990-3042) affects sandbox cleanup/destroy flows so you must run the recommended sandbox E2E suites; trigger the GitHub Actions workflow nightly-e2e.yaml for your branch with the jobs set to sandbox-survival-e2e,sandbox-operations-e2e,skip-permissions-e2e (gh workflow run nightly-e2e.yaml --ref <branch> -f jobs=sandbox-survival-e2e,sandbox-operations-e2e,skip-permissions-e2e), and attach the run ID/logs to this PR; if failures appear, reproduce locally against cleanupSandboxServices and the nearby lifecycle code to capture failing assertions and include those in the PR for follow-up fixes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/lib/onboard-ollama-proxy.ts`:
- Around line 349-395: The GET request created as const req = http.get(...) and
each POST created as unloadReq = http.request(...) need 'timeout' handlers that
call req.destroy(new Error(...)) / unloadReq.destroy(new Error(...)) (or
destroy() with no arg) to ensure timed-out sockets are aborted; add
req.on("timeout", () => req.destroy(new Error("request timeout"))) and similarly
for unloadReq.on("timeout", () => unloadReq.destroy(new Error("request
timeout"))), keep the existing 'error' handlers and ensure you attach the
timeout listeners before calling req.end()/write() so timed-out requests cannot
hang the shutdown.
---
Nitpick comments:
In `@src/nemoclaw.ts`:
- Around line 2942-2971: The change in cleanupSandboxServices (and adjacent
lifecycle code around lines ~2990-3042) affects sandbox cleanup/destroy flows so
you must run the recommended sandbox E2E suites; trigger the GitHub Actions
workflow nightly-e2e.yaml for your branch with the jobs set to
sandbox-survival-e2e,sandbox-operations-e2e,skip-permissions-e2e (gh workflow
run nightly-e2e.yaml --ref <branch> -f
jobs=sandbox-survival-e2e,sandbox-operations-e2e,skip-permissions-e2e), and
attach the run ID/logs to this PR; if failures appear, reproduce locally against
cleanupSandboxServices and the nearby lifecycle code to capture failing
assertions and include those in the PR for follow-up fixes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 23b9df43-25c3-4e00-8021-ad56db2c3007
📒 Files selected for processing (4)
src/lib/onboard-ollama-proxy.tssrc/lib/services.tssrc/nemoclaw.tstest/ollama-gpu-cleanup.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
- test/ollama-gpu-cleanup.test.js
| const req = http.get( | ||
| { | ||
| hostname: "localhost", | ||
| port: OLLAMA_PORT, | ||
| path: "/api/ps", | ||
| timeout: 3000, | ||
| }, | ||
| (res) => { | ||
| let data = ""; | ||
| res.on("data", (chunk) => { | ||
| data += chunk; | ||
| }); | ||
| res.on("end", () => { | ||
| if (res.statusCode !== 200) return; | ||
| try { | ||
| const parsed = JSON.parse(data); | ||
| const models = parsed.models || []; | ||
| for (const entry of models) { | ||
| if (!entry.name) continue; | ||
| const unloadReq = http.request( | ||
| { | ||
| hostname: "localhost", | ||
| port: OLLAMA_PORT, | ||
| path: "/api/generate", | ||
| method: "POST", | ||
| timeout: 3000, | ||
| headers: { "Content-Type": "application/json" }, | ||
| }, | ||
| () => { | ||
| /* ignore response */ | ||
| }, | ||
| ); | ||
| unloadReq.on("error", () => { | ||
| /* best-effort */ | ||
| }); | ||
| unloadReq.write(JSON.stringify({ model: entry.name, keep_alive: 0 })); | ||
| unloadReq.end(); | ||
| } | ||
| } catch { | ||
| /* best-effort */ | ||
| } | ||
| }); | ||
| }, | ||
| ); | ||
| req.on("error", () => { | ||
| /* best-effort */ | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In Node.js http.get/http.request, when a timeoutis set in request options, does the request automatically abort, or shouldreq.destroy()be called in atimeout handler?
💡 Result:
In Node.js http.get / http.request, when a timeout is set in the request options, the request does not automatically abort. Instead, it sets a socket timeout, which emits a 'timeout' event on the request when the underlying socket times out from inactivity. The event only notifies that the socket has been idle; you must manually call req.destroy (or the deprecated req.abort) in the 'timeout' event handler to abort the request. Example usage: const req = http.get({ ...options, timeout: 5000 }, (res) => { // handle response }); req.on('timeout', => { req.destroy; }); req.on('error', (err) => { // handle error }); This behavior is consistent across recent Node.js versions (v18+ to v25+), as documented in the official HTTP module docs.
Citations:
- 1: https://nodejs.org/docs/v22.19.0/api/http.html
- 2: https://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node
- 3: https://nodejs.org/api/http.html
- 4: https://nodejs.org/download/release/v18.20.4/docs/api/http.html
Add timeout handlers to destroy HTTP requests and prevent shutdown hangs.
Lines 354 and 374 set timeout: 3000, but neither request has a timeout handler. In Node.js, setting a timeout does not automatically abort the request—it only emits a 'timeout' event on the socket. Without calling destroy() in a timeout handler, timed-out requests can linger during teardown.
🔧 Proposed fix
const req = http.get(
{
hostname: "localhost",
port: OLLAMA_PORT,
path: "/api/ps",
timeout: 3000,
},
(res) => {
@@
const unloadReq = http.request(
{
hostname: "localhost",
port: OLLAMA_PORT,
path: "/api/generate",
method: "POST",
timeout: 3000,
headers: { "Content-Type": "application/json" },
},
() => {
/* ignore response */
},
);
+ unloadReq.on("timeout", () => {
+ unloadReq.destroy();
+ });
unloadReq.on("error", () => {
/* best-effort */
});
unloadReq.write(JSON.stringify({ model: entry.name, keep_alive: 0 }));
unloadReq.end();
@@
);
+ req.on("timeout", () => {
+ req.destroy();
+ });
req.on("error", () => {
/* best-effort */
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const req = http.get( | |
| { | |
| hostname: "localhost", | |
| port: OLLAMA_PORT, | |
| path: "/api/ps", | |
| timeout: 3000, | |
| }, | |
| (res) => { | |
| let data = ""; | |
| res.on("data", (chunk) => { | |
| data += chunk; | |
| }); | |
| res.on("end", () => { | |
| if (res.statusCode !== 200) return; | |
| try { | |
| const parsed = JSON.parse(data); | |
| const models = parsed.models || []; | |
| for (const entry of models) { | |
| if (!entry.name) continue; | |
| const unloadReq = http.request( | |
| { | |
| hostname: "localhost", | |
| port: OLLAMA_PORT, | |
| path: "/api/generate", | |
| method: "POST", | |
| timeout: 3000, | |
| headers: { "Content-Type": "application/json" }, | |
| }, | |
| () => { | |
| /* ignore response */ | |
| }, | |
| ); | |
| unloadReq.on("error", () => { | |
| /* best-effort */ | |
| }); | |
| unloadReq.write(JSON.stringify({ model: entry.name, keep_alive: 0 })); | |
| unloadReq.end(); | |
| } | |
| } catch { | |
| /* best-effort */ | |
| } | |
| }); | |
| }, | |
| ); | |
| req.on("error", () => { | |
| /* best-effort */ | |
| }); | |
| const req = http.get( | |
| { | |
| hostname: "localhost", | |
| port: OLLAMA_PORT, | |
| path: "/api/ps", | |
| timeout: 3000, | |
| }, | |
| (res) => { | |
| let data = ""; | |
| res.on("data", (chunk) => { | |
| data += chunk; | |
| }); | |
| res.on("end", () => { | |
| if (res.statusCode !== 200) return; | |
| try { | |
| const parsed = JSON.parse(data); | |
| const models = parsed.models || []; | |
| for (const entry of models) { | |
| if (!entry.name) continue; | |
| const unloadReq = http.request( | |
| { | |
| hostname: "localhost", | |
| port: OLLAMA_PORT, | |
| path: "/api/generate", | |
| method: "POST", | |
| timeout: 3000, | |
| headers: { "Content-Type": "application/json" }, | |
| }, | |
| () => { | |
| /* ignore response */ | |
| }, | |
| ); | |
| unloadReq.on("timeout", () => { | |
| unloadReq.destroy(); | |
| }); | |
| unloadReq.on("error", () => { | |
| /* best-effort */ | |
| }); | |
| unloadReq.write(JSON.stringify({ model: entry.name, keep_alive: 0 })); | |
| unloadReq.end(); | |
| } | |
| } catch { | |
| /* best-effort */ | |
| } | |
| }); | |
| }, | |
| ); | |
| req.on("timeout", () => { | |
| req.destroy(); | |
| }); | |
| req.on("error", () => { | |
| /* best-effort */ | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/lib/onboard-ollama-proxy.ts` around lines 349 - 395, The GET request
created as const req = http.get(...) and each POST created as unloadReq =
http.request(...) need 'timeout' handlers that call req.destroy(new Error(...))
/ unloadReq.destroy(new Error(...)) (or destroy() with no arg) to ensure
timed-out sockets are aborted; add req.on("timeout", () => req.destroy(new
Error("request timeout"))) and similarly for unloadReq.on("timeout", () =>
unloadReq.destroy(new Error("request timeout"))), keep the existing 'error'
handlers and ensure you attach the timeout listeners before calling
req.end()/write() so timed-out requests cannot hang the shutdown.
Signed-off-by: kagura-agent <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
test/ollama-gpu-cleanup.test.ts (1)
67-130: Use centralized mock cleanup withafterEachto prevent test leakage on early assertion failures.Each of the three tests manually restores spies only at the end. If any assertion throws before reaching cleanup, mocks persist to subsequent tests. Add
afterEach(() => { vi.restoreAllMocks(); })to the describe block and remove all manualmockRestore()calls.Suggested patch
-import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import http from "node:http"; describe("Ollama GPU cleanup", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + it("should unload all running Ollama models via HTTP API", async () => { const mockModels = { models: [{ name: "llama3.1:8b" }, { name: "qwen:7b" }], }; @@ - httpGetSpy.mockRestore(); - httpRequestSpy.mockRestore(); }); it("should handle errors gracefully when Ollama is not running", () => { @@ - httpGetSpy.mockRestore(); }); it("should handle empty model list", async () => { @@ - httpGetSpy.mockRestore(); - httpRequestSpy.mockRestore(); }); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/ollama-gpu-cleanup.test.ts` around lines 67 - 130, Add centralized mock cleanup for the "Ollama GPU cleanup" suite by inserting afterEach(() => { vi.restoreAllMocks(); }) inside the describe block and remove the manual httpGetSpy.mockRestore() and httpRequestSpy.mockRestore() calls at the end of the test; this ensures spies created for http.get and http.request (httpGetSpy, httpRequestSpy) and any other mocks are always restored even if assertions fail, while leaving unloadOllamaModels() and existing assertions unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@test/ollama-gpu-cleanup.test.ts`:
- Line 169: Rename the unused mock callback parameter in the vi.spyOn(http,
"get") mockImplementation from options to _options to follow the repository
convention for intentionally unused variables; update the mock defined by
httpGetSpy (the mockImplementation callback) to accept _options instead of
options and leave the rest of the mock body unchanged.
---
Nitpick comments:
In `@test/ollama-gpu-cleanup.test.ts`:
- Around line 67-130: Add centralized mock cleanup for the "Ollama GPU cleanup"
suite by inserting afterEach(() => { vi.restoreAllMocks(); }) inside the
describe block and remove the manual httpGetSpy.mockRestore() and
httpRequestSpy.mockRestore() calls at the end of the test; this ensures spies
created for http.get and http.request (httpGetSpy, httpRequestSpy) and any other
mocks are always restored even if assertions fail, while leaving
unloadOllamaModels() and existing assertions unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 49670ef6-4ec1-4b91-8e82-fb1a97d95320
📒 Files selected for processing (1)
test/ollama-gpu-cleanup.test.ts
…implementations Co-Authored-By: Claude Opus 4 (1M context) <[email protected]>
Head branch was pushed to by a user without write access
132dc4a to
fa2adf5
Compare
## Summary Updates NemoClaw documentation for the v0.0.32 release candidate, covering user-facing changes that landed since v0.0.31 and promoting the docs version switcher to 0.0.32. ## Changes - Document Windows-host Ollama support from WSL, including HTTP model pulls and avoiding duplicate Ollama instances on port 11434. Matches dev PR #2768. - Add Ollama GPU memory cleanup behavior for provider switches, service stops, and sandbox destroy. Matches dev PR #2651. - Document Hugging Face token forwarding for remote deploy workflows that pull gated model repositories. Matches dev PR #2729. - Add runtime sandbox and policy context injection to the architecture reference. Matches dev PR #2751. - Bump `docs/versions1.json` and regenerated `docs/project.json` to 0.0.32 for release prep. No separate dev PR. ## Type of Change - [ ] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [x] Doc only (includes code sample changes) ## Verification - [ ] `npx prek run --all-files` passes - [ ] `npm test` passes - [ ] Tests added or updated for new or changed behavior - [x] No secrets, API keys, or credentials committed - [x] Docs updated for user-facing behavior changes - [ ] `make docs` builds without warnings (doc changes only) - [x] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) ## AI Disclosure - [x] AI-assisted — tool: Cursor --- Signed-off-by: Miyoung Choi <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added guidance for deploying with Hugging Face gated models * Improved Windows/WSL Ollama configuration instructions * Documented GPU memory cleanup behavior during model transitions * Enhanced architecture and command reference documentation * Version bumped to 0.0.32 <!-- end of auto-generated comment: release notes by coderabbit.ai -->
<!-- markdownlint-disable MD041 --> ## Summary `nemoclaw <name> stop` left an Ollama-backed sandbox's model resident in GPU memory. Before this change the model stayed loaded until Ollama's own idle TTL expired, so several GB of VRAM remained reserved after a stop reported success. After this change a successful stop asks Ollama to unload that sandbox's model, closing the same gap `destroy` and host-service stop already closed. ## Related Issue Refs #9110 This PR fixes only the sandbox-stop symptom. #9110 also reports the provider-switch symptom, which is a separate code path and is left for a follow-up, so this does not close the issue. ## Changes - `src/lib/actions/sandbox/stop.ts`: after a successful stop of an Ollama-backed sandbox, unload the model that sandbox alone is holding. No new capability is introduced — `unloadOllamaModels()` already exists in `src/lib/inference/ollama/proxy.ts` and was already wired into `stopAll()` (`src/lib/tunnel/services.ts`) and `cleanupSandboxServices()` (`src/lib/actions/sandbox/destroy.ts`); the plain stop path was the one lifecycle point it was never hooked into. - The provider gate is the existing `provider.includes("ollama")` test already used at `destroy.ts` and `destroy-preflight.ts`, reading the registry entry `stopSandbox` has already resolved. No new config or environment flag. - `exclusivelyHeldOllamaModel()` then resolves which model is safe to release: this sandbox's own recorded model, unless a sibling Ollama-backed sandbox declares the same one. Peers are compared with `ollamaModelRefsMatch`, so a sibling recorded as `llama3` still protects `llama3:latest`. - The call is placed after the `outcome.exitCode !== 0` guard, so it covers both terminal-success paths (normal stop and already-stopped) with one statement and never runs when the stop itself failed. - The default implementation is a lazy `require` inside a closure, copied from the same pattern in `destroy.ts`. This keeps the `@ts-nocheck` proxy module off `stop.ts`'s static load path, so no new static fan-out edge is added. - The call is wrapped best-effort: a failing or absent `curl` must not change the exit code of a stop that already succeeded. - `src/lib/inference/ollama/proxy.ts`: `unloadOllamaModels()` takes an optional `onlyModels` filter. Existing no-argument callers keep the full host sweep. Filter entries are matched with `ollamaModelRefsMatch`, so a sandbox recorded as `llama3` still unloads the `llama3:latest` that `/api/ps` reports — an exact string match silently released nothing for any model pulled without a tag. - `test/ollama-gpu-cleanup.test.ts`: four proxy-level cases pinning the filtered path, the unfiltered path, and implicit-tag matching in both directions. - `src/lib/actions/sandbox/stop.test.ts`: twelve `#9110` cases via the new optional `unloadOllamaModels` and `listSandboxes` dependencies on `SandboxStopDeps`. - `docs/inference/set-up-ollama.mdx`: correct the Release GPU Memory section. It claimed "switch away from Ollama" releases memory, which no code path implements, and omitted sandbox stop entirely. It now names the three implemented triggers and separates their scope: destroy and host-service stop unload every loaded model, while a single sandbox stop unloads only that sandbox's own model and leaves it loaded when another Ollama-backed sandbox uses the same one. See the notes below. ## Behavior notes for reviewers - **This is the unfinished half of #2638.** That issue's acceptance criteria read "NemoClaw detects stale Ollama runners on provider switch **or sandbox stop**", and PR #2651's merged title was "unload Ollama models from GPU on provider switch and sandbox stop". #2651 hooked `cleanupSandboxServices()`, `sandboxDestroy()`, and `stopAll()` — none of which `nemoclaw <name> stop` reaches. `cleanupSandboxServices` has exactly one caller, `destroy.ts`. - **The docs change removes a promise, deliberately.** `docs/inference/set-up-ollama.mdx` claimed provider switch releases GPU memory. It does not: `src/lib/onboard.ts` never imports `unloadOllamaModels`, and its only provider-switch teardown, `runSandboxProviderPreDeleteCleanup`, detaches messaging and search providers only. Rather than leave a documented behavior that does not exist, the line now states what is implemented. The clause should be restored when the provider-switch path is wired. - **The stop-time unload is scoped to the stopping sandbox's own model** (advisor finding `PRA-1`, addressed in `7c3c13e959`). `unloadOllamaModels()` gained an optional model filter: `stopAll()` and `destroySandbox()` own the whole host, omit the filter, and keep unloading everything, so their behavior is byte-for-byte unchanged. Sandbox stop passes only its own recorded model, and skips the unload entirely when another registered Ollama-backed sandbox declares that same model, or when the sandbox has no recorded model. A single-sandbox stop can therefore never evict a model a sibling sandbox is using. - **Known limitation — two sandboxes recording the same model.** Stop preserves registry entries, so the sibling check cannot tell a registered peer from a running one and suppresses the unload for both. Those sandboxes release nothing on stop and wait for Ollama's idle TTL. That is exactly today's behavior on `main`, so this PR does not regress it, and `destroy` and host-service stop still release. Fixing it properly needs a driver-neutral running-state query, which the runtime-provider contract does not expose: `RuntimeProviderLifecycleSurface` has `start`, `stop`, and `verifyStarted`, and `recovery` only offers `recover(sandbox)`. I attempted it in `caa0d4d5d9` by calling into the Docker recovery module and reverted it in `de4bfcd46f` — `src/lib/actions/sandbox/stop.ts` is contractually driver-neutral and `test/runtime-provider-source-shape.test.ts:111` enforces that. Adding the capability belongs in its own PR. - **`nemoclaw <name> start` does not re-warm the model**, so the first inference after a stop/start pays a cold load. That is the intended trade for returning the VRAM. - **Not covered:** `nemoclaw inference set` is a third path that switches providers without unloading. Out of scope here. - `unloadOllamaModels()` targets `http://localhost:${OLLAMA_PORT}` directly rather than `getResolvedOllamaHost()`. On a remote-Ollama topology it no-ops — but it already no-ops identically in `destroy` today, so this PR neither introduces nor worsens that. Separate defect, not folded in. ## Type of Change - [x] Code change with doc updates ## Quality Gates - [x] Tests added or updated for changed behavior - [x] Docs updated for user-facing behavior changes - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [ ] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: Validation run locally on `de4bfcd46f`: - `npx vitest run src/lib/actions/sandbox/stop.test.ts test/ollama-gpu-cleanup.test.ts test/destroy-cleanup-sandbox-services.test.ts` — 53 passed, up from 31 on main. - `tools/growth-guardrails/test-conditionals.mts` — PASS (3 `if` at head vs 3 at base). - `tools/growth-guardrails/test-size-budget.mts` — PASS. - `npm run typecheck:cli` — clean. - `npx oxlint` on both changed source files — clean. - `npm run test-size:check` — passed (`stop.test.ts` is 588 lines against a 1500 budget). - `npm run source-shape:check` — `source_shape_cases=0`. - `npm run format:check` — neither changed file is flagged. - `npm run docs:check-routes` — OK. Test coverage added: | Case | Asserts | |---|---| | Ollama-backed stop | unload called once, exit 0 | | Already-stopped Ollama sandbox | unload called once, exit 0 | | `nvidia-prod` / `vllm-local` / unrecorded provider | unload not called, exit 0 | | Unload throws | exit 0 and no warning emitted | | Docker stop fails | unload not called, exit 1 | | Sibling Ollama sandbox on the **same** model | unload not called | | Sibling Ollama sandbox on a **different** model | unload called with only this sandbox's model | | Sandbox with no recorded model | unload not called | | Sibling recorded with an implicit vs explicit `latest` tag | unload not called (both directions) | | Proxy-level: filtered `unloadOllamaModels(["drop-me:7b"])` | one `keep_alive: 0` POST, for that model only | | Proxy-level: empty filter | every loaded model unloaded | | Proxy-level: filter `llama3` vs daemon `llama3:latest` | unloaded (both directions) | Two commits in this branch are a revert pair (`caa0d4d5d9` / `de4bfcd46f`) and cancel out; the net diff is four files. See the known-limitation note above for why. Branch selection is expressed by per-case fixtures rather than conditionals, so the file stays free of `if` statements and of source-text assertions. ## Documentation Writer Review - [ ] Documentation writer subagent reviewed the completed changes - Result: `docs-updated` - Evidence: `docs/inference/set-up-ollama.mdx` - Agent: Claude Code Signed-off-by: Dongni Yang <[email protected]> --------- Signed-off-by: Dongni Yang <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
<!-- markdownlint-disable MD041 --> ## Summary Re-onboarding an Ollama-backed sandbox onto a different provider left its model resident in GPU memory. The drift-recreate path never reaches `destroySandbox` — it detaches messaging and search providers and issues a raw `openshell sandbox delete` — so no unload ever ran and the model stayed loaded until Ollama's own idle TTL expired. After this change, a re-onboard that supersedes the sandbox's Ollama model releases that model once the new route has committed. Stacked on #9113 (sandbox-stop half). Base branch: `fix/9110-stop-ollama-unload`. ## Related Issue Closes #9110 #9110 reports two symptoms. PR #9113 fixes the sandbox-stop symptom; this PR fixes the provider-switch symptom. Together they cover the issue, so this PR carries the closing keyword. ## Changes - `src/lib/onboard/setup-inference.ts`: read the previous registry row and call `releaseSupersededOllamaModel` inside the sandbox-mutation-locked operation: the read happens before `reserveRoute` rewrites the row (after which the previous selection is unrecoverable), and the release completes before the lock opens, so a serialized re-onboard can neither replace the row under the read nor select the captured model before the cleanup runs (advisor finding `PRA-1`, addressed in `6de8d33f12`). The tail position covers both success exits (the ordinary `{ ok: true }` return and the Hermes provider-branch return) with one statement, runs after `verifyOnboardInferenceSmoke` has proven the new route, and never runs on the `{ retry: "selection" }` path, where the recorded route is untouched. Best-effort: a failed release cannot change the result or the exit code. - Review follow-up: a host-global Ollama model-ownership lock now encloses the registry peer scan and GPU release in both plain stop and re-onboard. Focused tests verify that the lock covers the scan and unload in both paths. A caller-level regression also proves that a thrown superseded-model unload remains best-effort and preserves the successful re-onboard result. - `src/lib/inference/ollama/model-ownership.ts` (new): one shared home for the ownership rule. `exclusivelyHeldOllamaModel` moves here from `stop.ts` unchanged; `supersededOllamaModel` builds on it. The release keys on the **model reference**, never the provider name: a provider switch that keeps the same model can still be served by the same host daemon (an operator can move an `ollama-local` sandbox onto a `compatible-endpoint` route pointed back at `http://127.0.0.1:11434/v1`), and releasing there would evict the model the new route was just proven against. Comparing model refs is strictly conservative — it can only miss a release, never evict a model the new route still uses. - `src/lib/actions/sandbox/stop.ts`: consume the moved helper through the same lazy-require pattern it already uses; behavior unchanged, all twelve `#9110` stop cases pass unmodified. - `src/lib/onboard.ts`: wire `getSandbox`, `listSandboxes`, and `unloadOllamaModels` into `getSetupInferenceDeps()`. Net-neutral (+2/-2): the additions fold into existing destructure and dep lines, and the Oxfmt hook formats added files only, so the folded lines stay put. - `test/support/setup-inference-test-harness.ts`: neutralize the new seams (`getSandbox: () => null`, empty `listSandboxes`, `vi.fn()` unload) so harness consumers backed by production defaults never read the developer's real registry or curl a live Ollama daemon. - `docs/inference/set-up-ollama.mdx`: the Release GPU Memory section now covers re-onboard — a different model releases the replaced one with the same sibling protection; the same model stays loaded. This restores the provider-switch clause that PR #9113 removed as undocumented-behavior, now that the behavior exists. ## Behavior notes for reviewers - **Why the recreate path leaks today:** `cleanupSandboxServices` — the only teardown that unloads — has exactly one caller, `destroy.ts`. The drift-recreate delete calls `runSandboxProviderPreDeleteCleanup`, which detaches messaging/search providers only. This PR does not touch that delete site; the release lives at the `setupInference` seam, which also covers the reuse path and fires only after the new route is proven. - **Why the previous row is still readable at that seam:** `removeSandboxUnlessSessionReservation` returns early while the sandbox-recreate checkpoint is in flight, so the old registry row (previous provider and model) survives the delete until `reserveRoute` rewrites it inside `setupInference`. - **This completes #2638's acceptance criteria** ("provider switch or sandbox stop") whose PR #2651 wired destroy/stopAll only. - **Shared-model limitation carries over from #9113:** a sibling registered against the same model suppresses the release. Conservative by design. - **Still out of scope:** `nemoclaw inference set` switches providers without unloading and also erases the recorded model name; separate issue. ## Type of Change - [x] Code change with doc updates ## Quality Gates - [x] Tests added or updated for changed behavior - [x] Docs updated for user-facing behavior changes - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [ ] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: Validation run locally on `6de8d33f12`: - `npm run test:changed` — 1408 tests in 113 files pass (on `b416e0a528`; the lock-move commit re-ran the touched suites below). - `npx vitest run test/onboard-inference-reconciliation.test.ts test/ollama-gpu-cleanup.test.ts test/sandbox-provider-cleanup.test.ts` (integration project, not covered by `--changed`) — 56 pass. - `npm run typecheck:cli` — clean. - oxlint and oxfmt clean on the new and changed files. - `src/lib/onboard.ts` diff is +2/-2 (net-neutral guardrail). - `test/onboard-inference-reconciliation.test.ts`: 1083 lines against the 1500 budget, `if` count unchanged at 5. - The host-global ownership-lock change ran 75 focused tests: 74 passed; one unrelated existing DGX Spark case failed because the x86 development host does not meet the DGX Spark platform requirement. The unload-failure follow-up ran the reconciliation file once: 20 tests passed, including the new failure path; the same unrelated DGX Spark platform case failed. Normal pre-commit and commit-msg hooks passed. Test coverage added: | Case | Asserts | |---|---| | `model-ownership.test.ts` (new, 9 cases) | superseded release, same-model keep (tag variants both directions), sibling protection, non-Ollama previous provider, unrecorded/blank models, missing previous entry, non-Ollama peer does not block | | Reconciliation: re-onboard onto a different model | `unloadOllamaModels(["llama3"])` after the route commits | | Reconciliation: re-onboard onto the same model | unload not called | | Reconciliation: sibling records `llama3:latest` | unload not called | | Reconciliation: route returns `{ retry: "selection" }` | unload not called | | Reconciliation: instrumented lock | exact order `lock-enter`, `read-prior-route`, `ownership-lock-enter`, `peer-scan`, `unload`, `ownership-lock-exit`, `lock-exit` | ## Documentation Writer Review - [x] Documentation writer subagent reviewed the completed changes - Result: `docs-updated` - Evidence: `docs/inference/set-up-ollama.mdx` documents replacement unload, same-model retention, and sibling protection. - Agent: Codex Desktop <!-- docs-review-head-sha: bb3facc --> <!-- docs-review-agents-blob-sha: e30afb2 --> Signed-off-by: Dongni Yang <[email protected]> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved Ollama model management during re-onboarding. * Replaced models are automatically unloaded after successful model changes. * Models still used by other sandboxes remain available. * Re-onboarding with the same model leaves it loaded. * **Bug Fixes** * Prevented model cleanup when onboarding fails or returns to provider selection. * Improved handling of shared and equivalent model references. * **Documentation** * Added guidance explaining Ollama GPU-memory cleanup behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Dongni Yang <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Carlos Villela <[email protected]>
Summary
When switching inference providers or stopping/destroying a sandbox, Ollama runners remain active and continue holding GPU memory. Users must manually
systemctl restart ollamato free VRAM.Related Issue
Closes #2638
Changes
Added
unloadOllamaModels()function insrc/lib/onboard-ollama-proxy.tsthat:GET /api/psto list currently loaded Ollama modelsPOST /api/generatewithkeep_alive: 0to immediately unload from GPU memoryHooked into three lifecycle points:
cleanupSandboxServices()innemoclaw.tssandboxDestroy()innemoclaw.tsstopAll()inservices.tsAlso exported
killStaleProxyfromonboard-ollama-proxy.tssosandboxDestroy()can kill the auth proxy during teardown.All calls are best-effort with silent error handling — no impact if Ollama is not running.
Testing
test/ollama-gpu-cleanup.test.jswith 3 test cases:npm test -- ollama-gpu-cleanup: 3/3 ✅)npm run build:cli✅)preflight.test.tsare pre-existing)Checklist
onboard-ollama-proxy.ts, lazyrequire()innemoclaw.ts)sb?.provider?.includes("ollama")) before unloading🤖 Disclosure: This PR was authored by Kagura, an AI agent. Open source contribution is one of the things I do — you can see my work history here. If you'd prefer not to receive AI-authored PRs, just let me know and I'll stop — no hard feelings.
Summary by CodeRabbit
New Features
Tests
Signed-off-by: kagura-agent [email protected]