grouprollaws: reap plugins only after the group kill; bound --version
The plugin's exit is observed without reaping (waitid WNOWAIT, kqueue NOTE_EXIT), so its pid and group id stay reserved until the group is killed. The --version run gets its own group, a read deadline and the same kill-then-reap order. The floor comment names aws-cli 37b21e67; version parsing strips whitespace and allows four parts, as the CLI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/grouprollaws/pty_darwin.go+38 −0internal/grouprollaws/pty_linux.go+18 −0internal/grouprollaws/pty_other.go+4 −0internal/grouprollaws/pty_unix.go+124 −22internal/grouprollaws/session.go+26 −35internal/grouprollaws/session_linux_test.go+149 −0internal/grouprollaws/session_test.go+17 −9internal/grouprollaws/testdata/fakeplugin/main.go+42 −12
CI failed — run details
Intent
<task-notification> <task-id>a896eadf34d50bd7e</task-id> <tool-use-id>toolu_016ZB5rNpw6yDfWsLv9eeyzY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a896eadf34d50bd7e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: SSM transport" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS. Task 4 is built and the tests pass. Commit: `182fe4aa grouprollaws: run framed box verbs through Session Manager` on `group-roll-verb`, not pushed. Tests: all of the task's named tests pass, plus checks on how session ids are found across split reads and an exact 4 MiB output case. The full gate passes: the grouproll and grouprollaws suites, the stable rerun (`-count=3`), the region HA boundary test, vet on linux, darwin and windows, both cross-builds and gofmt. I ran 14 deliberate code breaks: 12 failed a test, and the 2 that survived change nothing in practice. I ran `go` with the sandbox off because the default build cache is read-only inside it. Concerns: - **Floor version in the message:** the plugin check is strict, so 1.2.497.0 itself is refused. The approved text reads "Version {floor} or later is required", so I show 1.2.497.1 there and compare against 1.2.497.0. Changing it is a single-constant edit, or the copy could say "newer than {floor}". - **Session id reported earlier than the script did:** it goes to `onSession` straight from the StartSession answer, before the plugin starts, so a session can be cancelled even if the plugin dies. Each id is still reported once. - **StartSession failure:** a failed call returns uncertain `api`, where the script returned refused `remote`. - **Extra file:** shared Linux/Darwin code lives in `pty_unix.go`, which the brief did not list. - **Darwin:** the Mac terminal code builds and passes vet but has not run on a Mac. Report: `.superpowers/sdd/2026-11-09-group-roll-verb/task-4-report.md`</result> <usage><subagent_tokens>168816</subagent_tokens><tool_uses>45</tool_uses><duration_ms>871617</duration_ms></usage> </task-notification>
<task-notification> <task-id>buw1yuj61</task-id> <tool-use-id>toolu_014PjCFQdwT8hTnycMWcL2qu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/buw1yuj61.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra Task 4 review" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 19.7 g CO₂e (2,520,888 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/grouprollaws/pty_darwin.go b/internal/grouprollaws/pty_darwin.go| index a50ded5b4..54ef3f345 100644 |
| --- a/internal/grouprollaws/pty_darwin.go |
| +++ b/internal/grouprollaws/pty_darwin.go |
| @@ -54,3 +54,41 @@ func openPTY() (*pty, error) { |
| } |
| return p, nil |
| } |
| + |
| +// watchExit closes the returned channel once pid has exited, without |
| +// reaping it: a kqueue EVFILT_PROC/NOTE_EXIT event leaves the zombie, and |
| +// with it the pid and process group id, to the caller's cmd.Wait. |
| +func watchExit(pid int) (<-chan struct{}, error) { |
| + kq, err := unix.Kqueue() |
| + if err != nil { |
| + return nil, err |
| + } |
| + var ev unix.Kevent_t |
| + unix.SetKevent(&ev, pid, unix.EVFILT_PROC, unix.EV_ADD|unix.EV_ONESHOT) |
| + ev.Fflags = unix.NOTE_EXIT |
| + ch := make(chan struct{}) |
| + if _, err := unix.Kevent(kq, []unix.Kevent_t{ev}, nil, nil); err != nil { |
| + _ = unix.Close(kq) |
| + if err == unix.ESRCH { |
| + // Already exited (and still unreaped: only the caller reaps). |
| + close(ch) |
| + return ch, nil |
| + } |
| + return nil, err |
| + } |
| + go func() { |
| + defer close(ch) |
| + defer unix.Close(kq) |
| + events := make([]unix.Kevent_t, 1) |
| + for { |
| + n, err := unix.Kevent(kq, nil, events, nil) |
| + if err == unix.EINTR { |
| + continue |
| + } |
| + if err != nil || n > 0 { |
| + return |
| + } |
| + } |
| + }() |
| + return ch, nil |
| +} |
diff --git a/internal/grouprollaws/pty_linux.go b/internal/grouprollaws/pty_linux.go| index e48f86aed..9e1cae833 100644 |
| --- a/internal/grouprollaws/pty_linux.go |
| +++ b/internal/grouprollaws/pty_linux.go |
| @@ -42,3 +42,21 @@ func openPTY() (*pty, error) { |
| } |
| return p, nil |
| } |
| + |
| +// watchExit closes the returned channel once pid has exited, without |
| +// reaping it: waitid(P_PID, WEXITED|WNOWAIT) leaves the zombie, and with it |
| +// the pid and process group id, to the caller's cmd.Wait. |
| +func watchExit(pid int) (<-chan struct{}, error) { |
| + ch := make(chan struct{}) |
| + go func() { |
| + defer close(ch) |
| + var info unix.Siginfo |
| + for { |
| + // ECHILD once the caller has reaped it: done either way. |
| + if err := unix.Waitid(unix.P_PID, pid, &info, unix.WEXITED|unix.WNOWAIT, nil); err != unix.EINTR { |
| + return |
| + } |
| + } |
| + }() |
| + return ch, nil |
| +} |
diff --git a/internal/grouprollaws/pty_other.go b/internal/grouprollaws/pty_other.go| index 628357032..7626811cb 100644 |
| --- a/internal/grouprollaws/pty_other.go |
| +++ b/internal/grouprollaws/pty_other.go |
| @@ -20,3 +20,7 @@ func (p *pty) close() {} |
| func (p *pty) run(context.Context, string, []string, []string, time.Time, func(string)) ([]byte, error) { |
| return nil, grouproll.Refusal{Key: "windows"} |
| } |
| + |
| +func runVersion(context.Context, string, []string, time.Duration) (string, error) { |
| + return "", grouproll.Refusal{Key: "windows"} |
| +} |
diff --git a/internal/grouprollaws/pty_unix.go b/internal/grouprollaws/pty_unix.go| index de8461b37..05c03ff15 100644 |
| --- a/internal/grouprollaws/pty_unix.go |
| +++ b/internal/grouprollaws/pty_unix.go |
| @@ -5,6 +5,7 @@ package grouprollaws |
| import ( |
| "context" |
| "errors" |
| + "io" |
| "os" |
| "os/exec" |
| "syscall" |
| @@ -72,15 +73,60 @@ func readable(fd int, d time.Duration) (bool, error) { |
| return n > 0 && set.IsSet(fd), nil |
| } |
| +// killGroup sends SIGKILL to process group pgid. Callers only use it |
| +// while the group's leader is unreaped, so the id cannot name another |
| +// process's group. Tests wrap it to observe the order. |
| +var killGroup = func(pgid int) error { return unix.Kill(-pgid, unix.SIGKILL) } |
| + |
| +// owned is a started child leading its own process group. It is reaped |
| +// only by finish, which first kills the group when asked: until then the |
| +// leader, alive or a zombie, keeps its pid and so the group id reserved. |
| +// Exit is observed without reaping (watchExit). |
| +type owned struct { |
| + cmd *exec.Cmd |
| + pid int |
| + exited <-chan struct{} |
| + reaped bool |
| + err error // cmd.Wait's answer |
| +} |
| + |
| +func startOwned(cmd *exec.Cmd) (*owned, error) { |
| + if err := cmd.Start(); err != nil { |
| + return nil, err |
| + } |
| + o := &owned{cmd: cmd, pid: cmd.Process.Pid} |
| + exited, err := watchExit(o.pid) |
| + if err != nil { |
| + o.finish(true) |
| + return nil, err |
| + } |
| + o.exited = exited |
| + return o, nil |
| +} |
| + |
| +// finish kills the group if kill is set, then reaps the leader, once. |
| +func (o *owned) finish(kill bool) error { |
| + if !o.reaped { |
| + if kill { |
| + _ = killGroup(o.pid) |
| + } |
| + o.err = o.cmd.Wait() |
| + o.reaped = true |
| + } |
| + return o.err |
| +} |
| + |
| // run is the script's session_output: start the plugin on the slave in a |
| // new session and process group, read the master until it ends or end |
| -// passes, report each session id banner as it appears, then reap. Whatever |
| -// happens, an unreaped plugin's group is killed with SIGKILL before its |
| -// leader is reaped, so the group id cannot be reused meanwhile. |
| +// passes, report each session id banner as it appears, then reap. A plugin |
| +// that has not exited by the time the outcome is decided has its group |
| +// killed with SIGKILL before its leader is reaped (:774-781); the leader |
| +// is never reaped earlier, even when it exits while a descendant still |
| +// holds the terminal. |
| func (p *pty) run(ctx context.Context, path string, argv, env []string, end time.Time, report func(string)) ([]byte, error) { |
| slave := os.NewFile(uintptr(p.slave), "pty") |
| p.slave = -1 |
| - cmd := &exec.Cmd{ |
| + proc, err := startOwned(&exec.Cmd{ |
| Path: path, |
| Args: append([]string{pluginName}, argv...), |
| Env: env, |
| @@ -88,23 +134,13 @@ func (p *pty) run(ctx context.Context, path string, argv, env []string, end time |
| Stdout: slave, |
| Stderr: slave, |
| SysProcAttr: &syscall.SysProcAttr{Setsid: true}, |
| - } |
| - err := cmd.Start() |
| + }) |
| slave.Close() |
| if err != nil { |
| return nil, grouproll.Uncertain{Key: "remote"} |
| } |
| - done := make(chan error, 1) |
| - go func() { done <- cmd.Wait() }() |
| - reaped := false |
| - kill := func() { |
| - if !reaped { |
| - _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL) |
| - <-done |
| - reaped = true |
| - } |
| - } |
| - defer kill() |
| + // Every early return kills the group, then reaps. |
| + defer proc.finish(true) |
| var body []byte |
| buf := make([]byte, 65536) |
| @@ -143,9 +179,9 @@ func (p *pty) run(ctx context.Context, path string, argv, env []string, end time |
| timer := time.NewTimer(max(10*time.Millisecond, time.Until(end))) |
| defer timer.Stop() |
| select { |
| - case err := <-done: |
| - reaped = true |
| - if err != nil { |
| + case <-proc.exited: |
| + // The script's proc.wait() returned: reap without a kill. |
| + if err := proc.finish(false); err != nil { |
| var exit *exec.ExitError |
| if errors.As(err, &exit) { |
| return nil, grouproll.Refusal{Key: "remote"} |
| @@ -154,10 +190,76 @@ func (p *pty) run(ctx context.Context, path string, argv, env []string, end time |
| } |
| return body, nil |
| case <-timer.C: |
| - kill() |
| return nil, grouproll.Uncertain{Key: "remote", Timeout: true} |
| case <-ctx.Done(): |
| - kill() |
| return nil, ctx.Err() |
| } |
| } |
| + |
| +// versionOutputCap is how much of --version's output is kept. |
| +const versionOutputCap = 4096 |
| + |
| +// runVersion runs `session-manager-plugin --version` in its own process |
| +// group with stdin and stderr on /dev/null and returns its stdout. The |
| +// bound covers the whole run: stdout is read with a deadline, so a |
| +// descendant holding it open cannot stall the check, and at the end the |
| +// group is killed before the leader is reaped. A run past the bound, a |
| +// nonzero exit or a failure to start is an error; ctx's cancellation is |
| +// ctx.Err(). |
| +func runVersion(ctx context.Context, path string, env []string, bound time.Duration) (string, error) { |
| + r, w, err := os.Pipe() |
| + if err != nil { |
| + return "", err |
| + } |
| + defer r.Close() |
| + proc, err := startOwned(&exec.Cmd{ |
| + Path: path, |
| + Args: []string{pluginName, "--version"}, |
| + Env: env, |
| + Stdout: w, |
| + SysProcAttr: &syscall.SysProcAttr{Setpgid: true}, |
| + }) |
| + w.Close() |
| + if err != nil { |
| + return "", err |
| + } |
| + // The group is ours whatever happened: kill what is left, then reap. |
| + defer proc.finish(true) |
| + |
| + deadline := time.Now().Add(bound) |
| + if err := r.SetReadDeadline(deadline); err != nil { |
| + return "", err |
| + } |
| + stop := context.AfterFunc(ctx, func() { _ = r.SetReadDeadline(time.Now()) }) |
| + defer stop() |
| + var out []byte |
| + buf := make([]byte, 4096) |
| + for { |
| + n, err := r.Read(buf) |
| + if room := versionOutputCap - len(out); room > 0 { |
| + out = append(out, buf[:min(n, room)]...) |
| + } |
| + if err == io.EOF { |
| + break |
| + } |
| + if err != nil { |
| + if ctx.Err() != nil { |
| + return "", ctx.Err() |
| + } |
| + return "", err |
| + } |
| + } |
| + timer := time.NewTimer(max(0, time.Until(deadline))) |
| + defer timer.Stop() |
| + select { |
| + case <-proc.exited: |
| + if err := proc.finish(true); err != nil { |
| + return "", err |
| + } |
| + return string(out), nil |
| + case <-timer.C: |
| + return "", os.ErrDeadlineExceeded |
| + case <-ctx.Done(): |
| + return "", ctx.Err() |
| + } |
| +} |
diff --git a/internal/grouprollaws/session.go b/internal/grouprollaws/session.go| index 97b8c158c..377de5b13 100644 |
| --- a/internal/grouprollaws/session.go |
| +++ b/internal/grouprollaws/session.go |
| @@ -27,12 +27,14 @@ var _ grouproll.Box = (*Adapter)(nil) |
| // pluginName is the Session Manager plugin the AWS CLI runs. |
| const pluginName = "session-manager-plugin" |
| -// pluginFloor is LAST_PLUGIN_VERSION_WITHOUT_ENV_VAR in the AWS CLI's |
| -// awscli/customizations/sessionmanager.py (aws-cli develop, read |
| -// 2026-11-10). The CLI hands the StartSession answer over in the |
| -// environment only to a plugin strictly newer than this (the version |
| -// check is not inclusive); older plugins get it in argv, token and all, so |
| -// they are refused (spec §5.3, §7 V8). |
| +// pluginFloor is StartSessionCaller.LAST_PLUGIN_VERSION_WITHOUT_ENV_VAR in |
| +// awscli/customizations/sessionmanager.py at aws-cli commit |
| +// 37b21e674b4e262f2789d58b82ac72dfc63e6bdd (develop, 2026-11-10). The CLI |
| +// hands the StartSession answer over in the environment only when |
| +// VersionRequirement.meets_requirement(plugin_version) holds with its |
| +// default inclusive=False, i.e. for a plugin strictly newer than this; |
| +// older plugins get it in argv, token and all, so they are refused (spec |
| +// §5.3, §7 V8). |
| const pluginFloor = "1.2.497.0" |
| // pluginFloorShown is the version the plugin_old text names as the oldest |
| @@ -59,6 +61,9 @@ var sessionTimeouts = map[string]time.Duration{ |
| const defaultSessionTimeout = 15 * time.Second |
| +// versionBound bounds the whole --version run, descendants included. |
| +var versionBound = 15 * time.Second |
| + |
| func sessionBound(verb string) time.Duration { |
| if d, ok := sessionTimeouts[verb]; ok { |
| return d |
| @@ -74,8 +79,11 @@ var ( |
| sessionBannerAny = regexp.MustCompile(`Starting session with SessionId: ([A-Za-z0-9_-]+)`) |
| bannerPrefix = []byte("Starting session with SessionId: ") |
| sessionID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) |
| - pluginVersion = regexp.MustCompile(`^[0-9]+(\.[0-9]+)*$`) |
| - plainVersion = regexp.MustCompile(`^[0-9A-Za-z.+_-]{1,64}$`) |
| + // The CLI's SSM_SESSION_PLUGIN_VERSION_REGEX, after it removes all |
| + // whitespace: one to four numeric components. |
| + pluginVersion = regexp.MustCompile(`^[0-9]+(\.[0-9]+){0,3}$`) |
| + whitespace = regexp.MustCompile(`\s+`) |
| + plainVersion = regexp.MustCompile(`^[0-9A-Za-z.+_-]{1,64}$`) |
| ) |
| // pluginCheck caches the plugin's path and version check for one Adapter. |
| @@ -124,15 +132,16 @@ func checkPlugin(ctx context.Context, env []string) (string, error) { |
| if err != nil { |
| return "", grouproll.Refusal{Key: "plugin_missing"} |
| } |
| - vctx, cancel := context.WithTimeout(ctx, defaultSessionTimeout) |
| - defer cancel() |
| - out := &cappedBuffer{max: 4096} |
| - cmd := exec.CommandContext(vctx, path, "--version") |
| - cmd.Env = env |
| - cmd.Stdout = out |
| - runErr := cmd.Run() |
| - version := strings.TrimSpace(out.String()) |
| - if runErr != nil || !versionAbove(version, pluginFloor) { |
| + out, runErr := runVersion(ctx, path, env, versionBound) |
| + if ctx.Err() != nil { |
| + return "", ctx.Err() |
| + } |
| + var unsupported grouproll.Refusal |
| + if errors.As(runErr, &unsupported) { |
| + return "", unsupported |
| + } |
| + version := strings.TrimSpace(out) |
| + if runErr != nil || !versionAbove(whitespace.ReplaceAllString(out, ""), pluginFloor) { |
| shown := version |
| if !plainVersion.MatchString(shown) { |
| if len(shown) > 64 { |
| @@ -183,24 +192,6 @@ func versionAbove(v, floor string) bool { |
| return false |
| } |
| -type cappedBuffer struct { |
| - buf bytes.Buffer |
| - max int |
| -} |
| - |
| -func (b *cappedBuffer) Write(p []byte) (int, error) { |
| - if room := b.max - b.buf.Len(); room > 0 { |
| - if len(p) > room { |
| - b.buf.Write(p[:room]) |
| - } else { |
| - b.buf.Write(p) |
| - } |
| - } |
| - return len(p), nil |
| -} |
| - |
| -func (b *cappedBuffer) String() string { return b.buf.String() } |
| - |
| // pluginEndpoint is the SSM endpoint the SDK resolves for the client's |
| // region and partition, as the CLI passes client.meta.endpoint_url. The |
| // client has no configured endpoint (newAdapter clears it), so these are |
diff --git a/internal/grouprollaws/session_linux_test.go b/internal/grouprollaws/session_linux_test.go| new file mode 100644 |
| index 000000000..2db5ef082 |
| --- /dev/null |
| +++ b/internal/grouprollaws/session_linux_test.go |
| @@ -0,0 +1,149 @@ |
| +//go:build linux |
| + |
| +package grouprollaws |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +type killCall struct { |
| + pgid int |
| + reserved bool // the leader was still unreaped when the kill was sent |
| +} |
| + |
| +// observeKills wraps killGroup. Each call records whether pgid's leader |
| +// was still an unreaped child of this process (waitid WNOHANG|WNOWAIT: |
| +// ECHILD means it was already reaped and its id may be reused). |
| +func observeKills(t *testing.T) func() []killCall { |
| + t.Helper() |
| + var mu sync.Mutex |
| + var calls []killCall |
| + real := killGroup |
| + killGroup = func(pgid int) error { |
| + var info unix.Siginfo |
| + err := unix.Waitid(unix.P_PID, pgid, &info, unix.WEXITED|unix.WNOHANG|unix.WNOWAIT, nil) |
| + mu.Lock() |
| + calls = append(calls, killCall{pgid: pgid, reserved: err == nil}) |
| + mu.Unlock() |
| + return real(pgid) |
| + } |
| + t.Cleanup(func() { killGroup = real }) |
| + return func() []killCall { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + return append([]killCall(nil), calls...) |
| + } |
| +} |
| + |
| +func TestSessionLeaderExitsBeforeOutputEnds(t *testing.T) { |
| + // The plugin exits at once while its child keeps the terminal open, so |
| + // the read loop outlives the leader. The leader must stay unreaped until |
| + // the group is killed; the child must still be cleaned up. |
| + cases := []struct { |
| + mode string |
| + timeout bool // else the output cap |
| + }{{"orphan", true}, {"orphanflood", false}} |
| + for _, c := range cases { |
| + t.Run(c.mode, func(t *testing.T) { |
| + dir := withFakePlugin(t, fakeControl{Mode: c.mode}) |
| + shortBound(t, 1500*time.Millisecond) |
| + kills := observeKills(t) |
| + a, _ := sessionAdapter(t, "eu-west-1") |
| + _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {}) |
| + if c.timeout { |
| + if u := uncertainKey(t, err); u.Key != "remote" || !u.Timeout { |
| + t.Fatalf("error %#v, want Uncertain{remote, timeout}", u) |
| + } |
| + } else if k := refusalKey(t, err); k != "remote" { |
| + t.Fatalf("refusal %q, want remote", k) |
| + } |
| + f := readRecord(t, dir) |
| + var plugin bool |
| + for _, k := range kills() { |
| + if !k.reserved { |
| + t.Fatalf("SIGKILL sent to group %d after its leader was reaped", k.pgid) |
| + } |
| + plugin = plugin || k.pgid == f.PID |
| + } |
| + if !plugin { |
| + t.Fatalf("the plugin's group %d was never killed: %+v", f.PID, kills()) |
| + } |
| + waitGone(t, "plugin", f.PID) |
| + waitGone(t, "plugin child", f.Child) |
| + }) |
| + } |
| +} |
| + |
| +func TestSessionNormalExitNoKill(t *testing.T) { |
| + // A plugin that ends normally is reaped without a kill, as the script's |
| + // finally skips killpg once returncode is set. |
| + dir := withFakePlugin(t, fakeControl{Body: statusBody}) |
| + a, _ := sessionAdapter(t, "eu-west-1") |
| + if err := a.CheckPlugin(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + kills := observeKills(t) |
| + if _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if k := kills(); len(k) != 0 { |
| + t.Fatalf("kills %+v for plugin %d", k, readRecord(t, dir).PID) |
| + } |
| +} |
| + |
| +func TestPluginVersionBounded(t *testing.T) { |
| + old := versionBound |
| + versionBound = time.Second |
| + t.Cleanup(func() { versionBound = old }) |
| + for _, mode := range []string{"fork", "hang"} { |
| + t.Run(mode, func(t *testing.T) { |
| + dir := withFakePlugin(t, fakeControl{VersionMode: mode}) |
| + kills := observeKills(t) |
| + a, rec := sessionAdapter(t, "eu-west-1") |
| + start := time.Now() |
| + err := a.CheckPlugin(ctx) |
| + elapsed := time.Since(start) |
| + if elapsed > versionBound+time.Second { |
| + t.Fatalf("the check took %v, bound %v", elapsed, versionBound) |
| + } |
| + if k := refusalKey(t, err); k != "plugin_old" { |
| + t.Fatalf("refusal %q, want plugin_old", k) |
| + } |
| + for _, k := range kills() { |
| + if !k.reserved { |
| + t.Fatalf("SIGKILL sent to group %d after its leader was reaped", k.pgid) |
| + } |
| + } |
| + if len(kills()) == 0 { |
| + t.Fatal("the version run's group was never killed") |
| + } |
| + raw, rerr := os.ReadFile(filepath.Join(dir, "fakeplugin-version-child")) |
| + if rerr != nil { |
| + t.Fatal(rerr) |
| + } |
| + pid, _ := strconv.Atoi(strings.TrimSpace(string(raw))) |
| + waitGone(t, "the --version descendant", pid) |
| + // A cancelled check returns promptly too, and is not cached. |
| + c, cancel := contextWithCancelAfter(300 * time.Millisecond) |
| + defer cancel() |
| + b, _ := sessionAdapter(t, "eu-west-1") |
| + start = time.Now() |
| + if err := b.CheckPlugin(c); err == nil || time.Since(start) > 900*time.Millisecond { |
| + t.Fatalf("cancelled check: %v after %v", err, time.Since(start)) |
| + } |
| + if len(rec.requests()) != 0 { |
| + t.Fatalf("requests %v", rec.actions()) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/grouprollaws/session_test.go b/internal/grouprollaws/session_test.go| index d41e9e364..6a52dfd5b 100644 |
| --- a/internal/grouprollaws/session_test.go |
| +++ b/internal/grouprollaws/session_test.go |
| @@ -59,13 +59,14 @@ func startAnswer() string { |
| } |
| type fakeControl struct { |
| - Version string `json:"version,omitempty"` |
| - Mode string `json:"mode,omitempty"` |
| - Body string `json:"body,omitempty"` |
| - Code string `json:"code,omitempty"` |
| - Exit int `json:"exit,omitempty"` |
| - FloodTotal int `json:"flood_total,omitempty"` |
| - BannerID string `json:"banner_id,omitempty"` |
| + Version string `json:"version,omitempty"` |
| + Mode string `json:"mode,omitempty"` |
| + Body string `json:"body,omitempty"` |
| + Code string `json:"code,omitempty"` |
| + Exit int `json:"exit,omitempty"` |
| + FloodTotal int `json:"flood_total,omitempty"` |
| + BannerID string `json:"banner_id,omitempty"` |
| + VersionMode string `json:"version_mode,omitempty"` |
| } |
| type fakeRecord struct { |
| @@ -564,8 +565,9 @@ func TestPluginVersionFloor(t *testing.T) { |
| {"1.2.498.0", true}, |
| {"1.10.0.0", true}, |
| {"2", true}, |
| - {"1.2.497.0.1", true}, |
| - {"1.2.497.0", false}, // the floor itself: the CLI's check is strict |
| + {" 1.2.4 98.0\t", true}, // the CLI removes all whitespace first |
| + {"1.2.497.0.1", false}, // five components: the CLI's regex refuses it |
| + {"1.2.497.0", false}, // the floor itself: the CLI's check is strict |
| {"1.2.497", false}, |
| {"1.2.496.999", false}, |
| {"1.1.999.0", false}, |
| @@ -675,3 +677,9 @@ func TestSessionTimeouts(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func contextWithCancelAfter(d time.Duration) (context.Context, context.CancelFunc) { |
| + c, cancel := context.WithCancel(ctx) |
| + time.AfterFunc(d, cancel) |
| + return c, cancel |
| +} |
diff --git a/internal/grouprollaws/testdata/fakeplugin/main.go b/internal/grouprollaws/testdata/fakeplugin/main.go| index 96eafed08..0a7765f2a 100644 |
| --- a/internal/grouprollaws/testdata/fakeplugin/main.go |
| +++ b/internal/grouprollaws/testdata/fakeplugin/main.go |
| @@ -28,6 +28,24 @@ type control struct { |
| Exit int `json:"exit"` |
| FloodTotal int `json:"flood_total"` |
| BannerID string `json:"banner_id"` // the id the banner names, if not the answer's |
| + // VersionMode: "fork" prints the version and exits, leaving a child |
| + // that holds stdout open; "hang" prints it and never exits. |
| + VersionMode string `json:"version_mode"` |
| +} |
| + |
| +// forkChild starts this program again as a child in the same process |
| +// group, sharing stdout and stderr, ignoring SIGTERM, and returns its pid. |
| +func forkChild(mode string) int { |
| + self, err := os.Executable() |
| + if err != nil { |
| + panic(err) |
| + } |
| + child := exec.Command(self, mode) |
| + child.Stdout, child.Stderr = os.Stdout, os.Stderr |
| + if err := child.Start(); err != nil { |
| + panic(err) |
| + } |
| + return child.Process.Pid |
| } |
| type record struct { |
| @@ -46,8 +64,11 @@ var nonce = regexp.MustCompile(`([0-9a-f]{32}):BEGIN`) |
| func main() { |
| dir := os.Getenv("TMPDIR") |
| - if len(os.Args) > 1 && os.Args[1] == "child" { |
| + if len(os.Args) > 1 && (os.Args[1] == "child" || os.Args[1] == "childflood") { |
| signal.Ignore(syscall.SIGTERM) |
| + if os.Args[1] == "childflood" { |
| + os.Stdout.WriteString(strings.Repeat("x", 4<<20+1)) |
| + } |
| for { |
| time.Sleep(time.Hour) |
| } |
| @@ -64,7 +85,18 @@ func main() { |
| if v == "" { |
| v = "1.2.835.0" |
| } |
| + signal.Ignore(syscall.SIGTERM) |
| + if c.VersionMode == "fork" { |
| + pid := forkChild("child") |
| + _ = os.WriteFile(filepath.Join(dir, "fakeplugin-version-child"), []byte(fmt.Sprint(pid)), 0o600) |
| + } |
| fmt.Println(v) |
| + if c.VersionMode == "hang" { |
| + _ = os.WriteFile(filepath.Join(dir, "fakeplugin-version-child"), []byte(fmt.Sprint(os.Getpid())), 0o600) |
| + for { |
| + time.Sleep(time.Hour) |
| + } |
| + } |
| return |
| } |
| @@ -82,17 +114,11 @@ func main() { |
| _ = unix.SetNonblock(0, false) |
| } |
| signal.Ignore(syscall.SIGTERM) |
| - if c.Mode == "hang" { |
| - self, err := os.Executable() |
| - if err != nil { |
| - panic(err) |
| - } |
| - child := exec.Command(self, "child") |
| - child.Stdout, child.Stderr = os.Stdout, os.Stderr |
| - if err := child.Start(); err != nil { |
| - panic(err) |
| - } |
| - rec.Child = child.Process.Pid |
| + switch c.Mode { |
| + case "hang", "orphan": |
| + rec.Child = forkChild("child") |
| + case "orphanflood": |
| + rec.Child = forkChild("childflood") |
| } |
| raw, _ := json.Marshal(rec) |
| if err := os.WriteFile(filepath.Join(dir, "fakeplugin-record.json"), raw, 0o600); err != nil { |
| @@ -132,6 +158,10 @@ func main() { |
| for { |
| time.Sleep(time.Hour) |
| } |
| + case "orphan", "orphanflood": |
| + // The leader exits at once; its child keeps the terminal open. |
| + os.Stdout.WriteString(banner) |
| + os.Exit(0) |
| case "flood": |
| pad := c.FloodTotal - len(banner) - len(frame) |
| os.Stdout.WriteString(banner + strings.Repeat("x", pad) + frame) |