oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package headless
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/hex"
9 "encoding/json"
10 "log/slog"
11 "maps"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "slices"
16 "strings"
17 "sync"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/equipo/internal/runner"
22 "amadan.net/oficina/equipo/internal/runnerproto"
23 "amadan.net/oficina/equipo/internal/testci"
24 "amadan.net/oficina/equipo/internal/thintest"
25 "amadan.net/oficina/equipo/internal/wire"
26)
27
28// slice4 is the protocol 1 release the mixed-version tests run against:
29// the staging line (thin-v1-composer at 0797ad0: slice 4c with
30// connections, housekeeping and attachments), which this branch upgrades
31// from. (The spec names ca0a65c, slice 4 itself; its wire predates the
32// 4b, 4c and connections frame fields, a skew those releases already
33// have.)
34const slice4 = "0797ad0762da8c3a8ebde6664583c77c9f9c34a2"
35
36// oldInstanceTest is added to the slice 4 tree when its test binary is
37// built: an instance of that release, in its own process, until stdin
38// closes.
39const oldInstanceTest = `package headless
40
41import (
42 "encoding/json"
43 "io"
44 "os"
45 "testing"
46
47 "amadan.net/oficina/equipo/internal/thintest"
48)
49
50func TestM8OldInstance(t *testing.T) {
51 out := os.Getenv("EQUIPO_M8_OUT")
52 if out == "" {
53 t.Skip("M8 only")
54 }
55 inst := thintest.StartInstance(t)
56 token := inst.DeviceToken(t)
57 cred := inst.EnrolRunner(t)
58 raw, _ := json.Marshal(map[string]any{"url": inst.URL, "team": inst.TeamID, "token": token, "db": inst.Path, "credential": cred})
59 if err := os.WriteFile(out+".tmp", raw, 0600); err != nil {
60 t.Fatal(err)
61 }
62 if err := os.Rename(out+".tmp", out); err != nil {
63 t.Fatal(err)
64 }
65 _, _ = io.Copy(io.Discard, os.Stdin)
66}
67`
68
69var oldOnce sync.Mutex
70
71// oldBinary is the slice 4 headless test binary (the real slice 4 runner
72// and, with the overlay above, instance), built from git history once
73// and kept in EQUIPO_M8_CACHE when it is set (CI keeps it as an
74// artifact), else in the test's own directory.
75func oldBinary(t *testing.T) string {
76 return oldBinaryAt(t, slice4, "", map[string]string{"m8_old_instance_test.go": oldInstanceTest})
77}
78
79// oldBinaryAt is the headless test binary of commit, built with tags
80// ("" for none) and the extra test files (name: source) added to its
81// headless package, once, and cached as oldBinary says (by commit and
82// tags). Nothing is downloaded: the tree comes from git history and the
83// modules from the module cache (-mod=readonly).
84func oldBinaryAt(t *testing.T, commit, tags string, extra map[string]string) string {
85 t.Helper()
86 oldOnce.Lock()
87 defer oldOnce.Unlock()
88 key := commit
89 if tags != "" {
90 // Keyed by its extra files too, so a changed overlay is built
91 // again (slice 4's key stays as CI's cache has it).
92 names := slices.Sorted(maps.Keys(extra))
93 h := sha256.New()
94 for _, n := range names {
95 h.Write([]byte(n + "\x00" + extra[n] + "\x00"))
96 }
97 key += "-" + tags + "-" + hex.EncodeToString(h.Sum(nil))[:12]
98 }
99 cache := os.Getenv("EQUIPO_M8_CACHE")
100 if cache == "" || os.MkdirAll(filepath.Join(cache, key), 0700) != nil {
101 cache = t.TempDir()
102 }
103 bin := filepath.Join(cache, key, "headless.test")
104 if info, err := os.Stat(bin); err == nil && info.Mode().IsRegular() {
105 return bin
106 }
107 if err := os.MkdirAll(filepath.Dir(bin), 0700); err != nil {
108 bin = filepath.Join(t.TempDir(), "headless.test")
109 }
110 top, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
111 if err != nil {
112 t.Fatalf("M8 needs the repository's history: %v", err)
113 }
114 src := t.TempDir()
115 archive := exec.Command("git", "-C", strings.TrimSpace(string(top)), "archive", "--format=tar", commit)
116 untar := exec.Command("tar", "-x", "-C", src)
117 pipe, _ := archive.StdoutPipe()
118 untar.Stdin = pipe
119 if err := untar.Start(); err != nil {
120 t.Fatal(err)
121 }
122 if err := archive.Run(); err != nil {
123 t.Fatalf("M8 needs commit %s in the repository's history: %v", commit, err)
124 }
125 if err := untar.Wait(); err != nil {
126 t.Fatal(err)
127 }
128 replace := map[string]string{}
129 for name, body := range extra {
130 file := filepath.Join(t.TempDir(), name)
131 if err := os.WriteFile(file, []byte(body), 0600); err != nil {
132 t.Fatal(err)
133 }
134 replace[filepath.Join(src, "internal", "headless", name)] = file
135 }
136 overlay := filepath.Join(t.TempDir(), "overlay.json")
137 raw, _ := json.Marshal(map[string]any{"Replace": replace})
138 if err := os.WriteFile(overlay, raw, 0600); err != nil {
139 t.Fatal(err)
140 }
141 // Niced, two compile jobs: the build must not starve the packages
142 // testing beside it.
143 args := []string{"go", "test", "-c", "-p", "2", "-overlay", overlay, "-o", bin + ".tmp"}
144 if tags != "" {
145 args = append(args, "-tags", tags)
146 }
147 args = append(args, "./internal/headless")
148 if nice, err := exec.LookPath("nice"); err == nil {
149 args = append([]string{nice, "-n", "15"}, args...)
150 }
151 build := exec.Command(args[0], args[1:]...)
152 build.Dir = src
153 build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly")
154 if out, err := build.CombinedOutput(); err != nil {
155 t.Fatalf("building %s at %s: %v %s", key, commit, err, out)
156 }
157 if err := os.Rename(bin+".tmp", bin); err != nil {
158 t.Fatal(err)
159 }
160 return bin
161}
162
163// sampleToReady sends the typo fix on oficina/sample and waits until the
164// task is ready to merge or done.
165func sampleToReady(t *testing.T, env *Env, title string) wire.Task {
166 t.Helper()
167 s := open(t, env)
168 s.keep()
169 s.wait(t, "runner online", 30*time.Second, func(c *thintest.Conversation) bool { return c.Runner.Online })
170 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")
171 id := s.taskOf(t, sent.Turn.ID)
172 k := s.settled(t, id, 3*time.Minute)
173 // settled saw ready to merge and then read the task again; by then
174 // the instance may have started merging it, which is later, not worse.
175 if k.Stage != wire.StageReadyToMerge && k.Stage != wire.StageMerging && k.Stage != wire.StageDone {
176 t.Fatalf("not ready: %+v", k)
177 }
178 if k.Checks != wire.ChecksPassed || k.Verdict != wire.VerdictApprove {
179 t.Fatalf("judged %+v", k)
180 }
181 return k
182}
183
184// M8: mixed versions with the real slice 4 code.
185func TestMixedVersions(t *testing.T) {
186 testci.Quarantine(t)
187 if testing.Short() {
188 t.Skip("builds slice 4")
189 }
190 old := oldBinary(t)
191
192 // The slice 4 runner against this instance: it speaks protocol 1,
193 // runs the sample scenario to ready, and is never sent anything
194 // protocol 1 lacks (no blob, no needs, nothing new in welcome).
195 t.Run("old runner, new instance", func(t *testing.T) {
196 env, inst, r := localEnv(t)
197 var mu sync.Mutex
198 var sent [][]byte
199 inst.Store.Chat().SetFrameTap(func(_ string, raw []byte) {
200 mu.Lock()
201 sent = append(sent, append([]byte(nil), raw...))
202 mu.Unlock()
203 })
204 r.subprocess, r.binary = true, old
205 r.start(t)
206 k := sampleToReady(t, env, "Fix the panes typo")
207 var protocol int
208 if err := inst.DB.Writer().QueryRow("SELECT protocol FROM runner_sessions").Scan(&protocol); err != nil || protocol != wire.Protocol1 {
209 t.Fatalf("protocol %d %v", protocol, err)
210 }
211 mu.Lock()
212 defer mu.Unlock()
213 kinds := map[string]int{}
214 for _, raw := range sent {
215 f, _, err := wire.ParseFrame(raw)
216 if err != nil {
217 t.Fatalf("unparsable frame %s", raw)
218 }
219 kinds[f.Type]++
220 // Exactly the protocol 1 frame: nothing Encode would drop.
221 old, err := wire.Encode(f, wire.Protocol1)
222 if err != nil || !bytes.Equal(old.Data, f.Data) {
223 t.Fatalf("a protocol 1 runner was sent more than protocol 1: %v %s", err, raw)
224 }
225 }
226 if kinds[wire.FrameDispatch] < 3 || kinds[wire.FrameWelcome] < 1 {
227 t.Fatalf("frames sent %v", kinds)
228 }
229 t.Logf("slice 4 runner: task %s %s on %s; frames %v", k.ID, k.Stage, k.CandidateSHA[:7], kinds)
230 })
231
232 // This runner against the slice 4 instance: its protocol 2 hello is
233 // refused once, it says hello at protocol 1, logs it, and runs the same
234 // scenario. A worker enrolling with that instance is refused with a
235 // clear diagnostic and nothing is created or lost.
236 t.Run("new runner, old instance", func(t *testing.T) {
237 out := filepath.Join(t.TempDir(), "instance.json")
238 cmd := exec.Command(old, "-test.run", "^TestM8OldInstance$", "-test.timeout", "20m")
239 cmd.Env = append(os.Environ(), "EQUIPO_M8_OUT="+out)
240 stdin, _ := cmd.StdinPipe()
241 var logs bytes.Buffer
242 cmd.Stdout, cmd.Stderr = &logs, &logs
243 if err := cmd.Start(); err != nil {
244 t.Fatal(err)
245 }
246 t.Cleanup(func() {
247 stdin.Close()
248 done := make(chan error, 1)
249 go func() { done <- cmd.Wait() }()
250 select {
251 case <-done:
252 case <-time.After(30 * time.Second):
253 cmd.Process.Kill()
254 <-done
255 }
256 })
257 var info struct {
258 URL, Team, Token, DB string
259 Credential runnerproto.RunnerCredential
260 }
261 deadline := time.Now().Add(2 * time.Minute)
262 for {
263 raw, err := os.ReadFile(out)
264 if err == nil && json.Unmarshal(raw, &info) == nil {
265 break
266 }
267 if time.Now().After(deadline) {
268 t.Fatalf("slice 4 instance did not start: %s", logs.String())
269 }
270 time.Sleep(100 * time.Millisecond)
271 }
272 r, _ := runnerSetup(t, info.URL, info.Team, info.Credential)
273 t.Cleanup(func() { r.stop(t) })
274 runnerLog := &lockedBuffer{}
275 r.opts.Logger = slog.New(slog.NewTextHandler(runnerLog, nil))
276 turns := 0
277 env := &Env{Client: thintest.NewClient(info.URL, info.Token), turns: &turns, ForgePath: r.opts.Forge.(*localForge).path}
278 r.start(t)
279 k := sampleToReady(t, env, "Fix the panes typo")
280 if !strings.Contains(runnerLog.String(), "the instance is older: speaking protocol 1") {
281 t.Fatalf("no fallback line: %s", runnerLog.String())
282 }
283 t.Logf("against slice 4: task %s %s on %s", k.ID, k.Stage, k.CandidateSHA[:7])
284
285 // A worker cannot enrol there.
286 worker := runner.Config{Origin: info.URL, InstanceID: info.Team, StateDir: filepath.Join(t.TempDir(), "worker"), WorkerOnly: true}
287 var printed bytes.Buffer
288 err := runner.Enrol(context.Background(), worker, &printed)
289 if code, _ := runner.Diagnostic(err); code != "runner.instance_older_than_worker" {
290 t.Fatalf("worker enrolment with slice 4: %q %v", code, err)
291 }
292 d, err := sql.Open("sqlite", "file:"+info.DB+"?mode=ro&_pragma=busy_timeout(5000)")
293 if err != nil {
294 t.Fatal(err)
295 }
296 defer d.Close()
297 var runners, enrolments int
298 d.QueryRow("SELECT count(*) FROM runners").Scan(&runners)
299 d.QueryRow("SELECT count(*) FROM runner_enrolments").Scan(&enrolments)
300 if runners != 1 || enrolments != 1 {
301 t.Fatalf("the refused worker left %d runners, %d enrolments", runners, enrolments)
302 }
303 // Nothing lost: the primary still serves the person.
304 s := open(t, env)
305 sent := s.send(t, "Still there?")
306 if turn := s.waitTurn(t, sent.Turn.ID, wire.TurnReplied); turn.State != wire.TurnReplied {
307 t.Fatalf("after the refused worker: %+v", turn)
308 }
309 })
310}
311
312// lockedBuffer is a log sink read while the runner writes.
313type lockedBuffer struct {
314 mu sync.Mutex
315 b bytes.Buffer
316}
317
318func (l *lockedBuffer) Write(p []byte) (int, error) {
319 l.mu.Lock()
320 defer l.mu.Unlock()
321 return l.b.Write(p)
322}
323
324func (l *lockedBuffer) String() string {
325 l.mu.Lock()
326 defer l.mu.Unlock()
327 return l.b.String()
328}
329