package mac import ( "context" "errors" "os" "path/filepath" "slices" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/mac/proc" ) // The follow-up to task 9: the two clearances of a turn whose end could // not be proven (its record incomplete, or what it owes). Synthetic // tables, rows made up 2026-11-29 in the darwin table's shape (see // sweep_test.go). var turnStart = time.Unix(1_800_000_000, 0) // clearRig is a turns over tb (its table when the turn began is // turnBegan's), with a boot that reads as boot. func clearRig(t *testing.T, tb Procs, boot proc.Boot, bootErr error) (*Turns, *Executor, *Own, []ProcID) { t.Helper() list, err := tb.List(time.Now().Add(time.Second), nil) if err != nil { t.Fatal(err) } var before []ProcID for _, q := range list { before = append(before, q.ID) } own := &Own{} turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(tb) turns.own, turns.Settle = own, 300*time.Millisecond turns.boot = func() (proc.Boot, error) { return boot, bootErr } return turns, &Executor{Turns: turns, Settle: 300 * time.Millisecond}, own, before } // owed is an incomplete turn's obligation, begun at turnStart in boot-1, // in which nothing ran outside a sandbox. func owed(before []ProcID) proc.Obligation { return proc.Obligation{Markers: []string{"attempt-c"}, Incomplete: true, Began: turnStart, BootID: "boot-1", Before: before, FlagsKnown: true} } var ( sameBoot = proc.Boot{ID: "boot-1", Time: turnStart.Add(-time.Hour)} laterBoot = proc.Boot{ID: "boot-2", Time: turnStart.Add(time.Hour)} ) // A reboot after the turn began proves it ended: an incomplete record // from an earlier boot is settled without a sweep (what runs now is this // boot's), what it owes is cleared, and Retry is allowed. The same for // an obligation already owed. func TestRebootClearsAnIncompleteTurn(t *testing.T) { me := os.Getuid() for _, viaRecord := range []bool{true, false} { tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, laterBoot, nil) // A process of this boot, which no settling of the old turn may touch. tb.add(row(98000, 1, 98000, 98000, 5000, me, ""), "/Users/paulequipo/w/now") tb.mark(&tb.unkillable, 98000) if viaRecord { if err := turns.saveTurn(turnRecord{ID: "old", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-c"}, Began: turnStart, BootID: "boot-1"}); err != nil { t.Fatal(err) } } else if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if !x.Verify(RecordID(0, "attempt-c")) { t.Fatalf("record %v: not proven over after a reboot", viaRecord) } if code, _ := turns.Unproven(); code != "" || turns.Incomplete() { t.Fatalf("record %v: still said unproven: %q", viaRecord, code) } if slices.Contains(tb.signalled(), 98000) { t.Fatalf("record %v: settling an earlier boot's turn signalled this boot's process", viaRecord) } } } // No reboot after the turn began (the same boot, even if the clock moved // past the turn's start; or a boot read before it), or a boot that // cannot be read: unproven. func TestNoRebootKeepsItUnproven(t *testing.T) { me := os.Getuid() for name, c := range map[string]struct { boot proc.Boot err error }{ "boot before the turn": {proc.Boot{ID: "boot-2", Time: turnStart.Add(-time.Hour)}, nil}, "same boot, the clock moved": {proc.Boot{ID: "boot-1", Time: turnStart.Add(time.Hour)}, nil}, // A read that half failed: whatever it returned proves nothing. "boot unreadable": {laterBoot, errors.New("sysctl failed")}, } { tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, c.boot, c.err) // Something unaccounted, so the idle read cannot clear it either. tb.add(row(98010, 1, 98010, 98010, 5000, me, ""), "/Users/paulequipo/w/left") if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if x.Verify(RecordID(0, "attempt-c")) || !turns.Incomplete() { t.Fatalf("%s: proven over", name) } } } // With no turn running, a whole read of the runner user's processes that // finds only the runner, its own helpers and processes from before the // turn proves the turn's processes gone: proven, Retry allowed. func TestIdleReadClears(t *testing.T) { me, self := os.Getuid(), os.Getpid() tb := parseTable(t, turnBegan) turns, x, own, before := clearRig(t, tb, sameBoot, nil) tb.add(row(98100, self, self, self, 6000, me, ""), "/usr/bin/xcrun") own.Add(ProcID{PID: 98100, Start: 6000}) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if !x.Verify(RecordID(0, "attempt-c")) { t.Fatal("a clean idle read did not prove it over") } if code, _ := turns.Unproven(); code != "" { t.Fatalf("still said %q", code) } } // Processes of the runner user no record accounts for keep it unproven, // and the Machines page gets their count, nothing more. func TestIdleReadCountsStrays(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, sameBoot, nil) tb.add(row(98200, 1, 98200, 98200, 5000, me, ""), "/Users/paulequipo/w/a") tb.add(row(98201, 1, 98201, 98201, 5100, me, ""), "/Users/paulequipo/w/b") if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven with unaccounted processes running") } if code, n := turns.Unproven(); code != "processes_left" || n != 2 { t.Fatalf("said %q, %d", code, n) } if len(tb.signalled()) != 0 { t.Fatalf("an idle read signalled: %v", tb.signalled()) } } // What the turn owes must be gone too, for every user: a group it // recorded, still alive under another user, keeps it unproven. func TestIdleReadNeedsObligationsGone(t *testing.T) { tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, sameBoot, nil) tb.add(row(98301, 1, 98300, 98301, 7000, 501, ""), "/bin/zsh") o := owed(before) o.Groups = proc.Span{98300: 6000} if err := turns.debts.Owe(o); err != nil { t.Fatal(err) } if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven with a recorded group alive under another user") } } // failOnce fails the List call numbered at (counting from 1 once armed). type failOnce struct { *table n, at atomic.Int32 } func (f *failOnce) List(deadline time.Time, markers []string) ([]ProcInfo, error) { if at := f.at.Load(); at > 0 && f.n.Add(1) == at { return nil, errors.New("sysctl failed") } return f.table.List(deadline, markers) } // A read that fails proves nothing, even if the next one is clean. func TestIdleReadFailedKeepsItUnproven(t *testing.T) { tb := &failOnce{table: parseTable(t, turnBegan)} turns, x, _, before := clearRig(t, tb, sameBoot, nil) // The recovery turn's own read is the first; the idle reads follow. tb.at.Store(2) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven on a failed read") } } // Identities are read again before the clearance is accepted: a helper's // pid taken by another process between the reads keeps it unproven. func TestIdleReadRechecksBeforeAccepting(t *testing.T) { me, self := os.Getuid(), os.Getpid() tb := parseTable(t, turnBegan) turns, x, own, before := clearRig(t, tb, sameBoot, nil) tb.add(row(98400, self, self, self, 6000, me, ""), "/usr/bin/xcrun") own.Add(ProcID{PID: 98400, Start: 6000}) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } // The recovery turn's own read is the first, the first idle read the // second: right after it, the pid changes hands. reads := 0 tb.afterList = func(tb *table, _ int, _ []string) { if reads++; reads == 2 { // The helper exits; its pid is reused at once by a process // that is not the runner's. tb.procs[98400] = row(98400, 1, 98400, 98400, 6500, me, "") } } if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven though a pid changed hands between the reads") } } // The idle clearance runs only holding the Mac's turn (no turn, a given // one, another Turns's): it refuses and clears nothing. func TestIdleClearanceOnlyUnderTheTurn(t *testing.T) { tb := parseTable(t, turnBegan) turns, _, _, before := clearRig(t, tb, laterBoot, nil) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } given, err := turns.Take(context.Background(), OpCheck) if err != nil { t.Fatal(err) } given.Give() other, _, _, _ := clearRig(t, tb, laterBoot, nil) foreign, err := other.Take(context.Background(), OpCheck) if err != nil { t.Fatal(err) } defer foreign.Give() for name, u := range map[string]*Turn{"no turn": nil, "a given turn": given, "another's turn": foreign} { if rebooted, met, err := turns.clearOwed(u, "attempt-c", time.Now().Add(time.Second)); !errors.Is(err, ErrNoTurn) || rebooted || met { t.Fatalf("%s: rebooted %v, met %v, %v", name, rebooted, met, err) } } if !turns.Incomplete() { t.Fatal("cleared outside the turn") } } // noSweep is a table that may not drive a runner-user sweep (Linux // outside a test's scope): it also proves nothing idle. type noSweep struct{ *table } func (noSweep) Sweeps() bool { return false } // An idle read needs a table that may sweep the runner user: where the // user is not dedicated to the runner, other processes prove nothing. func TestIdleReadNeedsASweepingTable(t *testing.T) { tb := parseTable(t, turnBegan) turns, _, _, before := clearRig(t, tb, sameBoot, nil) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } u, err := turns.Take(context.Background(), OpRecover) if err != nil { t.Fatal(err) } defer u.Give() turns.sweep = noSweep{tb} if _, met, err := turns.clearOwed(u, "attempt-c", time.Now().Add(time.Second)); err != nil || met || !turns.Incomplete() { t.Fatalf("cleared on a table that may not sweep (met %v, %v)", met, err) } } // selfID is this test process's identity (proc.Self). func selfID() ProcID { return proc.Self() }