Mac slice F task 16 fix 1: rollback, lingering child, fresh fix tree
Astra round 1 (4 Important, 1 Minor), tests first: - M9e: the CLI starts a setsid child that ignores SIGTERM and keeps the attempt's marker; it outlives the runner and recovery must end it, by identity, before the end is proven (F2 now fails there) - M9g: one worker's state across 37, 35 (the branch point on the pre-upgrade snapshot) and 37 again; Engineering that finished while the instance was away is held, by outbox id, and resumes at 37. It found a bug: a worker sent its Engineering reports to a 35 instance, which dropped them; below 37 they now wait in the outbox - M9b: the fix round resumes the first round's very session in another directory, without the file the first round left uncommitted - M4 makes its own precondition and runs on its own - named mutations reach republish, rebase placement, ask binding The fake's checks take the Mac's turns; playing a seatbelt Mac they run under a testbuild srt stand-in, so a check killed mid-run is cleared by the idle read as on a Mac. An unsandboxed one waits for a reboot (TestFakeWorkerCrashedCheck, via creds.BootForTest).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+737
−109
.rastrillo/budgets.txt+2 −2internal/fakeclaude/fake.go+59 −0internal/headless/m8_test.go+12 −1internal/headless/mac_mixed_test.go+294 −85internal/headless/mac_test.go+123 −9internal/headless/xcodebuild_test.go+7 −1internal/runner/mac/creds/boot_testbuild.go+9 −0internal/runner/mac/creds/guard.go+7 −0internal/runner/thin/contract_test.go+9 −0internal/runner/thin/fakeworker_check_test.go+128 −0internal/runner/thin/fakeworker_testbuild.go+33 −9internal/runner/thin/link.go+6 −0internal/runner/thin/step.go+48 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 65a54a9e..2b6038d2 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 34320 31129 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes, D1, the fake Mac worker that makes changes; 34320/31129. |
| +size internal/runner/thin 34396 31329 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, Engineering, asks, F probes, D1, the fake Mac worker that makes changes; 34396/31329. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
| @@ -70,7 +70,7 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only |
| perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen. |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| -size internal/headless - 12993 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; Mac Engineering M9 and mixed versions; measured 12993 test lines. |
| +size internal/headless - 13333 Grant scenarios (#48); sign-in email at 1280 and 390; Assistant files end to end; the restart wait; the live site waits for a place; a card answer settles at the bottom; Mac Engineering M9 and mixed versions; measured 13333 test lines. |
| size internal/thintest - 40338 Protocol 31 contracts, 35 diffs, stuck tasks, no-access merges, held retries, unfinished work, free rounds, previews, Assistant files, places, Mac waits, Mac Engineering, conns, asks, D1; 40338. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 9e0fb1ae..3aa00ff1 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -67,6 +67,10 @@ |
| // and, if allowed, copies its bytes to /workspace/<path> (asking for |
| // Write); "rowrite:<absolute path>" writes there directly, asking |
| // nobody, and says whether the filesystem refused (with its errno); |
| +// "linger:<absolute path>" starts, once, a child in its own session that |
| +// ignores SIGTERM and SIGHUP, keeps the environment and writes its pid |
| +// there; "probe:<path>" says whether the file is in the workspace and |
| +// "saycwd" names the workspace in the reply; |
| // "stepsleep:<ms>" pauses before editing, "stepwait:<absolute path>" |
| // waits before editing while that file exists, and "afterwait:<absolute |
| // path>" waits the same way after editing, before the reply (at most ten |
| @@ -150,6 +154,7 @@ import ( |
| "io" |
| "os" |
| "os/exec" |
| + "os/signal" |
| "path/filepath" |
| "regexp" |
| "strconv" |
| @@ -163,6 +168,9 @@ const Version = "2.1.312" |
| // Main runs the fake with argv after the program name. |
| func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| + if len(args) == 2 && args[0] == lingerArg { |
| + return lingerMain(args[1]) |
| + } |
| // The token by descriptor, as the pinned CLI reads it (task 1, S4): |
| // /dev/fd/<n>, trimmed, when CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR |
| // names one; the fake then holds it as if it were in its environment. |
| @@ -581,6 +589,43 @@ var sayWord = regexp.MustCompile(`say:([^;\n]*)`) |
| var moveWord = regexp.MustCompile(`move:([^|\s]+)\|([^;\s]+)`) |
| var limitLeave = regexp.MustCompile(`limitleave:([^;\s]+)`) |
| var stepWait = regexp.MustCompile(`stepwait:(/[^;\s]+)`) |
| +var lingerWord = regexp.MustCompile(`linger:(/[^;\s]+)`) |
| +var probeWord = regexp.MustCompile(`probe:([^;\s]+)`) |
| +var sayCwd = regexp.MustCompile(`\bsaycwd\b`) |
| + |
| +// lingerArg starts the fake as linger's child. |
| +const lingerArg = "__linger" |
| + |
| +// linger starts, once (while pidfile is not there), a child in a session |
| +// of its own that keeps this process's environment (its attempt marker |
| +// among it), ignores SIGTERM, SIGHUP and SIGINT, writes its pid to |
| +// pidfile and sleeps ten minutes: what a launch leaves behind that only |
| +// a SIGKILL ends. |
| +func linger(pidfile string) { |
| + if _, err := os.Lstat(pidfile); err == nil { |
| + return |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + return |
| + } |
| + cmd := exec.Command(self, lingerArg, pidfile) |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + if cmd.Start() == nil { |
| + _ = cmd.Process.Release() |
| + } |
| +} |
| + |
| +func lingerMain(pidfile string) int { |
| + signal.Ignore(syscall.SIGTERM, syscall.SIGHUP, syscall.SIGINT) |
| + tmp := pidfile + ".tmp" |
| + if os.WriteFile(tmp, []byte(strconv.Itoa(os.Getpid())), 0600) != nil || os.Rename(tmp, pidfile) != nil { |
| + return 1 |
| + } |
| + time.Sleep(10 * time.Minute) |
| + return 0 |
| +} |
| + |
| var afterWait = regexp.MustCompile(`afterwait:(/[^;\s]+)`) |
| // holdWhile waits, at most ten minutes, while the file the prompt's word |
| @@ -625,8 +670,22 @@ func (f *fake) engineer(prompt string, turn int, emit func(any)) string { |
| ms, _ := strconv.Atoi(m[1]) |
| time.Sleep(time.Duration(ms) * time.Millisecond) |
| } |
| + if m := lingerWord.FindStringSubmatch(prompt); m != nil { |
| + linger(m[1]) |
| + } |
| holdWhile(stepWait, prompt) |
| var done []string |
| + for _, m := range probeWord.FindAllStringSubmatch(prompt, -1) { |
| + rel := filepath.Clean("/" + m[1])[1:] |
| + if _, err := os.Lstat(filepath.Join(root, rel)); err == nil { |
| + done = append(done, "Found "+rel+".") |
| + } else { |
| + done = append(done, "No "+rel+".") |
| + } |
| + } |
| + if sayCwd.MatchString(prompt) { |
| + done = append(done, "Working in "+root+".") |
| + } |
| ask := func(i int, tool string, input map[string]any) bool { |
| id := fmt.Sprintf("toolu_fake_%d_e%d", turn, i) |
| emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": tool, "input": input}}}, "uuid": "assistant-" + id}) |
diff --git a/internal/headless/m8_test.go b/internal/headless/m8_test.go| index ea611ff2..91e2a09f 100644 |
| --- a/internal/headless/m8_test.go |
| +++ b/internal/headless/m8_test.go |
| @@ -3,12 +3,16 @@ package headless |
| import ( |
| "bytes" |
| "context" |
| + "crypto/sha256" |
| "database/sql" |
| + "encoding/hex" |
| "encoding/json" |
| "log/slog" |
| + "maps" |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "slices" |
| "strings" |
| "sync" |
| "testing" |
| @@ -83,7 +87,14 @@ func oldBinaryAt(t *testing.T, commit, tags string, extra map[string]string) str |
| defer oldOnce.Unlock() |
| key := commit |
| if tags != "" { |
| - key += "-" + tags |
| + // Keyed by its extra files too, so a changed overlay is built |
| + // again (slice 4's key stays as CI's cache has it). |
| + names := slices.Sorted(maps.Keys(extra)) |
| + h := sha256.New() |
| + for _, n := range names { |
| + h.Write([]byte(n + "\x00" + extra[n] + "\x00")) |
| + } |
| + key += "-" + tags + "-" + hex.EncodeToString(h.Sum(nil))[:12] |
| } |
| cache := os.Getenv("EQUIPO_M8_CACHE") |
| if cache == "" || os.MkdirAll(filepath.Join(cache, key), 0700) != nil { |
diff --git a/internal/headless/mac_mixed_test.go b/internal/headless/mac_mixed_test.go| index be7a82e5..f4b873b5 100644 |
| --- a/internal/headless/mac_mixed_test.go |
| +++ b/internal/headless/mac_mixed_test.go |
| @@ -6,15 +6,16 @@ import ( |
| "bytes" |
| "database/sql" |
| "encoding/json" |
| + "fmt" |
| "os" |
| "os/exec" |
| "path/filepath" |
| "slices" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| - "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/oficina/equipo/internal/thintest" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -45,11 +46,28 @@ func TestM9OldInstance(t *testing.T) { |
| if out == "" { |
| t.Skip("M9g only") |
| } |
| - inst := thintest.StartInstance(t) |
| + // EQUIPO_M9_DB: the instance's database lives there, outside this |
| + // test's own directory, so a later process (or a newer release) can |
| + // open it; with EQUIPO_M9_EXISTING=1 it is opened as it is. |
| + path, existing := os.Getenv("EQUIPO_M9_DB"), os.Getenv("EQUIPO_M9_EXISTING") == "1" |
| + inst := thintest.StartInstanceWith(t, func(i *thintest.Instance) { |
| + if path == "" { |
| + return |
| + } |
| + if !existing { |
| + raw, err := os.ReadFile(i.Path) |
| + if err != nil || os.WriteFile(path, raw, 0600) != nil { |
| + t.Fatal("the database could not be placed") |
| + } |
| + } |
| + i.Path = path |
| + }) |
| token := inst.DeviceToken(t) |
| - primary := inst.EnrolRunner(t) |
| - worker := inst.EnrolRunner(t) |
| - raw, _ := json.Marshal(map[string]any{"url": inst.URL, "team": inst.TeamID, "token": token, "db": inst.Path, "primary": primary, "worker": worker}) |
| + out2 := map[string]any{"url": inst.URL, "team": inst.TeamID, "token": token, "db": inst.Path} |
| + if !existing { |
| + out2["primary"], out2["worker"] = inst.EnrolRunner(t), inst.EnrolRunner(t) |
| + } |
| + raw, _ := json.Marshal(out2) |
| if err := os.WriteFile(out+".tmp", raw, 0600); err != nil { |
| t.Fatal(err) |
| } |
| @@ -174,62 +192,121 @@ func TestMacMixedVersions(t *testing.T) { |
| s.waitsForUpdate(t, inst, worker.runnerID, primaryID) |
| }) |
| - t.Run("new worker, old instance", func(t *testing.T) { |
| - out := filepath.Join(t.TempDir(), "instance.json") |
| - cmd := exec.Command(old, "-test.run", "^TestM9OldInstance$", "-test.timeout", "20m") |
| - cmd.Env = append(os.Environ(), "EQUIPO_M9_OUT="+out) |
| - stdin, _ := cmd.StdinPipe() |
| - var logs bytes.Buffer |
| - cmd.Stdout, cmd.Stderr = &logs, &logs |
| - if err := cmd.Start(); err != nil { |
| + // The same worker, rolled back and forward: at 37 it makes a change |
| + // (a candidate it retains, a session it keeps). The instance is rolled |
| + // back to the branch point on the database snapshot taken before the |
| + // upgrade; the worker speaks 35, its first connection check there is |
| + // a frame only 37 carries, which it holds. Forward again on the |
| + // database as 37 left it: the held frames go (the same rows, acked) |
| + // and the retained work resumes (Engineering answers from the session |
| + // it kept before the rollback). |
| + t.Run("same worker, 37 to 35 to 37", func(t *testing.T) { |
| + dir := t.TempDir() |
| + base := filepath.Join(dir, "base.db") |
| + first := startBranchInstance(t, old, base, false) |
| + first.stop() |
| + cur := filepath.Join(dir, "current.db") |
| + copyFile(t, base, cur) |
| + inst := thintest.StartInstanceWith(t, func(i *thintest.Instance) { i.Path, i.MacEngineering = cur, true }) |
| + primary, forge := runnerSetup(t, inst.URL, inst.TeamID, first.Primary) |
| + t.Cleanup(func() { primary.stop(t) }) |
| + addWoodstar(t, primary.root, forge) |
| + woodstarCredentials(t, primary) |
| + primary.start(t) |
| + worker, _ := macWorkerAs(t, first.Worker, primary) |
| + worker.inst = inst |
| + worker.start(t) |
| + turns := 0 |
| + env := &Env{Client: thintest.NewClient(inst.URL, inst.DeviceToken(t)), turns: &turns, ForgePath: forge.path} |
| + s := open(t, env) |
| + s.keep() |
| + s.workerOnline(t) |
| + if p := sessionProtocol(t, inst, worker.runnerID); p != wire.ProtocolMacEngineering { |
| + t.Fatalf("at 37 the worker speaks %d", p) |
| + } |
| + // 37: Engineering on the worker. Its CLI holds after its edit while |
| + // the instance goes away (the rollback starts); then the attempt |
| + // finishes with nobody to tell: it commits, retains the candidate, |
| + // keeps the session, and queues what it would say. |
| + hold := filepath.Join(t.TempDir(), "hold") |
| + if err := os.WriteFile(hold, nil, 0600); err != nil { |
| t.Fatal(err) |
| } |
| - t.Cleanup(func() { |
| - stdin.Close() |
| - done := make(chan error, 1) |
| - go func() { done <- cmd.Wait() }() |
| - select { |
| - case <-done: |
| - case <-time.After(30 * time.Second): |
| - cmd.Process.Kill() |
| - <-done |
| - } |
| + sent := s.send(t, "tool:record_task:woodstar/panes|Swipe, across the rollback|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true afterwait:"+hold) |
| + task := s.taskOf(t, sent.Turn.ID) |
| + s.wait(t, "Engineering running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool { |
| + e := stepOf(c.Tasks[task], wire.SpecialistEngineering, 0) |
| + return e.RunnerID == worker.runnerID && e.State == wire.StepRunning && e.StartedAt != nil |
| }) |
| - var info struct { |
| - URL, Team, Token, DB string |
| - Primary, Worker runnerproto.RunnerCredential |
| + for deadline := time.Now().Add(time.Minute); len(engineeringProcs(worker)) == 0; time.Sleep(50 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the CLI never started on the worker") |
| + } |
| } |
| - for deadline := time.Now().Add(2 * time.Minute); ; time.Sleep(100 * time.Millisecond) { |
| - raw, err := os.ReadFile(out) |
| - if err == nil && json.Unmarshal(raw, &info) == nil { |
| + k, err := env.Client.Task(s.ctx, task) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + eng := stepOf(k, wire.SpecialistEngineering, 0) |
| + s.close() |
| + before := workerOutbox(t, worker) |
| + inst.Stop() |
| + if err := os.Remove(hold); err != nil { |
| + t.Fatal(err) |
| + } |
| + var queued []string |
| + for deadline := time.Now().Add(2 * time.Minute); ; time.Sleep(250 * time.Millisecond) { |
| + queued = queued[:0] |
| + steps := 0 |
| + for id, row := range workerOutbox(t, worker) { |
| + if _, seen := before[id]; !seen && !row.acked { |
| + queued = append(queued, id) |
| + if row.kind == wire.FrameStep { |
| + steps++ |
| + } |
| + } |
| + } |
| + // Committed, then done: the worker's two reports of the end. |
| + if steps >= 2 && len(workerKept(t, worker, eng.ID)) == 1 && len(engineeringProcs(worker)) == 0 { |
| break |
| } |
| if time.Now().After(deadline) { |
| - t.Fatalf("the branch point's instance did not start: %s", logs.String()) |
| + out := workerOutbox(t, worker) |
| + var ks []string |
| + for _, id := range queued { |
| + ks = append(ks, out[id].kind) |
| + } |
| + t.Fatalf("the attempt did not finish offline: queued %v %v, kept %v, procs %v", queued, ks, workerKept(t, worker, eng.ID), engineeringProcs(worker)) |
| } |
| } |
| - primary, forge := runnerSetup(t, info.URL, info.Team, info.Primary) |
| - t.Cleanup(func() { primary.stop(t) }) |
| - addWoodstar(t, primary.root, forge) |
| - woodstarCredentials(t, primary) |
| + slices.Sort(queued) |
| + kinds := workerOutbox(t, worker) |
| + kept, refs := workerKept(t, worker, eng.ID), workerRefs(t, worker) |
| + if !slices.ContainsFunc(refs, func(r string) bool { return strings.HasPrefix(r, "refs/equipo/"+task+"/"+eng.ID+"/1 ") }) { |
| + t.Fatalf("the candidate is not retained: %v", refs) |
| + } |
| + t.Logf("queued while the instance was away: %d frames", len(queued)) |
| + |
| + // Rolled back: the branch point on the snapshot from before the |
| + // upgrade, at its own address; the runners follow it there. |
| + worker.stop(t) |
| + primary.stop(t) |
| + back := filepath.Join(dir, "rollback.db") |
| + copyFile(t, base, back) |
| + old35 := startBranchInstance(t, old, back, true) |
| + primary.cfg.Origin = old35.URL |
| primary.start(t) |
| - worker, _ := macWorkerAs(t, info.Worker, primary) |
| - worker.instanceDB = info.DB |
| + worker.cfg.Origin, worker.inst, worker.instanceDB = old35.URL, nil, back |
| worker.start(t) |
| - turns := 0 |
| - env := &Env{Client: thintest.NewClient(info.URL, info.Token), turns: &turns, ForgePath: forge.path} |
| - s := open(t, env) |
| - s.keep() |
| - s.workerOnline(t) |
| - // Its hello is a protocol 35 hello: none of slice F's fields. |
| - d, err := sql.Open("sqlite", "file:"+info.DB+"?mode=ro&_pragma=busy_timeout(5000)") |
| + d, err := sql.Open("sqlite", "file:"+back+"?mode=ro&_pragma=busy_timeout(5000)") |
| if err != nil { |
| t.Fatal(err) |
| } |
| - defer d.Close() |
| var protocol int |
| var hello string |
| - if err := d.QueryRow("SELECT protocol, hello FROM runner_sessions WHERE runner_id = ?", info.Worker.RunnerID).Scan(&protocol, &hello); err != nil { |
| + err = d.QueryRow("SELECT protocol, hello FROM runner_sessions WHERE runner_id = ?", worker.runnerID).Scan(&protocol, &hello) |
| + d.Close() |
| + if err != nil { |
| t.Fatal(err) |
| } |
| var h wire.Hello |
| @@ -239,58 +316,190 @@ func TestMacMixedVersions(t *testing.T) { |
| if protocol != wire.Protocol35 || h.Capabilities.Engineering != nil || h.SealKey != "" || h.Inventory || len(h.Connections) != 0 || slices.ContainsFunc(h.Capabilities.Probes, func(p wire.Probe) bool { return strings.HasPrefix(p.ID, "F") }) { |
| t.Fatalf("the worker's hello at %d: %s", protocol, hello) |
| } |
| - // It still takes checks: a Swift change on Woodstar, checked on it. |
| - sent := s.send(t, "tool:record_task:woodstar/woodstar|iOS edge swipe, rolled back|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| - id := s.taskOf(t, sent.Turn.ID) |
| - k := s.settled(t, id, 3*time.Minute) |
| - if c := stepOf(k, wire.SpecialistChecks, 0); c.Checks != wire.ChecksPassed || c.RunnerID != info.Worker.RunnerID { |
| - t.Fatalf("checks on the worker against the rolled-back instance: %+v (%s)", c, stepKinds(k)) |
| + // Nothing only 37 carries is sent to it; nothing is lost; what the |
| + // worker retained stays. |
| + time.Sleep(3 * time.Second) |
| + during := workerOutbox(t, worker) |
| + for _, id := range queued { |
| + row, ok := during[id] |
| + if !ok { |
| + t.Fatalf("frame %s (%s) was lost in the rollback", id, kinds[id].kind) |
| + } |
| + if row.acked { |
| + // A report of Engineering, which only 37 places: an older |
| + // instance would drop it. |
| + t.Fatalf("frame %s (%s), which only 37 carries, was sent at 35", id, row.kind) |
| + } |
| } |
| - // It queued nothing only protocol 37 carries, and lost nothing it |
| - // sent: every frame of its outbox is a protocol 35 frame, acked. |
| - w, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| - if err != nil { |
| - t.Fatal(err) |
| + if k, r := workerKept(t, worker, eng.ID), workerRefs(t, worker); !slices.Equal(k, kept) || !slices.Equal(r, refs) { |
| + t.Fatalf("retained work changed at 35: sessions %v (were %v), refs %v (were %v)", k, kept, r, refs) |
| } |
| - defer w.Close() |
| - for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(200 * time.Millisecond) { |
| - var unacked int |
| - w.QueryRow("SELECT count(*) FROM outbox WHERE acked = 0").Scan(&unacked) |
| - if unacked == 0 { |
| + var at35 []string |
| + for _, id := range queued { |
| + at35 = append(at35, fmt.Sprintf("%s:%s:acked=%v", id, during[id].kind, during[id].acked)) |
| + } |
| + t.Logf("at 35: %v", at35) |
| + |
| + // Forward again: 37 on its own database, at its address. |
| + worker.stop(t) |
| + primary.stop(t) |
| + old35.stop() |
| + inst.Restart(t) |
| + primary.cfg.Origin = inst.URL |
| + primary.start(t) |
| + worker.cfg.Origin, worker.inst, worker.instanceDB = inst.URL, inst, "" |
| + worker.start(t) |
| + if p := sessionProtocol(t, inst, worker.runnerID); p != wire.ProtocolMacEngineering { |
| + t.Fatalf("forward again, the worker speaks %d", p) |
| + } |
| + for deadline := time.Now().Add(time.Minute); ; time.Sleep(250 * time.Millisecond) { |
| + now, sent := workerOutbox(t, worker), 0 |
| + for _, id := range queued { |
| + if row, ok := now[id]; !ok { |
| + t.Fatalf("queued frame %s is gone", id) |
| + } else if row.acked { |
| + sent++ |
| + } |
| + } |
| + if sent == len(queued) { |
| break |
| } |
| if time.Now().After(deadline) { |
| - t.Fatalf("%d frames of the worker never acked", unacked) |
| + t.Fatalf("%d of %d queued frames sent at 37", sent, len(queued)) |
| } |
| } |
| - rows, err := w.Query("SELECT id, kind, body FROM outbox") |
| - if err != nil { |
| - t.Fatal(err) |
| + s = open(t, env) |
| + s.keep() |
| + s.workerOnline(t) |
| + // The work resumes: the attempt the instance saw start is done and |
| + // published, judged, and Engineering answers from its session. |
| + k = s.settled(t, task, 3*time.Minute) |
| + if e := stepOf(k, wire.SpecialistEngineering, 0); e.ID != eng.ID || e.Attempt != 1 || e.State != wire.StepDone || !e.Pushed || k.Stage != wire.StageReadyToMerge || !slices.ContainsFunc(refs, func(r string) bool { return r == "refs/equipo/"+task+"/"+eng.ID+"/1 "+e.CandidateSHA }) { |
| + t.Fatalf("after the round trip: %s %s", k.Stage, stepKinds(k)) |
| } |
| - n := 0 |
| - for rows.Next() { |
| - var fid, kind, body string |
| - if err := rows.Scan(&fid, &kind, &body); err != nil { |
| - t.Fatal(err) |
| - } |
| - f := wire.Frame{ID: fid, Type: kind, Data: json.RawMessage(body)} |
| - at35, err := wire.Encode(f, wire.Protocol35) |
| - if err != nil || !jsonEqual(at35.Data, f.Data) { |
| - t.Fatalf("the worker queued more than protocol 35 carries: %v %s %s", err, kind, body) |
| + q, _ := s.asked(t, task, "What did you change? ask:git", wire.SpecialistEngineering, time.Minute) |
| + if q.State != wire.QuestionAnswered || q.StepID != eng.ID || !strings.HasPrefix(q.Answer, "From my session:") || !strings.Contains(q.Answer, "The change: +") { |
| + t.Fatalf("the retained work after the rollback: %+v", q) |
| + } |
| + if attempt, session, keptNow := macAskPin(t, inst, worker, q.ID); attempt != 1 || session != kept[0] || keptNow != kept[0] { |
| + t.Fatalf("answered from attempt %d session %q (kept %q), want the session kept before the rollback, %q", attempt, session, keptNow, kept[0]) |
| + } |
| + }) |
| +} |
| + |
| +// branchInstance is the branch point's instance in its own process. |
| +type branchInstance struct { |
| + URL, Team, Token, DB string |
| + Primary, Worker runnerproto.RunnerCredential |
| + stop func() |
| +} |
| + |
| +// startBranchInstance starts the branch point's instance on the database |
| +// at db: made there afresh (a primary and a worker enrolled), or opened |
| +// as it is. |
| +func startBranchInstance(t *testing.T, old, db string, existing bool) *branchInstance { |
| + t.Helper() |
| + out := filepath.Join(t.TempDir(), "instance.json") |
| + cmd := exec.Command(old, "-test.run", "^TestM9OldInstance$", "-test.timeout", "20m") |
| + cmd.Env = append(os.Environ(), "EQUIPO_M9_OUT="+out, "EQUIPO_M9_DB="+db) |
| + if existing { |
| + cmd.Env = append(cmd.Env, "EQUIPO_M9_EXISTING=1") |
| + } |
| + stdin, _ := cmd.StdinPipe() |
| + var logs bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &logs, &logs |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + var once sync.Once |
| + b := &branchInstance{} |
| + b.stop = func() { |
| + once.Do(func() { |
| + stdin.Close() |
| + done := make(chan error, 1) |
| + go func() { done <- cmd.Wait() }() |
| + select { |
| + case <-done: |
| + case <-time.After(30 * time.Second): |
| + cmd.Process.Kill() |
| + <-done |
| } |
| - n++ |
| + }) |
| + } |
| + t.Cleanup(b.stop) |
| + for deadline := time.Now().Add(2 * time.Minute); ; time.Sleep(100 * time.Millisecond) { |
| + raw, err := os.ReadFile(out) |
| + if err == nil && json.Unmarshal(raw, b) == nil { |
| + return b |
| } |
| - rows.Close() |
| - // Its own Claude connection is still on disk, for a 37 instance. |
| - raw, err := os.ReadFile(worker.cfg.AccountBindingsPath) |
| - if err != nil || !strings.Contains(string(raw), `"`+macClaude+`"`) { |
| - t.Fatalf("the worker's bindings after the rolled-back instance: %s %v", raw, err) |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the branch point's instance did not start: %s", logs.String()) |
| } |
| - if _, err := os.Stat(filepath.Join(worker.root, "accounts", macClaude, provider.TokenFile)); err != nil { |
| - t.Fatalf("the worker's token: %v", err) |
| + } |
| +} |
| + |
| +func copyFile(t *testing.T, from, to string) { |
| + t.Helper() |
| + raw, err := os.ReadFile(from) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(from + "-wal"); err == nil { |
| + t.Fatalf("%s was not closed cleanly (its WAL is there)", from) |
| + } |
| + if err := os.WriteFile(to, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +type outboxRow struct { |
| + kind string |
| + acked bool |
| +} |
| + |
| +// workerOutbox is every frame of the worker's outbox, by id. |
| +func workerOutbox(t *testing.T, worker *localRunner) map[string]outboxRow { |
| + t.Helper() |
| + d, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + rows, err := d.Query("SELECT id, kind, acked FROM outbox") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + out := map[string]outboxRow{} |
| + for rows.Next() { |
| + var id string |
| + var r outboxRow |
| + if err := rows.Scan(&id, &r.kind, &r.acked); err != nil { |
| + t.Fatal(err) |
| } |
| - t.Logf("rolled back: worker at %d, %d frames, task %s %s", protocol, n, id, k.Stage) |
| - }) |
| + out[id] = r |
| + } |
| + return out |
| +} |
| + |
| +// workerRefs is every candidate ref of the worker's stores, as |
| +// "<ref> <sha>", sorted. |
| +func workerRefs(t *testing.T, worker *localRunner) []string { |
| + t.Helper() |
| + stores, _ := filepath.Glob(filepath.Join(worker.cfg.StateDir, "worker", "objects", "*.git")) |
| + var out []string |
| + for _, store := range stores { |
| + raw, err := exec.Command("git", "--git-dir="+store, "for-each-ref", "--format=%(refname) %(objectname)", "refs/equipo").Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, strings.Fields(strings.ReplaceAll(string(raw), " ", "\x00"))...) |
| + } |
| + for i := range out { |
| + out[i] = strings.ReplaceAll(out[i], "\x00", " ") |
| + } |
| + slices.Sort(out) |
| + return out |
| } |
| // jsonEqual compares two JSON documents by value. |
diff --git a/internal/headless/mac_test.go b/internal/headless/mac_test.go| index d97cb7c0..55d9f1ac 100644 |
| --- a/internal/headless/mac_test.go |
| +++ b/internal/headless/mac_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "strconv" |
| "strings" |
| "testing" |
| "time" |
| @@ -50,6 +51,7 @@ func seedIOS(t *testing.T, root string, f *localForge, repo string, gate map[str |
| work := filepath.Join(root, "seed-"+filepath.Base(repo)) |
| files := map[string]string{ |
| "README.md": "# Woodstar\n\nAn iOS reading app with sliding panes.\n", |
| + ".gitignore": "build/\n", |
| ".equipo/gates.json": "{\"version\":1,\"files\":[]}\n", |
| "Woodstar/Swipe.swift": "let edgeSwipe = false\n", |
| "Woodstar/About.swift": "let about = \"An iOS reading app\"\n", |
| @@ -257,6 +259,82 @@ func staticBinary(path string) bool { |
| return true |
| } |
| +// procIdentity is a process by pid and start time (/proc's starttime): |
| +// a pid used again is another process. |
| +type procIdentity struct { |
| + PID int |
| + Start string |
| +} |
| + |
| +func startTime(pid int) string { |
| + raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) |
| + if err != nil { |
| + return "" |
| + } |
| + end := strings.LastIndexByte(string(raw), ')') |
| + f := strings.Fields(string(raw[end+1:])) |
| + if end < 0 || len(f) < 20 || f[0] == "Z" { |
| + return "" |
| + } |
| + return f[19] |
| +} |
| + |
| +func (p procIdentity) alive() bool { return p.PID > 0 && startTime(p.PID) == p.Start } |
| + |
| +// lingering is the launch's lingering child (the fake CLI's linger:), |
| +// once it has said its pid (in this test's own file), checked to carry |
| +// the attempt's Engineering marker. |
| +func lingering(t *testing.T, pidfile string) procIdentity { |
| + t.Helper() |
| + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(50 * time.Millisecond) { |
| + raw, err := os.ReadFile(pidfile) |
| + if pid, perr := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && perr == nil { |
| + env, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "environ")) |
| + if !strings.Contains(string(env), "EQUIPO_ATTEMPT=engineering-") { |
| + t.Fatalf("the lingering child %d is not the attempt's", pid) |
| + } |
| + return procIdentity{PID: pid, Start: startTime(pid)} |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("the launch's lingering child never started") |
| + } |
| + } |
| +} |
| + |
| +// workedIn is the directory a fake CLI's reply says it worked in |
| +// (saycwd). |
| +func workedIn(summary string) string { |
| + _, rest, ok := strings.Cut(summary, "Working in ") |
| + if !ok { |
| + return "" |
| + } |
| + dir, _, _ := strings.Cut(rest, " ") |
| + return strings.TrimSuffix(dir, ".") |
| +} |
| + |
| +// workerKept is the sessions the worker keeps for a step, from its own |
| +// state. |
| +func workerKept(t *testing.T, worker *localRunner, step string) []string { |
| + t.Helper() |
| + d, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer d.Close() |
| + rows, err := d.Query("SELECT session_id FROM kept_sessions WHERE step_id = ? ORDER BY attempt", step) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var sid string |
| + _ = rows.Scan(&sid) |
| + out = append(out, sid) |
| + } |
| + return out |
| +} |
| + |
| // macClaude is the fake Mac's own Claude token connection. |
| const macClaude = "mac-claude" |
| @@ -503,11 +581,14 @@ func TestMacWorker(t *testing.T) { |
| // the end by process group, and only then does Retry run the checks |
| // again, which pass. |
| t.Run("M4", func(t *testing.T) { |
| + // Its own precondition: the worker running, started here. |
| + worker.stop(t) |
| worker.start(t) |
| if err := os.WriteFile(xcodebuild+".hang", nil, 0600); err != nil { |
| t.Fatal(err) |
| } |
| - sent := s.send(t, "tool:record_task:woodstar/woodstar|Killed mid checks|Tighten the summary line.\ntool:start_task:$task|edit:Woodstar/About.swift|reading app (m2a)|reading app (m4)") |
| + t.Cleanup(func() { os.Remove(xcodebuild + ".hang") }) |
| + sent := s.send(t, "tool:record_task:woodstar/woodstar|Killed mid checks|Tighten the summary line.\ntool:start_task:$task|create:Woodstar/Summary.swift|let summaryTitle = 4\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| id := s.taskOf(t, sent.Turn.ID) |
| s.wait(t, "checks running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool { |
| for _, st := range c.Tasks[id].Steps { |
| @@ -619,7 +700,10 @@ func TestMacWorker(t *testing.T) { |
| bare := env.ForgePath(panes) |
| refuse := refusePushes(t, bare) |
| before := macDispatches(t, inst, worker.runnerID) |
| - sent := s.send(t, "tool:record_task:woodstar/panes|Pane back gesture|Add the back gesture to the panes.\ntool:start_task:$task|create:Woodstar/Pane.swift|let paneBack = false") |
| + // The first round also leaves a file its commit ignores (build/), |
| + // and says where it worked; the fix round (from the checks' |
| + // output) says where it works and whether that file is there. |
| + sent := s.send(t, "tool:record_task:woodstar/panes|Pane back gesture|Add the back gesture to the panes.\ntool:start_task:$task|create:Woodstar/Pane.swift|let paneBack = false\ncreate:build/leftover.txt|left by the first round\nsaycwd") |
| id := s.taskOf(t, sent.Turn.ID) |
| paneTask = id |
| s.wait(t, "the publication refused", 3*time.Minute, func(c *thintest.Conversation) bool { |
| @@ -653,6 +737,27 @@ func TestMacWorker(t *testing.T) { |
| if fix.Round != 1 || fix.RunnerID != worker.runnerID || fix.BaseSHA != first.CandidateSHA || !fix.Pushed || !strings.Contains(fix.Summary, "(resumed session)") || fix.Account != macClaude { |
| t.Fatalf("fix round %+v", fix) |
| } |
| + // The very session of the first round, resumed in a fresh tree |
| + // of its commit: another directory, without the file the first |
| + // round left uncommitted. |
| + var s0, s1 string |
| + db := inst.DB.Writer() |
| + if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", first.ID).Scan(&s0); err != nil || s0 == "" { |
| + t.Fatalf("the first round's session %q %v", s0, err) |
| + } |
| + if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", fix.ID).Scan(&s1); err != nil || s1 != s0 { |
| + t.Fatalf("the fix round resumed session %q, the first round's was %q (%v)", s1, s0, err) |
| + } |
| + if kept := workerKept(t, worker, fix.ID); len(kept) != 1 || kept[0] != s0 { |
| + t.Fatalf("the worker kept %v for the fix round, want [%s]", kept, s0) |
| + } |
| + dir0, dir1 := workedIn(first.Summary), workedIn(fix.Summary) |
| + if dir0 == "" || dir1 == "" || dir0 == dir1 || !strings.Contains(dir0, "/worker-steps/") || !strings.Contains(dir1, "/worker-steps/") { |
| + t.Fatalf("worktrees %q then %q (%q / %q)", dir0, dir1, first.Summary, fix.Summary) |
| + } |
| + if !strings.Contains(first.Summary, "Created build/leftover.txt.") || !strings.Contains(fix.Summary, "No build/leftover.txt.") { |
| + t.Fatalf("the fix round's tree is not fresh: %q / %q", first.Summary, fix.Summary) |
| + } |
| if passed.Checks != wire.ChecksPassed || passed.CandidateSHA != fix.CandidateSHA || k.Stage != wire.StageReadyToMerge || k.CandidateSHA != fix.CandidateSHA { |
| t.Fatalf("after the fix round %+v / %+v", passed, k) |
| } |
| @@ -741,7 +846,11 @@ func TestMacWorker(t *testing.T) { |
| if err := os.WriteFile(hold, nil, 0600); err != nil { |
| t.Fatal(err) |
| } |
| - sent := s.send(t, "tool:record_task:woodstar/panes|Killed mid Engineering|Name the app in About.\ntool:start_task:$task|stepwait:"+hold+" edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with panes\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| + // The CLI also starts a child in a session of its own that ignores |
| + // SIGTERM and SIGHUP and keeps the attempt's marker: it outlives |
| + // the runner, and only the restart's recovery may end it. |
| + linger := filepath.Join(t.TempDir(), "linger.pid") |
| + sent := s.send(t, "tool:record_task:woodstar/panes|Killed mid Engineering|Name the app in About.\ntool:start_task:$task|linger:"+linger+" stepwait:"+hold+" edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with panes\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") |
| id := s.taskOf(t, sent.Turn.ID) |
| killedTask = id |
| defer func() { |
| @@ -754,13 +863,13 @@ func TestMacWorker(t *testing.T) { |
| e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0) |
| return e.RunnerID == worker.runnerID && e.State == wire.StepRunning && e.StartedAt != nil |
| }) |
| - // The CLI is in its turn: its process carries the attempt's marker. |
| - for deadline := time.Now().Add(time.Minute); len(engineeringProcs(worker)) == 0; time.Sleep(50 * time.Millisecond) { |
| - if time.Now().After(deadline) { |
| - t.Fatal("the CLI never started on the worker") |
| - } |
| - } |
| + // The CLI is in its turn: it has started its lingering child, |
| + // which carries the attempt's marker. |
| + child := lingering(t, linger) |
| worker.kill(t) |
| + if !child.alive() { |
| + t.Fatalf("the launch's lingering child %+v did not outlive the runner", child) |
| + } |
| if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 { |
| t.Fatalf("retry before the worker proved the end: %v", err) |
| } |
| @@ -780,6 +889,11 @@ func TestMacWorker(t *testing.T) { |
| if e.Reason != "runner_restarted" || e.TerminationKind != wire.TerminationProcessGroup || e.RunnerID != worker.runnerID || k.NeedsYou != wire.NeedsRetry { |
| t.Fatalf("after the restart %+v (needs %q)", e, k.NeedsYou) |
| } |
| + // Recovery ended it, by its identity, before the end was proven |
| + // (and so before the clearance and any Retry). |
| + if child.alive() { |
| + t.Fatalf("the launch's lingering child %+v survived the restart, and the end was proven", child) |
| + } |
| if left := engineeringProcs(worker); len(left) > 0 { |
| t.Fatalf("processes %v of the killed attempt survived the restart", left) |
| } |
diff --git a/internal/headless/xcodebuild_test.go b/internal/headless/xcodebuild_test.go| index fa6caee2..39e1ba4e 100644 |
| --- a/internal/headless/xcodebuild_test.go |
| +++ b/internal/headless/xcodebuild_test.go |
| @@ -22,7 +22,13 @@ func fakeXcodebuild() int { |
| for _, c := range [][2]string{{"Woodstar/Swipe.swift", "edgeSwipe"}, {"Woodstar/Pane.swift", "paneBack"}} { |
| src, _ := os.ReadFile(c[0]) |
| if strings.Contains(string(src), c[1]+" = false") { |
| - fmt.Printf("%s:1: error: XCTAssertTrue failed: %s is false. edit:%s|%s = false|%s = true\n** TEST FAILED **\n", c[0], c[1], c[0], c[1], c[1]) |
| + fmt.Printf("%s:1: error: XCTAssertTrue failed: %s is false. edit:%s|%s = false|%s = true\n", c[0], c[1], c[0], c[1], c[1]) |
| + if c[1] == "paneBack" { |
| + // The fix round says where it works and whether the |
| + // first round's uncommitted file is there (M9b). |
| + fmt.Println("note: probe:build/leftover.txt saycwd") |
| + } |
| + fmt.Println("** TEST FAILED **") |
| return 65 |
| } |
| } |
diff --git a/internal/runner/mac/creds/boot_testbuild.go b/internal/runner/mac/creds/boot_testbuild.go| new file mode 100644 |
| index 00000000..ac4adb37 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/boot_testbuild.go |
| @@ -0,0 +1,9 @@ |
| +//go:build testbuild |
| + |
| +package creds |
| + |
| +import "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| + |
| +// BootForTest makes Boot answer boot (a test build's reboot); nil reads |
| +// the machine's again. |
| +func BootForTest(boot func() (proc.Boot, error)) { bootStandIn = boot } |
diff --git a/internal/runner/mac/creds/guard.go b/internal/runner/mac/creds/guard.go| index f9eedc90..8e55f96b 100644 |
| --- a/internal/runner/mac/creds/guard.go |
| +++ b/internal/runner/mac/creds/guard.go |
| @@ -318,8 +318,15 @@ func within(home, p string) bool { |
| return p == home || strings.HasPrefix(p, home+"/") |
| } |
| +// bootStandIn stands in for this machine's boot in a test build |
| +// (BootForTest); nil in every other build. |
| +var bootStandIn func() (proc.Boot, error) |
| + |
| // Boot is this boot: its identity (BootID) and when it began (BootTime). |
| func Boot() (proc.Boot, error) { |
| + if bootStandIn != nil { |
| + return bootStandIn() |
| + } |
| t, err := BootTime() |
| if err != nil { |
| return proc.Boot{}, err |
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go| index c5fef010..82a1c56e 100644 |
| --- a/internal/runner/thin/contract_test.go |
| +++ b/internal/runner/thin/contract_test.go |
| @@ -47,6 +47,11 @@ func TestMain(m *testing.M) { |
| if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| os.Exit(containment.NamespaceMain(os.Args[2:])) |
| } |
| + if testHelper != nil { |
| + if code, ok := testHelper(); ok { |
| + os.Exit(code) |
| + } |
| + } |
| // The fake carlos binaries answer no version verb: a current release |
| // stands in, and the guard's own tests set theirs. |
| readCarlosVersion = func(context.Context, string) string { return "v0.43.3" } |
| @@ -57,6 +62,10 @@ func TestMain(m *testing.M) { |
| os.Exit(code) |
| } |
| +// testHelper, when a test build's file sets it, may run this binary as |
| +// one of its helper processes instead of the tests (ok). |
| +var testHelper func() (code int, ok bool) |
| + |
| // stubCoordinator streams two deltas and replies, or waits to be cancelled. |
| type stubCoordinator struct { |
| mu sync.Mutex |
diff --git a/internal/runner/thin/fakeworker_check_test.go b/internal/runner/thin/fakeworker_check_test.go| new file mode 100644 |
| index 00000000..222818db |
| --- /dev/null |
| +++ b/internal/runner/thin/fakeworker_check_test.go |
| @@ -0,0 +1,128 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/runner/mac/creds" |
| + "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// fakeCheckEnv starts this binary as a fake worker's checks gate running |
| +// a check that never ends, in the directory it names (the gate as |
| +// EQUIPO_TEST_FAKE_CHECK_SANDBOX plays it). |
| +const fakeCheckEnv = "EQUIPO_TEST_FAKE_CHECK" |
| + |
| +const fakeCheckAttempt = "checks/0123456789abcdef" |
| + |
| +func init() { |
| + testHelper = func() (int, bool) { |
| + dir := os.Getenv(fakeCheckEnv) |
| + if dir == "" { |
| + return 0, false |
| + } |
| + entry := proc.ScopeEnv + "=" + os.Getenv(proc.ScopeEnv) |
| + turns := mac.NewTurns(filepath.Join(dir, "mac-gate.lock")).Sweep(proc.Scoped(entry)) |
| + g, err := fakeWorker{}.checksGate(dir, dir, os.Getenv(fakeCheckEnv+"_SANDBOX"), turns, entry) |
| + tree := filepath.Join(dir, "tree") |
| + if err != nil || os.MkdirAll(tree, 0o700) != nil { |
| + return 2, true |
| + } |
| + g.Run(context.Background(), fakeCheckAttempt, tree, []string{"/bin/sleep", "600"}, 10*time.Minute, func(id string) error { |
| + return os.WriteFile(filepath.Join(dir, "record"), []byte(id), 0o600) |
| + }) |
| + return 0, true |
| + } |
| +} |
| + |
| +// TestFakeWorkerCrashedCheck: a fake worker killed mid-check leaves its |
| +// turn's record incomplete. Playing a seatbelt Mac (the srt stand-in) |
| +// the turn ran nothing unsandboxed, so the restart's idle read proves |
| +// it over, as on a Mac. Without a sandbox it is never cleared at this |
| +// boot, even with nothing left of it: only a reboot clears it (task 9). |
| +func TestFakeWorkerCrashedCheck(t *testing.T) { |
| + for _, c := range []struct { |
| + name, sandbox string |
| + idle bool |
| + }{{"seatbelt", wire.SandboxSeatbelt, true}, {"unsandboxed", "", false}} { |
| + t.Run(c.name, func(t *testing.T) { |
| + dir := shortDir(t) |
| + raw := make([]byte, 8) |
| + _, _ = rand.Read(raw) |
| + entry := proc.ScopeEnv + "=fc" + hex.EncodeToString(raw) |
| + table := proc.Scoped(entry) |
| + t.Cleanup(func() { |
| + list, _ := table.List(time.Time{}, nil) |
| + for _, q := range list { |
| + _ = syscall.Kill(q.PID, syscall.SIGKILL) |
| + } |
| + }) |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command(self, "-test.run=^$") |
| + cmd.Env = append(os.Environ(), fakeCheckEnv+"="+dir, fakeCheckEnv+"_SANDBOX="+c.sandbox, entry) |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + var record string |
| + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(20 * time.Millisecond) { |
| + raw, _ := os.ReadFile(filepath.Join(dir, "record")) |
| + if record = string(raw); strings.HasPrefix(record, "pg:") && !strings.HasPrefix(record, "pg:0:") { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + cmd.Process.Kill() |
| + cmd.Wait() |
| + t.Fatal("the check never started") |
| + } |
| + } |
| + // The runner dies mid-check; the check lives on. |
| + _ = cmd.Process.Kill() |
| + _ = cmd.Wait() |
| + if list, _ := table.List(time.Time{}, []string{fakeCheckAttempt}); len(list) == 0 { |
| + t.Fatal("nothing of the check outlived the runner") |
| + } |
| + turns := mac.NewTurns(filepath.Join(dir, "mac-gate.lock")).Sweep(table) |
| + x := &mac.Executor{Turns: turns, Settle: 5 * time.Second} |
| + if got := x.Verify(record); got != c.idle { |
| + t.Fatalf("at this boot, proven %v, want %v", got, c.idle) |
| + } |
| + if list, _ := table.List(time.Time{}, []string{fakeCheckAttempt}); len(list) != 0 { |
| + t.Fatalf("the restart left %d of the check's processes", len(list)) |
| + } |
| + if c.idle { |
| + return |
| + } |
| + // Nothing of it is left, yet the idle read may not clear it. |
| + if again := x.Verify(record); again { |
| + t.Fatal("an unsandboxed turn was cleared by the idle read") |
| + } |
| + if code, _ := turns.Unproven(); code == "" { |
| + t.Fatal("the Mac does not say the attempt is unproven") |
| + } |
| + now, err := creds.Boot() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + creds.BootForTest(func() (proc.Boot, error) { return proc.Boot{ID: now.ID + "-next", Time: time.Now()}, nil }) |
| + t.Cleanup(func() { creds.BootForTest(nil) }) |
| + if !x.Verify(record) { |
| + t.Fatal("a reboot did not clear the unsandboxed turn") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/thin/fakeworker_testbuild.go b/internal/runner/thin/fakeworker_testbuild.go| index 349fba8a..4c1a1ed4 100644 |
| --- a/internal/runner/thin/fakeworker_testbuild.go |
| +++ b/internal/runner/thin/fakeworker_testbuild.go |
| @@ -114,9 +114,9 @@ var fakeScope = regexp.MustCompile(`^[A-Za-z0-9]{8,64}$`) |
| const fakeUserTemp = mac.UserTempPrefix + "/eq/fake-worker/T" |
| // setup is the fake Mac worker: the fixture report, composed as a Mac |
| -// composes its own with what its guards and records say now; the gate, |
| -// over the Mac's turns as a Mac's checks gate is; and the Mac's |
| -// credential operations and Engineering pieces (engineering). |
| +// composes its own with what its guards and records say now; the gate |
| +// (checksGate); and the Mac's credential operations and Engineering |
| +// pieces (engineering). |
| func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (workerSetup, error) { |
| m, eng, err := f.engineering(ctx, c, o) |
| if err != nil { |
| @@ -142,15 +142,39 @@ func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (wor |
| } |
| return caps |
| } |
| - // The gate takes the Mac's turn and carries the fake's scope, as a |
| - // Mac's checks gate takes its turn over the runner user: a check is |
| - // never swept by an Engineering turn's end, and one a crash left is |
| - // ended, and proven over, as a Mac's is. |
| - gate := f.gate(o.FakeBin, o.FakeSandbox).(macGate) |
| - gate.g.Env, gate.g.Turns = append(gate.g.Env, proc.ScopeEnv+"="+os.Getenv(proc.ScopeEnv)), m.turns |
| + gate, err := f.checksGate(m.paths.InstallDir, o.FakeBin, o.FakeSandbox, m.turns, proc.ScopeEnv+"="+os.Getenv(proc.ScopeEnv)) |
| + if err != nil { |
| + return workerSetup{}, err |
| + } |
| return workerSetup{probe: probe, gate: gate, creds: m, engineering: eng}, nil |
| } |
| +// fakeSRT is the test build's stand-in for srt, for a fake that plays a |
| +// Mac whose probe P2 denied: it takes srt's own arguments (--settings |
| +// <file> --) and runs the command, so the gate runs it as a seatbelt |
| +// Mac's runs it under srt, and its turn is a sandboxed one. |
| +const fakeSRT = "#!/bin/sh\nwhile [ \"$#\" -gt 0 ] && [ \"$1\" != \"--\" ]; do shift; done\nshift\nexec \"$@\"\n" |
| + |
| +// checksGate is the fake's checks gate (gate) as a Mac's is: over the |
| +// Mac's turns, its processes in the fake's scope (entry). Playing a |
| +// seatbelt Mac, it runs under the srt stand-in written in dir, so a |
| +// check killed mid-run is cleared as a seatbelt Mac's is (the idle |
| +// read); otherwise without a sandbox, which only a reboot clears (task |
| +// 9). |
| +func (f fakeWorker) checksGate(dir, bin, sandbox string, turns *mac.Turns, entry string) (GateRunner, error) { |
| + g := f.gate(bin, sandbox).(macGate) |
| + g.g.Env, g.g.Turns = append(g.g.Env, entry), turns |
| + if sandbox == wire.SandboxSeatbelt { |
| + srt := filepath.Join(dir, "srt") |
| + if err := os.WriteFile(srt, []byte(fakeSRT), 0o700); err != nil { |
| + return nil, err |
| + } |
| + g.g.SRT = srt |
| + g.g.Settings = func(string, string) ([]byte, error) { return []byte("{}"), nil } |
| + } |
| + return g, nil |
| +} |
| + |
| // engineering is the fake Mac's credential operations and Engineering |
| // pieces. Its home is the directory above its state dir (the runner |
| // user's home on a Mac); the stand-in is provisioned into the install |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index 67142292..bea190cf 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -484,6 +484,12 @@ func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error |
| // the outbox for a connection that speaks it. |
| return nil |
| } |
| + if f.Type == wire.FrameStep && (l.WorkerOnly || role == wire.RoleWorker) && proto < wire.ProtocolMacEngineering && l.State.engineeringReport(ctx, f) { |
| + // Nor of its Engineering, which only 37 places: an older instance |
| + // (a rollback) takes a report of a step it never dispatched and |
| + // drops it, and the work would be lost when 37 is back (M9g). |
| + return nil |
| + } |
| if f.Type == wire.FrameToolCall { |
| body, err := f.Decode() |
| if err != nil { |
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go| index f3f1c01b..f361b5f8 100644 |
| --- a/internal/runner/thin/step.go |
| +++ b/internal/runner/thin/step.go |
| @@ -286,6 +286,23 @@ func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport) |
| }) |
| } |
| +// engineeringReport: f is a step report of an Engineering attempt |
| +// dispatched here (its row's dispatch says so). Anything unreadable is |
| +// not. |
| +func (s *State) engineeringReport(ctx context.Context, f wire.Frame) bool { |
| + body, err := f.Decode() |
| + rep, ok := body.(*wire.StepReport) |
| + if err != nil || !ok { |
| + return false |
| + } |
| + var raw string |
| + if s.db.QueryRowContext(ctx, "SELECT body FROM steps WHERE step_id=? AND attempt=?", rep.StepID, rep.Attempt).Scan(&raw) != nil { |
| + return false |
| + } |
| + var d wire.DispatchCommand |
| + return json.Unmarshal([]byte(raw), &d) == nil && d.Specialist == wire.SpecialistEngineering |
| +} |
| + |
| // unfinishedReport is a queued step report as the sender sends it at |
| // protocol: at ProtocolUnfinishedWork or later, a step that failed |
| // step_timeout whose attempt pushed its unfinished work (its row: done, |
| @@ -571,6 +588,9 @@ type StepEngine struct { |
| // Verify reports whether a namespace's exit is verified now (its |
| // record released after proof, or gone). |
| Verify func(ctx context.Context, nsID string) bool |
| + // Acknowledge, if set, is told of each namespace whose proven exit |
| + // is committed here: only then may the proof's evidence go (a Mac's). |
| + Acknowledge func(ctx context.Context, nsID string) |
| // TerminationKind is how this runner proves an attempt's end |
| // (wire.TerminationNamespace on Linux), reported with termination. |
| TerminationKind string |
| @@ -623,7 +643,11 @@ func (e *StepEngine) Probe(ctx context.Context) { |
| if !e.Verify(ctx, p.ns) { |
| continue |
| } |
| - e.log("step probe", e.State.proveTermination(ctx, p)) |
| + err := e.State.proveTermination(ctx, p) |
| + e.log("step probe", err) |
| + if err == nil && e.Acknowledge != nil { |
| + e.Acknowledge(ctx, p.ns) |
| + } |
| sent = true |
| } |
| if e.Meter != nil { |
| @@ -637,9 +661,31 @@ func (e *StepEngine) Probe(ctx context.Context) { |
| } |
| } |
| +// recoverSteps is State.RecoverSteps, acknowledging each proven exit |
| +// once the recovery has committed it. |
| +func (e *StepEngine) recoverSteps(ctx context.Context) error { |
| + verify, proven := e.Verify, []string{} |
| + if verify != nil && e.Acknowledge != nil { |
| + verify = func(ctx context.Context, id string) bool { |
| + ok := e.Verify(ctx, id) |
| + if ok { |
| + proven = append(proven, id) |
| + } |
| + return ok |
| + } |
| + } |
| + if err := e.State.RecoverSteps(ctx, verify); err != nil { |
| + return err |
| + } |
| + for _, id := range proven { |
| + e.Acknowledge(ctx, id) |
| + } |
| + return nil |
| +} |
| + |
| // Start recovers what a previous process left and starts the worker. |
| func (e *StepEngine) Start(ctx context.Context) error { |
| - if err := e.State.RecoverSteps(ctx, e.Verify); err != nil { |
| + if err := e.recoverSteps(ctx); err != nil { |
| return err |
| } |
| if err := e.State.RecoverAsks(ctx, e.Verify); err != nil { |