package api
import (
"os/exec"
"path/filepath"
"slices"
"testing"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/zitcli"
)
func makeStackFixture(t *testing.T, count int) (dir string, names []string, ids map[string]string, ix *index.Index, sync func() (int, error)) {
t.Helper()
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir = t.TempDir()
zrun(t, dir, "init", ".")
zwrite(t, dir, "base.txt", "root\n")
zrun(t, dir, "add", "base.txt")
zrun(t, dir, "commit", "-m", "root", "--user", "u")
ids = map[string]string{}
prev := "trunk"
for i := 1; i <= count; i++ {
b := "r" + string(rune('0'+i))
names = append(names, b)
zrun(t, dir, "update", prev)
zwrite(t, dir, b+".txt", b+"\n")
zrun(t, dir, "add", b+".txt")
zrun(t, dir, "commit", "-m", b, "--branch", b, "--user", "u")
id, err := zitcli.New(dir).LandingOpen(testToken, "dan", b, prev, "land "+b, "")
if err != nil {
t.Fatal(err)
}
ids[b] = id
prev = b
}
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
lastStoreEvents = ev
ix, err = index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(zitcli.New(dir), ev, ix, "test", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
return dir, names, ids, ix, pipe.Sync
}
// A single green top-of-stack run pair(tip(top), tip(trunk)) satisfies
// every rung by inclusion and lands a 5-rung stack atomically (#464, #507).
func TestTopOfStackGreenLandsWholeStackAtomically(t *testing.T) {
dir, names, ids, ix, sync := makeStackFixture(t, 5)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
// Only top rung r5 tested against trunk; r1..r4 have zero runs.
ci.green(ztip(t, dir, "r5"), ztip(t, dir, "trunk"))
d := Deps{
Version: "v",
ZitVersion: zitcli.MinVersion,
Checks: mergeChecks{},
CI: ci,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}}),
}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
// landing.get on r5 must read fresh (not stale against r4) and ci-pass.
gotGet, err := r.Invoke(as("dan", "i"), "landing.get", landingGetIn{Repo: "test", ID: ids["r5"]})
if err != nil {
t.Fatal(err)
}
g := gotGet.(landingGetOut)
if g.Stale {
t.Errorf("FAIL: top rung r5 read stale against trunk: %+v", g)
}
if g.Landing.CI != "ci-pass" {
t.Errorf("FAIL: top rung r5 CI = %q, want ci-pass", g.Landing.CI)
}
// Landing lower rung r1 ALONE must NOT ride r5's verdict.
gotLow, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["r1"]})
if err != nil {
t.Fatal(err)
}
if lowOut := gotLow.(landingLandOut); len(lowOut.Landed) != 0 {
t.Fatalf("FAIL: landing r1 alone rode r5's top-of-stack verdict: %+v", lowOut)
}
// Landing the stack at r5 lands all 5 rungs atomically.
gotLand, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["r5"]})
if err != nil {
t.Fatal(err)
}
out := gotLand.(landingLandOut)
if len(out.Landed) != 5 || out.Stopped != "" {
t.Fatalf("FAIL: landStack = %+v; want all 5 rungs landed atomically", out)
}
for _, b := range names {
if st := stateOf(t, ix, ids[b]); st != "accepted" {
t.Errorf("FAIL: rung %s state = %q, want accepted", b, st)
}
}
t.Log("ok: 5-rung stack landed atomically from one green top-of-stack check; r1 alone still required its own check")
}
// When top-of-stack CI fails, an armed stack does not land and falls
// back to per-rung checks enqueued bottom-up to isolate the break (#464, #507).
func TestTopOfStackFailureFallsBackToPerRungBottomUp(t *testing.T) {
dir, _, ids, ix, sync := makeStackFixture(t, 3)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
topPair := "pair:" + ztip(t, dir, "r3") + ":" + ztip(t, dir, "trunk")
ci.runs[topPair] = []CIRun{{Checkin: topPair, Pair: topPair, Workflow: "ci", Pipeline: "ci", Status: "failed"}}
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
if err := db.AddAccount("dan", "a-long-enough-password", false); err != nil {
t.Fatal(err)
}
if err := db.SetAutoAccept("test", ids["r3"], "dan", ztip(t, dir, "r3")); err != nil {
t.Fatal(err)
}
var enqueued []string
d := Deps{
Version: "v",
ZitVersion: zitcli.MinVersion,
Checks: mergeChecks{},
CI: ci,
Auto: db,
CIRunPair: func(_, branch, tip, target string) error {
enqueued = append(enqueued, branch)
pair := "pair:" + tip + ":" + target
ci.runs[pair] = append(ci.runs[pair], CIRun{Checkin: pair, Pair: pair, Workflow: "ci", Pipeline: "ci", Status: "running"})
return nil
},
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}}),
}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
landed := d.AutoAcceptSweep(db)
if len(landed) != 0 {
t.Fatalf("FAIL: failed top-of-stack landed %v", landed)
}
if !slices.Equal(enqueued, []string{"r1", "r2"}) && !slices.Equal(enqueued, []string{"r1", "r2", "r3"}) {
t.Fatalf("FAIL: fallback enqueued %v; want bottom-up r1, r2 (and optionally r3)", enqueued)
}
t.Logf("ok: top-of-stack failure fell back to per-rung bottom-up: %v", enqueued)
}
// Top-of-stack inclusion rejects:
// 1. a forked stack (never lands an untested sibling),
// 2. a top rung that is behind the rung below it (r2 moved without r3),
// 3. a final target that moved after pair(top, oldTarget) passed,
// 4. a protected target where MayJoin is false;
//
// and preserves an already-green pair(top, currentTrunk) without
// needlessly rewriting r1 when r1 has not merged trunk yet.
func TestTopOfStackSafetyInvariants(t *testing.T) {
// 1. Forked stack: r1->trunk, r2a->r1, r2b->r1, r3->r2a.
t.Run("forked sibling never lands untested", func(t *testing.T) {
dir, _, ids, ix, sync := makeStackFixture(t, 2) // r1->trunk, r2->r1
// Add sibling r2b -> r1 and r3 -> r2.
zrun(t, dir, "update", "r1")
zwrite(t, dir, "r2b.txt", "r2b\n")
zrun(t, dir, "add", "r2b.txt")
zrun(t, dir, "commit", "-m", "r2b", "--branch", "r2b", "--user", "u")
id2b, err := zitcli.New(dir).LandingOpen(testToken, "dan", "r2b", "r1", "land r2b", "")
if err != nil {
t.Fatal(err)
}
zrun(t, dir, "update", "r2")
zwrite(t, dir, "r3.txt", "r3\n")
zrun(t, dir, "add", "r3.txt")
zrun(t, dir, "commit", "-m", "r3", "--branch", "r3", "--user", "u")
id3, err := zitcli.New(dir).LandingOpen(testToken, "dan", "r3", "r2", "land r3", "")
if err != nil {
t.Fatal(err)
}
if _, err := sync(); err != nil {
t.Fatal(err)
}
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "r3"), ztip(t, dir, "trunk"))
d := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}})}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: id3})
if err != nil {
t.Fatal(err)
}
if out := got.(landingLandOut); len(out.Landed) != 0 {
t.Fatalf("FAIL: forked stack landed %v via top-of-stack green", out.Landed)
}
if st := stateOf(t, ix, id2b); st != "open" {
t.Fatalf("FAIL: untested forked sibling r2b changed state to %q", st)
}
_ = ids
})
// 2. Behind top rung: r2 gains a new commit while r3 keeps old green pair(r3, trunk).
t.Run("behind top rung does not bypass stackGate", func(t *testing.T) {
dir, _, ids, ix, sync := makeStackFixture(t, 3)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci.green(ztip(t, dir, "r1"), ztip(t, dir, "trunk"))
ci.green(ztip(t, dir, "r3"), ztip(t, dir, "trunk"))
// r2 moves ahead of r3 with a new commit C2, green on r1.
zrun(t, dir, "update", "r2")
zwrite(t, dir, "c2.txt", "c2\n")
zrun(t, dir, "add", "c2.txt")
zrun(t, dir, "commit", "-m", "c2", "--user", "u")
if _, err := sync(); err != nil {
t.Fatal(err)
}
ci.green(ztip(t, dir, "r2"), ztip(t, dir, "r1"))
d := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}})}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
// r3's landing.get must read stale (against r2), not fresh against trunk.
gotGet, err := r.Invoke(as("dan", "i"), "landing.get", landingGetIn{Repo: "test", ID: ids["r3"]})
if err != nil {
t.Fatal(err)
}
if !gotGet.(landingGetOut).Stale {
t.Fatalf("FAIL: behind top rung r3 read Stale=false after r2 moved")
}
// Pressing land on r3 must NOT land r3 with untested C2.
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["r3"]})
if err != nil {
t.Fatal(err)
}
if out := got.(landingLandOut); len(out.Landed) != 0 {
t.Fatalf("FAIL: behind top rung landed %v without testing C2", out.Landed)
}
})
// 3. Moved finalTarget + 4. MayJoin=false + 5. Already-green pair(top, currentTrunk) lands without rewriting r1.
t.Run("moved target, protection, and green-without-restack", func(t *testing.T) {
dir, names, ids, ix, sync := makeStackFixture(t, 3)
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
oldTrunk := ztip(t, dir, "trunk")
ci.green(ztip(t, dir, "r3"), oldTrunk)
// Trunk moves cleanly; old pair(r3, oldTrunk) is now stale.
trunkMoves(t, dir, "extra.txt", "extra\n", sync)
newTrunk := ztip(t, dir, "trunk")
d := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}})}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
// Old trunk green must not land against newTrunk.
got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["r3"]})
if err != nil {
t.Fatal(err)
}
if out := got.(landingLandOut); len(out.Landed) != 0 {
t.Fatalf("FAIL: stale pair(r3, oldTrunk) landed after trunk moved: %+v", out)
}
// Now mark pair(r3, newTrunk) green while r1 is behind newTrunk;
// first verify MayJoin=false still blocks landing.
dir2, names2, ids2, ix2, sync2 := makeStackFixture(t, 3)
trunkMoves(t, dir2, "extra.txt", "extra\n", sync2)
ci2 := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
ci2.green(ztip(t, dir2, "r3"), ztip(t, dir2, "trunk"))
r1Before := ztip(t, dir2, "r1")
dDeny := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci2, Protect: denyJoin{},
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix2, Zit: zitcli.New(dir2), Sync: sync2}})}
rDeny := ops.NewRegistry()
if err := RegisterAll(rDeny, dDeny); err != nil {
t.Fatal(err)
}
gotDeny, err := rDeny.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids2["r3"]})
if err != nil {
t.Fatal(err)
}
if out := gotDeny.(landingLandOut); len(out.Landed) != 0 {
t.Fatalf("FAIL: MayJoin=false still landed via topGreen: %+v", out)
}
// With MayJoin=true, already-green pair(r3, newTrunk) lands all 3
// rungs directly without rewriting r1 first.
dAllow := Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci2,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix2, Zit: zitcli.New(dir2), Sync: sync2}})}
rAllow := ops.NewRegistry()
if err := RegisterAll(rAllow, dAllow); err != nil {
t.Fatal(err)
}
gotAllow, err := rAllow.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids2["r3"]})
if err != nil {
t.Fatal(err)
}
if out := gotAllow.(landingLandOut); len(out.Landed) != 3 {
t.Fatalf("FAIL: already-green pair(r3, newTrunk) did not land all 3 rungs: %+v", out)
}
if ztip(t, dir2, "r1") != r1Before {
t.Errorf("FAIL: r1 was needlessly rewritten before landing an already-green top-of-stack")
}
for _, b := range names2 {
if st := stateOf(t, ix2, ids2[b]); st != "accepted" {
t.Errorf("FAIL: %s state = %q, want accepted", b, st)
}
}
_, _ = names, newTrunk
})
}