plugin: a host ended ends what its plugin started, at any depth (#5402)

A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

The host now starts as a proc.Tree (new Output.StartTree): a session of
its own on Unix, a job (kill on close) on Windows. host.kill kills the
tree; stop (after stopWait, so EndHosts, Restart, a moved proxy, an
update) and the line-too-long path both use it. A host that ends by
itself is swept by the tree's Wait: the Unix group is killed, the
Windows job closed. Nothing outside the host's own session or job is
signalled, so magpie's own process group is never reached.

Ported from baijiu666's fix/plugin-host-tree (a8172a1), which called
proc.End then Process.Kill. Reviewed against it:
- macOS/Linux: proc.End is SIGTERM to the host pid alone, followed at
  once by SIGKILL; host.js has no SIGTERM handler and the host was in
  magpie's own process group with no session of its own, so nothing it
  started was ended. Red on mote and WSL, same as main.
- Windows: endTree walks living parents, so it covers the killed host
  but not a host that ends on its own (crash, process.exit) or one that
  leaves when its input closes; those were red on Windows too.
- Its test was Windows-only and checked a direct child, which Bun's job
  already ends: the new test checks a grandchild, through a real host.

Run (TestHostEndedEndsWhatItsPluginStarted: a real Bun host whose
plugin starts a child that starts another; subtests stop / killed /
own end):
- origin/main 125fd93ec: red 3/3 on macOS (mote), Windows (win-run) and
  Linux (wsl-run).
- baijiu666's host.go: red 3/3 on macOS and Linux; on Windows red on
  stop and own end, green on killed.
- this change: green 3/3 on all three; -race green on mote and WSL with
  TestEndHostsLeavesNoChild, TestHostReapedWhileItsChildHoldsStdout and
  TestHostRunsAsMagpieBun.
- go test ./internal/plugin ./internal/proc: ok on macOS and Linux; on
  Windows ok except TestPiPackage, red the same at 125fd93ec (no `sh`
  on PATH there; #4115).
- go vet: darwin, linux, windows (./internal/... for windows). gofmt -l
  clean.
Broken by hand: the old and baijiu666 trees above are the fix taken out.
Not tried: a real headless Edge plugin (magpie-magicrew-auth) on
Windows; a plugin reading /dev/tty (the host has no controlling
terminal now, as every proc.Tree child).

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
This commit is contained in:
yetone
2026-11-06 00:34:42 +08:00
co-authored by baijiu666
parent 5666cb0490
commit 5055349922
6 changed files with 224 additions and 8 deletions
+1 -1
View File
@@ -297,7 +297,7 @@ The host is told where magpie's gateway is as `MAGPIE_ADDR` (`hostAddr` in [`hos
What a plugin writes with `console.log`, `console.warn` and the rest goes to the host's stderr, which magpie logs a line at a time (`drainStderr` in [`host.go`](../../internal/plugin/host.go)). A line over 4 MiB ends the logging: magpie logs that it did, and reads and drops the rest, so the host never blocks on a full pipe. Before, nothing read the pipe after such a line: on Windows the host hung on its next write, and on Linux Bun kept everything written after it in memory.
The host is waited for the moment it ends, not when its stdout reaches EOF (`reap` in [`host.go`](../../internal/plugin/host.go), `proc.Output` in [`output.go`](../../internal/proc/output.go)). A program a plugin started that kept a copy of the host's stdout (a `Bun.spawn` given `Bun.stdout`, a daemon it left running) held that pipe open past the host's end, so the reader never saw EOF, the only `cmd.Wait` never ran, and every host stopped (a restart, a moved proxy) stayed a `<defunct>` magpie-bun under magpie until it quit (acezan on Discord, a Linux systemd service). Once the host has ended, the reader has `proc.OutputGrace` (2s) to read its last lines; then its stdout and stderr are closed under their readers and the host fails as one that quit. Every command magpie starts elsewhere is waited for too: one it leaves running goes through `proc.StartReaped`, never `Process.Release`, which doesn't reap on Unix (`TestEveryStartedCommandIsWaited` in [`reap_test.go`](../../internal/proc/reap_test.go)). `TestHostReapedWhileItsChildHoldsStdout` (Linux) runs a real host whose plugin holds its stdout that way and counts this process's `<defunct>` children after each Restart. Before `magpie web` puts a new version in its own place (`Web.Wait`, `update.Reexec`), `plugin.EndHosts` stops every host, waits until each has been waited for, and starts none after: a host still running at the exec is a child nothing waits for after it, one `<defunct>` magpie-bun per restart to update (#3285; `TestEndHostsLeavesNoChild`).
The host is waited for the moment it ends, not when its stdout reaches EOF (`reap` in [`host.go`](../../internal/plugin/host.go), `proc.Output` in [`output.go`](../../internal/proc/output.go)). A program a plugin started that kept a copy of the host's stdout (a `Bun.spawn` given `Bun.stdout`, a daemon it left running) held that pipe open past the host's end, so the reader never saw EOF, the only `cmd.Wait` never ran, and every host stopped (a restart, a moved proxy) stayed a `<defunct>` magpie-bun under magpie until it quit (acezan on Discord, a Linux systemd service). Once the host has ended, the reader has `proc.OutputGrace` (2s) to read its last lines; then its stdout and stderr are closed under their readers and the host fails as one that quit. Every command magpie starts elsewhere is waited for too: one it leaves running goes through `proc.StartReaped`, never `Process.Release`, which doesn't reap on Unix (`TestEveryStartedCommandIsWaited` in [`reap_test.go`](../../internal/proc/reap_test.go)). `TestHostReapedWhileItsChildHoldsStdout` (Linux) runs a real host whose plugin holds its stdout that way and counts this process's `<defunct>` children after each Restart. Before `magpie web` puts a new version in its own place (`Web.Wait`, `update.Reexec`), `plugin.EndHosts` stops every host, waits until each has been waited for, and starts none after: a host still running at the exec is a child nothing waits for after it, one `<defunct>` magpie-bun per restart to update (#3285; `TestEndHostsLeavesNoChild`). The host is started as a `proc.Tree` (`Output.StartTree`): a session of its own on Unix, a job on Windows. Every way a host ends (`stop` after `stopWait`, a line too long, the host ending by itself) ends what its plugins started with it, at any depth: `host.kill` kills the tree, and the wait sweeps what a host that ended by itself left. A host killed alone left a plugin's headless Edge processes running with no parent (Bun's own job lets a child's children out of it on Windows), 620 msedge.exe in an hour on one machine (#5402, baijiu666). Nothing outside the host's session or job is reached, magpie's own process group included. `TestHostEndedEndsWhatItsPluginStarted` runs a real host whose plugin starts a child that starts another, on each of the three ends.
A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`).
+21 -5
View File
@@ -498,6 +498,9 @@ type host struct {
// fake hosts, which have no child
output *proc.Output
waited func() error
// tree is the child with what it starts (Output.StartTree), ended
// together; nil in the fake hosts
tree *proc.Tree
}
// wait is the child's end: what Wait said, once it has ended and the
@@ -923,8 +926,21 @@ func (h *host) stop() {
case <-tick.C:
}
}
h.kill()
}
// kill ends the host's child and every process it started: a plugin's
// headless browser or daemon outlived a host killed alone, with no parent
// to end it (620 msedge.exe and 57GB of temp profiles in an hour on one
// Windows machine, #5402). The tree is the host's session on Unix and its
// job on Windows (proc.StartTree), so nothing outside it is reached.
func (h *host) kill() {
if h.tree != nil {
h.tree.Kill()
return
}
if h.cmd.Process != nil {
h.cmd.Process.Kill()
_ = h.cmd.Process.Kill()
}
}
@@ -1094,7 +1110,8 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
output.Close()
return nil, false, errHostsEnded
}
waited, err := output.Start(cmd)
// in a tree of its own: what its plugins start is ended with it
tree, waited, err := output.StartTree(cmd)
if err != nil {
live.Unlock()
return nil, false, err
@@ -1116,6 +1133,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
addr: addr,
output: output,
waited: waited,
tree: tree,
}
live.hosts[h] = true
live.Unlock()
@@ -1265,9 +1283,7 @@ func (h *host) read(out io.Reader) {
if errors.Is(err, errLineTooLong) {
// a child that never ends a line: stop it rather than allocate
h.fail(fmt.Errorf("the plugin host sent a line longer than %d bytes", h.lineLimit()))
if h.cmd.Process != nil {
_ = h.cmd.Process.Kill()
}
h.kill()
break
}
if err != nil {
+125
View File
@@ -0,0 +1,125 @@
package plugin
import (
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
// The test binary stands in for a program a plugin starts (a headless
// browser, a daemon) when MAGPIE_HOST_TREE_CHILD names a file: it starts
// one of its own, as a browser starts its GPU and renderer processes, and
// sits; that one writes its pid to the file and sits too.
func init() {
if f := os.Getenv("MAGPIE_HOST_TREE_CHILD"); f != "" {
kid := exec.Command(os.Args[0])
kid.Env = append(os.Environ(), "MAGPIE_HOST_TREE_CHILD=", "MAGPIE_HOST_TREE_GRANDCHILD="+f)
if kid.Start() != nil {
os.Exit(1)
}
time.Sleep(90 * time.Second)
os.Exit(0)
}
if f := os.Getenv("MAGPIE_HOST_TREE_GRANDCHILD"); f != "" {
_ = os.WriteFile(f+".tmp", []byte(strconv.Itoa(os.Getpid())), 0o600)
_ = os.Rename(f+".tmp", f)
time.Sleep(90 * time.Second)
os.Exit(0)
}
}
// A plugin host ended ends what its plugin started, at any depth: a host
// killed alone left a plugin's headless Edge's processes running with no
// parent (Bun ends its own children with it on Windows, through a job they
// can start others out of, but not theirs), one more set for
// every host ended (620 msedge.exe and 57GB of temp profiles in an hour on
// one Windows machine, #5402, found and first fixed by baijiu666). Each way
// a host ends is tried: stopped (Restart, as a proxy change or an update
// does) and leaving as its input closes, stopped and killed once stopWait
// has passed (a line too long kills it the same way, host.kill), and the
// host ending by itself.
func TestHostEndedEndsWhatItsPluginStarted(t *testing.T) {
for _, how := range []string{"stop", "killed", "own end"} {
t.Run(how, func(t *testing.T) {
sandbox(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
pidFile := filepath.Join(t.TempDir(), "child.pid")
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
q := func(s string) string { b, _ := json.Marshal(s); return string(b) }
spawn := "Bun.spawn({ cmd: [" + q(self) + "], env: { ...process.env, MAGPIE_HOST_TREE_CHILD: " + q(pidFile) + " }, stdout: \"ignore\", stderr: \"ignore\" })\n"
if how == "killed" {
// a host that doesn't leave when its input closes, so
// stop kills it once stopWait has passed
spawn += "process.exit = () => {}\nsetInterval(() => {}, 1000)\n"
}
if how == "own end" {
spawn += "setTimeout(() => process.exit(3), 500)\n"
}
b, err := os.ReadFile("testdata/fake/index.js")
if err != nil {
t.Fatal(err)
}
js := filepath.Join(t.TempDir(), "index.js")
if err := os.WriteFile(js, append([]byte(spawn), b...), 0o644); err != nil {
t.Fatal(err)
}
if _, err := Add(ctx, js); err != nil {
t.Fatal(err)
}
_, _ = Providers(ctx) // the host may end under it ("own end")
kid := readPID(t, pidFile)
t.Cleanup(func() { endPID(kid) })
hostMu.Lock()
h := current
hostMu.Unlock()
switch how {
case "stop", "killed":
if h == nil {
t.Fatal("no host")
}
Restart()
}
if h != nil {
select {
case <-h.dead:
case <-time.After(30 * time.Second):
t.Fatal("the host isn't ended 30s on")
}
}
until := time.Now().Add(15 * time.Second)
for living(kid) {
if time.Now().After(until) {
t.Fatalf("the process %d the plugin's child started outlived the host (%s)", kid, how)
}
time.Sleep(50 * time.Millisecond)
}
})
}
}
// readPID waits for the plugin's child to write its pid down.
func readPID(t *testing.T, file string) int {
t.Helper()
until := time.Now().Add(30 * time.Second)
for time.Now().Before(until) {
if b, err := os.ReadFile(file); err == nil {
if pid, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && pid > 0 {
return pid
}
}
time.Sleep(50 * time.Millisecond)
}
t.Fatal("the plugin never started its child")
return 0
}
+26
View File
@@ -0,0 +1,26 @@
//go:build !windows
package plugin
import (
"os/exec"
"strconv"
"strings"
"syscall"
)
// living says whether pid runs: one ended and not yet reaped by whoever
// took it in counts as gone.
func living(pid int) bool {
if syscall.Kill(pid, 0) != nil {
return false
}
out, err := exec.Command("ps", "-o", "stat=", "-p", strconv.Itoa(pid)).Output()
if err != nil {
return false
}
s := strings.TrimSpace(string(out))
return s != "" && !strings.HasPrefix(s, "Z")
}
func endPID(pid int) { _ = syscall.Kill(pid, syscall.SIGKILL) }
+27
View File
@@ -0,0 +1,27 @@
//go:build windows
package plugin
import "golang.org/x/sys/windows"
// living says whether pid is still running.
func living(pid int) bool {
const stillActive = 259 // STILL_ACTIVE
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(h)
var code uint32
if err := windows.GetExitCodeProcess(h, &code); err != nil {
return false
}
return code == stillActive
}
func endPID(pid int) {
if h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, uint32(pid)); err == nil {
_ = windows.TerminateProcess(h, 1)
_ = windows.CloseHandle(h)
}
}
+24 -2
View File
@@ -68,7 +68,29 @@ func (o *Output) Close() {
// output has been read or closed; any number of goroutines can call it,
// any number of times. When cmd doesn't start, o is closed.
func (o *Output) Start(cmd *exec.Cmd) (wait func() error, err error) {
err = cmd.Start()
return o.start(cmd, cmd.Start, cmd.Wait)
}
// StartTree is Start for a command started as a Tree (StartTree): what
// it starts in turn is ended with it by the Tree's Kill, and, once it has
// ended on its own, by the wait. A plugin host ended alone left the
// headless browser its plugin had started running with no parent, one
// more for every host ended (620 msedge.exe on one Windows machine,
// #5402).
func (o *Output) StartTree(cmd *exec.Cmd) (*Tree, func() error, error) {
var t *Tree
wait, err := o.start(cmd, func() (err error) {
t, err = StartTree(cmd)
return err
}, func() error { return t.Wait() })
if err != nil {
return nil, nil, err
}
return t, wait, nil
}
func (o *Output) start(cmd *exec.Cmd, start, waitFor func() error) (wait func() error, err error) {
err = start()
for _, w := range o.ws {
w.Close() // the command has its own copies
}
@@ -80,7 +102,7 @@ func (o *Output) Start(cmd *exec.Cmd) (wait func() error, err error) {
ended := make(chan struct{})
var werr error
go func() {
werr = cmd.Wait()
werr = waitFor()
grace := time.NewTimer(OutputGrace)
defer grace.Stop()
for _, s := range []struct {