| new file mode 100644 |
| index 00000000..fdf17b9b |
| --- /dev/null |
| +++ b/internal/headless/m8_test.go |
| @@ -0,0 +1,304 @@ |
| +package headless |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/thintest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// slice4 is the protocol 1 release the mixed-version tests run against: |
| +// thin v1 slice 4c, the release staging serves and this branch starts |
| +// from. (The spec names ca0a65c, slice 4 itself; its wire predates the |
| +// 4b and 4c frame fields, a skew that release already has.) |
| +const slice4 = "2d1edaf08eedce9c1add0d6de584cdd7debddff0" |
| + |
| +// 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 the user cache (EQUIPO_M8_CACHE overrides; a read-only |
| +// cache falls back to the test's own directory). |
| +func oldBinary(t *testing.T) string { |
| + t.Helper() |
| + oldOnce.Lock() |
| + defer oldOnce.Unlock() |
| + cache := os.Getenv("EQUIPO_M8_CACHE") |
| + if cache == "" { |
| + if dir, err := os.UserCacheDir(); err == nil { |
| + cache = filepath.Join(dir, "equipo-m8") |
| + } |
| + } |
| + if cache == "" || os.MkdirAll(filepath.Join(cache, slice4), 0700) != nil { |
| + cache = t.TempDir() |
| + } |
| + bin := filepath.Join(cache, slice4, "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", slice4) |
| + 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", slice4, err) |
| + } |
| + if err := untar.Wait(); err != nil { |
| + t.Fatal(err) |
| + } |
| + extra := filepath.Join(t.TempDir(), "m8_old_instance_test.go") |
| + if err := os.WriteFile(extra, []byte(oldInstanceTest), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + overlay := filepath.Join(t.TempDir(), "overlay.json") |
| + raw, _ := json.Marshal(map[string]any{"Replace": map[string]string{filepath.Join(src, "internal", "headless", "m8_old_instance_test.go"): extra}}) |
| + if err := os.WriteFile(overlay, raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + build := exec.Command("go", "test", "-c", "-overlay", overlay, "-o", bin+".tmp", "./internal/headless") |
| + build.Dir = src |
| + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly") |
| + if out, err := build.CombinedOutput(); err != nil { |
| + t.Fatalf("building slice 4 at %s: %v %s", slice4, 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) |
| + if k.Stage != wire.StageReadyToMerge && 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) { |
| + 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]++ |
| + if !wire.Speaks(wire.Protocol1, f.Type) { |
| + t.Fatalf("protocol 1 runner sent %s", raw) |
| + } |
| + for _, field := range []string{`"needs"`, `"runner_id":"`, `"protocol"`, `"role"`, `"release"`, `"step_id":"","attempt"`} { |
| + if f.Type != wire.FrameWelcome && field == `"runner_id":"` { |
| + if f.Type == wire.FrameDispatch && bytes.Contains(f.Data, []byte(field)) { |
| + t.Fatalf("dispatch with runner_id at protocol 1: %s", raw) |
| + } |
| + continue |
| + } |
| + if f.Type != wire.FrameWelcome && field != `"needs"` { |
| + continue |
| + } |
| + if bytes.Contains(f.Data, []byte(field)) && field != `"runner_id":"` { |
| + t.Fatalf("protocol 2 field %s at protocol 1: %s", field, 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() |
| +} |
| + |
| +var _ = io.Discard |