package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/ci"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/lease"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/zitcli"
)
// When a target branch moves and puts an open landing into a merge
// conflict, landingSweep cancels any still-running pair run against the
// old target so the dead run does not keep burning a runner slot (#507).
func TestConflictingTargetMoveCancelsStalePairRun(t *testing.T) {
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir := t.TempDir()
write := func(name, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
zitIn(t, dir, "init", ".")
write("ci/test.json", `{"name":"test","version":"1.0","steps":[]}`)
write("CHANGELOG.md", "line1\n")
zitIn(t, dir, "add", "ci/test.json", "CHANGELOG.md")
zitIn(t, dir, "commit", "-m", "root", "--user", "u")
write("CHANGELOG.md", "line1\nfeat-entry\n")
zitIn(t, dir, "commit", "-m", "feat", "--branch", "feat", "--user", "u")
cli := zitcli.New(dir)
if _, err := cli.LandingOpen(lease.Unguarded("test"), "dan", "feat", "trunk", "land feat", ""); err != nil {
t.Fatal(err)
}
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(cli, ev, ix, "r", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var cancelled []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/runs/run-stale" && r.Method == http.MethodGet:
json.NewEncoder(w).Encode(map[string]any{
"run_id": "run-stale",
"status": "running",
"labels": map[string]string{"subject": "pair"},
})
case r.URL.Path == "/runs/run-stale/cancel" && r.Method == http.MethodPost:
mu.Lock()
cancelled = append(cancelled, "run-stale")
mu.Unlock()
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"cancelled"}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
rg := newTestRegistrar(t, 25)
rg.engine = ci.New(srv.URL)
rg.deps = &api.Deps{Repos: api.NewRepos(map[string]*api.Repo{"r": {Chat: "r", Index: ix, Zit: cli}})}
featTip, _ := ix.BranchTip("feat")
oldTrunk, _ := ix.BranchTip("trunk")
oldPair := ci.Pair(featTip, oldTrunk)
if err := rg.odb.AddCIRun(oltp.CIRun{
RunID: "run-stale", Repo: "r", Checkin: featTip, Pair: oldPair,
Workflow: "test", Pipeline: "ci/test.json", Status: "running",
}); err != nil {
t.Fatal(err)
}
// Clean non-conflicting move on trunk: stale run must NOT be cancelled.
zitIn(t, dir, "update", "trunk")
write("other.txt", "clean\n")
zitIn(t, dir, "add", "other.txt")
zitIn(t, dir, "commit", "-m", "clean trunk move", "--user", "u")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
open, _ := ix.Landings("open", 500)
rg.cancelConflictingPairs("r", ix, open)
mu.Lock()
if len(cancelled) != 0 {
t.Fatalf("FAIL: clean move cancelled %v; want none", cancelled)
}
mu.Unlock()
// Conflicting move on trunk in CHANGELOG.md: stale run MUST be cancelled.
write("CHANGELOG.md", "line1\ntrunk-entry\n")
zitIn(t, dir, "commit", "-m", "conflict trunk move", "--user", "u")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
open, _ = ix.Landings("open", 500)
rg.cancelConflictingPairs("r", ix, open)
mu.Lock()
defer mu.Unlock()
if !slices.Equal(cancelled, []string{"run-stale"}) {
t.Fatalf("FAIL: conflicting move cancelled %v; want [run-stale]", cancelled)
}
t.Log("ok: conflicting target move cancels stale in-flight pair run")
}
// pairSweep enqueues stacked landings strictly bottom-up regardless of
// the order ix.Landings returns them (#507).
func TestPairSweepEnqueuesStackBottomUp(t *testing.T) {
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir := t.TempDir()
write := func(name, body string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
zitIn(t, dir, "init", ".")
write("ci/test.json", `{"name":"test","version":"1.0","steps":[]}`)
write("f.txt", "root\n")
zitIn(t, dir, "add", "ci/test.json", "f.txt")
zitIn(t, dir, "commit", "-m", "root", "--user", "u")
cli := zitcli.New(dir)
for _, r := range []struct{ b, to string }{{"b1", "trunk"}, {"b2", "b1"}, {"b3", "b2"}} {
zitIn(t, dir, "update", r.to)
write(r.b+".txt", r.b+"\n")
zitIn(t, dir, "add", r.b+".txt")
zitIn(t, dir, "commit", "-m", r.b, "--branch", r.b, "--user", "u")
if _, err := cli.LandingOpen(lease.Unguarded("test"), "dan", r.b, r.to, "land "+r.b, ""); err != nil {
t.Fatal(err)
}
}
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(cli, ev, ix, "r", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
rg := newTestRegistrar(t, 25)
engine, started := subjectEngine(t)
rg.engine = engine
rg.deps = &api.Deps{Repos: api.NewRepos(map[string]*api.Repo{"r": {Chat: "r", Index: ix, Zit: cli}})}
open, _ := ix.Landings("open", 500)
// Reverse so b3 comes before b2 before b1.
slices.Reverse(open)
rg.pairSweep("r", ix, open, nil)
got := started()
tip := func(b string) string { h, _ := ix.BranchTip(b); return h }
want := []string{
ci.Pair(tip("b1"), tip("trunk")),
ci.Pair(tip("b2"), tip("b1")),
ci.Pair(tip("b3"), tip("b2")),
}
if !slices.Equal(got, want) {
var gs, ws []string
for _, s := range got {
gs = append(gs, fmt.Sprintf("%.24s", strings.TrimPrefix(s, "pair:")))
}
for _, s := range want {
ws = append(ws, fmt.Sprintf("%.24s", strings.TrimPrefix(s, "pair:")))
}
t.Fatalf("FAIL: pairSweep order = %v; want bottom-up %v", gs, ws)
}
t.Log("ok: pairSweep enqueued b1 -> b2 -> b3 strictly bottom-up")
}