oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build linux
2
3package mac
4
5import (
6 "context"
7 "errors"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "slices"
12 "strconv"
13 "strings"
14 "syscall"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner/containment"
19 "amadan.net/oficina/equipo/internal/runner/mac/proc"
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/runner/provider/claude"
22)
23
24// These tests run real processes on Linux through the /pr table. The
25// machine is shared, so every table here is scoped: it lists, and
26// signals, only processes whose environment carries this test's
27// EQUIPO_TEST_SCOPE nonce (or its own unique marker). The runner-user
28// sweep therefore sees the test's processes as a Mac's turn sees the
29// runner user's, and can never reach anyone else's.
30
31type launchRig struct {
32 t *testing.T
33 nonce string
34 procs Procs
35 turns *Turns
36 x *Executor
37}
38
39func newLaunchRig(t *testing.T, extra ...string) *launchRig {
40 t.Helper()
41 nonce := token()[:12]
42 procs := proc.Scoped(append([]string{proc.ScopeEnv + "=" + nonce}, extra...)...)
43 turns := NewTurns(filepath.Join(t.TempDir(), "lock")).Sweep(procs)
44 turns.Settle = 3 * time.Second
45 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}}
46 t.Cleanup(func() {
47 // Whatever of the test's own is left (a failed test): by scope.
48 if list, err := procs.List(time.Now().Add(5*time.Second), nil); err == nil {
49 for _, q := range list {
50 _ = procs.Signal(q.PID, syscall.SIGKILL)
51 }
52 }
53 })
54 return r
55}
56
57func (r *launchRig) env(more ...string) []string {
58 return append([]string{"PATH=/usr/bin:/bin", proc.ScopeEnv + "=" + r.nonce}, more...)
59}
60
61func (r *launchRig) take(op Op) (context.Context, *Turn) {
62 r.t.Helper()
63 u, err := r.turns.Take(context.Background(), op)
64 if err != nil {
65 r.t.Fatal(err)
66 }
67 return u.Context(context.Background()), u
68}
69
70// start runs argv in a session of its own with env (reaped when it
71// ends, so a dead one is not a zombie in a group).
72func (r *launchRig) start(env []string, argv ...string) *exec.Cmd {
73 r.t.Helper()
74 c := exec.Command(argv[0], argv[1:]...)
75 c.Env = env
76 c.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
77 if err := c.Start(); err != nil {
78 r.t.Fatal(err)
79 }
80 go func() { _ = c.Wait() }()
81 r.waitListed(c.Process.Pid)
82 return c
83}
84
85// waitListed waits until the table shows pid (the kernel shows a new
86// environment a moment after the exec).
87func (r *launchRig) waitListed(pid int) ProcInfo {
88 r.t.Helper()
89 for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
90 if q, ok := r.procs.Lookup(pid); ok {
91 return q
92 }
93 }
94 r.t.Fatalf("pid %d never listed", pid)
95 return ProcInfo{}
96}
97
98func gone(pid int) bool { return syscall.Kill(pid, 0) == syscall.ESRCH }
99
100func hasKey(m span, k int) bool { _, ok := m[k]; return ok }
101
102// waitPID reads a pid a script wrote to file.
103func waitPID(t *testing.T, file string) int {
104 t.Helper()
105 for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
106 raw, _ := os.ReadFile(file)
107 if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
108 return pid
109 }
110 }
111 t.Fatalf("no pid in %s", file)
112 return 0
113}
114
115// engLaunch is the Engineering launch rig with body as the pinned CLI,
116// a unique marker, and a scoped table that sees what carries it.
117func engLaunch(t *testing.T, body string) (*engRig, *launchRig) {
118 t.Helper()
119 er := newEngRigWith(t, []byte(body))
120 er.in.Attempt = "attempt-" + token()[:12]
121 return er, newLaunchRig(t, "EQUIPO_ATTEMPT="+er.in.Attempt)
122}
123
124// The marker is on the step row (and the turn's record) before the CLI
125// starts; the group once it exists. A marker that cannot be written
126// starts nothing; a group that cannot be stops the CLI at once, proven.
127func TestEngineeringLaunchRecordsMarkerThenGroup(t *testing.T) {
128 er, r := engLaunch(t, "#!/bin/sh\ntouch \"$TMPDIR/started\"\ncat <&3 >/dev/null\nread line\n")
129 p := er.policy()
130 argv := claude.DarwinArgv(p)
131 started := filepath.Join(er.in.Scratch, "started")
132 marker := er.in.Attempt
133 ctx, turn := r.take(OpEngineering)
134 defer turn.Give()
135 launch := func(fail int) (provider.Process, []string, error) {
136 var ids []string
137 pctx, kill := context.WithCancel(ctx)
138 t.Cleanup(kill)
139 s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
140 pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, argv, func(_ context.Context, rec containment.Record) error {
141 ids = append(ids, rec.ID)
142 if len(ids) == 1 {
143 if exists(started) {
144 t.Error("the CLI started before its marker was on record")
145 }
146 if rec, ok, _ := r.turns.loadTurn(); !ok || !slices.Contains(rec.Markers, marker) {
147 t.Error("the turn's record lacks the marker at the first write")
148 }
149 }
150 if len(ids) == 2 {
151 pgid, _, _ := parseRecord(rec.ID)
152 if pgid <= 1 || syscall.Kill(-pgid, 0) != nil {
153 t.Errorf("group %d recorded before it existed", pgid)
154 }
155 }
156 if len(ids) == fail {
157 return errors.New("disk full")
158 }
159 return nil
160 })
161 return pr, ids, err
162 }
163 pr, ids, err := launch(0)
164 if err != nil {
165 t.Fatal(err)
166 }
167 if len(ids) != 2 || ids[0] != RecordID(0, marker) || !strings.HasPrefix(ids[1], "pg:") || !strings.HasSuffix(ids[1], ":"+marker) || ids[1] == ids[0] || pr.ID() != ids[1] {
168 t.Fatalf("records %v, process %s", ids, pr.ID())
169 }
170 pgid, _, _ := parseRecord(ids[1])
171 if rec, ok, _ := r.turns.loadTurn(); !ok || !hasKey(rec.Groups, pgid) {
172 t.Fatalf("the turn's record lacks the group: %+v", rec)
173 }
174 pr.Stdin().Close()
175 if _, err := pr.Wait(context.Background()); err != nil || !gone(pgid) {
176 t.Fatalf("a CLI that ended by itself: %v", err)
177 }
178 // The marker cannot be written: nothing starts.
179 _ = os.Remove(started)
180 if _, ids, err = launch(1); !errors.Is(err, ErrRecord) || len(ids) != 1 || ids[0] != RecordID(0, marker) {
181 t.Fatalf("first write failed: %v %v", err, ids)
182 }
183 time.Sleep(200 * time.Millisecond)
184 if exists(started) {
185 t.Fatal("the CLI ran without its marker on record")
186 }
187 // The group cannot be written: stopped at once, and proven.
188 if _, ids, err = launch(2); !errors.Is(err, ErrRecord) || errors.Is(err, ErrUnproven) || len(ids) != 2 {
189 t.Fatalf("second write failed: %v %v", err, ids)
190 }
191 if pgid, _, _ := parseRecord(ids[1]); !gone(pgid) {
192 t.Fatal("the CLI outlived its failed group record")
193 }
194}
195
196// A fake CLI starts two Bash-like commands in sessions of their own, as
197// Claude Code does (setsid): one keeps the marker, one scrubbed it. Both
198// ignore SIGTERM. Cancelling the launch ends them (SIGKILL after the
199// grace), and the proof waits for that: nothing of the attempt is alive
200// when Wait says it ended.
201func TestEngineeringTerminationGroupAndMarker(t *testing.T) {
202 scope := token()[:12]
203 body := "#!/bin/bash\ncat <&3 >/dev/null\nexport " + proc.ScopeEnv + "=" + scope + "\n" +
204 "setsid bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/marked\"; exec sleep 60' &\n" +
205 "setsid env -u EQUIPO_ATTEMPT bash -c 'trap \"\" TERM; echo $$ > \"$TMPDIR/scrubbed\"; exec sleep 60' &\n" +
206 "read line\n"
207 er, r := engLaunch(t, body)
208 r.procs = proc.Scoped(proc.ScopeEnv+"="+scope, "EQUIPO_ATTEMPT="+er.in.Attempt)
209 r.turns.Sweep(r.procs)
210 p := er.policy()
211 ctx, turn := r.take(OpEngineering)
212 defer turn.Give()
213 pctx, kill := context.WithCancel(ctx)
214 defer kill()
215 s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
216 pr, err := s.StartRecorded(pctx, provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil })
217 if err != nil {
218 t.Fatal(err)
219 }
220 marked, scrubbed := waitPID(t, filepath.Join(er.in.Scratch, "marked")), waitPID(t, filepath.Join(er.in.Scratch, "scrubbed"))
221 for _, pid := range []int{marked, scrubbed} {
222 if q := r.waitListed(pid); q.SID != pid || q.PGID != pid {
223 t.Fatalf("%d is not in a session of its own: %+v", pid, q)
224 }
225 }
226 waited := make(chan error, 1)
227 go func() { _, err := pr.Wait(context.Background()); waited <- err }()
228 stopped := time.Now()
229 kill()
230 if err := <-waited; err != nil {
231 t.Fatalf("end not proven: %v", err)
232 }
233 if !gone(marked) || !gone(scrubbed) {
234 t.Fatal("proven over with a command still running")
235 }
236 if took := time.Since(stopped); took < r.x.Grace {
237 t.Fatalf("proven in %s, before the grace ended what ignores SIGTERM", took)
238 }
239 if rec, ok, _ := r.turns.loadTurn(); !ok || len(rec.Groups) < 3 || len(rec.Sessions) < 3 {
240 t.Fatalf("the turn's record lacks the commands' groups and sessions: %+v", rec)
241 }
242}
243
244// After a restart: a recorded group alive with no marked process in it
245// (a child that scrubbed its environment, or the id used again) is never
246// killed, and the attempt is not proven over while it lives.
247func TestRestartUnmarkedSurvivorWithholdsProof(t *testing.T) {
248 r := newLaunchRig(t)
249 r.x.Settle = 500 * time.Millisecond
250 survivor := r.start(r.env(), "/bin/sleep", "60")
251 id := RecordID(survivor.Process.Pid, "attempt-u-"+r.nonce)
252 if r.x.Verify(id) {
253 t.Fatal("proven over while its recorded group is alive")
254 }
255 if gone(survivor.Process.Pid) {
256 t.Fatal("an unmarked group was killed")
257 }
258 // The same through a gate (the worker's Verify).
259 g := &Gate{Turns: r.turns, Settle: 500 * time.Millisecond}
260 if g.Verify(id) || gone(survivor.Process.Pid) {
261 t.Fatal("the gate proved or killed it")
262 }
263 _ = survivor.Process.Kill()
264 for deadline := time.Now().Add(5 * time.Second); !gone(survivor.Process.Pid) && time.Now().Before(deadline); {
265 time.Sleep(10 * time.Millisecond)
266 }
267 if !r.x.Verify(id) {
268 t.Fatal("not proven once the group is gone")
269 }
270}
271
272// After a restart, the dead runner's turn is settled first: what it
273// started (marked or not) is swept, what was there before it began is
274// not, and a group id since used by a process from before is neither
275// killed nor proven over until it is gone.
276func TestRestartReusedGroupNotKilled(t *testing.T) {
277 r := newLaunchRig(t)
278 r.x.Settle = 500 * time.Millisecond
279 marker := "attempt-r-" + r.nonce
280 unrelated := r.start(r.env(), "/bin/sleep", "60")
281 before, err := r.procs.List(time.Now().Add(5*time.Second), nil)
282 if err != nil {
283 t.Fatal(err)
284 }
285 var ids []ProcID
286 for _, q := range before {
287 ids = append(ids, q.ID)
288 }
289 dead := r.start(r.env(), "/bin/sleep", "0.2")
290 deadID := r.waitListed(dead.Process.Pid).ID
291 for !gone(dead.Process.Pid) {
292 time.Sleep(10 * time.Millisecond)
293 }
294 left := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/sleep", "60")
295 scrubbed := r.start(r.env(), "/bin/sleep", "60")
296 // Its final note was written (complete) before the runner died.
297 if err := r.turns.saveTurn(turnRecord{ID: "dead-turn", Op: OpEngineering, Runner: deadID, Sweep: true, Before: ids, Markers: []string{marker}, Complete: true}); err != nil {
298 t.Fatal(err)
299 }
300 if r.x.Verify(RecordID(unrelated.Process.Pid, marker)) {
301 t.Fatal("proven over while the reused group lives")
302 }
303 if gone(unrelated.Process.Pid) {
304 t.Fatal("a process from before the turn was killed")
305 }
306 for name, c := range map[string]*exec.Cmd{"marked": left, "unmarked": scrubbed} {
307 for deadline := time.Now().Add(5 * time.Second); !gone(c.Process.Pid) && time.Now().Before(deadline); {
308 time.Sleep(10 * time.Millisecond)
309 }
310 if !gone(c.Process.Pid) {
311 t.Fatalf("the dead turn's %s leftover survived", name)
312 }
313 }
314 if _, ok, _ := r.turns.loadTurn(); ok {
315 t.Fatal("the dead turn's record was not settled")
316 }
317 _ = unrelated.Process.Kill()
318 for deadline := time.Now().Add(5 * time.Second); !gone(unrelated.Process.Pid) && time.Now().Before(deadline); {
319 time.Sleep(10 * time.Millisecond)
320 }
321 if !r.x.Verify(RecordID(unrelated.Process.Pid, marker)) {
322 t.Fatal("not proven once it is gone")
323 }
324}
325
326// After a restart every marked process is killed, the recorded group
327// with it, and a marked grandchild that double-forked out of it too;
328// then the attempt is over. A marker-only record settles the same way.
329func TestRestartKillsMarked(t *testing.T) {
330 r := newLaunchRig(t)
331 marker := "attempt-k-" + r.nonce
332 pidFile := filepath.Join(t.TempDir(), "grandchild")
333 leader := r.start(r.env("EQUIPO_ATTEMPT="+marker), "/bin/bash", "-c", "(setsid sleep 60 & echo $! > "+quote(pidFile)+"); exec sleep 60")
334 grandchild := waitPID(t, pidFile)
335 r.waitListed(grandchild)
336 if !r.x.Verify(RecordID(leader.Process.Pid, marker)) {
337 t.Fatal("not settled")
338 }
339 if !gone(leader.Process.Pid) || !gone(grandchild) {
340 t.Fatal("a marked process survived")
341 }
342 alone := r.start(r.env("EQUIPO_ATTEMPT="+marker+"-0"), "/bin/sleep", "60")
343 if !r.x.Verify(RecordID(0, marker+"-0")) || !gone(alone.Process.Pid) {
344 t.Fatal("a marker-only record not settled")
345 }
346}
347
348// The sweep spares the runner and every helper it started for itself,
349// by identity: a helper started during the turn and still running at
350// its end lives on, a step's process running the very same program
351// with the same arguments does not.
352func TestSweepSparesTheRunnerAndItsHelpers(t *testing.T) {
353 r := newLaunchRig(t)
354 ctx, turn := r.take(OpEngineering)
355 defer turn.Give()
356 run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", "sleep 60 & exec sleep 60"}, Env: r.env("EQUIPO_ATTEMPT=attempt-o-" + r.nonce)}, "attempt-o-"+r.nonce, func(string) error { return nil })
357 if err != nil {
358 t.Fatal(err)
359 }
360 helper := exec.Command("/bin/sleep", "60")
361 helper.Env = r.env()
362 if err := StartOwn(helper); err != nil {
363 t.Fatal(err)
364 }
365 defer func() { _ = helper.Process.Kill(); _ = helper.Wait() }()
366 // The same program, arguments and environment, but the step's: its
367 // own session, after the turn began, not the runner's.
368 impostor := r.start(r.env(), "/bin/sleep", "60")
369 if !run.Stop() {
370 t.Fatal("end not proven")
371 }
372 if gone(helper.Process.Pid) {
373 t.Fatal("the runner's own helper was killed")
374 }
375 if !gone(impostor.Process.Pid) {
376 t.Fatal("a process like the helper's but not the runner's survived")
377 }
378}
379
380// A step that double-forks to escape (its parent gone, a session of its
381// own, no marker) is found by the runner-user sweep alone: the tree poll
382// never saw it.
383func TestSweepCatchesDoubleForkToLaunchd(t *testing.T) {
384 r := newLaunchRig(t)
385 r.x.Poll = time.Hour
386 ctx, turn := r.take(OpEngineering)
387 defer turn.Give()
388 pidFile := filepath.Join(t.TempDir(), "escaped")
389 script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")"
390 run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-d-" + r.nonce)}, "attempt-d-"+r.nonce, func(string) error { return nil })
391 if err != nil {
392 t.Fatal(err)
393 }
394 escaped := waitPID(t, pidFile)
395 <-run.Exited()
396 // Listed as soon as forked; an escape once setsid has run in it.
397 q := r.waitListed(escaped)
398 for deadline := time.Now().Add(5 * time.Second); q.SID != escaped && time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) {
399 q, _ = r.procs.Lookup(escaped)
400 }
401 if q.Marker != "" || q.SID != escaped {
402 t.Fatalf("not an escape: %+v", q)
403 }
404 if !run.Stop() || !gone(escaped) {
405 t.Fatal("a double-forked step outlived the turn's end")
406 }
407}
408
409// Proof only when nothing is left: a process only the runner-user sweep
410// finds (it double-forked out unseen: no marker, no recorded group or
411// session) that will not die keeps the end unproven within its bound,
412// the turn's record stays past Give, and the next turn cannot begin
413// until that process is gone.
414func TestProofOnlyWhenNothingRemains(t *testing.T) {
415 r := newLaunchRig(t)
416 r.x.Settle, r.turns.Settle, r.x.Poll = 400*time.Millisecond, 400*time.Millisecond, time.Hour
417 stuck := &stuckProcs{Procs: r.procs}
418 r.turns.Sweep(stuck)
419 ctx, turn := r.take(OpEngineering)
420 pidFile := filepath.Join(t.TempDir(), "p")
421 script := "sleep 0.3; (setsid env -u EQUIPO_ATTEMPT sleep 60 & echo $! > " + quote(pidFile) + ")"
422 run, err := r.x.Start(ctx, Command{Argv: []string{"/bin/bash", "-c", script}, Env: r.env("EQUIPO_ATTEMPT=attempt-p-" + r.nonce)}, "attempt-p-"+r.nonce, func(string) error { return nil })
423 if err != nil {
424 t.Fatal(err)
425 }
426 <-run.Exited()
427 r.waitListed(waitPID(t, pidFile))
428 stuck.hold()
429 start := time.Now()
430 if run.Stop() {
431 t.Fatal("proven over with a process of the turn alive")
432 }
433 if took := time.Since(start); took > r.x.Settle+time.Second {
434 t.Fatalf("the proof took %s, past its bound", took)
435 }
436 turn.Give()
437 if _, ok, _ := r.turns.loadTurn(); !ok {
438 t.Fatal("an unproven turn's record went")
439 }
440 if _, err := r.turns.Take(context.Background(), OpCheck); !errors.Is(err, ErrUnsettled) {
441 t.Fatalf("a turn began beside an unproven one: %v", err)
442 }
443 stuck.release()
444 next, err := r.turns.Take(context.Background(), OpCheck)
445 if err != nil {
446 t.Fatalf("not settled once it could be: %v", err)
447 }
448 next.Give()
449}
450
451// stuckProcs drops every signal while held: a process that will not die.
452type stuckProcs struct {
453 Procs
454 held bool
455}
456
457func (s *stuckProcs) hold() { s.held = true }
458func (s *stuckProcs) release() { s.held = false }
459func (s *stuckProcs) Signal(pid int, sig syscall.Signal) error {
460 if s.held && sig != 0 {
461 return nil
462 }
463 return s.Procs.Signal(pid, sig)
464}
465
466// Every operation that has a model token in a process, runs Xcode or
467// repository code holds the Mac's one turn: an Engineering launch, a
468// token check and a probe run never overlap, a launch outside a turn
469// starts nothing, and a check waits while a sign-in holds its pty.
470func TestTurnsCoverEveryTokenOperation(t *testing.T) {
471 er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n")
472 er.in.Action = claude.DarwinCheck
473 check := er.policy()
474 // A token check outside any turn: refused, nothing on record.
475 recorded := 0
476 s := &Starter{Exec: r.x, CLI: er.cli, Input: er.in, Token: slices.Clone(er.token)}
477 if _, err := s.StartRecorded(context.Background(), provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { recorded++; return nil }); !errors.Is(err, ErrNoTurn) || recorded != 0 {
478 t.Fatalf("a token check ran outside the turn: %v (%d records)", err, recorded)
479 }
480 // While Engineering holds the turn, a token check and a probe run wait.
481 _, eng := r.take(OpEngineering)
482 short, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
483 if _, err := r.turns.Take(short, OpTokenCheck); err == nil {
484 t.Fatal("a token check took the turn beside Engineering")
485 }
486 cancel()
487 f := newProbeFixture(t, allLines("denied"))
488 f.h.Turns, f.h.Limit = r.turns, 300*time.Millisecond
489 if rep := RunProbes(context.Background(), f.h); len(rep.Unfinished) != len(rep.Probes) || slices.ContainsFunc(f.execLog, func(k string) bool { return strings.Contains(k, "simctl") }) {
490 t.Fatalf("probes ran beside Engineering: %+v", rep)
491 }
492 eng.Give()
493 // The token check in its own turn runs, and ends proven.
494 ctx, tc := r.take(OpTokenCheck)
495 s.Token = slices.Clone(er.token)
496 pr, err := s.StartRecorded(ctx, provider.Launch{Policy: check}, claude.DarwinArgv(check), func(context.Context, containment.Record) error { return nil })
497 if err != nil {
498 t.Fatal(err)
499 }
500 pr.Stdin().Close()
501 if _, err := pr.Wait(context.Background()); err != nil {
502 t.Fatal(err)
503 }
504 tc.Give()
505 // A sign-in's pty holds the turn: a check waits for it.
506 _, signIn := r.take(OpSignIn)
507 g, dir := gateFixture(t, false)
508 g.Turns = r.turns
509 g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce)
510 ran := make(chan Result, 1)
511 var at time.Time
512 go func() {
513 res := g.Run(context.Background(), "checks-w-"+r.nonce, dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(string) error {
514 if at.IsZero() {
515 at = time.Now()
516 }
517 return nil
518 })
519 ran <- res
520 }()
521 time.Sleep(300 * time.Millisecond)
522 select {
523 case res := <-ran:
524 t.Fatalf("a check ran while a sign-in held the turn: %+v", res)
525 default:
526 }
527 gave := time.Now()
528 signIn.Give()
529 if res := <-ran; res.Code != 0 || !res.Terminated || at.Before(gave) {
530 t.Fatalf("the check after the sign-in: %+v", res)
531 }
532}
533
534// A stored connection holds no turn: once the token is stored, an
535// Engineering launch, a sandboxed check and an ask take turns one after
536// another, each proven over, and nothing is left on record.
537func TestStoredConnectionAllowsSerialTurns(t *testing.T) {
538 er, r := engLaunch(t, "#!/bin/sh\ncat <&3 >/dev/null\nread line\n")
539 store, err := r.turns.Take(context.Background(), OpTokenStore)
540 if err != nil {
541 t.Fatal(err)
542 }
543 if err := os.WriteFile(filepath.Join(er.in.CredentialHome, ".oauth-token"), er.token, 0600); err != nil {
544 t.Fatal(err)
545 }
546 store.Give()
547 ask := newEngRigWith(t, []byte("#!/bin/sh\ncat <&3 >/dev/null\nread line\n"))
548 ask.in.Attempt, ask.in.Action = er.in.Attempt, claude.DarwinAnswer
549 cli := func(op Op, rig *engRig) error {
550 p, err := EngineeringPolicy(rig.cli, rig.in)
551 if err != nil {
552 return err
553 }
554 u, err := r.turns.Take(context.Background(), op)
555 if err != nil {
556 return err
557 }
558 defer u.Give()
559 s := &Starter{Exec: r.x, CLI: rig.cli, Input: rig.in, Token: slices.Clone(rig.token)}
560 pr, err := s.StartRecorded(u.Context(context.Background()), provider.Launch{Policy: p}, claude.DarwinArgv(p), func(context.Context, containment.Record) error { return nil })
561 if err != nil {
562 return err
563 }
564 pr.Stdin().Close()
565 _, err = pr.Wait(context.Background())
566 return err
567 }
568 g, dir := gateFixture(t, true)
569 _, temp := userTempFixture(t)
570 g.Turns, g.UserTemp = r.turns, temp
571 g.Env = append(g.Env, proc.ScopeEnv+"="+r.nonce)
572 done := make(chan []string)
573 go func() {
574 var errs []string
575 if err := cli(OpEngineering, er); err != nil {
576 errs = append(errs, "engineering: "+err.Error())
577 }
578 if res, _ := run(g, dir, "checks-s-"+r.nonce, time.Minute, "true"); res.Code != 0 || !res.Terminated {
579 errs = append(errs, "sandboxed check did not pass")
580 }
581 if err := cli(OpAsk, ask); err != nil {
582 errs = append(errs, "ask: "+err.Error())
583 }
584 done <- errs
585 }()
586 select {
587 case errs := <-done:
588 if len(errs) > 0 {
589 t.Fatal(errs)
590 }
591 case <-time.After(30 * time.Second):
592 t.Fatal("a turn waited on the stored connection")
593 }
594 if _, ok, _ := r.turns.loadTurn(); ok || r.turns.Pending() {
595 t.Fatal("a turn or a cleanup was left on record")
596 }
597}
598
599// An interrupted cleanup (its attempt's end not proven) is finished
600// only by its owner (that attempt's proof, in the runner process that
601// wrote it) or by a restart (that process gone), never by another turn.
602func TestCleanupOwnedByItsTurn(t *testing.T) {
603 g, dir := gateFixture(t, true)
604 _, temp := userTempFixture(t)
605 g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock"))
606 g.procs = withPhantom()
607 res, id := run(g, dir, "checks-o-1", time.Minute, `touch `+quote(filepath.Join(temp, "left-by-1")))
608 if res.Terminated || !g.Turns.Pending() {
609 t.Fatalf("not interrupted: %+v", res)
610 }
611 g.procs = nil
612 // Another turn of this runner: it neither finishes it nor runs.
613 if res, _ := run(g, dir, "checks-o-2", time.Minute, `touch `+quote(filepath.Join(temp, "ran-2"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran-2")) {
614 t.Fatalf("another turn ran: %+v", res)
615 }
616 if !exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending() {
617 t.Fatal("another turn finished the cleanup")
618 }
619 // Nor does a recovery for another attempt.
620 if g.Verify(RecordID(0, "checks-o-other")) && (!exists(filepath.Join(temp, "left-by-1")) || !g.Turns.Pending()) {
621 t.Fatal("another attempt's proof finished the cleanup")
622 }
623 // Its owner does.
624 if !g.Verify(id) || exists(filepath.Join(temp, "left-by-1")) || g.Turns.Pending() {
625 t.Fatal("the owner did not finish its cleanup")
626 }
627 // A restart: the record of a runner process that is gone.
628 dead := exec.Command("/bin/true")
629 if err := dead.Start(); err != nil {
630 t.Fatal(err)
631 }
632 deadID, ok := platformProcs.Lookup(dead.Process.Pid)
633 _ = dead.Wait()
634 if !ok {
635 deadID.ID = ProcID{PID: dead.Process.Pid, Start: 1}
636 }
637 s, err := openTemp(temp, nil)
638 if err != nil {
639 t.Fatal(err)
640 }
641 if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-dead", Before: s.before, Runner: deadID.ID}); err != nil {
642 t.Fatal(err)
643 }
644 s.close()
645 if err := os.WriteFile(filepath.Join(temp, "left-by-dead"), nil, 0600); err != nil {
646 t.Fatal(err)
647 }
648 if res, _ := run(g, dir, "checks-o-3", time.Minute, `ls `+quote(temp)); res.Code != 0 || strings.Contains(res.Output, "left-by-dead") || g.Turns.Pending() {
649 t.Fatalf("a restart did not finish the dead runner's cleanup: %+v", res)
650 }
651 // This live runner's record for an attempt of another turn: never.
652 if err := g.Turns.writePending(pendingRecord{Attempt: "checks-o-live", Before: tempListing{}, Runner: selfID()}); err != nil {
653 t.Fatal(err)
654 }
655 if res, _ := run(g, dir, "checks-o-4", time.Minute, `true`); res.Reason != "checks_unavailable" || !g.Turns.Pending() {
656 t.Fatalf("a live owner's cleanup taken by another turn: %+v", res)
657 }
658}
659
660// #8: a turn record that cannot be written (here its directory turned
661// read-only) stops the operation by itself and withholds its proof; a
662// restart then settles what it left from the record it had.
663func TestTurnRecordWriteFailureStopsTheOperation(t *testing.T) {
664 r := newLaunchRig(t)
665 dir := filepath.Dir(r.turns.lock)
666 pidFile := filepath.Join(t.TempDir(), "child")
667 ctx, turn := r.take(OpEngineering)
668 marker := "attempt-w-" + r.nonce
669 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 })
670 if err != nil {
671 t.Fatal(err)
672 }
673 if err := os.Chmod(dir, 0500); err != nil {
674 t.Fatal(err)
675 }
676 defer os.Chmod(dir, 0700)
677 select {
678 case <-run.Exited():
679 case <-time.After(5 * time.Second):
680 t.Fatal("the operation ran on with its turn's record unwritable")
681 }
682 child := waitPID(t, pidFile)
683 if run.Stop() {
684 t.Fatal("proven over with its groups not on record")
685 }
686 turn.Give()
687 if err := os.Chmod(dir, 0700); err != nil {
688 t.Fatal(err)
689 }
690 next := NewTurns(r.turns.lock).Sweep(r.procs)
691 next.Settle = 3 * time.Second
692 u, err := next.Take(context.Background(), OpCheck)
693 if err != nil {
694 t.Fatalf("a restart did not settle it: %v", err)
695 }
696 u.Give()
697 if !gone(child) {
698 t.Fatal("what it left survived the restart's settling")
699 }
700 // Its record was never completed. Nothing of the runner user's is
701 // left that the runner does not account for, so the idle read (taken
702 // holding the turn) proves it over.
703 nx := &Executor{Turns: next, Settle: time.Second}
704 if !nx.Verify(run.ID()) || next.Incomplete() {
705 t.Fatal("an idle read with nothing unaccounted did not prove it over")
706 }
707}
708
709// blind cannot read pid's identity (a sysctl that failed), though the
710// process is there.
711type blind struct {
712 Procs
713 pid int
714}
715
716func (b *blind) Lookup(pid int) (ProcInfo, bool) {
717 if pid == b.pid {
718 return ProcInfo{}, false
719 }
720 return b.Procs.Lookup(pid)
721}
722
723// #9: a cleanup's owner whose identity cannot be read is not a restart:
724// another turn neither finishes the cleanup nor runs.
725func TestCleanupOwnerUnknownIsNotARestart(t *testing.T) {
726 g, dir := gateFixture(t, true)
727 _, temp := userTempFixture(t)
728 g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock"))
729 owner := exec.Command("/bin/sleep", "60")
730 if err := owner.Start(); err != nil {
731 t.Fatal(err)
732 }
733 defer func() { _ = owner.Process.Kill(); _ = owner.Wait() }()
734 id, ok := platformProcs.Lookup(owner.Process.Pid)
735 if !ok {
736 t.Fatal("owner not listed")
737 }
738 g.Turns.ids = &blind{Procs: platformProcs, pid: owner.Process.Pid}
739 s, err := openTemp(temp, nil)
740 if err != nil {
741 t.Fatal(err)
742 }
743 if err := g.Turns.writePending(pendingRecord{Attempt: "checks-u-owner", Before: s.before, Runner: id.ID}); err != nil {
744 t.Fatal(err)
745 }
746 s.close()
747 left := filepath.Join(temp, "left-by-owner")
748 if err := os.WriteFile(left, nil, 0600); err != nil {
749 t.Fatal(err)
750 }
751 if res, _ := run(g, dir, "checks-u-1", time.Minute, "true"); res.Reason != "checks_unavailable" || !exists(left) || !g.Turns.Pending() {
752 t.Fatalf("a live owner's cleanup taken on an unreadable identity: %+v", res)
753 }
754}
755