package mac import ( "context" "errors" "os" "path/filepath" "slices" "sync/atomic" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/runner/mac/proc" ) // Fix round 2 (Astra round 2) regressions on synthetic tables: rows // made up 2026-11-28 in the darwin table's shape (see sweep_test.go). // stopReads calls fn on each table read the stop makes (the stop asks // for markers; the poll does not), with its number. func stopReads(tb *table, fn func(tb *table, k int)) { k := 0 tb.afterList = func(tb *table, _ int, markers []string) { if len(markers) > 0 { k++ fn(tb, k) } } } // #7: the final note is part of the proof: a note that returns after // the deadline means no proof. func TestProofDeadlineCoversTheFinalNote(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) turns, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond) defer u.Give() var slow atomic.Bool turns.beforeWrite = func() error { if slow.Load() { time.Sleep(400 * time.Millisecond) } return nil } tb.add(row(94100, 1, 94100, 94100, 5000, me, ""), "/Users/paulequipo/w/a") slow.Store(true) if run.Stop() { t.Fatal("proven though its final note returned after the deadline") } } // #7: Verify has one deadline for settling the turn, the record and the // debts: recovery that spends most of it settling the turn has only the // rest for the recorded group. func TestVerifyHasOneDeadline(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) tb.add(row(94300, 1, 94300, 94300, 900, me, ""), "/Users/paulequipo/w/old") list, _ := tb.List(time.Time{}, nil) var before []ProcID for _, q := range list { before = append(before, q.ID) } tb.add(row(94200, 1, 94200, 94200, 5000, me, ""), "/Users/paulequipo/w/left") tb.mark(&tb.unkillable, 94200) turns := NewTurns("").Sweep(tb) turns.own, turns.Settle = &Own{}, 300*time.Millisecond x := &Executor{Turns: turns, Settle: 300 * time.Millisecond} if err := turns.saveTurn(turnRecord{ID: "dead", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-d"}, Complete: true}); err != nil { t.Fatal(err) } time.AfterFunc(50*time.Millisecond, func() { tb.unmark(&tb.unkillable, 94200) }) time.AfterFunc(350*time.Millisecond, func() { tb.remove(94300) }) if x.Verify(RecordID(94300, "attempt-d")) { t.Fatal("proven after its one deadline (its recorded group ended at 350 ms)") } if !x.Verify(RecordID(94300, "attempt-d")) { t.Fatal("not proven on a later try once everything ended") } } // #8 and the follow-up: the poll finds a session, its write fails, and // what is left of it is another user's (a setuid program) and survives a // restart. The record on disk was never completed. A restart in the same // boot proves nothing by itself: while a process of the runner user that // nothing accounts for runs, the end stays unproven and the runner says // how many; once only accounted processes remain, the idle read proves // it (a reboot would too; see clear_test.go). func TestIncompleteRecordNeedsAClearance(t *testing.T) { me := os.Getuid() lock := filepath.Join(t.TempDir(), "lock") tb := parseTable(t, turnBegan) turns := NewTurns(lock).Sweep(tb) turns.own, turns.Settle = &Own{}, 200*time.Millisecond u, err := turns.Take(context.Background(), OpEngineering) if err != nil { t.Fatal(err) } x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond} run, err := x.Start(u.Context(context.Background()), Command{Argv: []string{"/bin/true"}}, "attempt-i", func(string) error { return nil }) if err != nil { t.Fatal(err) } <-run.Exited() var failing atomic.Bool turns.beforeWrite = func() error { if failing.Load() { return errors.New("disk full") } return nil } failing.Store(true) residue := row(95002, 1, 95002, 95001, 7000, 0, "") tb.after = func(tb *table, pid int, sig syscall.Signal) { if pid == 95001 && tb.procs[95002].PID == 0 { tb.procs[95002] = residue tb.paths[95002] = "/usr/bin/login" } } // In the attempt's group, a session of its own: the poll finds it. tb.add(row(95001, 1, run.pgid, 95001, 6001, me, ""), "/Users/paulequipo/w/s") select { case <-run.Aborted(): case <-time.After(3 * time.Second): t.Fatal("not stopped when its record could not be written") } if run.Stop() { t.Fatal("proven with its record unwritten") } u.Give() failing.Store(false) next := NewTurns(lock).Sweep(tb) next.own, next.Settle = &Own{}, 200*time.Millisecond nx := &Executor{Turns: next, Settle: 200 * time.Millisecond} v, err := next.Take(context.Background(), OpCheck) if err != nil { t.Fatalf("the restarted runner is blocked: %v", err) } v.Give() tb.add(row(95100, 1, 95100, 95100, 9000, me, ""), "/Users/paulequipo/w/stray") if nx.Verify(run.ID()) { t.Fatal("recovery proved an incomplete record with an unaccounted process running") } if code, n := next.Unproven(); code != "processes_left" || n != 1 { t.Fatalf("the runner said %q, %d", code, n) } tb.remove(95002) tb.remove(95100) if !nx.Verify(run.ID()) || next.Incomplete() { t.Fatal("not proven once an idle read accounts for every process") } } // #10: the relaunch cutoff is the moment of the first kill pass (the // table's clock, just before the first signal), not the newest start in // that pass's read: a system agent born between that read and the first // signal predates the kill pass, and is killed. func TestRelaunchCutoffIsTheKillPassStart(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) _, u, _, run := liveTurn(t, tb, &Own{}, time.Second) defer u.Give() tb.add(row(83100, 1, 83100, 83100, 4000, me, ""), "/Users/paulequipo/w/first") stopReads(tb, func(tb *table, k int) { if k == 1 { tb.procs[83200] = row(83200, 1, 83200, 83200, 5050, me, "") tb.paths[83200] = "/usr/libexec/trustd" tb.clock = 5100 } }) if !run.Stop() { t.Fatalf("not proven: %v", tb.signalled()) } if sig := tb.signalled(); !slices.Contains(sig, 83200) && !slices.Contains(sig, -83200) || tb.has(83200) { t.Fatalf("an agent born before the first signal was taken for a relaunch: %v", tb.signalled()) } } // #10: discovery is the one read after the first kill pass. Later reads // add nothing to the kill set, but any process of the runner user born // during the turn (here as the leader dies of the SIGKILL after // discovery), not the runner's own and not a launchd relaunch, keeps // both the proof and the Mac's clearance withheld: the turn's record // stays, and the next turn's settling kills it. func TestDiscoveryIsOneSnapshot(t *testing.T) { me := os.Getuid() for _, c := range []struct { name string late ProcInfo }{ {"unrelated", row(83400, 1, 83400, 83400, 9000, me, "")}, {"in a killed process's group", row(83600, 1, 83500, 83600, 9000, me, "")}, } { t.Run(c.name, func(t *testing.T) { tb := parseTable(t, turnBegan) turns, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond) tb.add(row(83500, 1, 83500, 83500, 4000, me, ""), "/Users/paulequipo/w/lead") // It needs SIGKILL, sent once the grace has passed. tb.mark(&tb.stubborn, 83500) tb.after = func(tb *table, pid int, sig syscall.Signal) { if (pid == 83500 || pid == -83500) && sig == syscall.SIGKILL && tb.procs[c.late.PID].PID == 0 { tb.procs[c.late.PID] = c.late tb.paths[c.late.PID] = "/Users/paulequipo/w/late" } } if run.Stop() { t.Fatalf("proven with %d alive (signalled %v)", c.late.PID, tb.signalled()) } if slices.Contains(tb.signalled(), c.late.PID) { t.Fatalf("a read after discovery added %d: %v", c.late.PID, tb.signalled()) } u.Give() if _, ok, _ := turns.loadTurn(); !ok { t.Fatal("the turn's record went with a process of the turn alive") } next, err := turns.Take(context.Background(), OpCheck) if err != nil { t.Fatalf("the next turn did not settle it: %v", err) } next.Give() if tb.has(c.late.PID) { t.Fatalf("%d survived the next turn's settling", c.late.PID) } }) } } // flaky's List works once and then fails. type flaky struct { *table n atomic.Int32 } func (f *flaky) List(deadline time.Time, markers []string) ([]ProcInfo, error) { if f.n.Add(1) > 1 { return nil, errors.New("sysctl failed") } return f.table.List(deadline, markers) } // #14: a failed read voids what an earlier read showed: an empty read, // then failed reads (a process of the runner user appearing meanwhile) // is never a clearance to release the Mac. func TestFailedScanVoidsClearance(t *testing.T) { me := os.Getuid() tb := &flaky{table: parseTable(t, turnBegan)} list, _ := tb.table.List(time.Time{}, nil) var before []ProcID for _, q := range list { before = append(before, q.ID) } tb.add(row(96001, 1, 96001, 96001, 7000, 501, ""), "/bin/zsh") tb.table.afterList = func(tb *table, _ int, _ []string) { tb.procs[96100] = row(96100, 1, 96100, 96100, 7100, me, "") tb.paths[96100] = "/Users/paulequipo/w/survivor" } s := newScope(tb, []string{"attempt-f"}, before) s.Groups[96001] = 1 if out := s.Settle(&Own{}, time.Now().Add(300*time.Millisecond), 0, func() bool { return true }, nil); out != proc.Left { t.Fatalf("settled %v after failed reads, want left", out) } } // The proof waits for every target, also one that leads no group or // session the obligations would hold: the child left by a double fork, // its session leader gone, that will not die. func TestProofWaitsForEveryTarget(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond) defer u.Give() tb.add(row(84100, 1, 84000, 84000, 5000, me, ""), "/Users/paulequipo/w/orphan") tb.mark(&tb.unkillable, 84100) if run.Stop() { t.Fatal("proven over with a double-forked child alive") } } // #7: the pending user-temp cleanup's proof read is under the same one // deadline: recovery that spends most of it settling the turn has only // the rest for the cleanup's recorded group. func TestVerifyHasOneDeadlineWithCleanup(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) tb.add(row(94400, 1, 94400, 94400, 900, me, ""), "/Users/paulequipo/w/old") list, _ := tb.List(time.Time{}, nil) var before []ProcID for _, q := range list { before = append(before, q.ID) } tb.add(row(94200, 1, 94200, 94200, 5000, me, ""), "/Users/paulequipo/w/left") tb.mark(&tb.unkillable, 94200) turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(tb) turns.own, turns.Settle = &Own{}, 300*time.Millisecond _, temp := userTempFixture(t) x := &Executor{Turns: turns, Settle: 300 * time.Millisecond, UserTemp: temp} if err := turns.saveTurn(turnRecord{ID: "dead", Op: OpCheck, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-c"}, Complete: true}); err != nil { t.Fatal(err) } s, err := openTemp(temp, nil) if err != nil { t.Fatal(err) } if err := turns.writePending(pendingRecord{Attempt: "attempt-c", PGID: 94400, Before: s.before, Runner: selfID()}); err != nil { t.Fatal(err) } s.close() time.AfterFunc(50*time.Millisecond, func() { tb.unmark(&tb.unkillable, 94200) }) time.AfterFunc(350*time.Millisecond, func() { tb.remove(94400) }) if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven after its one deadline (the cleanup's group ended at 350 ms)") } if !x.Verify(RecordID(0, "attempt-c")) || turns.Pending() { t.Fatal("not proven, or not cleaned, on a later try once everything ended") } } // #8: once a launch's evidence could not be written, no other launch // starts in that turn, so no later stop can mark the record complete; // after a restart the first launch is never proven over. func TestFailedLaunchEndsTheTurnsLaunches(t *testing.T) { me := os.Getuid() lock := filepath.Join(t.TempDir(), "lock") tb := parseTable(t, turnBegan) turns := NewTurns(lock).Sweep(tb) turns.own, turns.Settle = &Own{}, 200*time.Millisecond u, err := turns.Take(context.Background(), OpEngineering) if err != nil { t.Fatal(err) } ctx := u.Context(context.Background()) x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond} a, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-a", func(string) error { return nil }) if err != nil { t.Fatal(err) } <-a.Exited() var failing atomic.Bool turns.beforeWrite = func() error { if failing.Load() { return errors.New("disk full") } return nil } failing.Store(true) tb.after = func(tb *table, pid int, sig syscall.Signal) { if pid == 97001 && tb.procs[97002].PID == 0 { tb.procs[97002] = row(97002, 1, 97002, 97001, 7000, 0, "") tb.paths[97002] = "/usr/bin/login" } } tb.add(row(97001, 1, a.pgid, 97001, 6001, me, ""), "/Users/paulequipo/w/s") select { case <-a.Aborted(): case <-time.After(3 * time.Second): t.Fatal("not stopped when its record could not be written") } if a.Stop() { t.Fatal("proven with its record unwritten") } // The disk recovers; the turn takes no other launch. failing.Store(false) b, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-b", func(string) error { return nil }) if err == nil { <-b.Exited() b.Stop() t.Error("a launch started after the turn lost a launch's evidence") } u.Give() next := NewTurns(lock).Sweep(tb) next.own, next.Settle = &Own{}, 200*time.Millisecond v, err := next.Take(context.Background(), OpCheck) if err != nil { t.Fatalf("the restarted runner is blocked: %v", err) } v.Give() // An unaccounted process: no idle clearance. tb.add(row(97100, 1, 97100, 97100, 9000, me, ""), "/Users/paulequipo/w/stray") nx := &Executor{Turns: next, Settle: 200 * time.Millisecond} if nx.Verify(a.ID()) || !next.Incomplete() { t.Fatal("the first launch was proven over, or the runner does not say it cannot be") } } // #8: the record is complete only when every launch of the turn has // finished its own durable writes: a launch not yet stopped keeps it // incomplete whatever another launch's stop wrote. func TestCompleteOnlyWhenEveryLaunchFinished(t *testing.T) { tb := parseTable(t, turnBegan) turns := NewTurns("").Sweep(tb) turns.own, turns.Settle = &Own{}, 200*time.Millisecond u, err := turns.Take(context.Background(), OpEngineering) if err != nil { t.Fatal(err) } defer u.Give() ctx := u.Context(context.Background()) x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond} a, err := x.Start(ctx, Command{Argv: []string{"/bin/sleep", "0.5"}}, "attempt-a", func(string) error { return nil }) if err != nil { t.Fatal(err) } b, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-b", func(string) error { return nil }) if err != nil { t.Fatal(err) } <-b.Exited() b.Stop() if rec, ok, _ := turns.loadTurn(); !ok || rec.Complete { t.Fatalf("complete with a launch not finished: %+v", rec) } <-a.Exited() a.Stop() if rec, ok, _ := turns.loadTurn(); !ok || !rec.Complete { t.Fatalf("not complete once every launch finished: %+v", rec) } } // #10: settling an earlier turn never releases the Mac (Owed) while a // process of the runner user born during that turn lives, though its // check reads add nothing: here a child born into a killed leader's // group after the settle's discovery read. func TestSettleKeepsTheTurnWhileALateProcessLives(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) list, _ := tb.List(time.Time{}, nil) var before []ProcID for _, q := range list { before = append(before, q.ID) } turns := NewTurns("").Sweep(tb) turns.own, turns.Settle = &Own{}, 300*time.Millisecond if err := turns.saveTurn(turnRecord{ID: "old", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-o"}, Complete: true}); err != nil { t.Fatal(err) } tb.add(row(83700, 1, 83700, 83700, 4000, me, ""), "/Users/paulequipo/w/lead") tb.mark(&tb.unkillable, 83700) signals := 0 tb.after = func(tb *table, pid int, sig syscall.Signal) { if pid != 83700 && pid != -83700 { return } // Signalled at the first kill pass and again after discovery: // then its last fork, and it dies. if signals++; signals == 3 && tb.procs[83701].PID == 0 { tb.procs[83701] = row(83701, 1, 83700, 83701, 9000, me, "") tb.paths[83701] = "/Users/paulequipo/w/late" delete(tb.unkillable, 83700) delete(tb.procs, 83700) } } if err := turns.settle(time.Now().Add(turns.settleLimit())); err == nil { t.Fatal("the Mac was released with a process of the earlier turn alive") } if _, ok, _ := turns.loadTurn(); !ok { t.Fatal("the earlier turn's record went") } } // #10: the group a killed process led stays an obligation after it // dies: a child born into it after discovery that is another user's (a // setuid program), which no read lists, still keeps the proof waiting, // though it is never signalled. func TestLedGroupObligationOutlivesItsLeader(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond) defer u.Give() tb.add(row(83800, 1, 83800, 83800, 4000, me, ""), "/Users/paulequipo/w/lead") tb.mark(&tb.stubborn, 83800) tb.after = func(tb *table, pid int, sig syscall.Signal) { if (pid == 83800 || pid == -83800) && sig == syscall.SIGKILL && tb.procs[83801].PID == 0 { tb.procs[83801] = row(83801, 1, 83800, 83801, 9000, 0, "") tb.paths[83801] = "/usr/bin/login" } } if run.Stop() { t.Fatal("proven while another user's child is in a group a killed process led") } if slices.Contains(tb.signalled(), 83801) { t.Fatal("another user's process was signalled") } }