oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "go/ast"
8 "go/parser"
9 "go/token"
10 "net"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "strconv"
16 "strings"
17 "testing"
18 "time"
19
20 "amadan.net/oficina/equipo/internal/runner/workspace"
21 "amadan.net/oficina/equipo/internal/testci"
22 "amadan.net/oficina/equipo/internal/wire"
23)
24
25func gitT(t *testing.T, dir string, args ...string) string {
26 t.Helper()
27 testci.Tools(t, "git")
28 cmd := exec.Command("git", args...)
29 cmd.Dir = dir
30 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t", "GIT_CONFIG_GLOBAL=/dev/null")
31 out, err := cmd.CombinedOutput()
32 if err != nil {
33 t.Fatalf("git %v: %v %s", args, err, out)
34 }
35 return strings.TrimSpace(string(out))
36}
37
38// mergeRig is a clone (as the runner keeps it) with a base commit, a
39// task candidate made by change, and main moved on by mainChange.
40func mergeRig(t *testing.T, change, mainChange func(dir string)) (*MergeWatch, watch) {
41 t.Helper()
42 root := t.TempDir()
43 work := filepath.Join(root, "work")
44 gitT(t, root, "init", "-q", "-b", "main", work)
45 os.WriteFile(filepath.Join(work, "café.txt"), []byte("old\n"), 0644)
46 os.WriteFile(filepath.Join(work, "run.sh"), []byte("echo hi\n"), 0644)
47 gitT(t, work, "add", "-A")
48 gitT(t, work, "commit", "-qm", "base")
49 base := gitT(t, work, "rev-parse", "HEAD")
50 gitT(t, work, "checkout", "-qb", "task")
51 change(work)
52 gitT(t, work, "add", "-A")
53 gitT(t, work, "commit", "-qm", "candidate")
54 cand := gitT(t, work, "rev-parse", "HEAD")
55 gitT(t, work, "checkout", "-q", "main")
56 mainChange(work)
57 gitT(t, work, "add", "-A")
58 gitT(t, work, "commit", "-qm", "main moves", "--allow-empty")
59 c := &Clones{Root: filepath.Join(root, "clones"), Git: "/usr/bin/git"}
60 repo := "amadan.net/oficina/sample"
61 os.MkdirAll(filepath.Dir(c.Path(repo)), 0700)
62 gitT(t, root, "clone", "-q", "--bare", "--no-local", work, c.Path(repo))
63 gitT(t, root, "--git-dir="+c.Path(repo), "fetch", "-q", work, "task:task")
64 return &MergeWatch{Clones: c, Git: "/usr/bin/git"}, watch{task: "tk1", repo: repo, branch: "equipo/tk1", candidate: cand, base: base}
65}
66
67// Astra round 1, findings 2 and 3: the squash check reads paths
68// NUL-delimited, tells a missing entry from a failed lookup, and compares
69// whole tree entries (mode, type and object). When in doubt, not merged.
70func TestMergedSquashCheckIsConservative(t *testing.T) {
71 for _, tc := range []struct {
72 name string
73 change, mainChange func(string)
74 want bool
75 }{
76 {"unmerged edit to café.txt", func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) }, func(d string) {}, false},
77 {"unmerged executable bit", func(d string) { os.Chmod(filepath.Join(d, "run.sh"), 0755) }, func(d string) {}, false},
78 {"squashed edit to café.txt", func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) }, func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) }, true},
79 {"squashed executable bit", func(d string) { os.Chmod(filepath.Join(d, "run.sh"), 0755) }, func(d string) { os.Chmod(filepath.Join(d, "run.sh"), 0755) }, true},
80 {"squashed delete", func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, true},
81 {"unmerged delete", func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, func(d string) {}, false},
82 } {
83 m, w := mergeRig(t, tc.change, tc.mainChange)
84 if got := m.merged(context.Background(), w.repo, "main", w); got != tc.want {
85 t.Fatalf("%s: merged %v, want %v", tc.name, got, tc.want)
86 }
87 }
88 // A failed lookup is unknown, never merged.
89 m, w := mergeRig(t, func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) }, func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) })
90 w.base = strings.Repeat("e", 40)
91 if m.merged(context.Background(), w.repo, "main", w) {
92 t.Fatal("merged with an unreadable base")
93 }
94}
95
96// stalledRemote accepts connections and never answers.
97func stalledRemote(t *testing.T) string {
98 l, err := net.Listen("tcp", "127.0.0.1:0")
99 if err != nil {
100 t.Fatal(err)
101 }
102 t.Cleanup(func() { l.Close() })
103 go func() {
104 for {
105 c, err := l.Accept()
106 if err != nil {
107 return
108 }
109 t.Cleanup(func() { c.Close() })
110 }
111 }()
112 return "https://" + l.Addr().String() + "/oficina/sample"
113}
114
115type stalledForge struct {
116 Forge
117 url string
118}
119
120func (f stalledForge) Remote(context.Context, string, Use) (workspace.Remote, error) {
121 return workspace.Remote{URL: f.url, GitPassword: "p"}, nil
122}
123
124// Astra round 1, finding 5: a fetch that stalls reaches its deadline,
125// the retries and the backoff, and the step ends clone_failed; the serial
126// step worker is never held.
127func TestJudgeFetchHasDeadlines(t *testing.T) {
128 old := []any{fetchAttempts, fetchBackoff, fetchTimeout}
129 fetchAttempts, fetchBackoff, fetchTimeout = 2, 10*time.Millisecond, 300*time.Millisecond
130 t.Cleanup(func() {
131 fetchAttempts, fetchBackoff, fetchTimeout = old[0].(int), old[1].(time.Duration), old[2].(time.Duration)
132 })
133 root := t.TempDir()
134 e := &Engineer{Clones: &Clones{Root: root, Git: "/usr/bin/git", Forge: stalledForge{url: stalledRemote(t)}}, Owners: []string{"p@x"}}
135 e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir = "/usr/bin/git", root, root
136 r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s1", Attempt: 1, Specialist: wire.SpecialistChecks, Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-x", CandidateSHA: strings.Repeat("a", 40)}}
137 done := make(chan string, 1)
138 go func() {
139 _, reason, _ := e.judgeTree(context.Background(), r)
140 done <- reason
141 }()
142 select {
143 case reason := <-done:
144 if reason != "clone_failed" {
145 t.Fatalf("reason %q", reason)
146 }
147 case <-time.After(15 * time.Second):
148 t.Fatal("a stalled fetch held the step")
149 }
150}
151
152// Astra round 1, finding 6: the review diff and the checks repository
153// are streamed with limits: an oversized candidate never lands in the
154// runner's memory.
155func TestOversizedCandidateStaysOutOfMemory(t *testing.T) {
156 if testing.Short() {
157 t.Skip("writes 16 MiB")
158 }
159 root := t.TempDir()
160 work := filepath.Join(root, "work")
161 gitT(t, root, "init", "-q", "-b", "main", work)
162 os.WriteFile(filepath.Join(work, "a.txt"), []byte("a\n"), 0644)
163 gitT(t, work, "add", "-A")
164 gitT(t, work, "commit", "-qm", "base")
165 base := gitT(t, work, "rev-parse", "HEAD")
166 // 16 MiB of text lines that do not compress or delta well.
167 var big bytes.Buffer
168 raw := make([]byte, 48<<17)
169 rand.Read(raw)
170 for i := 0; i < len(raw); i += 48 {
171 big.WriteString(strconv.Quote(string(raw[i:i+48])) + "\n")
172 }
173 os.WriteFile(filepath.Join(work, "big.txt"), big.Bytes(), 0644)
174 gitT(t, work, "add", "-A")
175 gitT(t, work, "commit", "-qm", "big")
176 cand := gitT(t, work, "rev-parse", "HEAD")
177 big.Reset()
178 raw = nil
179 measure := func(name string, fn func()) {
180 t.Helper()
181 runtime.GC()
182 var a, b runtime.MemStats
183 runtime.ReadMemStats(&a)
184 fn()
185 runtime.ReadMemStats(&b)
186 if grew := b.TotalAlloc - a.TotalAlloc; grew > 8<<20 {
187 t.Fatalf("%s allocated %d MiB", name, grew>>20)
188 }
189 }
190 gitDir := filepath.Join(work, ".git")
191 measure("diff", func() {
192 d, err := treeDiff(context.Background(), "/usr/bin/git", gitDir, base, cand, wire.MaxDiffBytes)
193 if err != nil || len(d) > wire.MaxDiffBytes+200 || !strings.Contains(d, "the rest of the diff is cut") {
194 t.Fatalf("diff %d bytes %v", len(d), err)
195 }
196 })
197 tree := workspace.TaskTree{Dir: filepath.Join(root, "tree"), GitDir: gitDir, Git: "/usr/bin/git", Branch: "equipo/tk1-x", Base: cand}
198 os.MkdirAll(tree.Dir, 0700)
199 e := &Engineer{}
200 e.O.Runner.GitPath = "/usr/bin/git"
201 measure("checks repository", func() {
202 if err := e.checkRepository(context.Background(), tree, cand); err != nil {
203 t.Fatal(err)
204 }
205 })
206 if got := gitT(t, tree.Dir, "rev-parse", "HEAD"); got != cand {
207 t.Fatalf("checks repository at %s", got)
208 }
209 // Past the pack bound the checks repository is refused, not filled.
210 old := maxCheckPack
211 maxCheckPack = 1 << 20
212 t.Cleanup(func() { maxCheckPack = old })
213 small := tree
214 small.Dir = filepath.Join(root, "tree2")
215 os.MkdirAll(small.Dir, 0700)
216 if err := e.checkRepository(context.Background(), small, cand); err == nil || !strings.Contains(err.Error(), "too large") {
217 t.Fatalf("an oversized pack was taken: %v", err)
218 }
219}
220
221// Astra round 1, finding 4: every step reason this runner emits is one
222// the instance knows. The literals are read from the source: reasons in
223// fail(...), done(...), stepResult/gateResult{reason: ...}, assignments
224// to a Reason or reason field, and reasonFor's returns.
225func TestRunnerReasonsAreKnown(t *testing.T) {
226 fset := token.NewFileSet()
227 files, _ := filepath.Glob("*.go")
228 steps := map[string]bool{"engineer.go": true, "judge.go": true, "step.go": true, "merge.go": true}
229 found := map[string]bool{}
230 lit := func(e ast.Expr) {
231 if b, ok := e.(*ast.BasicLit); ok && b.Kind == token.STRING {
232 s, _ := strconv.Unquote(b.Value)
233 found[s] = true
234 }
235 }
236 for _, f := range files {
237 if strings.HasSuffix(f, "_test.go") {
238 continue
239 }
240 file, err := parser.ParseFile(fset, f, nil, 0)
241 if err != nil {
242 t.Fatal(err)
243 }
244 ast.Inspect(file, func(n ast.Node) bool {
245 if !steps[f] {
246 // Elsewhere only reasonFor, which steps share.
247 if d, ok := n.(*ast.FuncDecl); !ok || d.Name.Name != "reasonFor" {
248 return true
249 }
250 }
251 switch v := n.(type) {
252 case *ast.CallExpr:
253 if id, ok := v.Fun.(*ast.Ident); ok && (id.Name == "fail" || id.Name == "done") {
254 for _, a := range v.Args {
255 lit(a)
256 }
257 }
258 case *ast.KeyValueExpr:
259 if id, ok := v.Key.(*ast.Ident); ok && (id.Name == "reason" || id.Name == "Reason") {
260 lit(v.Value)
261 }
262 case *ast.AssignStmt:
263 for i, l := range v.Lhs {
264 if sel, ok := l.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Reason" || sel.Sel.Name == "reason") && i < len(v.Rhs) {
265 lit(v.Rhs[i])
266 }
267 }
268 case *ast.FuncDecl:
269 if v.Name.Name == "reasonFor" {
270 ast.Inspect(v, func(n ast.Node) bool {
271 if r, ok := n.(*ast.ReturnStmt); ok {
272 for _, e := range r.Results {
273 lit(e)
274 }
275 }
276 return true
277 })
278 }
279 }
280 return true
281 })
282 }
283 if !found["needs_macos"] || !found["no_verdict"] || !found["push_failed"] {
284 t.Fatalf("the scan found too little: %v", found)
285 }
286 for s := range found {
287 // The launch path also serves questions (ask.go), whose reasons
288 // the instance knows as answer reasons (session_gone on resume).
289 if s != "" && !wire.StepReasons[s] && !wire.AnswerReasons[s] {
290 t.Errorf("the runner emits reason %q the instance does not know", s)
291 }
292 }
293}
294