oficina / equipo Public

Mac slice F task 9: reboot and idle clearance of an unproven turn

A worker killed mid-turn left its record incomplete and the attempt
unproven for good (M9e). Two clearances now prove such a turn over:

- an idle read (first): holding the Mac's turn, two whole, timely reads
  of the runner user find only the runner, its registered helpers and
  processes from before the turn, by pid and start time, and everything
  the record names is gone for every user; refused outside a held turn
  and on a table that may not sweep
- a reboot (fallback): another boot id (kern.bootsessionuuid) and a boot
  time after the turn began; such a record is dropped without a sweep

Unaccounted processes keep it unproven and the Mac reports only their
count (unproven: processes_left, protocol 37). record_incomplete now
says a restart clears it; both texts pending. Turn and pending records
move to proc.Store (mac budget). Spec 8.8 updated.

Mutations, all caught: B1-B5 (reboot), I1-I9 (idle), W1, W2, W4.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 3545d40a9330b7f53f20442a40e5061fde4967e8 parent 46a1bed
23 files changed, +730 −116
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json +9 −3
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +2 −1
  • docs/superpowers/specs/2026-11-07-equipo-mac-runners.md +31 −4
  • internal/equipo/copy.go +2 −1
  • internal/equipo/mac_view_test.go +20 −3
  • internal/equipo/runners.go +7 −2
  • internal/runner/mac/clear_test.go +273 −0
  • internal/runner/mac/creds/boot_darwin.go +4 −0
  • internal/runner/mac/creds/boot_linux.go +10 −0
  • internal/runner/mac/creds/guard.go +15 −0
  • internal/runner/mac/creds/guard_test.go +11 −0
  • internal/runner/mac/fix2_test.go +18 −8
  • internal/runner/mac/launch.go +3 −1
  • internal/runner/mac/launch_test.go +5 −4
  • internal/runner/mac/proc/clear.go +117 −0
  • internal/runner/mac/proc/proc.go +19 −3
  • internal/runner/mac/proc/store.go +69 −0
  • internal/runner/mac/turns.go +65 −79
  • internal/runner/thin/mac.go +2 −2
  • internal/wire/mac_engineering.go +2 −2
  • internal/wire/runners.go +16 −1
  • internal/wire/unproven_count_test.go +28 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index cb17c9c2..0bea8ae2 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI.
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
-size internal/equipo 24235 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes, Mac credential copy, Mac connections, Engineering reasons, F probes, D1; 24235.
-size internal/wire 8694 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes, credential_unproven, model hold, runner user; 8694.
+size internal/equipo 24241 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, slice F codes, connections, reasons, F probes, D1; measured 24241.
+size internal/wire 8709 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, unproven codes, model hold, runner user; measured 8709.
size internal/equipotest - 12683 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures and Rastrillo asset contract; measured 0/12683 source/test lines.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
diff --git a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
index 1ad14eab..52df6cb7 100644
--- a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
+++ b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json
@@ -99,9 +99,9 @@
},
{
"key": "runner.unproven.record_incomplete",
- "where": "Machines page, a Mac's card: a note when an attempt there can never be proven over (its turn record was incomplete; wire.UnprovenRecordIncomplete). The step stays unfinished, with no Retry.",
- "draft": "Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished.",
- "reviewed": "Luna, delegated (Paul 2026-10-25), 2026-11-29"
+ "where": "Machines page, a Mac's card: a note when an attempt there is not proven over (its turn record was incomplete; wire.UnprovenRecordIncomplete). The step stays unfinished, with no Retry, until a restart of the Mac or an idle check clears it.",
+ "draft": "Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished. Restart the Mac to clear it.",
+ "reviewed": "pending re-review (changed after Luna)"
},
{
"key": "runner.mac.home_open",
@@ -357,5 +357,11 @@
"key": "docs/mac-runner.md#make-changes-on-the-mac",
"where": "docs/mac-runner.md, the section \"Make changes on the Mac\" (owner turns the switch on; the runner user fixes its home folder if the Machines page asks; the person adds Claude to the Mac and signs in)",
"draft": "PLACEHOLDER: not written yet. Plan task 17 adds this section as draft copy; review it with the rest once it exists."
+ },
+ {
+ "key": "runner.unproven.processes_left",
+ "where": "Machines page, a Mac's card: an idle check found processes of the runner user no record accounts for, so an earlier step stays unfinished (wire.UnprovenProcessesLeft); %d is their count, never names, pids or paths. A restart of the Mac clears it.",
+ "draft": "Processes from an earlier step are still running on this Mac: %d. Restart the Mac to clear it.",
+ "reviewed": "pending re-review"
}
]
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index b7af8895..94828b2f 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -7021,7 +7021,7 @@ records remain unchanged.
| `chat.merge.not.mac_made` | it was made on a Mac runner, so it merges only when you choose | Copy specialist | COPY REVIEW PENDING |
| `work.reason.workspace_too_large` | the change is too large to send to the Mac | Copy specialist | COPY REVIEW PENDING |
| `runner.probe_detail.turn_busy` | The Mac was busy with other work, so this was not checked. | Copy specialist | COPY REVIEW PENDING |
-| `runner.unproven.record_incomplete` | Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished. | Copy specialist | COPY REVIEW PENDING |
+| `runner.unproven.record_incomplete` | Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished. Restart the Mac to clear it. | Copy specialist | COPY REVIEW PENDING |
| `runner.mac.home_open` | Other people can open %[1]s's home folder on this Mac, so Equipo will not keep Claude there. As %[1]s, run chmod 700 ~, then try again. | Copy specialist | COPY REVIEW PENDING |
| `runner.mac.home_open_folder` | Other people can reach a folder where %[1]s keeps Claude on this Mac, so Equipo will not keep Claude there. The runner log names the folder and what to change. | Copy specialist | COPY REVIEW PENDING |
| `runner.mac.keychain_item` | This Mac's Keychain has an item named %[1]s, so Equipo will not keep Claude there. As %[2]s, remove it in Keychain Access, then try again. | Copy specialist | COPY REVIEW PENDING |
@@ -7055,6 +7055,7 @@ records remain unchanged.
| `runner.engineering.tainted` | No: it once ran checks outside the sandbox | Copy specialist | COPY REVIEW PENDING |
| `runner.mac.holds_claude` | This Mac holds a Claude connection, or something one left, so its checks run only in its sandbox. | Copy specialist | COPY REVIEW PENDING |
| `runner.tainted_held` | A check ran outside the sandbox on this Mac, so Equipo no longer trusts its sandbox. This Mac also holds a Claude connection or something left by one. Its checks cannot run outside the sandbox, so they wait. To start clean, install the runner again under a new Mac user. | Copy specialist | COPY REVIEW PENDING |
+| `runner.unproven.processes_left` | Processes from an earlier step are still running on this Mac: %d. Restart the Mac to clear it. | Copy specialist | COPY REVIEW PENDING |
## Task 21
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 cedf82d7..4452d57e 100644
--- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
+++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
@@ -1022,10 +1022,37 @@ and its proof withheld, and no further launch starts in that turn. A
record is complete (a durable `complete` mark) only once every launch of
the turn has written its own final note, each after all its group and
session writes, and no evidence write of the turn ever failed. After a restart, a record without that mark is
-incomplete: what it left is swept as usual, but recovery never proves its
-attempts over. Each such attempt stays unterminated with no Retry, and
-the Mac's card on the Machines page says so (the capability code
-`unproven: record_incomplete`, worded on the instance).
+incomplete: what it left is swept as usual, but recovery alone never
+proves its attempts over. Each such attempt stays unterminated with no
+Retry, and the Mac's card on the Machines page says so (the capability
+code `unproven: record_incomplete`, worded on the instance, which also
+says a restart of the Mac clears it), until one of two clearances proves
+it:
+
+1. **An idle read** (first, and cheaper). The runner user is dedicated.
+ At runner start, and each time the instance syncs (a person's Retry
+ among them), the runner holds the Mac's turn, so no operation starts
+ a process meanwhile. It then reads every process of the runner user
+ twice, each read whole and in time. Every process found must be the
+ runner, a helper it registered (with what that helper started), or a
+ process the turn's record shows was there before the turn began, all
+ by pid and start time. Then every process, group and session the
+ record names must be gone, for every user. 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, pids or paths, and says a restart
+ clears it. The clearance refuses to run outside a held turn.
+2. **A reboot** (the fallback). Nothing outlives a boot. A record or an
+ obligation whose turn began in an earlier boot counts as proven. That
+ needs another boot identity (`kern.bootsessionuuid`, so a clock step
+ cannot fake it) and a boot time after the turn's start. The record is
+ then dropped without a sweep (its table is the earlier boot's), and
+ what it owed is cleared. An unreadable boot proves nothing.
+
+The idle read cannot see a process that has left the runner user by
+changing its real uid (a setuid program that calls `setuid`) and sits
+in a group or session the incomplete record never got. For a dedicated
+Standard user that is hard to reach; a reboot covers it.
Otherwise the step stays unterminated (no Retry), and its turn's record
stays too. The next turn, in any runner process, settles that record
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 6d47d038..ef9f0a70 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2116,7 +2116,8 @@ var pageCopy = map[string]string{
"runner.verdict.skipped": "Not run",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"runner.verdict.unavailable": "Unavailable",
- "runner.unproven.record_incomplete": "Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished.", // COPY REVIEW PENDING
+ "runner.unproven.record_incomplete": "Equipo could not confirm that an earlier step on this Mac stopped completely, so the step stays unfinished. Restart the Mac to clear it.", // COPY REVIEW PENDING
+ "runner.unproven.processes_left": "Processes from an earlier step are still running on this Mac: %d. Restart the Mac to clear it.", // COPY REVIEW PENDING
"runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING
"runner.mac.home_open": "Other people can open %[1]s's home folder on this Mac, so Equipo will not keep Claude there. As %[1]s, run chmod 700 ~, then try again.", // COPY REVIEW PENDING
"runner.mac.home_open_folder": "Other people can reach a folder where %[1]s keeps Claude on this Mac, so Equipo will not keep Claude there. The runner log names the folder and what to change.", // COPY REVIEW PENDING
diff --git a/internal/equipo/mac_view_test.go b/internal/equipo/mac_view_test.go
index d60967fa..6a9c48e4 100644
--- a/internal/equipo/mac_view_test.go
+++ b/internal/equipo/mac_view_test.go
@@ -87,14 +87,31 @@ func TestProbeDetailCodes(t *testing.T) {
// An attempt whose end a Mac can never prove is said on the Machines
// page, worded here from its code; no code, nothing.
func TestUnprovenEndShown(t *testing.T) {
- if got := unprovenText(wire.UnprovenRecordIncomplete); got == "" || got == wire.UnprovenRecordIncomplete || got != copyText("runner.unproven.record_incomplete") {
+ if got := unprovenText(wire.UnprovenRecordIncomplete, 0); got == "" || got == wire.UnprovenRecordIncomplete || got != copyText("runner.unproven.record_incomplete") {
t.Fatalf("shown as %q", got)
}
// A Mac that could not prove a credential launch ended (task 10).
- if got := unprovenText(wire.UnprovenCredential); got == "" || got != copyText("runner.unproven.credential_unproven") {
+ if got := unprovenText(wire.UnprovenCredential, 0); got == "" || got != copyText("runner.unproven.credential_unproven") {
t.Fatalf("credential_unproven shown as %q", got)
}
- if unprovenText("") != "" || unprovenText("no_such_code") != "" {
+ if unprovenText("", 0) != "" || unprovenText("no_such_code", 0) != "" {
t.Fatal("an unknown or empty code said something")
}
}
+
+// An idle read that found processes no record accounts for says how
+// many, and nothing else about them; both texts say a restart clears it.
+func TestUnprovenProcessesLeftShown(t *testing.T) {
+ got := unprovenText(wire.UnprovenProcessesLeft, 3)
+ if want := strings.ReplaceAll(copyText("runner.unproven.processes_left"), "%d", "3"); got != want || !strings.Contains(got, "3") {
+ t.Fatalf("shown as %q, want %q", got, want)
+ }
+ if unprovenText(wire.UnprovenProcessesLeft, 0) != "" {
+ t.Fatal("a count of none said something")
+ }
+ for _, key := range []string{"runner.unproven.processes_left", "runner.unproven.record_incomplete"} {
+ if !strings.Contains(copyText(key), "Restart the Mac") {
+ t.Fatalf("%s does not say what clears it: %q", key, copyText(key))
+ }
+ }
+}
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go
index 7cd25bfc..6c9a718e 100644
--- a/internal/equipo/runners.go
+++ b/internal/equipo/runners.go
@@ -367,7 +367,7 @@ func reportOf(h wire.Hello) *setup.RunnerReport {
for _, p := range h.Capabilities.Probes {
r.Probes = append(r.Probes, setup.RunnerProbe{ID: p.ID, Verdict: p.Verdict, Detail: probeDetail(p.Detail)})
}
- r.Unproven = unprovenText(h.Capabilities.Unproven)
+ r.Unproven = unprovenText(h.Capabilities.Unproven, h.Capabilities.UnprovenCount)
macGuards(r, *h.Capabilities)
}
return r
@@ -410,12 +410,17 @@ func probeDetail(d string) string {
// unprovenText words a runner's Unproven code; "" for none or one it
// does not know.
-func unprovenText(code string) string {
+func unprovenText(code string, n int) string {
switch code {
case wire.UnprovenRecordIncomplete:
return copyText("runner.unproven.record_incomplete")
case wire.UnprovenCredential:
return copyText("runner.unproven.credential_unproven")
+ case wire.UnprovenProcessesLeft:
+ // A count only: never which processes.
+ if n > 0 {
+ return fmt.Sprintf(copyText("runner.unproven.processes_left"), n)
+ }
}
return ""
}
diff --git a/internal/runner/mac/clear_test.go b/internal/runner/mac/clear_test.go
new file mode 100644
index 00000000..b3427739
--- /dev/null
+++ b/internal/runner/mac/clear_test.go
@@ -0,0 +1,273 @@
+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.
+func owed(before []ProcID) proc.Obligation {
+ return proc.Obligation{Markers: []string{"attempt-c"}, Incomplete: true, Began: turnStart, BootID: "boot-1", Before: before}
+}
+
+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 err := turns.clearOwed(u, "attempt-c"); !errors.Is(err, ErrNoTurn) {
+ t.Fatalf("%s: %v", name, 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 err := turns.clearOwed(u, "attempt-c"); err != nil || !turns.Incomplete() {
+ t.Fatalf("cleared on a table that may not sweep (%v)", err)
+ }
+}
diff --git a/internal/runner/mac/creds/boot_darwin.go b/internal/runner/mac/creds/boot_darwin.go
index e76a954c..cb5a0f76 100644
--- a/internal/runner/mac/creds/boot_darwin.go
+++ b/internal/runner/mac/creds/boot_darwin.go
@@ -15,3 +15,7 @@ func BootTime() (time.Time, error) {
}
return time.Unix(tv.Sec, int64(tv.Usec)*1000), nil
}
+
+// BootID names this boot (kern.bootsessionuuid): a new value after every
+// boot, whatever the clock did.
+func BootID() (string, error) { return unix.Sysctl("kern.bootsessionuuid") }
diff --git a/internal/runner/mac/creds/boot_linux.go b/internal/runner/mac/creds/boot_linux.go
index 6e374d50..2af6f9d2 100644
--- a/internal/runner/mac/creds/boot_linux.go
+++ b/internal/runner/mac/creds/boot_linux.go
@@ -26,3 +26,13 @@ func BootTime() (time.Time, error) {
}
return time.Time{}, errors.New("creds: no boot time")
}
+
+// BootID names this boot (/proc/sys/kernel/random/boot_id): a new value
+// after every boot, whatever the clock did.
+func BootID() (string, error) {
+ raw, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ if id := strings.TrimSpace(string(raw)); err == nil && id != "" {
+ return id, nil
+ }
+ return "", errors.Join(errors.New("creds: no boot id"), err)
+}
diff --git a/internal/runner/mac/creds/guard.go b/internal/runner/mac/creds/guard.go
index efd821ab..f9eedc90 100644
--- a/internal/runner/mac/creds/guard.go
+++ b/internal/runner/mac/creds/guard.go
@@ -16,6 +16,8 @@ import (
"strconv"
"strings"
"syscall"
+
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
)
// ACE is one access control entry as ls -le prints it:
@@ -315,3 +317,16 @@ func tilde(home, p string) string {
func within(home, p string) bool {
return p == home || strings.HasPrefix(p, home+"/")
}
+
+// Boot is this boot: its identity (BootID) and when it began (BootTime).
+func Boot() (proc.Boot, error) {
+ t, err := BootTime()
+ if err != nil {
+ return proc.Boot{}, err
+ }
+ id, err := BootID()
+ if err != nil {
+ return proc.Boot{}, err
+ }
+ return proc.Boot{ID: id, Time: t}, nil
+}
diff --git a/internal/runner/mac/creds/guard_test.go b/internal/runner/mac/creds/guard_test.go
index a4e8f99c..1d498620 100644
--- a/internal/runner/mac/creds/guard_test.go
+++ b/internal/runner/mac/creds/guard_test.go
@@ -253,3 +253,14 @@ func TestParseLSRefusesWhatItCannotRead(t *testing.T) {
t.Fatalf("a path with a space: %+v %v", f, err)
}
}
+
+// This boot has an identity and a time, the same on every read.
+func TestBootIsStable(t *testing.T) {
+ a, err := Boot()
+ if err != nil || a.ID == "" || a.Time.IsZero() {
+ t.Fatalf("%+v %v", a, err)
+ }
+ if b, err := Boot(); err != nil || b != a {
+ t.Fatalf("%+v then %+v (%v)", a, b, err)
+ }
+}
diff --git a/internal/runner/mac/fix2_test.go b/internal/runner/mac/fix2_test.go
index d716ff71..32994029 100644
--- a/internal/runner/mac/fix2_test.go
+++ b/internal/runner/mac/fix2_test.go
@@ -80,11 +80,14 @@ func TestVerifyHasOneDeadline(t *testing.T) {
}
}
-// #8: 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: recovery never proves the end,
-// even once that process is gone, and the runner says so.
-func TestIncompleteRecordIsNeverProven(t *testing.T) {
+// #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)
@@ -135,12 +138,17 @@ func TestIncompleteRecordIsNeverProven(t *testing.T) {
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 attempt whose record was incomplete")
+ 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)
- if nx.Verify(run.ID()) || !next.Incomplete() {
- t.Fatal("an incomplete record became provable, or the runner does not say so")
+ tb.remove(95100)
+ if !nx.Verify(run.ID()) || next.Incomplete() {
+ t.Fatal("not proven once an idle read accounts for every process")
}
}
@@ -367,6 +375,8 @@ func TestFailedLaunchEndsTheTurnsLaunches(t *testing.T) {
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")
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go
index ec4f6de6..747ae3d7 100644
--- a/internal/runner/mac/launch.go
+++ b/internal/runner/mac/launch.go
@@ -498,7 +498,7 @@ func (x *Executor) Verify(id string) bool {
if x.Turns != nil {
r, pending, err := x.Turns.readPending()
owned := x.UserTemp != "" && (err != nil || pending && r.Attempt == attempt)
- if x.Turns.unsettledFor(attempt) || owned {
+ if x.Turns.unsettledFor(attempt) || owned || x.Turns.debts.Owes(attempt) {
u, ok := x.Turns.tryTakeBy(OpRecover, deadline)
if !ok {
return false
@@ -506,6 +506,8 @@ func (x *Executor) Verify(id string) bool {
defer u.Give()
u.adopt(attempt)
held = u
+ // Holding the turn: a reboot or an idle read may prove it.
+ _ = x.Turns.clearOwed(u, attempt)
}
}
// One deadline for the whole proof: settling the turn, the record
diff --git a/internal/runner/mac/launch_test.go b/internal/runner/mac/launch_test.go
index e63429d9..aac5e7a7 100644
--- a/internal/runner/mac/launch_test.go
+++ b/internal/runner/mac/launch_test.go
@@ -697,11 +697,12 @@ func TestTurnRecordWriteFailureStopsTheOperation(t *testing.T) {
if !gone(child) {
t.Fatal("what it left survived the restart's settling")
}
- // Its record was never completed: its end is never proven, and the
- // runner says so.
+ // 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 attempt with an incomplete record was proven over, or the runner does not say so")
+ if !nx.Verify(run.ID()) || next.Incomplete() {
+ t.Fatal("an idle read with nothing unaccounted did not prove it over")
}
}
diff --git a/internal/runner/mac/proc/clear.go b/internal/runner/mac/proc/clear.go
new file mode 100644
index 00000000..7201b3ca
--- /dev/null
+++ b/internal/runner/mac/proc/clear.go
@@ -0,0 +1,117 @@
+package proc
+
+import (
+ "os"
+ "slices"
+ "time"
+)
+
+// Rebooted reports whether now is a later boot than the one a turn began
+// in (boot id then, at began): another boot id, and a boot time after
+// the turn's start. A process does not outlive a boot, so nothing of
+// that turn can be running. Anything unknown or unreadable: no.
+func Rebooted(then string, began time.Time, now Boot, err error) bool {
+ return err == nil && then != "" && now.ID != "" && now.ID != then && !began.IsZero() && now.Time.After(began)
+}
+
+// IdleClear is the clearance of an incomplete turn while no turn runs
+// (the caller holds the Mac's turn): two whole reads of the runner
+// user's processes, each in time, must find only the runner, its own
+// helpers and processes from before that turn (by identity), and then
+// everything o names must be gone for every user. left is how many
+// processes the reads found that nothing accounts for (-1: a read
+// failed).
+func IdleClear(t Table, own *Own, o Obligation, deadline time.Time) (left int, ok bool) {
+ if !t.Sweeps() {
+ // The runner user is not the runner's alone (Linux outside a
+ // test's scope): its other processes prove nothing.
+ return -1, false
+ }
+ before := map[ID]bool{}
+ for _, id := range o.Before {
+ before[id] = true
+ }
+ uid, self := os.Getuid(), os.Getpid()
+ // Two reads: an identity the first accepted that is another process
+ // by the second (a pid used again) is unaccounted then.
+ for range 2 {
+ list, mine, err := own.Snapshot(deadline, t, nil)
+ if err != nil || !time.Now().Before(deadline) {
+ return -1, false
+ }
+ left = 0
+ for _, q := range list {
+ if q.UID == uid && q.PID != self && !mine[q.ID] && !before[q.ID] {
+ left++
+ }
+ }
+ if left > 0 {
+ return left, false
+ }
+ }
+ return 0, o.gone(t) && time.Now().Before(deadline)
+}
+
+// Clear clears what attempt owes when that is proven over: by a reboot
+// since its turn began, or, for an incomplete turn, by an idle read
+// (IdleClear; the caller holds the Mac's turn). What stays keeps the
+// count of unaccounted processes its last idle read found.
+func (d *Debts) Clear(attempt string, t Table, own *Own, boot Boot, bootErr error, deadline time.Time) error {
+ return d.locked(func() error {
+ all, err := d.load()
+ if err != nil {
+ return err
+ }
+ var keep []Obligation
+ for _, o := range all {
+ switch {
+ case !slices.Contains(o.Markers, attempt):
+ case Rebooted(o.BootID, o.Began, boot, bootErr):
+ continue
+ case o.Incomplete:
+ left, ok := IdleClear(t, own, o, deadline)
+ if ok {
+ continue
+ }
+ o.Left = max(left, 0)
+ }
+ keep = append(keep, o)
+ }
+ if len(keep) == len(all) && slices.EqualFunc(keep, all, func(a, b Obligation) bool { return a.Left == b.Left }) {
+ return nil
+ }
+ return d.save(keep)
+ })
+}
+
+// Owes reports whether attempt owes anything (an unreadable file: yes).
+func (d *Debts) Owes(attempt string) bool {
+ owes := true
+ _ = d.locked(func() error {
+ all, err := d.load()
+ owes = err != nil || slices.ContainsFunc(all, func(o Obligation) bool { return slices.Contains(o.Markers, attempt) })
+ return nil
+ })
+ return owes
+}
+
+// Unproven reports whether an obligation can never be met as it stands
+// (an incomplete turn; an unreadable file says yes), and the largest
+// count of unaccounted processes an idle read found for one.
+func (d *Debts) Unproven() (incomplete bool, left int) {
+ incomplete = true
+ _ = d.locked(func() error {
+ all, err := d.load()
+ if err != nil {
+ return nil
+ }
+ incomplete = false
+ for _, o := range all {
+ if o.Incomplete {
+ incomplete, left = true, max(left, o.Left)
+ }
+ }
+ return nil
+ })
+ return incomplete, left
+}
diff --git a/internal/runner/mac/proc/proc.go b/internal/runner/mac/proc/proc.go
index e51ec533..39449901 100644
--- a/internal/runner/mac/proc/proc.go
+++ b/internal/runner/mac/proc/proc.go
@@ -557,6 +557,13 @@ func (s *Scope) remaining(list []Info, own map[ID]bool) (left, kill []Info) {
// must be gone (none is ever signalled again).
type Obligation struct {
Markers []string `json:"markers"`
+ // Began and BootID are the turn's start and the boot it ran in (a
+ // later boot ends it); Before is the runner user's table then.
+ Began time.Time `json:"began,omitzero"`
+ BootID string `json:"boot_id,omitempty"`
+ Before []ID `json:"before,omitempty"`
+ // Left is how many unaccounted processes the last idle read found.
+ Left int `json:"left,omitempty"`
// Incomplete: the turn's record was never completed, so what it owes
// cannot be known: never met.
Incomplete bool `json:"incomplete,omitempty"`
@@ -582,9 +589,12 @@ func (s *Scope) Owe() Obligation {
// Met reports whether everything o names is gone now.
func (o Obligation) Met(p Table) bool {
- if o.Incomplete {
- return false
- }
+ return !o.Incomplete && o.gone(p)
+}
+
+// gone: every process, group and session o names is gone, for every
+// user (its being incomplete aside).
+func (o Obligation) gone(p Table) bool {
s := NewScope(p, o.Markers, nil)
for _, id := range o.Killed {
s.Killed[id] = true
@@ -597,3 +607,9 @@ func (o Obligation) Met(p Table) bool {
}
return s.Gone()
}
+
+// Boot is one boot of the machine: its identity and when it began.
+type Boot struct {
+ ID string
+ Time time.Time
+}
diff --git a/internal/runner/mac/proc/store.go b/internal/runner/mac/proc/store.go
new file mode 100644
index 00000000..77581f79
--- /dev/null
+++ b/internal/runner/mac/proc/store.go
@@ -0,0 +1,69 @@
+package proc
+
+import (
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "os"
+ "slices"
+ "sync"
+)
+
+// Store keeps one JSON record durably at Path (written beside, synced,
+// renamed over), or in memory when Path is "" (one process: tests).
+type Store struct {
+ Path string
+ mu sync.Mutex
+ mem []byte
+}
+
+// Save keeps v.
+func (s *Store) Save(v any) error {
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ if s.Path != "" {
+ return WriteDurably(s.Path, raw)
+ }
+ s.mu.Lock()
+ s.mem = raw
+ s.mu.Unlock()
+ return nil
+}
+
+// Load reads the record into v; ok is false when there is none. One
+// that cannot be read or decoded is an error.
+func (s *Store) Load(v any) (bool, error) {
+ var raw []byte
+ if s.Path == "" {
+ s.mu.Lock()
+ raw = slices.Clone(s.mem)
+ s.mu.Unlock()
+ } else {
+ var err error
+ if raw, err = os.ReadFile(s.Path); errors.Is(err, fs.ErrNotExist) {
+ return false, nil
+ } else if err != nil {
+ return false, err
+ }
+ }
+ if raw == nil {
+ return false, nil
+ }
+ return true, json.Unmarshal(raw, v)
+}
+
+// Drop removes the record (none is not an error).
+func (s *Store) Drop() error {
+ if s.Path == "" {
+ s.mu.Lock()
+ s.mem = nil
+ s.mu.Unlock()
+ return nil
+ }
+ if err := os.Remove(s.Path); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+}
diff --git a/internal/runner/mac/turns.go b/internal/runner/mac/turns.go
index 0617cde8..9b3cde4f 100644
--- a/internal/runner/mac/turns.go
+++ b/internal/runner/mac/turns.go
@@ -4,15 +4,15 @@ import (
"context"
"crypto/rand"
"encoding/hex"
- "encoding/json"
"errors"
- "io/fs"
"os"
"slices"
"sync"
"time"
+ "amadan.net/oficina/equipo/internal/runner/mac/creds"
"amadan.net/oficina/equipo/internal/runner/mac/proc"
+ "amadan.net/oficina/equipo/internal/wire"
)
// Op is what a turn is for. Every operation that runs repository code,
@@ -73,11 +73,14 @@ type Turns struct {
// beforeWrite runs before each turn record write (tests: a slow or
// failing disk).
beforeWrite func() error
+ // boot reads this boot (creds.BootID, creds.BootTime; tests stand in).
+ boot func() (proc.Boot, error)
// Settle bounds settling an earlier turn (30 s).
Settle time.Duration
// mem is the turn record without a lock file (one process).
- mu sync.Mutex
- mem *turnRecord
+ // records keeps the turn record (lock+".turn"), pends the pending
+ // cleanup (lock+".pending").
+ records, pends *proc.Store
// debts is what unproven turns still owe (lock+".owed").
debts proc.Debts
}
@@ -85,9 +88,9 @@ type Turns struct {
// NewTurns makes the runner's one turn; lock is its file in the state
// dir ("" keeps the turn, and its record, within this process).
func NewTurns(lock string) *Turns {
- t := &Turns{lock: lock, lk: proc.NewLock(lock)}
+ t := &Turns{lock: lock, lk: proc.NewLock(lock), records: &proc.Store{}, pends: &proc.Store{}}
if lock != "" {
- t.debts.Path = lock + ".owed"
+ t.debts.Path, t.records.Path, t.pends.Path = lock+".owed", lock+".turn", lock+".pending"
}
return t
}
@@ -148,6 +151,9 @@ type turnRecord struct {
Killed []ProcID `json:"killed,omitempty"`
// Complete: the stop's final note was written, after every other.
Complete bool `json:"complete,omitempty"`
+ // Began and BootID: when, and in which boot, the turn began.
+ Began time.Time `json:"began,omitzero"`
+ BootID string `json:"boot_id,omitempty"`
}
// Take waits for the turn and begins op: an earlier turn left unsettled
@@ -381,9 +387,10 @@ func (t *Turns) begin(op Op, deadline time.Time) (*Turn, error) {
if err := t.settle(deadline); err != nil {
return nil, err
}
+ b, _ := t.bootNow()
var raw [8]byte
_, _ = rand.Read(raw[:])
- rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: selfID()}
+ rec := turnRecord{ID: hex.EncodeToString(raw[:]), Op: op, Runner: selfID(), Began: time.Now(), BootID: b.ID}
if t.sweep != nil {
if !t.sweep.Sweeps() {
return nil, ErrNoSweep
@@ -415,6 +422,11 @@ func (t *Turns) settle(deadline time.Time) error {
if err != nil || !ok {
return err
}
+ if b, err := t.bootNow(); proc.Rebooted(rec.BootID, rec.Began, b, err) {
+ // Nothing of a turn from an earlier boot runs now: no sweep (its
+ // table is that boot's), nothing owed.
+ return t.dropTurn(rec.ID)
+ }
if rec.Runner != selfID() {
// Another runner process's record: only once it is surely gone.
if alive, known := proc.Alive(t.identities(), rec.Runner); alive || !known {
@@ -448,7 +460,7 @@ func (t *Turns) settle(deadline time.Time) error {
// so its attempts are never proven over (the Machines page says
// so). Nothing of the runner user's is left: the Mac goes on.
o := s.Owe()
- o.Incomplete = true
+ o.Incomplete, o.Began, o.BootID, o.Before = true, rec.Began, rec.BootID, rec.Before
if err := t.debts.Owe(o); err != nil {
return errors.Join(ErrUnsettled, err)
}
@@ -476,58 +488,25 @@ func (t *Turns) unsettledFor(attempt string) bool {
return err != nil || ok && slices.Contains(rec.Markers, attempt)
}
-func (t *Turns) turnFile() string {
- if t.lock == "" {
- return ""
- }
- return t.lock + ".turn"
-}
-
func (t *Turns) saveTurn(rec turnRecord) error {
if t.beforeWrite != nil {
if err := t.beforeWrite(); err != nil {
return err
}
}
- p := t.turnFile()
- if p == "" {
- t.mu.Lock()
- c := rec
- c.Before, c.Markers = slices.Clone(rec.Before), slices.Clone(rec.Markers)
- c.Groups, c.Sessions = rec.Groups.Clone(), rec.Sessions.Clone()
- t.mem = &c
- t.mu.Unlock()
- return nil
- }
- raw, err := json.Marshal(rec)
- if err != nil {
- return err
- }
- return proc.WriteDurably(p, raw)
+ return t.records.Save(rec)
}
func (t *Turns) loadTurn() (turnRecord, bool, error) {
- p := t.turnFile()
- if p == "" {
- t.mu.Lock()
- defer t.mu.Unlock()
- if t.mem == nil {
- return turnRecord{}, false, nil
- }
- return *t.mem, true, nil
- }
- raw, err := os.ReadFile(p)
- if errors.Is(err, fs.ErrNotExist) {
- return turnRecord{}, false, nil
+ var rec turnRecord
+ ok, err := t.records.Load(&rec)
+ if err == nil && ok && rec.ID == "" {
+ err = errors.New("no id")
}
if err != nil {
- return turnRecord{}, false, err
- }
- var rec turnRecord
- if err := json.Unmarshal(raw, &rec); err != nil || rec.ID == "" {
return turnRecord{}, false, errors.Join(ErrUnsettled, errors.New("mac: unreadable turn record"), err)
}
- return rec, true, nil
+ return rec, ok, nil
}
// dropTurn removes the stored record if it is still id's.
@@ -536,16 +515,7 @@ func (t *Turns) dropTurn(id string) error {
if err != nil || !ok || rec.ID != id {
return err
}
- if p := t.turnFile(); p != "" {
- if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
- return err
- }
- return nil
- }
- t.mu.Lock()
- t.mem = nil
- t.mu.Unlock()
- return nil
+ return t.records.Drop()
}
var self struct {
@@ -595,36 +565,26 @@ type pendingRecord struct {
// writePending records r durably. Without a lock file (tests) there is
// nowhere to keep it.
func (t *Turns) writePending(r pendingRecord) error {
- p := t.pending()
- if p == "" {
+ if t.pending() == "" {
return nil
}
- raw, err := json.Marshal(r)
- if err != nil {
- return err
- }
- return proc.WriteDurably(p, raw)
+ return t.pends.Save(r)
}
// readPending is the record an earlier attempt left; ok is false when
// there is none. One that cannot be read is an error: nothing runs
// until a person looks.
func (t *Turns) readPending() (r pendingRecord, ok bool, err error) {
- p := t.pending()
- if p == "" {
+ if t.pending() == "" {
return r, false, nil
}
- raw, err := os.ReadFile(p)
- if errors.Is(err, fs.ErrNotExist) {
- return r, false, nil
+ if ok, err = t.pends.Load(&r); err == nil && ok && (r.Attempt == "" || r.Before == nil) {
+ err = errors.New("incomplete")
}
if err != nil {
- return r, false, err
+ return pendingRecord{}, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err)
}
- if err := json.Unmarshal(raw, &r); err != nil || r.Attempt == "" || r.Before == nil {
- return r, false, errors.Join(ErrUserTemp, errors.New("mac: unreadable pending cleanup"), err)
- }
- return r, true, nil
+ return r, ok, nil
}
// mayFinish: u may finish r. Its owner: the attempt, in the runner
@@ -646,14 +606,40 @@ func (t *Turns) mayFinish(u *Turn, r pendingRecord) bool {
// dropPending removes the record once its cleanup is done.
func (t *Turns) dropPending() error {
- p := t.pending()
- if p == "" {
+ if t.pending() == "" {
return nil
}
- if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) {
- return err
+ return t.pends.Drop()
+}
+
+// clearOwed clears what attempt owes once it is proven over, by a
+// reboot or an idle read (proc.Debts.Clear). It runs only holding u, a
+// live turn of t: no operation can start a process meanwhile.
+func (t *Turns) clearOwed(u *Turn, attempt string) error {
+ if u == nil || u.t != t || HeldTurn(u.Context(context.Background()), t) == nil {
+ return ErrNoTurn
}
- return nil
+ b, err := t.bootNow()
+ return t.debts.Clear(attempt, t.table(), t.owned(), b, err, time.Now().Add(t.settleLimit()))
+}
+
+func (t *Turns) bootNow() (proc.Boot, error) {
+ if t.boot != nil {
+ return t.boot()
+ }
+ return creds.Boot()
+}
+
+// Unproven is the Machines page's code for an attempt whose end is not
+// proven here, and how many unaccounted processes keep it so.
+func (t *Turns) Unproven() (string, int) {
+ switch incomplete, left := t.debts.Unproven(); {
+ case incomplete && left > 0:
+ return wire.UnprovenProcessesLeft, left
+ case incomplete:
+ return wire.UnprovenRecordIncomplete, 0
+ }
+ return "", 0
}
// Incomplete reports whether an attempt's end can never be proven: its
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 229d73a4..0127ef64 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -789,8 +789,8 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) {
caps.Tainted = h.taint.Tainted()
h.credentialCaps(ctx, &caps)
h.eng.compose(&caps)
- if h.turns.Incomplete() && caps.Unproven == "" {
- caps.Unproven = wire.UnprovenRecordIncomplete
+ if code, n := h.turns.Unproven(); code != "" && caps.Unproven == "" {
+ caps.Unproven, caps.UnprovenCount = code, n
}
return caps
}
diff --git a/internal/wire/mac_engineering.go b/internal/wire/mac_engineering.go
index 6883ab16..71599b51 100644
--- a/internal/wire/mac_engineering.go
+++ b/internal/wire/mac_engineering.go
@@ -285,11 +285,11 @@ func WithoutMacEngineering(h *Hello) bool {
// A slice F Mac (it says its Engineering status) says claude only at
// 37: an older instance would take it for a Mac that can run Claude.
macClaude := h.Platform != nil && h.Platform.OS == "darwin" && c.Engineering != nil && slices.Contains(c.Tags, TagClaude)
- if c.Engineering == nil && c.Unproven == "" && !c.ModelHold && c.HoldingItems == nil && c.RunnerUser == "" && !slices.ContainsFunc(c.Probes, isF) && !macClaude {
+ if c.Engineering == nil && c.Unproven == "" && c.UnprovenCount == 0 && !c.ModelHold && c.HoldingItems == nil && c.RunnerUser == "" && !slices.ContainsFunc(c.Probes, isF) && !macClaude {
return inventory
}
out := *c
- out.Engineering, out.Unproven, out.ModelHold, out.HoldingItems, out.RunnerUser = nil, "", false, nil, ""
+ out.Engineering, out.Unproven, out.UnprovenCount, out.ModelHold, out.HoldingItems, out.RunnerUser = nil, "", 0, false, nil, ""
if macClaude {
out.Tags = slices.DeleteFunc(slices.Clone(c.Tags), func(t string) bool { return t == TagClaude })
}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 0460ac2d..b342eec1 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -333,6 +333,9 @@ type Capabilities struct {
// Unproven (ProtocolMacEngineering) is a code for an attempt whose
// end this runner can never prove (UnprovenRecordIncomplete).
Unproven string `json:"unproven,omitempty"`
+ // UnprovenCount is how many processes keep it so
+ // (UnprovenProcessesLeft only); never names, pids or paths.
+ UnprovenCount int `json:"unproven_count,omitempty"`
// ModelHold (ProtocolMacEngineering): a Mac worker holds, or may
// hold, a model credential: an attempt connecting, a connection's
// files, a Keychain item a launch left, or a launch not yet proven
@@ -356,6 +359,13 @@ const UnprovenRecordIncomplete = "record_incomplete"
// its Claude connections closed until it restarts.
const UnprovenCredential = "credential_unproven"
+// MaxUnprovenCount bounds UnprovenCount.
+const MaxUnprovenCount = 100000
+
+// UnprovenProcessesLeft: an idle read found UnprovenCount processes of
+// the runner user that no record accounts for; a restart clears it.
+const UnprovenProcessesLeft = "processes_left"
+
// PreviewHost is a preview host a runner pairs with: its kind (an
// adapter: CARLOS devbox on the tailnet, or Carloku temporary sites) and
// the domain its links live under, "" until known.
@@ -453,7 +463,7 @@ func ValidCapabilities(c Capabilities) error {
if h := c.PreviewHost; h != nil && (!c.Previews || h.Kind != PreviewHostDevbox && h.Kind != PreviewHostCarlokuTemp || h.Domain != "" && (len(h.Domain) > 253 || !previewHostDomain.MatchString(h.Domain))) {
return ErrCapabilities
}
- if h := c.Tools; h != nil && !validToolHealth(*h) || c.Unproven != "" && c.Unproven != UnprovenRecordIncomplete && c.Unproven != UnprovenCredential {
+ if h := c.Tools; h != nil && !validToolHealth(*h) || c.Unproven != "" && c.Unproven != UnprovenRecordIncomplete && c.Unproven != UnprovenCredential && c.Unproven != UnprovenProcessesLeft || (c.UnprovenCount != 0) != (c.Unproven == UnprovenProcessesLeft) || c.UnprovenCount < 0 || c.UnprovenCount > MaxUnprovenCount {
return ErrCapabilities
}
if r := c.Reach; r != nil && !validReach(*r) {
@@ -483,6 +493,11 @@ func checkStrings(v reflect.Value) error {
return ErrCapabilities
}
case reflect.Bool:
+ case reflect.Int:
+ // A count (UnprovenCount): bounded, never negative.
+ if v.Int() < 0 || v.Int() > MaxUnprovenCount {
+ return ErrCapabilities
+ }
case reflect.Pointer:
if !v.IsNil() {
return checkStrings(v.Elem())
diff --git a/internal/wire/unproven_count_test.go b/internal/wire/unproven_count_test.go
new file mode 100644
index 00000000..67539daa
--- /dev/null
+++ b/internal/wire/unproven_count_test.go
@@ -0,0 +1,28 @@
+package wire
+
+import "testing"
+
+// UnprovenCount comes only with UnprovenProcessesLeft, is bounded, and an
+// older instance never sees either.
+func TestUnprovenCount(t *testing.T) {
+ for _, c := range []struct {
+ code string
+ n int
+ ok bool
+ }{
+ {UnprovenProcessesLeft, 3, true},
+ {UnprovenProcessesLeft, 0, false},
+ {UnprovenRecordIncomplete, 3, false},
+ {"", 3, false},
+ {UnprovenProcessesLeft, MaxUnprovenCount + 1, false},
+ {UnprovenProcessesLeft, -1, false},
+ } {
+ if err := ValidCapabilities(Capabilities{Unproven: c.code, UnprovenCount: c.n}); (err == nil) != c.ok {
+ t.Fatalf("%q %d: %v", c.code, c.n, err)
+ }
+ }
+ h := &Hello{Capabilities: &Capabilities{Unproven: UnprovenProcessesLeft, UnprovenCount: 3}}
+ if WithoutMacEngineering(h); h.Capabilities.Unproven != "" || h.Capabilities.UnprovenCount != 0 {
+ t.Fatalf("kept below 37: %+v", h.Capabilities)
+ }
+}