plugin, gui: magpie web ends its plugin hosts, waited for, before it runs the new version (#3285)

The second way acezan's 57 <defunct> magpie-bun (v0.1.2819, a Linux
systemd service, 47 hours) pile up: magpie web's restart to update
(AutoRestart) runs the new version with syscall.Exec in the same pid.
The running plugin host was the old image's child, and the old image's
host.read held the only Wait for it. After the exec nothing waits for
it, so it ends on stdin EOF and stays <defunct> under that pid, one per
restart to update. skygunner reproduced it and AAEE86 counted 22 zombies
for 23 images under one pid (#3285). With about a hundred releases a
day, an AutoRestart service makes about one a hour, as acezan's did.

- plugin.EndHosts (host.go) stops every host started and not yet
  reaped, including the retiring ones, waits until each one has been
  waited for, and refuses to start another (errHostsEnded). startOn
  starts the host and records it under one lock (live), so a host that
  starts during EndHosts isn't missed.
- Web.Wait calls it right before update.Reexec.

Run at 72bc741ef (on origin/main 40a287b21, after the previous commit):
- mote (macOS): gofmt -l clean; go vet ./internal/gui ./internal/plugin,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
  go test -count=1 -timeout 45m ./internal/plugin: ok; -run Web
  ./internal/gui: ok.
- WSL magpie-desktop (Linux): ./internal/plugin ok, including
  TestEndHostsLeavesNoChild and TestHostReapedWhileItsChildHoldsStdout
  with a real Bun host; -race -count=3 of both: ok; go vet -tags nogui
  and -run Web of ./internal/gui: ok.

Both commits were then rebased onto 0acba61a3, which changes only
app.js and plugin-checkin.test.cjs; no Go file these runs built moved,
and they were not run again there.

Broken by hand: EndHosts returning at once makes
TestEndHostsLeavesNoChild fail on Linux ("children left once EndHosts
returned: [16459 S bun]").

Not tried: a real magpie web restart to update (a downloaded update
exec'd in the same pid) on Linux. The test covers EndHosts, not the
exec. Not changed: anything else alive at the exec (pii's helper,
awake's caffeinate, #4188) still outlives it the same way.

Reported by acezan on Discord. Diagnosed in #3285 by skygunner and
AAEE86.
This commit is contained in:
yetone
2026-11-03 17:58:31 +08:00
parent a9a8f11e7f
commit f4c664a09c
4 changed files with 126 additions and 1 deletions
+1 -1
View File
@@ -283,7 +283,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.
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`).
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`).
+5
View File
@@ -21,6 +21,7 @@ import (
"github.com/klauspost/compress/gzhttp"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/update"
)
@@ -141,6 +142,10 @@ func (w *Web) Wait() error {
if err != nil {
return err
}
// the plugin hosts end, waited for, first: one still running at the
// exec is a child nothing waits for after it, <defunct> under this
// pid from then on (#3285)
plugin.EndHosts()
return update.Reexec(exe, os.Args[1:], append(os.Environ(), webRunKey+"="+w.key))
}
+53
View File
@@ -518,6 +518,49 @@ func (h *host) wait() error {
// at once and closes the pipe a moment later, which ends the reader too.
func (h *host) reap() {
h.fail(quitErr(h.wait()))
live.Lock()
delete(live.hosts, h)
live.Unlock()
}
// live are the hosts started and not yet reaped, the retired ones on their
// way out among them.
var live = struct {
sync.Mutex
hosts map[*host]bool
// ended is set by EndHosts: no host starts after it
ended bool
}{hosts: map[*host]bool{}}
// errHostsEnded is a host asked for once EndHosts has run.
var errHostsEnded = errors.New("magpie is restarting; the plugins are back in a moment")
// EndHosts stops every plugin host, waits until each has been waited for,
// and starts none after: what magpie runs before it puts a new version in
// its own place (update.Reexec). A host still running at the exec was one
// nothing waited for after it, so each restart to update (magpie web's
// AutoRestart) left one <defunct> magpie-bun under magpie's pid for as long
// as it ran (#3285, found by skygunner and AAEE86; acezan on Discord saw
// 57 after 47 hours as a systemd service).
func EndHosts() {
live.Lock()
live.ended = true
hs := make([]*host, 0, len(live.hosts))
for h := range live.hosts {
hs = append(hs, h)
}
live.Unlock()
hostMu.Lock()
current = nil
hostMu.Unlock()
var wg sync.WaitGroup
for _, h := range hs {
wg.Go(func() {
h.stop()
_ = h.wait()
})
}
wg.Wait()
}
// quitErr is the error of a host whose child ended with err.
@@ -1040,8 +1083,16 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
if err != nil {
return nil, false, err
}
// started and counted live under one lock, so EndHosts misses none
live.Lock()
if live.ended {
live.Unlock()
output.Close()
return nil, false, errHostsEnded
}
waited, err := output.Start(cmd)
if err != nil {
live.Unlock()
return nil, false, err
}
hctx, hcancel := context.WithCancel(context.Background())
@@ -1062,6 +1113,8 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) {
output: output,
waited: waited,
}
live.hosts[h] = true
live.Unlock()
go func() {
drainStderr(output.Err)
output.ErrRead()
+67
View File
@@ -115,3 +115,70 @@ func killSleeps(secs string) {
}
}
}
// EndHosts, which magpie runs before it puts a new version in its place,
// returns with every host ended and waited for, and starts none after: a
// host left running
// at the exec was a <defunct> magpie-bun under magpie's pid from then on
// (#3285).
func TestEndHostsLeavesNoChild(t *testing.T) {
sandbox(t)
t.Cleanup(func() {
live.Lock()
live.ended = false
live.Unlock()
})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
abs, _ := filepath.Abs("testdata/fake/index.js")
if _, err := Add(ctx, abs); err != nil {
t.Fatal(err)
}
if _, err := Providers(ctx); err != nil {
t.Fatal(err)
}
if len(childrenNamed("bun")) == 0 {
t.Fatal("no host running to end")
}
EndHosts()
if c := childrenNamed("bun"); len(c) > 0 {
t.Fatalf("children left once EndHosts returned: %v", c)
}
hostMu.Lock()
_, err := getLocked(ctx)
hostMu.Unlock()
if err == nil {
t.Fatal("a host started after EndHosts")
}
if c := childrenNamed("bun"); len(c) > 0 {
t.Fatalf("children after a host was asked for: %v", c)
}
}
// childrenNamed lists this process's children, running or <defunct>,
// whose name holds name.
func childrenNamed(name string) []string {
me := strconv.Itoa(os.Getpid())
ents, _ := os.ReadDir("/proc")
var c []string
for _, e := range ents {
if _, err := strconv.Atoi(e.Name()); err != nil {
continue
}
b, err := os.ReadFile("/proc/" + e.Name() + "/stat")
if err != nil {
continue
}
s := string(b)
i := strings.LastIndexByte(s, ')')
if i < 0 || i+2 > len(s) {
continue
}
f := strings.Fields(s[i+2:])
comm := s[strings.IndexByte(s, '(')+1 : i]
if len(f) > 1 && f[1] == me && strings.Contains(comm, name) {
c = append(c, e.Name()+" "+f[0]+" "+comm)
}
}
return c
}