//go:build linux package mac import ( "context" "errors" "os" "os/exec" "path/filepath" "slices" "strconv" "strings" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" ) // These tests run real processes on Linux through the /pr table. The // machine is shared, so every table here is scoped: it lists, and // signals, only processes whose environment carries this test's // EQUIPO_TEST_SCOPE nonce (or its own unique marker). The runner-user // sweep therefore sees the test's processes as a Mac's turn sees the // runner user's, and can never reach anyone else's. type launchRig struct { t *testing.T nonce string procs Procs turns *Turns x *Executor } func newLaunchRig(t *testing.T, extra ...string) *launchRig { t.Helper() nonce := token()[:12] procs := proc.Scoped(append([]string{proc.ScopeEnv + "=" + nonce}, extra...)...) turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(procs) turns.Settle = 3 * time.Second r := &launchRig{t: t, nonce: nonce, procs: procs, turns: turns, x: &Executor{Turns: turns, Grace: 300 * time.Millisecond, Settle: 3 * time.Second, Poll: 50 * time.Millisecond}} t.Cleanup(func() { // Whatever of the test's own is left (a failed test): by scope. if list, err := procs.List(time.Now().Add(5*time.Second), nil); err == nil { for _, q := range list { _ = procs.Signal(q.PID, syscall.SIGKILL) } } }) return r } func (r *launchRig) env(more ...string) []string { return append([]string{"PATH=/usr/bin:/bin", proc.ScopeEnv + "=" + r.nonce}, more...) } func (r *launchRig) take(op Op) (context.Context, *Turn) { r.t.Helper() u, err := r.turns.Take(context.Background(), op) if err != nil { r.t.Fatal(err) } return u.Context(context.Background()), u } // start runs argv in a session of its own with env (reaped when it // ends, so a dead one is not a zombie in a group). func (r *launchRig) start(env []string, argv ...string) *exec.Cmd { r.t.Helper() c := exec.Command(argv[0], argv[1:]...) c.Env = env c.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := c.Start(); err != nil { r.t.Fatal(err) } go func() { _ = c.Wait() }() r.waitListed(c.Process.Pid) return c } // waitListed waits until the table shows pid (the kernel shows a new // environment a moment after the exec). func (r *launchRig) waitListed(pid int) ProcInfo { r.t.Helper() for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { if q, ok := r.procs.Lookup(pid); ok { return q } } r.t.Fatalf("pid %d never listed", pid) return ProcInfo{} } func gone(pid int) bool { return syscall.Kill(pid, 0) == syscall.ESRCH } func hasKey(m span, k int) bool { _, ok := m[k]; return ok } // waitPID reads a pid a script wrote to file. func waitPID(t *testing.T, file string) int { t.Helper() for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { raw, _ := os.ReadFile(file) if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 { return pid } } t.Fatalf("no pid in %s", file) return 0 } // engLaunch is the Engineering launch rig with body as the pinned CLI, // a unique marker, and a scoped table that sees what carries it. func engLaunch(t *testing.T, body string) (*engRig, *launchRig) { t.Helper() er := newEngRigWith(t, []byte(body)) er.in.Attempt = "attempt-" + token()[:12] return er, newLaunchRig(t, "EQUIPO_ATTEMPT="+er.in.Attempt) } // The marker is on the step row (and the turn's record) before the CLI // starts; the group once it exists. A marker that cannot be written // starts nothing; a group that cannot be stops the CLI at once, proven. func TestEngineeringLaunchRecordsMarkerThenGroup(t *testing.T) { er, r := engLaunch(t, "#!/bin/sh\ntouch \"$TMPDIR/started\"\ncat <&3 >/dev/null\nread line\n") p := er.policy() argv := claude.DarwinArgv(p) started := filepath.Join(er.in.Scratch, "started") marker := er.in.Attempt ctx, turn := r.take(OpEngineering) defer turn.Give() launch := func(fail int) (provider.Process, []string, error) { var ids []string pctx, kill := context.WithCancel(ctx) t.Cleanup(kill) s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)} pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, argv, func(_ context.Context, rec containment.Record) error { ids = append(ids, rec.ID) if len(ids) == 1 { if exists(started) { t.Error("the CLI started before its marker was on record") } if rec, ok, _ := r.turns.loadTurn(); !ok || !slices.Contains(rec.Markers, marker) { t.Error("the turn's record lacks the marker at the first write") } } if len(ids) == 2 { pgid, _, _ := parseRecord(rec.ID) if pgid <= 1 || syscall.Kill(-pgid, 0) != nil { t.Errorf("group %d recorded before it existed", pgid) } } if len(ids) == fail { return errors.New("disk full") } return nil }) return pr, ids, err } pr, ids, err := launch(0) if err != nil { t.Fatal(err) } if len(ids) != 2 || ids[0] != RecordID(0, marker) || !strings.HasPrefix(ids[1], "pg:") || !strings.HasSuffix(ids[1], ":"+marker) || ids[1] == ids[0] || pr.ID() != ids[1] { t.Fatalf("records %v, process %s", ids, pr.ID()) } pgid, _, _ := parseRecord(ids[1]) if rec, ok, _ := r.turns.loadTurn(); !ok || !hasKey(rec.Groups, pgid) { t.Fatalf("the turn's record lacks the group: %+v", rec) } pr.Stdin().Close() if _, err := pr.Wait(context.Background()); err != nil || !gone(pgid) { t.Fatalf("a CLI that ended by itself: %v", err) } // The marker cannot be written: nothing starts. _ = os.Remove(started) if _, ids, err = launch(1); !errors.Is(err, ErrRecord) || len(ids) != 1 || ids[0] != RecordID(0, marker) { t.Fatalf("first write failed: %v %v", err, ids) } time.Sleep(200 * time.Millisecond) if exists(started) { t.Fatal("the CLI ran without its marker on record") } // The group cannot be written: stopped at once, and proven. if _, ids, err = launch(2); !errors.Is(err, ErrRecord) || errors.Is(err, ErrUnproven) || len(ids) != 2 { t.Fatalf("second write failed: %v %v", err, ids) } if pgid, _, _ := parseRecord(ids[1]); !gone(pgid) { t.Fatal("the CLI outlived its failed group record") } } // A fake CLI starts two Bash-like commands in sessions of their own, as // Claude Code does (setsid): one keeps the marker, one scrubbed it. Both // ignore SIGTERM. Cancelling the launch ends them (SIGKILL after the // grace), and the proof waits for that: nothing of the attempt is alive // when Wait says it ended. func TestEngineeringTerminationGroupAndMarker(t *testing.T) { scope := token()[:12] body := "#!/bin/bash\ncat <&3 >/dev/null\nexport " + proc.ScopeEnv + "=" + scope + "\n" + "setsid bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/marked\"; exec sleep 60' &\n" + "setsid env -u EQUIPO_ATTEMPT bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/scrubbed\"; exec sleep 60' &\n" + "read line\n" er, r := engLaunch(t, body) r.procs = proc.Scoped(proc.ScopeEnv+"="+scope, "EQUIPO_ATTEMPT="+er.in.Attempt) r.turns.Sweep(r.procs) p := er.policy() ctx, turn := r.take(OpEngineering) defer turn.Give() pctx, kill := context.WithCancel(ctx) defer kill() s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)} pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil }) if err != nil { t.Fatal(err) } marked, scrubbed := waitPID(t, filepath.Join(er.in.Scratch, "marked")), waitPID(t, filepath.Join(er.in.Scratch, "scrubbed")) for _, pid := range []int{marked, scrubbed} { if q := r.waitListed(pid); q.SID != pid || q.PGID != pid { t.Fatalf("%d is not in a session of its own: %+v", pid, q) } } waited := make(chan error, 1) go func() { _, err := pr.Wait(context.Background()); waited <- err }() stopped := time.Now() kill() if err := <-waited; err != nil { t.Fatalf("end not proven: %v", err) } if !gone(marked) || !gone(scrubbed) { t.Fatal("proven over with a command still running") } if took := time.Since(stopped); took < r.x.Grace { t.Fatalf("proven in %s, before the grace ended what ignores SIGTERM", took) } if rec, ok, _ := r.turns.loadTurn(); !ok || len(rec.Groups) < 3 || len(rec.Sessions) < 3 { t.Fatalf("the turn's record lacks the commands' groups and sessions: %+v", rec) } } // After a restart: a recorded group alive with no marked process in it // (a child that scrubbed its environment, or the id used again) is never // killed, and the attempt is not proven over while it lives. func TestRestartUnmarkedSurvivorWithholdsProof(t *testing.T) { r := newLaunchRig(t) r.x.Settle = 500 * time.Millisecond survivor := r.start(r.env(), "/bin/sleep", "60") id := RecordID(survivor.Process.Pid, "attempt-u-"+r.nonce) if r.x.Verify(id) { t.Fatal("proven over while its recorded group is alive") } if gone(survivor.Process.Pid) { t.Fatal("an unmarked group was killed") } // The same through a gate (the worker's Verify). g := &Gate{Turns: r.turns, Settle: 500 * time.Millisecond} if g.Verify(id) || gone(survivor.Process.Pid) { t.Fatal("the gate proved or killed it") } _ = survivor.Process.Kill() for deadline := time.Now().Add(5 * time.Second); !gone(survivor.Process.Pid) && time.Now().Before(deadline); { time.Sleep(10 * time.Millisecond) } if !r.x.Verify(id) { t.Fatal("not proven once the group is gone") } } // After a restart, the dead runner's turn is settled first: what it // started (marked or not) is swept, what was there before it began is // not, and a group id since used by a process from before is neither // killed nor proven over until it is gone. func TestRestartReusedGroupNotKilled(t *testing.T) { r := newLaunchRig(t) r.x.Settle = 500 * time.Millisecond marker := "attempt-r-" + r.nonce unrelated := r.start(r.env(), "/bin/sleep", "60") before, err := r.procs.List(time.Now().Add(5*time.Second), nil) if err != nil { t.Fatal(err) } var ids []ProcID for _, q := range before { ids = append(ids, q.ID) } dead := r.start(r.env(), "/bin/sleep", "0.2") deadID := r.waitListed(dead.Process.Pid).ID for !gone(dead.Process.Pid) { time.Sleep(10 * time.Millisecond) } left := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/sleep", "60") scrubbed := r.start(r.env(), "/bin/sleep", "60") // Its final note was written (complete) before the runner died. if err := r.turns.saveTurn(turnRecord{ID: "dead-turn", Op: OpEngineering, Runner: deadID, Sweep: true, Before: ids, Markers: []string{marker}, Complete: true}); err != nil { t.Fatal(err) } if r.x.Verify(RecordID(unrelated.Process.Pid, marker)) { t.Fatal("proven over while the reused group lives") } if gone(unrelated.Process.Pid) { t.Fatal("a process from before the turn was killed") } for name, c := range map[string]*exec.Cmd{"marked": left, "unmarked": scrubbed} { for deadline := time.Now().Add(5 * time.Second); !gone(c.Process.Pid) && time.Now().Before(deadline); { time.Sleep(10 * time.Millisecond) } if !gone(c.Process.Pid) { t.Fatalf("the dead turn's %s leftover survived", name) } } if _, ok, _ := r.turns.loadTurn(); ok { t.Fatal("the dead turn's record was not settled") } _ = unrelated.Process.Kill() for deadline := time.Now().Add(5 * time.Second); !gone(unrelated.Process.Pid) && time.Now().Before(deadline); { time.Sleep(10 * time.Millisecond) } if !r.x.Verify(RecordID(unrelated.Process.Pid, marker)) { t.Fatal("not proven once it is gone") } } // After a restart every marked process is killed, the recorded group // with it, and a marked grandchild that double-forked out of it too; // then the attempt is over. A marker-only record settles the same way. func TestRestartKillsMarked(t *testing.T) { r := newLaunchRig(t) marker := "attempt-k-" + r.nonce pidFile := filepath.Join(t.TempDir(), "grandchild") leader := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/bash", "-c", "(setsid sleep 60 & echo $! > "+quote(pidFile)+"); exec sleep 60") grandchild := waitPID(t, pidFile) r.waitListed(grandchild) if !r.x.Verify(RecordID(leader.Process.Pid, marker)) { t.Fatal("not settled") } if !gone(leader.Process.Pid) || !gone(grandchild) { t.Fatal("a marked process survived") } alone := r.start(r.env("EQUIPO_ATTEMPT="+marker+"-0"), "/bin/sleep", "60") if !r.x.Verify(RecordID(0, marker+"-0")) || !gone(alone.Process.Pid) { t.Fatal("a marker-only record not settled") } } // The sweep spares the runner and every helper it started for itself, // by identity: a helper started during the turn and still running at // its end lives on, a step's process running the very same program // with the same arguments does not. func TestSweepSparesTheRunnerAndItsHelpers(t *testing.T) { r := newLaunchRig(t) ctx, turn := r.take(OpEngineering) defer turn.Give() run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", "sleep 60 & exec sleep 60"}, Env: r.env("EQUIPO_ATTEMPT=attempt-o-" + r.nonce)}, "attempt-o-"+r.nonce, func(string) error { return nil }) if err != nil { t.Fatal(err) } helper := exec.Command("/bin/sleep", "60") helper.Env = r.env() if err := StartOwn(helper); err != nil { t.Fatal(err) } defer func() { _ = helper.Process.Kill(); _ = helper.Wait() }() // The same program, arguments and environment, but the step's: its // own session, after the turn began, not the runner's. impostor := r.start(r.env(), "/bin/sleep", "60") if !run.Stop() { t.Fatal("end not proven") } if gone(helper.Process.Pid) { t.Fatal("the runner's own helper was killed") } if !gone(impostor.Process.Pid) { t.Fatal("a process like the helper's but not the runner's survived") } } // A step that double-forks to escape (its parent gone, a session of its // own, no marker) is found by the runner-user sweep alone: the tree poll // never saw it. func TestSweepCatchesDoubleForkToLaunchd(t *testing.T) { r := newLaunchRig(t) r.x.Poll = time.Hour ctx, turn := r.take(OpEngineering) defer turn.Give() pidFile := filepath.Join(t.TempDir(), "escaped") script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")" run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-d-" + r.nonce)}, "attempt-d-"+r.nonce, func(string) error { return nil }) if err != nil { t.Fatal(err) } escaped := waitPID(t, pidFile) <-run.Exited() // Listed as soon as forked; an escape once setsid has run in it. q := r.waitListed(escaped) for deadline := time.Now().Add(5 * time.Second); q.SID != escaped && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { q, _ = r.procs.Lookup(escaped) } if q.Marker != "" || q.SID != escaped { t.Fatalf("not an escape: %+v", q) } if !run.Stop() || !gone(escaped) { t.Fatal("a double-forked step outlived the turn's end") } } // Proof only when nothing is left: a process only the runner-user sweep // finds (it double-forked out unseen: no marker, no recorded group or // session) that will not die keeps the end unproven within its bound, // the turn's record stays past Give, and the next turn cannot begin // until that process is gone. func TestProofOnlyWhenNothingRemains(t *testing.T) { r := newLaunchRig(t) r.x.Settle, r.turns.Settle, r.x.Poll = 400*time.Millisecond, 400*time.Millisecond, time.Hour stuck := &stuckProcs{Procs: r.procs} r.turns.Sweep(stuck) ctx, turn := r.take(OpEngineering) pidFile := filepath.Join(t.TempDir(), "p") script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")" run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-p-" + r.nonce)}, "attempt-p-"+r.nonce, func(string) error { return nil }) if err != nil { t.Fatal(err) } <-run.Exited() r.waitListed(waitPID(t, pidFile)) stuck.hold() start := time.Now() if run.Stop() { t.Fatal("proven over with a process of the turn alive") } if took := time.Since(start); took > r.x.Settle+time.Second { t.Fatalf("the proof took %s, past its bound", took) } turn.Give() if _, ok, _ := r.turns.loadTurn(); !ok { t.Fatal("an unproven turn's record went") } if _, err := r.turns.Take(context.Background(), OpCheck); !errors.Is(err, ErrUnsettled) { t.Fatalf("a turn began beside an unproven one: %v", err) } stuck.release() next, err := r.turns.Take(context.Background(), OpCheck) if err != nil { t.Fatalf("not settled once it could be: %v", err) } next.Give() } // stuckProcs drops every signal while held: a process that will not die. type stuckProcs struct { Procs held bool } func (s *stuckProcs) hold() { s.held = true } func (s *stuckProcs) release() { s.held = false } func (s *stuckProcs) Signal(pid int, sig syscall.Signal) error { if s.held && sig != 0 { return nil } return s.Procs.Signal(pid, sig) } // Every operation that has a model token in a process, runs Xcode or // repository code holds the Mac's one turn: an Engineering launch, a // token check and a probe run never overlap, a launch outside a turn // starts nothing, and a check waits while a sign-in holds its pty. func TestTurnsCoverEveryTokenOperation(t *testing.T) { er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n") er.in.Action = claude.DarwinCheck check := er.policy() // A token check outside any turn: refused, nothing on record. recorded := 0 s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)} if _, err := s.StartRecorded(context.Background(), provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { recorded++; return nil }); !errors.Is(err, ErrNoTurn) || recorded != 0 { t.Fatalf("a token check ran outside the turn: %v (%d records)", err, recorded) } // While Engineering holds the turn, a token check and a probe run wait. _, eng := r.take(OpEngineering) short, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) if _, err := r.turns.Take(short, OpTokenCheck); err == nil { t.Fatal("a token check took the turn beside Engineering") } cancel() f := newProbeFixture(t, allLines("denied")) f.h.Turns, f.h.Limit = r.turns, 300*time.Millisecond if rep := RunProbes(context.Background(), f.h); len(rep.Unfinished) != len(rep.Probes) || slices.ContainsFunc(f.execLog, func(k string) bool { return strings.Contains(k, "simctl") }) { t.Fatalf("probes ran beside Engineering: %+v", rep) } eng.Give() // The token check in its own turn runs, and ends proven. ctx, tc := r.take(OpTokenCheck) s.Token = slices.Clone(er.token) pr, err := s.StartRecorded(ctx, provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { return nil }) if err != nil { t.Fatal(err) } pr.Stdin().Close() if _, err := pr.Wait(context.Background()); err != nil { t.Fatal(err) } tc.Give() // A sign-in's pty holds the turn: a check waits for it. _, signIn := r.take(OpSignIn) g, dir := gateFixture(t, false) g.Turns = r.turns g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce) ran := make(chan Result, 1) var at time.Time go func() { res := g.Run(context.Background(), "checks-w-"+r.nonce, dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(string) error { if at.IsZero() { at = time.Now() } return nil }) ran <- res }() time.Sleep(300 * time.Millisecond) select { case res := <-ran: t.Fatalf("a check ran while a sign-in held the turn: %+v", res) default: } gave := time.Now() signIn.Give() if res := <-ran; res.Code != 0 || !res.Terminated || at.Before(gave) { t.Fatalf("the check after the sign-in: %+v", res) } } // A stored connection holds no turn: once the token is stored, an // Engineering launch, a sandboxed check and an ask take turns one after // another, each proven over, and nothing is left on record. func TestStoredConnectionAllowsSerialTurns(t *testing.T) { er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n") store, err := r.turns.Take(context.Background(), OpTokenStore) if err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(er.in.CredentialHome, ".oauth-token"), er.token, 0600); err != nil { t.Fatal(err) } store.Give() ask := newEngRigWith(t, []byte("#!/bin/sh\ncat <&3 >/dev/null\nread line\n")) ask.in.Attempt, ask.in.Action = er.in.Attempt, claude.DarwinAnswer cli := func(op Op, rig *engRig) error { p, err := EngineeringPolicy(rig.cli, rig.in) if err != nil { return err } u, err := r.turns.Take(context.Background(), op) if err != nil { return err } defer u.Give() s := &Starter{Exec: r.x, CLI: rig.cli, Input: rig.in, Token: slices.Clone(rig.token)} pr, err := s.StartRecorded(u.Context(context.Background()), provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil }) if err != nil { return err } pr.Stdin().Close() _, err = pr.Wait(context.Background()) return err } g, dir := gateFixture(t, true) _, temp := userTempFixture(t) g.Turns, g.UserTemp = r.turns, temp g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce) done := make(chan []string) go func() { var errs []string if err := cli(OpEngineering, er); err != nil { errs = append(errs, "engineering: "+err.Error()) } if res, _ := run(g, dir, "checks-s-"+r.nonce, time.Minute, "true"); res.Code != 0 || !res.Terminated { errs = append(errs, "sandboxed check did not pass") } if err := cli(OpAsk, ask); err != nil { errs = append(errs, "ask: "+err.Error()) } done <- errs }() select { case errs := <-done: if len(errs) > 0 { t.Fatal(errs) } case <-time.After(30 * time.Second): t.Fatal("a turn waited on the stored connection") } if _, ok, _ := r.turns.loadTurn(); ok || r.turns.Pending() { t.Fatal("a turn or a cleanup was left on record") } } // An interrupted cleanup (its attempt's end not proven) is finished // only by its owner (that attempt's proof, in the runner process that // wrote it) or by a restart (that process gone), never by another turn. func TestCleanupOwnedByItsTurn(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock")) g.procs = withPhantom() res, id := run(g, dir, "checks-o-1", time.Minute, `touch `+quote(filepath.Join(temp, "left-by-1"))) if res.Terminated || !g.Turns.Pending() { t.Fatalf("not interrupted: %+v", res) } g.procs = nil // Another turn of this runner: it neither finishes it nor runs. if res, _ := run(g, dir, "checks-o-2", time.Minute, `touch `+quote(filepath.Join(temp, "ran-2"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran-2")) { t.Fatalf("another turn ran: %+v", res) } if !exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending() { t.Fatal("another turn finished the cleanup") } // Nor does a recovery for another attempt. if g.Verify(RecordID(0, "checks-o-other")) && (!exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending()) { t.Fatal("another attempt's proof finished the cleanup") } // Its owner does. if !g.Verify(id) || exists(filepath.Join(temp, "left-by-1")) || g.Turns.Pending() { t.Fatal("the owner did not finish its cleanup") } // A restart: the record of a runner process that is gone. dead := exec.Command("/bin/true") if err := dead.Start(); err != nil { t.Fatal(err) } deadID, ok := platformProcs.Lookup(dead.Process.Pid) _ = dead.Wait() if !ok { deadID.ID = ProcID{PID: dead.Process.Pid, Start: 1} } s, err := openTemp(temp, nil) if err != nil { t.Fatal(err) } if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-dead", Before: s.before, Runner: deadID.ID}); err != nil { t.Fatal(err) } s.close() if err := os.WriteFile(filepath.Join(temp, "left-by-dead"), nil, 0600); err != nil { t.Fatal(err) } if res, _ := run(g, dir, "checks-o-3", time.Minute, `ls `+quote(temp)); res.Code != 0 || strings.Contains(res.Output, "left-by-dead") || g.Turns.Pending() { t.Fatalf("a restart did not finish the dead runner's cleanup: %+v", res) } // This live runner's record for an attempt of another turn: never. if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-live", Before: tempListing{}, Runner: selfID()}); err != nil { t.Fatal(err) } if res, _ := run(g, dir, "checks-o-4", time.Minute, `true`); res.Reason != "checks_unavailable" || !g.Turns.Pending() { t.Fatalf("a live owner's cleanup taken by another turn: %+v", res) } } // #8: a turn record that cannot be written (here its directory turned // read-only) stops the operation by itself and withholds its proof; a // restart then settles what it left from the record it had. func TestTurnRecordWriteFailureStopsTheOperation(t *testing.T) { r := newLaunchRig(t) dir := filepath.Dir(r.turns.lock) pidFile := filepath.Join(t.TempDir(), "child") ctx, turn := r.take(OpEngineering) marker := "attempt-w-" + r.nonce run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", "sleep 0.4; setsid sleep 60 & echo $! > " + quote(pidFile) + "; sleep 60"}, Env: r.env("EQUIPO_ATTEMPT=" + marker)}, marker, func(string) error { return nil }) if err != nil { t.Fatal(err) } if err := os.Chmod(dir, 0500); err != nil { t.Fatal(err) } defer os.Chmod(dir, 0700) select { case <-run.Exited(): case <-time.After(5 * time.Second): t.Fatal("the operation ran on with its turn's record unwritable") } child := waitPID(t, pidFile) if run.Stop() { t.Fatal("proven over with its groups not on record") } turn.Give() if err := os.Chmod(dir, 0700); err != nil { t.Fatal(err) } next := NewTurns(r.turns.lock).Sweep(r.procs) next.Settle = 3 * time.Second u, err := next.Take(context.Background(), OpCheck) if err != nil { t.Fatalf("a restart did not settle it: %v", err) } u.Give() if !gone(child) { t.Fatal("what it left survived the restart's settling") } // Its record was never completed. Nothing of the runner user's is // left that the runner does not account for, so the idle read (taken // holding the turn) proves it over. nx := &Executor{Turns: next, Settle: time.Second} if !nx.Verify(run.ID()) || next.Incomplete() { t.Fatal("an idle read with nothing unaccounted did not prove it over") } } // blind cannot read pid's identity (a sysctl that failed), though the // process is there. type blind struct { Procs pid int } func (b *blind) Lookup(pid int) (ProcInfo, bool) { if pid == b.pid { return ProcInfo{}, false } return b.Procs.Lookup(pid) } // #9: a cleanup's owner whose identity cannot be read is not a restart: // another turn neither finishes the cleanup nor runs. func TestCleanupOwnerUnknownIsNotARestart(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock")) owner := exec.Command("/bin/sleep", "60") if err := owner.Start(); err != nil { t.Fatal(err) } defer func() { _ = owner.Process.Kill(); _ = owner.Wait() }() id, ok := platformProcs.Lookup(owner.Process.Pid) if !ok { t.Fatal("owner not listed") } g.Turns.ids = &blind{Procs: platformProcs, pid: owner.Process.Pid} s, err := openTemp(temp, nil) if err != nil { t.Fatal(err) } if err := g.Turns.writePending(pendingRecord{Attempt: "checks-u-owner", Before: s.before, Runner: id.ID}); err != nil { t.Fatal(err) } s.close() left := filepath.Join(temp, "left-by-owner") if err := os.WriteFile(left, nil, 0600); err != nil { t.Fatal(err) } if res, _ := run(g, dir, "checks-u-1", time.Minute, "true"); res.Reason != "checks_unavailable" || !exists(left) || !g.Turns.Pending() { t.Fatalf("a live owner's cleanup taken on an unreadable identity: %+v", res) } }