From 49d049638333014d2c9527247c0bb256e1bf7e98 Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 01:41:15 -0800 Subject: [PATCH 1/6] fix(engine-manager): explain LM Studio installer download failures Signed-off-by: Sherief Farouk --- services/nvpair-engine-manager/install.go | 38 ++++---- .../nvpair-engine-manager/installerrors.go | 93 +++++++++++++++++++ .../installerrors_test.go | 71 ++++++++++++++ 3 files changed, 182 insertions(+), 20 deletions(-) create mode 100644 services/nvpair-engine-manager/installerrors.go create mode 100644 services/nvpair-engine-manager/installerrors_test.go diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index 4c4c2b024..599066501 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -49,8 +49,7 @@ 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 { @@ -58,8 +57,7 @@ func (e *Executor) Install(ctx context.Context, engine string) error { } 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) @@ -74,24 +72,21 @@ 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 + return e.reportInstallFailed(engine, 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 + return e.reportInstallFailed(engine, 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 + return e.reportInstallFailed(engine, err) } defer os.Remove(dp) vars["download"] = dp @@ -101,8 +96,7 @@ 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 + return e.reportInstallFailed(engine, err) } maps.Copy(vars, artifactVars) e.emitInstallProgress(engine, "verified", 50) @@ -111,24 +105,21 @@ 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 + return e.reportInstallFailed(engine, 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 + return e.reportInstallFailed(engine, 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 + 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. @@ -384,7 +375,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 @@ -458,12 +449,19 @@ 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" { + if kind := classifyLMSInstallFailure(err); kind != "" { + 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 diff --git a/services/nvpair-engine-manager/installerrors.go b/services/nvpair-engine-manager/installerrors.go new file mode 100644 index 000000000..e0e9c352d --- /dev/null +++ b/services/nvpair-engine-manager/installerrors.go @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "regexp" + "strings" + "syscall" +) + +type downloadHTTPError struct{ status int } + +func (e *downloadHTTPError) Error() string { return fmt.Sprintf("HTTP %d", e.status) } + +var checksumVariableError = regexp.MustCompile(`_checksum_value: (?:unbound variable|parameter not set)`) + +// lmsInstallFailure keeps the diagnostic available without exposing vendor +// script internals in the message shared by RPC, progress, and errors:report. +type lmsInstallFailure struct { + cause error + kind string + attempts int +} + +func (e *lmsInstallFailure) Unwrap() error { return e.cause } + +func (e *lmsInstallFailure) Error() string { + message := "LM Studio download failed" + switch e.kind { + case "timeout": + message = "LM Studio download timed out" + case "checksum-download": + message = "LM Studio’s installer could not download its checksum" + } + if e.attempts > 1 { + message += fmt.Sprintf(" after %d attempts", e.attempts) + } + return message + ". Check your connection and try again." +} + +func classifyLMSInstallFailure(err error) string { + if err == nil || errors.Is(err, context.Canceled) { + return "" + } + detail := strings.ToLower(err.Error()) + // Never let incidental network text make an integrity failure retryable. + if strings.Contains(detail, "checksum mismatch") { + return "" + } + var networkError net.Error + if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &networkError) && networkError.Timeout()) { + return "timeout" + } + var dnsError *net.DNSError + if errors.As(err, &dnsError) && dnsError.IsTemporary { + return "network" + } + if errors.Is(err, syscall.ECONNRESET) { + return "network" + } + var httpError *downloadHTTPError + if errors.As(err, &httpError) { + switch httpError.status { + case http.StatusRequestTimeout: + return "timeout" + case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + return "network" + } + } + // Only downloader diagnostics qualify; unrelated installer failures may + // contain words such as "download" or "timeout" too. + for _, line := range strings.Split(detail, "\n") { + if !strings.Contains(line, "curl:") && !strings.Contains(line, "wget:") && !strings.Contains(line, "download failed:") { + continue + } + if strings.Contains(line, "timed out") || strings.Contains(line, "timed-out") || strings.Contains(line, "curl: (28)") { + return "timeout" + } + if strings.Contains(line, "connection reset") || strings.Contains(line, "forcibly closed by the remote host") { + return "network" + } + } + if checksumVariableError.MatchString(detail) { + return "checksum-download" + } + return "" +} diff --git a/services/nvpair-engine-manager/installerrors_test.go b/services/nvpair-engine-manager/installerrors_test.go new file mode 100644 index 000000000..b2d3f1b61 --- /dev/null +++ b/services/nvpair-engine-manager/installerrors_test.go @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLMSInstallFailure_ClassifiesDownloadDiagnostics(t *testing.T) { + test := func(name string, err error, want string) { + t.Run(name, func(t *testing.T) { + require.Equal(t, want, classifyLMSInstallFailure(err)) + }) + } + test("checksum variable at reported line", errors.New("install.sh: line 228: _checksum_value: unbound variable"), "checksum-download") + test("checksum variable at different line", errors.New("install.sh: line 213: _checksum_value: unbound variable"), "checksum-download") + test("timeout precedes checksum variable", errors.New("curl: (28) Operation timed out\n_checksum_value: unbound variable"), "timeout") + test("wget timeout", errors.New("wget: connection timed out"), "timeout") + test("downloader reset", errors.New("curl: (56) Recv failure: Connection reset by peer"), "network") + test("wrapped timeout", fmt.Errorf("fetch: %w", context.DeadlineExceeded), "timeout") + test("temporary DNS", &net.DNSError{IsTemporary: true}, "network") + test("wrapped reset", fmt.Errorf("fetch: %w", syscall.ECONNRESET), "network") + for _, status := range []int{http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout} { + test(fmt.Sprintf("HTTP %d", status), &downloadHTTPError{status: status}, "network") + } + test("HTTP request timeout", &downloadHTTPError{status: http.StatusRequestTimeout}, "timeout") + test("HTTP not found", &downloadHTTPError{status: http.StatusNotFound}, "") + test("permanent DNS", &net.DNSError{IsNotFound: true}, "") + test("cancelled", context.Canceled, "") + test("checksum mismatch overrides network wording", errors.New("checksum mismatch: download failed: timed out"), "") + test("permission denied", errors.New("permission denied"), "") + test("missing dependency", errors.New("need curl (command not found)"), "") + test("unsupported platform", errors.New("no compatible downloads were found"), "") + test("unrelated timeout", errors.New("install timeout configuring download directory"), "") + test("different variable", errors.New("_other_value: unbound variable"), "") + test("nil", nil, "") +} + +func TestLMSInstallFailure_FormatsActionableMessages(t *testing.T) { + for _, tc := range []struct{ kind, want string }{ + {"timeout", "LM Studio download timed out after 3 attempts. Check your connection and try again."}, + {"checksum-download", "LM Studio’s installer could not download its checksum after 3 attempts. Check your connection and try again."}, + {"network", "LM Studio download failed after 3 attempts. Check your connection and try again."}, + } { + t.Run(tc.kind, func(t *testing.T) { + cause := errors.New("internal installer diagnostic") + err := &lmsInstallFailure{cause: cause, kind: tc.kind, attempts: 3} + require.EqualError(t, err, tc.want) + require.ErrorIs(t, err, cause) + }) + } +} + +func TestInstallFailure_SharesFormattedReasonAcrossOutputs(t *testing.T) { + ex := NewExecutor(NewRegistry(), NewReporter(nil), func(string, any) {}, t.TempDir()) + var failure string + ex.emit = func(_ string, params any) { failure = params.(map[string]any)["error"].(string) } + err := ex.reportInstallFailed("lmstudio", errors.New("curl: (28) Operation timed out")) + require.EqualError(t, err, "LM Studio download timed out. Check your connection and try again.") + require.Equal(t, err.Error(), failure) + require.Equal(t, err.Error(), ex.reporter.snapshot()[0].Message) +} From 86e92d9fe0d3741c6270a0ffc3b053485ca1a6a5 Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 01:44:17 -0800 Subject: [PATCH 2/6] refactor(engine-manager): isolate an engine installation attempt Signed-off-by: Sherief Farouk --- services/nvpair-engine-manager/install.go | 47 ++++++++++++++--------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index 599066501..ce875ceb4 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -63,6 +63,29 @@ func (e *Executor) Install(ctx context.Context, engine string) error { return fmt.Errorf("create install dir: %w", err) } + if err := e.installAttempt(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 { @@ -72,21 +95,21 @@ func (e *Executor) Install(ctx context.Context, engine string) error { e.emitInstallProgress(engine, "installing", 0) argv, err := resolveArgs(inst.Script, vars) if err != nil { - return 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) - return 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 { - return e.reportInstallFailed(engine, err) + return err } defer os.Remove(dp) vars["download"] = dp @@ -96,7 +119,7 @@ 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 { - return e.reportInstallFailed(engine, err) + return err } maps.Copy(vars, artifactVars) e.emitInstallProgress(engine, "verified", 50) @@ -105,30 +128,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 { - return 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) - return e.reportInstallFailed(engine, werr) + return werr } } } - 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 } From 605f55b22a7747a7abf4273fed45279b9f6ee805 Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 01:48:28 -0800 Subject: [PATCH 3/6] fix(engine-manager): retry transient LM Studio installation failures Signed-off-by: Sherief Farouk --- services/nvpair-engine-manager/executor.go | 3 + services/nvpair-engine-manager/install.go | 6 +- .../nvpair-engine-manager/installretry.go | 49 +++++ .../installretry_test.go | 172 ++++++++++++++++++ .../testdata/fakeengine/main.go | 35 ++++ 5 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 services/nvpair-engine-manager/installretry.go create mode 100644 services/nvpair-engine-manager/installretry_test.go diff --git a/services/nvpair-engine-manager/executor.go b/services/nvpair-engine-manager/executor.go index a4073a7a3..bc1950159 100644 --- a/services/nvpair-engine-manager/executor.go +++ b/services/nvpair-engine-manager/executor.go @@ -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 @@ -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, diff --git a/services/nvpair-engine-manager/install.go b/services/nvpair-engine-manager/install.go index ce875ceb4..e71b1a4c2 100644 --- a/services/nvpair-engine-manager/install.go +++ b/services/nvpair-engine-manager/install.go @@ -7,6 +7,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" "log/slog" @@ -63,7 +64,7 @@ func (e *Executor) Install(ctx context.Context, engine string) error { return fmt.Errorf("create install dir: %w", err) } - if err := e.installAttempt(ctx, engine, st); err != nil { + if err := e.installWithRetry(ctx, engine, st); err != nil { return e.reportInstallFailed(engine, err) } @@ -462,7 +463,8 @@ func runManifestCommand(ctx context.Context, argv []string, environment map[stri func (e *Executor) reportInstallFailed(engine string, err error) error { if engine == "lmstudio" { - if kind := classifyLMSInstallFailure(err); kind != "" { + 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} } diff --git a/services/nvpair-engine-manager/installretry.go b/services/nvpair-engine-manager/installretry.go new file mode 100644 index 000000000..48bb50f6d --- /dev/null +++ b/services/nvpair-engine-manager/installretry.go @@ -0,0 +1,49 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "log/slog" + "time" +) + +const lmsInstallAttempts = 3 + +func (e *Executor) installWithRetry(ctx context.Context, engine string, st *engineState) error { + if engine != "lmstudio" { + return e.installAttempt(ctx, engine, st) + } + for attempt := 1; ; attempt++ { + if err := ctx.Err(); err != nil { + return err + } + err := e.installAttempt(ctx, engine, st) + if err == nil { + return nil + } + // A stopped caller must not be mistaken for a retryable network timeout. + if ctx.Err() != nil { + return ctx.Err() + } + kind := classifyLMSInstallFailure(err) + if kind == "" { + return err + } + slog.Warn("LM Studio installer download failed", "engine", engine, + "attempt", attempt, "of", lmsInstallAttempts, "category", kind, "err", err) + if attempt == lmsInstallAttempts { + return &lmsInstallFailure{cause: err, kind: kind, attempts: attempt} + } + // installAttempt has already removed its temporary downloads. Keep + // progress in flight until a new attempt starts or the operation ends. + timer := time.NewTimer(e.installRetryBackoff * time.Duration(attempt)) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } +} diff --git a/services/nvpair-engine-manager/installretry_test.go b/services/nvpair-engine-manager/installretry_test.go new file mode 100644 index 000000000..afe5e88bb --- /dev/null +++ b/services/nvpair-engine-manager/installretry_test.go @@ -0,0 +1,172 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type installFixture struct { + ex *Executor + manifest *Manifest + counter string + marker string + requests atomic.Int32 + progress installProgressRecorder +} + +func newInstallFixture(t *testing.T, engine, diagnostic string, failures int) *installFixture { + t.Helper() + f := &installFixture{counter: filepath.Join(t.TempDir(), "attempts"), marker: filepath.Join(t.TempDir(), "installed")} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + f.requests.Add(1) + writeTestResponse(t, w, []byte(diagnostic)) + })) + t.Cleanup(server.Close) + f.manifest = testEngineManifest(fakeEngineBin) + f.manifest.Engine = engine + p := f.manifest.Platforms[hostKey()] + p.Detect = []string{f.marker} + p.Install = &Install{ + Fetch: &Fetch{URL: server.URL + "/install.sh"}, + Run: []string{fakeEngineBin, "installsim", f.counter, f.marker, strconv.Itoa(failures), "{download}"}, + } + f.manifest.Platforms[hostKey()] = p + require.NoError(t, f.manifest.Validate()) + f.ex = newTestExecutor(t, f.manifest) + f.ex.installRetryBackoff = time.Millisecond + f.ex.emit = f.progress.emit + return f +} + +func TestLMStudioInstall_RecoversWithoutReportingIntermediateFailure(t *testing.T) { + f := newInstallFixture(t, "lmstudio", "install.sh: line 228: _checksum_value: unbound variable", 2) + f.ex.emit = func(method string, params any) { + f.progress.emit(method, params) + if method == "engine:install-progress" { + p := params.(map[string]any) + if _, measured := p["percent"]; p["stage"] == "downloading" && !measured { + assertNoArtifactTemps(t, "lmstudio") + } + } + } + require.NoError(t, f.ex.Install(t.Context(), "lmstudio")) + require.Equal(t, 3, readCount(t, f.counter)) + require.Equal(t, int32(3), f.requests.Load()) + f.progress.assertSingleTerminal(t, "done") + require.Empty(t, f.ex.reporter.snapshot()) + st, err := f.ex.state("lmstudio") + require.NoError(t, err) + require.True(t, installedByPAIR(st.installDir)) + assertNoArtifactTemps(t, "lmstudio") +} + +func TestLMStudioInstall_ReportsFailureAfterRetryBudget(t *testing.T) { + test := func(name, diagnostic, want string) { + t.Run(name, func(t *testing.T) { + f := newInstallFixture(t, "lmstudio", diagnostic, 10) + err := f.ex.Install(t.Context(), "lmstudio") + require.EqualError(t, err, want) + require.Equal(t, 3, readCount(t, f.counter)) + require.Equal(t, int32(3), f.requests.Load()) + f.progress.assertSingleTerminal(t, "failed") + require.Equal(t, want, f.ex.reporter.snapshot()[0].Message) + require.NoFileExists(t, f.marker) + assertNoArtifactTemps(t, "lmstudio") + }) + } + test("timeout", "curl: (28) Operation timed out\n_checksum_value: unbound variable", "LM Studio download timed out after 3 attempts. Check your connection and try again.") + test("checksum fetch", "line 213: _checksum_value: unbound variable", "LM Studio’s installer could not download its checksum after 3 attempts. Check your connection and try again.") +} + +func TestLMStudioInstall_DoesNotRetryPermanentFailures(t *testing.T) { + for _, diagnostic := range []string{"permission denied", "need curl (command not found)", "no compatible downloads were found", "unexpected installer failure"} { + t.Run(diagnostic, func(t *testing.T) { + f := newInstallFixture(t, "lmstudio", diagnostic, 10) + require.ErrorContains(t, f.ex.Install(t.Context(), "lmstudio"), diagnostic) + require.Equal(t, 1, readCount(t, f.counter)) + f.progress.assertSingleTerminal(t, "failed") + }) + } +} + +func TestLMStudioInstall_RejectsChecksumMismatchWithoutRunningInstaller(t *testing.T) { + f := newInstallFixture(t, "lmstudio", "payload", 0) + f.manifest.Platforms[hostKey()].Install.Fetch.SHA256 = strings.Repeat("0", 64) + require.ErrorContains(t, f.ex.Install(t.Context(), "lmstudio"), "checksum mismatch") + require.Equal(t, int32(1), f.requests.Load()) + require.NoFileExists(t, f.counter) + assertNoArtifactTemps(t, "lmstudio") +} + +func TestOtherEngineInstall_DoesNotRetryDownloadFailure(t *testing.T) { + f := newInstallFixture(t, "other", "curl: (28) Operation timed out", 10) + require.ErrorContains(t, f.ex.Install(t.Context(), "other"), "curl: (28)") + require.Equal(t, 1, readCount(t, f.counter)) + f.progress.assertSingleTerminal(t, "failed") +} + +func TestLMStudioInstall_RecoversFromTransientScriptFetchFailure(t *testing.T) { + f := newInstallFixture(t, "lmstudio", "payload", 0) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if requests.Add(1) < 3 { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + writeTestResponse(t, w, []byte("payload")) + })) + defer server.Close() + f.manifest.Platforms[hostKey()].Install.Fetch.URL = server.URL + require.NoError(t, f.ex.Install(t.Context(), "lmstudio")) + require.Equal(t, int32(3), requests.Load()) + require.Equal(t, 1, readCount(t, f.counter)) + f.progress.assertSingleTerminal(t, "done") +} + +func TestLMStudioInstall_CancelsPendingRetry(t *testing.T) { + f := newInstallFixture(t, "lmstudio", "payload", 0) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + w.WriteHeader(http.StatusServiceUnavailable) + })) + defer server.Close() + f.manifest.Platforms[hostKey()].Install.Fetch.URL = server.URL + f.ex.installRetryBackoff = time.Hour + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) + defer cancel() + require.ErrorIs(t, f.ex.Install(ctx, "lmstudio"), context.DeadlineExceeded) + require.Equal(t, int32(1), requests.Load()) + require.NoFileExists(t, f.counter) + f.progress.assertSingleTerminal(t, "failed") +} + +func TestLMStudioInstall_CancelsActiveScriptFetch(t *testing.T) { + f := newInstallFixture(t, "lmstudio", "payload", 0) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + writeTestResponse(t, w, []byte("partial")) + w.(http.Flusher).Flush() + cancel() + <-r.Context().Done() + })) + defer server.Close() + f.manifest.Platforms[hostKey()].Install.Fetch.URL = server.URL + require.ErrorIs(t, f.ex.Install(ctx, "lmstudio"), context.Canceled) + require.NoFileExists(t, f.counter) + assertNoArtifactTemps(t, "lmstudio") + require.NoFileExists(t, f.marker) +} diff --git a/services/nvpair-engine-manager/testdata/fakeengine/main.go b/services/nvpair-engine-manager/testdata/fakeengine/main.go index 5d0f6c875..da43b0b22 100644 --- a/services/nvpair-engine-manager/testdata/fakeengine/main.go +++ b/services/nvpair-engine-manager/testdata/fakeengine/main.go @@ -334,6 +334,41 @@ func main() { case "noserve": // run but never bind — used to test readiness timeout time.Sleep(time.Hour) return + case "installsim": // fail with the downloaded diagnostic, then install a marker + if len(os.Args) != 6 { + fmt.Fprintln(os.Stderr, "installsim: need counter, marker, failures, download") + os.Exit(2) + } + data, err := os.ReadFile(os.Args[2]) + if err != nil && !os.IsNotExist(err) { + panic(err) + } + count := 0 + if len(data) > 0 { + count, err = strconv.Atoi(string(data)) + if err != nil { + panic(err) + } + } + if err := os.WriteFile(os.Args[2], []byte(strconv.Itoa(count+1)), 0o600); err != nil { + panic(err) + } + failures, err := strconv.Atoi(os.Args[4]) + if err != nil { + panic(err) + } + diagnostic, err := os.ReadFile(os.Args[5]) + if err != nil { + panic(err) + } + if count < failures { + fmt.Fprintln(os.Stderr, string(diagnostic)) + os.Exit(1) + } + if err := os.WriteFile(os.Args[3], []byte("installed"), 0o600); err != nil { + panic(err) + } + return case "failmark": // append a byte then exit non-zero — for uninstall-retry tests if len(os.Args) > 2 { if f, err := os.OpenFile(os.Args[2], os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644); err == nil { From b5ca3cb0ab2d007982138cea636a04523e0a7efd Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 01:50:00 -0800 Subject: [PATCH 4/6] test(engine-manager): verify LM Studio install recovery across control paths Signed-off-by: Sherief Farouk --- .../installcontrol_test.go | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 services/nvpair-engine-manager/installcontrol_test.go diff --git a/services/nvpair-engine-manager/installcontrol_test.go b/services/nvpair-engine-manager/installcontrol_test.go new file mode 100644 index 000000000..e5d90a764 --- /dev/null +++ b/services/nvpair-engine-manager/installcontrol_test.go @@ -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)) +} From 9535d78650285581722205d6ed151b93d8e9691a Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 01:59:47 -0800 Subject: [PATCH 5/6] docs(engine-manager): describe LM Studio installation recovery Signed-off-by: Sherief Farouk --- services/nvpair-engine-manager/README.md | 34 +++++++++++++++++++++--- services/nvpair-engine-manager/spec.md | 15 +++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 2f41e9393..ac6ce52cf 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -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 diff --git a/services/nvpair-engine-manager/spec.md b/services/nvpair-engine-manager/spec.md index 91aac87ce..87809782e 100644 --- a/services/nvpair-engine-manager/spec.md +++ b/services/nvpair-engine-manager/spec.md @@ -435,6 +435,21 @@ fails it with the peer's error message. ## 12. Failure Modes and Mitigations - **Download / checksum failure on install**: engine stays NotInstalled. → Fail fast before `run`; `engine:install-progress` error + `errors:report` (`engine-manager:install-failed:`); never execute an unverified payload. +- **Transient LM Studio installation download failure**: retry the fetch-and-run + sequence up to three total attempts, waiting two and four seconds between + attempts while holding the lifecycle lock. Retry timeouts, temporary DNS + failures, connection resets, HTTP 408/429/500/502/503/504, explicit downloader + timeout/reset diagnostics, and the vendor's `_checksum_value` unbound-variable + error (independent of its script line number). Remove each attempt's temporary + downloads before retrying. Do not retry cancellation, checksum mismatches, or + other permanent/unrecognized failures. Preserve existing command timeouts and + verification. Keep existing nonterminal progress during retries; report a + terminal failure only once, using the same readable reason in the RPC error, + `engine:install-progress`, and `errors:report`. Identify a timeout only when + evidence supports it; otherwise describe a failed checksum download or generic + download failure. Retain the original diagnostic, category, and attempt number + in service logs. Both local and remote installs share this behavior; other + engines keep a single attempt. - **Engine fails its readiness probe**: start never reaches Running. → Bounded ready timeout → back to Stopped; structured error; no half-started state. - **Engine process crashes**: engine unavailable. → A watcher flips state, emits `engine:state-changed` + `errors:report` (`engine-manager:exited:`); the parent's supervisor reports if the *manager itself* dies. (Automatic restart is planned — see §4 — not yet implemented.) - **A status check overlaps a stop or port change**: an old result could restore From 33c5269e69fd82ca190774c4e7c35238af8bee6d Mon Sep 17 00:00:00 2001 From: Sherief Farouk Date: Tue, 24 Nov 2026 02:04:05 -0800 Subject: [PATCH 6/6] fix(engine-manager): recognize Windows installer connection resets Signed-off-by: Sherief Farouk --- .../nvpair-engine-manager/installerrors.go | 3 +-- .../installerrors_unix.go | 15 +++++++++++++++ .../installerrors_windows.go | 14 ++++++++++++++ .../installerrors_windows_test.go | 18 ++++++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 services/nvpair-engine-manager/installerrors_unix.go create mode 100644 services/nvpair-engine-manager/installerrors_windows.go create mode 100644 services/nvpair-engine-manager/installerrors_windows_test.go diff --git a/services/nvpair-engine-manager/installerrors.go b/services/nvpair-engine-manager/installerrors.go index e0e9c352d..c3cff3f02 100644 --- a/services/nvpair-engine-manager/installerrors.go +++ b/services/nvpair-engine-manager/installerrors.go @@ -11,7 +11,6 @@ import ( "net/http" "regexp" "strings" - "syscall" ) type downloadHTTPError struct{ status int } @@ -61,7 +60,7 @@ func classifyLMSInstallFailure(err error) string { if errors.As(err, &dnsError) && dnsError.IsTemporary { return "network" } - if errors.Is(err, syscall.ECONNRESET) { + if isInstallConnectionReset(err) { return "network" } var httpError *downloadHTTPError diff --git a/services/nvpair-engine-manager/installerrors_unix.go b/services/nvpair-engine-manager/installerrors_unix.go new file mode 100644 index 000000000..2b0ea2367 --- /dev/null +++ b/services/nvpair-engine-manager/installerrors_unix.go @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows + +package main + +import ( + "errors" + "syscall" +) + +func isInstallConnectionReset(err error) bool { + return errors.Is(err, syscall.ECONNRESET) +} diff --git a/services/nvpair-engine-manager/installerrors_windows.go b/services/nvpair-engine-manager/installerrors_windows.go new file mode 100644 index 000000000..54ccbc8b4 --- /dev/null +++ b/services/nvpair-engine-manager/installerrors_windows.go @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "errors" + "syscall" +) + +func isInstallConnectionReset(err error) bool { + // Windows sockets return the Winsock code, distinct from ECONNRESET. + return errors.Is(err, syscall.WSAECONNRESET) || errors.Is(err, syscall.ECONNRESET) +} diff --git a/services/nvpair-engine-manager/installerrors_windows_test.go b/services/nvpair-engine-manager/installerrors_windows_test.go new file mode 100644 index 000000000..72eec19d1 --- /dev/null +++ b/services/nvpair-engine-manager/installerrors_windows_test.go @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "net" + "os" + "syscall" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLMSInstallFailure_ClassifiesWindowsSocketReset(t *testing.T) { + err := &net.OpError{Op: "read", Net: "tcp", Err: &os.SyscallError{Syscall: "wsarecv", Err: syscall.WSAECONNRESET}} + require.Equal(t, "network", classifyLMSInstallFailure(err)) +}