Mac slice F task 9 follow-up fix 2: fail closed, reusable reboot proof
Astra 9f round 2 rulings: - Assess fails closed: every open, flock or read error of the debts gives met=false (TestAssessFailsClosedOnLockErrors). - An idle read needs every other unresolved turn sandbox-only with all it names gone for every user (othersClear); spec 8.8 argues over all unresolved turns (TestIdleRefusedWhileAnotherTurnIsUnresolved). - A reboot's proof is kept as a completion (attempt, boot id) until the step and Keychain recoveries have both taken it; Executor.VerifyFor names the consumer. TestRebootIgnoresTheOldBootsGroups verifies again after a restart, as both consumers, with no signals. - The deadline bounds the pending cleanup (simulator shutdown) and the discharge's lock; a late proof keeps the debt and the cleanup (TestPendingCleanupUnderTheDeadline, TestDischargeUnderTheDeadline, TestDebtsUnderTheDeadline). RED before the fixes: fix9f2_test.go:37, :69, :115, :146 and fix9f_test.go:196. Mutations F1 to F5 (14) all killed. finishPending takes settleBy and cleanBy, so Start's 3-minute cleanup bound does not stretch the proof (it stalled a test for 181 s). The scope rebuild moved to proc.Resume to keep mac under 5000 lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+452
−57
docs/superpowers/specs/2026-11-07-equipo-mac-runners.md+32 −3internal/runner/mac/clear_test.go+3 −0internal/runner/mac/fix9f2_test.go+188 −0internal/runner/mac/fix9f_test.go+12 −1internal/runner/mac/gate.go+3 −0internal/runner/mac/launch.go+39 −11internal/runner/mac/proc/clear.go+73 −10internal/runner/mac/proc/debts.go+43 −4internal/runner/mac/proc/proc.go+28 −0internal/runner/mac/proc/proc_test.go+24 −1internal/runner/mac/turns.go+4 −24internal/runner/thin/mac.go+2 −2internal/runner/thin/maccreds.go+1 −1
diff --git a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md| index 8012cc5f..f321158e 100644 |
| --- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md |
| +++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md |
| @@ -1058,6 +1058,14 @@ it: |
| nothing. Then every process, group and session the record names |
| must be gone, for every user. |
| + The clearance covers every unresolved turn, not only the attempt's. |
| + While any other turn that still owes anything ran something outside |
| + a sandbox, or has a record that cannot show it did not, nothing is |
| + cleared this way: one of its processes may have changed its uid and |
| + still be running. Each other unresolved turn must be sandbox-only, |
| + and every process, group and session it names must be gone, for |
| + every user, before this attempt clears. |
| + |
| Any unaccounted process, or a failed or late read, keeps the attempt |
| unproven. The Machines page then gives only their number |
| (`unproven: processes_left` with `unproven_count`), never names, |
| @@ -1066,9 +1074,13 @@ it: |
| alone. |
| **Why a process born after the second read is not a survivor.** |
| - Every exempt process predates every unresolved turn, so it is none |
| - of their processes. Every process of those turns was absent from |
| - both reads, so none can fork after the second. Both reads and the |
| + Take any unresolved turn. It ran only sandboxed, so none of its |
| + processes left the runner user's table, and every one it recorded is |
| + gone for every user. Every exempt process predates every unresolved |
| + turn, so it is none of that turn's processes. Every other process of |
| + the runner user blocks the clearance at either read. So no process |
| + of any unresolved turn was present at either read, under any uid, |
| + and none can fork after the second. Both reads and the |
| acceptance happen holding the turn, so no operation of the runner's |
| starts a process meanwhile, and any process born after the earliest |
| unresolved turn began that is not the runner's own blocks the |
| @@ -1086,11 +1098,28 @@ it: |
| they are neither checked nor signalled. An unreadable boot proves |
| nothing. |
| + A record has more than one consumer: the step's recovery and the |
| + Keychain recovery both prove the same process record, in either |
| + order and perhaps in different runner processes. So the reboot's |
| + proof is kept on `<lock>.owed` as a completion, keyed by the |
| + attempt and this boot's identity, until every consumer has taken |
| + it. A later proof of the same record finds the completion and |
| + succeeds without checking or signalling anything, across a runner |
| + restart too. A completion that some consumer never takes is dropped |
| + after 30 days. |
| + |
| Both clearances run under the attempt's one proof deadline. They remove |
| nothing on their own: what the attempt owes is discharged only once its |
| whole proof, including any cleanup, has succeeded in time. A proof that |
| fails or expires leaves every obligation in place. |
| +The deadline covers every step of the proof: the pending user-temp |
| +cleanup (shutting simulators down among it), and the lock on |
| +`<lock>.owed.lock` that the discharge needs. If either cannot finish in |
| +time, the proof fails, and the debt and the pending cleanup stay; a |
| +later proof carries on from there, the cleanup being safe to repeat. |
| +An assessment that cannot open or lock the debts proves nothing. |
| + |
| Otherwise the step stays unterminated (no Retry), and its turn's record |
| stays too. The next turn, in any runner process, settles that record |
| before it begins, with the same kill set and the earlier turn's "before" |
diff --git a/internal/runner/mac/clear_test.go b/internal/runner/mac/clear_test.go| index 7ad71d65..dc1b8c0d 100644 |
| --- a/internal/runner/mac/clear_test.go |
| +++ b/internal/runner/mac/clear_test.go |
| @@ -272,3 +272,6 @@ func TestIdleReadNeedsASweepingTable(t *testing.T) { |
| 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() } |
diff --git a/internal/runner/mac/fix9f2_test.go b/internal/runner/mac/fix9f2_test.go| new file mode 100644 |
| index 00000000..1c9f3770 |
| --- /dev/null |
| +++ b/internal/runner/mac/fix9f2_test.go |
| @@ -0,0 +1,188 @@ |
| +package mac |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "sync/atomic" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| +) |
| + |
| +// Follow-up fix round 2 (Astra 9f round 2). Synthetic tables, rows made |
| +// up 2026-11-29 in the darwin table's shape (see sweep_test.go). |
| + |
| +// #1 (new): an assessment whose lock fails proves nothing, though the |
| +// discharge after it would succeed. |
| +func TestAssessFailsClosedOnLockErrors(t *testing.T) { |
| + tb := parseTable(t, turnBegan) |
| + turns, x, _, before := clearRig(t, tb, sameBoot, nil) |
| + o := owed(before) |
| + o.UnsandboxedRan = true |
| + if err := turns.debts.Owe(o); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := 0 |
| + turns.debts.LockHook = func(int) error { |
| + // Verify asks whether it owes, then assesses, then discharges. |
| + if calls++; calls == 2 { |
| + return errors.New("lock failed") |
| + } |
| + return nil |
| + } |
| + if x.Verify(RecordID(0, "attempt-c")) || !turns.debts.Owes("attempt-c") { |
| + t.Fatal("an assessment that could not lock proved an unsandboxed turn over") |
| + } |
| +} |
| + |
| +// #2: an idle read clears a turn only if every unresolved turn is |
| +// sandbox-only and has everything it names gone for every user: an |
| +// unsandboxed turn A, still unresolved, keeps sandboxed B from clearing |
| +// while A's uid-switched survivor lives; so does A's recorded group held |
| +// by another user. Once A is resolved, B clears. |
| +func TestIdleRefusedWhileAnotherTurnIsUnresolved(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + edit func(o *proc.Obligation) |
| + holding ProcInfo |
| + }{ |
| + "A unsandboxed": {func(o *proc.Obligation) { o.UnsandboxedRan = true }, row(99601, 1, 99601, 99601, 5000, 0, "")}, |
| + "A's flags unknown": {func(o *proc.Obligation) { o.FlagsKnown = false }, row(99601, 1, 99601, 99601, 5000, 0, "")}, |
| + "A's group still held": {func(o *proc.Obligation) { o.Groups = proc.Span{99602: 4000} }, row(99603, 1, 99602, 99603, 5000, 501, "")}, |
| + } { |
| + tb := parseTable(t, turnBegan) |
| + turns, x, _, before := clearRig(t, tb, sameBoot, nil) |
| + tb.add(c.holding, "/usr/bin/login") |
| + a := owed(before) |
| + a.Markers = []string{"attempt-a"} |
| + c.edit(&a) |
| + b := owed(before) |
| + b.Markers, b.Began = []string{"attempt-b"}, turnStart.Add(time.Hour) |
| + for _, o := range []proc.Obligation{a, b} { |
| + if err := turns.debts.Owe(o); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if x.Verify(RecordID(0, "attempt-b")) { |
| + t.Fatalf("%s: B cleared while A is unresolved", name) |
| + } |
| + if err := turns.debts.Discharge("attempt-a", time.Time{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !x.Verify(RecordID(0, "attempt-b")) { |
| + t.Fatalf("%s: B not cleared once A was resolved", name) |
| + } |
| + } |
| +} |
| + |
| +// #4: the pending cleanup is under the one deadline: a simulator |
| +// shutdown slower than it makes the proof fail, and keeps the debt and |
| +// the cleanup; a later Verify finishes both. |
| +func TestPendingCleanupUnderTheDeadline(t *testing.T) { |
| + tb := parseTable(t, turnBegan) |
| + turns, x, _, before := clearRig(t, tb, sameBoot, nil) |
| + if err := turns.debts.Owe(owed(before)); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, temp := userTempFixture(t) |
| + x.UserTemp = temp |
| + s, err := openTemp(temp, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := turns.writePending(pendingRecord{Attempt: "attempt-c", Before: s.before, Runner: ProcID{PID: 1 << 30, Start: 1}, Began: turnStart, BootID: "boot-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.close() |
| + left := filepath.Join(temp, "left") |
| + if err := os.WriteFile(left, nil, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + var slow atomic.Bool |
| + slow.Store(true) |
| + x.QuietSimulators = func(ctx context.Context) { |
| + if slow.Load() { |
| + select { |
| + case <-ctx.Done(): |
| + case <-time.After(3 * time.Second): |
| + } |
| + } |
| + } |
| + start := time.Now() |
| + if x.Verify(RecordID(0, "attempt-c")) { |
| + t.Fatal("proven with its cleanup past the deadline") |
| + } |
| + if took := time.Since(start); took > 2*time.Second { |
| + t.Fatalf("the slow cleanup held Verify %s, past its deadline", took) |
| + } |
| + if !turns.debts.Owes("attempt-c") || !turns.Pending() { |
| + t.Fatal("the debt or the cleanup went with the proof expired") |
| + } |
| + slow.Store(false) |
| + if !x.Verify(RecordID(0, "attempt-c")) || turns.Pending() || exists(left) || turns.debts.Owes("attempt-c") { |
| + t.Fatal("a later Verify did not finish the cleanup and the proof") |
| + } |
| +} |
| + |
| +// #4: the discharge is under the deadline too: a lock that comes too |
| +// late keeps the debt, and the proof fails. |
| +func TestDischargeUnderTheDeadline(t *testing.T) { |
| + tb := parseTable(t, turnBegan) |
| + turns, x, _, before := clearRig(t, tb, sameBoot, nil) |
| + if err := turns.debts.Owe(owed(before)); err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := 0 |
| + turns.debts.LockHook = func(int) error { |
| + if calls++; calls == 3 { |
| + // The discharge's lock: held by another runner process. |
| + time.Sleep(400 * time.Millisecond) |
| + } |
| + return nil |
| + } |
| + if x.Verify(RecordID(0, "attempt-c")) { |
| + t.Fatal("proven though its discharge came after the deadline") |
| + } |
| + turns.debts.LockHook = nil |
| + if !turns.debts.Owes("attempt-c") { |
| + t.Fatal("the debt went with the proof expired") |
| + } |
| + |
| + // The same with the lock really held: another open file description |
| + // takes the flock just before the discharge asks for it, and lets go |
| + // only after the deadline. |
| + calls = 0 |
| + turns.debts.LockHook = func(int) error { |
| + if calls++; calls != 3 { |
| + return nil |
| + } |
| + f, err := os.OpenFile(turns.debts.Path+".lock", os.O_CREATE|os.O_RDWR, 0600) |
| + if err != nil { |
| + return err |
| + } |
| + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { |
| + f.Close() |
| + return err |
| + } |
| + time.AfterFunc(time.Second, func() { f.Close() }) |
| + return nil |
| + } |
| + start := time.Now() |
| + if x.Verify(RecordID(0, "attempt-c")) { |
| + t.Fatal("proven though another process held the discharge's lock past the deadline") |
| + } |
| + if took := time.Since(start); took > 900*time.Millisecond { |
| + t.Fatalf("a held lock kept Verify waiting %s, past its deadline", took) |
| + } |
| + turns.debts.LockHook = nil |
| + time.Sleep(1100 * time.Millisecond) |
| + if !turns.debts.Owes("attempt-c") { |
| + t.Fatal("the debt went with the lock held") |
| + } |
| + if !x.Verify(RecordID(0, "attempt-c")) || turns.debts.Owes("attempt-c") { |
| + t.Fatal("a later Verify did not carry on once the lock was free") |
| + } |
| +} |
diff --git a/internal/runner/mac/fix9f_test.go b/internal/runner/mac/fix9f_test.go| index 7e3bb66f..79db6883 100644 |
| --- a/internal/runner/mac/fix9f_test.go |
| +++ b/internal/runner/mac/fix9f_test.go |
| @@ -184,9 +184,20 @@ func TestRebootIgnoresTheOldBootsGroups(t *testing.T) { |
| } |
| s.close() |
| } |
| - if !x.Verify(RecordID(99400, "attempt-c")) || turns.Pending() { |
| + if !x.VerifyFor(RecordID(99400, "attempt-c"), ConsumerStep) || turns.Pending() { |
| t.Fatalf("record %v: a reused group id of the old boot blocked a proven reboot", viaRecord) |
| } |
| + // Proven again for the same consumer after a runner restart, and |
| + // for the other consumer: the completion stays until both have it. |
| + again := NewTurns(turns.lock).Sweep(tb) |
| + again.own, again.Settle, again.boot = turns.own, turns.Settle, turns.boot |
| + y := &Executor{Turns: again, Settle: x.Settle} |
| + if !y.VerifyFor(RecordID(99400, "attempt-c"), ConsumerStep) || !y.VerifyFor(RecordID(99400, "attempt-c"), ConsumerKeychain) { |
| + t.Fatalf("record %v: a later proof of the same record failed", viaRecord) |
| + } |
| + if again.debts.Owes("attempt-c") { |
| + t.Fatalf("record %v: the completion stayed after every consumer had it", viaRecord) |
| + } |
| if sig := tb.signalled(); len(sig) != 0 { |
| t.Fatalf("record %v: signalled %v", viaRecord, sig) |
| } |
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go| index 5cb34fb7..1975e622 100644 |
| --- a/internal/runner/mac/gate.go |
| +++ b/internal/runner/mac/gate.go |
| @@ -222,6 +222,9 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi |
| // kills every marked process before the runner reports runner_restarted. |
| func (g *Gate) Verify(id string) bool { return g.executor().Verify(id) } |
| +// VerifyFor is Verify by a named consumer (Executor.VerifyFor). |
| +func (g *Gate) VerifyFor(id, consumer string) bool { return g.executor().VerifyFor(id, consumer) } |
| + |
| func exitCode(err error) int { |
| if err == nil { |
| return 0 |
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go| index 2bd151fd..d16513ce 100644 |
| --- a/internal/runner/mac/launch.go |
| +++ b/internal/runner/mac/launch.go |
| @@ -146,7 +146,7 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f |
| // cleanup on record: a runner killed from here on leaves it to the |
| // next process (a restart), never to another turn of this one. |
| if x.UserTemp != "" { |
| - if err := x.finishPending(ctx, turn, time.Now().Add(x.settleLimit())); err != nil { |
| + if err := x.finishPending(ctx, turn, time.Now().Add(x.settleLimit()), time.Now().Add(x.settleLimit()+3*time.Minute)); err != nil { |
| return nil, err |
| } |
| temp, err := openTemp(x.UserTemp, nil) |
| @@ -154,7 +154,7 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f |
| return nil, err |
| } |
| r.temp = temp |
| - if err := x.Turns.writePending(pendingRecord{Attempt: marker, Before: temp.before, Runner: selfID(), Began: began, BootID: bootID}); err != nil { |
| + if err := x.Turns.writePending(pendingRecord{Attempt: marker, Before: temp.before, Runner: proc.Self(), Began: began, BootID: bootID}); err != nil { |
| temp.close() |
| return nil, errors.Join(ErrRecord, err) |
| } |
| @@ -216,7 +216,7 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f |
| r.adopt([]ProcInfo{leader}) |
| } |
| if r.temp != nil { |
| - _ = x.Turns.writePending(pendingRecord{Attempt: marker, PGID: r.pgid, Before: r.temp.before, Runner: selfID(), Began: began, BootID: bootID}) |
| + _ = x.Turns.writePending(pendingRecord{Attempt: marker, PGID: r.pgid, Before: r.temp.before, Runner: proc.Self(), Began: began, BootID: bootID}) |
| } |
| var noted error |
| if turn != nil { |
| @@ -439,8 +439,9 @@ func (r *Run) Finish(ctx context.Context) { |
| // only when it is turn's to finish (Turns.mayFinish: its owner, or a |
| // restart): that attempt's end proven (settleRecord), its simulators |
| // shut down, then T cleaned against what it held before. Another live |
| -// owner's: ErrPendingCleanup, nothing touched. |
| -func (x *Executor) finishPending(ctx context.Context, turn *Turn, deadline time.Time) error { |
| +// owner's: ErrPendingCleanup, nothing touched. The proof is due by |
| +// settleBy, the rest by cleanBy. |
| +func (x *Executor) finishPending(ctx context.Context, turn *Turn, settleBy, cleanBy time.Time) error { |
| r, ok, err := x.Turns.readPending() |
| if err != nil || !ok { |
| return err |
| @@ -448,17 +449,21 @@ func (x *Executor) finishPending(ctx context.Context, turn *Turn, deadline time. |
| if !x.Turns.mayFinish(turn, r) { |
| return ErrPendingCleanup |
| } |
| - // settleRecord refuses a proof once deadline has passed (its last |
| + // settleRecord refuses a proof once settleBy has passed (its last |
| // act): the cleanup's proof read is under the caller's deadline. |
| // An attempt of an earlier boot is over (its group id is this boot's |
| // to use); otherwise its end is proven first. |
| b, berr := x.Turns.bootNow() |
| - if !proc.Rebooted(r.BootID, r.Began, b, berr) && !x.settleRecord(r.PGID, r.Attempt, deadline) { |
| + if !proc.Rebooted(r.BootID, r.Began, b, berr) && !x.settleRecord(r.PGID, r.Attempt, settleBy) { |
| // That attempt's end, not this one's: nothing of this one ran. |
| return errors.Join(ErrPendingCleanup, errors.New("mac: its end is not proven")) |
| } |
| + // Bounded by cleanBy: past it the record stays and a later call |
| + // continues (shutting simulators down and cleaning T again is safe). |
| + qctx, cancel := context.WithDeadline(context.WithoutCancel(ctx), cleanBy) |
| + defer cancel() |
| if x.QuietSimulators != nil { |
| - x.QuietSimulators(context.WithoutCancel(ctx)) |
| + x.QuietSimulators(qctx) |
| } |
| s, err := openTemp(x.UserTemp, r.Before) |
| if err != nil { |
| @@ -468,6 +473,9 @@ func (x *Executor) finishPending(ctx context.Context, turn *Turn, deadline time. |
| if err := s.clean(); err != nil { |
| return err |
| } |
| + if !time.Now().Before(cleanBy) { |
| + return errors.Join(ErrPendingCleanup, errors.New("mac: the cleanup outlasted its deadline")) |
| + } |
| return x.Turns.dropPending() |
| } |
| @@ -496,7 +504,12 @@ func parseRecord(id string) (int, string, bool) { return proc.ParseRecord(id) } |
| // Ended only when the group is gone (kill(-pgid, 0) is ESRCH), nothing |
| // carries the marker, its turn is settled and owes nothing, and its |
| // cleanup is done. |
| -func (x *Executor) Verify(id string) bool { |
| +func (x *Executor) Verify(id string) bool { return x.VerifyFor(id, "") } |
| + |
| +// VerifyFor is Verify by a named consumer of the record's proof |
| +// (ConsumerStep, ConsumerKeychain): a reboot's completion is kept until |
| +// each has taken it ("" takes nothing). |
| +func (x *Executor) VerifyFor(id, consumer string) bool { |
| pgid, attempt, ok := parseRecord(id) |
| if !ok { |
| return false |
| @@ -535,13 +548,28 @@ func (x *Executor) Verify(id string) bool { |
| if err != nil { |
| return false |
| } |
| - if pending && r.Attempt == attempt && x.finishPending(context.Background(), held, deadline) != nil { |
| + if pending && r.Attempt == attempt && x.finishPending(context.Background(), held, deadline, deadline) != nil { |
| return false |
| } |
| } |
| - return x.Turns == nil || x.Turns.debts.Discharge(attempt) == nil |
| + if x.Turns == nil { |
| + return true |
| + } |
| + if rebooted { |
| + // Kept for every consumer (and any later proof) of the record. |
| + b, err := x.Turns.bootNow() |
| + return err == nil && x.Turns.debts.Complete(attempt, consumer, b.ID, []string{ConsumerStep, ConsumerKeychain}, deadline) == nil |
| + } |
| + return x.Turns.debts.Discharge(attempt, deadline) == nil |
| } |
| +// The consumers of a record's proof (VerifyFor): the step's recovery |
| +// and the credential (Keychain) recovery. |
| +const ( |
| + ConsumerStep = "step" |
| + ConsumerKeychain = "keychain" |
| +) |
| + |
| // settleRecord is proc.SettleMarked on this executor's table. |
| func (x *Executor) settleRecord(pgid int, attempt string, deadline time.Time) bool { |
| return proc.SettleMarked(x.procs(), x.own(), pgid, attempt, deadline) |
diff --git a/internal/runner/mac/proc/clear.go b/internal/runner/mac/proc/clear.go| index ce0682ff..98d7b53b 100644 |
| --- a/internal/runner/mac/proc/clear.go |
| +++ b/internal/runner/mac/proc/clear.go |
| @@ -65,18 +65,18 @@ func IdleClear(t Table, own *Own, o Obligation, baseline []ID, deadline time.Tim |
| // that once the whole proof holds); an idle read's count is kept. |
| func (d *Debts) Assess(attempt string, t Table, own *Own, boot Boot, bootErr error, deadline time.Time) (rebooted, met bool) { |
| met = true |
| - _ = d.locked(func() error { |
| + err := d.lockedBy(deadline, func() error { |
| all, err := d.load() |
| if err != nil { |
| - met = false |
| - return nil |
| + return err |
| } |
| + resolved := func(o Obligation) bool { return o.ProvenIn != "" || Rebooted(o.BootID, o.Began, boot, bootErr) } |
| // The earliest unresolved turn's table, by start: one with no |
| // start counts as earliest; one a reboot resolved does not count. |
| var earliest *Obligation |
| for i := range all { |
| o := &all[i] |
| - if Rebooted(o.BootID, o.Began, boot, bootErr) { |
| + if resolved(*o) { |
| continue |
| } |
| if earliest == nil || o.Began.IsZero() || !earliest.Began.IsZero() && o.Began.Before(earliest.Began) { |
| @@ -96,11 +96,11 @@ func (d *Debts) Assess(attempt string, t Table, own *Own, boot Boot, bootErr err |
| continue |
| } |
| switch { |
| - case Rebooted(o.BootID, o.Began, boot, bootErr): |
| + case resolved(o): |
| rebooted = true |
| case !o.Incomplete: |
| met = met && o.Met(t) |
| - case !o.FlagsKnown || o.UnsandboxedRan: |
| + case !o.FlagsKnown || o.UnsandboxedRan || !othersClear(all, i, t, resolved): |
| // Something may have left the runner user: a reboot only. |
| met = false |
| default: |
| @@ -116,12 +116,29 @@ func (d *Debts) Assess(attempt string, t Table, own *Own, boot Boot, bootErr err |
| } |
| return nil |
| }) |
| - return rebooted, met && time.Now().Before(deadline) |
| + return rebooted, err == nil && met && time.Now().Before(deadline) |
| +} |
| + |
| +// othersClear: every other unresolved turn shows nothing ran outside a |
| +// sandbox, and has everything it names gone for every user. Else one of |
| +// its processes may have left the runner user and could serve this |
| +// turn's work unseen. |
| +func othersClear(all []Obligation, me int, t Table, resolved func(Obligation) bool) bool { |
| + for i, o := range all { |
| + if i == me || resolved(o) { |
| + continue |
| + } |
| + if !o.FlagsKnown || o.UnsandboxedRan || !o.gone(t) { |
| + return false |
| + } |
| + } |
| + return true |
| } |
| -// Discharge removes every obligation naming attempt (its end proven). |
| -func (d *Debts) Discharge(attempt string) error { |
| - return d.locked(func() error { |
| +// Discharge removes every obligation naming attempt (its end proven), |
| +// before deadline (zero: none), or not at all. |
| +func (d *Debts) Discharge(attempt string, deadline time.Time) error { |
| + return d.lockedBy(deadline, func() error { |
| all, err := d.load() |
| if err != nil { |
| return err |
| @@ -130,6 +147,52 @@ func (d *Debts) Discharge(attempt string) error { |
| d.between() |
| } |
| keep := slices.DeleteFunc(all, func(o Obligation) bool { return slices.Contains(o.Markers, attempt) }) |
| + if !deadline.IsZero() && !time.Now().Before(deadline) { |
| + return errLate |
| + } |
| + return d.save(keep) |
| + }) |
| +} |
| + |
| +// completionLife bounds how long a reboot's completion waits for its |
| +// consumers (a record that only one of them ever verifies). |
| +const completionLife = 30 * 24 * time.Hour |
| + |
| +// Complete records, before deadline, that attempt was proven over by a |
| +// reboot into boot (a boot-qualified completion): what it owed goes, one |
| +// completion stays, and consumer is on it. Every later proof of the |
| +// record, in any runner process, is that completion: no process check, |
| +// no signal. It goes once every one of consumers has it ("" records |
| +// nothing), or after completionLife. |
| +func (d *Debts) Complete(attempt, consumer, boot string, consumers []string, deadline time.Time) error { |
| + return d.lockedBy(deadline, func() error { |
| + all, err := d.load() |
| + if err != nil { |
| + return err |
| + } |
| + done := Obligation{Markers: []string{attempt}, ProvenIn: boot, ProvenAt: time.Now()} |
| + var keep []Obligation |
| + for _, o := range all { |
| + switch { |
| + case o.ProvenIn != "" && time.Since(o.ProvenAt) > completionLife: |
| + case !slices.Contains(o.Markers, attempt): |
| + keep = append(keep, o) |
| + case o.ProvenIn != "": |
| + done = o |
| + } |
| + } |
| + if consumer != "" && !slices.Contains(done.Recorded, consumer) { |
| + done.Recorded = append(done.Recorded, consumer) |
| + } |
| + if !slices.ContainsFunc(consumers, func(c string) bool { return !slices.Contains(done.Recorded, c) }) { |
| + done = Obligation{} |
| + } |
| + if done.ProvenIn != "" { |
| + keep = append(keep, done) |
| + } |
| + if !deadline.IsZero() && !time.Now().Before(deadline) { |
| + return errLate |
| + } |
| return d.save(keep) |
| }) |
| } |
diff --git a/internal/runner/mac/proc/debts.go b/internal/runner/mac/proc/debts.go| index a2b1dd43..9caff366 100644 |
| --- a/internal/runner/mac/proc/debts.go |
| +++ b/internal/runner/mac/proc/debts.go |
| @@ -8,6 +8,7 @@ import ( |
| "slices" |
| "sync" |
| "syscall" |
| + "time" |
| ) |
| // Debts keeps what unproven turns still owe, past their turn records: |
| @@ -19,6 +20,10 @@ type Debts struct { |
| // between runs between a read and its write (tests: another |
| // process's write in the gap). |
| between func() |
| + // LockHook (a test seam) runs before each lock is taken, with its number from 1 |
| + // (tests: a lock that fails, or is slow). |
| + LockHook func(n int) error |
| + locks int |
| } |
| // Owe keeps o durably. |
| @@ -35,10 +40,31 @@ func (d *Debts) Owe(o Obligation) error { |
| // locked runs fn holding the debts: this instance's mutex and, for a |
| // file, an flock on Path+".lock" that every runner process takes for |
| // every read-modify-write. |
| -func (d *Debts) locked(fn func() error) error { |
| - d.mu.Lock() |
| +func (d *Debts) locked(fn func() error) error { return d.lockedBy(time.Time{}, fn) } |
| + |
| +// errLate: the debts could not be read or written before the deadline. |
| +var errLate = errors.New("mac: the debts were not reached in time") |
| + |
| +// lockedBy is locked, given up at deadline (zero: none). Every error |
| +// (the lock file, the lock, the deadline) is the caller's. |
| +func (d *Debts) lockedBy(deadline time.Time, fn func() error) error { |
| + late := func() bool { return !deadline.IsZero() && !time.Now().Before(deadline) } |
| + for !d.mu.TryLock() { |
| + if late() { |
| + return errLate |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| defer d.mu.Unlock() |
| + if d.locks++; d.LockHook != nil { |
| + if err := d.LockHook(d.locks); err != nil { |
| + return err |
| + } |
| + } |
| if d.Path == "" { |
| + if late() { |
| + return errLate |
| + } |
| return fn() |
| } |
| f, err := os.OpenFile(d.Path+".lock", os.O_CREATE|os.O_RDWR, 0600) |
| @@ -46,10 +72,23 @@ func (d *Debts) locked(fn func() error) error { |
| return err |
| } |
| defer f.Close() |
| - if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { |
| - return err |
| + for { |
| + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| + if err == nil { |
| + break |
| + } |
| + if !errors.Is(err, syscall.EWOULDBLOCK) { |
| + return err |
| + } |
| + if late() { |
| + return errLate |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| } |
| defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) |
| + if late() { |
| + return errLate |
| + } |
| return fn() |
| } |
diff --git a/internal/runner/mac/proc/proc.go b/internal/runner/mac/proc/proc.go| index 75a689be..013e10df 100644 |
| --- a/internal/runner/mac/proc/proc.go |
| +++ b/internal/runner/mac/proc/proc.go |
| @@ -270,6 +270,28 @@ func NewScope(p Table, markers []string, before []ID) *Scope { |
| return s |
| } |
| +// Resume is a scope over p carrying on a stored turn's: its markers, |
| +// groups, sessions and kill set. With sweep, before is the turn's table |
| +// when it began (a nil one is empty); without, there is no sweep. |
| +func Resume(p Table, markers []string, sweep bool, before []ID, groups, sessions Span, killed []ID) *Scope { |
| + if !sweep { |
| + before = nil |
| + } else if before == nil { |
| + before = []ID{} |
| + } |
| + s := NewScope(p, markers, before) |
| + for id, at := range groups { |
| + s.Groups[id] = at |
| + } |
| + for id, at := range sessions { |
| + s.Sessions[id] = at |
| + } |
| + for _, id := range killed { |
| + s.Killed[id] = true |
| + } |
| + return s |
| +} |
| + |
| // Track adds to the scope what list shows of it: children of what it |
| // has seen (a true child started no earlier than its parent), members |
| // of its groups and sessions (not of an id used again), and marked |
| @@ -568,6 +590,12 @@ type Obligation struct { |
| // only a turn whose record shows nothing ran outside a sandbox). |
| FlagsKnown bool `json:"flags_known,omitempty"` |
| UnsandboxedRan bool `json:"unsandboxed_ran,omitempty"` |
| + // ProvenIn is set on a completion: the boot (its id) whose start |
| + // proved the attempt over; ProvenAt when, and Recorded which |
| + // consumers have taken it (Complete). |
| + ProvenIn string `json:"proven_in,omitempty"` |
| + ProvenAt time.Time `json:"proven_at,omitzero"` |
| + Recorded []string `json:"recorded,omitempty"` |
| // Incomplete: the turn's record was never completed, so what it owes |
| // cannot be known: never met. |
| Incomplete bool `json:"incomplete,omitempty"` |
diff --git a/internal/runner/mac/proc/proc_test.go b/internal/runner/mac/proc/proc_test.go| index 1c8850e3..249cb4ac 100644 |
| --- a/internal/runner/mac/proc/proc_test.go |
| +++ b/internal/runner/mac/proc/proc_test.go |
| @@ -85,7 +85,7 @@ func TestDebtsSerializedAcrossInstances(t *testing.T) { |
| go func() { done <- b.Owe(Obligation{Markers: []string{"attempt-b"}}) }() |
| time.Sleep(200 * time.Millisecond) |
| } |
| - if err := a.Discharge("attempt-a"); err != nil { |
| + if err := a.Discharge("attempt-a", time.Time{}); err != nil { |
| t.Fatal(err) |
| } |
| a.between = nil |
| @@ -96,3 +96,26 @@ func TestDebtsSerializedAcrossInstances(t *testing.T) { |
| t.Fatal("another instance's obligation was lost, or the discharged one stayed") |
| } |
| } |
| + |
| +// Fix round 2, #4: a lock that comes after the deadline runs nothing, |
| +// and a discharge whose work outlasts it removes nothing. |
| +func TestDebtsUnderTheDeadline(t *testing.T) { |
| + d := &Debts{Path: filepath.Join(t.TempDir(), "owed")} |
| + if err := d.Owe(Obligation{Markers: []string{"attempt-a"}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + d.LockHook = func(int) error { time.Sleep(150 * time.Millisecond); return nil } |
| + ran := false |
| + if err := d.lockedBy(time.Now().Add(50*time.Millisecond), func() error { ran = true; return nil }); err == nil || ran { |
| + t.Fatalf("a lock taken after its deadline ran its work (err %v)", err) |
| + } |
| + d.LockHook = nil |
| + d.between = func() { time.Sleep(150 * time.Millisecond) } |
| + if err := d.Discharge("attempt-a", time.Now().Add(50*time.Millisecond)); err == nil { |
| + t.Fatal("a discharge that outlasted its deadline succeeded") |
| + } |
| + d.between = nil |
| + if !d.Owes("attempt-a") { |
| + t.Fatal("a late discharge removed the obligation") |
| + } |
| +} |
diff --git a/internal/runner/mac/turns.go b/internal/runner/mac/turns.go| index d2fb2ff2..3846a47c 100644 |
| --- a/internal/runner/mac/turns.go |
| +++ b/internal/runner/mac/turns.go |
| @@ -394,7 +394,7 @@ func (t *Turns) begin(op Op, deadline time.Time) (*Turn, error) { |
| b, _ := t.bootNow() |
| var raw [8]byte |
| _, _ = rand.Read(raw[:]) |
| - rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: selfID(), Began: time.Now(), BootID: b.ID, FlagsKnown: true} |
| + rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: proc.Self(), Began: time.Now(), BootID: b.ID, FlagsKnown: true} |
| if t.sweep != nil { |
| if !t.sweep.Sweeps() { |
| return nil, ErrNoSweep |
| @@ -435,33 +435,16 @@ func (t *Turns) settle(deadline time.Time) error { |
| } |
| return t.dropTurn(rec.ID) |
| } |
| - if rec.Runner != selfID() { |
| + if rec.Runner != proc.Self() { |
| // Another runner process's record: only once it is surely gone. |
| if alive, known := proc.Alive(t.identities(), rec.Runner); alive || !known { |
| return ErrUnsettled |
| } |
| } |
| - procs := t.table() |
| if rec.Sweep && (t.sweep == nil || !t.sweep.Sweeps()) { |
| return ErrUnsettled |
| } |
| - var before []ProcID |
| - if rec.Sweep { |
| - before = rec.Before |
| - if before == nil { |
| - before = []ProcID{} |
| - } |
| - } |
| - s := newScope(procs, rec.Markers, before) |
| - for id, at := range rec.Groups { |
| - s.Groups[id] = at |
| - } |
| - for id, at := range rec.Sessions { |
| - s.Sessions[id] = at |
| - } |
| - for _, id := range rec.Killed { |
| - s.Killed[id] = true |
| - } |
| + s := proc.Resume(t.table(), rec.Markers, rec.Sweep, rec.Before, rec.Groups, rec.Sessions, rec.Killed) |
| out := s.Settle(t.owned(), deadline, 0, func() bool { return true }, nil) |
| owe := func() proc.Obligation { |
| o := s.Owe() |
| @@ -531,9 +514,6 @@ func (t *Turns) dropTurn(id string) error { |
| return t.records.Drop() |
| } |
| -// selfID is this runner process's identity (proc.Self). |
| -func selfID() ProcID { return proc.Self() } |
| - |
| func (t *Turns) identities() Procs { |
| if t != nil && t.ids != nil { |
| return t.ids |
| @@ -597,7 +577,7 @@ func (t *Turns) mayFinish(u *Turn, r pendingRecord) bool { |
| if r.Runner.PID == 0 { |
| return true |
| } |
| - if r.Runner == selfID() { |
| + if r.Runner == proc.Self() { |
| return u.owns(r.Attempt) |
| } |
| // A restart only once the writer is surely gone: an identity that |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index 0127ef64..dd2e68f1 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -46,7 +46,7 @@ func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, li |
| return gateResult{output: r.Output, reason: r.Reason, code: r.Code, terminated: r.Terminated, sandbox: r.Sandbox} |
| } |
| -func (m macGate) Verify(id string) bool { return m.g.Verify(id) } |
| +func (m macGate) Verify(id string) bool { return m.g.VerifyFor(id, mac.ConsumerStep) } |
| // macChecks chooses each attempt's gate from the probe report this |
| // process made and still trusts (macProbes.trusted): srt and seatbelt |
| @@ -141,7 +141,7 @@ func unsandboxedChosen(ctx context.Context) bool { |
| // Verify settles a recorded attempt the same way whatever confined it, |
| // with the user temp, so the attempt's own unfinished cleanup is |
| // finished once its end is proven. |
| -func (m *macChecks) Verify(id string) bool { return m.sandboxed.Verify(id) } |
| +func (m *macChecks) Verify(id string) bool { return m.sandboxed.VerifyFor(id, mac.ConsumerStep) } |
| // macTaint is sticky: set once a check ran outside the sandbox, kept in |
| // the state dir and by the instance (which says so in every welcome), so |
diff --git a/internal/runner/thin/maccreds.go b/internal/runner/thin/maccreds.go| index 33643d23..2060c7fa 100644 |
| --- a/internal/runner/thin/maccreds.go |
| +++ b/internal/runner/thin/maccreds.go |
| @@ -286,7 +286,7 @@ func (m *macCreds) ended(w creds.Watch) bool { |
| if run == "" { |
| run = mac.RecordID(0, w.Marker) |
| } |
| - if m.exec.Verify(run) { |
| + if m.exec.VerifyFor(run, mac.ConsumerKeychain) { |
| return true |
| } |
| boot, err := m.boot() |