//go:build testbuild package headless import ( "bytes" "database/sql" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // branchPoint is main where Mac runners slice F branched: protocol 35, // Mac work waiting for a Mac, no Engineering on one. M9g runs its // runner, fake Mac worker (the test build) and instance against this // branch's. const branchPoint = "8bd40ed15aae17b594ce2f0fe07e02978b80222f" // oldMacInstanceTest is added to the branch point's tree when its test // binary is built: an instance of that release, in its own process, with // a primary and a worker enrolled, until stdin closes. const oldMacInstanceTest = `package headless import ( "encoding/json" "io" "os" "testing" "amadan.net/oficina/equipo/internal/thintest" ) func TestM9OldInstance(t *testing.T) { out := os.Getenv("EQUIPO_M9_OUT") if out == "" { t.Skip("M9g only") } // 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) 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) } if err := os.Rename(out+".tmp", out); err != nil { t.Fatal(err) } _, _ = io.Copy(io.Discard, os.Stdin) } ` // branchBinary is the branch point's headless test binary, with the // test build (its fake Mac worker) and the old instance above, built // once and cached as M8's is. func branchBinary(t *testing.T) string { return oldBinaryAt(t, branchPoint, "testbuild", map[string]string{"m9_old_instance_test.go": oldMacInstanceTest}) } // workerOnline waits for the worker labelled Tito Studio. func (s *session) workerOnline(t *testing.T) { t.Helper() s.wait(t, "the worker online", 30*time.Second, func(c *thintest.Conversation) bool { for _, r := range c.Runners { if r.Role == wire.RoleWorker && r.Online && r.Label == "Tito Studio" { return true } } return false }) } // waitsForUpdate sends a Panes change (Mac work) and waits for its // Engineering to wait for the update of who, never dispatched. func (s *session) waitsForUpdate(t *testing.T, inst *thintest.Instance, worker, who string) { t.Helper() sent := s.send(t, "tool:record_task:woodstar/panes|Pane titles, mixed|Say what each pane is for.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true") id := s.taskOf(t, sent.Turn.ID) s.wait(t, "Engineering waiting for the update", 2*time.Minute, func(c *thintest.Conversation) bool { return stepOf(c.Tasks[id], wire.SpecialistEngineering, 0).Placement == wire.PlacementMacUpdate }) k, err := s.env.Client.Task(s.ctx, id) if err != nil { t.Fatal(err) } eng := stepOf(k, wire.SpecialistEngineering, 0) var waits string if err := inst.DB.Writer().QueryRow("SELECT coalesce(sandbox_runner, '') FROM chat_steps WHERE id = ?", eng.ID).Scan(&waits); err != nil { t.Fatal(err) } if eng.State != wire.StepQueued || eng.RunnerID != "" || waits != who { t.Fatalf("waiting for %q to update: %+v (waits for %q)", who, eng, waits) } // A moment more: nothing is dispatched anywhere meanwhile. time.Sleep(2 * time.Second) var dispatched int if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND instr(body, ?) > 0", wire.FrameDispatch, eng.ID).Scan(&dispatched); err != nil || dispatched != 0 { t.Fatalf("%d dispatches of the waiting Engineering step (%v)", dispatched, err) } if _, err := s.env.Client.CancelTask(s.ctx, id); err != nil { t.Fatal(err) } } func sessionProtocol(t *testing.T, inst *thintest.Instance, runner string) int { t.Helper() var p int if err := inst.DB.Writer().QueryRow("SELECT protocol FROM runner_sessions WHERE runner_id = ?", runner).Scan(&p); err != nil { t.Fatal(err) } return p } // M9g: mixed versions with main at the branch point (protocol 35). Mac // Engineering needs 37 on both the primary and the worker: either one // older, and it waits for that one's update (waiting_mac_update), // dispatched nowhere. A 37 worker against an instance rolled back to // the branch point speaks 35 in its hello, queues nothing only 37 // carries, and loses nothing: its Claude connection stays, and it still // takes checks. func TestMacMixedVersions(t *testing.T) { if testing.Short() { t.Skip("builds main at the branch point") } old := branchBinary(t) t.Run("old worker, new primary", func(t *testing.T) { env, inst, primary := localEnv(t) addWoodstar(t, primary.root, primary.opts.Forge.(*localForge)) woodstarCredentials(t, primary) primary.start(t) inst.Store.Chat().SetMacEngineering(true) worker, _ := macWorker(t, inst, primary) worker.binary = old worker.start(t) s := open(t, env) s.keep() s.workerOnline(t) if p := sessionProtocol(t, inst, worker.runnerID); p != wire.Protocol35 { t.Fatalf("the branch point's worker speaks %d", p) } s.waitsForUpdate(t, inst, worker.runnerID, worker.runnerID) }) t.Run("new worker, old primary", func(t *testing.T) { env, inst, primary := localEnv(t) addWoodstar(t, primary.root, primary.opts.Forge.(*localForge)) woodstarCredentials(t, primary) primary.subprocess, primary.binary = true, old primary.start(t) var primaryID string if err := inst.DB.Writer().QueryRow("SELECT runner_id FROM runner_sessions WHERE connected = 1").Scan(&primaryID); err != nil { t.Fatal(err) } inst.Store.Chat().SetMacEngineering(true) worker, _ := macWorker(t, inst, primary) worker.start(t) s := open(t, env) s.keep() s.workerOnline(t) if p, w := sessionProtocol(t, inst, primaryID), sessionProtocol(t, inst, worker.runnerID); p != wire.Protocol35 || w != wire.ProtocolCurrent { t.Fatalf("protocols: primary %d, worker %d", p, w) } s.waitsForUpdate(t, inst, worker.runnerID, primaryID) }) // 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.ProtocolCurrent { t.Fatalf("at 37 or later 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) } 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 }) 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") } } 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) { 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)) } } 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.cfg.Origin, worker.inst, worker.instanceDB = old35.URL, nil, back worker.start(t) d, err := sql.Open("sqlite", "file:"+back+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } var protocol int var hello string 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 if err := json.Unmarshal([]byte(hello), &h); err != nil || h.Capabilities == nil { t.Fatalf("hello %s: %v", hello, err) } 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) } // 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) } } 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) } 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.ProtocolCurrent { 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 of %d queued frames sent at 37", sent, len(queued)) } } 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)) } 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 } }) } 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 } if time.Now().After(deadline) { t.Fatalf("the branch point's instance did not start: %s", logs.String()) } } } 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) } out[id] = r } return out } // workerRefs is every candidate ref of the worker's stores, as // " ", 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 }