package api
import (
"log"
"sort"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/oltp"
)
// Top-of-stack CI for linear strata (#464, #507).
//
// In an open linear stack r1 -> r2 -> ... -> rN -> target, testing every
// rung separately burns O(N) full CI runs on a single-slot runner. When
// every upper rung contains the work of the rung below it (BehindWork == 0
// on links 1..N-1), merging rN directly onto target (pair:<tip(rN)>:<tip(target)>)
// produces the exact tree that landing r1..rN back-to-back writes.
//
// When that single top-of-stack run is green, every rung in the chain is
// green by inclusion and landStack lands the whole stack atomically. If
// it fails, the forge falls back to per-rung checks (enqueued bottom-up)
// so the failing rung is isolated; landing a single rung alone without
// the rungs above it still requires that rung's own merge check.
// stackLinearChain finds the open linear stack containing l, sorted
// bottom-up, and reports whether l belongs to a clean linear stack of
// depth >= 2. A forked stack (two open landings targeting the same
// branch) returns ok=false so forked branches fall back to per-rung CI.
func stackLinearChain(repo *Repo, l index.LandingSummary) (chain []index.LandingSummary, finalTarget string, ok bool) {
if repo == nil || repo.Index == nil || l.State != "open" {
return nil, "", false
}
open, err := repo.Index.Landings("open", 500)
if err != nil {
return nil, "", false
}
return LinearStackIn(repo, open, l.ID)
}
// LinearStackIn extracts the open linear stack containing landingID from
// open landings, sorted bottom-up, with its effective final target.
func LinearStackIn(repo *Repo, open []index.LandingSummary, landingID string) (chain []index.LandingSummary, finalTarget string, ok bool) {
if len(open) < 2 {
return nil, "", false
}
ls := append([]index.LandingSummary(nil), open...)
index.AttachStrata(ls)
var me *index.LandingSummary
for i := range ls {
if ls[i].ID == landingID {
me = &ls[i]
break
}
}
if me == nil || me.Stack == "" || me.Broken != "" || me.Depth < 2 {
return nil, "", false
}
posCount := map[int]int{}
for _, x := range ls {
if x.Stack == me.Stack && x.State == "open" && x.SupersededBy == "" {
if x.Broken != "" {
return nil, "", false
}
posCount[x.Position]++
if posCount[x.Position] > 1 {
// Forked stack: multiple open landings share a position.
return nil, "", false
}
chain = append(chain, x)
}
}
if len(chain) < 2 {
return nil, "", false
}
sort.Slice(chain, func(i, j int) bool { return chain[i].Position < chain[j].Position })
for i := range chain {
if chain[i].Position != i+1 {
return nil, "", false
}
}
return chain, targetNow(repo, chain[0]), true
}
// stackTopFinalTarget returns the stack's final target if l is the top
// rung of an open linear stack of depth >= 2 whose upper rungs already
// contain every lower rung's work, else "".
func stackTopFinalTarget(repo *Repo, l index.LandingSummary) string {
chain, finalTarget, ok := stackLinearChain(repo, l)
if !ok || chain[len(chain)-1].ID != l.ID || !StackContainsLowerRungs(repo, chain) {
return ""
}
return finalTarget
}
// StackContainsLowerRungs reports whether chain is a strictly linear
// chain (chain[k].Target == chain[k-1].Branch with contiguous positions)
// and every upper rung chain[1..N-1] already contains all non-merge work
// of the rung immediately below it. Only then does
// pair(tip(top), tip(finalTarget)) test the exact combined tree of the
// entire stack.
func StackContainsLowerRungs(repo *Repo, chain []index.LandingSummary) bool {
if repo == nil || repo.Index == nil || len(chain) < 2 {
return false
}
clean := cleanMergeOf(repo)
for k := 1; k < len(chain); k++ {
if chain[k].Target != chain[k-1].Branch {
return false
}
if chain[k].Position != 0 && chain[k-1].Position != 0 && chain[k].Position != chain[k-1].Position+1 {
return false
}
n, err := repo.Index.BehindWork(chain[k].Branch, chain[k].Target, clean)
if err != nil || n > 0 {
return false
}
}
return true
}
func stackContainsLowerRungs(repo *Repo, chain []index.LandingSummary) bool {
return StackContainsLowerRungs(repo, chain)
}
// topOfStackVerdict judges the single pair(tip(top), tip(finalTarget))
// merge against finalTarget's required checks.
func (d Deps) topOfStackVerdict(repoName string, repo *Repo, top index.LandingSummary, finalTarget string) (pair string, j judgement, ok bool) {
if d.Checks == nil || d.CI == nil || repo == nil || repo.Index == nil {
return "", judgement{}, false
}
topTip := sourceTipOf(repo, top.Branch)
targetTip := branchTipOf(repo, finalTarget)
if topTip == "" || targetTip == "" {
return "", judgement{}, false
}
required := d.Checks.RequiredChecks(repoName, finalTarget)
if len(required) == 0 {
return "", judgement{}, false
}
pair = "pair:" + topTip + ":" + targetTip
rows := d.checksOn(repoName, pair, true)
j = judgeRows(judgeIn{Required: required, Rows: rows, Merge: true})
return pair, j, true
}
// rerunTopOfStack starts pair(tip(top), tip(finalTarget)) once if no run
// has already been tried for that exact pair.
func (d Deps) rerunTopOfStack(repoName string, repo *Repo, chain []index.LandingSummary, finalTarget string) {
if len(chain) == 0 || repo == nil || repo.Index == nil || d.CIRunPair == nil {
return
}
top := chain[len(chain)-1]
topTip := sourceTipOf(repo, top.Branch)
targetTip := branchTipOf(repo, finalTarget)
if topTip == "" || targetTip == "" {
return
}
pair := "pair:" + topTip + ":" + targetTip
if len(d.checksOn(repoName, pair, true)) > 0 {
return
}
if lp, ok := d.CI.(AnyPairLister); ok {
if p, err := lp.NewestPairFor(repoName, topTip); err != nil || p == pair {
return
}
}
if err := d.CIRunPair(repoName, top.Branch, topTip, targetTip); err != nil {
log.Printf("landing: auto-land %s/%.12s: top-of-stack merge: %v", repoName, top.ID, err)
return
}
log.Printf("landing: auto-land %s/%.12s: testing stack at top %s against %.12s", repoName, top.ID, top.Branch, targetTip)
}
// recoverTopOfStack recovers an armed stack waiting on its top-of-stack
// check: starts pair(tip(top), tip(finalTarget)) if missing, or if it
// failed, records the failure and kicks off per-rung fallback bottom-up.
func (d Deps) recoverTopOfStack(store AutoSweeper, a oltp.AutoAccept, repo *Repo, chain []index.LandingSummary, finalTarget string) bool {
if len(chain) < 2 || !stackContainsLowerRungs(repo, chain) {
return false
}
top := chain[len(chain)-1]
_, j, ok := d.topOfStackVerdict(a.Repo, repo, top, finalTarget)
if !ok {
return false
}
if len(j.Failed) > 0 {
// Top-of-stack failed: report on the top rung and fall back to
// per-rung checks bottom-up to isolate which rung broke.
for _, l := range chain[:len(chain)-1] {
d.rerunStaleMerge(a.Repo, l.ID)
}
return false
}
if len(j.NoRun) > 0 {
d.rerunTopOfStack(a.Repo, repo, chain, finalTarget)
}
return true
}