Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions services/nvpair-engine-manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -493,10 +493,36 @@ Stopped --engine:start----> (adopt if already serving the port, else spawn)
Running --engine:stop-----> (stop signal, bounded grace, force if needed) --> Stopped
```

Detect uses the manifest's `detect` paths. Install is one-shot and
user-mode — an HTTPS download, verified against the manifest's `sha256`
when one is pinned (an unpinned fetch runs with a loud warning). Start
waits for the readiness probe, then runs a periodic health probe; an
Detect uses the manifest's `detect` paths. Install is user-mode — an HTTPS
download, verified against the manifest's `sha256` when one is pinned (an
unpinned fetch runs with a loud warning).

LM Studio installation retries recognized transient download failures up to
three total attempts, with waits of two and four seconds. Each attempt fetches
a fresh installer and removes PAIR's temporary downloads before another attempt
starts. The same policy covers local and remote installations; other engines
retain a single installation attempt. Retrying restarts installation and does
not promise download resumption.

Retryable failures include network timeouts, temporary DNS failures, connection
resets, HTTP 408/429/500/502/503/504, explicit downloader timeout/reset messages,
and LM Studio's `_checksum_value: unbound variable` installer error. That vendor
error can follow a failed checksum download, so it does not establish that the
network timed out. Cancellation, checksum mismatches, permissions, missing
dependencies, unsupported platforms, and unrecognized errors are not retried.

Progress remains in flight during retries. Only the final failure is reported,
using the same reason in the RPC response, progress notification, and error
entry. A confirmed timeout says, "LM Studio download timed out after 3 attempts.
Check your connection and try again." The checksum-variable error without
timeout evidence instead says, "LM Studio’s installer could not download its
checksum after 3 attempts. Check your connection and try again." Other recognized
transient failures say, "LM Studio download failed after 3 attempts. Check your
connection and try again." The original diagnostic and attempt number remain in
service logs. Check connectivity to `lmstudio.ai` and `llmster.lmstudio.ai`, then
use Retry after the connection recovers. Verification is never bypassed.

Start waits for the readiness probe, then runs a periodic health probe; an
unexpected exit is reported. The bundled Ollama manifest allows up to ten
minutes for startup because GPU discovery can exceed the previous 30-second
allowance on supported Windows systems. The deadline remains finite: if Ollama
Expand Down
3 changes: 3 additions & 0 deletions services/nvpair-engine-manager/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ type Executor struct {
// detectTimeout bounds the post-install/uninstall detect poll
// (installers finish their file work asynchronously). Overridable.
detectTimeout time.Duration
// installRetryBackoff spaces LM Studio's transient installation retries.
installRetryBackoff time.Duration
// actionTimeout bounds ordinary engine actions and CLI-driven model pulls so
// a hung engine can't park the goroutine or starve the caller forever.
actionTimeout time.Duration
Expand Down Expand Up @@ -211,6 +213,7 @@ func NewExecutor(reg *Registry, reporter *Reporter, emit func(string, any), base
baseDir: baseDir,
desired: newDesiredStateStore(baseDir),
detectTimeout: 30 * time.Second,
installRetryBackoff: 2 * time.Second,
actionTimeout: 30 * time.Minute,
pullProgressTimeout: 30 * time.Minute,
pullStartTimeout: 30 * time.Second,
Expand Down
61 changes: 36 additions & 25 deletions services/nvpair-engine-manager/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
Expand Down Expand Up @@ -49,22 +50,43 @@ func (e *Executor) Install(ctx context.Context, engine string) error {
}
if presence.Occupied && st.plat.Runtime.modeOrDefault() == "process" {
err := fmt.Errorf("cannot install engine %q for port %d: the port is occupied by a service that did not identify as %s; use the existing service or choose another port", engine, port, st.manifest.DisplayName)
e.reportInstallFailed(engine, err)
return err
return e.reportInstallFailed(engine, err)
}
inst := st.plat.Install
if inst == nil {
return fmt.Errorf("engine %q has no install block for this platform", engine)
}
if inst.ModeOrDefault() == "admin" {
err := fmt.Errorf("engine %q declares an admin install, which is refused (engine-manager is user-mode only)", engine)
e.reportInstallFailed(engine, err)
return err
return e.reportInstallFailed(engine, err)
}
if err := os.MkdirAll(st.installDir, 0o755); err != nil {
return fmt.Errorf("create install dir: %w", err)
}

if err := e.installWithRetry(ctx, engine, st); err != nil {
return e.reportInstallFailed(engine, err)
}

if !e.waitDetect(engine, true, e.detectTimeout) {
err := fmt.Errorf("engine %q was not detected after install", engine)
return e.reportInstallFailed(engine, err)
}
// Claim the install now that it is real and detected. A failure to record it
// only costs the ability to uninstall later, so it must not fail the install.
if err := writeInstallMarker(st.installDir, engine); err != nil {
slog.Warn("could not record that PAIR installed this engine; uninstall will decline it", "engine", engine, "err", err)
}
e.reporter.clear(installFailedID(engine))
e.emitInstallProgress(engine, "done", 100)
e.emitState(engine)
return nil
}

// installAttempt owns one attempt's downloads and cleans them up before returning.
// Terminal reporting belongs to Install, after the attempt settles.
func (e *Executor) installAttempt(ctx context.Context, engine string, st *engineState) error {
inst := st.plat.Install
vars := map[string]string{"install_dir": st.installDir}

if len(inst.Script) > 0 {
Expand All @@ -74,23 +96,20 @@ func (e *Executor) Install(ctx context.Context, engine string) error {
e.emitInstallProgress(engine, "installing", 0)
argv, err := resolveArgs(inst.Script, vars)
if err != nil {
e.reportInstallFailed(engine, err)
return err
}
for i := range argv {
argv[i] = expandPath(argv[i])
}
if err := e.runCommand(ctx, argv); err != nil {
werr := fmt.Errorf("script install failed: %w", err)
e.reportInstallFailed(engine, werr)
return werr
}
} else {
if inst.Fetch != nil {
e.emitInstallProgress(engine, "downloading", 0)
dp, err := e.download(ctx, engine, inst.Fetch)
if err != nil {
e.reportInstallFailed(engine, err)
return err
}
defer os.Remove(dp)
Expand All @@ -101,7 +120,6 @@ func (e *Executor) Install(ctx context.Context, engine string) error {
paths, artifactVars, err := e.downloadInstallArtifacts(ctx, engine, inst.Artifacts)
defer removeDownloadedFiles(paths)
if err != nil {
e.reportInstallFailed(engine, err)
return err
}
maps.Copy(vars, artifactVars)
Expand All @@ -111,33 +129,18 @@ func (e *Executor) Install(ctx context.Context, engine string) error {
e.emitInstallProgress(engine, "installing", 0)
args, err := resolveArgs(inst.Run, vars)
if err != nil {
e.reportInstallFailed(engine, err)
return err
}
for i := range args {
args[i] = expandPath(args[i])
}
if err := e.runCommandWithEnv(ctx, args, installCommandEnv(vars, inst.Artifacts)); err != nil {
werr := fmt.Errorf("install command failed: %w", err)
e.reportInstallFailed(engine, werr)
return werr
}
}
}

if !e.waitDetect(engine, true, e.detectTimeout) {
err := fmt.Errorf("engine %q was not detected after install", engine)
e.reportInstallFailed(engine, err)
return err
}
// Claim the install now that it is real and detected. A failure to record it
// only costs the ability to uninstall later, so it must not fail the install.
if err := writeInstallMarker(st.installDir, engine); err != nil {
slog.Warn("could not record that PAIR installed this engine; uninstall will decline it", "engine", engine, "err", err)
}
e.reporter.clear(installFailedID(engine))
e.emitInstallProgress(engine, "done", 100)
e.emitState(engine)
return nil
}

Expand Down Expand Up @@ -384,7 +387,7 @@ func (e *Executor) downloadWithProgress(
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("download %s: HTTP %d", f.URL, resp.StatusCode)
return "", fmt.Errorf("download %s: %w", f.URL, &downloadHTTPError{status: resp.StatusCode})
}

// Preserve the URL suffix so tools that require one (notably PowerShell's
Expand Down Expand Up @@ -458,12 +461,20 @@ func runManifestCommand(ctx context.Context, argv []string, environment map[stri
return nil
}

func (e *Executor) reportInstallFailed(engine string, err error) {
func (e *Executor) reportInstallFailed(engine string, err error) error {
if engine == "lmstudio" {
var failure *lmsInstallFailure
if kind := classifyLMSInstallFailure(err); kind != "" && !errors.As(err, &failure) {
slog.Warn("LM Studio installer download failed", "engine", engine, "attempt", 1, "category", kind, "err", err)
err = &lmsInstallFailure{cause: err, kind: kind, attempts: 1}
}
}
e.emitInstallFrame(engine, "failed", -1, err.Error())
e.reporter.report(serviceError{
ID: installFailedID(engine), Message: err.Error(),
Severity: "error", Action: "retry", EngineType: engine, Operation: "install",
})
return err
}

// progressWriter counts bytes and reports integer-percent download
Expand Down
150 changes: 150 additions & 0 deletions services/nvpair-engine-manager/installcontrol_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package main

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"
)

func TestEngineManager_ReportsLMStudioDownloadTimeoutOverStdio(t *testing.T) {
f := newInstallFixture(t, "lmstudio", "curl: (28) Operation timed out\nline 228: _checksum_value: unbound variable", 10)
// Give the real worker a private port and an absolute detect path, so it
// cannot adopt or modify an engine installed on the developer's machine.
p := f.manifest.Platforms[hostKey()]
port, err := freePort()
require.NoError(t, err)
p.Runtime.Port = port
p.Runtime.Mode = "process"
f.manifest.Platforms[hostKey()] = p
cfg, home := t.TempDir(), t.TempDir()
for _, dir := range []string{
filepath.Join(cfg, "Nvidia Corporation", "Personal AI Router", "engines"),
filepath.Join(home, "Library", "Application Support", "Nvidia Corporation", "Personal AI Router", "engines"),
} {
require.NoError(t, os.MkdirAll(dir, 0o700))
require.NoError(t, writeJSONAtomic(filepath.Join(dir, "lmstudio.json"), f.manifest))
}
manager := startE2EManager(t, cfg, home)
send(t, manager.stdin, 1, "engine:install", map[string]string{"engine": "lmstudio"})
want := "LM Studio download timed out after 3 attempts. Check your connection and try again."
installing, failed, reported := 0, 0, 0
deadline := time.NewTimer(30 * time.Second)
defer deadline.Stop()
for {
select {
case frame := <-manager.frames:
switch frame.Method {
case "engine:install-progress":
var progress struct{ Engine, Stage, Error string }
require.NoError(t, json.Unmarshal(frame.Params, &progress))
if progress.Engine != "lmstudio" {
continue
}
switch progress.Stage {
case "installing":
installing++
case "failed":
failed++
require.Equal(t, 3, installing, "failure must follow all attempts")
require.Equal(t, want, progress.Error)
}
case "errors:report":
var entry serviceError
require.NoError(t, json.Unmarshal(frame.Params, &entry))
if entry.ID == installFailedID("lmstudio") {
reported++
require.Equal(t, 3, installing)
require.Equal(t, want, entry.Message)
require.Equal(t, "retry", entry.Action)
}
}
if string(frame.ID) == "1" {
var rpcError RPCError
require.NoError(t, json.Unmarshal(frame.Error, &rpcError))
require.Equal(t, -32000, rpcError.Code)
require.Equal(t, want, rpcError.Message)
require.Equal(t, 1, failed)
require.Equal(t, 1, reported)
require.Equal(t, 3, readCount(t, f.counter))
require.Equal(t, int32(3), f.requests.Load())
manager.stop(t)
return
}
case <-deadline.C:
t.Fatal("LM Studio install did not return its terminal RPC error")
}
}
}

func TestRemoteInstall_StreamsOneFailureAfterLMStudioRetries(t *testing.T) {
f := newInstallFixture(t, "lmstudio", "line 213: _checksum_value: unbound variable", 10)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, controlInstallPath, strings.NewReader(`{"opId":"install-test","engine":"lmstudio"}`))
(&controlServer{exec: f.ex}).handleInstall(recorder, request)
frames := decodeFrames(t, recorder.Body.String())
require.NotEmpty(t, frames)
want := "LM Studio’s installer could not download its checksum after 3 attempts. Check your connection and try again."
installing, failed, terminal := 0, 0, 0
for _, frame := range frames {
require.Equal(t, "install-test", frame.OpID)
require.Equal(t, "lmstudio", frame.Engine)
require.Equal(t, "install", frame.Op)
if frame.Type == "progress" {
switch frame.Stage {
case "installing":
installing++
case "failed":
failed++
require.Equal(t, 3, installing)
require.Equal(t, want, frame.Message)
}
} else {
terminal++
require.Equal(t, "error", frame.Type)
require.Equal(t, want, frame.Message)
}
}
require.Equal(t, "error", frames[len(frames)-1].Type)
require.Equal(t, 1, terminal)
require.Equal(t, 1, failed)
require.Equal(t, 3, readCount(t, f.counter))
require.Equal(t, want, f.ex.reporter.snapshot()[0].Message)
}

func TestRemoteInstall_StreamsSuccessAfterLMStudioRecovers(t *testing.T) {
f := newInstallFixture(t, "lmstudio", "curl: (28) Operation timed out", 2)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, controlInstallPath, strings.NewReader(`{"opId":"install-test","engine":"lmstudio"}`))
(&controlServer{exec: f.ex}).handleInstall(recorder, request)
frames := decodeFrames(t, recorder.Body.String())
require.NotEmpty(t, frames)
terminal := frames[len(frames)-1]
require.Equal(t, "result", terminal.Type)
require.NotNil(t, terminal.Status)
require.True(t, terminal.Status.Installed)
results, done := 0, 0
for _, frame := range frames {
require.NotEqual(t, "error", frame.Type)
require.NotEqual(t, "failed", frame.Stage)
if frame.Type == "result" {
results++
}
if frame.Stage == "done" {
done++
}
}
require.Equal(t, 1, results)
require.Equal(t, 1, done)
require.Empty(t, f.ex.reporter.snapshot())
require.Equal(t, 3, readCount(t, f.counter))
}
Loading
Loading