package oltp
import (
"strings"
"testing"
)
// The newest pair for a tip is the one its checks are read from,
// whichever target it merged into, and another tip's pairs never
// answer for it.
func TestLatestPairForATip(t *testing.T) {
db := testDB(t)
tip, other := strings.Repeat("a", 64), strings.Repeat("a", 63)+"b"
t1, t2 := strings.Repeat("1", 64), strings.Repeat("2", 64)
if got, err := db.LatestPairFor("r", tip); err != nil || got != "" {
t.Fatalf("FAIL: no runs answered %q, %v", got, err)
}
add := func(id, pair string) {
t.Helper()
if err := db.AddCIRun(CIRun{RunID: id, Repo: "r", Checkin: pair, Pair: pair, Workflow: "w", Pipeline: "p", Status: "running"}); err != nil {
t.Fatal(err)
}
}
add("1", "pair:"+tip+":"+t1)
add("2", "pair:"+other+":"+t2)
if got, _ := db.LatestPairFor("r", tip); got != "pair:"+tip+":"+t1 {
t.Fatalf("FAIL: latest pair = %q, want the tip's own", got)
}
if _, err := db.w.Exec(`UPDATE ci_run SET started = '2000-01-01T00:00:00Z' WHERE run_id = '1'`); err != nil {
t.Fatal(err)
}
add("3", "pair:"+tip+":"+t2)
if got, _ := db.LatestPairFor("r", tip); got != "pair:"+tip+":"+t2 {
t.Fatalf("FAIL: latest pair = %q, want the newer target's", got)
}
t.Log("ok: the newest pair for the tip, never another tip's")
}
// A pair whose every run was cancelled judged nothing: the newest pair
// for the tip is the newest that has, or may yet have, a verdict.
func TestLatestPairForSkipsACancelledPair(t *testing.T) {
db := testDB(t)
tip := strings.Repeat("a", 64)
t1, t2 := strings.Repeat("1", 64), strings.Repeat("2", 64)
add := func(id, pair, status, started string) {
t.Helper()
if err := db.AddCIRun(CIRun{RunID: id, Repo: "r", Checkin: pair, Pair: pair, Workflow: "w", Pipeline: id, Status: status}); err != nil {
t.Fatal(err)
}
if _, err := db.w.Exec(`UPDATE ci_run SET started = ? WHERE run_id = ?`, started, id); err != nil {
t.Fatal(err)
}
}
add("pass", "pair:"+tip+":"+t1, "completed", "2026-01-01T00:00:00Z")
add("gone", "pair:"+tip+":"+t2, "cancelled", "2026-01-02T00:00:00Z")
add("also", "pair:"+tip+":"+t2, "canceled", "2026-01-02T00:00:01Z")
if got, _ := db.LatestPairFor("r", tip); got != "pair:"+tip+":"+t1 {
t.Fatalf("FAIL: latest pair = %q; want the older pair with a verdict", got)
}
add("going", "pair:"+tip+":"+t2, "running", "2026-01-02T00:00:02Z")
if got, _ := db.LatestPairFor("r", tip); got != "pair:"+tip+":"+t2 {
t.Fatalf("FAIL: latest pair = %q; want the newer pair, a run of it still going", got)
}
if err := db.SetCIStatus("pass", "cancelled"); err != nil {
t.Fatal(err)
}
if err := db.SetCIStatus("going", "cancelled"); err != nil {
t.Fatal(err)
}
if got, _ := db.LatestPairFor("r", tip); got != "" {
t.Fatalf("FAIL: latest pair = %q; want none, every run cancelled", got)
}
t.Log("ok: a pair with only cancelled runs is never the latest")
}