proc: EndProbes returns once a killed probe's whole group is gone, so an exit right after can't leave a missed child running (#1278)

JJ-Lin's fault injection on #1278: when the first signal to a probe's
group missed a process being forked, group.kill went on signalling it
from a goroutine nobody waited for, and the probe counted as ended as
soon as the first signal went out. EndProbes returned in ~0.2ms; magpie
then exiting (or Exec'ing the new version) ended that goroutine, and the
missed child lived on with PPID 1.

group.kill now returns a channel closed once none of the group is left
(or killFor has passed). A probe's Cancel marks its kill as begun and
counts the probe ended only when that channel closes. EndProbes waits up
to endWait for each kill to begin (a probe that already answered has
none, as before) and then for the group to be empty, bounded by killFor
plus a second. Every exit path goes through EndProbes: the GUI's
OnShutdown, the CLI's return and signal handler, and update.Reexec.

Windows: the job's TerminateJobObject takes no new process once it is
ending, and a probe is killed alone with TerminateProcess, so there was
no background loop to outlive; kill returns a closed channel there. The
known Windows gap that a shim's children aren't in a job for probes is
unchanged.

Run:
- TestEndProbesThenExitLeavesNothing (new) re-runs the test binary as a
  magpie whose group signals miss for 300ms, which calls EndProbes and
  os.Exit(0) at once. On the old code it fails 3/3 on darwin: "what the
  probe started (pid N) outlived magpie's exit after EndProbes".
- darwin: go test -race ./internal/proc ok; -race -count=10 of the
  probe/EndProbes tests ok.
- linux (docker golang:1.26.8 --init, GOTOOLCHAIN=local): -race -count=5
  of the probe/tree tests ok. Without --init the container's PID 1
  reaps nothing and every group test fails on zombies, on old code too.
- Windows box: new TestEndProbesWindows (ping probe ended, EndProbes
  ~0ms) passes 3/3; the rest of the package passes except
  TestNoCommandBypassesProc, which walks ../.. and found other
  checkouts in C:\Users\yeton since the binary ran outside a tree.
- gofmt -l, go vet (darwin), GOOS=linux vet -tags nogui, GOOS=windows vet.
This commit is contained in:
yetone
2026-10-13 05:21:03 +08:00
parent 1f0ff81dfc
commit 73ce9765f1
8 changed files with 161 additions and 22 deletions
+22 -11
View File
@@ -18,7 +18,7 @@ import (
// exits. ctx must end (a timeout): the probe is forgotten when it does.
func ProbeContext(ctx context.Context, name string, args ...string) *exec.Cmd {
ctx, cancel := context.WithCancel(ctx)
p := &probe{cancel: cancel, ended: make(chan struct{})}
p := &probe{cancel: cancel, killing: make(chan struct{}), ended: make(chan struct{})}
cmd := CommandContext(ctx, name, args...)
probeGroup(cmd, p)
probes.Lock()
@@ -33,24 +33,29 @@ func ProbeContext(ctx context.Context, name string, args ...string) *exec.Cmd {
}
type probe struct {
cancel context.CancelFunc
once sync.Once
ended chan struct{} // closed once it was killed
cancel context.CancelFunc
killOnce, once sync.Once
killing, ended chan struct{} // closed once its kill began, and once it was over
}
func (p *probe) end() { p.once.Do(func() { close(p.ended) }) }
func (p *probe) kill() { p.killOnce.Do(func() { close(p.killing) }) }
func (p *probe) end() { p.once.Do(func() { close(p.ended) }) }
var probes = struct {
sync.Mutex
m map[*probe]struct{}
}{m: map[*probe]struct{}{}}
// endWait is how long EndProbes waits for the probes to be killed.
// endWait is how long EndProbes waits for a probe's kill to begin: one that
// had answered, or never started, has none.
var endWait = time.Second
// EndProbes kills every probe still running, with what it started, and
// waits a moment for that: magpie is exiting or putting a new version in its
// place, and nothing would end them after.
// waits until none of that is left: magpie is exiting or putting a new
// version in its place, and nothing would end them after. A kill that missed
// a process being forked signals the group again until it is empty, and an
// exit before that left the missed one running, adopted by init (#1278); the
// wait is bounded by how long a kill goes on (killFor on Unix).
func EndProbes() {
probes.Lock()
ps := make([]*probe, 0, len(probes.m))
@@ -61,12 +66,18 @@ func EndProbes() {
for _, p := range ps {
p.cancel()
}
deadline := time.After(endWait)
begun := time.Now().Add(endWait)
over := begun.Add(killWait())
for _, p := range ps {
select {
case <-p.killing:
case <-time.After(time.Until(begun)):
continue // one that had answered already, or never started
}
select {
case <-p.ended:
case <-deadline:
return // one that had answered already, or never started
case <-time.After(time.Until(over)):
return
}
}
}
+14 -4
View File
@@ -2,16 +2,26 @@
package proc
import "os/exec"
import (
"os/exec"
"time"
)
// probeGroup has the probe lead a session, and its context ending kill the
// session's group: the script at its head and what that started.
// session's group: the script at its head and what that started. The probe
// counts as ended once none of the group is left, not once the first signal
// went out (#1278).
func probeGroup(cmd *exec.Cmd, p *probe) {
ownGroup(cmd)
cmd.Cancel = func() error {
defer p.end()
p.kill()
var g group
g.kill(cmd)
gone := g.kill(cmd)
go func() { <-gone; p.end() }()
return cmd.Process.Kill()
}
}
// killWait is how long EndProbes waits, past a kill's start, for the group
// to be empty: as long as the kill goes on signalling it, and a moment more.
func killWait() time.Duration { return killFor + time.Second }
+64
View File
@@ -163,3 +163,67 @@ func TestProbeKillEndsWhatTheSignalMissed(t *testing.T) {
t.Fatalf("what the probe started (pid %d) outlived a kill that missed it once", pid)
}
}
// missFor has the group's signal reach nobody for d from its first call, as
// signals racing a launcher's forks do, and puts the real one back after.
func missFor(t *testing.T, d time.Duration) {
old := signalGroup
var mu sync.Mutex
var first time.Time
signalGroup = func(pgid int) error {
mu.Lock()
if first.IsZero() {
first = time.Now()
}
missing := time.Since(first) < d
mu.Unlock()
if missing {
return nil // sent, and reached nobody
}
return old(pgid)
}
t.Cleanup(func() { signalGroup = old })
}
// magpie exiting right after EndProbes leaves nothing of a probe running,
// even when the kill missed some of it at first (JJ-Lin's case on #1278):
// EndProbes returned after the first signal, the exit ended the loop that
// signals the group again, and the missed child lived on, adopted by init.
// The exit is a real one: the test runs itself as a magpie that ends its
// probes and exits at once.
func TestEndProbesThenExitLeavesNothing(t *testing.T) {
if os.Getenv("MAGPIE_PROC_EXIT_HELPER") == "1" {
missFor(t, 300*time.Millisecond)
sh, pidFile := probeScript(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
done := runProbe(ProbeContext(ctx, sh))
pid := childPid(t, pidFile, done)
os.Stdout.WriteString("child " + strconv.Itoa(pid) + "\n")
EndProbes()
os.Exit(0)
}
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
cmd := exec.Command(self, "-test.run=^TestEndProbesThenExitLeavesNothing$")
cmd.Env = append(os.Environ(), "MAGPIE_PROC_EXIT_HELPER=1")
out, err := cmd.Output()
if err != nil {
t.Fatalf("the exiting magpie: %v\n%s", err, out)
}
var pid int
for _, l := range strings.Split(string(out), "\n") {
if s, ok := strings.CutPrefix(l, "child "); ok {
pid, _ = strconv.Atoi(s)
}
}
if pid == 0 {
t.Fatalf("the exiting magpie named no child:\n%s", out)
}
t.Cleanup(func() { _ = syscall.Kill(pid, syscall.SIGKILL) })
if !gone(pid) {
t.Fatalf("what the probe started (pid %d) outlived magpie's exit after EndProbes", pid)
}
}
+9 -1
View File
@@ -1,6 +1,9 @@
package proc
import "os/exec"
import (
"os/exec"
"time"
)
// probeGroup kills the probe alone, as CommandContext does: a job, as
// StartTree gives a command, is joined only once it has started, and Output
@@ -8,7 +11,12 @@ import "os/exec"
// so what a shim started (npm's .cmd running node) is still left running.
func probeGroup(cmd *exec.Cmd, p *probe) {
cmd.Cancel = func() error {
p.kill()
defer p.end()
return cmd.Process.Kill()
}
}
// killWait is how long EndProbes waits, past a kill's start, for it to be
// over: the probe is killed alone, and nothing is signalled again.
func killWait() time.Duration { return time.Second }
+33
View File
@@ -4,12 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
func TestHideWithoutConsole(t *testing.T) {
@@ -84,3 +86,34 @@ func TestEchoArgs(t *testing.T) {
fmt.Fprintf(os.Stdout, "%s\n", b)
os.Exit(0)
}
// a probe still asking when magpie exits is ended by EndProbes, and
// EndProbes returns once its kill is over, not after its whole wait (#1278)
func TestEndProbesWindows(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
cmd := ProbeContext(ctx, "ping", "-n", "60", "127.0.0.1")
out, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
done := make(chan error, 1)
go func() {
_, _ = io.Copy(io.Discard, out)
done <- cmd.Wait()
}()
time.Sleep(500 * time.Millisecond) // asking, not starting
start := time.Now()
EndProbes()
if d := time.Since(start); d > endWait {
t.Fatalf("EndProbes took %v over a probe it killed", d)
}
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("the probe went on after EndProbes")
}
}
+1 -1
View File
@@ -45,6 +45,6 @@ func (t *Tree) Kill() {
if t.done {
return
}
t.kill(t.cmd)
_ = t.kill(t.cmd)
_ = t.cmd.Process.Kill()
}
+11 -4
View File
@@ -31,8 +31,12 @@ func (group) join(*exec.Cmd) {}
// is still in the group, and the group keeps its id while any of it lives,
// so the group is signalled again until none of it is left. Its leader,
// killed and not yet waited for, counts until it is: hence behind the
// caller, which waits for it next.
func (group) kill(cmd *exec.Cmd) {
// caller, which waits for it next. The channel closes once none of the group
// is left, or killFor has passed: magpie exiting or putting a new version in
// its place waits for it, since an exit ends the loop with what it missed
// still running (#1278).
func (group) kill(cmd *exec.Cmd) <-chan struct{} {
gone := make(chan struct{})
pgid := cmd.Process.Pid
// the one kill function for the whole kill, taken once: the loop below
// outlives the caller, and a test swapping signalGroup for its own and
@@ -40,9 +44,11 @@ func (group) kill(cmd *exec.Cmd) {
// data race TestProbeKillEndsWhatTheSignalMissed went red under).
signal := signalGroup
if signal(pgid) != nil {
return // none of it is left
close(gone) // none of it is left
return gone
}
go func() {
defer close(gone)
for end := time.Now().Add(killFor); time.Now().Before(end); {
time.Sleep(5 * time.Millisecond)
if signal(pgid) != nil {
@@ -50,6 +56,7 @@ func (group) kill(cmd *exec.Cmd) {
}
}
}()
return gone
}
// signalGroup kills the group pgid leads; a var so a test can have it miss.
@@ -61,4 +68,4 @@ var killFor = 10 * time.Second
// sweep ends what is left of the group once its leader is gone: the group
// keeps the leader's pid while any of it runs, so none else has it.
func (g group) sweep(cmd *exec.Cmd) { g.kill(cmd) }
func (g group) sweep(cmd *exec.Cmd) { _ = g.kill(cmd) }
+7 -1
View File
@@ -39,12 +39,18 @@ func (g *group) join(cmd *exec.Cmd) {
g.job = job
}
func (g *group) kill(*exec.Cmd) {
// kill ends the job's processes. Unlike a Unix group, a job takes no new
// process once it is being ended, so nothing can be missed and nothing is
// left to wait on: the channel is closed already.
func (g *group) kill(*exec.Cmd) <-chan struct{} {
if g.job != 0 {
_ = windows.TerminateJobObject(g.job, 1)
}
return closed
}
var closed = func() chan struct{} { c := make(chan struct{}); close(c); return c }()
func (g *group) sweep(*exec.Cmd) {
if g.job != 0 {
_ = windows.CloseHandle(g.job)