From 4d9e2b86aa20d6bd98d9bc77854875432bd637c4 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Wed, 25 Nov 2026 16:40:28 -0700 Subject: [PATCH] fix(engine-manager): resolve process images on macOS via lsof Orphan reclaim in Stop compares the executable the kernel mapped for the port's PID against our managed binary, but procImage read only Linux's /proc, so on macOS the image was always empty and the fail-closed check declined even a clearly managed orphan: TestUninstall_TerminatesRunningInstance failed there and the lifecycle_stop reclaim/decline tests skipped. Give procImage and procRunsScript per-platform homes. Linux keeps the /proc reads verbatim; darwin asks lsof for the process's txt mappings (-Fn, one path per line), whose first entry is the exec'd binary - that is kernel vnode info, unlike ps, which echoes spoofable argv. A venv script engine (vLLM) keeps declining on macOS, as before: no trustworthy command line is readable there. isOurEngineImage gains a canonicalised retry so macOS's canonical /private/var/... image spelling matches a managed path written through the /var symlink; anything unresolvable still fails closed. Signed-off-by: Steven Beverly --- services/nvpair-engine-manager/README.md | 10 +- .../lifecycle_stop_test.go | 5 +- services/nvpair-engine-manager/proc.go | 36 +++++- services/nvpair-engine-manager/proc_darwin.go | 60 ++++++++++ .../nvpair-engine-manager/proc_darwin_test.go | 108 ++++++++++++++++++ services/nvpair-engine-manager/proc_linux.go | 54 +++++++++ services/nvpair-engine-manager/proc_unix.go | 50 +------- 7 files changed, 269 insertions(+), 54 deletions(-) create mode 100644 services/nvpair-engine-manager/proc_darwin.go create mode 100644 services/nvpair-engine-manager/proc_darwin_test.go create mode 100644 services/nvpair-engine-manager/proc_linux.go diff --git a/services/nvpair-engine-manager/README.md b/services/nvpair-engine-manager/README.md index 2f41e9393..fc9b092ad 100644 --- a/services/nvpair-engine-manager/README.md +++ b/services/nvpair-engine-manager/README.md @@ -540,9 +540,13 @@ would only collide on the port. Consequences worth knowing: - **An adopted engine has no child process the service owns**, so `engine:stop` (and `engine:restart`'s stop phase, and shutdown's cleanup) resolves the PID bound to the engine's port and terminates it **only when that process is - running the very binary NVPAIR manages for the engine** (for an engine - installed as a Python package, such as vLLM, that is the interpreter running the - engine's script, read from the process's command line on Linux) — reclaiming an orphan + running the very binary NVPAIR manages for the engine**, read from what the + kernel mapped at exec time (`/proc//exe` on Linux, the first `txt` + image lsof reports on macOS) rather than the process's own argv, which + anything can rewrite (for an engine installed as a Python package, such as + vLLM, that is the interpreter running the engine's script, read from the + process's command line where it can be trusted, on Linux; a script-run + vLLM on macOS stays declined) — reclaiming an orphan a prior run left on our own managed port (e.g. an `ollama serve` on `11435` whose handle was lost after a crash). This is precise to the port, so a genuine third-party listener on a *different* port (Ollama's own desktop app diff --git a/services/nvpair-engine-manager/lifecycle_stop_test.go b/services/nvpair-engine-manager/lifecycle_stop_test.go index 701b2f73b..d555bef73 100644 --- a/services/nvpair-engine-manager/lifecycle_stop_test.go +++ b/services/nvpair-engine-manager/lifecycle_stop_test.go @@ -34,8 +34,9 @@ func TestStop_TerminatesManagedEngineWithinGracePeriod(t *testing.T) { // spawnFakeListener starts a fake-engine copied to binPath, bound to // 127.0.0.1:port, and skips the test when this host can't resolve the PID/ -// image behind a listening port (no lsof/ss, or a /proc-less OS) — the -// reclaim/decline behavior can't be exercised without that resolution. +// image behind a listening port (no lsof/ss, or a kernel that reports no +// executable for a PID) — the reclaim/decline behavior can't be exercised +// without that resolution. func spawnFakeListener(t *testing.T, binPath string, port int) *exec.Cmd { t.Helper() cmd := exec.Command(binPath) diff --git a/services/nvpair-engine-manager/proc.go b/services/nvpair-engine-manager/proc.go index a408e0e1a..ed01593c7 100644 --- a/services/nvpair-engine-manager/proc.go +++ b/services/nvpair-engine-manager/proc.go @@ -191,13 +191,43 @@ func normalizeEngineImage(path string) string { // running the same binary this service manages for the engine (st.binPath). // The compare is path-cleaned and case-insensitive so a PAIR-owned orphan on // our managed port is reclaimed by Stop, while an unrelated process that -// merely grabbed the port is left for the caller to decline. An empty image -// (e.g. a PID we can't introspect) never matches, so Stop fails closed. +// merely grabbed the port is left for the caller to decline. When that first +// compare differs only in spelling — macOS reports a running process's image +// canonically (/private/var/...) while a managed path can be written through +// a symlink (/var/...) — it tries again with every symlink component +// resolved. An empty image (e.g. a PID we can't introspect) never matches, +// so Stop fails closed. func isOurEngineImage(image, binPath string) bool { if image == "" || binPath == "" { return false } - return strings.EqualFold(normalizeEngineImage(image), normalizeEngineImage(binPath)) + want, ours := normalizeEngineImage(image), normalizeEngineImage(binPath) + if strings.EqualFold(want, ours) { + return true + } + canImage, ok := canonicalPath(want) + if !ok { + return false + } + canOurs, ok := canonicalPath(ours) + return ok && strings.EqualFold(canImage, canOurs) +} + +// canonicalPath resolves every symlink component of an absolute path. When +// the final element itself no longer exists — a replaced binary still +// running, whose kernel-reported path names the deleted file — the directory +// is resolved instead and the name re-joined, mirroring how the " (deleted)" +// suffix still matches on Linux. A path that cannot be resolved at all +// answers false, which is the fail-closed direction. +func canonicalPath(path string) (string, bool) { + if canon, err := filepath.EvalSymlinks(path); err == nil { + return canon, true + } + canon, err := filepath.EvalSymlinks(filepath.Dir(path)) + if err != nil { + return "", false + } + return filepath.Join(canon, filepath.Base(path)), true } // isManagedInstallPath reports whether binPath is inside this engine's diff --git a/services/nvpair-engine-manager/proc_darwin.go b/services/nvpair-engine-manager/proc_darwin.go new file mode 100644 index 000000000..6a2fc7ccf --- /dev/null +++ b/services/nvpair-engine-manager/proc_darwin.go @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build darwin + +package main + +import ( + "context" + "os/exec" + "strconv" + "strings" +) + +// procImage resolves a PID's executable path from what the kernel mapped, not +// from what the process's caller wrote: lsof's txt entries list the mapped +// executables, and the first is always the one that was exec'd (the dynamic +// linker and shared libraries follow). Unlike ps — which echoes argv[0] as it +// was last written and so can be told to name any file — this reports the +// vnode the kernel opened at exec time, so a foreign listener cannot present +// itself as our managed binary. -Fn asks for just the path fields, one per +// line, so paths with spaces need no column parsing. macOS answers in +// canonical form (/private/var/...); isOurEngineImage folds the symlink +// spellings together. An exited PID, a process we may not introspect, or a +// lookup that resolves nothing all answer "" and the caller fails closed. +func procImage(pid int) string { + if pid <= 0 { + return "" + } + ctx, cancel := context.WithTimeout(context.Background(), portLookupTimeout) + defer cancel() + out, err := exec.CommandContext(ctx, "lsof", "-a", "-p", strconv.Itoa(pid), "-d", "txt", "-Fn").Output() + if err != nil && len(out) == 0 { + return "" + } + return parseLsofExecName(string(out)) +} + +// parseLsofExecName returns the first n-field of lsof -F output — the path of +// the first txt entry, which is the executed binary. It answers "" for output +// with no name fields, keeping an unresolved lookup on the fail-closed path. +func parseLsofExecName(out string) string { + for line := range strings.SplitSeq(out, "\n") { + if name, ok := strings.CutPrefix(line, "n"); ok && name != "" { + return name + } + } + return "" +} + +// procRunsScript reports whether pid was started as an interpreter running the +// engine script at binPath. The honest answer needs the process's own command +// line, and macOS exposes only views of it that echo what the process's +// caller wrote, which the identity gate must not trust. So an engine +// installed as a script — vLLM's venv/bin/vllm — is not recognised here: +// Stop declines it and says so, exactly as before macOS image lookups +// existed. Fail closed, like every other unresolvable identity. +func procRunsScript(pid int, binPath string) bool { + return false +} diff --git a/services/nvpair-engine-manager/proc_darwin_test.go b/services/nvpair-engine-manager/proc_darwin_test.go new file mode 100644 index 000000000..208ef0d45 --- /dev/null +++ b/services/nvpair-engine-manager/proc_darwin_test.go @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build darwin + +package main + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// startTempEngine copies the fake engine into dir and runs it in its +// `noserve` mode (stays alive, binds no port). The copies run from paths +// spelled the way a managed install is spelled — under $TMPDIR, which macOS +// hides behind the /var → /private/var symlink — and one directory name +// carries a space, because macOS reports paths in their canonical shape and +// leaves spaces unquoted, and both are things the identity check survives in +// production. +func startTempEngine(t *testing.T, dir, name string) (*managedProc, string) { + t.Helper() + require.NoError(t, os.MkdirAll(dir, 0o755)) + binPath := filepath.Join(dir, name) + copyFile(t, fakeEngineBin, binPath) + proc, err := startManagedProc(binPath, []string{"noserve"}, nil, nil) + require.NoError(t, err) + t.Cleanup(func() { proc.stop(0) }) + return proc, binPath +} + +// waitForImage gives the kernel-backed lookup a moment after the process +// starts: on a loaded machine the first probe can still catch it mid-launch. +func waitForImage(t *testing.T, pid int) string { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + image := procImage(pid) + if image != "" || !time.Now().Before(deadline) { + return image + } + time.Sleep(50 * time.Millisecond) + } +} + +// TestProcImage_IdentifiesOurManagedCopyUnderASymlinkedTempRoot proves the +// identity gate Stop uses for orphan reclaim can fire on macOS: the image +// read from the running process and the manifest's managed path name one +// file once isOurEngineImage canonicalises, even though macOS spells a +// temporary path /private/var/... while t.TempDir answers /var/.... +func TestProcImage_IdentifiesOurManagedCopyUnderASymlinkedTempRoot(t *testing.T) { + proc, binPath := startTempEngine(t, filepath.Join(t.TempDir(), "engine bin"), "fakeu") + image := waitForImage(t, proc.cmd.Process.Pid) + require.NotEmpty(t, image, "a live process must report its executable image on macOS") + assert.Contains(t, image, filepath.Join("engine bin", "fakeu"), + "the image must name the running copy with its full path, spaces included (image %q)", image) + + require.True(t, isOurEngineImage(image, binPath), + "procImage and the manifest path name one file, but the check declined them: %q vs %q", image, binPath) + + // The fail-closed side: a same-named, byte-identical copy elsewhere is + // foreign, and canonicalising must not blur the two. + otherDir := t.TempDir() + other := filepath.Join(otherDir, "fakeu") + copyFile(t, fakeEngineBin, other) + assert.False(t, isOurEngineImage(image, other), + "an identical copy at a different path must not read as our managed binary (%q vs %q)", image, other) +} + +func TestProcImage_ReportsNothingForProcessesThatAlreadyExited(t *testing.T) { + assert.Empty(t, procImage(0), "pid 0 is not a process") + assert.Empty(t, procImage(999_999_999), "a pid far above anything this machine assigns never existed") + + proc, _ := startTempEngine(t, t.TempDir(), "fakeu") + pid := proc.cmd.Process.Pid + require.NotEmpty(t, waitForImage(t, pid), "precondition: the copy runs and reports its image") + + proc.stop(0) + select { + case <-proc.done: // the managed-proc goroutine reaped the child + case <-time.After(5 * time.Second): + require.FailNow(t, "test engine did not exit") + } + assert.Empty(t, procImage(pid), "an exited process must fail closed, not report a stale image") +} + +// The fixtures below are real `lsof -a -p -d txt -Fn` captures, kept +// verbatim so the parser is pinned to the format lsof actually emits. + +// TestParseLsofExecName_PicksTheExecutedBinaryAheadOfItsLibraries covers the +// one contract the identity gate relies on: the first path field is the +// exec'd binary, not dyld or a library — including when the path carries +// spaces or the executable sits inside an app bundle. +func TestParseLsofExecName_PicksTheExecutedBinaryAheadOfItsLibraries(t *testing.T) { + const copiedBinaryWithSpaces = "p87789\nftxt\nn/private/tmp/pair space dir/fake u\nftxt\nn/usr/lib/dyld\n" + assert.Equal(t, "/private/tmp/pair space dir/fake u", parseLsofExecName(copiedBinaryWithSpaces)) + + const pythonFramework = "p87795\nftxt\nn/opt/homebrew/Cellar/python@3.14/3.14.10/Frameworks/Python.framework/Versions/3.14/Resources/Python.app/Contents/MacOS/Python\nftxt\nn/usr/lib/dyld\n" + assert.Equal(t, "/opt/homebrew/Cellar/python@3.14/3.14.10/Frameworks/Python.framework/Versions/3.14/Resources/Python.app/Contents/MacOS/Python", + parseLsofExecName(pythonFramework)) + + assert.Empty(t, parseLsofExecName("p12345\n"), "a record with no path fields reports nothing") + assert.Empty(t, parseLsofExecName(""), "lsof on a dead pid prints nothing at all") +} diff --git a/services/nvpair-engine-manager/proc_linux.go b/services/nvpair-engine-manager/proc_linux.go new file mode 100644 index 000000000..c374d3fff --- /dev/null +++ b/services/nvpair-engine-manager/proc_linux.go @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package main + +import ( + "os" + "path/filepath" + "strconv" + "strings" +) + +// procImage resolves a PID's executable path by reading /proc//exe. An +// unknown or exited PID answers "", and the caller fails closed. +func procImage(pid int) string { + if pid <= 0 { + return "" + } + if path, err := os.Readlink("/proc/" + strconv.Itoa(pid) + "/exe"); err == nil { + return path + } + return "" +} + +// procRunsScript reports whether pid was started as an interpreter running the +// engine script at binPath. An engine installed as a Python package (vLLM's +// venv/bin/vllm) is a script, so the process's executable is the interpreter and +// procImage never matches binPath; what does match is the script named in the +// command line, as one of its first arguments ("python /path/venv/bin/vllm +// serve ..."). Only Linux exposes a trustworthy command line through /proc: +// the darwin build answers false, which keeps script-run engines failing +// closed. +func procRunsScript(pid int, binPath string) bool { + if pid <= 0 || binPath == "" { + return false + } + raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline") + if err != nil { + return false + } + want := filepath.Clean(binPath) + if !filepath.IsAbs(want) { + return false // an engine path is absolute; a bare word could match any argument + } + args := strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00") + for i := 0; i < len(args) && i < 3; i++ { + if args[i] != "" && filepath.Clean(args[i]) == want { + return true + } + } + return false +} diff --git a/services/nvpair-engine-manager/proc_unix.go b/services/nvpair-engine-manager/proc_unix.go index 8707b2e9d..8677b3ee2 100644 --- a/services/nvpair-engine-manager/proc_unix.go +++ b/services/nvpair-engine-manager/proc_unix.go @@ -8,18 +8,17 @@ package main import ( "context" "errors" - "os" "os/exec" - "path/filepath" "strconv" "strings" "syscall" "time" ) -// portLookupTimeout bounds each external port-owner lookup (lsof/ss). The -// broker no longer force-kills engine-manager on a timeout, so an unbounded -// lookup that hung would wedge StopAll (and the whole app shutdown). +// portLookupTimeout bounds each external lookup against a live process +// (port owner via lsof/ss, executable image via lsof). The broker no longer +// force-kills engine-manager on a timeout, so an unbounded lookup that hung +// would wedge StopAll (and the whole app shutdown). const portLookupTimeout = 2 * time.Second // configureSysProcAttr puts the child in its own process group so a @@ -95,47 +94,6 @@ func ssPID(port int) (int, bool) { return 0, false } -// procImage resolves a PID's executable path via /proc (Linux). macOS has no -// /proc, so it returns "" there and the image check is skipped — reclamation -// on macOS relies on the caller declining when the image can't be confirmed. -func procImage(pid int) string { - if pid <= 0 { - return "" - } - if path, err := os.Readlink("/proc/" + strconv.Itoa(pid) + "/exe"); err == nil { - return path - } - return "" -} - -// procRunsScript reports whether pid was started as an interpreter running the -// engine script at binPath. An engine installed as a Python package (vLLM's -// venv/bin/vllm) is a script, so the process's executable is the interpreter and -// procImage never matches binPath; what does match is the script named in the -// command line, as one of its first arguments ("python /path/venv/bin/vllm -// serve ..."). Linux only: elsewhere there is no /proc to read, and the answer -// is false, which keeps the caller failing closed. -func procRunsScript(pid int, binPath string) bool { - if pid <= 0 || binPath == "" { - return false - } - raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline") - if err != nil { - return false - } - want := filepath.Clean(binPath) - if !filepath.IsAbs(want) { - return false // an engine path is absolute; a bare word could match any argument - } - args := strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00") - for i := 0; i < len(args) && i < 3; i++ { - if args[i] != "" && filepath.Clean(args[i]) == want { - return true - } - } - return false -} - // signalPID sends SIGTERM (or SIGKILL when force) to the process group when // possible. The owned-process escalation and orphan reclaim share it so forced // stops reach forked helpers (model runners, etc.).