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
10 changes: 7 additions & 3 deletions services/nvpair-engine-manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<pid>/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
Expand Down
5 changes: 3 additions & 2 deletions services/nvpair-engine-manager/lifecycle_stop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 33 additions & 3 deletions services/nvpair-engine-manager/proc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
60 changes: 60 additions & 0 deletions services/nvpair-engine-manager/proc_darwin.go
Original file line number Diff line number Diff line change
@@ -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
}
108 changes: 108 additions & 0 deletions services/nvpair-engine-manager/proc_darwin_test.go
Original file line number Diff line number Diff line change
@@ -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 <pid> -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")
}
54 changes: 54 additions & 0 deletions services/nvpair-engine-manager/proc_linux.go
Original file line number Diff line number Diff line change
@@ -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/<pid>/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
}
50 changes: 4 additions & 46 deletions services/nvpair-engine-manager/proc_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.).
Expand Down