package thin import ( "bytes" "context" "crypto/rand" "go/ast" "go/parser" "go/token" "net" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" ) func gitT(t *testing.T, dir string, args ...string) string { t.Helper() testci.Tools(t, "git") cmd := exec.Command("git", args...) cmd.Dir = dir 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") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v %s", args, err, out) } return strings.TrimSpace(string(out)) } // mergeRig is a clone (as the runner keeps it) with a base commit, a // task candidate made by change, and main moved on by mainChange. func mergeRig(t *testing.T, change, mainChange func(dir string)) (*MergeWatch, watch) { t.Helper() root := t.TempDir() work := filepath.Join(root, "work") gitT(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "café.txt"), []byte("old\n"), 0644) os.WriteFile(filepath.Join(work, "run.sh"), []byte("echo hi\n"), 0644) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "base") base := gitT(t, work, "rev-parse", "HEAD") gitT(t, work, "checkout", "-qb", "task") change(work) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "candidate") cand := gitT(t, work, "rev-parse", "HEAD") gitT(t, work, "checkout", "-q", "main") mainChange(work) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "main moves", "--allow-empty") c := &Clones{Root: filepath.Join(root, "clones"), Git: "/usr/bin/git"} repo := "amadan.net/oficina/sample" os.MkdirAll(filepath.Dir(c.Path(repo)), 0700) gitT(t, root, "clone", "-q", "--bare", "--no-local", work, c.Path(repo)) gitT(t, root, "--git-dir="+c.Path(repo), "fetch", "-q", work, "task:task") return &MergeWatch{Clones: c, Git: "/usr/bin/git"}, watch{task: "tk1", repo: repo, branch: "equipo/tk1", candidate: cand, base: base} } // Astra round 1, findings 2 and 3: the squash check reads paths // NUL-delimited, tells a missing entry from a failed lookup, and compares // whole tree entries (mode, type and object). When in doubt, not merged. func TestMergedSquashCheckIsConservative(t *testing.T) { for _, tc := range []struct { name string change, mainChange func(string) want bool }{ {"unmerged edit to café.txt", func(d string) { os.WriteFile(filepath.Join(d, "café.txt"), []byte("new\n"), 0644) }, func(d string) {}, false}, {"unmerged executable bit", func(d string) { os.Chmod(filepath.Join(d, "run.sh"), 0755) }, func(d string) {}, false}, {"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}, {"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}, {"squashed delete", func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, true}, {"unmerged delete", func(d string) { os.Remove(filepath.Join(d, "café.txt")) }, func(d string) {}, false}, } { m, w := mergeRig(t, tc.change, tc.mainChange) if got := m.merged(context.Background(), w.repo, "main", w); got != tc.want { t.Fatalf("%s: merged %v, want %v", tc.name, got, tc.want) } } // A failed lookup is unknown, never merged. 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) }) w.base = strings.Repeat("e", 40) if m.merged(context.Background(), w.repo, "main", w) { t.Fatal("merged with an unreadable base") } } // stalledRemote accepts connections and never answers. func stalledRemote(t *testing.T) string { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { l.Close() }) go func() { for { c, err := l.Accept() if err != nil { return } t.Cleanup(func() { c.Close() }) } }() return "https://" + l.Addr().String() + "/oficina/sample" } type stalledForge struct { Forge url string } func (f stalledForge) Remote(context.Context, string, Use) (workspace.Remote, error) { return workspace.Remote{URL: f.url, GitPassword: "p"}, nil } // Astra round 1, finding 5: a fetch that stalls reaches its deadline, // the retries and the backoff, and the step ends clone_failed; the serial // step worker is never held. func TestJudgeFetchHasDeadlines(t *testing.T) { old := []any{fetchAttempts, fetchBackoff, fetchTimeout} fetchAttempts, fetchBackoff, fetchTimeout = 2, 10*time.Millisecond, 300*time.Millisecond t.Cleanup(func() { fetchAttempts, fetchBackoff, fetchTimeout = old[0].(int), old[1].(time.Duration), old[2].(time.Duration) }) root := t.TempDir() e := &Engineer{Clones: &Clones{Root: root, Git: "/usr/bin/git", Forge: stalledForge{url: stalledRemote(t)}}, Owners: []string{"p@x"}} e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir = "/usr/bin/git", root, root 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)}} done := make(chan string, 1) go func() { _, reason, _ := e.judgeTree(context.Background(), r) done <- reason }() select { case reason := <-done: if reason != "clone_failed" { t.Fatalf("reason %q", reason) } case <-time.After(15 * time.Second): t.Fatal("a stalled fetch held the step") } } // Astra round 1, finding 6: the review diff and the checks repository // are streamed with limits: an oversized candidate never lands in the // runner's memory. func TestOversizedCandidateStaysOutOfMemory(t *testing.T) { if testing.Short() { t.Skip("writes 16 MiB") } root := t.TempDir() work := filepath.Join(root, "work") gitT(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "a.txt"), []byte("a\n"), 0644) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "base") base := gitT(t, work, "rev-parse", "HEAD") // 16 MiB of text lines that do not compress or delta well. var big bytes.Buffer raw := make([]byte, 48<<17) rand.Read(raw) for i := 0; i < len(raw); i += 48 { big.WriteString(strconv.Quote(string(raw[i:i+48])) + "\n") } os.WriteFile(filepath.Join(work, "big.txt"), big.Bytes(), 0644) gitT(t, work, "add", "-A") gitT(t, work, "commit", "-qm", "big") cand := gitT(t, work, "rev-parse", "HEAD") big.Reset() raw = nil measure := func(name string, fn func()) { t.Helper() runtime.GC() var a, b runtime.MemStats runtime.ReadMemStats(&a) fn() runtime.ReadMemStats(&b) if grew := b.TotalAlloc - a.TotalAlloc; grew > 8<<20 { t.Fatalf("%s allocated %d MiB", name, grew>>20) } } gitDir := filepath.Join(work, ".git") measure("diff", func() { d, err := treeDiff(context.Background(), "/usr/bin/git", gitDir, base, cand, wire.MaxDiffBytes) if err != nil || len(d) > wire.MaxDiffBytes+200 || !strings.Contains(d, "the rest of the diff is cut") { t.Fatalf("diff %d bytes %v", len(d), err) } }) tree := workspace.TaskTree{Dir: filepath.Join(root, "tree"), GitDir: gitDir, Git: "/usr/bin/git", Branch: "equipo/tk1-x", Base: cand} os.MkdirAll(tree.Dir, 0700) e := &Engineer{} e.O.Runner.GitPath = "/usr/bin/git" measure("checks repository", func() { if err := e.checkRepository(context.Background(), tree, cand); err != nil { t.Fatal(err) } }) if got := gitT(t, tree.Dir, "rev-parse", "HEAD"); got != cand { t.Fatalf("checks repository at %s", got) } // Past the pack bound the checks repository is refused, not filled. old := maxCheckPack maxCheckPack = 1 << 20 t.Cleanup(func() { maxCheckPack = old }) small := tree small.Dir = filepath.Join(root, "tree2") os.MkdirAll(small.Dir, 0700) if err := e.checkRepository(context.Background(), small, cand); err == nil || !strings.Contains(err.Error(), "too large") { t.Fatalf("an oversized pack was taken: %v", err) } } // Astra round 1, finding 4: every step reason this runner emits is one // the instance knows. The literals are read from the source: reasons in // fail(...), done(...), stepResult/gateResult{reason: ...}, assignments // to a Reason or reason field, and reasonFor's returns. func TestRunnerReasonsAreKnown(t *testing.T) { fset := token.NewFileSet() files, _ := filepath.Glob("*.go") steps := map[string]bool{"engineer.go": true, "judge.go": true, "step.go": true, "merge.go": true} found := map[string]bool{} lit := func(e ast.Expr) { if b, ok := e.(*ast.BasicLit); ok && b.Kind == token.STRING { s, _ := strconv.Unquote(b.Value) found[s] = true } } for _, f := range files { if strings.HasSuffix(f, "_test.go") { continue } file, err := parser.ParseFile(fset, f, nil, 0) if err != nil { t.Fatal(err) } ast.Inspect(file, func(n ast.Node) bool { if !steps[f] { // Elsewhere only reasonFor, which steps share. if d, ok := n.(*ast.FuncDecl); !ok || d.Name.Name != "reasonFor" { return true } } switch v := n.(type) { case *ast.CallExpr: if id, ok := v.Fun.(*ast.Ident); ok && (id.Name == "fail" || id.Name == "done") { for _, a := range v.Args { lit(a) } } case *ast.KeyValueExpr: if id, ok := v.Key.(*ast.Ident); ok && (id.Name == "reason" || id.Name == "Reason") { lit(v.Value) } case *ast.AssignStmt: for i, l := range v.Lhs { if sel, ok := l.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Reason" || sel.Sel.Name == "reason") && i < len(v.Rhs) { lit(v.Rhs[i]) } } case *ast.FuncDecl: if v.Name.Name == "reasonFor" { ast.Inspect(v, func(n ast.Node) bool { if r, ok := n.(*ast.ReturnStmt); ok { for _, e := range r.Results { lit(e) } } return true }) } } return true }) } if !found["needs_macos"] || !found["no_verdict"] || !found["push_failed"] { t.Fatalf("the scan found too little: %v", found) } for s := range found { // The launch path also serves questions (ask.go), whose reasons // the instance knows as answer reasons (session_gone on resume). if s != "" && !wire.StepReasons[s] && !wire.AnswerReasons[s] { t.Errorf("the runner emits reason %q the instance does not know", s) } } }