Skip to content
quarry Artifact [60b0e3b28f]
Login

Artifact [60b0e3b28f]

Artifact 60b0e3b28fc755852b19ece7f45b1fb16a9acf493a63eaa5f12f4e345d3711e0:


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 }
	wantTop := []string{ci.Pair(tip("b3"), tip("trunk"))}
	if !slices.Equal(got, wantTop) {
		t.Fatalf("FAIL: healthy 3-rung stack pairSweep started %v; want single top-of-stack %v", got, wantTop)
	}

	// Mark top-of-stack run as failed: pairSweep now falls back to lower
	// rungs strictly bottom-up (b1 -> b2).
	if err := rg.odb.AddCIRun(oltp.CIRun{
		RunID: "top-fail", Repo: "r", Checkin: tip("b3"), Pair: wantTop[0],
		Workflow: "test", Pipeline: "ci/test.json", Status: "failed",
	}); err != nil {
		t.Fatal(err)
	}
	rg.pairSweep("r", ix, open, nil)
	gotFallback := started()
	wantFallback := []string{
		ci.Pair(tip("b1"), tip("trunk")),
		ci.Pair(tip("b2"), tip("b1")),
	}
	if !slices.Equal(gotFallback, wantFallback) {
		var gs, ws []string
		for _, s := range gotFallback {
			gs = append(gs, fmt.Sprintf("%.24s", strings.TrimPrefix(s, "pair:")))
		}
		for _, s := range wantFallback {
			ws = append(ws, fmt.Sprintf("%.24s", strings.TrimPrefix(s, "pair:")))
		}
		t.Fatalf("FAIL: fallback pairSweep order = %v; want bottom-up %v", gs, ws)
	}
	t.Log("ok: pairSweep ran top-of-stack b3->trunk alone, then fell back b1 -> b2 bottom-up on failure")
}

// pairSweep cancels an in-flight lower-rung pair when a caught-up top
// rung exists (even if launchPush already started top's run), and does
// NOT cancel lower fallback runs when top has failed (#464, #507).
func TestPairSweepCancelsLowerPairsOnlyWhenTopDidNotFail(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)
	var id2 string
	for _, r := range []struct{ b, to string }{{"b1", "trunk"}, {"b2", "b1"}} {
		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")
		id, err := cli.LandingOpen(lease.Unguarded("test"), "dan", r.b, r.to, "land "+r.b, "")
		if err != nil {
			t.Fatal(err)
		}
		if r.b == "b2" {
			id2 = id
		}
	}
	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
	var started []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.URL.Path == "/workflows":
			w.WriteHeader(http.StatusCreated)
			w.Write([]byte(`{"status":"registered"}`))
		case r.URL.Path == "/runs" && r.Method == http.MethodPost:
			var body struct {
				Input map[string]any `json:"input"`
			}
			json.NewDecoder(r.Body).Decode(&body)
			mu.Lock()
			started = append(started, fmt.Sprint(body.Input["checkin"]))
			id := fmt.Sprintf("r-%d", len(started))
			mu.Unlock()
			w.WriteHeader(http.StatusCreated)
			fmt.Fprintf(w, `{"run_id":%q}`, id)
		case r.URL.Path == "/runs":
			w.Write([]byte(`[]`))
		case strings.HasPrefix(r.URL.Path, "/runs/") && strings.HasSuffix(r.URL.Path, "/cancel") && r.Method == http.MethodPost:
			id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/runs/"), "/cancel")
			mu.Lock()
			cancelled = append(cancelled, id)
			mu.Unlock()
			w.Write([]byte(`{"status":"cancelled"}`))
		case strings.HasPrefix(r.URL.Path, "/runs/") && r.Method == http.MethodGet:
			id := strings.TrimPrefix(r.URL.Path, "/runs/")
			json.NewEncoder(w).Encode(map[string]any{"run_id": id, "status": "running", "labels": map[string]string{"subject": "pair"}})
		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}})}

	b1Tip, _ := ix.BranchTip("b1")
	b2Tip, _ := ix.BranchTip("b2")
	trunkTip, _ := ix.BranchTip("trunk")
	// Lower rung b1 already has an in-flight pair run; top rung b2 ALREADY
	// has a push-pair run recorded (so tried > 0 on b2).
	if err := rg.odb.AddCIRun(oltp.CIRun{
		RunID: "run-b1", Repo: "r", Checkin: b1Tip, Pair: ci.Pair(b1Tip, trunkTip),
		Workflow: "test", Pipeline: "ci/test.json", Status: "running",
	}); err != nil {
		t.Fatal(err)
	}
	if err := rg.odb.AddCIRun(oltp.CIRun{
		RunID: "run-b2", Repo: "r", Checkin: b2Tip, Pair: ci.Pair(b2Tip, trunkTip),
		Workflow: "test", Pipeline: "ci/test.json", Status: "running",
	}); err != nil {
		t.Fatal(err)
	}
	open, _ := ix.Landings("open", 500)
	rg.pairSweep("r", ix, open, nil)
	mu.Lock()
	if !slices.Equal(cancelled, []string{"run-b1"}) {
		t.Fatalf("FAIL: expected run-b1 cancelled even when b2 already had a run; got %v", cancelled)
	}
	cancelled = nil
	mu.Unlock()

	// Now mark b2's top run as failed and re-run pairSweep with opening[b2]=true:
	// b1's fallback run must NOT be self-cancelled.
	if err := rg.odb.CompleteCIRun("run-b2", "failed", "2026-12-01T20:00:00Z"); err != nil {
		t.Fatal(err)
	}
	if err := rg.odb.CompleteCIRun("run-b1", "cancelled", "2026-12-01T20:00:00Z"); err != nil {
		t.Fatal(err)
	}
	if err := rg.odb.AddCIRun(oltp.CIRun{
		RunID: "run-b1-fallback", Repo: "r", Checkin: b1Tip, Pair: ci.Pair(b1Tip, trunkTip),
		Workflow: "test", Pipeline: "ci/test.json", Status: "running",
	}); err != nil {
		t.Fatal(err)
	}
	rg.pairSweep("r", ix, open, map[string]bool{id2: true})
	mu.Lock()
	defer mu.Unlock()
	if len(cancelled) != 0 {
		t.Fatalf("FAIL: failed top rung cancelled fallback lower run(s): %v", cancelled)
	}
	t.Log("ok: cancelLowerPairs cancels superseded lower runs even when top already ran, and never cancels fallback runs after top fails")
}