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" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // slice4 is the protocol 1 release the mixed-version tests run against: // the staging line (thin-v1-composer at 0797ad0: slice 4c with // connections, housekeeping and attachments), which this branch upgrades // from. (The spec names ca0a65c, slice 4 itself; its wire predates the // 4b, 4c and connections frame fields, a skew those releases already // have.) const slice4 = "0797ad0762da8c3a8ebde6664583c77c9f9c34a2" // oldInstanceTest is added to the slice 4 tree when its test binary is // built: an instance of that release, in its own process, until stdin // closes. const oldInstanceTest = `package headless import ( "encoding/json" "io" "os" "testing" "amadan.net/oficina/equipo/internal/thintest" ) func TestM8OldInstance(t *testing.T) { out := os.Getenv("EQUIPO_M8_OUT") if out == "" { t.Skip("M8 only") } inst := thintest.StartInstance(t) token := inst.DeviceToken(t) cred := inst.EnrolRunner(t) raw, _ := json.Marshal(map[string]any{"url": inst.URL, "team": inst.TeamID, "token": token, "db": inst.Path, "credential": cred}) 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) } ` var oldOnce sync.Mutex // oldBinary is the slice 4 headless test binary (the real slice 4 runner // and, with the overlay above, instance), built from git history once // and kept in EQUIPO_M8_CACHE when it is set (CI keeps it as an // artifact), else in the test's own directory. func oldBinary(t *testing.T) string { return oldBinaryAt(t, slice4, "", map[string]string{"m8_old_instance_test.go": oldInstanceTest}) } // oldBinaryAt is the headless test binary of commit, built with tags // ("" for none) and the extra test files (name: source) added to its // headless package, once, and cached as oldBinary says (by commit and // tags). Nothing is downloaded: the tree comes from git history and the // modules from the module cache (-mod=readonly). func oldBinaryAt(t *testing.T, commit, tags string, extra map[string]string) string { t.Helper() oldOnce.Lock() defer oldOnce.Unlock() key := commit if 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 { cache = t.TempDir() } bin := filepath.Join(cache, key, "headless.test") if info, err := os.Stat(bin); err == nil && info.Mode().IsRegular() { return bin } if err := os.MkdirAll(filepath.Dir(bin), 0700); err != nil { bin = filepath.Join(t.TempDir(), "headless.test") } top, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { t.Fatalf("M8 needs the repository's history: %v", err) } src := t.TempDir() archive := exec.Command("git", "-C", strings.TrimSpace(string(top)), "archive", "--format=tar", commit) untar := exec.Command("tar", "-x", "-C", src) pipe, _ := archive.StdoutPipe() untar.Stdin = pipe if err := untar.Start(); err != nil { t.Fatal(err) } if err := archive.Run(); err != nil { t.Fatalf("M8 needs commit %s in the repository's history: %v", commit, err) } if err := untar.Wait(); err != nil { t.Fatal(err) } replace := map[string]string{} for name, body := range extra { file := filepath.Join(t.TempDir(), name) if err := os.WriteFile(file, []byte(body), 0600); err != nil { t.Fatal(err) } replace[filepath.Join(src, "internal", "headless", name)] = file } overlay := filepath.Join(t.TempDir(), "overlay.json") raw, _ := json.Marshal(map[string]any{"Replace": replace}) if err := os.WriteFile(overlay, raw, 0600); err != nil { t.Fatal(err) } // Niced, two compile jobs: the build must not starve the packages // testing beside it. args := []string{"go", "test", "-c", "-p", "2", "-overlay", overlay, "-o", bin + ".tmp"} if tags != "" { args = append(args, "-tags", tags) } args = append(args, "./internal/headless") if nice, err := exec.LookPath("nice"); err == nil { args = append([]string{nice, "-n", "15"}, args...) } build := exec.Command(args[0], args[1:]...) build.Dir = src build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly") if out, err := build.CombinedOutput(); err != nil { t.Fatalf("building %s at %s: %v %s", key, commit, err, out) } if err := os.Rename(bin+".tmp", bin); err != nil { t.Fatal(err) } return bin } // sampleToReady sends the typo fix on oficina/sample and waits until the // task is ready to merge or done. func sampleToReady(t *testing.T, env *Env, title string) wire.Task { t.Helper() s := open(t, env) s.keep() s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online }) sent := s.send(t, "tool:record_task:oficina/sample|"+title+"|The README says teh panes.\ntool:start_task:$task|edit:README.md|teh panes|the panes") id := s.taskOf(t, sent.Turn.ID) k := s.settled(t, id, 3*time.Minute) // settled saw ready to merge and then read the task again; by then // the instance may have started merging it, which is later, not worse. if k.Stage != wire.StageReadyToMerge && k.Stage != wire.StageMerging && k.Stage != wire.StageDone { t.Fatalf("not ready: %+v", k) } if k.Checks != wire.ChecksPassed || k.Verdict != wire.VerdictApprove { t.Fatalf("judged %+v", k) } return k } // M8: mixed versions with the real slice 4 code. func TestMixedVersions(t *testing.T) { testci.Quarantine(t) if testing.Short() { t.Skip("builds slice 4") } old := oldBinary(t) // The slice 4 runner against this instance: it speaks protocol 1, // runs the sample scenario to ready, and is never sent anything // protocol 1 lacks (no blob, no needs, nothing new in welcome). t.Run("old runner, new instance", func(t *testing.T) { env, inst, r := localEnv(t) var mu sync.Mutex var sent [][]byte inst.Store.Chat().SetFrameTap(func(_ string, raw []byte) { mu.Lock() sent = append(sent, append([]byte(nil), raw...)) mu.Unlock() }) r.subprocess, r.binary = true, old r.start(t) k := sampleToReady(t, env, "Fix the panes typo") var protocol int if err := inst.DB.Writer().QueryRow("SELECT protocol FROM runner_sessions").Scan(&protocol); err != nil || protocol != wire.Protocol1 { t.Fatalf("protocol %d %v", protocol, err) } mu.Lock() defer mu.Unlock() kinds := map[string]int{} for _, raw := range sent { f, _, err := wire.ParseFrame(raw) if err != nil { t.Fatalf("unparsable frame %s", raw) } kinds[f.Type]++ // Exactly the protocol 1 frame: nothing Encode would drop. old, err := wire.Encode(f, wire.Protocol1) if err != nil || !bytes.Equal(old.Data, f.Data) { t.Fatalf("a protocol 1 runner was sent more than protocol 1: %v %s", err, raw) } } if kinds[wire.FrameDispatch] < 3 || kinds[wire.FrameWelcome] < 1 { t.Fatalf("frames sent %v", kinds) } t.Logf("slice 4 runner: task %s %s on %s; frames %v", k.ID, k.Stage, k.CandidateSHA[:7], kinds) }) // This runner against the slice 4 instance: its protocol 2 hello is // refused once, it says hello at protocol 1, logs it, and runs the same // scenario. A worker enrolling with that instance is refused with a // clear diagnostic and nothing is created or lost. t.Run("new runner, old instance", func(t *testing.T) { out := filepath.Join(t.TempDir(), "instance.json") cmd := exec.Command(old, "-test.run", "^TestM8OldInstance$", "-test.timeout", "20m") cmd.Env = append(os.Environ(), "EQUIPO_M8_OUT="+out) stdin, _ := cmd.StdinPipe() var logs bytes.Buffer cmd.Stdout, cmd.Stderr = &logs, &logs if err := cmd.Start(); 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 } }) var info struct { URL, Team, Token, DB string Credential runnerproto.RunnerCredential } deadline := time.Now().Add(2 * time.Minute) for { raw, err := os.ReadFile(out) if err == nil && json.Unmarshal(raw, &info) == nil { break } if time.Now().After(deadline) { t.Fatalf("slice 4 instance did not start: %s", logs.String()) } time.Sleep(100 * time.Millisecond) } r, _ := runnerSetup(t, info.URL, info.Team, info.Credential) t.Cleanup(func() { r.stop(t) }) runnerLog := &lockedBuffer{} r.opts.Logger = slog.New(slog.NewTextHandler(runnerLog, nil)) turns := 0 env := &Env{Client: thintest.NewClient(info.URL, info.Token), turns: &turns, ForgePath: r.opts.Forge.(*localForge).path} r.start(t) k := sampleToReady(t, env, "Fix the panes typo") if !strings.Contains(runnerLog.String(), "the instance is older: speaking protocol 1") { t.Fatalf("no fallback line: %s", runnerLog.String()) } t.Logf("against slice 4: task %s %s on %s", k.ID, k.Stage, k.CandidateSHA[:7]) // A worker cannot enrol there. worker := runner.Config{Origin: info.URL, InstanceID: info.Team, StateDir: filepath.Join(t.TempDir(), "worker"), WorkerOnly: true} var printed bytes.Buffer err := runner.Enrol(context.Background(), worker, &printed) if code, _ := runner.Diagnostic(err); code != "runner.instance_older_than_worker" { t.Fatalf("worker enrolment with slice 4: %q %v", code, err) } d, err := sql.Open("sqlite", "file:"+info.DB+"?mode=ro&_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } defer d.Close() var runners, enrolments int d.QueryRow("SELECT count(*) FROM runners").Scan(&runners) d.QueryRow("SELECT count(*) FROM runner_enrolments").Scan(&enrolments) if runners != 1 || enrolments != 1 { t.Fatalf("the refused worker left %d runners, %d enrolments", runners, enrolments) } // Nothing lost: the primary still serves the person. s := open(t, env) sent := s.send(t, "Still there?") if turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied); turn.State != wire.TurnReplied { t.Fatalf("after the refused worker: %+v", turn) } }) } // lockedBuffer is a log sink read while the runner writes. type lockedBuffer struct { mu sync.Mutex b bytes.Buffer } func (l *lockedBuffer) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() return l.b.Write(p) } func (l *lockedBuffer) String() string { l.mu.Lock() defer l.mu.Unlock() return l.b.String() }