oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "context"
5 "errors"
6 "os"
7 "path/filepath"
8 "slices"
9 "sync/atomic"
10 "syscall"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/runner/mac/proc"
15)
16
17// Fix round 2 (Astra round 2) regressions on synthetic tables: rows
18// made up 2026-11-28 in the darwin table's shape (see sweep_test.go).
19
20// stopReads calls fn on each table read the stop makes (the stop asks
21// for markers; the poll does not), with its number.
22func stopReads(tb *table, fn func(tb *table, k int)) {
23 k := 0
24 tb.afterList = func(tb *table, _ int, markers []string) {
25 if len(markers) > 0 {
26 k++
27 fn(tb, k)
28 }
29 }
30}
31
32// #7: the final note is part of the proof: a note that returns after
33// the deadline means no proof.
34func TestProofDeadlineCoversTheFinalNote(t *testing.T) {
35 me := os.Getuid()
36 tb := parseTable(t, turnBegan)
37 turns, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
38 defer u.Give()
39 var slow atomic.Bool
40 turns.beforeWrite = func() error {
41 if slow.Load() {
42 time.Sleep(400 * time.Millisecond)
43 }
44 return nil
45 }
46 tb.add(row(94100, 1, 94100, 94100, 5000, me, ""), "/Users/paulequipo/w/a")
47 slow.Store(true)
48 if run.Stop() {
49 t.Fatal("proven though its final note returned after the deadline")
50 }
51}
52
53// #7: Verify has one deadline for settling the turn, the record and the
54// debts: recovery that spends most of it settling the turn has only the
55// rest for the recorded group.
56func TestVerifyHasOneDeadline(t *testing.T) {
57 me := os.Getuid()
58 tb := parseTable(t, turnBegan)
59 tb.add(row(94300, 1, 94300, 94300, 900, me, ""), "/Users/paulequipo/w/old")
60 list, _ := tb.List(time.Time{}, nil)
61 var before []ProcID
62 for _, q := range list {
63 before = append(before, q.ID)
64 }
65 tb.add(row(94200, 1, 94200, 94200, 5000, me, ""), "/Users/paulequipo/w/left")
66 tb.mark(&tb.unkillable, 94200)
67 turns := NewTurns("").Sweep(tb)
68 turns.own, turns.Settle = &Own{}, 300*time.Millisecond
69 x := &Executor{Turns: turns, Settle: 300 * time.Millisecond}
70 if err := turns.saveTurn(turnRecord{ID: "dead", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-d"}, Complete: true}); err != nil {
71 t.Fatal(err)
72 }
73 time.AfterFunc(50*time.Millisecond, func() { tb.unmark(&tb.unkillable, 94200) })
74 time.AfterFunc(350*time.Millisecond, func() { tb.remove(94300) })
75 if x.Verify(RecordID(94300, "attempt-d")) {
76 t.Fatal("proven after its one deadline (its recorded group ended at 350 ms)")
77 }
78 if !x.Verify(RecordID(94300, "attempt-d")) {
79 t.Fatal("not proven on a later try once everything ended")
80 }
81}
82
83// #8 and the follow-up: the poll finds a session, its write fails, and
84// what is left of it is another user's (a setuid program) and survives a
85// restart. The record on disk was never completed. A restart in the same
86// boot proves nothing by itself: while a process of the runner user that
87// nothing accounts for runs, the end stays unproven and the runner says
88// how many; once only accounted processes remain, the idle read proves
89// it (a reboot would too; see clear_test.go).
90func TestIncompleteRecordNeedsAClearance(t *testing.T) {
91 me := os.Getuid()
92 lock := filepath.Join(t.TempDir(), "lock")
93 tb := parseTable(t, turnBegan)
94 turns := NewTurns(lock).Sweep(tb)
95 turns.own, turns.Settle = &Own{}, 200*time.Millisecond
96 u, err := turns.Take(context.Background(), OpEngineering)
97 if err != nil {
98 t.Fatal(err)
99 }
100 x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond}
101 run, err := x.Start(u.Context(context.Background()), Command{Argv: []string{"/bin/true"}}, "attempt-i", func(string) error { return nil })
102 if err != nil {
103 t.Fatal(err)
104 }
105 <-run.Exited()
106 var failing atomic.Bool
107 turns.beforeWrite = func() error {
108 if failing.Load() {
109 return errors.New("disk full")
110 }
111 return nil
112 }
113 failing.Store(true)
114 residue := row(95002, 1, 95002, 95001, 7000, 0, "")
115 tb.after = func(tb *table, pid int, sig syscall.Signal) {
116 if pid == 95001 && tb.procs[95002].PID == 0 {
117 tb.procs[95002] = residue
118 tb.paths[95002] = "/usr/bin/login"
119 }
120 }
121 // In the attempt's group, a session of its own: the poll finds it.
122 tb.add(row(95001, 1, run.pgid, 95001, 6001, me, ""), "/Users/paulequipo/w/s")
123 select {
124 case <-run.Aborted():
125 case <-time.After(3 * time.Second):
126 t.Fatal("not stopped when its record could not be written")
127 }
128 if run.Stop() {
129 t.Fatal("proven with its record unwritten")
130 }
131 u.Give()
132 failing.Store(false)
133 next := NewTurns(lock).Sweep(tb)
134 next.own, next.Settle = &Own{}, 200*time.Millisecond
135 nx := &Executor{Turns: next, Settle: 200 * time.Millisecond}
136 v, err := next.Take(context.Background(), OpCheck)
137 if err != nil {
138 t.Fatalf("the restarted runner is blocked: %v", err)
139 }
140 v.Give()
141 tb.add(row(95100, 1, 95100, 95100, 9000, me, ""), "/Users/paulequipo/w/stray")
142 if nx.Verify(run.ID()) {
143 t.Fatal("recovery proved an incomplete record with an unaccounted process running")
144 }
145 if code, n := next.Unproven(); code != "processes_left" || n != 1 {
146 t.Fatalf("the runner said %q, %d", code, n)
147 }
148 tb.remove(95002)
149 tb.remove(95100)
150 if !nx.Verify(run.ID()) || next.Incomplete() {
151 t.Fatal("not proven once an idle read accounts for every process")
152 }
153}
154
155// #10: the relaunch cutoff is the moment of the first kill pass (the
156// table's clock, just before the first signal), not the newest start in
157// that pass's read: a system agent born between that read and the first
158// signal predates the kill pass, and is killed.
159func TestRelaunchCutoffIsTheKillPassStart(t *testing.T) {
160 me := os.Getuid()
161 tb := parseTable(t, turnBegan)
162 _, u, _, run := liveTurn(t, tb, &Own{}, time.Second)
163 defer u.Give()
164 tb.add(row(83100, 1, 83100, 83100, 4000, me, ""), "/Users/paulequipo/w/first")
165 stopReads(tb, func(tb *table, k int) {
166 if k == 1 {
167 tb.procs[83200] = row(83200, 1, 83200, 83200, 5050, me, "")
168 tb.paths[83200] = "/usr/libexec/trustd"
169 tb.clock = 5100
170 }
171 })
172 if !run.Stop() {
173 t.Fatalf("not proven: %v", tb.signalled())
174 }
175 if sig := tb.signalled(); !slices.Contains(sig, 83200) && !slices.Contains(sig, -83200) || tb.has(83200) {
176 t.Fatalf("an agent born before the first signal was taken for a relaunch: %v", tb.signalled())
177 }
178}
179
180// #10: discovery is the one read after the first kill pass. Later reads
181// add nothing to the kill set, but any process of the runner user born
182// during the turn (here as the leader dies of the SIGKILL after
183// discovery), not the runner's own and not a launchd relaunch, keeps
184// both the proof and the Mac's clearance withheld: the turn's record
185// stays, and the next turn's settling kills it.
186func TestDiscoveryIsOneSnapshot(t *testing.T) {
187 me := os.Getuid()
188 for _, c := range []struct {
189 name string
190 late ProcInfo
191 }{
192 {"unrelated", row(83400, 1, 83400, 83400, 9000, me, "")},
193 {"in a killed process's group", row(83600, 1, 83500, 83600, 9000, me, "")},
194 } {
195 t.Run(c.name, func(t *testing.T) {
196 tb := parseTable(t, turnBegan)
197 turns, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
198 tb.add(row(83500, 1, 83500, 83500, 4000, me, ""), "/Users/paulequipo/w/lead")
199 // It needs SIGKILL, sent once the grace has passed.
200 tb.mark(&tb.stubborn, 83500)
201 tb.after = func(tb *table, pid int, sig syscall.Signal) {
202 if (pid == 83500 || pid == -83500) && sig == syscall.SIGKILL && tb.procs[c.late.PID].PID == 0 {
203 tb.procs[c.late.PID] = c.late
204 tb.paths[c.late.PID] = "/Users/paulequipo/w/late"
205 }
206 }
207 if run.Stop() {
208 t.Fatalf("proven with %d alive (signalled %v)", c.late.PID, tb.signalled())
209 }
210 if slices.Contains(tb.signalled(), c.late.PID) {
211 t.Fatalf("a read after discovery added %d: %v", c.late.PID, tb.signalled())
212 }
213 u.Give()
214 if _, ok, _ := turns.loadTurn(); !ok {
215 t.Fatal("the turn's record went with a process of the turn alive")
216 }
217 next, err := turns.Take(context.Background(), OpCheck)
218 if err != nil {
219 t.Fatalf("the next turn did not settle it: %v", err)
220 }
221 next.Give()
222 if tb.has(c.late.PID) {
223 t.Fatalf("%d survived the next turn's settling", c.late.PID)
224 }
225 })
226 }
227}
228
229// flaky's List works once and then fails.
230type flaky struct {
231 *table
232 n atomic.Int32
233}
234
235func (f *flaky) List(deadline time.Time, markers []string) ([]ProcInfo, error) {
236 if f.n.Add(1) > 1 {
237 return nil, errors.New("sysctl failed")
238 }
239 return f.table.List(deadline, markers)
240}
241
242// #14: a failed read voids what an earlier read showed: an empty read,
243// then failed reads (a process of the runner user appearing meanwhile)
244// is never a clearance to release the Mac.
245func TestFailedScanVoidsClearance(t *testing.T) {
246 me := os.Getuid()
247 tb := &flaky{table: parseTable(t, turnBegan)}
248 list, _ := tb.table.List(time.Time{}, nil)
249 var before []ProcID
250 for _, q := range list {
251 before = append(before, q.ID)
252 }
253 tb.add(row(96001, 1, 96001, 96001, 7000, 501, ""), "/bin/zsh")
254 tb.table.afterList = func(tb *table, _ int, _ []string) {
255 tb.procs[96100] = row(96100, 1, 96100, 96100, 7100, me, "")
256 tb.paths[96100] = "/Users/paulequipo/w/survivor"
257 }
258 s := newScope(tb, []string{"attempt-f"}, before)
259 s.Groups[96001] = 1
260 if out := s.Settle(&Own{}, time.Now().Add(300*time.Millisecond), 0, func() bool { return true }, nil); out != proc.Left {
261 t.Fatalf("settled %v after failed reads, want left", out)
262 }
263}
264
265// The proof waits for every target, also one that leads no group or
266// session the obligations would hold: the child left by a double fork,
267// its session leader gone, that will not die.
268func TestProofWaitsForEveryTarget(t *testing.T) {
269 me := os.Getuid()
270 tb := parseTable(t, turnBegan)
271 _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
272 defer u.Give()
273 tb.add(row(84100, 1, 84000, 84000, 5000, me, ""), "/Users/paulequipo/w/orphan")
274 tb.mark(&tb.unkillable, 84100)
275 if run.Stop() {
276 t.Fatal("proven over with a double-forked child alive")
277 }
278}
279
280// #7: the pending user-temp cleanup's proof read is under the same one
281// deadline: recovery that spends most of it settling the turn has only
282// the rest for the cleanup's recorded group.
283func TestVerifyHasOneDeadlineWithCleanup(t *testing.T) {
284 me := os.Getuid()
285 tb := parseTable(t, turnBegan)
286 tb.add(row(94400, 1, 94400, 94400, 900, me, ""), "/Users/paulequipo/w/old")
287 list, _ := tb.List(time.Time{}, nil)
288 var before []ProcID
289 for _, q := range list {
290 before = append(before, q.ID)
291 }
292 tb.add(row(94200, 1, 94200, 94200, 5000, me, ""), "/Users/paulequipo/w/left")
293 tb.mark(&tb.unkillable, 94200)
294 turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(tb)
295 turns.own, turns.Settle = &Own{}, 300*time.Millisecond
296 _, temp := userTempFixture(t)
297 x := &Executor{Turns: turns, Settle: 300 * time.Millisecond, UserTemp: temp}
298 if err := turns.saveTurn(turnRecord{ID: "dead", Op: OpCheck, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-c"}, Complete: true}); err != nil {
299 t.Fatal(err)
300 }
301 s, err := openTemp(temp, nil)
302 if err != nil {
303 t.Fatal(err)
304 }
305 if err := turns.writePending(pendingRecord{Attempt: "attempt-c", PGID: 94400, Before: s.before, Runner: selfID()}); err != nil {
306 t.Fatal(err)
307 }
308 s.close()
309 time.AfterFunc(50*time.Millisecond, func() { tb.unmark(&tb.unkillable, 94200) })
310 time.AfterFunc(350*time.Millisecond, func() { tb.remove(94400) })
311 if x.Verify(RecordID(0, "attempt-c")) {
312 t.Fatal("proven after its one deadline (the cleanup's group ended at 350 ms)")
313 }
314 if !x.Verify(RecordID(0, "attempt-c")) || turns.Pending() {
315 t.Fatal("not proven, or not cleaned, on a later try once everything ended")
316 }
317}
318
319// #8: once a launch's evidence could not be written, no other launch
320// starts in that turn, so no later stop can mark the record complete;
321// after a restart the first launch is never proven over.
322func TestFailedLaunchEndsTheTurnsLaunches(t *testing.T) {
323 me := os.Getuid()
324 lock := filepath.Join(t.TempDir(), "lock")
325 tb := parseTable(t, turnBegan)
326 turns := NewTurns(lock).Sweep(tb)
327 turns.own, turns.Settle = &Own{}, 200*time.Millisecond
328 u, err := turns.Take(context.Background(), OpEngineering)
329 if err != nil {
330 t.Fatal(err)
331 }
332 ctx := u.Context(context.Background())
333 x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond}
334 a, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-a", func(string) error { return nil })
335 if err != nil {
336 t.Fatal(err)
337 }
338 <-a.Exited()
339 var failing atomic.Bool
340 turns.beforeWrite = func() error {
341 if failing.Load() {
342 return errors.New("disk full")
343 }
344 return nil
345 }
346 failing.Store(true)
347 tb.after = func(tb *table, pid int, sig syscall.Signal) {
348 if pid == 97001 && tb.procs[97002].PID == 0 {
349 tb.procs[97002] = row(97002, 1, 97002, 97001, 7000, 0, "")
350 tb.paths[97002] = "/usr/bin/login"
351 }
352 }
353 tb.add(row(97001, 1, a.pgid, 97001, 6001, me, ""), "/Users/paulequipo/w/s")
354 select {
355 case <-a.Aborted():
356 case <-time.After(3 * time.Second):
357 t.Fatal("not stopped when its record could not be written")
358 }
359 if a.Stop() {
360 t.Fatal("proven with its record unwritten")
361 }
362 // The disk recovers; the turn takes no other launch.
363 failing.Store(false)
364 b, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-b", func(string) error { return nil })
365 if err == nil {
366 <-b.Exited()
367 b.Stop()
368 t.Error("a launch started after the turn lost a launch's evidence")
369 }
370 u.Give()
371 next := NewTurns(lock).Sweep(tb)
372 next.own, next.Settle = &Own{}, 200*time.Millisecond
373 v, err := next.Take(context.Background(), OpCheck)
374 if err != nil {
375 t.Fatalf("the restarted runner is blocked: %v", err)
376 }
377 v.Give()
378 // An unaccounted process: no idle clearance.
379 tb.add(row(97100, 1, 97100, 97100, 9000, me, ""), "/Users/paulequipo/w/stray")
380 nx := &Executor{Turns: next, Settle: 200 * time.Millisecond}
381 if nx.Verify(a.ID()) || !next.Incomplete() {
382 t.Fatal("the first launch was proven over, or the runner does not say it cannot be")
383 }
384}
385
386// #8: the record is complete only when every launch of the turn has
387// finished its own durable writes: a launch not yet stopped keeps it
388// incomplete whatever another launch's stop wrote.
389func TestCompleteOnlyWhenEveryLaunchFinished(t *testing.T) {
390 tb := parseTable(t, turnBegan)
391 turns := NewTurns("").Sweep(tb)
392 turns.own, turns.Settle = &Own{}, 200*time.Millisecond
393 u, err := turns.Take(context.Background(), OpEngineering)
394 if err != nil {
395 t.Fatal(err)
396 }
397 defer u.Give()
398 ctx := u.Context(context.Background())
399 x := &Executor{Turns: turns, Grace: 20 * time.Millisecond, Settle: 200 * time.Millisecond, Poll: 10 * time.Millisecond}
400 a, err := x.Start(ctx, Command{Argv: []string{"/bin/sleep", "0.5"}}, "attempt-a", func(string) error { return nil })
401 if err != nil {
402 t.Fatal(err)
403 }
404 b, err := x.Start(ctx, Command{Argv: []string{"/bin/true"}}, "attempt-b", func(string) error { return nil })
405 if err != nil {
406 t.Fatal(err)
407 }
408 <-b.Exited()
409 b.Stop()
410 if rec, ok, _ := turns.loadTurn(); !ok || rec.Complete {
411 t.Fatalf("complete with a launch not finished: %+v", rec)
412 }
413 <-a.Exited()
414 a.Stop()
415 if rec, ok, _ := turns.loadTurn(); !ok || !rec.Complete {
416 t.Fatalf("not complete once every launch finished: %+v", rec)
417 }
418}
419
420// #10: settling an earlier turn never releases the Mac (Owed) while a
421// process of the runner user born during that turn lives, though its
422// check reads add nothing: here a child born into a killed leader's
423// group after the settle's discovery read.
424func TestSettleKeepsTheTurnWhileALateProcessLives(t *testing.T) {
425 me := os.Getuid()
426 tb := parseTable(t, turnBegan)
427 list, _ := tb.List(time.Time{}, nil)
428 var before []ProcID
429 for _, q := range list {
430 before = append(before, q.ID)
431 }
432 turns := NewTurns("").Sweep(tb)
433 turns.own, turns.Settle = &Own{}, 300*time.Millisecond
434 if err := turns.saveTurn(turnRecord{ID: "old", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-o"}, Complete: true}); err != nil {
435 t.Fatal(err)
436 }
437 tb.add(row(83700, 1, 83700, 83700, 4000, me, ""), "/Users/paulequipo/w/lead")
438 tb.mark(&tb.unkillable, 83700)
439 signals := 0
440 tb.after = func(tb *table, pid int, sig syscall.Signal) {
441 if pid != 83700 && pid != -83700 {
442 return
443 }
444 // Signalled at the first kill pass and again after discovery:
445 // then its last fork, and it dies.
446 if signals++; signals == 3 && tb.procs[83701].PID == 0 {
447 tb.procs[83701] = row(83701, 1, 83700, 83701, 9000, me, "")
448 tb.paths[83701] = "/Users/paulequipo/w/late"
449 delete(tb.unkillable, 83700)
450 delete(tb.procs, 83700)
451 }
452 }
453 if err := turns.settle(time.Now().Add(turns.settleLimit())); err == nil {
454 t.Fatal("the Mac was released with a process of the earlier turn alive")
455 }
456 if _, ok, _ := turns.loadTurn(); !ok {
457 t.Fatal("the earlier turn's record went")
458 }
459}
460
461// #10: the group a killed process led stays an obligation after it
462// dies: a child born into it after discovery that is another user's (a
463// setuid program), which no read lists, still keeps the proof waiting,
464// though it is never signalled.
465func TestLedGroupObligationOutlivesItsLeader(t *testing.T) {
466 me := os.Getuid()
467 tb := parseTable(t, turnBegan)
468 _, u, _, run := liveTurn(t, tb, &Own{}, 300*time.Millisecond)
469 defer u.Give()
470 tb.add(row(83800, 1, 83800, 83800, 4000, me, ""), "/Users/paulequipo/w/lead")
471 tb.mark(&tb.stubborn, 83800)
472 tb.after = func(tb *table, pid int, sig syscall.Signal) {
473 if (pid == 83800 || pid == -83800) && sig == syscall.SIGKILL && tb.procs[83801].PID == 0 {
474 tb.procs[83801] = row(83801, 1, 83800, 83801, 9000, 0, "")
475 tb.paths[83801] = "/usr/bin/login"
476 }
477 }
478 if run.Stop() {
479 t.Fatal("proven while another user's child is in a group a killed process led")
480 }
481 if slices.Contains(tb.signalled(), 83801) {
482 t.Fatal("another user's process was signalled")
483 }
484}
485