diff --git a/changelog.d/fixed-same-issue-claim-conflict-gate.md b/changelog.d/fixed-same-issue-claim-conflict-gate.md new file mode 100644 index 0000000000..85a0f0a1fb --- /dev/null +++ b/changelog.d/fixed-same-issue-claim-conflict-gate.md @@ -0,0 +1 @@ +- Merge queue holds every open PR claiming an issue that another open PR in a different automerge lane also claims (the hive's own PR vs a trusted human's PR for one issue) until a decision is recorded — lane reason `merge-train:claim-conflict#:`, log `same-issue claim conflict undecided: #A vs #B`, tracker chevron "held · duplicate of #B · needs decision", and a delegate plan that names the concrete PRs to keep and close instead of "all 2 PRs" (hivecommons/hive#15810). diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index e0831daf13..c07e28d96a 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -909,6 +909,28 @@ contributor task already dispatched on it (see [operator-reference.md § Open-PR dispatch guard](operator-reference.md#open-pr-dispatch-guard-and-duplicate-fix-sweep-scanner)), so the hive does not open the second PR in the first place. +The duplicate pick above sees one lane at a time. When the two PRs sit in +**different lanes** — the hive's own PR in the self lane and a trusted +human's PR in the trusted lane both closing one issue, as #15783 and +#15793 did for #15773 — neither lane's winner rule saw the other and both +marched toward merge. Every lane therefore also runs a **same-issue claim +gate** before its trains are grouped: a candidate whose closing issue any +other open PR of the repository also claims (`Fixes`/`Closes`/`Resolves`; +a `Refs` line is not a claim; an adoption copy and the original it +`Supersedes` are one change, not a pair) is held with lane reason +`merge-train:claim-conflict#:/0:0/0:` and the log line +`same-issue claim conflict undecided: #A vs #B` — in every lane, so +**neither PR is admitted** while the conflict stands. The hive does not +pick: the stage engine parks the held PR at 085, the tracker chevron reads +*held · duplicate of #B · needs decision*, the row's options name the +concrete PRs (*Keep #A — admit it to the merge queue*, *Close #A as +superseded by #B*), and *Let hive decide* only recommends ("Hold both: #A +and #B claim issue #N. Keep #B, close #A — or keep #A, close #B"). A +recorded trusted decision on a PR's head (the tracker's Approve, or any +`/hive decision` on it — the downstream gates still judge the merge) is +what lifts the gate for that PR; closing the other ends it +([#15810](https://github.com/hivecommons/hive/issues/15810)). + ### Empty-diff PRs of the hive's own A PR of the hive's own (the App's, or an adoption it opened) whose diff diff --git a/src/docs/operator-reference.md b/src/docs/operator-reference.md index 9451ab9c4d..88ad09343d 100644 --- a/src/docs/operator-reference.md +++ b/src/docs/operator-reference.md @@ -439,7 +439,7 @@ advanced into the merge path. | `auto_merge.require_current_base_default` | `false` | Hive-wide default of the current-base gate for repos in neither `require_current_base` nor `skip_current_base` (Settings → Features → Auto-merge → "Merge only on current base"). **Off** by default: the merge train already update-branches overlapping siblings, so the gate is being soaked per repo (hive's own hive first, via `require_current_base`) before any hive turns it on everywhere. When `true`, a behind head the App cannot update merges as it was tested, with one WARN per PR (`automerge current-base gate: … merging as tested`), so fork-heavy repos are not parked wholesale. | | `auto_merge.skip_current_base` | unset | Repo list (`owner/repo`) with an explicit **off** override for the current-base gate (Settings → Repos → "Merge only on current base" unchecked): a green head there merges even if the base has moved, whatever `require_current_base_default` says. An explicit `require_current_base` entry wins over this list. | | `auto_merge.merge_forward_trusted_human` | unset (off) | Repo list (`owner/repo`) where a `role/trusted` + `author/human` PR on a same-repo branch that GitHub reports as conflicting (`dirty`) gets the base merged into its head as one App-authored, signed-off merge commit via the GitHub merges API (no human commit is rewritten), then merges once CI is green on the new head. A real conflict pushes nothing and posts one `` note naming the files both sides changed. Fork heads are never written. Attempted once per head (#13636). | -| `auto_merge.merge_train.enabled` | `true` | Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — ordered readiness first: a head the lane last saw at the merge gate (green, approved, soaking or waiting on a sweep) leads, one it has not evaluated since its push comes next, one still at CI / Review trails, then clean-mergeable before behind, then oldest; recomputed every pass, so a member that turns green moves up and one that turns red moves back — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge queue · 3 of 4 · ~4m", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the fixer's rebase-resolve episode (`requested_by: merge-train`, the shared two-attempt guard of [#15104](https://github.com/hivecommons/hive/pull/15104); the fixer router still requires a head the hive can push to, so a fork without maintainer edits stays on the plain `conflicting` path for a person). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. The queue carries one PR per issue: when two open PRs declare the same `Fixes #N`, the sweep keeps one (green first, then the earlier-opened) and holds the other with lane reason `merge-train:duplicate-of#:/0:0/0:` (tracker pill "Duplicate of #15402 · needs a pick"; *Let hive decide* supersedes, [#15395](https://github.com/hivecommons/hive/issues/15395)). `false` restores independent per-PR evaluation. A PR GitHub reports conflicting on its own, or one at stage/072 returned-to-contributor (label or stage record), is never a member nor counted in the train's size and draws no train idle comment; a conflicting PR rides only while the train itself is repairing it (its rebase requested behind a merged front, loop guard not spent) ([#15395](https://github.com/hivecommons/hive/issues/15395)). | +| `auto_merge.merge_train.enabled` | `true` | Conflict-aware merge train in every automerge lane (hive, trusted-author, contributor) ([#15117](https://github.com/hivecommons/hive/issues/15117)). Each sweep groups the open approved / mergeable-pending PRs of one repo+base by overlapping changed files (`GET /pulls/{n}/files`, cached per head SHA) and lets ONE front per group merge — ordered readiness first: a head the lane last saw at the merge gate (green, approved, soaking or waiting on a sweep) leads, one it has not evaluated since its push comes next, one still at CI / Review trails, then clean-mergeable before behind, then oldest; recomputed every pass, so a member that turns green moves up and one that turns red moves back — while the others wait at stage/080 with lane reason `merge-train:queued-behind#:/:…` (tracker pill "In merge queue · 3 of 4 · ~4m", never a human stage, never `needs-rebase` as a human flag). The moment the front merges, every sibling whose branch is merely `behind` gets `PUT /pulls/{n}/update-branch`; a `dirty` one is handed to the fixer's rebase-resolve episode (`requested_by: merge-train`, the shared two-attempt guard of [#15104](https://github.com/hivecommons/hive/pull/15104); the fixer router still requires a head the hive can push to, so a fork without maintainer edits stays on the plain `conflicting` path for a person). A head the lane last saw blocked on its own (red required check, terminal hold, permanent merge refusal) never fronts, and a group whose best member is blocked imposes no ordering (fail-open) — nobody waits behind a PR that is not moving. One INFO line `merge train` per order change, not per cycle. The queue carries one PR per issue: when two open PRs declare the same `Fixes #N`, the sweep keeps one (green first, then the earlier-opened) and holds the other with lane reason `merge-train:duplicate-of#:/0:0/0:` (tracker pill "Duplicate of #15402 · needs a pick"; *Let hive decide* supersedes, [#15395](https://github.com/hivecommons/hive/issues/15395)). That pick sees one lane; when the two claimants sit in different lanes (the hive's own PR and a trusted human's PR for one issue) every lane holds its candidate with lane reason `merge-train:claim-conflict#:/0:0/0:` and the log line `same-issue claim conflict undecided: #A vs #B`, so neither is admitted until a decision is recorded on one head or the other PR closes — the PR parks at 085, the chevron reads "held · duplicate of #B · needs decision", and the row's options name the concrete PRs; the hive recommends and never picks ([#15810](https://github.com/hivecommons/hive/issues/15810)). `false` restores independent per-PR evaluation. A PR GitHub reports conflicting on its own, or one at stage/072 returned-to-contributor (label or stage record), is never a member nor counted in the train's size and draws no train idle comment; a conflicting PR rides only while the train itself is repairing it (its rebase requested behind a merged front, loop guard not spent) ([#15395](https://github.com/hivecommons/hive/issues/15395)). | | `auto_merge.merge_train.max_rebase_attempts` | `2` | Loop guard: how many rebase-resolve requests the train makes for one PR behind one front. Past it the PR moves to stage/085 with the pill "Needs human decision · rebase failed twice" and the decision option "Rebase, then merge as maintainer". | | `auto_merge.native_merge_queue.enabled` | `false` | Opt-in: once the lane's gates pass, enqueue the PR into GitHub's native merge queue (App auth only) instead of merging directly, and withdraw only Hive's own entries when the PR loses eligibility ([#15198](https://github.com/hivecommons/hive/issues/15198)). Off keeps the pre-queue behaviour everywhere, including the `merge-queue-required` park. See [native-merge-queue.md](native-merge-queue.md). | | `auto_merge.native_merge_queue.repos` | unset (every watched repo once enabled) | `owner/repo` allow-list for the hand-off, matched case-insensitively. | diff --git a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go index c2082420b8..6c86148dce 100644 --- a/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go +++ b/src/pkg/dashboard/api_repo_item_decide_delegated_plan.go @@ -187,6 +187,17 @@ func delegatedPlanWording(in delegatedecision.Input, d delegatedecision.Decision } } switch { + case d.Rule == delegatedecision.RuleSameIssueClaimConflict && in.ClaimConflictWith > 0: + other := "#" + strconv.Itoa(in.ClaimConflictWith) + issue := "the same issue" + if in.ClaimConflictIssue > 0 { + issue = "issue #" + strconv.Itoa(in.ClaimConflictIssue) + } + return "Hold both: " + ref + " and " + other + " claim " + issue + ". Keep " + other + ", close " + ref + " — or keep " + ref + ", close " + other + "; the hive will not pick.", + []string{ + "Neither PR merges until one of them is closed or approved.", + "Approve on a row admits that PR to the merge queue; Close as superseded on the other closes it with credit.", + } case d.Verdict == delegatedecision.VerdictAdoptSupersede: return "Re-open " + ref + " as hive's own PR with the same commits and merge that; close " + ref + " as superseded.", []string{ diff --git a/src/pkg/dashboard/delegated_pr_context.go b/src/pkg/dashboard/delegated_pr_context.go index 968fe1b9e7..8a7cb737a9 100644 --- a/src/pkg/dashboard/delegated_pr_context.go +++ b/src/pkg/dashboard/delegated_pr_context.go @@ -131,13 +131,28 @@ func (s *Server) gatherDelegatedPRContext(ctx context.Context, repo string, pr * }) } in.TrainDuplicateOf, in.TrainDuplicateIssue = delegatedTrainDuplicate(s.stageStoreOrShared(), repo, pr.GetNumber()) + in.ClaimConflictWith, in.ClaimConflictIssue = delegatedClaimConflict(s.stageStoreOrShared(), repo, pr.GetNumber()) return nil } +// delegatedClaimConflict reads the stage store for the cross-lane +// same-issue hold the merge queue recorded on a PR +// (hivecommons/hive#15810): the other claimant and the shared issue, 0 +// when it is not held. +func delegatedClaimConflict(store *stagelabels.Store, repo string, number int) (other, issue int) { + return delegatedTrainState(store, repo, number, prstage.MergeTrainStateClaimConflict) +} + // delegatedTrainDuplicate reads the stage store for the one-PR-per-issue // hold the merge queue recorded on a PR (hivecommons/hive#15395): the PR // it yields to and the shared issue, 0 when it is not held. func delegatedTrainDuplicate(store *stagelabels.Store, repo string, number int) (winner, issue int) { + return delegatedTrainState(store, repo, number, prstage.MergeTrainStateDuplicateOf) +} + +// delegatedTrainState is the front and position of the merge-train reason +// recorded on a PR when its state is state, 0,0 otherwise. +func delegatedTrainState(store *stagelabels.Store, repo string, number int, state string) (int, int) { if store == nil { return 0, 0 } @@ -146,7 +161,7 @@ func delegatedTrainDuplicate(store *stagelabels.Store, repo string, number int) return 0, 0 } mt, ok := prstage.ParseMergeTrain(rec.Reason) - if !ok || mt.State != prstage.MergeTrainStateDuplicateOf { + if !ok || mt.State != state { return 0, 0 } return mt.Front, mt.Position diff --git a/src/pkg/dashboard/stage_tracker_build.go b/src/pkg/dashboard/stage_tracker_build.go index e35072aa5c..a824013daa 100644 --- a/src/pkg/dashboard/stage_tracker_build.go +++ b/src/pkg/dashboard/stage_tracker_build.go @@ -174,6 +174,9 @@ func (s *Server) buildStageTracker(status *StatusPayload, store *stagelabels.Sto if c := stageTrackerSoakCaption(rec, now); c != "" { it.Caption = c } + if c := stageTrackerClaimConflictCaption(it); c != "" { + it.Caption, it.Actor = c, StageActorHuman + } if hasRec && rec.Stage != stagelabels.None { if at := stageTrackerNoteChangedAt(rec, now); !at.IsZero() { it.NoteChangedAt = &at diff --git a/src/pkg/dashboard/stage_tracker_claim_conflict_test.go b/src/pkg/dashboard/stage_tracker_claim_conflict_test.go new file mode 100644 index 0000000000..4b201f6691 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_claim_conflict_test.go @@ -0,0 +1,87 @@ +package dashboard + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/delegatedecision" + "github.com/hivecommons/hive/pkg/stageengine/prstage" + "github.com/hivecommons/hive/pkg/stagelabels" +) + +// hivecommons/hive#15810: a PR the merge queue holds because an open PR in +// another lane claims the same issue reads "claim-conflict:" on the +// gate, rides no train, captions "held · duplicate of # · needs +// decision", and its decision options name both PRs — never "all N PRs". +func TestStageTrackerApplyClaimConflict(t *testing.T) { + reason := prstage.MergeTrain{State: prstage.MergeTrainStateClaimConflict, Front: 15793, Position: 15773}.Reason() + it := StageTrackerItem{Repo: "hivecommons/hive", Kind: "pr", Number: 15783, Stage: 85, BaseRef: "v5", Reason: reason} + stageTrackerApplyMergeTrain(&it) + if it.MergeTrain != nil { + t.Fatalf("a held claimant rides no train: %+v", it.MergeTrain) + } + if it.MergeGate == nil || it.MergeGate.State != "claim-conflict:15793" || it.MergeGate.DuplicateOf != 15793 || it.MergeGate.DuplicateIssue != 15773 { + t.Fatalf("gate = %+v", it.MergeGate) + } + if !slices.Contains(it.Modifiers, modNeedsDecision) { + t.Fatalf("modifiers = %v", it.Modifiers) + } + if c := stageTrackerClaimConflictCaption(&it); c != "held · duplicate of #15793 · needs decision" { + t.Fatalf("caption = %q", c) + } + d := stageTrackerDecisionNeededAt(it, nil, "", time.Now()) + if d == nil || !strings.Contains(d.Question, "#15783 and #15793 both claim issue #15773") { + t.Fatalf("decision = %+v", d) + } + labels := make([]string, 0, len(d.Options)) + for _, o := range d.Options { + labels = append(labels, o.Label) + } + if !slices.Contains(labels, "Keep #15783 — admit it to the merge queue") || !slices.Contains(labels, "Close #15783 as superseded by #15793") { + t.Fatalf("options = %v", labels) + } + for _, l := range labels { + if strings.Contains(l, "all 2") { + t.Fatalf("generic option %q", l) + } + } + + // The other row — a plain duplicate-of hold — is untouched by the + // claim-conflict caption. + dup := StageTrackerItem{Kind: "pr", Number: 15407, Reason: prstage.MergeTrain{State: prstage.MergeTrainStateDuplicateOf, Front: 15402, Position: 15396}.Reason()} + stageTrackerApplyMergeTrain(&dup) + if c := stageTrackerClaimConflictCaption(&dup); c != "" { + t.Fatalf("duplicate-of caption = %q", c) + } +} + +// The delegate's plan for a held claimant names the concrete PRs and the +// two ways out instead of "all 2 PRs", and only recommends. +func TestDelegatedPlanWordingClaimConflictNamesPRs(t *testing.T) { + now := time.Date(2026, 11, 3, 15, 0, 0, 0, time.UTC) + store := stagelabels.NewStore("", func() time.Time { return now }) + store.Observe(stagelabels.Key("hivecommons/hive", 15783), stagelabels.NeedsDecision, + prstage.MergeTrain{State: prstage.MergeTrainStateClaimConflict, Front: 15793, Position: 15773}.Reason()) + other, issue := delegatedClaimConflict(store, "hivecommons/hive", 15783) + if other != 15793 || issue != 15773 { + t.Fatalf("store read = #%d issue #%d", other, issue) + } + if w, _ := delegatedTrainDuplicate(store, "hivecommons/hive", 15783); w != 0 { + t.Fatal("a claim conflict is not the duplicate-of pick") + } + + in := delegatedecision.Input{Kind: delegatedecision.KindPR, Number: 15783, HiveAuthored: true, CIGreen: true, ClaimConflictWith: other, ClaimConflictIssue: issue} + d := delegatedecision.Decide(in) + if d.Verdict != delegatedecision.VerdictRecommendOnly || d.Rule != delegatedecision.RuleSameIssueClaimConflict { + t.Fatalf("verdict %s rule %s", d.Verdict, d.Rule) + } + summary, next := delegatedPlanWording(in, d) + if summary != "Hold both: #15783 and #15793 claim issue #15773. Keep #15793, close #15783 — or keep #15783, close #15793; the hive will not pick." { + t.Fatalf("summary %q", summary) + } + if len(next) != 2 || strings.Contains(summary, "all 2") { + t.Fatalf("then %v", next) + } +} diff --git a/src/pkg/dashboard/stage_tracker_decision.go b/src/pkg/dashboard/stage_tracker_decision.go index 32a11a7126..2e7c36e3ba 100644 --- a/src/pkg/dashboard/stage_tracker_decision.go +++ b/src/pkg/dashboard/stage_tracker_decision.go @@ -203,6 +203,8 @@ func stageTrackerDecisionNeededWith(it StageTrackerItem, verdict *review.Aggrega switch { case it.Kind == "pr" && it.MergeTrain != nil && it.MergeTrain.State == MergeGateStateRebaseExhausted: return decisionForMergeTrain(it, held) + case it.Kind == "pr" && it.MergeGate != nil && mergeGateClaimConflictOf(it.MergeGate.State) > 0: + return decisionForClaimConflict(it, held) case it.Kind == "issue" && it.Blocker != nil && !it.Mirrored && (slices.Contains(it.Modifiers, modNeedsHuman) || it.Stage == stagelabels.IssueNeedsDecision.Number() || slices.Contains(it.Modifiers, modNeedsDecision)): // A structured blocker outranks the generic park wording: the // person is not being asked to decide, the hive is saying what it diff --git a/src/pkg/dashboard/stage_tracker_decision_claim.go b/src/pkg/dashboard/stage_tracker_decision_claim.go new file mode 100644 index 0000000000..bb49dfbd69 --- /dev/null +++ b/src/pkg/dashboard/stage_tracker_decision_claim.go @@ -0,0 +1,30 @@ +package dashboard + +import "strconv" + +// decisionForClaimConflict: the merge queue holds this PR because an open +// PR in another lane claims the same issue and nobody has decided which +// lands (hivecommons/hive#15810). The options name the concrete PRs — +// "Keep #15793 (this PR)", "Close #15793 as superseded by #15783" — never +// a generic "all N PRs": Approve admits this one to the queue, Close ends +// the conflict in the other's favour, and the hive picks neither itself. +func decisionForClaimConflict(it StageTrackerItem, held bool) *StageTrackerDecision { + this := "#" + strconv.Itoa(it.Number) + other := "#" + strconv.Itoa(it.MergeGate.DuplicateOf) + issue := "the same issue" + if it.MergeGate.DuplicateIssue > 0 { + issue = "issue #" + strconv.Itoa(it.MergeGate.DuplicateIssue) + } + d := &StageTrackerDecision{Since: it.StageSince, AskedBy: decisionAskedByLane, BlockerReason: it.Reason} + d.Question = this + " and " + other + " both claim " + issue + ". Keep " + this + " and close " + other + ", or keep " + other + " and close " + this + "?" + d.Blocker = "The merge queue admits neither PR while two open PRs claim one issue and no decision is recorded, so two implementations of one fix never both land." + if held { + d.Blocker += " " + decisionHeldBlocker(it.Hold) + } + keep := decisionOption(decisionActionApprove, "Keep "+this+" — admit it to the merge queue", !held, decisionWhyHeld) + keep.Consequence = "Hive records your approval on " + this + " and the queue admits it on the next pass; close " + other + " yourself or from its own row so it does not land too." + closeThis := decisionOption(decisionActionCloseSuperseded, "Close "+this+" as superseded by "+other, !held, decisionWhyHeld) + closeThis.Consequence = this + " is closed with a comment crediting the work and pointing at " + other + "; " + other + " then proceeds alone." + d.Options = []StageTrackerDecisionOption{keep, closeThis, decisionHoldOption(held)} + return d +} diff --git a/src/pkg/dashboard/stage_tracker_merge_gate.go b/src/pkg/dashboard/stage_tracker_merge_gate.go index bca110d8f7..468e1e9fb1 100644 --- a/src/pkg/dashboard/stage_tracker_merge_gate.go +++ b/src/pkg/dashboard/stage_tracker_merge_gate.go @@ -105,6 +105,27 @@ func MergeGateStateDuplicateOf(n int) string { return MergeGateStateDuplicateOfPrefix + strconv.Itoa(n) } +// MergeGateStateClaimConflictPrefix opens the gate state of a PR the merge +// queue holds because an open PR in another lane claims the same issue and +// no decision is recorded (hivecommons/hive#15810): "claim-conflict:15793". +const MergeGateStateClaimConflictPrefix = prstage.MergeTrainStateClaimConflict + ":" + +// MergeGateStateClaimConflict is the gate state for a PR held against n. +func MergeGateStateClaimConflict(n int) string { + return MergeGateStateClaimConflictPrefix + strconv.Itoa(n) +} + +// mergeGateClaimConflictOf reads the other claimant out of a +// claim-conflict gate state, 0 for any other state. +func mergeGateClaimConflictOf(state string) int { + rest, ok := strings.CutPrefix(state, MergeGateStateClaimConflictPrefix) + if !ok { + return 0 + } + n, _ := strconv.Atoi(rest) + return n +} + // stageTrackerMergeGateState maps a stage to its merge-gate state; "" off // the gate. func stageTrackerMergeGateState(stage stagelabels.Stage) string { diff --git a/src/pkg/dashboard/stage_tracker_merge_train.go b/src/pkg/dashboard/stage_tracker_merge_train.go index 140402ab4a..b7919f00e6 100644 --- a/src/pkg/dashboard/stage_tracker_merge_train.go +++ b/src/pkg/dashboard/stage_tracker_merge_train.go @@ -172,6 +172,10 @@ func stageTrackerApplyMergeTrain(it *StageTrackerItem) { stageTrackerApplyDuplicateHold(it, mt) return } + if mt.State == prstage.MergeTrainStateClaimConflict { + stageTrackerApplyClaimConflict(it, mt) + return + } mt.ID = it.BaseRef + "#" + strconv.Itoa(mt.Front) it.MergeTrain = mt parsed, _ := prstage.ParseMergeTrain(it.Reason) @@ -208,6 +212,41 @@ func stageTrackerApplyDuplicateHold(it *StageTrackerItem, mt *StageTrackerMergeT } } +// stageTrackerApplyClaimConflict decorates a PR the sweep held because an +// open PR in another lane claims the same issue and nobody has decided +// which lands (hivecommons/hive#15810): the gate reads +// "claim-conflict:" with the other PR and the issue on the gate, +// the row rides no train, the caption says "held · duplicate of # +// · needs decision", and it wears needs-decision so the row offers the +// keep / close choice by name. +func stageTrackerApplyClaimConflict(it *StageTrackerItem, mt *StageTrackerMergeTrain) { + parsed, _ := prstage.ParseMergeTrain(it.Reason) + if it.MergeGate == nil { + it.MergeGate = &StageTrackerMergeGate{} + } + it.MergeGate.State = MergeGateStateClaimConflict(mt.Front) + it.MergeGate.Reason = parsed.Sentence() + it.MergeGate.DuplicateOf = mt.Front + it.MergeGate.DuplicateIssue = mt.Position + it.MergeTrain = nil + if !slices.Contains(it.Modifiers, modNeedsDecision) { + it.Modifiers = append(it.Modifiers, modNeedsDecision) + } +} + +// stageTrackerClaimConflictCaption is the row caption of a PR held on an +// undecided same-issue claim, "" for every other row. +func stageTrackerClaimConflictCaption(it *StageTrackerItem) string { + if it == nil || it.MergeGate == nil { + return "" + } + other := mergeGateClaimConflictOf(it.MergeGate.State) + if other <= 0 { + return "" + } + return prstage.ClaimConflictCaption(other) +} + // stageTrackerLeftTrainNote is the muted hover note on a PR the view // dropped from its merge train while a person or the fixer has it // (hivecommons/hive#15405 led a train header as "1st: #15405" while its diff --git a/src/pkg/dashboard/static-src/js/tracker-words-core.js b/src/pkg/dashboard/static-src/js/tracker-words-core.js index 9423592ba3..e70caaf2b5 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-core.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-core.js @@ -163,6 +163,16 @@ // fixes the same issue: "duplicate-of:15402" (merge_gate.duplicate_of // / duplicate_issue carry the numbers). const STAGE_TRACKER_GATE_DUPLICATE_PREFIX = 'duplicate-of:'; + // merge_gate.state of a PR the queue holds because an open PR in + // another lane claims the same issue and nobody has decided which + // lands (hivecommons/hive#15810): "claim-conflict:15793". + const STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX = 'claim-conflict:'; + // Pure: the other claimant of a "claim-conflict:" gate state; 0 for + // any other state. + function stageTrackerGateClaimConflictOf(state) { + state = String(state || ''); + return state.indexOf(STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX) === 0 ? Number(state.slice(STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX.length)) || 0 : 0; + } // Pure: the PR number a "duplicate-of:" gate state yields to; 0 for // any other state. function stageTrackerGateDuplicateOf(state) { @@ -177,6 +187,12 @@ if (STAGE_TRACKER_MERGE_GATE_WORD[state]) return STAGE_TRACKER_MERGE_GATE_WORD[state]; const dup = stageTrackerGateDuplicateOf(state); if (dup) return STAGE_TRACKER_TRAIN_STATE_WORD['duplicate-of'] + ' #' + dup; + // Inline prefix read (hivecommons/hive#15810): this function is + // lifted alone into node by the Go tests. + if (state.indexOf('claim-conflict:') === 0) { + const conflict = Number(state.slice('claim-conflict:'.length)) || 0; + if (conflict) return 'Held · duplicate of #' + conflict + ' · needs decision'; + } if (STAGE_TRACKER_TRAIN_STATE_WORD[state]) return STAGE_TRACKER_TRAIN_STATE_WORD[state]; const plain = state.replace(/[-_]+/g, ' ').trim(); return plain ? plain.charAt(0).toUpperCase() + plain.slice(1) : ''; diff --git a/src/pkg/dashboard/static-src/js/tracker-words-gate.js b/src/pkg/dashboard/static-src/js/tracker-words-gate.js index aaa7700098..c865eb6163 100644 --- a/src/pkg/dashboard/static-src/js/tracker-words-gate.js +++ b/src/pkg/dashboard/static-src/js/tracker-words-gate.js @@ -139,6 +139,15 @@ // kept one and holds this one — "Duplicate of #15402 · needs a // pick"; no clock, no train. Let hive decide on either row closes // the held one as superseded. + // Two open PRs for one issue in different lanes (hivecommons/hive#15810): + // the queue admits neither until a person keeps one and closes the + // other; the row's decision options name both PRs. + const conflictWith = typeof stageTrackerGateClaimConflictOf === 'function' ? stageTrackerGateClaimConflictOf(state) : 0; + if (conflictWith) { + const issue = Number(mg.duplicate_issue) || 0; + const tip = 'This PR and #' + conflictWith + ' both claim' + (issue ? ' #' + issue : ' the same issue') + " from different merge lanes. Hive's merge queue admits neither until one is closed or approved, so two implementations of one fix never both land. Keep this one (Approve) or close it as superseded by #" + conflictWith + '.' + lastSeen; + return { state, word: word, detail: 'needs decision', tip, cue: 'waiting', until: 0, duplicateOf: conflictWith }; + } const dupOf = stageTrackerGateDuplicateOf(state); if (dupOf) { const issue = Number(mg.duplicate_issue) || 0; diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index c14ecd8ad1..1cf4b58376 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14625,6 +14625,16 @@

Where to get help

// fixes the same issue: "duplicate-of:15402" (merge_gate.duplicate_of // / duplicate_issue carry the numbers). const STAGE_TRACKER_GATE_DUPLICATE_PREFIX = 'duplicate-of:'; + // merge_gate.state of a PR the queue holds because an open PR in + // another lane claims the same issue and nobody has decided which + // lands (hivecommons/hive#15810): "claim-conflict:15793". + const STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX = 'claim-conflict:'; + // Pure: the other claimant of a "claim-conflict:" gate state; 0 for + // any other state. + function stageTrackerGateClaimConflictOf(state) { + state = String(state || ''); + return state.indexOf(STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX) === 0 ? Number(state.slice(STAGE_TRACKER_GATE_CLAIM_CONFLICT_PREFIX.length)) || 0 : 0; + } // Pure: the PR number a "duplicate-of:" gate state yields to; 0 for // any other state. function stageTrackerGateDuplicateOf(state) { @@ -14639,6 +14649,12 @@

Where to get help

if (STAGE_TRACKER_MERGE_GATE_WORD[state]) return STAGE_TRACKER_MERGE_GATE_WORD[state]; const dup = stageTrackerGateDuplicateOf(state); if (dup) return STAGE_TRACKER_TRAIN_STATE_WORD['duplicate-of'] + ' #' + dup; + // Inline prefix read (hivecommons/hive#15810): this function is + // lifted alone into node by the Go tests. + if (state.indexOf('claim-conflict:') === 0) { + const conflict = Number(state.slice('claim-conflict:'.length)) || 0; + if (conflict) return 'Held · duplicate of #' + conflict + ' · needs decision'; + } if (STAGE_TRACKER_TRAIN_STATE_WORD[state]) return STAGE_TRACKER_TRAIN_STATE_WORD[state]; const plain = state.replace(/[-_]+/g, ' ').trim(); return plain ? plain.charAt(0).toUpperCase() + plain.slice(1) : ''; @@ -15539,6 +15555,15 @@

Where to get help

// kept one and holds this one — "Duplicate of #15402 · needs a // pick"; no clock, no train. Let hive decide on either row closes // the held one as superseded. + // Two open PRs for one issue in different lanes (hivecommons/hive#15810): + // the queue admits neither until a person keeps one and closes the + // other; the row's decision options name both PRs. + const conflictWith = typeof stageTrackerGateClaimConflictOf === 'function' ? stageTrackerGateClaimConflictOf(state) : 0; + if (conflictWith) { + const issue = Number(mg.duplicate_issue) || 0; + const tip = 'This PR and #' + conflictWith + ' both claim' + (issue ? ' #' + issue : ' the same issue') + " from different merge lanes. Hive's merge queue admits neither until one is closed or approved, so two implementations of one fix never both land. Keep this one (Approve) or close it as superseded by #" + conflictWith + '.' + lastSeen; + return { state, word: word, detail: 'needs decision', tip, cue: 'waiting', until: 0, duplicateOf: conflictWith }; + } const dupOf = stageTrackerGateDuplicateOf(state); if (dupOf) { const issue = Number(mg.duplicate_issue) || 0; diff --git a/src/pkg/delegatedecision/policy.go b/src/pkg/delegatedecision/policy.go index ee9b0db6f4..ae0c2662fe 100644 --- a/src/pkg/delegatedecision/policy.go +++ b/src/pkg/delegatedecision/policy.go @@ -242,6 +242,12 @@ type Input struct { // TrainDuplicateIssue is that issue (hivecommons/hive#15395). TrainDuplicateOf int TrainDuplicateIssue int + // ClaimConflictWith is the open PR in another merge lane that claims + // the same issue as this one while no decision is recorded, so the + // queue admits neither (0 = none); ClaimConflictIssue is that issue + // (hivecommons/hive#15810). + ClaimConflictWith int + ClaimConflictIssue int // ReporterTrustHold: the park is the reporter-trust gate on the fixing PR. ReporterTrustHold bool // AdoptionStalled: a contributor PR whose adoption parked at 085. @@ -662,6 +668,11 @@ func decidePR(in Input) Decision { Actions: []Action{decisionComment(text), {Kind: ActionApproveReview}}, } } + // Two open PRs for one issue in different lanes (hivecommons/hive#15810): + // the queue holds both and the hive only names the choice. + if d, ok := decideClaimConflict(in, ref); ok { + return d + } // Two open PRs for one issue (hivecommons/hive#15395): the merge // queue already picked the survivor (green first, then earlier); the // held one closes as superseded, the kept one is released. @@ -778,6 +789,31 @@ func decideAdoptedByHive(in Input, ref string) (Decision, bool) { // held as a duplicate closes as superseded by the one it kept. const RuleOnePRPerIssue = "one-pr-per-issue" +// RuleSameIssueClaimConflict: two open PRs in different merge lanes claim +// one issue and nobody has decided which lands; the queue admits neither +// and the hive names the choice without making it (hivecommons/hive#15810). +const RuleSameIssueClaimConflict = "same-issue-claim-conflict" + +// decideClaimConflict is the recommend-only answer for a PR the merge +// queue holds on an undecided same-issue claim: the hive's own PR and a +// trusted human's PR for hivecommons/hive#15773 both marched toward merge +// because each lane saw only its own. The hive does not pick — it names +// the two PRs and the two ways out; Approve on one row admits that PR, +// Close as superseded on the other ends the conflict. +func decideClaimConflict(in Input, ref string) (Decision, bool) { + if in.Kind != KindPR || in.ClaimConflictWith <= 0 { + return Decision{}, false + } + other := fmt.Sprintf("#%d", in.ClaimConflictWith) + issue := "the same issue" + if in.ClaimConflictIssue > 0 { + issue = fmt.Sprintf("issue #%d", in.ClaimConflictIssue) + } + return recommendOnly(RuleSameIssueClaimConflict, + fmt.Sprintf("%s and %s both claim %s from different merge lanes; the merge queue admits neither until one is closed or approved, so two implementations of one fix never both land", ref, other, issue), + fmt.Sprintf("keep %s, close %s — or keep %s, close %s; the hive will not pick", other, ref, ref, other)), true +} + // decideTrainDuplicate resolves a same-issue pair the merge queue split // (hivecommons/hive#15395). The queue's pick stands: a green head beats a // red one, the earlier-opened wins among equals. Deciding on the held PR diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 254e894bb3..b5548fcc1c 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -445,6 +445,11 @@ func (c *Engine) SweepContributorLaneAutoMerges(ctx context.Context, opts AutoMe stage(c.mergeTrainDuplicateSkip(train, number), false, nil) continue } + if _, held := train.claimConflictOf(number); held { + result.Skipped++ + stage(c.mergeTrainClaimConflictSkip(train, number), false, nil) + continue + } if train.isSibling(number) { result.Skipped++ stage(c.mergeTrainSkip(train, number), false, nil) diff --git a/src/pkg/github/automerge/automerge_forgestate.go b/src/pkg/github/automerge/automerge_forgestate.go index d217727fa3..620fa72672 100644 --- a/src/pkg/github/automerge/automerge_forgestate.go +++ b/src/pkg/github/automerge/automerge_forgestate.go @@ -265,6 +265,9 @@ func (c *Engine) openPullRequests(ctx context.Context, owner, repoName string, t fullRepo := owner + "/" + repoName if c.openPRs == nil { prs, err := c.listOpenPullRequests(ctx, owner, repoName) + if err == nil { + c.rememberClaimants(fullRepo, prs) + } if err != nil || targets == nil { return prs, "", err } diff --git a/src/pkg/github/automerge/automerge_merge_train.go b/src/pkg/github/automerge/automerge_merge_train.go index 20eaf711ea..ca02609ba5 100644 --- a/src/pkg/github/automerge/automerge_merge_train.go +++ b/src/pkg/github/automerge/automerge_merge_train.go @@ -362,6 +362,9 @@ type mergeTrainPlan struct { // duplicates are the PRs held out of every train this pass because // another open PR fixes the same issue (one PR per issue). duplicates map[int]mergeTrainDuplicateHold + // claimConflicts are the candidates held because an open PR outside + // this lane claims the same issue and no decision is recorded. + claimConflicts map[int]mergeTrainClaimConflict } // group returns the train number rides in, if any. @@ -414,7 +417,7 @@ func (c *Engine) planMergeTrains(ctx context.Context, lane, displayRepo, owner, if !c.mergeTrainPolicyNow().Enabled || c == nil || c.gh == nil { return plan } - prs = c.planDuplicateHolds(plan, lane, owner, repo, displayRepo, prs, prefilter) + prs = c.planDuplicateHolds(ctx, plan, lane, owner, repo, displayRepo, prs, prefilter) perBase := map[string][]*gh.PullRequest{} for _, pr := range prs { if pr == nil || pr.GetNumber() <= 0 || pr.GetHead() == nil || pr.GetHead().GetSHA() == "" { diff --git a/src/pkg/github/automerge/automerge_merge_train_claim_conflict_test.go b/src/pkg/github/automerge/automerge_merge_train_claim_conflict_test.go new file mode 100644 index 0000000000..d937ab3010 --- /dev/null +++ b/src/pkg/github/automerge/automerge_merge_train_claim_conflict_test.go @@ -0,0 +1,167 @@ +package automerge + +import ( + "bytes" + "context" + "log/slog" + "strings" + "testing" + "time" + + gh "github.com/google/go-github/v72/github" + "github.com/hivecommons/hive/pkg/review" + "github.com/hivecommons/hive/pkg/stageengine/prstage" +) + +func claimPR(n int, login, body string, at time.Time) *gh.PullRequest { + return &gh.PullRequest{ + Number: gh.Int(n), Title: gh.String("t"), Body: gh.String(body), State: gh.String("open"), + CreatedAt: &gh.Timestamp{Time: at}, MergeableState: gh.String("clean"), + User: &gh.User{Login: gh.String(login)}, + Head: &gh.PullRequestBranch{SHA: gh.String("sha-" + login)}, + Base: &gh.PullRequestBranch{Ref: gh.String("v5")}, + } +} + +// hivecommons/hive#15810: the hive's own #15783 (self lane) and a trusted +// human's #15793 (trusted lane) both closed #15773 and both marched toward +// merge because each lane's one-PR-per-issue rule saw only its own PRs. +// Now any lane candidate whose issue another open PR of the repo claims is +// held as a claim conflict — in every lane, so neither is admitted — with +// the log line naming the pair. +func TestPlanClaimConflictsHoldsCrossLanePair(t *testing.T) { + var logs bytes.Buffer + c := &Engine{logger: slog.New(slog.NewTextHandler(&logs, nil))} + t0 := time.Date(2026, 11, 3, 10, 25, 0, 0, time.UTC) + hive, human := claimPR(15783, "hive-app[bot]", "Closes #15773", t0), claimPR(15793, "clubanderson", "Fixes #15773", t0.Add(28*time.Minute)) + prs := []*gh.PullRequest{hive, human} + selfOnly := func(p *gh.PullRequest) string { + if p.GetUser().GetLogin() != "hive-app[bot]" { + return "author:not-self" + } + return "" + } + trustedOnly := func(p *gh.PullRequest) string { + if p.GetUser().GetLogin() != "clubanderson" { + return "author:not-trusted" + } + return "" + } + + self := &mergeTrainPlan{lane: stageLaneSelf, displayRepo: "o/r"} + kept := c.planDuplicateHolds(context.Background(), self, stageLaneSelf, "o", "r", "o/r", prs, selfOnly) + if len(kept) != 1 || kept[0].GetNumber() != 15793 { + t.Fatalf("self lane kept %v, want only the other lane's PR left (itself not a self candidate)", kept) + } + h, held := self.claimConflictOf(15783) + if !held || h.Other != 15793 || h.Issue != 15773 { + t.Fatalf("self hold = %+v held=%v", h, held) + } + if _, dup := self.duplicateOf(15783); dup { + t.Fatal("a cross-lane pair is a claim conflict, not a same-lane duplicate pick") + } + + trusted := &mergeTrainPlan{lane: stageLaneTrusted, displayRepo: "o/r"} + c.planDuplicateHolds(context.Background(), trusted, stageLaneTrusted, "o", "r", "o/r", prs, trustedOnly) + h, held = trusted.claimConflictOf(15793) + if !held || h.Other != 15783 || h.Issue != 15773 { + t.Fatalf("trusted hold = %+v held=%v", h, held) + } + if !strings.Contains(logs.String(), "same-issue claim conflict undecided: #15783 vs #15793") { + t.Fatalf("log missing the pair:\n%s", logs.String()) + } + + reason := c.mergeTrainClaimConflictSkip(self, 15783) + mt, ok := prstage.ParseMergeTrain(reason) + if !ok || mt.State != prstage.MergeTrainStateClaimConflict || mt.Front != 15793 || mt.Position != 15773 { + t.Fatalf("reason %q parsed %+v ok=%v", reason, mt, ok) + } + if !strings.HasPrefix(mt.Sentence(), "held · duplicate of #15793 · needs decision") { + t.Fatalf("sentence = %q", mt.Sentence()) + } +} + +// A recorded decision on the candidate's head is the answer the gate waits +// for: that PR is admitted (the other lane's still holds its own); an +// adoption pair (`Supersedes #N`) is one change in flight, not a conflict; +// a `Refs` line is not a claim. +func TestPlanClaimConflictsDecidedOrAdoptionAdmits(t *testing.T) { + t0 := time.Date(2026, 11, 3, 10, 25, 0, 0, time.UTC) + all := func(*gh.PullRequest) string { return "" } + hiveOnly := func(p *gh.PullRequest) string { + if p.GetUser().GetLogin() != "hive-app[bot]" { + return "author:not-self" + } + return "" + } + + store := review.NewHumanChangeRequests("") + if err := store.Record(review.HumanChangeRequest{Repo: "o/r", Number: 15793, HeadSHA: "sha-clubanderson", Source: review.HumanChangeRequestSourceDecision, SourceID: 1, Actor: "clubanderson", Body: "approve"}); err != nil { + t.Fatal(err) + } + c := &Engine{humanChangeRequests: store} + prs := []*gh.PullRequest{claimPR(15783, "hive-app[bot]", "Closes #15773", t0), claimPR(15793, "clubanderson", "Fixes #15773", t0.Add(time.Hour))} + trusted := &mergeTrainPlan{lane: stageLaneTrusted} + kept := c.planDuplicateHolds(context.Background(), trusted, stageLaneTrusted, "o", "r", "o/r", prs, func(p *gh.PullRequest) string { + if p.GetUser().GetLogin() != "clubanderson" { + return "author:not-trusted" + } + return "" + }) + if _, held := trusted.claimConflictOf(15793); held || len(kept) != 2 { + t.Fatalf("a decided head is admitted; held=%v kept=%d", held, len(kept)) + } + self := &mergeTrainPlan{lane: stageLaneSelf} + c.planDuplicateHolds(context.Background(), self, stageLaneSelf, "o", "r", "o/r", prs, hiveOnly) + if _, held := self.claimConflictOf(15783); !held { + t.Fatal("the undecided side stays held") + } + + c = &Engine{} + adoption := []*gh.PullRequest{claimPR(15783, "hive-app[bot]", "Closes #15773\n\nSupersedes #15793", t0), claimPR(15793, "clubanderson", "Fixes #15773", t0.Add(time.Hour))} + plan := &mergeTrainPlan{lane: stageLaneSelf} + c.planDuplicateHolds(context.Background(), plan, stageLaneSelf, "o", "r", "o/r", adoption, hiveOnly) + if plan.claimConflicts != nil { + t.Fatalf("an adoption pair is not a conflict: %+v", plan.claimConflicts) + } + + refs := []*gh.PullRequest{claimPR(15783, "hive-app[bot]", "Closes #15773", t0), claimPR(15793, "clubanderson", "Refs #15773", t0.Add(time.Hour))} + plan = &mergeTrainPlan{lane: stageLaneSelf} + c.planDuplicateHolds(context.Background(), plan, stageLaneSelf, "o", "r", "o/r", refs, hiveOnly) + if plan.claimConflicts != nil { + t.Fatalf("a Refs line is not a claim: %+v", plan.claimConflicts) + } + + // Two candidates of one lane stay with the one-PR-per-issue winner + // rule, which already sees them both. + plan = &mergeTrainPlan{lane: stageLaneSelf} + c.planDuplicateHolds(context.Background(), plan, stageLaneSelf, "o", "r", "o/r", prs, all) + if plan.claimConflicts != nil { + t.Fatalf("same-lane pair is the duplicate rule's: %+v", plan.claimConflicts) + } + if _, dup := plan.duplicateOf(15793); !dup { + t.Fatal("same-lane loser held as duplicate") + } +} + +// A targeted (webhook-nudged) pass hands the lane only the nudged PR; the +// gate still groups against the full list the legacy /pulls listing +// returned for the repo this pass, so a CI-green nudge for the human's PR +// alone does not slip past the undecided conflict with the hive's. +func TestPlanClaimConflictsSeesClaimantsOutsideNarrowedList(t *testing.T) { + t0 := time.Date(2026, 11, 3, 10, 25, 0, 0, time.UTC) + hive, human := claimPR(15783, "hive-app[bot]", "Closes #15773", t0), claimPR(15793, "clubanderson", "Fixes #15773", t0.Add(time.Hour)) + c := &Engine{} + c.rememberClaimants("o/r", []*gh.PullRequest{hive, human}) + plan := &mergeTrainPlan{lane: stageLaneTrusted} + kept := c.planDuplicateHolds(context.Background(), plan, stageLaneTrusted, "o", "r", "o/r", []*gh.PullRequest{human}, func(*gh.PullRequest) string { return "" }) + if h, held := plan.claimConflictOf(15793); !held || h.Other != 15783 || h.Issue != 15773 || len(kept) != 0 { + t.Fatalf("narrowed pass: hold=%+v held=%v kept=%d", h, held, len(kept)) + } + // Another repo's memory does not leak in. + plan = &mergeTrainPlan{lane: stageLaneTrusted} + c.planDuplicateHolds(context.Background(), plan, stageLaneTrusted, "o", "other", "o/other", []*gh.PullRequest{human}, func(*gh.PullRequest) string { return "" }) + if plan.claimConflicts != nil { + t.Fatalf("other repo held: %+v", plan.claimConflicts) + } +} diff --git a/src/pkg/github/automerge/automerge_merge_train_duplicate.go b/src/pkg/github/automerge/automerge_merge_train_duplicate.go index 23a53019b5..fa69496bd4 100644 --- a/src/pkg/github/automerge/automerge_merge_train_duplicate.go +++ b/src/pkg/github/automerge/automerge_merge_train_duplicate.go @@ -1,6 +1,8 @@ package automerge import ( + "context" + "slices" "sort" "strconv" "time" @@ -15,6 +17,10 @@ import ( // out of the train because another open PR fixes the same issue. const autoMergeReasonMergeTrainDuplicate = "merge-train-duplicate" +// autoMergeReasonMergeTrainClaimConflict buckets the candidates held by an +// undecided same-issue claim across lanes (hivecommons/hive#15810). +const autoMergeReasonMergeTrainClaimConflict = "merge-train-claim-conflict" + // mergeTrainDuplicateCandidate is one open PR declaring `Fixes #N`, as the // one-PR-per-issue rule reads it (hivecommons/hive#15395). type mergeTrainDuplicateCandidate struct { @@ -113,7 +119,8 @@ func mergeTrainDuplicateReason(h mergeTrainDuplicateHold) string { // planDuplicateHolds runs the one-PR-per-issue rule over the lane's // candidates before the trains are grouped: the held PRs leave the // candidate list and the plan remembers who each one yields to. -func (c *Engine) planDuplicateHolds(plan *mergeTrainPlan, lane, owner, repo, displayRepo string, prs []*gh.PullRequest, prefilter func(*gh.PullRequest) string) []*gh.PullRequest { +func (c *Engine) planDuplicateHolds(ctx context.Context, plan *mergeTrainPlan, lane, owner, repo, displayRepo string, prs []*gh.PullRequest, prefilter func(*gh.PullRequest) string) []*gh.PullRequest { + prs = c.planClaimConflicts(ctx, plan, owner, repo, displayRepo, prs, prefilter) byIssue := map[int][]mergeTrainDuplicateCandidate{} for _, pr := range prs { if pr == nil || pr.GetNumber() <= 0 || !mergeTrainCandidate(prefilter(pr)) { @@ -180,3 +187,149 @@ func mergeTrainDuplicateOf(reason string) int { } return train.Front } + +// mergeTrainClaimConflict is a lane candidate held because another open PR +// of the repository — one this lane does not evaluate, so the one-PR-per- +// issue winner above could not see it — claims the same issue and nobody +// has decided which one lands (hivecommons/hive#15810). +type mergeTrainClaimConflict struct { + Number, Other, Issue int +} + +// mergeTrainClaimConflictReason is the stage reason recorded on a candidate +// held by an undecided same-issue claim: +// merge-train:claim-conflict#:/0:0/0: +func mergeTrainClaimConflictReason(h mergeTrainClaimConflict) string { + return prstage.MergeTrain{State: prstage.MergeTrainStateClaimConflict, Front: h.Other, Position: h.Issue}.Reason() +} + +// mergeTrainAdoptionPair reports whether a or b declares that it supersedes +// the other (`Supersedes #N`): an adoption copy and its original are one +// change in flight, not two competing fixes. +func mergeTrainAdoptionPair(a, b *gh.PullRequest) bool { + return hgithub.PRSupersedes(a.GetBody(), b.GetNumber()) || hgithub.PRSupersedes(b.GetBody(), a.GetNumber()) +} + +// rememberClaimants keeps the full open-PR list the legacy /pulls listing +// returned for fullRepo this pass, before any event narrowing, so a +// targeted (webhook-nudged) pass still sees every claimant. +func (c *Engine) rememberClaimants(fullRepo string, prs []*gh.PullRequest) { + if c == nil { + return + } + c.claimantsMu.Lock() + defer c.claimantsMu.Unlock() + if c.claimants == nil { + c.claimants = map[string][]*gh.PullRequest{} + } + c.claimants[fullRepo] = slices.Clone(prs) +} + +// claimantsForConflicts is the set of open PRs the claim-conflict gate +// groups — the whole repository, never the lane's event-narrowed list: +// the forge-state snapshot when one is wired, else the full /pulls list +// the lane's openPullRequests just fetched for this repo (remembered +// before narrowing to targets); the lane's own list only when neither is +// available (a bare Engine in tests). +func (c *Engine) claimantsForConflicts(ctx context.Context, owner, repo string, prs []*gh.PullRequest) []*gh.PullRequest { + if c == nil { + return prs + } + if c.openPRs == nil { + c.claimantsMu.Lock() + all, ok := c.claimants[owner+"/"+repo] + c.claimantsMu.Unlock() + if ok && len(all) > 0 { + return all + } + return prs + } + all, skip, err := c.openPullRequests(ctx, owner, repo, nil) + if err != nil || skip != "" || len(all) == 0 { + return prs + } + return all +} + +// planClaimConflicts holds every lane candidate whose closing issue another +// open PR of the repository also claims, unless a human decision is +// recorded for the candidate's head. Candidates of this lane that claim +// the same issue are left to the one-PR-per-issue winner rule, which sees +// them both; the gate exists for the pair the lanes split — the hive's +// own PR in the self lane and a trusted human's PR in the trusted lane +// both marched toward merge for hivecommons/hive#15773 because each lane +// saw only its own (hivecommons/hive#15810). +func (c *Engine) planClaimConflicts(ctx context.Context, plan *mergeTrainPlan, owner, repo, displayRepo string, prs []*gh.PullRequest, prefilter func(*gh.PullRequest) string) []*gh.PullRequest { + candidate := map[int]bool{} + for _, pr := range prs { + if pr != nil && pr.GetNumber() > 0 && mergeTrainCandidate(prefilter(pr)) { + candidate[pr.GetNumber()] = true + } + } + if len(candidate) == 0 { + return prs + } + byIssue := map[int][]*gh.PullRequest{} + for _, pr := range c.claimantsForConflicts(ctx, owner, repo, prs) { + if pr == nil || pr.GetNumber() <= 0 || (pr.State != nil && pr.GetState() != "open") { + continue + } + for _, issue := range mergeTrainClosedIssues(pr, displayRepo) { + byIssue[issue] = append(byIssue[issue], pr) + } + } + held := map[int]mergeTrainClaimConflict{} + for _, pr := range prs { + n := pr.GetNumber() + if !candidate[n] { + continue + } + for _, issue := range mergeTrainClosedIssues(pr, displayRepo) { + for _, other := range byIssue[issue] { + o := other.GetNumber() + if o == n || candidate[o] || mergeTrainAdoptionPair(pr, other) { + continue + } + if _, ok := c.recordedDecisionFor(ctx, owner, repo, n, pr.GetBase().GetRef(), pr.GetHead().GetSHA()); ok { + c.info("merge train: same-issue claim conflict decided; admitting", "repo", displayRepo, "pr", n, "other", o, "issue", issue, "lane", plan.lane) + continue + } + held[n] = mergeTrainClaimConflict{Number: n, Other: o, Issue: issue} + c.info("same-issue claim conflict undecided: #"+strconv.Itoa(n)+" vs #"+strconv.Itoa(o), "repo", displayRepo, "pr", n, "other", o, "issue", issue, "lane", plan.lane) + break + } + if _, done := held[n]; done { + break + } + } + } + if len(held) == 0 { + return prs + } + plan.claimConflicts = held + kept := make([]*gh.PullRequest, 0, len(prs)) + for _, pr := range prs { + if _, h := held[pr.GetNumber()]; !h { + kept = append(kept, pr) + } + } + return kept +} + +// claimConflictOf reports the open PR this candidate is held behind by an +// undecided same-issue claim, false when it is not held this pass. +func (p *mergeTrainPlan) claimConflictOf(number int) (mergeTrainClaimConflict, bool) { + if p == nil || p.claimConflicts == nil { + return mergeTrainClaimConflict{}, false + } + h, ok := p.claimConflicts[number] + return h, ok +} + +// mergeTrainClaimConflictSkip records the hold and returns the stage reason. +func (c *Engine) mergeTrainClaimConflictSkip(plan *mergeTrainPlan, number int) string { + h, _ := plan.claimConflictOf(number) + reason := mergeTrainClaimConflictReason(h) + c.debug("automerge skip", "repo", plan.displayRepo, "pr", number, "reason", reason, "lane", plan.lane, "other", strconv.Itoa(h.Other)) + return reason +} diff --git a/src/pkg/github/automerge/automerge_merge_train_duplicate_test.go b/src/pkg/github/automerge/automerge_merge_train_duplicate_test.go index d9f9ff1f40..3f5f9901b7 100644 --- a/src/pkg/github/automerge/automerge_merge_train_duplicate_test.go +++ b/src/pkg/github/automerge/automerge_merge_train_duplicate_test.go @@ -86,7 +86,7 @@ func TestPlanDuplicateHoldsFiltersCandidates(t *testing.T) { pr(15411, "Fixes #15397", t0, "clean"), } plan := &mergeTrainPlan{lane: "self", displayRepo: "o/r"} - kept := c.planDuplicateHolds(plan, stageLaneSelf, "o", "r", "o/r", prs, func(*gh.PullRequest) string { return "" }) + kept := c.planDuplicateHolds(context.Background(), plan, stageLaneSelf, "o", "r", "o/r", prs, func(*gh.PullRequest) string { return "" }) if len(kept) != 3 || kept[0].GetNumber() != 15407 { t.Fatalf("kept = %v", kept) } @@ -100,17 +100,22 @@ func TestPlanDuplicateHoldsFiltersCandidates(t *testing.T) { if _, held := plan.duplicateOf(15410); held { t.Fatal("a Refs line is not a claim") } - // A prefilter refusal keeps the PR out of the rule entirely. + // A prefilter refusal keeps the PR out of the winner rule entirely — + // but it is still an open claimant, so the lane's remaining candidate + // for that issue is held as a claim conflict (hivecommons/hive#15810). plan2 := &mergeTrainPlan{} - kept = c.planDuplicateHolds(plan2, stageLaneSelf, "o", "r", "o/r", prs, func(p *gh.PullRequest) string { + kept = c.planDuplicateHolds(context.Background(), plan2, stageLaneSelf, "o", "r", "o/r", prs, func(p *gh.PullRequest) string { if p.GetNumber() == 15407 { return "label:hold" } return "" }) - if len(kept) != 4 || plan2.duplicates != nil { + if len(kept) != 3 || plan2.duplicates != nil { t.Fatalf("kept = %d dup=%v", len(kept), plan2.duplicates) } + if h, held := plan2.claimConflictOf(15402); !held || h.Other != 15407 || h.Issue != 15396 { + t.Fatalf("claim conflict = %+v held=%v", h, held) + } } // Through the planner: the held duplicate leaves the train (the train is diff --git a/src/pkg/github/automerge/automerge_sweep.go b/src/pkg/github/automerge/automerge_sweep.go index 17a2bd2f5a..1b4c5fe6bf 100644 --- a/src/pkg/github/automerge/automerge_sweep.go +++ b/src/pkg/github/automerge/automerge_sweep.go @@ -246,6 +246,13 @@ type Engine struct { inactiveQueueMu sync.Mutex inactiveQueueLast map[string]time.Time + // claimantsMu / claimants: the full open-PR list the legacy (no + // forge-state source) /pulls listing returned per owner/name this + // pass, kept before any event narrowing so the same-issue claim gate + // sees every claimant (hivecommons/hive#15810). + claimantsMu sync.Mutex + claimants map[string][]*gh.PullRequest + nativeMergeQueuePolicy func() NativeMergeQueuePolicy nativeQueueProbeMu sync.Mutex nativeQueueProbes map[string]nativeQueueProbe @@ -1163,6 +1170,13 @@ func (c *Engine) SweepSelfAuthoredAutoMerges(ctx context.Context, opts AutoMerge stage(c.mergeTrainDuplicateSkip(train, number), false, nil) continue } + if _, held := train.claimConflictOf(number); held { + result.Skipped++ + repoSkipped++ + repoSkipReasons[autoMergeReasonMergeTrainClaimConflict]++ + stage(c.mergeTrainClaimConflictSkip(train, number), false, nil) + continue + } if train.isSibling(number) { result.Skipped++ repoSkipped++ @@ -1398,6 +1412,11 @@ func (c *Engine) SweepTrustedAuthorAutoMerges(ctx context.Context, opts AutoMerg stage(c.mergeTrainDuplicateSkip(train, number), false, nil) continue } + if _, held := train.claimConflictOf(number); held { + result.Skipped++ + stage(c.mergeTrainClaimConflictSkip(train, number), false, nil) + continue + } if train.isSibling(number) { result.Skipped++ stage(c.mergeTrainSkip(train, number), false, nil) diff --git a/src/pkg/stageengine/derive_pr_classify.go b/src/pkg/stageengine/derive_pr_classify.go index abca3bc989..3a0b2bdc59 100644 --- a/src/pkg/stageengine/derive_pr_classify.go +++ b/src/pkg/stageengine/derive_pr_classify.go @@ -379,6 +379,12 @@ func ClassifyStage(o stageObservation) stageVerdict { if train.State == prstage.MergeTrainStateRebaseExhausted { return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} } + if train.State == prstage.MergeTrainStateClaimConflict { + // Another lane's open PR claims the same issue and nobody has + // decided which lands (hivecommons/hive#15810): a person's + // call, so 085 — not a turn in the queue. + return stageVerdict{Stage: stagelabels.NeedsDecision, Rank: stageRankOwned, Human: true} + } if train.State == prstage.MergeTrainStateDuplicateOf { // Two open PRs fix one issue and the queue kept the other // (hivecommons/hive#15469): this one goes back to its author diff --git a/src/pkg/stageengine/derive_pr_merge_train_test.go b/src/pkg/stageengine/derive_pr_merge_train_test.go index d6552d4dda..265460041d 100644 --- a/src/pkg/stageengine/derive_pr_merge_train_test.go +++ b/src/pkg/stageengine/derive_pr_merge_train_test.go @@ -24,6 +24,9 @@ func TestClassifyStageMergeTrainReasons(t *testing.T) { {"queued-behind", prstage.MergeTrain{State: prstage.MergeTrainStateQueuedBehind, Front: 15074, Position: 3, Size: 4, OverlapFiles: files}.Reason(), stagelabels.AwaitingMergeAdmission, false}, {"rebasing", prstage.MergeTrain{State: prstage.MergeTrainStateRebasing, Front: 15074, Position: 2, Size: 4, Attempt: 1, MaxAttempts: 2, OverlapFiles: files}.Reason(), stagelabels.AwaitingMergeAdmission, false}, {"exhausted", prstage.MergeTrain{State: prstage.MergeTrainStateRebaseExhausted, Front: 15074, Position: 2, Size: 4, Attempt: 2, MaxAttempts: 2, OverlapFiles: files}.Reason(), stagelabels.NeedsDecision, true}, + // hivecommons/hive#15810: an undecided same-issue claim across + // lanes is a person's call, not a turn in the queue. + {"claim-conflict", prstage.MergeTrain{State: prstage.MergeTrainStateClaimConflict, Front: 15793, Position: 15773}.Reason(), stagelabels.NeedsDecision, true}, } { v := ClassifyStage(stageObservation{Lane: lane, Reason: tc.reason, HeadSHA: goldenHead, Labels: []string{"needs-rebase"}}) if v.Stage != tc.want || v.Rank != stageRankOwned || v.Human != tc.human || v.Terminal { diff --git a/src/pkg/stageengine/prstage/merge_train.go b/src/pkg/stageengine/prstage/merge_train.go index dafbf08c0d..e948959893 100644 --- a/src/pkg/stageengine/prstage/merge_train.go +++ b/src/pkg/stageengine/prstage/merge_train.go @@ -43,7 +43,13 @@ const ( // the tracker reads "returned" with the gate pill "Duplicate of #N" // rather than "Approved; waiting its turn" (hivecommons/hive#15469). MergeTrainStateDuplicateOf = "duplicate-of" - MergeTrainReasonMaxFiles = 4 + // MergeTrainStateClaimConflict: two or more open PRs claim the same + // issue and no decision has been recorded on this one, so every lane + // refuses to admit it (hivecommons/hive#15810). Front is the other + // claimant, Position the issue. Unlike DuplicateOf the queue picked + // nobody: the PR parks at 085 until a person or the delegate decides. + MergeTrainStateClaimConflict = "claim-conflict" + MergeTrainReasonMaxFiles = 4 ) // MergeTrain is the decoded form of a merge-train reason. @@ -155,6 +161,12 @@ func ParseMergeTrain(reason string) (m MergeTrain, ok bool) { return m, true } +// ClaimConflictCaption is the chevron caption of a PR held on an undecided +// same-issue claim conflict: "held · duplicate of #B · needs decision". +func ClaimConflictCaption(other int) string { + return "held · duplicate of #" + strconv.Itoa(other) + " · needs decision" +} + // IsMergeTrainReason reports whether reason carries a merge-train position. func IsMergeTrainReason(reason string) bool { return strings.HasPrefix(strings.TrimSpace(reason), MergeTrainReasonPrefix) @@ -197,6 +209,8 @@ func (m MergeTrain) Sentence() string { issue = " for issue #" + strconv.Itoa(m.Position) } return "duplicate of #" + strconv.Itoa(m.Front) + issue + "; superseded by #" + strconv.Itoa(m.Front) + " — the merge queue carries one PR per issue; close it or let the delegate decide" + case MergeTrainStateClaimConflict: + return ClaimConflictCaption(m.Front) + " (both claim issue #" + strconv.Itoa(m.Position) + "; the merge queue admits neither until one is closed or approved)" } return "behind #" + strconv.Itoa(m.Front) + " in merge train (" + slot + files + ")" } diff --git a/src/pkg/stageengine/prstage/merge_train_test.go b/src/pkg/stageengine/prstage/merge_train_test.go index 1596934a0b..a39acba9ed 100644 --- a/src/pkg/stageengine/prstage/merge_train_test.go +++ b/src/pkg/stageengine/prstage/merge_train_test.go @@ -55,6 +55,26 @@ func TestMergeTrainSentence(t *testing.T) { } } +// hivecommons/hive#15810: the claim-conflict hold round-trips and reads as +// the tracker caption first. +func TestMergeTrainClaimConflictSentence(t *testing.T) { + m := MergeTrain{State: MergeTrainStateClaimConflict, Front: 15793, Position: 15773} + reason := m.Reason() + if reason != "merge-train:claim-conflict#15793:15773/0:0/0:" { + t.Fatalf("reason = %q", reason) + } + back, ok := ParseMergeTrain(reason) + if !ok || back.State != MergeTrainStateClaimConflict || back.Front != 15793 || back.Position != 15773 { + t.Fatalf("parse = %+v ok=%v", back, ok) + } + if got, want := back.Sentence(), "held · duplicate of #15793 · needs decision (both claim issue #15773; the merge queue admits neither until one is closed or approved)"; got != want { + t.Fatalf("Sentence() = %q, want %q", got, want) + } + if got := ClaimConflictCaption(15793); got != "held · duplicate of #15793 · needs decision" { + t.Fatalf("caption = %q", got) + } +} + func TestParseMergeTrainRejectsMalformed(t *testing.T) { for _, reason := range []string{ "held",