oficina / equipo Public

Mac slice F task 9 fix 2: one deadline, complete records, one discovery

Astra round 2 (#6, #7, #8, #10 partly resolved; new #13, #14), tests
first:
- #7 one deadline covers reads, the final note and its fsync, turn
  settlement, settleRecord and the debt check; Verify has no separate
  budgets
- #8 a record is complete only once the stop's final note succeeds; an
  incomplete record's attempts are never proven over, and the runner
  reports unproven: record_incomplete (protocol 37), worded on the
  instance from pending copy
- #10 the relaunch cutoff is the table's clock just before the first
  signal; exactly one discovery read; later reads only check and
  re-signal the kill set; groups and sessions a target leads are
  obligations; spec 8.8 rewritten
- #13 debts read-modify-writes hold an flock in every runner process
- #14 a failed read voids clearance; a late read clears nothing

Mutations on the final code, all caught: R7a-R14 (this round), F1-F11b
(round 1; F7 redone to compile), M1-M12 (original guards; M9 caught by
the new TestProofWaitsForEveryTarget).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 569cdb515e649f124e43e124fa7b88bc8169a7b5 parent 0feb233
25 files changed, +762 −169
  • .rastrillo/budgets.txt +3 −3
  • docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json +5 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −0
  • docs/superpowers/specs/2026-11-07-equipo-mac-runners.md +49 −16
  • internal/equipo/copy.go +3 −2
  • internal/equipo/mac_view_test.go +11 −0
  • internal/equipo/runners.go +10 −0
  • internal/equipo/setup/runner_models.go +3 −0
  • internal/equipo/templates/runners.html +1 −0
  • internal/runner/mac/fix1_sweep_test.go +5 −5
  • internal/runner/mac/fix2_test.go +258 −0
  • internal/runner/mac/launch.go +14 −11
  • internal/runner/mac/launch_test.go +8 −1
  • internal/runner/mac/proc/debts.go +58 −8
  • internal/runner/mac/proc/lock.go +89 −0
  • internal/runner/mac/proc/proc.go +91 −33
  • internal/runner/mac/proc/proc_darwin.go +3 −0
  • internal/runner/mac/proc/proc_linux.go +14 −0
  • internal/runner/mac/proc/proc_test.go +31 −0
  • internal/runner/mac/procs_test.go +18 −0
  • internal/runner/mac/sweep_test.go +3 −3
  • internal/runner/mac/turns.go +69 −83
  • internal/runner/thin/mac.go +3 −0
  • internal/wire/mac_engineering.go +3 −3
  • internal/wire/runners.go +9 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 9f5b5260..516edda5 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 24000 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe codes; measured 24000.
-size internal/wire 8596 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe codes; measured 8596.
+size internal/equipo 24011 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes; measured 24011.
+size internal/wire 8604 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes; measured 8604.
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).
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 30737 26650 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns; measured 30737/26650.
+size internal/runner/thin 30740 26650 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns; measured 30740/26650.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
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 85ad1ae4..23f6aa6a 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
@@ -78,5 +78,10 @@
"key": "runner.probe_detail.turn_busy",
"where": "Machines page, a Mac's self-checks: a probe's detail when the probe run could not get the Mac's turn (wire.ProbeDetailTurnBusy), beside the verdict Unavailable",
"draft": "The Mac was busy with other work, so this was not checked."
+ },
+ {
+ "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 prove that an earlier step on this Mac stopped completely, so that step stays unfinished."
}
]
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index c8fd86b8..2dc7624f 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -7021,6 +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 project 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 prove that an earlier step on this Mac stopped completely, so that step stays unfinished. | 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 3a91a09d..20bfa229 100644
--- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
+++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
@@ -978,27 +978,49 @@ the same identity and still the runner user's. A group is signalled
whole only while a member read just then is still in it. Another user's
process is never signalled.
-**The re-snapshot and launchd's relaunches.** After the first kill pass
-the runner keeps reading the table until the proof or the deadline. A
-new process joins the kill set. One exception: a process whose parent is
-launchd, whose kernel path (`proc_pidpath`, never `argv[0]`) is under
-`/System` (not `/System/Volumes`), `/usr/libexec` or `/usr/sbin`, and
-which started after the first kill pass began, is taken as launchd
-starting a killed agent again. It is not killed and does not block the
-proof.
+**Three phases.**
+
+1. The first kill pass signals what the first read found. Just before
+ its first signal, the runner reads the table's clock (the clock of the
+ kernel's start times): that moment is the relaunch cutoff.
+2. Discovery is exactly one more read. What it finds new joins the kill
+ set and is signalled. One exception: a process whose parent is
+ launchd, whose kernel path (`proc_pidpath`, never `argv[0]`) is under
+ `/System` (not `/System/Volumes`), `/usr/libexec` or `/usr/sbin`, and
+ which started after the cutoff, is taken as launchd starting a killed
+ agent again. It is not killed and does not block the proof. One that
+ started before the cutoff is killed, even if the first read missed
+ it.
+3. Later reads only check whether the kill set and the obligations are
+ gone. They signal the kill set again (SIGKILL once the grace is over)
+ and never add or spare anything.
+
+Every group and session a kill-set process leads becomes an obligation.
+So a process born into one after discovery (a fork from a dying target)
+keeps the proof waiting, though no read adds it.
**The proof.** Termination is proven only when all of these hold, within
-one absolute 30 s deadline that also bounds every table read (a read
-that returns after it proves nothing):
+one absolute 30 s deadline. The deadline covers every table read, every
+durable note and its fsync, the settling of an earlier turn,
+`settleRecord` and the debt check. A proof is accepted only if the
+deadline has not passed when the last of these returns, and `Verify`
+gives its parts no separate budgets:
- every process in the kill set is gone, matched by pid and start time;
- every recorded group returns ESRCH to `kill(-pgid, 0)`;
- no process of any user is left in a recorded session;
- no marked process remains, and the leader is reaped;
-- everything above is durably on the turn's record.
+- everything above is durably on the turn's record, and the stop's
+ final note marked it complete.
If the turn's record cannot be written, the operation is stopped at once
-and its proof withheld.
+and its proof withheld. A record is complete only once the stop's final
+note, written after every group and session write, has succeeded (a
+durable `complete` mark). 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).
Otherwise the step stays unterminated (no Retry), and its turn's record
stays too. The next turn, in any runner process, settles that record
@@ -1009,6 +1031,12 @@ are left, the Mac may take turns again: those obligations are kept
(`<lock>.owed`), never signalled, and the attempt is not proven over
until they end.
+That release needs a clean read: a read that fails voids any earlier
+clearance, and only a later read in time that shows nothing of the
+runner user's left restores it. Every runner process reads and writes
+`<lock>.owed` only under an flock on `<lock>.owed.lock`, `Verify`
+included.
+
**After a restart.** The new runner settles the dead runner's turn
record first. Then, for each recorded attempt, it kills every process
carrying the marker, and the recorded group only while a marked process,
@@ -1031,10 +1059,15 @@ its limit reports at once but keeps the turn until its gates have
stopped and cleaned up. The credential flag (task 11) is separate: it
holds no turn.
-**The honest limit.** One case is left: a process with a system path
-that is reparented to launchd and starts during the final kill pass
-itself. It cannot be told from a relaunch, so it is spared. Also not
-covered:
+**The honest limit.** Two cases are left:
+
+- a process with a system path, reparented to launchd, that starts
+ after the relaunch cutoff, during the kill pass itself. It cannot be
+ told from a relaunch, so it is spared;
+- a process born after the discovery read that carries no marker and is
+ outside every group and session the attempt made or led.
+
+Also not covered:
- the moment between a fresh read of a process and its signal, in which
a pid could in theory be used again (macOS allocates pids in sequence,
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 26355d4e..86fd3603 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2108,8 +2108,9 @@ var pageCopy = map[string]string{
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"runner.verdict.skipped": "Not run",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
- "runner.verdict.unavailable": "Unavailable",
- "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING
+ "runner.verdict.unavailable": "Unavailable",
+ "runner.unproven.record_incomplete": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished.", // COPY REVIEW PENDING
+ "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"runner.origin": "Equipo address:",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/mac_view_test.go b/internal/equipo/mac_view_test.go
index 13a460d3..2341ead6 100644
--- a/internal/equipo/mac_view_test.go
+++ b/internal/equipo/mac_view_test.go
@@ -83,3 +83,14 @@ func TestProbeDetailCodes(t *testing.T) {
t.Fatalf("a diagnostic changed: %q", got)
}
}
+
+// 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") {
+ t.Fatalf("shown as %q", got)
+ }
+ if unprovenText("") != "" || unprovenText("no_such_code") != "" {
+ t.Fatal("an unknown or empty code said something")
+ }
+}
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go
index dc057a62..4585b0f1 100644
--- a/internal/equipo/runners.go
+++ b/internal/equipo/runners.go
@@ -353,6 +353,7 @@ func runnerReport(tx *gorm.DB, id string) (*setup.RunnerReport, error) {
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)
}
return r, nil
}
@@ -367,6 +368,15 @@ func probeDetail(d string) string {
return d
}
+// unprovenText words a runner's Unproven code; "" for none or one it
+// does not know.
+func unprovenText(code string) string {
+ if code == wire.UnprovenRecordIncomplete {
+ return copyText("runner.unproven.record_incomplete")
+ }
+ return ""
+}
+
// RemoveRunnerNow removes a runner at once, for a lost or compromised
// machine: revoked now, and any step it may still be running is
// quarantined until the task's creator recovers it.
diff --git a/internal/equipo/setup/runner_models.go b/internal/equipo/setup/runner_models.go
index a687e615..a75a73dc 100644
--- a/internal/equipo/setup/runner_models.go
+++ b/internal/equipo/setup/runner_models.go
@@ -30,6 +30,9 @@ type Runner struct {
type RunnerReport struct {
Platform, Sandbox string
Probes []RunnerProbe
+ // Unproven says, in words, why an attempt's end there can never be
+ // proven ("" for none).
+ Unproven string
}
// RunnerProbe is one self-probe: P1 to P7, its verdict and detail.
diff --git a/internal/equipo/templates/runners.html b/internal/equipo/templates/runners.html
index 480892fb..1ef34e14 100644
--- a/internal/equipo/templates/runners.html
+++ b/internal/equipo/templates/runners.html
@@ -20,6 +20,7 @@
<dt>{{copy "runner.fingerprint"}}</dt><dd equipo-mach-key>{{$m.Fingerprint}}</dd>
</dl>
{{if $m.Tainted}}<p equipo-mach-note data-tainted>{{copy "runner.tainted"}}</p>{{end}}
+{{with $m.Report}}{{with .Unproven}}<p equipo-mach-note data-unproven>{{.}}</p>{{end}}{{end}}
{{with $m.Report}}{{if .Probes}}<h4 equipo-mach-sub>{{copy "runner.probes"}}</h4>
<ul equipo-probes>{{range .Probes}}<li data-probe="{{.ID}}" data-verdict="{{.Verdict}}"><span>{{copy (printf "runner.probe.%s" .ID)}}</span> <span equipo-probe-verdict>{{copy (printf "runner.verdict.%s" .Verdict)}}</span>{{with .Detail}} <span equipo-quiet>{{.}}</span>{{end}}</li>{{end}}</ul>{{end}}{{end}}
{{with $m.Record}}
diff --git a/internal/runner/mac/fix1_sweep_test.go b/internal/runner/mac/fix1_sweep_test.go
index 91c7639d..67516ca4 100644
--- a/internal/runner/mac/fix1_sweep_test.go
+++ b/internal/runner/mac/fix1_sweep_test.go
@@ -82,7 +82,7 @@ func TestSweepSparesLaunchdRelaunches(t *testing.T) {
me := os.Getuid()
tb := parseTable(t, turnBegan)
tb.after = func(tb *table, pid int, sig syscall.Signal) {
- if pid == 82200 && tb.procs[82201].PID == 0 {
+ if (pid == 82200 || pid == -82200) && tb.procs[82201].PID == 0 {
tb.procs[82201] = row(82201, 1, 82201, 82201, 99000, me, "")
tb.paths[82201] = "/usr/libexec/trustd"
tb.procs[82300] = row(82300, 1, 82300, 82300, 99001, me, "")
@@ -97,7 +97,7 @@ func TestSweepSparesLaunchdRelaunches(t *testing.T) {
}
sig := tb.signalled()
for _, pid := range []int{82200, 82300} {
- if !slices.Contains(sig, pid) {
+ if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
t.Fatalf("%d (new during the turn) was spared: %v", pid, sig)
}
}
@@ -125,7 +125,7 @@ func TestSweepSparesOrphanedHelperDescendants(t *testing.T) {
})
untouched(t, sig, 51101)
for _, pid := range []int{51100, 51102} {
- if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
+ if tb.has(pid) {
t.Fatalf("%d (a reused helper pid and its child) was spared: %v", pid, sig)
}
}
@@ -271,7 +271,7 @@ func TestSweepRelaunchOnlyAfterTheKillPass(t *testing.T) {
me := os.Getuid()
tb := parseTable(t, turnBegan)
tb.after = func(tb *table, pid int, sig syscall.Signal) {
- if pid == 82500 {
+ if pid == 82500 || pid == -82500 {
delete(tb.hidden, 82400)
}
}
@@ -283,7 +283,7 @@ func TestSweepRelaunchOnlyAfterTheKillPass(t *testing.T) {
if !run.Stop() {
t.Fatalf("not proven: %v", tb.signalled())
}
- if !slices.Contains(tb.signalled(), 82400) || tb.has(82400) {
+ if sig := tb.signalled(); !slices.Contains(sig, 82400) && !slices.Contains(sig, -82400) || tb.has(82400) {
t.Fatalf("a process from before the kill pass was taken for a relaunch: %v", tb.signalled())
}
}
diff --git a/internal/runner/mac/fix2_test.go b/internal/runner/mac/fix2_test.go
new file mode 100644
index 00000000..8be8c29c
--- /dev/null
+++ b/internal/runner/mac/fix2_test.go
@@ -0,0 +1,258 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
+)
+
+// Fix round 2 (Astra round 2) regressions on synthetic tables: rows
+// made up 2026-11-28 in the darwin table's shape (see sweep_test.go).
+
+// stopReads calls fn on each table read the stop makes (the stop asks
+// for markers; the poll does not), with its number.
+func stopReads(tb *table, fn func(tb *table, k int)) {
+ k := 0
+ tb.afterList = func(tb *table, _ int, markers []string) {
+ if len(markers) > 0 {
+ k++
+ fn(tb, k)
+ }
+ }
+}
+
+// #7: the final note is part of the proof: a note that returns after
+// the deadline means no proof.
+func TestProofDeadlineCoversTheFinalNote(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ turns, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
+ defer u.Give()
+ var slow atomic.Bool
+ turns.beforeWrite = func() error {
+ if slow.Load() {
+ time.Sleep(400 * time.Millisecond)
+ }
+ return nil
+ }
+ tb.add(row(94100, 1, 94100, 94100, 5000, me, ""), "/Users/paulequipo/w/a")
+ slow.Store(true)
+ if run.Stop() {
+ t.Fatal("proven though its final note returned after the deadline")
+ }
+}
+
+// #7: Verify has one deadline for settling the turn, the record and the
+// debts: recovery that spends most of it settling the turn has only the
+// rest for the recorded group.
+func TestVerifyHasOneDeadline(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ tb.add(row(94300, 1, 94300, 94300, 900, me, ""), "/Users/paulequipo/w/old")
+ list, _ := tb.List(time.Time{}, nil)
+ var before []ProcID
+ for _, q := range list {
+ before = append(before, q.ID)
+ }
+ tb.add(row(94200, 1, 94200, 94200, 5000, me, ""), "/Users/paulequipo/w/left")
+ tb.mark(&tb.unkillable, 94200)
+ turns := NewTurns("").Sweep(tb)
+ turns.own, turns.Settle = &Own{}, 300*time.Millisecond
+ x := &Executor{Turns: turns, Settle: 300 * time.Millisecond}
+ if err := turns.saveTurn(turnRecord{ID: "dead", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-d"}, Complete: true}); err != nil {
+ t.Fatal(err)
+ }
+ time.AfterFunc(50*time.Millisecond, func() { tb.unmark(&tb.unkillable, 94200) })
+ time.AfterFunc(350*time.Millisecond, func() { tb.remove(94300) })
+ if x.Verify(RecordID(94300, "attempt-d")) {
+ t.Fatal("proven after its one deadline (its recorded group ended at 350 ms)")
+ }
+ if !x.Verify(RecordID(94300, "attempt-d")) {
+ t.Fatal("not proven on a later try once everything ended")
+ }
+}
+
+// #8: 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) {
+ me := os.Getuid()
+ lock := filepath.Join(t.TempDir(), "lock")
+ tb := parseTable(t, turnBegan)
+ turns := NewTurns(lock).Sweep(tb)
+ turns.own, turns.Settle = &Own{}, 200*time.Millisecond
+ u, err := turns.Take(context.Background(), OpEngineering)
+ if err != nil {
+ t.Fatal(err)
+ }
+ x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond}
+ run, err := x.Start(u.Context(context.Background()), Command{Argv: []string{"/bin/true"}}, "attempt-i", func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-run.Exited()
+ var failing atomic.Bool
+ turns.beforeWrite = func() error {
+ if failing.Load() {
+ return errors.New("disk full")
+ }
+ return nil
+ }
+ failing.Store(true)
+ residue := row(95002, 1, 95002, 95001, 7000, 0, "")
+ tb.after = func(tb *table, pid int, sig syscall.Signal) {
+ if pid == 95001 && tb.procs[95002].PID == 0 {
+ tb.procs[95002] = residue
+ tb.paths[95002] = "/usr/bin/login"
+ }
+ }
+ // In the attempt's group, a session of its own: the poll finds it.
+ tb.add(row(95001, 1, run.pgid, 95001, 6001, me, ""), "/Users/paulequipo/w/s")
+ select {
+ case <-run.Aborted():
+ case <-time.After(3 * time.Second):
+ t.Fatal("not stopped when its record could not be written")
+ }
+ if run.Stop() {
+ t.Fatal("proven with its record unwritten")
+ }
+ u.Give()
+ failing.Store(false)
+ next := NewTurns(lock).Sweep(tb)
+ next.own, next.Settle = &Own{}, 200*time.Millisecond
+ nx := &Executor{Turns: next, Settle: 200 * time.Millisecond}
+ v, err := next.Take(context.Background(), OpCheck)
+ if err != nil {
+ t.Fatalf("the restarted runner is blocked: %v", err)
+ }
+ v.Give()
+ if nx.Verify(run.ID()) {
+ t.Fatal("recovery proved an attempt whose record was incomplete")
+ }
+ tb.remove(95002)
+ if nx.Verify(run.ID()) || !next.Incomplete() {
+ t.Fatal("an incomplete record became provable, or the runner does not say so")
+ }
+}
+
+// #10: the relaunch cutoff is the moment of the first kill pass (the
+// table's clock, just before the first signal), not the newest start in
+// that pass's read: a system agent born between that read and the first
+// signal predates the kill pass, and is killed.
+func TestRelaunchCutoffIsTheKillPassStart(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ _, u, _, run := liveTurn(t, tb, &Own{}, time.Second)
+ defer u.Give()
+ tb.add(row(83100, 1, 83100, 83100, 4000, me, ""), "/Users/paulequipo/w/first")
+ stopReads(tb, func(tb *table, k int) {
+ if k == 1 {
+ tb.procs[83200] = row(83200, 1, 83200, 83200, 5050, me, "")
+ tb.paths[83200] = "/usr/libexec/trustd"
+ tb.clock = 5100
+ }
+ })
+ if !run.Stop() {
+ t.Fatalf("not proven: %v", tb.signalled())
+ }
+ if sig := tb.signalled(); !slices.Contains(sig, 83200) && !slices.Contains(sig, -83200) || tb.has(83200) {
+ t.Fatalf("an agent born before the first signal was taken for a relaunch: %v", tb.signalled())
+ }
+}
+
+// #10: discovery is the one read after the first kill pass. Later reads
+// add nothing: a process born after it (here as the leader dies of the
+// SIGKILL after discovery) is not signalled; one born into the group
+// that killed process led keeps the proof waiting, as an obligation.
+func TestDiscoveryIsOneSnapshot(t *testing.T) {
+ me := os.Getuid()
+ for _, c := range []struct {
+ name string
+ late ProcInfo
+ proven bool
+ }{
+ {"unrelated", row(83400, 1, 83400, 83400, 9000, me, ""), true},
+ {"in a killed process's group", row(83600, 1, 83500, 83600, 9000, me, ""), false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ tb := parseTable(t, turnBegan)
+ _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
+ defer u.Give()
+ tb.add(row(83500, 1, 83500, 83500, 4000, me, ""), "/Users/paulequipo/w/lead")
+ // It needs SIGKILL, sent once the grace has passed.
+ tb.mark(&tb.stubborn, 83500)
+ tb.after = func(tb *table, pid int, sig syscall.Signal) {
+ if (pid == 83500 || pid == -83500) && sig == syscall.SIGKILL && tb.procs[c.late.PID].PID == 0 {
+ tb.procs[c.late.PID] = c.late
+ tb.paths[c.late.PID] = "/Users/paulequipo/w/late"
+ }
+ }
+ if got := run.Stop(); got != c.proven {
+ t.Fatalf("proven %v, want %v (signalled %v)", got, c.proven, tb.signalled())
+ }
+ if slices.Contains(tb.signalled(), c.late.PID) {
+ t.Fatalf("a read after discovery added %d: %v", c.late.PID, tb.signalled())
+ }
+ })
+ }
+}
+
+// flaky's List works once and then fails.
+type flaky struct {
+ *table
+ n atomic.Int32
+}
+
+func (f *flaky) List(deadline time.Time, markers []string) ([]ProcInfo, error) {
+ if f.n.Add(1) > 1 {
+ return nil, errors.New("sysctl failed")
+ }
+ return f.table.List(deadline, markers)
+}
+
+// #14: a failed read voids what an earlier read showed: an empty read,
+// then failed reads (a process of the runner user appearing meanwhile)
+// is never a clearance to release the Mac.
+func TestFailedScanVoidsClearance(t *testing.T) {
+ me := os.Getuid()
+ tb := &flaky{table: parseTable(t, turnBegan)}
+ list, _ := tb.table.List(time.Time{}, nil)
+ var before []ProcID
+ for _, q := range list {
+ before = append(before, q.ID)
+ }
+ tb.add(row(96001, 1, 96001, 96001, 7000, 501, ""), "/bin/zsh")
+ tb.table.afterList = func(tb *table, _ int, _ []string) {
+ tb.procs[96100] = row(96100, 1, 96100, 96100, 7100, me, "")
+ tb.paths[96100] = "/Users/paulequipo/w/survivor"
+ }
+ s := newScope(tb, []string{"attempt-f"}, before)
+ s.Groups[96001] = 1
+ if out := s.Settle(&Own{}, time.Now().Add(300*time.Millisecond), 0, func() bool { return true }, nil); out != proc.Left {
+ t.Fatalf("settled %v after failed reads, want left", out)
+ }
+}
+
+// The proof waits for every target, also one that leads no group or
+// session the obligations would hold: the child left by a double fork,
+// its session leader gone, that will not die.
+func TestProofWaitsForEveryTarget(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
+ defer u.Give()
+ tb.add(row(84100, 1, 84000, 84000, 5000, me, ""), "/Users/paulequipo/w/orphan")
+ tb.mark(&tb.unkillable, 84100)
+ if run.Stop() {
+ t.Fatal("proven over with a double-forked child alive")
+ }
+}
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go
index 3af500e6..4d84e56f 100644
--- a/internal/runner/mac/launch.go
+++ b/internal/runner/mac/launch.go
@@ -128,7 +128,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); err != nil {
+ if err := x.finishPending(ctx, turn, time.Now().Add(x.settleLimit())); err != nil {
return nil, err
}
temp, err := openTemp(x.UserTemp, nil)
@@ -372,7 +372,7 @@ func (r *Run) stopWith(grace time.Duration) bool {
deadline := time.Now().Add(r.x.settleLimit())
out := r.scope.Settle(r.own, deadline, grace, reaped, r.adopt)
if r.turn == nil {
- return out == proc.Proven
+ return out == proc.Proven && time.Now().Before(deadline)
}
// Proven only with everything it made durably on record (a restart
// must find the same).
@@ -380,11 +380,12 @@ func (r *Run) stopWith(grace time.Duration) bool {
for id := range r.scope.Killed {
killed = append(killed, id)
}
- err := r.turn.note(r.scope.Groups, r.scope.Sessions, killed...)
+ err := r.turn.finish(r.scope.Groups, r.scope.Sessions, killed)
r.mu.Lock()
r.unwritten = err
r.mu.Unlock()
- if out != proc.Proven || err != nil {
+ // The deadline covers the final note (its write and fsync) too.
+ if out != proc.Proven || err != nil || !time.Now().Before(deadline) {
r.turn.unprovenEnd()
return false
}
@@ -418,7 +419,7 @@ func (r *Run) Finish(ctx context.Context) {
// 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) error {
+func (x *Executor) finishPending(ctx context.Context, turn *Turn, deadline time.Time) error {
r, ok, err := x.Turns.readPending()
if err != nil || !ok {
return err
@@ -426,7 +427,7 @@ func (x *Executor) finishPending(ctx context.Context, turn *Turn) error {
if !x.Turns.mayFinish(turn, r) {
return ErrPendingCleanup
}
- if !x.settleRecord(r.PGID, r.Attempt) {
+ if !x.settleRecord(r.PGID, r.Attempt, deadline) {
// 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"))
}
@@ -485,12 +486,13 @@ func (x *Executor) Verify(id string) bool {
if !ok {
return false
}
+ deadline := time.Now().Add(x.settleLimit())
var held *Turn
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 {
- u, ok := x.Turns.TryTake(OpRecover)
+ u, ok := x.Turns.tryTakeBy(OpRecover, deadline)
if !ok {
return false
}
@@ -499,7 +501,9 @@ func (x *Executor) Verify(id string) bool {
held = u
}
}
- if !x.settleRecord(pgid, attempt) || x.Turns != nil && !x.Turns.debts.Paid(attempt, x.Turns.table()) {
+ // One deadline for the whole proof: settling the turn, the record
+ // and the debts, checked once the last of them has returned.
+ if !x.settleRecord(pgid, attempt, deadline) || x.Turns != nil && !x.Turns.debts.Paid(attempt, x.Turns.table()) || !time.Now().Before(deadline) {
return false
}
if held != nil && x.UserTemp != "" {
@@ -507,7 +511,7 @@ func (x *Executor) Verify(id string) bool {
if err != nil {
return false
}
- if pending && r.Attempt == attempt && x.finishPending(context.Background(), held) != nil {
+ if pending && r.Attempt == attempt && x.finishPending(context.Background(), held, time.Now().Add(x.settleLimit())) != nil {
return false
}
}
@@ -518,9 +522,8 @@ func (x *Executor) Verify(id string) bool {
// while a marked process, read just now, is still in it) and reports
// whether, before one deadline (Settle), the group is gone and nothing
// marked is left. pgid 0: the marker alone settles it.
-func (x *Executor) settleRecord(pgid int, attempt string) bool {
+func (x *Executor) settleRecord(pgid int, attempt string, deadline time.Time) bool {
procs, own := x.procs(), x.own()
- deadline := time.Now().Add(x.settleLimit())
me := os.Getpid()
s := newScope(procs, nil, nil)
for {
diff --git a/internal/runner/mac/launch_test.go b/internal/runner/mac/launch_test.go
index f8ad2b3a..e63429d9 100644
--- a/internal/runner/mac/launch_test.go
+++ b/internal/runner/mac/launch_test.go
@@ -293,7 +293,8 @@ func TestRestartReusedGroupNotKilled(t *testing.T) {
}
left := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/sleep", "60")
scrubbed := r.start(r.env(), "/bin/sleep", "60")
- if err := r.turns.saveTurn(turnRecord{ID: "dead-turn", Op: OpEngineering, Runner: deadID, Sweep: true, Before: ids, Markers: []string{marker}}); err != nil {
+ // Its final note was written (complete) before the runner died.
+ if err := r.turns.saveTurn(turnRecord{ID: "dead-turn", Op: OpEngineering, Runner: deadID, Sweep: true, Before: ids, Markers: []string{marker}, Complete: true}); err != nil {
t.Fatal(err)
}
if r.x.Verify(RecordID(unrelated.Process.Pid, marker)) {
@@ -696,6 +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.
+ 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")
+ }
}
// blind cannot read pid's identity (a sysctl that failed), though the
diff --git a/internal/runner/mac/proc/debts.go b/internal/runner/mac/proc/debts.go
index 60390ca4..91fd65ce 100644
--- a/internal/runner/mac/proc/debts.go
+++ b/internal/runner/mac/proc/debts.go
@@ -7,6 +7,7 @@ import (
"os"
"slices"
"sync"
+ "syscall"
)
// Debts keeps what unproven turns still owe, past their turn records:
@@ -15,27 +16,74 @@ type Debts struct {
Path string
mu sync.Mutex
mem []Obligation
+ // between runs between a read and its write (tests: another
+ // process's write in the gap).
+ between func()
}
// Owe keeps o durably.
func (d *Debts) Owe(o Obligation) error {
+ return d.locked(func() error {
+ all, err := d.load()
+ if err != nil {
+ return err
+ }
+ return d.save(append(all, o))
+ })
+}
+
+// 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()
defer d.mu.Unlock()
- all, err := d.load()
+ if d.Path == "" {
+ return fn()
+ }
+ f, err := os.OpenFile(d.Path+".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
- return d.save(append(all, o))
+ defer f.Close()
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
+ return err
+ }
+ defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ return fn()
+}
+
+// Incomplete reports whether an obligation can never be met (a turn
+// whose record was never completed); an unreadable file says yes.
+func (d *Debts) Incomplete() bool {
+ found := true
+ _ = d.locked(func() error {
+ all, err := d.load()
+ found = err != nil || slices.ContainsFunc(all, func(o Obligation) bool { return o.Incomplete })
+ return nil
+ })
+ return found
}
// Paid reports whether attempt owes nothing now: every obligation naming
// it is met by t (and forgotten). One that cannot be read is unpaid.
func (d *Debts) Paid(attempt string, t Table) bool {
- d.mu.Lock()
- defer d.mu.Unlock()
+ paid := false
+ err := d.locked(func() error {
+ var err error
+ paid, err = d.pay(attempt, t)
+ return err
+ })
+ return err == nil && paid
+}
+
+func (d *Debts) pay(attempt string, t Table) (bool, error) {
all, err := d.load()
if err != nil {
- return false
+ return false, err
+ }
+ if d.between != nil {
+ d.between()
}
var keep []Obligation
paid := true
@@ -47,10 +95,12 @@ func (d *Debts) Paid(attempt string, t Table) bool {
keep, paid = append(keep, o), false
}
}
- if len(keep) != len(all) && d.save(keep) != nil {
- return false
+ if len(keep) != len(all) {
+ if err := d.save(keep); err != nil {
+ return false, err
+ }
}
- return paid
+ return paid, nil
}
func (d *Debts) load() ([]Obligation, error) {
diff --git a/internal/runner/mac/proc/lock.go b/internal/runner/mac/proc/lock.go
new file mode 100644
index 00000000..a3cf11e0
--- /dev/null
+++ b/internal/runner/mac/proc/lock.go
@@ -0,0 +1,89 @@
+package proc
+
+import (
+ "context"
+ "errors"
+ "os"
+ "syscall"
+ "time"
+)
+
+// Lock is held by one holder at a time: across this process's
+// goroutines (a channel) and the runner's processes (an flock on Path;
+// "" keeps it within this process).
+type Lock struct {
+ ch chan struct{}
+ path string
+ f *os.File
+}
+
+// NewLock is a lock on path.
+func NewLock(path string) *Lock { return &Lock{ch: make(chan struct{}, 1), path: path} }
+
+// Acquire waits for the lock until ctx ends.
+func (l *Lock) Acquire(ctx context.Context) error {
+ select {
+ case l.ch <- struct{}{}:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ if l.path == "" {
+ return nil
+ }
+ f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ <-l.ch
+ return err
+ }
+ for {
+ err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
+ if err == nil {
+ l.f = f
+ return nil
+ }
+ if !errors.Is(err, syscall.EWOULDBLOCK) {
+ f.Close()
+ <-l.ch
+ return err
+ }
+ select {
+ case <-ctx.Done():
+ f.Close()
+ <-l.ch
+ return ctx.Err()
+ case <-time.After(250 * time.Millisecond):
+ }
+ }
+}
+
+// TryAcquire takes the lock only if it is free now.
+func (l *Lock) TryAcquire() bool {
+ select {
+ case l.ch <- struct{}{}:
+ default:
+ return false
+ }
+ if l.path == "" {
+ return true
+ }
+ f, err := os.OpenFile(l.path, os.O_CREATE|os.O_RDWR, 0600)
+ if err == nil {
+ if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
+ l.f = f
+ return true
+ }
+ f.Close()
+ }
+ <-l.ch
+ return false
+}
+
+// Release gives the lock back.
+func (l *Lock) Release() {
+ if l.f != nil {
+ _ = syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
+ l.f.Close()
+ l.f = nil
+ }
+ <-l.ch
+}
diff --git a/internal/runner/mac/proc/proc.go b/internal/runner/mac/proc/proc.go
index 52077ee9..4d6ec38d 100644
--- a/internal/runner/mac/proc/proc.go
+++ b/internal/runner/mac/proc/proc.go
@@ -73,6 +73,8 @@ type Table interface {
Sweeps() bool
// Signal sends sig to pid (a negative pid: that group).
Signal(pid int, sig syscall.Signal) error
+ // Now is the time now in the clock of the table's start times.
+ Now() int64
}
// ErrNoSweep refuses a runner-user sweep on a table that may not drive
@@ -248,9 +250,9 @@ type Scope struct {
Killed map[ID]bool
// before is the turn's table at its start; nil: no runner-user sweep.
before map[ID]bool
- // relaunchAfter is the latest start in the table of the first kill
- // pass (0 before it): a launchd child from a system path started
- // later is a relaunch.
+ // relaunchAfter is the table's clock just before the first kill
+ // pass's signals (0 before it): a launchd child from a system path
+ // started later is a relaunch.
relaunchAfter int64
procs Table
}
@@ -422,8 +424,6 @@ func (s *Scope) Gone() bool {
return true
}
-var errLate = errors.New("mac: the table was read after the deadline")
-
// gone: id has ended for sure: no process has its pid (ESRCH), or the
// pid is a later process of ours. EPERM is not gone: it may be the same
// process, now another user's (a setuid program that called setuid).
@@ -449,60 +449,115 @@ const (
Left
)
-// Settle ends the scope (each sees every table it reads): until deadline, it reads the table, signals
-// every target (SIGTERM while within grace of the start, then SIGKILL)
-// and proves the end once there is no target, reaped says the leader is
-// reaped and Gone holds, all before the deadline. The first kill pass
-// fixes relaunchAfter.
+// Settle ends the scope before deadline, in three phases (each sees
+// every table read in time):
+// 1. the first kill pass: the targets of the first read are signalled,
+// the relaunch cutoff taken from the table's clock just before;
+// 2. discovery: exactly one more read, whose new targets join the kill
+// set and are signalled;
+// 3. checks: later reads add and spare nothing; they signal the kill
+// set again (SIGTERM within grace of the start, then SIGKILL) and
+// test the proof.
+//
+// Proven only when a read in time shows nothing of the kill set and no
+// marked process, reaped says the leader is reaped and Gone holds, all
+// before the deadline. Owed only when the last read in time, after any
+// failed one, showed nothing of the runner user's left (a late read
+// clears nothing, though what it shows left counts); else Left.
func (s *Scope) Settle(own *Own, deadline time.Time, grace time.Duration, reaped func() bool, each func([]Info)) Outcome {
start := time.Now()
- // left is what the last read in time showed; read says one came.
- left, read := true, false
+ clear, phase := false, 0
for {
list, mine, err := own.Snapshot(deadline, s.procs, s.markers)
- if err == nil && !time.Now().Before(deadline) {
- // A read that came back too late proves nothing, and says
- // nothing about what is left.
- err = errLate
- }
- if err == nil {
+ // A read that came back too late proves nothing and clears
+ // nothing; what it shows left still counts.
+ late := !time.Now().Before(deadline)
+ if err != nil {
+ clear = false
+ } else {
if each != nil {
each(list)
}
- targets := s.Targets(list, mine)
- left, read = len(targets) > 0, true
- if !left && reaped() && s.Gone() && time.Now().Before(deadline) {
- return Proven
+ var left, kill []Info
+ if phase < 2 {
+ left = s.Targets(list, mine)
+ s.oblige(left)
+ kill = left
+ } else {
+ left, kill = s.remaining(list, mine)
}
- if left && s.relaunchAfter == 0 && s.before != nil {
- for _, q := range list {
- s.relaunchAfter = max(s.relaunchAfter, q.Start)
+ switch {
+ case !late:
+ clear = len(left) == 0
+ if clear && reaped() && s.Gone() && time.Now().Before(deadline) {
+ return Proven
}
+ case len(left) > 0:
+ clear = false
+ }
+ if phase == 0 && s.before != nil {
+ s.relaunchAfter = s.procs.Now()
}
sig := syscall.SIGKILL
if time.Since(start) < grace {
sig = syscall.SIGTERM
}
- s.Kill(targets, sig)
+ s.Kill(kill, sig)
+ phase = min(phase+1, 2)
}
if !time.Now().Before(deadline) {
- if left || !read {
- return Left
+ if clear {
+ return Owed
}
- return Owed
+ return Left
}
time.Sleep(min(100*time.Millisecond, time.Until(deadline)))
}
}
+// oblige makes the groups and sessions targets lead obligations: a
+// process born into one later (a fork from a dying target) keeps the
+// proof waiting, though no later read adds it.
+func (s *Scope) oblige(targets []Info) {
+ for _, q := range targets {
+ if _, ok := s.Groups[q.PGID]; !ok && q.PGID == q.PID {
+ s.Groups[q.PGID] = q.Start
+ }
+ if _, ok := s.Sessions[q.SID]; !ok && q.SID == q.PID {
+ s.Sessions[q.SID] = q.Start
+ }
+ }
+}
+
+// remaining is, in a check read, what keeps the proof from holding: the
+// kill set's processes still listed (signalled again) and marked
+// processes (never added).
+func (s *Scope) remaining(list []Info, own map[ID]bool) (left, kill []Info) {
+ for _, q := range list {
+ if q.UID != s.uid || q.PID == s.self || q.PID <= 1 || own[q.ID] {
+ continue
+ }
+ switch {
+ case s.Killed[q.ID]:
+ left, kill = append(left, q), append(kill, q)
+ case s.marked(q):
+ left = append(left, q)
+ }
+ }
+ return left, kill
+}
+
// Obligation is what an unproven turn still owes, kept past its record:
// the markers it launched and the processes, groups and sessions that
// must be gone (none is ever signalled again).
type Obligation struct {
- Markers []string `json:"markers"`
- Killed []ID `json:"killed,omitempty"`
- Groups Span `json:"groups,omitempty"`
- Sessions Span `json:"sessions,omitempty"`
+ Markers []string `json:"markers"`
+ // Incomplete: the turn's record was never completed, so what it owes
+ // cannot be known: never met.
+ Incomplete bool `json:"incomplete,omitempty"`
+ Killed []ID `json:"killed,omitempty"`
+ Groups Span `json:"groups,omitempty"`
+ Sessions Span `json:"sessions,omitempty"`
}
// Owe is what s still owes.
@@ -522,6 +577,9 @@ 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
+ }
s := NewScope(p, o.Markers, nil)
for _, id := range o.Killed {
s.Killed[id] = true
diff --git a/internal/runner/mac/proc/proc_darwin.go b/internal/runner/mac/proc/proc_darwin.go
index 9766e5f4..8cdd2e95 100644
--- a/internal/runner/mac/proc/proc_darwin.go
+++ b/internal/runner/mac/proc/proc_darwin.go
@@ -147,4 +147,7 @@ func (sysctlProcs) SessionGone(sid int) bool {
func (sysctlProcs) Sweeps() bool { return true }
+// Now is the wall clock in microseconds, as kern.proc's p_starttime.
+func (sysctlProcs) Now() int64 { return time.Now().UnixMicro() }
+
func (sysctlProcs) Signal(pid int, sig syscall.Signal) error { return syscall.Kill(pid, sig) }
diff --git a/internal/runner/mac/proc/proc_linux.go b/internal/runner/mac/proc/proc_linux.go
index a20f9f39..facd6663 100644
--- a/internal/runner/mac/proc/proc_linux.go
+++ b/internal/runner/mac/proc/proc_linux.go
@@ -156,6 +156,20 @@ func (procfs) SessionGone(sid int) bool {
func (p procfs) Sweeps() bool { return p.scope != "" }
+// Now is clock ticks since boot (USER_HZ, 100), as /proc's starttime.
+func (procfs) Now() int64 {
+ raw, err := os.ReadFile("/proc/uptime")
+ if err != nil {
+ return 0
+ }
+ f := strings.Fields(string(raw))
+ if len(f) == 0 {
+ return 0
+ }
+ up, _ := strconv.ParseFloat(f[0], 64)
+ return int64(up * 100)
+}
+
// Signal refuses to signal outside the scope: a scoped table's signals
// reach only the test's own processes (a group only while a member of
// it is the test's).
diff --git a/internal/runner/mac/proc/proc_test.go b/internal/runner/mac/proc/proc_test.go
index 16c6d83f..180eb153 100644
--- a/internal/runner/mac/proc/proc_test.go
+++ b/internal/runner/mac/proc/proc_test.go
@@ -3,6 +3,7 @@ package proc
import (
"os"
"os/exec"
+ "path/filepath"
"sync"
"testing"
"time"
@@ -69,3 +70,33 @@ func TestOwnConcurrentStarts(t *testing.T) {
_ = c.Wait()
}
}
+
+// #13: every read-modify-write of the debts file is serialized across
+// processes: another instance's obligation written in the gap of a
+// Paid is never lost.
+func TestDebtsSerializedAcrossInstances(t *testing.T) {
+ p := filepath.Join(t.TempDir(), "owed")
+ a, b := &Debts{Path: p}, &Debts{Path: p}
+ if err := a.Owe(Obligation{Markers: []string{"attempt-a"}}); err != nil {
+ t.Fatal(err)
+ }
+ me, ok := Platform.Lookup(os.Getpid())
+ if !ok {
+ t.Fatal("no identity")
+ }
+ done := make(chan error, 1)
+ a.between = func() {
+ go func() { done <- b.Owe(Obligation{Markers: []string{"attempt-b"}, Killed: []ID{me.ID}}) }()
+ time.Sleep(200 * time.Millisecond)
+ }
+ if !a.Paid("attempt-a", Platform) {
+ t.Fatal("a met obligation not paid")
+ }
+ a.between = nil
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if b.Paid("attempt-b", Platform) {
+ t.Fatal("another instance's obligation was lost")
+ }
+}
diff --git a/internal/runner/mac/procs_test.go b/internal/runner/mac/procs_test.go
index f3f08625..9463fdf0 100644
--- a/internal/runner/mac/procs_test.go
+++ b/internal/runner/mac/procs_test.go
@@ -72,6 +72,20 @@ type table struct {
after func(tb *table, pid int, sig syscall.Signal)
// hidden rows are left out of List (a read that missed them).
hidden map[int]bool
+ // clock is Now (10000 when 0); afterList runs (lock held) after each
+ // List, with how many lists there have been.
+ clock int64
+ lists int
+ afterList func(tb *table, n int, markers []string)
+}
+
+func (tb *table) Now() int64 {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ if tb.clock == 0 {
+ return 10000
+ }
+ return tb.clock
}
type sent struct {
@@ -135,6 +149,10 @@ func (tb *table) List(_ time.Time, markers []string) ([]ProcInfo, error) {
out = append(out, q)
}
slices.SortFunc(out, func(a, b ProcInfo) int { return a.PID - b.PID })
+ tb.lists++
+ if tb.afterList != nil {
+ tb.afterList(tb, tb.lists, markers)
+ }
return out, nil
}
diff --git a/internal/runner/mac/sweep_test.go b/internal/runner/mac/sweep_test.go
index db074c61..af9fc944 100644
--- a/internal/runner/mac/sweep_test.go
+++ b/internal/runner/mac/sweep_test.go
@@ -43,7 +43,7 @@ func sweepTurn(t *testing.T, tb *table, own *Own, during func(*Turn)) []int {
during(u)
u.unprovenEnd()
u.Give()
- _ = turns.settle()
+ _ = turns.settle(time.Now().Add(turns.settleLimit()))
return tb.signalled()
}
@@ -71,7 +71,7 @@ func TestSweepSparesOwnByIdentityNotName(t *testing.T) {
}
}
for _, pid := range []int{50200, 50300} {
- if !slices.Contains(sig, pid) {
+ if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
t.Fatalf("%d (not the runner's, whatever its name) was spared: %v", pid, sig)
}
}
@@ -82,7 +82,7 @@ func TestSweepSparesOwnByIdentityNotName(t *testing.T) {
own.Add(ProcID{PID: 50100, Start: 2000})
tb.add(row(50100, 1, 50100, 50100, 2500, me, ""), "/usr/bin/git")
})
- if !slices.Contains(sig, 50100) {
+ if !slices.Contains(sig, 50100) && !slices.Contains(sig, -50100) {
t.Fatalf("a reused helper pid was spared: %v", sig)
}
}
diff --git a/internal/runner/mac/turns.go b/internal/runner/mac/turns.go
index 19faa38a..1840ce34 100644
--- a/internal/runner/mac/turns.go
+++ b/internal/runner/mac/turns.go
@@ -10,7 +10,6 @@ import (
"os"
"slices"
"sync"
- "syscall"
"time"
"amadan.net/oficina/equipo/internal/runner/mac/proc"
@@ -61,9 +60,8 @@ var ErrPendingCleanup = errors.New("mac: another attempt's cleanup is pending")
// done, owned by the turn that wrote it: only that attempt (its run,
// or its proof later in the same runner) or a restart may finish it.
type Turns struct {
- ch chan struct{}
lock string
- f *os.File
+ lk *proc.Lock
// sweep is the table every turn sweeps the runner user with at its
// end (MachineProcs on a Mac); nil: no runner-user sweep.
sweep Procs
@@ -72,6 +70,9 @@ type Turns struct {
// ids reads runner processes' identities (the platform's table;
// tests stand in).
ids Procs
+ // beforeWrite runs before each turn record write (tests: a slow or
+ // failing disk).
+ beforeWrite func() error
// Settle bounds settling an earlier turn (30 s).
Settle time.Duration
// mem is the turn record without a lock file (one process).
@@ -84,7 +85,7 @@ 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{ch: make(chan struct{}, 1), lock: lock}
+ t := &Turns{lock: lock, lk: proc.NewLock(lock)}
if lock != "" {
t.debts.Path = lock + ".owed"
}
@@ -141,6 +142,8 @@ type turnRecord struct {
Sessions span `json:"sessions,omitempty"`
// Killed is what the turn's stops signalled: each must be gone.
Killed []ProcID `json:"killed,omitempty"`
+ // Complete: the stop's final note was written, after every other.
+ Complete bool `json:"complete,omitempty"`
}
// Take waits for the turn and begins op: an earlier turn left unsettled
@@ -148,26 +151,38 @@ type turnRecord struct {
// table is read for the sweep, and the record is written before Take
// returns. Give it back with Give.
func (t *Turns) Take(ctx context.Context, op Op) (*Turn, error) {
- if err := t.acquire(ctx); err != nil {
+ if err := t.lk.Acquire(ctx); err != nil {
return nil, err
}
- u, err := t.begin(op)
+ u, err := t.begin(op, time.Now().Add(t.settleLimit()))
if err != nil {
- t.release()
+ t.lk.Release()
return nil, err
}
return u, nil
}
+func (t *Turns) settleLimit() time.Duration {
+ if t.Settle > 0 {
+ return t.Settle
+ }
+ return 30 * time.Second
+}
+
// TryTake takes the turn for op only if it is free now (in this process
// and the others) and begins; ok is false otherwise.
func (t *Turns) TryTake(op Op) (*Turn, bool) {
- if !t.tryAcquire() {
+ return t.tryTakeBy(op, time.Now().Add(t.settleLimit()))
+}
+
+// tryTakeBy is TryTake settling an earlier turn by deadline.
+func (t *Turns) tryTakeBy(op Op, deadline time.Time) (*Turn, bool) {
+ if !t.lk.TryAcquire() {
return nil, false
}
- u, err := t.begin(op)
+ u, err := t.begin(op, deadline)
if err != nil {
- t.release()
+ t.lk.Release()
return nil, false
}
return u, true
@@ -227,7 +242,7 @@ func (u *Turn) Give() {
if !keep {
_ = u.t.dropTurn(u.ID)
}
- u.t.release()
+ u.t.lk.Release()
})
}
@@ -249,9 +264,28 @@ func (u *Turn) launch(marker string) error {
if !slices.Contains(u.rec.Markers, marker) {
u.rec.Markers = append(u.rec.Markers, marker)
}
+ // Incomplete again until this launch's stop writes its final note.
+ u.rec.Complete = false
return u.t.saveTurn(u.rec)
}
+// finish is a stop's final note: everything it made, with the record
+// marked complete, written whatever grew.
+func (u *Turn) finish(groups, sessions span, killed []ProcID) error {
+ if err := u.note(groups, sessions, killed...); err != nil {
+ return err
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ rec := u.rec
+ rec.Complete = true
+ if err := u.t.saveTurn(rec); err != nil {
+ return err
+ }
+ u.rec = rec
+ return nil
+}
+
// note adds groups and sessions an attempt made to the record (best
// effort: the record before the start has the marker and the table).
func (u *Turn) note(groups, sessions span, killed ...ProcID) error {
@@ -316,8 +350,8 @@ func (u *Turn) adopt(attempt string) {
u.mu.Unlock()
}
-func (t *Turns) begin(op Op) (*Turn, error) {
- if err := t.settle(); err != nil {
+func (t *Turns) begin(op Op, deadline time.Time) (*Turn, error) {
+ if err := t.settle(deadline); err != nil {
return nil, err
}
var raw [8]byte
@@ -349,7 +383,7 @@ func (t *Turns) begin(op Op) (*Turn, error) {
// this runner's own and launchd's system agents) killed, checked again
// before each signal, until none is left within Settle. A record of
// another live runner process is never settled from here.
-func (t *Turns) settle() error {
+func (t *Turns) settle(deadline time.Time) error {
rec, ok, err := t.loadTurn()
if err != nil || !ok {
return err
@@ -381,11 +415,19 @@ func (t *Turns) settle() error {
for _, id := range rec.Killed {
s.Killed[id] = true
}
- limit := t.Settle
- if limit <= 0 {
- limit = 30 * time.Second
+ out := s.Settle(t.owned(), deadline, 0, func() bool { return true }, nil)
+ if out != proc.Left && !rec.Complete && len(rec.Markers) > 0 {
+ // Its final note never came: what it left is not all on record,
+ // 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
+ if err := t.debts.Owe(o); err != nil {
+ return errors.Join(ErrUnsettled, err)
+ }
+ return t.dropTurn(rec.ID)
}
- switch s.Settle(t.owned(), time.Now().Add(limit), 0, func() bool { return true }, nil) {
+ switch out {
case proc.Proven:
return t.dropTurn(rec.ID)
case proc.Owed:
@@ -407,71 +449,6 @@ func (t *Turns) unsettledFor(attempt string) bool {
return err != nil || ok && slices.Contains(rec.Markers, attempt)
}
-func (t *Turns) acquire(ctx context.Context) error {
- select {
- case t.ch <- struct{}{}:
- case <-ctx.Done():
- return ctx.Err()
- }
- if t.lock == "" {
- return nil
- }
- f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
- if err != nil {
- <-t.ch
- return err
- }
- for {
- err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
- if err == nil {
- t.f = f
- return nil
- }
- if !errors.Is(err, syscall.EWOULDBLOCK) {
- f.Close()
- <-t.ch
- return err
- }
- select {
- case <-ctx.Done():
- f.Close()
- <-t.ch
- return ctx.Err()
- case <-time.After(250 * time.Millisecond):
- }
- }
-}
-
-func (t *Turns) tryAcquire() bool {
- select {
- case t.ch <- struct{}{}:
- default:
- return false
- }
- if t.lock == "" {
- return true
- }
- f, err := os.OpenFile(t.lock, os.O_CREATE|os.O_RDWR, 0600)
- if err == nil {
- if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err == nil {
- t.f = f
- return true
- }
- f.Close()
- }
- <-t.ch
- return false
-}
-
-func (t *Turns) release() {
- if t.f != nil {
- _ = syscall.Flock(int(t.f.Fd()), syscall.LOCK_UN)
- t.f.Close()
- t.f = nil
- }
- <-t.ch
-}
-
func (t *Turns) turnFile() string {
if t.lock == "" {
return ""
@@ -480,6 +457,11 @@ func (t *Turns) turnFile() string {
}
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()
@@ -647,6 +629,10 @@ func (t *Turns) dropPending() error {
return nil
}
+// Incomplete reports whether an attempt's end can never be proven: its
+// turn's record was not complete (the Machines page says so).
+func (t *Turns) Incomplete() bool { return t.debts.Incomplete() }
+
// Pending reports whether an attempt's cleanup is still to be done
// (the warm waits for it: that attempt's end is not proven yet).
func (t *Turns) Pending() bool {
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 18462a8b..bdd48665 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -753,6 +753,9 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) {
caps.Probes = probes
}
caps.Tainted = h.taint.Tainted()
+ if h.turns.Incomplete() {
+ caps.Unproven = wire.UnprovenRecordIncomplete
+ }
return caps
}
return h, nil
diff --git a/internal/wire/mac_engineering.go b/internal/wire/mac_engineering.go
index 29015ab4..39251bf5 100644
--- a/internal/wire/mac_engineering.go
+++ b/internal/wire/mac_engineering.go
@@ -253,7 +253,7 @@ const (
NeedsMacUpdate = "mac_update"
)
-// WithoutMacEngineering drops a hello's Engineering status and F probes
+// WithoutMacEngineering drops a hello's Engineering status, Unproven and F probes
// (in new values; the caller's are untouched). The runner's first hello
// on a connection goes out before the welcome names the protocol, and an
// older instance's ValidCapabilities refuses an F probe; the runner sends
@@ -264,11 +264,11 @@ func WithoutMacEngineering(h *Hello) bool {
return false
}
isF := func(p Probe) bool { _, ok := engineeringProbeSuccess[p.ID]; return ok }
- if c.Engineering == nil && !slices.ContainsFunc(c.Probes, isF) {
+ if c.Engineering == nil && c.Unproven == "" && !slices.ContainsFunc(c.Probes, isF) {
return false
}
out := *c
- out.Engineering = nil
+ out.Engineering, out.Unproven = nil, ""
if slices.ContainsFunc(c.Probes, isF) {
out.Probes = slices.DeleteFunc(slices.Clone(c.Probes), isF)
}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index fe573202..1d35a45f 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -328,8 +328,16 @@ type Capabilities struct {
// whether it can take Engineering. Withheld until the welcome says 37,
// with the F probes (WithoutMacEngineering).
Engineering *EngineeringStatus `json:"engineering,omitempty"`
+ // Unproven (ProtocolMacEngineering) is a code for an attempt whose
+ // end this runner can never prove (UnprovenRecordIncomplete).
+ Unproven string `json:"unproven,omitempty"`
}
+// UnprovenRecordIncomplete: an attempt's turn record was not complete
+// (its final write failed, or the runner stopped first), so its end is
+// never proven.
+const UnprovenRecordIncomplete = "record_incomplete"
+
// 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.
@@ -427,7 +435,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) {
+ if h := c.Tools; h != nil && !validToolHealth(*h) || c.Unproven != "" && c.Unproven != UnprovenRecordIncomplete {
return ErrCapabilities
}
if r := c.Reach; r != nil && !validReach(*r) {