oficina / equipo Public

Mac slice F task 9 fix 1: kill set by identity, no path exemption

Astra round 1 (1 Critical, 10 Important, 1 Minor), tests first:
- a probe run reports at its limit but holds the turn until it ends
- the worker's git starts as the runner's own (StartOwn)
- helper descendants stay own by identity after the helper exits
- own registrations under their own lock (race-tested)
- a group is signalled only with fresh membership
- proof needs the kill set, recorded groups and sessions gone; what
  another user holds is owed (<lock>.owed), never signalled, and blocks
  only that attempt's proof
- one absolute deadline: a late table read proves nothing
- an unwritable turn record stops the operation and withholds proof
- an unreadable owner identity is not a restart
- controller ruling: no exemption by path; launchd relaunches from a
  system path after the first kill pass are spared; spec 8.8 rewritten
- the probe's busy detail is a code worded from copy.go (pending)

Fail-first evidence for the original guards of 4cc9a164 (break, watch
the test fail, restore), on the fixed code:
- M1 restart proof without group check: RestartUnmarkedSurvivor...
- M1b live proof without group check: StopWaitsForEveryGroupItMade
- M2/M2b marker not first: EngineeringLaunchRecordsMarkerThenGroup
- M3 token check outside Turns: TurnsCoverEveryTokenOperation
- M4 another turn clears a cleanup: CleanupOwnedByItsTurn
- M5/M5b own by name or pid only: SweepSparesOwnByIdentityNotName
- M6/M6b/M7b no re-check before signals: SweepRechecksIdentity...
- M7 other users targeted: SweepNeverTouchesOtherUsers
- M8b no runner-user sweep: SweepCatchesDoubleForkToLaunchd
- M8c /System/Volumes as system: TestSystemPath
- M9/M9b/M9c proof or settle ignores leftovers: ProofOnlyWhen...
- M10/M11 probe run or gate without a turn: TurnsCoverEvery...
- M12 Verify skips settling: RestartReusedGroupNotKilled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 0feb233e9638b67ba93c62e1cbb0c5646e5f3073 parent 4cc9a16
24 files changed, +1,397 −358
  • .rastrillo/budgets.txt +4 −4
  • 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 +85 −76
  • internal/equipo/copy.go +2 −1
  • internal/equipo/mac_view_test.go +11 −0
  • internal/equipo/runners.go +11 −1
  • internal/runner/mac/fix1_sweep_test.go +289 −0
  • internal/runner/mac/gate.go +4 −0
  • internal/runner/mac/launch.go +87 −75
  • internal/runner/mac/launch_test.go +96 −3
  • internal/runner/mac/probe.go +7 −2
  • internal/runner/mac/probe_test.go +53 −0
  • internal/runner/mac/proc/debts.go +118 −0
  • internal/runner/mac/proc/proc.go +276 −102
  • internal/runner/mac/proc/proc_darwin.go +30 −2
  • internal/runner/mac/proc/proc_linux.go +25 −2
  • internal/runner/mac/proc/proc_test.go +41 −4
  • internal/runner/mac/procs_test.go +72 −5
  • internal/runner/mac/sweep_test.go +16 −16
  • internal/runner/mac/turns.go +70 −62
  • internal/runner/thin/mac_sweep_linux_test.go +74 −0
  • internal/runner/thin/worker.go +16 −3
  • internal/wire/runners.go +4 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index e886e136..9f5b5260 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 23989 - Preview grants, retry/timeline, no-access merges, kept work, check-db copy, notification actions, places page and its superseded card, GitHub owner routes, Mac waits; measured 23989.
-size internal/wire 8592 - Protocol 31 facts, 32 unfinished work, task evidence, CI units, notification inputs, 33 Assistant files, 34 places, 35 diffs, Mac waits, 37 Mac Engineering; measured 8592.
+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/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,9 +38,9 @@ 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 30724 26576 Protocol 31 facts, 35 diffs, merge credential, publication guards, kept work, CI units, places publish, token scans, Mac pin, paths, bases, endpoint, Mac turns; measured 30724/26576.
+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.
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 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing.
+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).
time internal/headless 780s End-to-end scenarios in two environments (attachments, relays, restarts, empty repos) run serially; 780s covers loaded CI.
perf GET /api/v1/turns/{id} skip Thin v1 person API: bearer-only JSON for devices, not a browser screen.
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 d1065327..85ad1ae4 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
@@ -73,5 +73,10 @@
"key": "work.reason.workspace_too_large",
"where": "Step stop reason: a Mac Engineering attempt's commits were too large to relay to the Mac (Needs you: Try again)",
"draft": "the project is too large to send to the Mac"
+ },
+ {
+ "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."
}
]
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 35707585..c8fd86b8 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -7020,6 +7020,7 @@ records remain unchanged.
| `work.reason.base_unavailable` | the main runner couldn’t get the version of the project to start from | Copy specialist | COPY REVIEW PENDING |
| `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 |
## 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 8879ca03..3a91a09d 100644
--- a/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
+++ b/docs/superpowers/specs/2026-11-07-equipo-mac-runners.md
@@ -927,9 +927,10 @@ build's fake worker and fake CLI.
### 8.8 Addendum to §5, 2026-11-28: finding what an attempt left
Written for plan task 9, from task 1's findings
-(`docs/superpowers/plans/MAC-SLICE-F-TASK1-FINDINGS.md`, R4 and S5) and
-the sweep the coordinating session approved on 2026-11-28. Where it
-disagrees with §5, this section is current.
+(`docs/superpowers/plans/MAC-SLICE-F-TASK1-FINDINGS.md`, R4 and S5), the
+sweep the coordinating session approved on 2026-11-28, and the
+controller's stricter ruling after review round 1 (no exemption by
+path). Where it disagrees with §5, this section is current.
**What task 1 found.**
@@ -946,95 +947,103 @@ disagrees with §5, this section is current.
Bash commands are made of. A sandboxed `sleep 1000 &` would outlive a
cancel, unseen.
-**The sweep.** Every process is named by its identity: its pid and the
-kernel's start time (microseconds, from `kern.proc`). A pid used again
-later is another identity. Nothing is matched by name. Three nets:
-
-- (a) While the operation runs, the runner reads the process table
- (`kern.proc.ruid` for the runner user, `getsid` for sessions) about
- every 250 ms. It records every process under the operation's leader,
- and every group and session those processes make, on the operation's
- scope and on the turn's durable record.
-- (b) When a turn begins, the runner records the identities of every
- process the runner user has. At the operation's end, every process of
- the runner user that was not there then is the operation's. Two
- exceptions:
- - the runner itself, and every helper it started for itself (capability
- queries, `ps`, `caffeinate`, git, gitleaks, packing), registered by
- identity when started (`mac.StartOwn`), and what those helpers start;
- - launchd's system agents: parent pid 1 and an executable under
- `/System` (not `/System/Volumes`) or `/usr/libexec`. The path is the
- kernel's (`proc_pidpath`, the file it runs), never `argv[0]`, which a
- process can set.
-
- A process in a group or session the operation made, or one carrying
- its marker, is the operation's whatever its parent or path.
-- (c) The marker, wherever the kernel shows it, as before.
+**Identity.** Every process is named by its pid and the kernel's start
+time (microseconds, from `kern.proc`). A pid used again later is another
+identity. Nothing is matched by name, and nothing is spared by path.
+
+**The kill set.** At an operation's end, these are killed:
+
+- (a) what the runner saw of the operation while it ran: the processes
+ under its leader, read about every 250 ms (`kern.proc.ruid` and
+ `getsid`), and every process in a group or session they made;
+- (b) every process of the runner user that started after the turn
+ began (it is not in the table read when the turn began), whatever its
+ parent or path. That includes launchd-parented processes under
+ `/System`, `/usr/libexec` or `/usr/sbin` started during the turn: they
+ are per-user on-demand agents of a dedicated user, and launchd starts
+ them again when they are next needed;
+- (c) every process carrying the marker, wherever the kernel shows it.
+
+The only processes never in it are the runner itself and the helpers it
+registered for itself (`mac.StartOwn`: capability queries, `ps`,
+`caffeinate`, the worker's git, later gitleaks and packing), by identity,
+together with their descendants seen while the helper lived. A
+descendant stays the runner's own after its helper exits; a process that
+later has a helper's pid is not.
**The stop.** Close stdin and wait for a graceful end. Then send SIGTERM
-to everything in (a), (b) and (c), wait the 10 s grace, and send
-SIGKILL. Before each signal the runner reads that process again and
-signals it only if it is the same identity and still the runner user's.
-A group is signalled whole only while a re-checked member is in it (a
-group id cannot be used again while it has a member). Another user's
-process is never a target. Then the user-temp protocol, as before:
-`simctl shutdown all`, then the cleanup of what the attempt created.
-
-**The proof.** Termination is proven only when, within 30 s of the
-stop's start, all of these hold:
-
-- nothing from (a), (b) or (c) remains;
-- the leader is reaped;
-- every group the operation made returns ESRCH to `kill(-pgid, 0)`. A
- group id now held by someone else keeps the proof waiting; it is never
- killed.
-
-Otherwise the step stays unterminated (no Retry). Its turn's record
+to the kill set, wait the 10 s grace, and send SIGKILL. Before each
+signal the runner reads that process again, and signals it only if it is
+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.
+
+**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):
+
+- 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.
+
+If the turn's record cannot be written, the operation is stopped at once
+and its proof withheld.
+
+Otherwise the step stays unterminated (no Retry), and its turn's record
stays too. The next turn, in any runner process, settles that record
-before it begins: it applies the same sweep with the earlier turn's
-"before" table. If anything is still left, the next turn does not begin.
+before it begins, with the same kill set and the earlier turn's "before"
+table. If a process of the runner user is still left, the next turn does
+not begin. If only processes, groups or sessions another user now holds
+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.
**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
-is in it. A recorded group that is alive with no marked process in it is
-either the attempt's child that scrubbed its environment or the group id
-used again by someone else. It is not killed, and the attempt is not
-proven over until the group is gone. A user-temp cleanup left pending
-belongs to the attempt, in the runner process that wrote it. Only that
-attempt (its run, or its later proof) or a restart may finish it.
+carrying the marker, and the recorded group only while a marked process,
+read just then, is in it. A recorded group that is alive with no marked
+process in it is either the attempt's child that scrubbed its
+environment or the group id used again by someone else. It is not
+killed, and the attempt is not proven over until the group is gone.
+
+A user-temp cleanup left pending belongs to the attempt, in the runner
+process that wrote it. Only that attempt (its run, or its later proof)
+or a restart may finish it. A restart is recognised only when the writer
+is surely gone: an identity that cannot be read is not a dead one.
**One turn per operation.** `mac.Turns` is taken for each operation's
life and no longer: a check, an Engineering attempt, an ask, a probe run
(P1 to P7 as one turn; F1 to F7 likewise), a token check, a sign-in pty
and a token store. What the operation starts itself belongs to it. Every
-Mac launch refuses to start outside a held turn. The credential flag
-(task 11) is separate: it holds no turn.
-
-**The honest limit, narrowed.** The sweep cannot tell a process launchd
-starts on the attempt's behalf from a system path from a system agent.
-Precisely, it spares any process that meets all of these:
-
-- its parent is launchd;
-- its kernel path is under `/System` or `/usr/libexec`;
-- it never showed in the attempt's tree, groups or sessions while the
- table was read, and shows no marker.
+Mac launch refuses to start outside a held turn. A probe run that reaches
+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.
-That includes a step that double-forks between two reads, starts a
-session of its own, and runs a system binary (a script interpreter under
-`/System`, for example). Such a process still runs under the attempt's
-Seatbelt profile, which it inherited. Also not covered:
+**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:
-- a process that changes its real uid (a setuid program that calls
- `setuid`), which leaves the runner user's table;
- 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,
so this needs a full wrap of the pid space within that moment);
-- after a restart, a group the attempt made whose members all changed
- uid (the live proof sees it, the restart does not).
+- a process that changes its real uid leaves the runner user's table.
+ The proof still waits for it while it is in the kill set or in a
+ recorded group or session.
Since the runner user is dedicated and turns are serialized, the sweep
also ends anything else of the runner user's that started during the
-turn: a person signed in as that user, or launchd agents outside
-`/System` and `/usr/libexec` (such as `cfprefsd` in `/usr/sbin`), which
-launchd starts again on demand.
+turn: a person signed in as that user, or launchd agents (which launchd
+starts again on demand).
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 128cf316..26355d4e 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -2108,7 +2108,8 @@ 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.verdict.unavailable": "Unavailable",
+ "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 a11f4c73..13a460d3 100644
--- a/internal/equipo/mac_view_test.go
+++ b/internal/equipo/mac_view_test.go
@@ -72,3 +72,14 @@ func TestInstallScript(t *testing.T) {
}
}
}
+
+// A probe detail that is a code is worded here (copy.go); any other
+// detail is the runner's own diagnostic, shown as it came.
+func TestProbeDetailCodes(t *testing.T) {
+ if got := probeDetail(wire.ProbeDetailTurnBusy); got == wire.ProbeDetailTurnBusy || got != copyText("runner.probe_detail.turn_busy") || got == "" {
+ t.Fatalf("turn_busy shown as %q", got)
+ }
+ if got := probeDetail("srt 0.0.81"); got != "srt 0.0.81" {
+ t.Fatalf("a diagnostic changed: %q", got)
+ }
+}
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go
index dac03a12..dc057a62 100644
--- a/internal/equipo/runners.go
+++ b/internal/equipo/runners.go
@@ -351,12 +351,22 @@ func runnerReport(tx *gorm.DB, id string) (*setup.RunnerReport, error) {
r := &setup.RunnerReport{Platform: h.Platform.OS + "/" + h.Platform.Arch, Sandbox: h.Sandbox}
if h.Capabilities != nil && wire.ValidCapabilities(*h.Capabilities) == nil {
for _, p := range h.Capabilities.Probes {
- r.Probes = append(r.Probes, setup.RunnerProbe{ID: p.ID, Verdict: p.Verdict, Detail: p.Detail})
+ r.Probes = append(r.Probes, setup.RunnerProbe{ID: p.ID, Verdict: p.Verdict, Detail: probeDetail(p.Detail)})
}
}
return r, nil
}
+// probeDetail is a probe's detail as the Machines page shows it: a
+// code the runner sends instead of words (wire.ProbeDetailTurnBusy) is
+// worded here; any other detail is the runner's diagnostic, as it came.
+func probeDetail(d string) string {
+ if d == wire.ProbeDetailTurnBusy {
+ return copyText("runner.probe_detail.turn_busy")
+ }
+ return d
+}
+
// 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/runner/mac/fix1_sweep_test.go b/internal/runner/mac/fix1_sweep_test.go
new file mode 100644
index 00000000..91c7639d
--- /dev/null
+++ b/internal/runner/mac/fix1_sweep_test.go
@@ -0,0 +1,289 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "os"
+ "slices"
+ "sync/atomic"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// Fix round 1 (Astra round 1) regressions on synthetic tables: rows
+// made up 2026-11-28 in the darwin table's shape (see sweep_test.go).
+
+// liveTurn begins a sweeping turn on tb and starts a leader that exits at
+// once; what the turn left is what the test adds to tb.
+func liveTurn(t *testing.T, tb Procs, own *Own, settle time.Duration) (*Turns, *Turn, *Executor, *Run) {
+ t.Helper()
+ turns := NewTurns("").Sweep(tb)
+ turns.own, turns.Settle = own, settle
+ u, err := turns.Take(context.Background(), OpEngineering)
+ if err != nil {
+ t.Fatal(err)
+ }
+ x := &Executor{Turns: turns, Grace: 50 * time.Millisecond, Settle: settle, Poll: 10 * time.Millisecond}
+ run, err := x.Start(u.Context(context.Background()), Command{Argv: []string{"/bin/true"}}, "attempt-l", func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-run.Exited()
+ return turns, u, x, run
+}
+
+func untouched(t *testing.T, sig []int, pids ...int) {
+ t.Helper()
+ for _, pid := range pids {
+ if slices.Contains(sig, pid) || slices.Contains(sig, -pid) {
+ t.Fatalf("%d (there before the turn, or spared) was signalled: %v", pid, sig)
+ }
+ }
+}
+
+// #10: a step that double-forked to launchd between two polls and runs a
+// system binary (a /System stand-in for a script interpreter) is killed,
+// and while it lives the end is not proven and no turn begins. What was
+// there before the turn is never touched.
+func TestSweepKillsSystemPathEscapes(t *testing.T) {
+ me := os.Getuid()
+ tb := parseTable(t, turnBegan)
+ turns, u, _, run := liveTurn(t, tb, &Own{}, 250*time.Millisecond)
+ tb.add(row(82100, 1, 82100, 82100, 5100, me, ""), "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Helpers/jsc")
+ tb.mark(&tb.unkillable, 82100)
+ if run.Stop() {
+ t.Fatal("proven over with a double-forked system-path process alive")
+ }
+ if !slices.Contains(tb.signalled(), 82100) {
+ t.Fatalf("the escape was spared: %v", tb.signalled())
+ }
+ u.Give()
+ if _, err := turns.Take(context.Background(), OpCheck); !errors.Is(err, ErrUnsettled) {
+ t.Fatalf("a turn began beside it: %v", err)
+ }
+ tb.unmark(&tb.unkillable, 82100)
+ next, err := turns.Take(context.Background(), OpCheck)
+ if err != nil {
+ t.Fatalf("not settled once it could die: %v", err)
+ }
+ next.Give()
+ if tb.has(82100) {
+ t.Fatal("the escape survived settling")
+ }
+ untouched(t, tb.signalled(), 40100, 40200, 40300)
+}
+
+// #10: a system agent launchd started during the turn is killed like
+// anything else new; what launchd starts again from a system path after
+// the kill pass began is a relaunch, spared and not in the way of the
+// proof. Something new outside the system after the kill pass is killed.
+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 {
+ 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, "")
+ tb.paths[82300] = "/Users/paulequipo/w/late"
+ }
+ }
+ _, u, _, run := liveTurn(t, tb, &Own{}, time.Second)
+ defer u.Give()
+ tb.add(row(82200, 1, 82200, 82200, 5200, me, ""), "/usr/libexec/trustd")
+ if !run.Stop() {
+ t.Fatalf("a launchd relaunch after the kill pass blocked the proof: %v", tb.signalled())
+ }
+ sig := tb.signalled()
+ for _, pid := range []int{82200, 82300} {
+ if !slices.Contains(sig, pid) {
+ t.Fatalf("%d (new during the turn) was spared: %v", pid, sig)
+ }
+ }
+ untouched(t, sig, 82201, 40100, 40200, 40300)
+}
+
+// #3: a helper's child seen while the helper lived stays the runner's
+// own after the helper exits and the child is reparented; a process that
+// later has the helper's pid (another start) is not, nor its child.
+func TestSweepSparesOrphanedHelperDescendants(t *testing.T) {
+ me, self := os.Getuid(), os.Getpid()
+ tb := parseTable(t, turnBegan)
+ own := &Own{}
+ sig := sweepTurn(t, tb, own, func(*Turn) {
+ tb.add(row(51100, self, self, self, 2000, me, ""), "/usr/bin/xcrun")
+ own.Add(ProcID{PID: 51100, Start: 2000})
+ tb.add(row(51101, 51100, 51101, 51101, 2001, me, ""), "/Applications/Xcode.app/Contents/Developer/usr/bin/simctl")
+ if _, _, err := own.Snapshot(time.Now().Add(time.Second), tb, nil); err != nil {
+ t.Fatal(err)
+ }
+ tb.remove(51100)
+ tb.reparent(51101, 1)
+ tb.add(row(51100, 1, 51100, 51100, 2500, me, ""), "/Users/paulequipo/w/reused")
+ tb.add(row(51102, 51100, 51100, 51100, 2501, me, ""), "/Users/paulequipo/w/reused-child")
+ })
+ untouched(t, sig, 51101)
+ for _, pid := range []int{51100, 51102} {
+ if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
+ t.Fatalf("%d (a reused helper pid and its child) was spared: %v", pid, sig)
+ }
+ }
+}
+
+// #5: a group is signalled whole only while a freshly read member is
+// still in it: a process that left the group between the table and the
+// re-check (setpgid, setsid) does not license a signal to the old group,
+// in the sweep or in the restart path.
+func TestGroupSignalNeedsFreshMembership(t *testing.T) {
+ me := os.Getuid()
+ moveOut := func(tb *table, target int) {
+ moved := false
+ tb.lookup = func(tb *table, pid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ if pid == target && !moved {
+ moved = true
+ q := tb.procs[pid]
+ q.PGID = pid
+ tb.procs[pid] = q
+ }
+ }
+ }
+ tb := parseTable(t, turnBegan)
+ sig := sweepTurn(t, tb, &Own{}, func(u *Turn) {
+ u.note(span{61200: 3000}, nil)
+ tb.add(row(61201, 1, 61200, 61201, 3001, me, ""), "/Users/paulequipo/w/a")
+ moveOut(tb, 61201)
+ })
+ untouched(t, sig, 61200)
+ tb = parseTable(t, turnBegan)
+ tb.add(row(61301, 1, 61300, 61301, 3100, me, "attempt-v"), "/Users/paulequipo/w/b")
+ moveOut(tb, 61301)
+ x := &Executor{Procs: tb, Own: &Own{}, Settle: 300 * time.Millisecond}
+ x.Verify(RecordID(61300, "attempt-v"))
+ untouched(t, tb.signalled(), 61300)
+}
+
+// #6: every group and session the attempt made must be gone, through
+// the live proof and through recovery: one now held only by another
+// user's process (never signalled) keeps the attempt unproven until it
+// ends.
+func TestRecoveryKeepsEveryGroupAndSession(t *testing.T) {
+ me := os.Getuid()
+ for _, c := range []struct {
+ name string
+ other ProcInfo
+ }{
+ // the group's id, now another user's group
+ {"group", row(91001, 1, 91001, 91001, 7000, 501, "")},
+ // the session's only member left, another user's (a setuid program)
+ {"session", row(91100, 1, 91100, 91001, 7000, 501, "")},
+ // our own process, which became root (a setuid program that
+ // called setuid): the same identity, out of our reach
+ {"setuid", row(91001, 1, 91002, 91002, 6001, 0, "")},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ tb := parseTable(t, turnBegan)
+ // Once ours is killed, another user's process has its id (or
+ // is what is left of its session).
+ tb.after = func(tb *table, pid int, sig syscall.Signal) {
+ if (pid == 91001 || pid == -91001) && tb.procs[c.other.PID].UID != 501 {
+ tb.procs[c.other.PID] = c.other
+ tb.paths[c.other.PID] = "/usr/bin/login"
+ // Signals before this were at our own process.
+ tb.sent = nil
+ }
+ }
+ turns, u, x, run := liveTurn(t, tb, &Own{}, 200*time.Millisecond)
+ tb.add(row(91001, 1, 91001, 91001, 6001, me, "attempt-l"), "/Users/paulequipo/w/m")
+ if run.Stop() {
+ t.Fatal("proven over while another user holds what it made")
+ }
+ u.Give()
+ // Nothing of the runner user's is left: the Mac takes turns
+ // again, and the attempt still owes what another user holds.
+ next, err := turns.Take(context.Background(), OpCheck)
+ if err != nil {
+ t.Fatalf("the Mac stays blocked on another user's process: %v", err)
+ }
+ next.Give()
+ if x.Verify(RecordID(0, "attempt-l")) {
+ t.Fatal("recovery proved it over while that lasts")
+ }
+ untouched(t, tb.signalled(), c.other.PID)
+ tb.remove(c.other.PID)
+ if !x.Verify(RecordID(0, "attempt-l")) {
+ t.Fatal("not proven once it ended")
+ }
+ })
+ }
+}
+
+// slowTable's List takes delay and then shows nothing: a read that
+// returns after the deadline with good news.
+type slowTable struct {
+ *table
+ delay time.Duration
+ slow atomic.Bool
+}
+
+func (s *slowTable) List(deadline time.Time, markers []string) ([]ProcInfo, error) {
+ if s.slow.Load() {
+ time.Sleep(s.delay)
+ return nil, nil
+ }
+ return s.table.List(deadline, markers)
+}
+
+// #7: one absolute deadline: a table read that returns after it never
+// makes a proof, in the live stop, in recovery, or settling a turn.
+func TestProofNeverAfterItsDeadline(t *testing.T) {
+ tb := &slowTable{table: parseTable(t, turnBegan), delay: 250 * time.Millisecond}
+ x := &Executor{Procs: tb, Own: &Own{}, Grace: 10 * time.Millisecond, Settle: 100 * time.Millisecond, Poll: time.Hour}
+ run, err := x.Start(context.Background(), Command{Argv: []string{"/bin/true"}}, "attempt-slow", func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ <-run.Exited()
+ tb.slow.Store(true)
+ if run.Stop() {
+ t.Fatal("the live stop proved it after its deadline")
+ }
+ if x.Verify(RecordID(0, "attempt-slow")) {
+ t.Fatal("recovery proved it after its deadline")
+ }
+ turns := NewTurns("").Sweep(tb)
+ turns.own, turns.Settle = &Own{}, 100*time.Millisecond
+ if err := turns.saveTurn(turnRecord{ID: "old", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: []ProcID{}, Markers: []string{"attempt-slow"}}); err != nil {
+ t.Fatal(err)
+ }
+ if u, err := turns.Take(context.Background(), OpCheck); err == nil {
+ u.Give()
+ t.Fatal("an earlier turn was settled after the deadline")
+ }
+}
+
+// #10: only a process that started after the first kill pass began can
+// be a relaunch. One with a system path and launchd as its parent that
+// started before it (here missing from that pass's read) is killed.
+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 {
+ delete(tb.hidden, 82400)
+ }
+ }
+ _, u, _, run := liveTurn(t, tb, &Own{}, time.Second)
+ defer u.Give()
+ tb.mark(&tb.hidden, 82400)
+ tb.add(row(82400, 1, 82400, 82400, 5400, me, ""), "/System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Helpers/jsc")
+ tb.add(row(82500, 1, 82500, 82500, 5500, me, ""), "/Users/paulequipo/w/first")
+ if !run.Stop() {
+ t.Fatalf("not proven: %v", tb.signalled())
+ }
+ if !slices.Contains(tb.signalled(), 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/gate.go b/internal/runner/mac/gate.go
index d5cb2d00..59197f6a 100644
--- a/internal/runner/mac/gate.go
+++ b/internal/runner/mac/gate.go
@@ -189,6 +189,10 @@ func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limi
}
}
}
+ case <-run.Aborted():
+ // Its turn's record could not be written: stopped, and its end
+ // proven only once a write succeeds.
+ res.Reason = "checks_unavailable"
case <-ctx.Done():
res.Reason = "cancelled"
case <-timer.C:
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go
index 42ccfb9e..3af500e6 100644
--- a/internal/runner/mac/launch.go
+++ b/internal/runner/mac/launch.go
@@ -14,6 +14,7 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
"amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runner/provider/claude"
)
@@ -113,7 +114,7 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f
if len(c.Argv) == 0 || !validMarker(marker) {
return nil, provider.ErrPolicy
}
- r := &Run{x: x, turn: turn, marker: marker, procs: x.procs(), own: x.own(), exited: make(chan struct{}), stopPoll: make(chan struct{}), polled: make(chan struct{})}
+ r := &Run{x: x, turn: turn, marker: marker, procs: x.procs(), own: x.own(), exited: make(chan struct{}), stopPoll: make(chan struct{}), polled: make(chan struct{}), aborted: make(chan struct{})}
var before []ProcID
if turn != nil {
// A sweeping turn's table is the run's: the identities it read
@@ -196,10 +197,11 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f
if r.temp != nil {
_ = x.Turns.writePending(pendingRecord{Attempt: marker, PGID: r.pgid, Before: r.temp.before, Runner: selfID()})
}
+ var noted error
if turn != nil {
- turn.note(r.scope.Groups, r.scope.Sessions)
+ noted = turn.note(r.scope.Groups, r.scope.Sessions)
}
- if err := record(RecordID(r.pgid, marker)); err != nil {
+ if err := errors.Join(noted, record(RecordID(r.pgid, marker))); err != nil {
r.pollOnce.Do(func() { close(r.stopPoll) })
close(r.polled)
proven := r.stopWith(0)
@@ -237,9 +239,16 @@ type Run struct {
waitErr error
stopPoll, polled chan struct{}
- pollOnce sync.Once
- stopOnce sync.Once
- proven bool
+ // unwritten is the turn record's last failed write: the operation is
+ // stopped and its proof withheld until a write succeeds.
+ unwritten error
+ abortOnce sync.Once
+ // aborted closes when the operation is stopped on its own (its
+ // turn's record could not be written).
+ aborted chan struct{}
+ pollOnce sync.Once
+ stopOnce sync.Once
+ proven bool
temp *tempState
finishOnce sync.Once
@@ -254,6 +263,10 @@ func (r *Run) ID() string { return RecordID(r.pgid, r.marker) }
// Exited is closed once the leader has exited (and been reaped).
func (r *Run) Exited() <-chan struct{} { return r.exited }
+// Aborted is closed when the run stopped itself (its turn's record
+// could not be written).
+func (r *Run) Aborted() <-chan struct{} { return r.aborted }
+
// ExitErr is the leader's exit (after Exited).
func (r *Run) ExitErr() error { return r.waitErr }
@@ -291,15 +304,27 @@ func (r *Run) poll() {
tick := time.NewTicker(every)
defer tick.Stop()
for {
- list, own, err := r.own.Snapshot(r.procs, nil)
+ list, own, err := r.own.Snapshot(time.Now().Add(every), r.procs, nil)
if err == nil {
r.mu.Lock()
r.adopt(list)
grew := r.scope.Track(list, own)
- groups, sessions := cloneSpan(r.scope.Groups), cloneSpan(r.scope.Sessions)
+ groups, sessions := r.scope.Groups.Clone(), r.scope.Sessions.Clone()
+ failed := r.unwritten != nil
r.mu.Unlock()
- if grew && r.turn != nil {
- r.turn.note(groups, sessions)
+ if (grew || failed) && r.turn != nil {
+ err := r.turn.note(groups, sessions)
+ r.mu.Lock()
+ r.unwritten = err
+ r.mu.Unlock()
+ if err != nil {
+ // What the attempt made is not on record for a
+ // restart: the attempt goes now.
+ r.abortOnce.Do(func() {
+ close(r.aborted)
+ go r.Stop()
+ })
+ }
}
}
select {
@@ -336,50 +361,34 @@ func (r *Run) Stop() bool {
}
func (r *Run) stopWith(grace time.Duration) bool {
- start := time.Now()
- deadline := start.Add(r.x.settleLimit())
- for {
- list, own, err := r.own.Snapshot(r.procs, []string{r.marker})
- if err == nil {
- r.mu.Lock()
- r.adopt(list)
- left := r.scope.Targets(list, own)
- reaped := false
- select {
- case <-r.exited:
- reaped = true
- default:
- }
- if len(left) == 0 && reaped && r.scope.GroupsGone() {
- r.mu.Unlock()
- if r.turn != nil {
- r.turn.note(r.scope.Groups, r.scope.Sessions)
- }
- return true
- }
- sig := syscall.SIGKILL
- if time.Since(start) < grace {
- sig = syscall.SIGTERM
- }
- r.scope.Kill(left, sig)
- r.mu.Unlock()
- }
- if time.Now().After(deadline) {
- r.mu.Lock()
- groups, sessions := cloneSpan(r.scope.Groups), cloneSpan(r.scope.Sessions)
- r.mu.Unlock()
- if r.turn != nil {
- r.turn.note(groups, sessions)
- r.turn.unprovenEnd()
- }
- return false
- }
+ reaped := func() bool {
select {
case <-r.exited:
- time.Sleep(20 * time.Millisecond)
- case <-time.After(100 * time.Millisecond):
+ return true
+ default:
+ return false
}
}
+ 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
+ }
+ // Proven only with everything it made durably on record (a restart
+ // must find the same).
+ killed := make([]ProcID, 0, len(r.scope.Killed))
+ for id := range r.scope.Killed {
+ killed = append(killed, id)
+ }
+ err := r.turn.note(r.scope.Groups, r.scope.Sessions, killed...)
+ r.mu.Lock()
+ r.unwritten = err
+ r.mu.Unlock()
+ if out != proc.Proven || err != nil {
+ r.turn.unprovenEnd()
+ return false
+ }
+ return true
}
// Finish is the user-temp cleanup once the end is proven (the
@@ -453,17 +462,24 @@ func parseRecord(id string) (int, string, bool) {
// Verify reports whether a recorded attempt has ended for sure (after a
// restart, or for a step whose end was not proven when it stopped):
+//
// - if its turn's record is still unsettled, a turn is taken (only
// if free now) and settles it first: everything that turn left, by
// its sweep;
+//
// - every process carrying its marker is killed, and its recorded
// group only while a marked process is in it. A group alive with no
// marked process (a child that scrubbed its environment, or the id
// used again by someone else) is never killed and never proven over;
+//
// - a user-temp cleanup the attempt owns is finished in that turn.
//
+// - whatever its turn still owes (a group, session or process another
+// user now holds: never signalled) must be gone.
+//
// Ended only when the group is gone (kill(-pgid, 0) is ESRCH), nothing
-// carries the marker, its turn is settled and its cleanup is done.
+// carries the marker, its turn is settled and owes nothing, and its
+// cleanup is done.
func (x *Executor) Verify(id string) bool {
pgid, attempt, ok := parseRecord(id)
if !ok {
@@ -483,7 +499,7 @@ func (x *Executor) Verify(id string) bool {
held = u
}
}
- if !x.settleRecord(pgid, attempt) {
+ if !x.settleRecord(pgid, attempt) || x.Turns != nil && !x.Turns.debts.Paid(attempt, x.Turns.table()) {
return false
}
if held != nil && x.UserTemp != "" {
@@ -499,34 +515,29 @@ func (x *Executor) Verify(id string) bool {
}
// settleRecord kills what carries the marker (and the recorded group
-// while a marked process is in it) and reports whether, within Settle,
-// the group is gone and nothing marked is left. pgid 0: the marker
-// alone settles it.
+// 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 {
procs, own := x.procs(), x.own()
deadline := time.Now().Add(x.settleLimit())
me := os.Getpid()
+ s := newScope(procs, nil, nil)
for {
- list, mine, err := own.Snapshot(procs, []string{attempt})
- if err != nil {
+ list, mine, err := own.Snapshot(deadline, procs, []string{attempt})
+ if err != nil || !time.Now().Before(deadline) {
return false
}
var marked []ProcInfo
- inGroup := false
for _, q := range list {
- if q.Marker != attempt || q.PID == me || q.PID <= 1 || mine[q.ID] {
- continue
+ if q.Marker == attempt && q.PID != me && q.PID > 1 && !mine[q.ID] {
+ marked = append(marked, q)
}
- marked = append(marked, q)
- inGroup = inGroup || pgid > 1 && q.PGID == pgid
- }
- s := newScope(procs, nil, nil)
- if inGroup {
- for _, q := range marked {
- if q.PGID == pgid && s.Still(q) {
- _ = procs.Signal(-pgid, syscall.SIGKILL)
- break
- }
+ }
+ for _, q := range marked {
+ if pgid > 1 && s.InGroup(q, pgid) {
+ _ = procs.Signal(-pgid, syscall.SIGKILL)
+ break
}
}
for _, q := range marked {
@@ -534,14 +545,14 @@ func (x *Executor) settleRecord(pgid int, attempt string) bool {
_ = procs.Signal(q.PID, syscall.SIGKILL)
}
}
- gone := pgid == 0 || procs.Signal(-pgid, 0) == syscall.ESRCH
- if gone && len(marked) == 0 {
+ gone := pgid == 0 || errors.Is(procs.Signal(-pgid, 0), syscall.ESRCH)
+ if gone && len(marked) == 0 && time.Now().Before(deadline) {
return true
}
- if time.Now().After(deadline) {
+ if !time.Now().Before(deadline) {
return false
}
- time.Sleep(100 * time.Millisecond)
+ time.Sleep(min(100*time.Millisecond, time.Until(deadline)))
}
}
@@ -553,7 +564,7 @@ func Marked(attempt string) ([]Proc, error) {
if attempt == "" {
return nil, errors.New("mac: no attempt marker")
}
- list, _, err := runnerOwn.Snapshot(platformProcs, []string{attempt})
+ list, _, err := runnerOwn.Snapshot(time.Now().Add(30*time.Second), platformProcs, []string{attempt})
if err != nil {
return nil, err
}
@@ -618,6 +629,7 @@ func (p *process) Wait(ctx context.Context) (provider.Exit, error) {
select {
case <-p.run.exited:
case <-p.run.stopPoll:
+ case <-p.run.aborted:
case <-ctx.Done():
}
proven := p.run.Stop()
diff --git a/internal/runner/mac/launch_test.go b/internal/runner/mac/launch_test.go
index edd38319..f8ad2b3a 100644
--- a/internal/runner/mac/launch_test.go
+++ b/internal/runner/mac/launch_test.go
@@ -45,7 +45,7 @@ func newLaunchRig(t *testing.T, extra ...string) *launchRig {
r := &launchRig{t: t, nonce: nonce, procs: procs, turns: turns, x: &Executor{Turns: turns, Grace: 300 * time.Millisecond, Settle: 3 * time.Second, Poll: 50 * time.Millisecond}}
t.Cleanup(func() {
// Whatever of the test's own is left (a failed test): by scope.
- if list, err := procs.List(nil); err == nil {
+ if list, err := procs.List(time.Now().Add(5*time.Second), nil); err == nil {
for _, q := range list {
_ = procs.Signal(q.PID, syscall.SIGKILL)
}
@@ -278,7 +278,7 @@ func TestRestartReusedGroupNotKilled(t *testing.T) {
r.x.Settle = 500 * time.Millisecond
marker := "attempt-r-" + r.nonce
unrelated := r.start(r.env(), "/bin/sleep", "60")
- before, err := r.procs.List(nil)
+ before, err := r.procs.List(time.Now().Add(5*time.Second), nil)
if err != nil {
t.Fatal(err)
}
@@ -392,7 +392,11 @@ func TestSweepCatchesDoubleForkToLaunchd(t *testing.T) {
}
escaped := waitPID(t, pidFile)
<-run.Exited()
+ // Listed as soon as forked; an escape once setsid has run in it.
q := r.waitListed(escaped)
+ for deadline := time.Now().Add(5 * time.Second); q.SID != escaped && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
+ q, _ = r.procs.Lookup(escaped)
+ }
if q.Marker != "" || q.SID != escaped {
t.Fatalf("not an escape: %+v", q)
}
@@ -408,7 +412,7 @@ func TestSweepCatchesDoubleForkToLaunchd(t *testing.T) {
// until that process is gone.
func TestProofOnlyWhenNothingRemains(t *testing.T) {
r := newLaunchRig(t)
- r.x.Settle, r.turns.Settle, r.x.Poll = 600*time.Millisecond, 600*time.Millisecond, time.Hour
+ r.x.Settle, r.turns.Settle, r.x.Poll = 400*time.Millisecond, 400*time.Millisecond, time.Hour
stuck := &stuckProcs{Procs: r.procs}
r.turns.Sweep(stuck)
ctx, turn := r.take(OpEngineering)
@@ -651,3 +655,92 @@ func TestCleanupOwnedByItsTurn(t *testing.T) {
t.Fatalf("a live owner's cleanup taken by another turn: %+v", res)
}
}
+
+// #8: a turn record that cannot be written (here its directory turned
+// read-only) stops the operation by itself and withholds its proof; a
+// restart then settles what it left from the record it had.
+func TestTurnRecordWriteFailureStopsTheOperation(t *testing.T) {
+ r := newLaunchRig(t)
+ dir := filepath.Dir(r.turns.lock)
+ pidFile := filepath.Join(t.TempDir(), "child")
+ ctx, turn := r.take(OpEngineering)
+ marker := "attempt-w-" + r.nonce
+ run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", "sleep 0.4; setsid sleep 60 & echo $! > " + quote(pidFile) + "; sleep 60"}, Env: r.env("EQUIPO_ATTEMPT=" + marker)}, marker, func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, 0500); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(dir, 0700)
+ select {
+ case <-run.Exited():
+ case <-time.After(5 * time.Second):
+ t.Fatal("the operation ran on with its turn's record unwritable")
+ }
+ child := waitPID(t, pidFile)
+ if run.Stop() {
+ t.Fatal("proven over with its groups not on record")
+ }
+ turn.Give()
+ if err := os.Chmod(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ next := NewTurns(r.turns.lock).Sweep(r.procs)
+ next.Settle = 3 * time.Second
+ u, err := next.Take(context.Background(), OpCheck)
+ if err != nil {
+ t.Fatalf("a restart did not settle it: %v", err)
+ }
+ u.Give()
+ if !gone(child) {
+ t.Fatal("what it left survived the restart's settling")
+ }
+}
+
+// blind cannot read pid's identity (a sysctl that failed), though the
+// process is there.
+type blind struct {
+ Procs
+ pid int
+}
+
+func (b *blind) Lookup(pid int) (ProcInfo, bool) {
+ if pid == b.pid {
+ return ProcInfo{}, false
+ }
+ return b.Procs.Lookup(pid)
+}
+
+// #9: a cleanup's owner whose identity cannot be read is not a restart:
+// another turn neither finishes the cleanup nor runs.
+func TestCleanupOwnerUnknownIsNotARestart(t *testing.T) {
+ g, dir := gateFixture(t, true)
+ _, temp := userTempFixture(t)
+ g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock"))
+ owner := exec.Command("/bin/sleep", "60")
+ if err := owner.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = owner.Process.Kill(); _ = owner.Wait() }()
+ id, ok := platformProcs.Lookup(owner.Process.Pid)
+ if !ok {
+ t.Fatal("owner not listed")
+ }
+ g.Turns.ids = &blind{Procs: platformProcs, pid: owner.Process.Pid}
+ s, err := openTemp(temp, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := g.Turns.writePending(pendingRecord{Attempt: "checks-u-owner", Before: s.before, Runner: id.ID}); err != nil {
+ t.Fatal(err)
+ }
+ s.close()
+ left := filepath.Join(temp, "left-by-owner")
+ if err := os.WriteFile(left, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if res, _ := run(g, dir, "checks-u-1", time.Minute, "true"); res.Reason != "checks_unavailable" || !exists(left) || !g.Turns.Pending() {
+ t.Fatalf("a live owner's cleanup taken on an unreadable identity: %+v", res)
+ }
+}
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
index fb7ad11c..b82d181f 100644
--- a/internal/runner/mac/probe.go
+++ b/internal/runner/mac/probe.go
@@ -155,12 +155,11 @@ func RunProbes(ctx context.Context, h ProbeHost) Report {
run, give, err := h.Turns.Hold(run, OpProbe)
if err != nil {
for _, id := range wire.ProbeIDs {
- r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: "not proven: the Mac's turn was not free"})
+ r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetailTurnBusy})
r.Unfinished = append(r.Unfinished, id)
}
return r
}
- defer give()
h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}}
h.Exec = h.late.do
var mu sync.Mutex
@@ -191,9 +190,15 @@ func RunProbes(ctx context.Context, h ProbeHost) Report {
put(probeP6(run, h, caps, ran))
put(probeP7(run, h))
}()
+ // Past the limit the report is made with what there is, but the turn
+ // is held until the run has ended (its context is cancelled, so its
+ // gates stop and prove their end and clean up): nothing else runs
+ // beside a probe still stopping.
select {
case <-done:
+ give()
case <-run.Done():
+ go func() { <-done; give() }()
}
mu.Lock()
defer mu.Unlock()
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go
index 05a4a871..e0359a00 100644
--- a/internal/runner/mac/probe_test.go
+++ b/internal/runner/mac/probe_test.go
@@ -30,6 +30,7 @@ import (
// ($XDG_CONFIG_HOME, else ~/.swiftpm) is not in TMPDIR as ~/.swiftpm
// did (exit 74).
const fakeXcodebuild = `#!/bin/bash
+[ -n "$FAKE_HANG" ] && { trap '' TERM; exec sleep 600; }
noise() { [ -n "$FAKE_NOISE" ] && for i in $(seq 1 300); do echo "CompileSwift normal arm64 step $i"; done; true; }
for f in -derivedDataPath -clonedSourcePackagesDirPath -packageCachePath; do
case " $* " in *" $f $TMPDIR/"*) ;; *) echo "error: Could not compute dependency graph: Error Domain=NSCocoaErrorDomain Code=513 (no permission to save in the folder workspace; $f not in TMPDIR)"; echo "** BUILD FAILED **"; exit 65 ;; esac
@@ -396,3 +397,55 @@ func TestRunProbesLimit(t *testing.T) {
t.Fatalf("report outside the capability rules: %v", err)
}
}
+
+// #1: a probe run that reaches its limit reports at once, but keeps the
+// Mac's turn until its gates have stopped (here one that ignores SIGTERM
+// for its grace): nothing else takes the turn meanwhile, and it is free
+// once they have.
+func TestProbeLimitHoldsTheTurnUntilItsGateEnds(t *testing.T) {
+ f := newProbeFixture(t, allLines("denied"), "FAKE_HANG=1")
+ turns := NewTurns(filepath.Join(t.TempDir(), "lock"))
+ inner := f.h.Gate
+ f.h.Gate = func(sandboxed bool) *Gate { g := inner(sandboxed); g.Grace = 900 * time.Millisecond; return g }
+ f.h.Turns, f.h.Limit = turns, 400*time.Millisecond
+ done := make(chan Report, 1)
+ go func() { done <- RunProbes(context.Background(), f.h) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("no report at the run's limit")
+ }
+ time.Sleep(200 * time.Millisecond)
+ if u, ok := turns.TryTake(OpCheck); ok {
+ u.Give()
+ t.Fatal("another operation took the turn while the probe's gate was still stopping")
+ }
+ for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) {
+ if u, ok := turns.TryTake(OpCheck); ok {
+ u.Give()
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the turn was never given back")
+ }
+ }
+}
+
+// #11: a probe run that cannot take the Mac's turn says so by a code
+// the instance words, not by English of its own.
+func TestRunProbesWithoutTheTurn(t *testing.T) {
+ f := newProbeFixture(t, allLines("denied"))
+ turns := NewTurns("")
+ held, err := turns.Take(context.Background(), OpEngineering)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Give()
+ f.h.Turns, f.h.Limit = turns, 200*time.Millisecond
+ rep := RunProbes(context.Background(), f.h)
+ for _, p := range rep.Probes {
+ if p.Verdict != wire.ProbeUnavailable || p.Detail != wire.ProbeDetailTurnBusy {
+ t.Fatalf("%+v", p)
+ }
+ }
+}
diff --git a/internal/runner/mac/proc/debts.go b/internal/runner/mac/proc/debts.go
new file mode 100644
index 00000000..60390ca4
--- /dev/null
+++ b/internal/runner/mac/proc/debts.go
@@ -0,0 +1,118 @@
+package proc
+
+import (
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "os"
+ "slices"
+ "sync"
+)
+
+// Debts keeps what unproven turns still owe, past their turn records:
+// a JSON file (Path), or memory when Path is "".
+type Debts struct {
+ Path string
+ mu sync.Mutex
+ mem []Obligation
+}
+
+// Owe keeps o durably.
+func (d *Debts) Owe(o Obligation) error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ all, err := d.load()
+ if err != nil {
+ return err
+ }
+ return d.save(append(all, o))
+}
+
+// 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()
+ all, err := d.load()
+ if err != nil {
+ return false
+ }
+ var keep []Obligation
+ paid := true
+ for _, o := range all {
+ switch {
+ case !slices.Contains(o.Markers, attempt):
+ keep = append(keep, o)
+ case !o.Met(t):
+ keep, paid = append(keep, o), false
+ }
+ }
+ if len(keep) != len(all) && d.save(keep) != nil {
+ return false
+ }
+ return paid
+}
+
+func (d *Debts) load() ([]Obligation, error) {
+ if d.Path == "" {
+ return slices.Clone(d.mem), nil
+ }
+ raw, err := os.ReadFile(d.Path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ var all []Obligation
+ return all, json.Unmarshal(raw, &all)
+}
+
+func (d *Debts) save(all []Obligation) error {
+ if d.Path == "" {
+ d.mem = all
+ return nil
+ }
+ if len(all) == 0 {
+ if err := os.Remove(d.Path); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+ }
+ raw, err := json.Marshal(all)
+ if err != nil {
+ return err
+ }
+ return WriteDurably(d.Path, raw)
+}
+
+// WriteDurably writes raw beside p, syncs it and renames it over p.
+func WriteDurably(p string, raw []byte) error {
+ f, err := os.OpenFile(p+".new", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
+ if err != nil {
+ return err
+ }
+ _, err = f.Write(raw)
+ if serr := f.Sync(); err == nil {
+ err = serr
+ }
+ if cerr := f.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return err
+ }
+ return os.Rename(p+".new", p)
+}
+
+// Clone is a copy of s (nil stays nil).
+func (s Span) Clone() Span {
+ if s == nil {
+ return nil
+ }
+ c := Span{}
+ for k, v := range s {
+ c[k] = v
+ }
+ return c
+}
diff --git a/internal/runner/mac/proc/proc.go b/internal/runner/mac/proc/proc.go
index 1b40fc21..52077ee9 100644
--- a/internal/runner/mac/proc/proc.go
+++ b/internal/runner/mac/proc/proc.go
@@ -12,23 +12,26 @@ import (
"strings"
"sync"
"syscall"
+ "time"
)
-// How the runner finds what an operation left (spec §5 and its
-// 2026-11-28 addendum, §8.8). Claude Code starts every Bash command in a
-// session of its own (setsid), and macOS 27.2 hides the environment of
-// platform binaries (bash, zsh, sleep, env, sandbox-exec) even from
-// their own user, so neither the attempt's group nor its marker finds
-// them all. Three nets, all keyed by process identity (pid and kernel
-// start time), never by name:
+// How the runner finds what an operation left (spec §8.8). Claude Code
+// starts every Bash command in a session of its own (setsid), and macOS
+// 27.2 hides the environment of platform binaries (bash, zsh, sleep,
+// env, sandbox-exec) even from their own user, so neither the attempt's
+// group nor its marker finds them all. Three nets, all keyed by process
+// identity (pid and kernel start time), never by name or path:
//
// (a) while the operation runs, the processes under its leader and
// every group and session they make;
// (b) at its end, every process of the runner user that did not exist
// when the turn began, except the runner and what it started for
-// itself (Own), and launchd's own system agents (ppid 1, executable
-// under /System or /usr/libexec, by the kernel's path);
+// itself (Own, with their descendants seen while they lived);
// (c) the marker, wherever the kernel shows it.
+//
+// The one exception to (b): once the first kill pass has begun, what
+// launchd starts again from a system path (a relaunched on-demand agent)
+// is not the operation's.
// ID names one process for its whole life: its pid and the kernel's
// start time (on a Mac microseconds since the epoch, on Linux clock
@@ -52,14 +55,18 @@ type Info struct {
// Linux, recorded tables in tests).
type Table interface {
// List is every process whose user is the runner's, each with
- // which of markers its environment carries.
- List(markers []string) ([]Info, error)
- // Lookup is pid as it is now; ok is false once it is gone (or is
- // another user's).
+ // which of markers its environment carries, read before deadline
+ // (a read still running then is given up).
+ List(deadline time.Time, markers []string) ([]Info, error)
+ // Lookup is pid as it is now; ok is false once it is gone, is
+ // another user's, or cannot be read.
Lookup(pid int) (Info, bool)
// Path is the executable the kernel runs as pid (its file, not its
// argv[0], which the process may set), "" when unknown.
Path(pid int) string
+ // SessionGone reports whether no process of any user is in session
+ // sid; false when that cannot be read.
+ SessionGone(sid int) bool
// Sweeps reports whether this table may drive the runner-user sweep
// (b): on a Mac, where the runner user is dedicated; on Linux only a
// table scoped to a test's own processes.
@@ -72,19 +79,42 @@ type Table interface {
// one (Linux outside a test's scope: other people's processes).
var ErrNoSweep = errors.New("mac: this process table cannot sweep the runner user")
+// Alive reads whether id is still running. known is false when that
+// cannot be told (the pid is there, ours to signal, and its identity
+// unreadable): a caller deciding ownership treats that as alive.
+func Alive(t Table, id ID) (alive, known bool) {
+ if id.PID <= 0 {
+ return false, true
+ }
+ switch err := t.Signal(id.PID, 0); {
+ case errors.Is(err, syscall.ESRCH), errors.Is(err, syscall.EPERM):
+ // Gone, or another user's process has the pid now.
+ return false, true
+ case err != nil:
+ return false, false
+ }
+ q, ok := t.Lookup(id.PID)
+ if !ok {
+ return false, false
+ }
+ return q.ID == id, true
+}
+
// Own is the runner's own processes: the runner itself and every helper
// it starts for itself (simctl and ps queries, caffeinate, git, the
-// gitleaks scan, packing), each by ID. A sweep never signals them,
-// nor, in the runner-user sweep, what they started. Its lock is held for
-// reading across a helper's start and registration and for writing
-// across a sweep's listing, so a helper is never listed unregistered.
+// gitleaks scan, packing), each by ID, and the descendants of each seen
+// while it lived. A sweep never signals them. gate is held for reading
+// across a helper's start and registration and for writing across a
+// sweep's listing, so a helper is never listed unregistered; mu guards
+// the record itself.
type Own struct {
- mu sync.RWMutex
- ids map[ID]bool
+ gate sync.RWMutex
+ mu sync.Mutex
+ ids map[ID]bool
}
// Runner is this process's registry; every helper the runner starts
-// for itself goes through StartOwn.
+// for itself goes through Start.
var Runner = &Own{}
// Start starts cmd as the runner's own helper (cmd.Start, then its
@@ -95,14 +125,14 @@ func Start(cmd *exec.Cmd) error { return Runner.Start(cmd, Platform) }
// Start starts cmd and records it as own, reading its identity from p.
func (o *Own) Start(cmd *exec.Cmd, p Table) error {
- o.mu.RLock()
- defer o.mu.RUnlock()
+ o.gate.RLock()
+ defer o.gate.RUnlock()
if err := cmd.Start(); err != nil {
return err
}
pid := cmd.Process.Pid
if info, ok := p.Lookup(pid); ok && info.PID == pid {
- o.add(info.ID)
+ o.Add(info.ID)
return nil
}
if syscall.Kill(pid, 0) == syscall.ESRCH {
@@ -114,48 +144,78 @@ func (o *Own) Start(cmd *exec.Cmd, p Table) error {
return errors.New("mac: a helper's identity could not be read")
}
-// Add records id as own (a helper started some other way).
-func (o *Own) Add(id ID) {
+// Owns reports whether id is on record as the runner's own.
+func (o *Own) Owns(id ID) bool {
o.mu.Lock()
defer o.mu.Unlock()
- o.add(id)
+ return o.ids[id]
}
-func (o *Own) add(id ID) {
+// Add records id as own (a helper started some other way).
+func (o *Own) Add(id ID) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
if o.ids == nil {
o.ids = map[ID]bool{}
}
o.ids[id] = true
}
-// Snapshot lists p with no helper half-started, and forgets the helpers
-// that are gone (their identity cannot come back).
-func (o *Own) Snapshot(p Table, markers []string) ([]Info, map[ID]bool, error) {
- o.mu.Lock()
- defer o.mu.Unlock()
- list, err := p.List(markers)
+// Snapshot lists p with no helper half-started. A process whose parent
+// (started no later than it) is own becomes own itself, so it stays the
+// runner's when that parent exits; identities no longer listed are
+// forgotten (they cannot come back).
+func (o *Own) Snapshot(deadline time.Time, p Table, markers []string) ([]Info, map[ID]bool, error) {
+ o.gate.Lock()
+ defer o.gate.Unlock()
+ list, err := p.List(deadline, markers)
if err != nil {
return nil, nil, err
}
- live := map[ID]bool{}
- for _, q := range list {
- live[q.ID] = true
- }
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ by := Index(list)
own := map[ID]bool{}
- for id := range o.ids {
- if live[id] {
- own[id] = true
- } else {
- delete(o.ids, id)
+ for _, q := range byStart(list) {
+ if o.ids[q.ID] {
+ own[q.ID] = true
+ continue
+ }
+ if parent, ok := by[q.PPID]; ok && parent.Start <= q.Start && own[parent.ID] {
+ own[q.ID] = true
}
}
- return list, own, nil
+ o.ids = own
+ return list, maps(own), nil
+}
+
+func maps(m map[ID]bool) map[ID]bool {
+ c := make(map[ID]bool, len(m))
+ for k, v := range m {
+ c[k] = v
+ }
+ return c
+}
+
+func byStart(list []Info) []Info {
+ sorted := slices.Clone(list)
+ slices.SortFunc(sorted, func(a, b Info) int {
+ if a.Start != b.Start {
+ if a.Start < b.Start {
+ return -1
+ }
+ return 1
+ }
+ return a.PID - b.PID
+ })
+ return sorted
}
// SystemPath reports whether the kernel's path of an executable is one
// only the system can write: under /System (but not its volumes, where
-// /System/Volumes/Data holds every user's files) or /usr/libexec. Exact
-// case: anything else is not a system agent, and is swept.
+// /System/Volumes/Data holds every user's files) or /usr/libexec or
+// /usr/sbin. Exact case. Only a relaunch after the kill pass began is
+// judged by it.
func SystemPath(p string) bool {
if p == "" || strings.Contains(p, "/../") || strings.Contains(p, "/./") || strings.HasSuffix(p, "/..") {
return false
@@ -163,7 +223,7 @@ func SystemPath(p string) bool {
switch {
case strings.HasPrefix(p, "/System/Volumes/"):
return false
- case strings.HasPrefix(p, "/System/"), strings.HasPrefix(p, "/usr/libexec/"):
+ case strings.HasPrefix(p, "/System/"), strings.HasPrefix(p, "/usr/libexec/"), strings.HasPrefix(p, "/usr/sbin/"):
return true
}
return false
@@ -174,22 +234,31 @@ func SystemPath(p string) bool {
// after it is the id used again by someone else.
type Span map[int]int64
-// scope is what one operation (or a turn's operations) may have left:
-// its processes seen, their groups and sessions, its markers, and, for
-// the runner-user sweep, what existed when the turn began.
+// Scope is what one operation (or a turn's operations) may have left:
+// its processes seen, their groups and sessions, its markers, the kill
+// set (every process it signalled), and, for the runner-user sweep, what
+// existed when the turn began.
type Scope struct {
uid, self int
markers []string
Seen map[ID]bool
Groups Span
Sessions Span
+ // Killed is every process the stop signalled: each must be gone.
+ Killed map[ID]bool
// before is the turn's table at its start; nil: no runner-user sweep.
before map[ID]bool
- procs Table
+ // 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 int64
+ procs Table
}
+// NewScope is a scope over p for markers; before is the turn's table
+// when it began (nil: no runner-user sweep).
func NewScope(p Table, markers []string, before []ID) *Scope {
- s := &Scope{uid: os.Getuid(), self: os.Getpid(), markers: markers, Seen: map[ID]bool{}, Groups: Span{}, Sessions: Span{}, procs: p}
+ s := &Scope{uid: os.Getuid(), self: os.Getpid(), markers: markers, Seen: map[ID]bool{}, Groups: Span{}, Sessions: Span{}, Killed: map[ID]bool{}, procs: p}
if before != nil {
s.before = map[ID]bool{}
for _, id := range before {
@@ -205,23 +274,13 @@ func NewScope(p Table, markers []string, before []ID) *Scope {
// processes; with each, its group and session. It reports whether a new
// group or session was found.
func (s *Scope) Track(list []Info, own map[ID]bool) bool {
- sorted := slices.Clone(list)
- slices.SortFunc(sorted, func(a, b Info) int {
- if a.Start != b.Start {
- if a.Start < b.Start {
- return -1
- }
- return 1
- }
- return a.PID - b.PID
- })
by := Index(list)
top := int64(0)
for _, q := range list {
top = max(top, q.Start)
}
grew := false
- for _, q := range sorted {
+ for _, q := range byStart(list) {
if q.UID != s.uid || q.PID == s.self || own[q.ID] {
continue
}
@@ -264,9 +323,9 @@ func (s *Scope) marked(q Info) bool {
// Targets is what of list the stop must end: the scope's own processes
// and, with a runner-user sweep, every process of the runner user that
-// was not there when the turn began, except the runner, its own helpers
-// and what they started, and launchd's system agents. Never another
-// user's process, never the runner's own.
+// was not there when the turn began and is not the runner's own,
+// whatever its path, but a launchd relaunch after the kill pass began.
+// Never another user's process, never the runner's own.
func (s *Scope) Targets(list []Info, own map[ID]bool) []Info {
s.Track(list, own)
by := Index(list)
@@ -276,42 +335,27 @@ func (s *Scope) Targets(list []Info, own map[ID]bool) []Info {
continue
}
switch {
- case s.Seen[q.ID] || s.member(q, by) || s.marked(q):
+ case s.Seen[q.ID] || s.member(q, by) || s.marked(q) || s.Killed[q.ID]:
out = append(out, q)
- case s.before != nil && !s.before[q.ID] && !ownChild(q, by, own) && !s.agent(q):
+ case s.before != nil && !s.before[q.ID] && !s.relaunch(q):
out = append(out, q)
}
}
return out
}
-// ownChild: q descends from one of the runner's own helpers (through
-// live parents, each started no later than its child).
-func ownChild(q Info, by map[int]Info, own map[ID]bool) bool {
- for range 64 {
- parent, ok := by[q.PPID]
- if !ok || parent.Start > q.Start || parent.PID == q.PID {
- return false
- }
- if own[parent.ID] {
- return true
- }
- q = parent
- }
- return false
-}
-
-// agent: launchd started q from the system (ppid 1, the kernel's path
-// under /System or /usr/libexec), read for the same process (its
-// identity again after the path).
-func (s *Scope) agent(q Info) bool {
- if q.PPID != 1 || !SystemPath(s.procs.Path(q.PID)) {
+// relaunch: launchd started q from a system path after the first kill
+// pass began (a killed on-demand agent started again), read for the
+// same process (its identity again after the path).
+func (s *Scope) relaunch(q Info) bool {
+ if s.relaunchAfter == 0 || q.Start <= s.relaunchAfter || q.PPID != 1 || !SystemPath(s.procs.Path(q.PID)) {
return false
}
now, ok := s.procs.Lookup(q.PID)
return ok && now.ID == q.ID
}
+// Index is list by pid.
func Index(list []Info) map[int]Info {
by := make(map[int]Info, len(list))
for _, q := range list {
@@ -320,22 +364,21 @@ func Index(list []Info) map[int]Info {
return by
}
-// Kill sends sig to each target, each checked again just before
-// (same pid, same start, still the runner user's): a pid used again
-// since the table was read is never signalled. A group is signalled
-// whole only while a checked target is in it (a group id cannot be used
-// again while it has a member).
+// Kill sends sig to each target, each read again just before (same pid,
+// same start, still the runner user's), and adds it to the kill set. A
+// group is signalled whole only while a target read just now is still
+// in it (a group id cannot be used again while it has a member).
func (s *Scope) Kill(targets []Info, sig syscall.Signal) {
done := map[int]bool{}
for _, q := range targets {
+ s.Killed[q.ID] = true
if q.PGID <= 1 || done[q.PGID] {
continue
}
- if _, ours := s.Groups[q.PGID]; !ours || !s.Still(q) {
- continue
+ if _, ours := s.Groups[q.PGID]; ours && s.InGroup(q, q.PGID) {
+ done[q.PGID] = true
+ _ = s.procs.Signal(-q.PGID, sig)
}
- done[q.PGID] = true
- _ = s.procs.Signal(-q.PGID, sig)
}
for _, q := range targets {
if s.Still(q) {
@@ -344,19 +387,150 @@ func (s *Scope) Kill(targets []Info, sig syscall.Signal) {
}
}
+// Still: q, read now, is the same process and still the runner user's.
func (s *Scope) Still(q Info) bool {
now, ok := s.procs.Lookup(q.PID)
return ok && now.ID == q.ID && now.UID == s.uid
}
-// GroupsGone reports whether every group the scope made is gone:
-// kill(-pgid, 0) says ESRCH. A group id used again by someone else
-// keeps it false until that group ends too.
-func (s *Scope) GroupsGone() bool {
+// InGroup: q, read now, is the same process and still in group pgid.
+func (s *Scope) InGroup(q Info, pgid int) bool {
+ now, ok := s.procs.Lookup(q.PID)
+ return ok && now.ID == q.ID && now.UID == s.uid && now.PGID == pgid
+}
+
+// Gone reports whether every obligation is met: each process in the
+// kill set gone (by identity), each group gone (kill(-pgid, 0) is
+// ESRCH) and each session without a member of any user. Nothing is
+// signalled: a group or session another user now holds keeps it false.
+func (s *Scope) Gone() bool {
+ for id := range s.Killed {
+ if !s.gone(id) {
+ return false
+ }
+ }
for g := range s.Groups {
- if s.procs.Signal(-g, 0) != syscall.ESRCH {
+ if !errors.Is(s.procs.Signal(-g, 0), syscall.ESRCH) {
+ return false
+ }
+ }
+ for sid := range s.Sessions {
+ if !s.procs.SessionGone(sid) {
return false
}
}
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).
+func (s *Scope) gone(id ID) bool {
+ if errors.Is(s.procs.Signal(id.PID, 0), syscall.ESRCH) {
+ return true
+ }
+ q, ok := s.procs.Lookup(id.PID)
+ return ok && q.Start != id.Start
+}
+
+// Outcome is how a settle ended.
+type Outcome int
+
+const (
+ // Proven: nothing of the scope is left.
+ Proven Outcome = iota
+ // Owed: nothing of the runner user's is left to kill, but a process,
+ // group or session of the scope is still there (another user's, or
+ // unreadable): never signalled, it must end before the proof.
+ Owed
+ // Left: a process of the runner user's is still a target.
+ 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.
+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
+ 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 {
+ 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
+ }
+ if left && s.relaunchAfter == 0 && s.before != nil {
+ for _, q := range list {
+ s.relaunchAfter = max(s.relaunchAfter, q.Start)
+ }
+ }
+ sig := syscall.SIGKILL
+ if time.Since(start) < grace {
+ sig = syscall.SIGTERM
+ }
+ s.Kill(targets, sig)
+ }
+ if !time.Now().Before(deadline) {
+ if left || !read {
+ return Left
+ }
+ return Owed
+ }
+ time.Sleep(min(100*time.Millisecond, time.Until(deadline)))
+ }
+}
+
+// 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"`
+}
+
+// Owe is what s still owes.
+func (s *Scope) Owe() Obligation {
+ o := Obligation{Markers: slices.Clone(s.markers), Groups: Span{}, Sessions: Span{}}
+ for id := range s.Killed {
+ o.Killed = append(o.Killed, id)
+ }
+ for k, v := range s.Groups {
+ o.Groups[k] = v
+ }
+ for k, v := range s.Sessions {
+ o.Sessions[k] = v
+ }
+ return o
+}
+
+// Met reports whether everything o names is gone now.
+func (o Obligation) Met(p Table) bool {
+ s := NewScope(p, o.Markers, nil)
+ for _, id := range o.Killed {
+ s.Killed[id] = true
+ }
+ for k, v := range o.Groups {
+ s.Groups[k] = v
+ }
+ for k, v := range o.Sessions {
+ s.Sessions[k] = v
+ }
+ return s.Gone()
+}
diff --git a/internal/runner/mac/proc/proc_darwin.go b/internal/runner/mac/proc/proc_darwin.go
index 2407e425..9766e5f4 100644
--- a/internal/runner/mac/proc/proc_darwin.go
+++ b/internal/runner/mac/proc/proc_darwin.go
@@ -2,6 +2,7 @@ package proc
import (
"context"
+ "errors"
"os"
"os/exec"
"syscall"
@@ -53,13 +54,16 @@ func fromKinfo(k *unix.KinfoProc) (Info, bool) {
// List reads the table, then ps -E, then the table again: a process is
// marked only when ps named its pid and that pid was the same process
// both times (so a pid used again meanwhile is never taken as marked).
-func (p sysctlProcs) List(markers []string) ([]Info, error) {
+func (p sysctlProcs) List(deadline time.Time, markers []string) ([]Info, error) {
first, err := p.table()
if err != nil || len(markers) == 0 {
return first, err
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ // ps is bounded by the caller's deadline (and never past 10 s).
+ ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
+ ctx, cancel2 := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel2()
// Not StartOwn: List runs under Own's write lock, and ps is started
// after the first table and reaped before the second, so neither
// lists it.
@@ -117,6 +121,30 @@ func (sysctlProcs) Path(pid int) string {
return string(buf[:n])
}
+// SessionGone reads every user's processes (kern.proc.all) and asks
+// each for its session: gone only when none is in sid and every answer
+// was read.
+func (sysctlProcs) SessionGone(sid int) bool {
+ kps, err := unix.SysctlKinfoProcSlice("kern.proc.all")
+ if err != nil {
+ return false
+ }
+ for i := range kps {
+ pid := int(kps[i].Proc.P_pid)
+ if pid <= 0 {
+ continue
+ }
+ got, err := unix.Getsid(pid)
+ if errors.Is(err, unix.ESRCH) {
+ continue
+ }
+ if err != nil || got == sid {
+ return false
+ }
+ }
+ return true
+}
+
func (sysctlProcs) Sweeps() bool { return true }
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 776c467e..a20f9f39 100644
--- a/internal/runner/mac/proc/proc_linux.go
+++ b/internal/runner/mac/proc/proc_linux.go
@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"syscall"
+ "time"
)
// procfs is the process table on Linux, where a Mac's runner is only
@@ -95,7 +96,7 @@ func (p procfs) read(pid int, markers []string) (Info, bool) {
return q, true
}
-func (p procfs) List(markers []string) ([]Info, error) {
+func (p procfs) List(_ time.Time, markers []string) ([]Info, error) {
entries, err := os.ReadDir("/proc")
if err != nil {
return nil, err
@@ -131,6 +132,28 @@ func (p procfs) Path(pid int) string {
return path
}
+// SessionGone reads every process's session from /proc (any user's).
+func (procfs) SessionGone(sid int) bool {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return false
+ }
+ for _, e := range entries {
+ if _, err := strconv.Atoi(e.Name()); err != nil {
+ continue
+ }
+ stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat"))
+ if err != nil {
+ continue
+ }
+ end := bytes.LastIndexByte(stat, ')')
+ if f := strings.Fields(string(stat[end+1:])); end >= 0 && len(f) > 3 && f[3] == strconv.Itoa(sid) {
+ return false
+ }
+ }
+ return true
+}
+
func (p procfs) Sweeps() bool { return p.scope != "" }
// Signal refuses to signal outside the scope: a scoped table's signals
@@ -142,7 +165,7 @@ func (p procfs) Signal(pid int, sig syscall.Signal) error {
if pid < 0 {
target = -pid
if _, ok := p.Lookup(target); !ok {
- list, err := p.List(nil)
+ list, err := p.List(time.Time{}, nil)
if err != nil {
return err
}
diff --git a/internal/runner/mac/proc/proc_test.go b/internal/runner/mac/proc/proc_test.go
index 2009b676..16c6d83f 100644
--- a/internal/runner/mac/proc/proc_test.go
+++ b/internal/runner/mac/proc/proc_test.go
@@ -2,16 +2,19 @@ package proc
import (
"os"
+ "os/exec"
+ "sync"
"testing"
+ "time"
"amadan.net/rastrillo/rastrillo/budget"
)
func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
-// Only a path the system alone can write is a launchd agent's: under
-// /System (not its volumes: /System/Volumes/Data is every user's data)
-// or /usr/libexec, exactly, with no climbing out.
+// Only a path the system alone can write counts for a relaunch: under
+// /System (not its volumes: /System/Volumes/Data is every user's data),
+// /usr/libexec or /usr/sbin, exactly, with no climbing out.
func TestSystemPath(t *testing.T) {
for p, want := range map[string]bool{
"/System/Library/PrivateFrameworks/X.framework/XPCServices/Y.xpc/Contents/MacOS/Y": true,
@@ -22,7 +25,7 @@ func TestSystemPath(t *testing.T) {
"/usr/libexec/./x": false,
"/usr/libexec/..": false,
"/system/Library/x": false,
- "/usr/sbin/cfprefsd": false,
+ "/usr/sbin/cfprefsd": true,
"/Users/paulequipo/.local/lib/equipo-runner/x": false,
"/System": false,
"": false,
@@ -32,3 +35,37 @@ func TestSystemPath(t *testing.T) {
}
}
}
+
+// #4: helpers start concurrently (capability queries beside a gate's
+// caffeinate): every registration lands, with no race (run with -race).
+func TestOwnConcurrentStarts(t *testing.T) {
+ o := &Own{}
+ var wg sync.WaitGroup
+ var mu sync.Mutex
+ var cmds []*exec.Cmd
+ for range 16 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ c := exec.Command("/bin/sleep", "1")
+ if err := o.Start(c, Platform); err != nil {
+ t.Error(err)
+ return
+ }
+ mu.Lock()
+ cmds = append(cmds, c)
+ mu.Unlock()
+ }()
+ }
+ wg.Add(1)
+ go func() { defer wg.Done(); _, _, _ = o.Snapshot(time.Now().Add(5*time.Second), Platform, nil) }()
+ wg.Wait()
+ for _, c := range cmds {
+ q, ok := Platform.Lookup(c.Process.Pid)
+ if !ok || !o.Owns(q.ID) {
+ t.Errorf("helper %d not on record", c.Process.Pid)
+ }
+ _ = c.Process.Kill()
+ _ = c.Wait()
+ }
+}
diff --git a/internal/runner/mac/procs_test.go b/internal/runner/mac/procs_test.go
index e18ea3eb..f3f08625 100644
--- a/internal/runner/mac/procs_test.go
+++ b/internal/runner/mac/procs_test.go
@@ -8,6 +8,7 @@ import (
"sync"
"syscall"
"testing"
+ "time"
)
// phantomPID is a process the table shows carrying a marker that no
@@ -27,8 +28,8 @@ func (p *phantom) ghost(m string) ProcInfo {
return ProcInfo{ID: ProcID{PID: phantomPID, Start: 1}, PPID: 1, PGID: phantomPID, SID: phantomPID, UID: os.Getuid(), Marker: m}
}
-func (p *phantom) List(markers []string) ([]ProcInfo, error) {
- list, err := p.Procs.List(markers)
+func (p *phantom) List(deadline time.Time, markers []string) ([]ProcInfo, error) {
+ list, err := p.Procs.List(deadline, markers)
if err != nil {
return nil, err
}
@@ -65,6 +66,12 @@ type table struct {
// lookup, when set, runs before each Lookup (a race between the
// listing and the re-check).
lookup func(t *table, pid int)
+ // unkillable rows survive every signal; after runs (lock held) once a
+ // signal has been delivered to pid.
+ unkillable map[int]bool
+ 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
}
type sent struct {
@@ -79,7 +86,7 @@ type sent struct {
// uid column is this test's uid, "self" in the pid column this process.
func parseTable(t *testing.T, rows string) *table {
t.Helper()
- tb := &table{procs: map[int]ProcInfo{}, paths: map[int]string{}, stubborn: map[int]bool{}}
+ tb := &table{procs: map[int]ProcInfo{}, paths: map[int]string{}, stubborn: map[int]bool{}, unkillable: map[int]bool{}}
for _, line := range strings.Split(rows, "\n") {
f := strings.Fields(line)
if len(f) == 0 || strings.HasPrefix(f[0], "#") {
@@ -114,11 +121,14 @@ func parseTable(t *testing.T, rows string) *table {
return tb
}
-func (tb *table) List(markers []string) ([]ProcInfo, error) {
+func (tb *table) List(_ time.Time, markers []string) ([]ProcInfo, error) {
tb.mu.Lock()
defer tb.mu.Unlock()
var out []ProcInfo
for _, q := range tb.procs {
+ if tb.hidden[q.PID] {
+ continue
+ }
if !slices.Contains(markers, q.Marker) {
q.Marker = ""
}
@@ -161,22 +171,79 @@ func (tb *table) Signal(pid int, sig syscall.Signal) error {
hit = append(hit, p)
}
}
+ if sig != 0 {
+ // Every attempt, even at nothing: a group signal sent on stale
+ // membership is the bug, whatever it reached.
+ tb.sent = append(tb.sent, sent{pid, sig})
+ }
if len(hit) == 0 {
return syscall.ESRCH
}
if sig == 0 {
+ // The kernel says EPERM for one pid we may not signal.
+ if q := tb.procs[pid]; pid > 0 && q.UID != os.Getuid() {
+ return syscall.EPERM
+ }
return nil
}
- tb.sent = append(tb.sent, sent{pid, sig})
for _, p := range hit {
+ if tb.unkillable[p] {
+ continue
+ }
if sig == syscall.SIGKILL || !tb.stubborn[p] {
delete(tb.procs, p)
delete(tb.paths, p)
}
}
+ if tb.after != nil {
+ tb.after(tb, pid, sig)
+ }
return nil
}
+// SessionGone: no row of any user is in session sid.
+func (tb *table) SessionGone(sid int) bool {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ for _, q := range tb.procs {
+ if q.SID == sid {
+ return false
+ }
+ }
+ return true
+}
+
+func (tb *table) remove(pid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ delete(tb.procs, pid)
+ delete(tb.paths, pid)
+}
+
+// reparent gives pid a new parent (its old one exited).
+func (tb *table) reparent(pid, ppid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ q := tb.procs[pid]
+ q.PPID = ppid
+ tb.procs[pid] = q
+}
+
+func (tb *table) mark(set *map[int]bool, pid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ if *set == nil {
+ *set = map[int]bool{}
+ }
+ (*set)[pid] = true
+}
+
+func (tb *table) unmark(set *map[int]bool, pid int) {
+ tb.mu.Lock()
+ defer tb.mu.Unlock()
+ delete(*set, pid)
+}
+
// signalled is every pid (negative: a group) the table was signalled at.
func (tb *table) signalled() []int {
tb.mu.Lock()
diff --git a/internal/runner/mac/sweep_test.go b/internal/runner/mac/sweep_test.go
index 307d5219..db074c61 100644
--- a/internal/runner/mac/sweep_test.go
+++ b/internal/runner/mac/sweep_test.go
@@ -140,9 +140,9 @@ func TestSweepNeverTouchesOtherUsers(t *testing.T) {
tb.add(row(70400, 70300, 70300, 70300, 4200, 0, "attempt-s"), "/usr/bin/login")
s := newScope(tb, []string{"attempt-s"}, u.before())
s.Groups[70300] = 3900
- list, _ := tb.List([]string{"attempt-s"})
+ list, _ := tb.List(time.Time{}, []string{"attempt-s"})
left = s.Targets(list, nil)
- if s.GroupsGone() {
+ if s.Gone() {
t.Error("proof given while another user holds a group id the attempt made")
}
})
@@ -151,35 +151,35 @@ func TestSweepNeverTouchesOtherUsers(t *testing.T) {
}
}
-// launchd's own agents (ppid 1, the kernel's path under /System or
-// /usr/libexec) are spared. A step that double-forked to launchd from
-// anywhere else is not: its own tree, a /System/Volumes path (every
-// user's data), a path that climbs out, an unknown path, a system path
-// whose parent is not launchd, or one in a session the attempt made.
-func TestSweepSystemAgentsByKernelPath(t *testing.T) {
+// #10 (the controller's ruling): no exemption by path. Every process of
+// the runner user that started during the turn and is not the runner's
+// own is the turn's: launchd-parented ones under /System, /usr/libexec
+// or /usr/sbin (on-demand agents launchd starts again when needed), a
+// double-fork from the step's own tree, a /System/Volumes path, a path
+// that climbs out, an unknown path. What was there before is untouched.
+func TestSweepKillsEveryNewProcessWhateverItsPath(t *testing.T) {
me := os.Getuid()
tb := parseTable(t, turnBegan)
sig := sweepTurn(t, tb, &Own{}, func(u *Turn) {
u.note(nil, span{81000: 5000})
tb.add(row(80100, 1, 80100, 80100, 5100, me, ""), "/System/Library/PrivateFrameworks/X.framework/XPCServices/Y.xpc/Contents/MacOS/Y")
tb.add(row(80200, 1, 80200, 80200, 5200, me, ""), "/usr/libexec/xpcproxy")
+ tb.add(row(80250, 1, 80250, 80250, 5250, me, ""), "/usr/sbin/cfprefsd")
tb.add(row(80300, 1, 80300, 80300, 5300, me, ""), "/Users/paulequipo/w/tree/.build/escape")
tb.add(row(80400, 1, 80400, 80400, 5400, me, ""), "/System/Volumes/Data/Users/paulequipo/escape")
tb.add(row(80500, 1, 80500, 80500, 5500, me, ""), "/System/Library/../../Users/paulequipo/escape")
tb.add(row(80600, 80300, 80600, 80600, 5600, me, ""), "/usr/libexec/xpcproxy")
tb.add(row(80700, 1, 80700, 80700, 5700, me, ""), "")
tb.add(row(80800, 1, 80800, 81000, 5800, me, ""), "/usr/libexec/xpcproxy")
- tb.add(row(80900, 1, 80900, 80900, 5900, me, ""), "/system/Library/escape")
})
- for _, pid := range []int{80100, 80200} {
- if slices.Contains(sig, pid) {
- t.Fatalf("a launchd system agent was signalled: %d in %v", pid, sig)
+ for _, pid := range []int{80100, 80200, 80250, 80300, 80400, 80500, 80600, 80700, 80800} {
+ if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
+ t.Fatalf("%d, new during the turn, was spared: %v", pid, sig)
}
}
- for _, pid := range []int{80300, 80400, 80500, 80600, 80700, 80800, 80900} {
- // 80800 is in a session the attempt made: ended with its group.
- if !slices.Contains(sig, pid) && !slices.Contains(sig, -pid) {
- t.Fatalf("%d escaped the sweep: %v", pid, sig)
+ for _, pid := range []int{40100, 40200, 40300} {
+ if slices.Contains(sig, pid) || slices.Contains(sig, -pid) {
+ t.Fatalf("%d, there before the turn, was signalled: %v", pid, sig)
}
}
}
diff --git a/internal/runner/mac/turns.go b/internal/runner/mac/turns.go
index 48596480..19faa38a 100644
--- a/internal/runner/mac/turns.go
+++ b/internal/runner/mac/turns.go
@@ -12,6 +12,8 @@ import (
"sync"
"syscall"
"time"
+
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
)
// Op is what a turn is for. Every operation that runs repository code,
@@ -67,16 +69,27 @@ type Turns struct {
sweep Procs
// own is the runner's own processes (runnerOwn; tests stand in).
own *Own
+ // ids reads runner processes' identities (the platform's table;
+ // tests stand in).
+ ids Procs
// 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
+ // debts is what unproven turns still owe (lock+".owed").
+ debts proc.Debts
}
// 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 { return &Turns{ch: make(chan struct{}, 1), lock: lock} }
+func NewTurns(lock string) *Turns {
+ t := &Turns{ch: make(chan struct{}, 1), lock: lock}
+ if lock != "" {
+ t.debts.Path = lock + ".owed"
+ }
+ return t
+}
// Sweep makes every turn sweep the runner user with p at its end: a
// Mac's turns (MachineProcs). A table that may not sweep (Linux outside
@@ -126,6 +139,8 @@ type turnRecord struct {
Markers []string `json:"markers,omitempty"`
Groups span `json:"groups,omitempty"`
Sessions span `json:"sessions,omitempty"`
+ // Killed is what the turn's stops signalled: each must be gone.
+ Killed []ProcID `json:"killed,omitempty"`
}
// Take waits for the turn and begins op: an earlier turn left unsettled
@@ -239,14 +254,18 @@ func (u *Turn) launch(marker string) error {
// 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) {
+func (u *Turn) note(groups, sessions span, killed ...ProcID) error {
u.mu.Lock()
defer u.mu.Unlock()
+ // Merged into a copy and kept only once written: a failed write is
+ // tried again at the next note, and the caller stops the operation.
+ rec := u.rec
+ rec.Groups, rec.Sessions, rec.Killed = rec.Groups.Clone(), rec.Sessions.Clone(), slices.Clone(rec.Killed)
grew := false
for _, m := range []struct {
to *span
from span
- }{{&u.rec.Groups, groups}, {&u.rec.Sessions, sessions}} {
+ }{{&rec.Groups, groups}, {&rec.Sessions, sessions}} {
if *m.to == nil {
*m.to = span{}
}
@@ -257,9 +276,20 @@ func (u *Turn) note(groups, sessions span) {
}
}
}
- if grew {
- _ = u.t.saveTurn(u.rec)
+ for _, id := range killed {
+ if !slices.Contains(rec.Killed, id) {
+ rec.Killed = append(rec.Killed, id)
+ grew = true
+ }
+ }
+ if !grew {
+ return nil
}
+ if err := u.t.saveTurn(rec); err != nil {
+ return err
+ }
+ u.rec = rec
+ return nil
}
// unprovenEnd keeps the record past Give: a launch's end is not proven.
@@ -297,7 +327,7 @@ func (t *Turns) begin(op Op) (*Turn, error) {
if !t.sweep.Sweeps() {
return nil, ErrNoSweep
}
- list, _, err := t.owned().Snapshot(t.sweep, nil)
+ list, _, err := t.owned().Snapshot(time.Now().Add(30*time.Second), t.sweep, nil)
if err != nil {
return nil, err
}
@@ -324,8 +354,11 @@ func (t *Turns) settle() error {
if err != nil || !ok {
return err
}
- if rec.Runner != selfID() && alive(rec.Runner) {
- return ErrUnsettled
+ 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 {
+ return ErrUnsettled
+ }
}
procs := t.table()
if rec.Sweep && (t.sweep == nil || !t.sweep.Sweeps()) {
@@ -345,25 +378,26 @@ func (t *Turns) settle() error {
for id, at := range rec.Sessions {
s.Sessions[id] = at
}
+ for _, id := range rec.Killed {
+ s.Killed[id] = true
+ }
limit := t.Settle
if limit <= 0 {
limit = 30 * time.Second
}
- deadline := time.Now().Add(limit)
- for {
- list, own, err := t.owned().Snapshot(procs, rec.Markers)
- if err == nil {
- left := s.Targets(list, own)
- if len(left) == 0 {
- return t.dropTurn(rec.ID)
- }
- s.Kill(left, syscall.SIGKILL)
- }
- if time.Now().After(deadline) {
- return ErrUnsettled
+ switch s.Settle(t.owned(), time.Now().Add(limit), 0, func() bool { return true }, nil) {
+ case proc.Proven:
+ return t.dropTurn(rec.ID)
+ case proc.Owed:
+ // Nothing of the runner user's is left to kill, so the Mac may
+ // take turns again; what another user now holds stays owed by
+ // the attempt, and its proof waits for it.
+ if err := t.debts.Owe(s.Owe()); err != nil {
+ return errors.Join(ErrUnsettled, err)
}
- time.Sleep(100 * time.Millisecond)
+ return t.dropTurn(rec.ID)
}
+ return ErrUnsettled
}
// unsettledFor: the stored turn record names attempt (its leftovers are
@@ -451,7 +485,7 @@ func (t *Turns) saveTurn(rec turnRecord) error {
t.mu.Lock()
c := rec
c.Before, c.Markers = slices.Clone(rec.Before), slices.Clone(rec.Markers)
- c.Groups, c.Sessions = cloneSpan(rec.Groups), cloneSpan(rec.Sessions)
+ c.Groups, c.Sessions = rec.Groups.Clone(), rec.Sessions.Clone()
t.mem = &c
t.mu.Unlock()
return nil
@@ -460,7 +494,7 @@ func (t *Turns) saveTurn(rec turnRecord) error {
if err != nil {
return err
}
- return writeDurably(p, raw)
+ return proc.WriteDurably(p, raw)
}
func (t *Turns) loadTurn() (turnRecord, bool, error) {
@@ -505,36 +539,6 @@ func (t *Turns) dropTurn(id string) error {
return nil
}
-func cloneSpan(s span) span {
- if s == nil {
- return nil
- }
- c := span{}
- for k, v := range s {
- c[k] = v
- }
- return c
-}
-
-// writeDurably writes raw beside p, syncs it and renames it over p.
-func writeDurably(p string, raw []byte) error {
- f, err := os.OpenFile(p+".new", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
- if err != nil {
- return err
- }
- _, err = f.Write(raw)
- if serr := f.Sync(); err == nil {
- err = serr
- }
- if cerr := f.Close(); err == nil {
- err = cerr
- }
- if err != nil {
- return err
- }
- return os.Rename(p+".new", p)
-}
-
var self struct {
once sync.Once
id ProcID
@@ -552,13 +556,11 @@ func selfID() ProcID {
return self.id
}
-// alive: the process id names is still running (same pid, same start).
-func alive(id ProcID) bool {
- if id.PID <= 0 {
- return false
+func (t *Turns) identities() Procs {
+ if t != nil && t.ids != nil {
+ return t.ids
}
- q, ok := platformProcs.Lookup(id.PID)
- return ok && q.ID == id
+ return platformProcs
}
func (t *Turns) pending() string {
@@ -592,7 +594,7 @@ func (t *Turns) writePending(r pendingRecord) error {
if err != nil {
return err
}
- return writeDurably(p, raw)
+ return proc.WriteDurably(p, raw)
}
// readPending is the record an earlier attempt left; ok is false when
@@ -621,10 +623,16 @@ func (t *Turns) readPending() (r pendingRecord, ok bool, err error) {
// the process that wrote it is gone (or was older than the owner field).
// Never another turn of a live owner.
func (t *Turns) mayFinish(u *Turn, r pendingRecord) bool {
- if r.Runner.PID == 0 || !alive(r.Runner) {
+ if r.Runner.PID == 0 {
return true
}
- return r.Runner == selfID() && u.owns(r.Attempt)
+ if r.Runner == selfID() {
+ return u.owns(r.Attempt)
+ }
+ // A restart only once the writer is surely gone: an identity that
+ // cannot be read is not a dead one.
+ alive, known := proc.Alive(t.identities(), r.Runner)
+ return known && !alive
}
// dropPending removes the record once its cleanup is done.
diff --git a/internal/runner/thin/mac_sweep_linux_test.go b/internal/runner/thin/mac_sweep_linux_test.go
new file mode 100644
index 00000000..75d7f8dd
--- /dev/null
+++ b/internal/runner/thin/mac_sweep_linux_test.go
@@ -0,0 +1,74 @@
+//go:build linux
+
+package thin
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/mac/proc"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+)
+
+// #2 (Astra round 1): the worker's git (index-pack, checkout) is the
+// runner's own helper. A probe's turn that ends while the worker prepares
+// a step sweeps the runner user, and must leave that git running. The
+// table is scoped to this test's markers (a shared Linux machine).
+func TestProbeEndSparesWorkerGit(t *testing.T) {
+ dir := t.TempDir()
+ git, pidFile := filepath.Join(dir, "git"), filepath.Join(dir, "pid")
+ script := "#!/bin/sh\necho $$ >> " + pidFile + "\n[ -n \"$GIT_INDEX_FILE\" ] && touch \"$GIT_INDEX_FILE\"\nsleep 1\necho ok\n"
+ if err := os.WriteFile(git, []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ marker := "checks/own-" + strconv.Itoa(os.Getpid())
+ w := &Worker{Engine: &Engineer{O: ClaudeOptions{Runner: runner.Config{GitPath: git}}}, marker: marker}
+ turns := mac.NewTurns("").Sweep(proc.Scoped("EQUIPO_ATTEMPT="+marker, "EQUIPO_ATTEMPT="+marker+"-probe"))
+ for name, prep := range map[string]func(context.Context) error{
+ "index-pack": func(ctx context.Context) error {
+ out, err := w.git(ctx, strings.NewReader("PACK"), "index-pack", "--stdin")
+ if err == nil && out != "ok" {
+ t.Errorf("git said %q", out)
+ }
+ return err
+ },
+ "checkout": func(ctx context.Context) error {
+ return w.checkout(ctx, workspace.TaskTree{Dir: filepath.Join(t.TempDir(), "tree"), GitDir: dir}, "0123456789abcdef0123456789abcdef01234567")
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ _ = os.Remove(pidFile)
+ u, err := turns.Take(context.Background(), mac.OpProbe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer u.Give()
+ x := &mac.Executor{Turns: turns, Grace: 50 * time.Millisecond, Settle: 3 * time.Second, Poll: 20 * time.Millisecond}
+ run, err := x.Start(u.Context(context.Background()), mac.Command{Argv: []string{"/bin/true"}, Env: []string{"PATH=/usr/bin:/bin", "EQUIPO_ATTEMPT=" + marker + "-probe"}}, marker+"-probe", func(string) error { return nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := make(chan error, 1)
+ go func() { got <- prep(context.Background()) }()
+ for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ if raw, _ := os.ReadFile(pidFile); len(raw) > 0 {
+ break
+ }
+ }
+ time.Sleep(100 * time.Millisecond)
+ if !run.Stop() {
+ t.Fatal("the probe's end not proven")
+ }
+ if err := <-got; err != nil {
+ t.Fatalf("the worker's git was swept: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go
index 5b1bb8be..c7b723e0 100644
--- a/internal/runner/thin/worker.go
+++ b/internal/runner/thin/worker.go
@@ -266,8 +266,7 @@ func (w *Worker) git(ctx context.Context, stdin io.Reader, args ...string) (stri
cmd.Env = append(cmd.Env, k+"="+v)
}
cmd.Env = append(cmd.Env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker)
- out, err := cmd.Output()
- return strings.TrimSpace(string(out)), err
+ return ownOutput(cmd)
}
// index adds the pack to the repository's store and requires that it
@@ -305,7 +304,8 @@ func (w *Worker) checkout(ctx context.Context, t workspace.TaskTree, sha string)
}
cmd.Env = append(cmd.Env, append(env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker)...)
cmd.Dir = t.Dir
- return cmd.Run()
+ _, err := ownOutput(cmd)
+ return err
}
if err := run("read-tree", "--end-of-options", sha); err != nil {
return err
@@ -315,3 +315,16 @@ func (w *Worker) checkout(ctx context.Context, t workspace.TaskTree, sha string)
}
return os.Remove(index)
}
+
+// ownOutput runs cmd as the runner's own helper (mac.StartOwn), so the
+// sweep at the end of a Mac turn (a probe run, say) spares it, and
+// returns its output, trimmed.
+func ownOutput(cmd *exec.Cmd) (string, error) {
+ var out strings.Builder
+ cmd.Stdout = &out
+ if err := mac.StartOwn(cmd); err != nil {
+ return "", err
+ }
+ err := cmd.Wait()
+ return strings.TrimSpace(out.String()), err
+}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index 61e512f1..fe573202 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -355,6 +355,10 @@ type Probe struct {
Detail string `json:"detail"`
}
+// ProbeDetailTurnBusy is a probe's detail when the probe run could not
+// take the Mac's turn: a code, which the instance words (copy.go).
+const ProbeDetailTurnBusy = "turn_busy"
+
// Probe verdicts. ProbeDenied is P2's pass: every hostile attempt was
// denied, so checks run in the sandbox; anything else and they run
// outside it, labelled so (Paul's ruling 2).