diff --git a/changelog.d/fixed-renovate-branch-updates.md b/changelog.d/fixed-renovate-branch-updates.md new file mode 100644 index 0000000000..80d3963178 --- /dev/null +++ b/changelog.d/fixed-renovate-branch-updates.md @@ -0,0 +1 @@ +- Auto-merge no longer merges the base branch into dependency-bot PRs (a `renovate/*` head branch or a `renovate[bot]`, `dependabot[bot]` or `mergeraptor[bot]` author) once they are out of hold: the lanes' update-branch, the current-base refresh, merge-forward, the merge train's sibling update and rebase requests, the trusted-author fixer rebase, adopted-PR recovery and `hive-merge --update-branch` all leave the rebase to the bot, and a behind bot branch holds as `behind` instead. A hive commit made Renovate stop rebasing the branch for good. diff --git a/src/cmd/hive/adopted_pr_fixer_test.go b/src/cmd/hive/adopted_pr_fixer_test.go index 4fdb6ca2a1..d2c990cbe5 100644 --- a/src/cmd/hive/adopted_pr_fixer_test.go +++ b/src/cmd/hive/adopted_pr_fixer_test.go @@ -233,6 +233,28 @@ func TestWriteMergeEligible_UntrustedConflictIsNotHiveRebaseWork(t *testing.T) { } } +// projectbluefin/utah#1097: a dirty Renovate branch is never the fixer's +// rebase work, even under a trusted author's identity — the bot resolves +// its own conflicts, and a hive push would stop it rebasing the branch for +// good. The same PR on an ordinary branch is (TestWriteMergeEligible_ +// TrustedAuthorConflictGetsRebaseKickWithLoopGuard). +func TestWriteMergeEligible_TrustedDependencyBotConflictIsNotHiveRebaseWork(t *testing.T) { + useMemoryRebaseAttempts(t) + cfg := trustedAuthorRebaseConfig() + pr := github.PullRequest{Number: 15091, Repo: "hive", Author: "clubanderson", HeadSHA: "fff6666", + HeadRef: "renovate/go-deps", HeadRepo: "hivecommons/hive", BaseRef: "v5", + Mergeable: github.MergeableNo, MergeableState: "dirty", CIStatus: "pending", Labels: []string{"needs-rebase"}} + _, failing := runWriteMergeEligible(t, []github.PullRequest{pr}, mergeEligibleInputs{org: "hivecommons", cfg: cfg}) + if len(failing) != 0 { + t.Fatalf("ci_failing = %+v, want nothing for a dependency bot's conflict", failing) + } + pr.HeadRef = "feat/x" + _, failing = runWriteMergeEligible(t, []github.PullRequest{pr}, mergeEligibleInputs{org: "hivecommons", cfg: cfg}) + if len(failing) != 1 || !failing[0].TrustedAuthor { + t.Fatalf("ci_failing = %+v, want the ordinary branch listed as trusted-author rebase work", failing) + } +} + // sweepRebaseLogged runs one writeMergeEligible sweep at now and returns the // ci-failing rows and the number of "routed to fixer for rebase" lines. func sweepRebaseLogged(t *testing.T, prs []github.PullRequest, now time.Time) ([]failingEntry, int) { diff --git a/src/cmd/hive/main_helpers.go b/src/cmd/hive/main_helpers.go index 2d592b4a6e..0ff529d6d5 100644 --- a/src/cmd/hive/main_helpers.go +++ b/src/cmd/hive/main_helpers.go @@ -328,7 +328,7 @@ func enforceHoldGuard( // pinned, and advancing a baseline that was never pinned would plant a wrong // one. // -// Branches a dependency bot owns (dependencyBotBranch) are skipped too: the +// Branches a dependency bot owns (github.DependencyBotBranch) are skipped too: the // bot rebases them itself, and a hive commit on the branch makes Renovate stop // rebasing it for good. func maintainHeldPRMergeability( @@ -354,7 +354,7 @@ func maintainHeldPRMergeability( if state != "behind" && state != "dirty" { continue } - if dependencyBotBranch(pr) { + if github.DependencyBotBranch(pr.HeadRef, pr.Author) { logger.Debug("hold guard: held PR branch belongs to a dependency bot; leaving the base sync to the bot", "repo", repo, "pr", pr.Number, "head_ref", pr.HeadRef, "author", pr.Author, "mergeable_state", state) continue @@ -448,17 +448,6 @@ func maintainHeldPRMergeability( } } -// dependencyBotBranch reports whether a PR's head branch belongs to a -// dependency bot that keeps it up to date itself: a `renovate/` head ref (any -// Renovate deployment, whatever App it runs as) or a dependencyBots author. -// Renovate refuses to rebase a branch once another identity has committed to -// it, so a hive merge-from-base on such a branch strands it behind its base -// for good (projectbluefin/utah#1097: three hive base merges, then "will not -// automatically rebase … does not recognize the last commit author"). -func dependencyBotBranch(pr github.PullRequest) bool { - return strings.HasPrefix(pr.HeadRef, "renovate/") || dependencyBots[pr.Author] -} - // intentConfigFromCfg maps config.IntentConfig onto the intent package's // classification config. Shared by writeIntentVerdicts (human merge lane) and // the App self-merge sweep's IntentGate (#6258) so both lanes classify with diff --git a/src/cmd/hive/main_sweeps.go b/src/cmd/hive/main_sweeps.go index d14ac2eb77..0ffdd1eda0 100644 --- a/src/cmd/hive/main_sweeps.go +++ b/src/cmd/hive/main_sweeps.go @@ -138,24 +138,14 @@ func redPRFixOwner(agent string) string { return review.DefaultFixerAgent } -// dependencyBots are forge bots whose PRs are dependency bumps, not hive fix -// attempts. They carry the "[bot]" suffix that otherwise marks a PR as -// agent-authored, but nothing in the hive opened them and no hive agent is -// iterating on them, so a red one is not a fix loop to break: escalating it -// only pages a human with "1 distinct fix attempts" about a crate bump that -// renovate will rebase on its own. Mirrors the hub's default contribute -// deny-authors list (config: hub.contribute_deny_authors). -var dependencyBots = map[string]bool{ - "renovate[bot]": true, - "dependabot[bot]": true, - "mergeraptor[bot]": true, -} - // isHiveAgentAuthor reports whether a PR author is one of OUR agents — the // configured ai_author, the App bot identity agents author as, or another -// bot account — excluding the dependency bots above. Shared by every fix-loop -// path (staleness clock, reaper, escalation sweep) so they classify PRs -// identically. +// bot account — excluding the dependency bots (github.IsDependencyBotAuthor): +// nothing in the hive opened those and no hive agent iterates on them, so a +// red one is not a fix loop to break — escalating it only pages a human with +// "1 distinct fix attempts" about a crate bump the bot rebases on its own. +// Shared by every fix-loop path (staleness clock, reaper, escalation sweep) +// so they classify PRs identically. func isHiveAgentAuthor(cfg *config.Config, author string) bool { if author == "" { return false @@ -166,7 +156,7 @@ func isHiveAgentAuthor(cfg *config.Config, author string) bool { if eff := cfg.EffectiveAIAuthor(); eff != "" && author == eff { return true } - return strings.HasSuffix(author, "[bot]") && !dependencyBots[author] + return strings.HasSuffix(author, "[bot]") && !github.IsDependencyBotAuthor(author) } // isIndependentCIControl reports whether a PR supplies human-authored evidence diff --git a/src/cmd/hive/merge_eligibility.go b/src/cmd/hive/merge_eligibility.go index 6883609482..3edfe19d76 100644 --- a/src/cmd/hive/merge_eligibility.go +++ b/src/cmd/hive/merge_eligibility.go @@ -853,8 +853,11 @@ const mergeTrainRebaseRequester = "merge-train" // would merge it unattended) whose head the hive can push to. Its rebase is // the hive's: the trusted-author lane never rebases, and the author is a // person who opened it through the hive and expects the hive to carry it. +// A dependency bot's branch never is: the bot resolves its own conflicts, +// and a fixer push would stop it rebasing the branch for good +// (github.DependencyBotBranch). func trustedAuthorRebasePR(cfg *config.Config, fullRepo string, pr github.PullRequest) bool { - if cfg == nil || github.ReachableAction(pr) != github.ReachableActionPush { + if cfg == nil || github.ReachableAction(pr) != github.ReachableActionPush || github.DependencyBotBranch(pr.HeadRef, pr.Author) { return false } policy := trustedAuthorPolicyFunc(cfg)() diff --git a/src/docs/hive-merge.md b/src/docs/hive-merge.md index 21c68f9668..eaa0e3af05 100644 --- a/src/docs/hive-merge.md +++ b/src/docs/hive-merge.md @@ -652,6 +652,21 @@ holds a behind head until the update lands. On current-base-gated repositories the separate preparation owner above refreshes the next admitted head, rather than refreshing every waiting sibling when a front merges. +**Dependency-bot branches are the bot's to rebase.** A PR whose head ref is +`renovate/*` or whose author is `renovate[bot]`, `dependabot[bot]` or +`mergeraptor[bot]` never gets a hive commit merging its base: no lane +update-branch, no current-base refresh, no merge-forward, no merge-train +update or rebase request, no trusted-author fixer rebase, no adopted-PR +recovery update and no `hive-merge --update-branch`. Renovate stops rebasing +a branch for good once another identity has committed to it +([projectbluefin/utah#1097](https://github.com/projectbluefin/utah/pull/1097)). +A behind bot branch holds as `behind` (logged once per head as `leaving the +base sync to the bot`) until the bot rebases it — Renovate does so on its own +when the repository requires up-to-date branches, and resolves conflicts on +its own. On a repository gated only by `require_current_base_default` (no +GitHub up-to-date rule, so no bot rebase is coming) such a head merges as +tested, like a head the App may not write. + The train's order is **readiness first**. Each pass the lane sorts the members by what it last saw of their heads: a head at the merge gate — green, approved, soaking or waiting on a sweep — leads; a head the lane has @@ -1154,7 +1169,8 @@ the head when it is behind (GitHub update-branch, which works on a fork the maintainers may edit) or re-runs the failed workflow jobs when it is current, at most once per (head, base tip) and three times per adoption, logged as `adopted PR recovery` with `reason=update-branch`, `rerun-failed-jobs` or -`skipped:`; an escalation already in place for that head is released +`skipped:` (`skipped:dependency-bot-branch` for a behind `renovate/*` or +dependency-bot branch, which is never updated); an escalation already in place for that head is released (hivecommons/hive#14500). An adoption with nothing the hive can push past the dwell — after that recovery was tried and the head is still red — goes to `stage/085-needs-decision` as @@ -1435,7 +1451,9 @@ lookup fails), the script prints an error naming the token-cache path and When set, the watcher syncs the PR branch with its base before attempting the merge (resolves the common "behind main" case). A failure to update the branch is not fatal — the merge attempt still proceeds and surfaces the real -blocker. +blocker. A dependency bot's branch (`renovate/*` head ref, or a Renovate, +Dependabot or Mergeraptor author) is never updated: the watcher logs the skip +and goes straight to the merge attempt, leaving the rebase to the bot. ## It is asynchronous, by design diff --git a/src/docs/operator-reference/README.md b/src/docs/operator-reference/README.md index 4a9e1cb756..cefc51c6a2 100644 --- a/src/docs/operator-reference/README.md +++ b/src/docs/operator-reference/README.md @@ -477,11 +477,11 @@ advanced into the merge path. | `auto_merge.human_merge_paths` | unset | Per-repo map of `owner/repo` to glob patterns (same syntax as `intent.guardrail_path_patterns`) for paths a person must merge, e.g. `Danathar/goodreads-mcp: [".claude/settings.json", ".claude/hooks/**"]`. Every App merge path honors it: the automerge sweep lanes (App self-merge, trusted-author, label-queued) and the agent merge-request relay refuse a PR that touches a listed path, add `hold`, and post one `` comment naming the path(s); a person must merge it. The sweep lanes skip that hold only for a PR admitted by `auto_merge.human_merge_pin_only` (#16266); the relay does not apply that exception yet. If the changed-file list cannot be fetched completely for a configured repo, the merge is withheld (#11038, #11039). | | `auto_merge.human_merge_title_prefixes` | `["⚠️", "⚠"]` | PR-title prefixes that mean "breaking change — owner merges" (U+26A0 with or without the VS16 selector by default, matched after trimming leading whitespace). One shared predicate, `automerge.RequiresHumanMerge(pr)`, runs where each lane computes eligibility — App self-merge, label-queued, trusted-author and contributor lanes, plus the refetch before a merge — so a matching PR is never merged by hive and never fronts a merge train, however green and however approved. The PR parks at stage 090 *Ready for human merge* with the `human merge` chip and reason *breaking change — owner merges*; the owner merges it with **Approve & merge as maintainer** or on GitHub. Hive posts one writeback-gated comment saying it will wait for a human. Set to `[]` to turn the title rule off. Added after a ⚠️-titled PR was auto-merged by the trusted-author lane while its owner was still deciding whether to ship it. | | `auto_merge.human_merge_labels` | `["needs-owner-merge"]` | Labels (case-insensitive, trimmed) that carry the same "a person merges this" meaning as the title prefixes above; either match is enough. Set to `[]` to turn the label rule off. | -| `auto_merge.require_current_base` | unset | Repo list (`owner/repo`) with an explicit **on** override for the current-base merge gate (Settings → Repos → "Merge only on current base"). On a gated repo the App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base ([#13634](https://github.com/hivecommons/hive/issues/13634), [#15335](https://github.com/hivecommons/hive/issues/15335)). Costs one compare call per merge candidate. Listing a repo here is also **strict**: a behind head the App cannot update (fork without maintainer edits, branch protection or a missing `contents: write`) is parked (`fork-not-editable` / `update-branch`) rather than merged as tested. Wins over `skip_current_base` and over the default. | +| `auto_merge.require_current_base` | unset | Repo list (`owner/repo`) with an explicit **on** override for the current-base merge gate (Settings → Repos → "Merge only on current base"). On a gated repo the App self-merge, trusted-author and contributor lanes only merge a head that contains the current base tip. A green head tested against an older base is updated with GitHub update-branch (a merge commit; no author commit is rewritten) and merges once CI is green on the new head, so a semantic conflict with work merged since turns that PR red instead of breaking the base ([#13634](https://github.com/hivecommons/hive/issues/13634), [#15335](https://github.com/hivecommons/hive/issues/15335)). Costs one compare call per merge candidate. Listing a repo here is also **strict**: a behind head the App cannot update (fork without maintainer edits, branch protection or a missing `contents: write`) is parked (`fork-not-editable` / `update-branch`) rather than merged as tested. A dependency bot's branch (`renovate/*` head ref, or a Renovate, Dependabot or Mergeraptor author) is never updated: on a listed repo, or when GitHub itself reports it `behind`, it holds as `behind` until the bot rebases it; a repo gated only by the default merges it as tested (projectbluefin/utah#1097). Wins over `skip_current_base` and over the default. | | `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` | **Settings → Auto-merge → Merge train → Conflict-aware merge train.** 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_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 and dependency-bot branches (`renovate/*` head ref, or a Renovate, Dependabot or Mergeraptor author) are never written. Attempted once per head (#13636). | +| `auto_merge.merge_train.enabled` | `true` | **Settings → Auto-merge → Merge train → Conflict-aware merge train.** 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 dependency bot's branch (`renovate/*` head ref, or a Renovate, Dependabot or Mergeraptor author) gets neither — behind or dirty, sibling or front, the bot rebases it itself (projectbluefin/utah#1097). 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`; `0` uses the default | **Settings → Auto-merge → Merge train → Rebase attempts per front.** 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. | @@ -689,7 +689,9 @@ session agent sat `dirty` with nobody kicked to fix it. Now: — the lane's update-branch runs and clears the label. - **`dirty` (real conflict):** the fixer router lists a trusted author's PR (`auto_merge.trusted_authors` enabled, repo allowed, author at the required - role, head pushable, no exclude label) as rebase work alongside the hive's + role, head pushable, no exclude label, not a dependency-bot branch — + `renovate/*` head ref or a Renovate, Dependabot or Mergeraptor author, which + the bot rebases itself) as rebase work alongside the hive's own and adopted PRs. The kick says *rebase-resolve (attempt n/2): `gh pr checkout`, `git rebase origin/`, resolve, re-run build and tests, `git push --force-with-lease` to the PR's diff --git a/src/pkg/github/automerge/automerge_adoption_recovery.go b/src/pkg/github/automerge/automerge_adoption_recovery.go index 62daa9627d..96a7cfd637 100644 --- a/src/pkg/github/automerge/automerge_adoption_recovery.go +++ b/src/pkg/github/automerge/automerge_adoption_recovery.go @@ -218,6 +218,14 @@ func (c *Engine) recoverStaleRedAdoption(ctx context.Context, store *stagelabels } behind := cmp.GetBehindBy() if behind > 0 { + if hgithub.DependencyBotBranch(obs.HeadRef, obs.Author) { + // The bot rebases its own branch; a hive merge commit would stop + // it doing so for good (projectbluefin/utah#1097). + out := adoptionRecoverySkipped("dependency-bot-branch") + c.info("adopted PR recovery", logArgs("reason", out.Reason, "base_sha", baseSHA, "behind_by", behind, "head_ref", obs.HeadRef, "author", obs.Author)...) + store.MarkAdoptionRecovery(key, obs.HeadSHA, baseSHA) + return out + } if c.requireCurrentBaseFor(obs.Owner + "/" + obs.Repo) { // Existing recovery evidence already proved that the new base // clears this failure. This admits repair, never a merge: the diff --git a/src/pkg/github/automerge/automerge_adoption_recovery_test.go b/src/pkg/github/automerge/automerge_adoption_recovery_test.go index 442997cda4..2d5e02c9c4 100644 --- a/src/pkg/github/automerge/automerge_adoption_recovery_test.go +++ b/src/pkg/github/automerge/automerge_adoption_recovery_test.go @@ -198,6 +198,46 @@ func TestAdoptedRecoveryPreparationWaitDoesNotConsumeAttempt(t *testing.T) { } } +// A dependency bot's adopted branch behind a base that clears its red check +// gets no update-branch (projectbluefin/utah#1097: Renovate stops rebasing a +// branch once the hive committed to it); the skip is recorded so the escape +// proceeds. An ordinary adopted head is still updated. +func TestAdoptedRecoveryLeavesDependencyBotBranchToTheBot(t *testing.T) { + cases := []struct { + name string + headRef string + author string + wantReason string + wantUpdates int + }{ + {name: "renovate head ref", headRef: "renovate/go-deps", author: "castrojo", wantReason: adoptionRecoverySkipPrefix + "dependency-bot-branch"}, + {name: "dependency bot author", headRef: "deps/bump", author: "renovate[bot]", wantReason: adoptionRecoverySkipPrefix + "dependency-bot-branch"}, + {name: "ordinary branch", headRef: "feature", author: "alice", wantReason: adoptionRecoveryUpdateBranch, wantUpdates: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h, key, done := recoveryHarness(t) + defer done() + h.adopt.compareBehind = 15 + h.adopt.baseChecks = map[string]string{"coverage": "success"} + rec, _ := h.e.stageStoreOrShared().Get(key) + out := h.e.recoverStaleRedAdoption(context.Background(), h.e.stageStoreOrShared(), key, stageObservation{ + Owner: "acme", Repo: "widget", Display: "acme/widget", Number: 7, + BaseRef: "v5", HeadSHA: "aaa", HeadRef: tc.headRef, Author: tc.author, Lane: stageLaneContributor, Reason: recoveryReason, + }, rec) + if out.Reason != tc.wantReason || out.Attempted != (tc.wantUpdates > 0) { + t.Fatalf("recovery = %+v, want reason %q", out, tc.wantReason) + } + if got := len(h.adopt.branchUpdates); got != tc.wantUpdates { + t.Fatalf("branch updates=%v, want %d", h.adopt.branchUpdates, tc.wantUpdates) + } + if rec, _ = h.e.stageStoreOrShared().Get(key); rec.AdoptRecoveryAttempt != "aaa@base1" { + t.Fatalf("recovery attempt=%q, want it recorded so the escape proceeds", rec.AdoptRecoveryAttempt) + } + }) + } +} + // The same head stays red after the re-run: one attempt per (head, base), // then the escalation runs; a new hive head starts over. func TestAdoptedStaleRedRecoveryEscalatesAfterOneAttempt(t *testing.T) { diff --git a/src/pkg/github/automerge/automerge_base_preparation_races_test.go b/src/pkg/github/automerge/automerge_base_preparation_races_test.go index 9a0ea05180..b91bd19f33 100644 --- a/src/pkg/github/automerge/automerge_base_preparation_races_test.go +++ b/src/pkg/github/automerge/automerge_base_preparation_races_test.go @@ -12,7 +12,7 @@ func TestBasePreparationProvenanceForEveryAdmittingLane(t *testing.T) { t.Run(lane, func(t *testing.T) { api, srv := newPreparationAPI(t) c := preparationEngine(srv.URL, NewBasePreparationStore("")) - if ev, _, _, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 1, "main", "head1", true, "behind", false, lane); err != nil || !ev.BranchUpdated { + if ev, _, _, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 1, "main", "head1", true, "behind", nil, lane); err != nil || !ev.BranchUpdated { t.Fatalf("admission: %+v %v", ev, err) } for _, other := range []string{stageLaneSelf, stageLaneTrusted, stageLaneContributor} { @@ -40,7 +40,7 @@ func TestBasePreparationPushBeforeRefreshYieldsUnstartedOwner(t *testing.T) { } api.prs[1].Head.SHA = gh.Ptr("author-push") api.pending["author-push"] = true - _, reason, err := c.updateBranchAndSkip(context.Background(), "acme/widget", "acme", "widget", 1, "head1", currentBaseUpdateReason, false) + _, reason, err := c.updateBranchAndSkip(context.Background(), "acme/widget", "acme", "widget", 1, "head1", currentBaseUpdateReason, nil) if err != nil || reason != basePreparationPrefix+"snapshot-changed" { t.Fatalf("stale refresh snapshot: %q %v", reason, err) } diff --git a/src/pkg/github/automerge/automerge_base_preparation_test.go b/src/pkg/github/automerge/automerge_base_preparation_test.go index fc30dd3538..cd88d21ba4 100644 --- a/src/pkg/github/automerge/automerge_base_preparation_test.go +++ b/src/pkg/github/automerge/automerge_base_preparation_test.go @@ -218,7 +218,7 @@ func preparationEngine(url string, store *BasePreparationStore) *Engine { } func preparationGate(c *Engine, n int, base, head string) (AutoMergeSweepEvent, string, bool, error) { - return c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", n, base, head, true, "behind", false) + return c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", n, base, head, true, "behind", nil) } func TestBasePreparationStickyAcrossLanesSweepsAndRestart(t *testing.T) { diff --git a/src/pkg/github/automerge/automerge_contributor_lane.go b/src/pkg/github/automerge/automerge_contributor_lane.go index 6029337342..80338d77ec 100644 --- a/src/pkg/github/automerge/automerge_contributor_lane.go +++ b/src/pkg/github/automerge/automerge_contributor_lane.go @@ -1394,7 +1394,7 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own if relay { return eval, "behind", nil } - _, reason, err := c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "behind", c.isForkPR(pr)) + _, reason, err := c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "behind", pr) return eval, reason, err } if mergeableState == "dirty" || mergeableState == "conflicting" { @@ -1466,7 +1466,7 @@ func (c *Engine) evaluateContributorLanePR(ctx context.Context, displayRepo, own // approved head is worth an update-branch commit; a relay evaluation // never updates the branch. if c.requireCurrentBaseFor(owner+"/"+repo) && !queueSkipsBase() { - if _, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, headSHA, !relay, "behind", c.isForkPR(pr), stageLaneContributor); stop { + if _, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, headSHA, !relay, "behind", pr, stageLaneContributor); stop { return eval, reason, err } } @@ -1532,7 +1532,7 @@ func (c *Engine) trySweepContributorLanePR(ctx context.Context, displayRepo, own }) if err != nil { if c.requiredChecksExpected(attempt, err) { - return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "required-checks-expected", c.isForkPR(eval.pr)) + return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "required-checks-expected", eval.pr) } if reason := c.workflowFenceMergeUnauthorized(ctx, displayRepo, owner, repo, eval, err); reason != "" { return AutoMergeSweepEvent{}, reason, nil diff --git a/src/pkg/github/automerge/automerge_current_base.go b/src/pkg/github/automerge/automerge_current_base.go index 9011a66191..f8f8de833e 100644 --- a/src/pkg/github/automerge/automerge_current_base.go +++ b/src/pkg/github/automerge/automerge_current_base.go @@ -85,11 +85,13 @@ func (c *Engine) warnCurrentBaseFallbackOnce(displayRepo string, number int, rea // repo opts in, the head must contain the current base tip: if it does not, // the branch is updated (a merge commit, no human commit rewritten) and the // merge waits for CI on the new head. holdReason is returned instead when -// the caller may not update the branch this tick. +// the caller may not update the branch this tick. pr is the PR payload the +// lane evaluated (fork head, dependency-bot branch); nil reads as a +// same-repo, non-bot head. // // stop is false when the merge may proceed; otherwise the caller returns the // event, reason and error as-is. -func (c *Engine) currentBaseGate(ctx context.Context, displayRepo, owner, repo string, number int, baseBranch, headSHA string, branchUpdateAllowed bool, holdReason string, fork bool, admissionLane ...string) (AutoMergeSweepEvent, string, bool, error) { +func (c *Engine) currentBaseGate(ctx context.Context, displayRepo, owner, repo string, number int, baseBranch, headSHA string, branchUpdateAllowed bool, holdReason string, pr *gh.PullRequest, admissionLane ...string) (AutoMergeSweepEvent, string, bool, error) { if combined, err := integrationCombinedBaseCheck(ctx, owner+"/"+repo, baseBranch, number, headSHA); combined { if err != nil { return AutoMergeSweepEvent{}, autoMergeReasonCurrentBaseCheck, true, err @@ -115,6 +117,22 @@ func (c *Engine) currentBaseGate(ctx context.Context, displayRepo, owner, repo s if !branchUpdateAllowed { return AutoMergeSweepEvent{}, holdReason, true, nil } + if c.leaveBaseSyncToDependencyBot(displayRepo, owner, repo, pr, "current-base") { + // The bot keeps its own branch current, and a hive merge commit + // would stop it doing so for good. The head holds as "behind" until + // the bot rebases it when the repo is explicitly listed in + // auto_merge.require_current_base, or when GitHub itself requires + // up-to-date branches (mergeable_state "behind": GitHub would refuse + // the merge, and Renovate rebases behind branches under that rule). + // A repo gated only by the hive-wide default merges it as tested, + // like a head the App may not write: no bot rebases a merely stale + // branch there. + if c.requireCurrentBaseStrictFor(owner+"/"+repo) || strings.EqualFold(pr.GetMergeableState(), "behind") { + return AutoMergeSweepEvent{}, "behind", true, nil + } + c.warnCurrentBaseFallbackOnce(displayRepo, number, "dependency-bot-branch", nil) + return AutoMergeSweepEvent{}, "", false, nil + } lane := stageLaneSelf if len(admissionLane) > 0 { lane = admissionLane[0] @@ -122,7 +140,7 @@ func (c *Engine) currentBaseGate(ctx context.Context, displayRepo, owner, repo s if reason, err := c.admitBasePreparation(ctx, owner, repo, baseBranch, number, headSHA, lane, false); reason != "" || err != nil { return AutoMergeSweepEvent{}, nonEmpty(reason, basePreparationPrefix+"state-unavailable"), true, err } - event, reason, err := c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, currentBaseUpdateReason, fork) + event, reason, err := c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, currentBaseUpdateReason, pr) if event.BranchUpdated { c.info("automerge head is behind the current base; updating before merge", "repo", displayRepo, "pr", number, "base", baseBranch, "behind_by", cmp.GetBehindBy()) } diff --git a/src/pkg/github/automerge/automerge_current_base_test.go b/src/pkg/github/automerge/automerge_current_base_test.go index 43c83a00bb..5920edc6e5 100644 --- a/src/pkg/github/automerge/automerge_current_base_test.go +++ b/src/pkg/github/automerge/automerge_current_base_test.go @@ -10,6 +10,8 @@ import ( "sync" "testing" "time" + + gh "github.com/google/go-github/v72/github" ) func TestCurrentBaseGate(t *testing.T) { @@ -72,7 +74,7 @@ func TestCurrentBaseGate(t *testing.T) { c.requireCurrentBase = func(repo string) bool { return tc.optIn && strings.EqualFold(repo, "acme/widget") } - event, reason, stop, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 7, "main", head, tc.updateAllowed, "behind", false) + event, reason, stop, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 7, "main", head, tc.updateAllowed, "behind", nil) if stop != tc.wantStop || reason != tc.wantReason { t.Fatalf("stop, reason = %v, %q; want %v, %q", stop, reason, tc.wantStop, tc.wantReason) } @@ -141,7 +143,7 @@ func TestCurrentBaseGateUpdateUnavailableFallback(t *testing.T) { c.requireCurrentBase = func(string) bool { return true } c.requireCurrentBaseStrict = func(string) bool { return tc.strict } for tick := 0; tick < 2; tick++ { - _, reason, stop, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 7, "main", head, true, "behind", tc.fork) + _, reason, stop, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 7, "main", head, true, "behind", currentBaseTestPR(tc.fork, "feature", "alice", "behind")) if err != nil { t.Fatalf("tick %d: err = %v", tick, err) } @@ -156,6 +158,145 @@ func TestCurrentBaseGateUpdateUnavailableFallback(t *testing.T) { } } +// currentBaseTestPR is the lane's PR payload for currentBaseGate: head ref, +// author and mergeable state, on a fork head or a same-repo branch. +func currentBaseTestPR(fork bool, headRef, author, mergeableState string) *gh.PullRequest { + headRepo := "acme/widget" + if fork { + headRepo = "someone/widget" + } + return &gh.PullRequest{ + Number: gh.Ptr(7), + User: &gh.User{Login: gh.Ptr(author)}, + MergeableState: gh.Ptr(mergeableState), + Head: &gh.PullRequestBranch{Ref: gh.Ptr(headRef), SHA: gh.Ptr("sha-head"), Repo: &gh.Repository{FullName: gh.Ptr(headRepo)}}, + Base: &gh.PullRequestBranch{Ref: gh.Ptr("main"), Repo: &gh.Repository{FullName: gh.Ptr("acme/widget")}}, + } +} + +// TestCurrentBaseGateLeavesDependencyBotBranchToTheBot pins +// projectbluefin/utah#1097: a behind Renovate branch is never +// update-branched (Renovate stops rebasing a branch once another identity +// committed to it). A repo listed in auto_merge.require_current_base, or a +// head GitHub itself reports behind under its up-to-date rule, holds as +// "behind" for the bot to rebase; a repo gated only by the hive-wide default +// merges it as tested. An ordinary PR on the same repo is still updated. +func TestCurrentBaseGateLeavesDependencyBotBranchToTheBot(t *testing.T) { + const head = "sha-head" + cases := []struct { + name string + pr *gh.PullRequest + strict bool + wantStop bool + wantReason string + wantUpdates int + }{ + {name: "renovate bot on a listed repo holds", pr: currentBaseTestPR(false, "renovate/actions-checkout-5.x", "renovate[bot]", "clean"), strict: true, wantStop: true, wantReason: "behind"}, + {name: "renovate head ref under another account holds", pr: currentBaseTestPR(false, "renovate/go-deps", "castrojo", "clean"), strict: true, wantStop: true, wantReason: "behind"}, + {name: "dependabot author holds", pr: currentBaseTestPR(false, "dependabot/npm_and_yarn/x", "dependabot[bot]", "clean"), strict: true, wantStop: true, wantReason: "behind"}, + {name: "github up-to-date rule holds on a default-gated repo", pr: currentBaseTestPR(false, "renovate/x", "renovate[bot]", "behind"), wantStop: true, wantReason: "behind"}, + {name: "default-gated repo merges as tested", pr: currentBaseTestPR(false, "renovate/x", "renovate[bot]", "clean")}, + {name: "ordinary PR is still updated", pr: currentBaseTestPR(false, "feature", "alice", "behind"), strict: true, wantStop: true, wantReason: basePreparationReady, wantUpdates: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var mu sync.Mutex + updates := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7": + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "head": map[string]string{"sha": head}, "base": map[string]string{"ref": "main", "sha": "base1"}}) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/compare/main..."+head: + _ = json.NewEncoder(w).Encode(map[string]any{"behind_by": 2, "ahead_by": 1}) + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/branches/main": + _ = json.NewEncoder(w).Encode(map[string]any{"name": "main", "commit": map[string]string{"sha": "base1"}}) + case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/update-branch": + updates++ + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"message":"Updating pull request branch."}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + c := newAutoMergeSweepClient(srv.URL) + c.requireCurrentBase = func(string) bool { return true } + c.requireCurrentBaseStrict = func(string) bool { return tc.strict } + event, reason, stop, err := c.currentBaseGate(context.Background(), "acme/widget", "acme", "widget", 7, "main", head, true, "behind", tc.pr) + if err != nil { + t.Fatalf("err = %v", err) + } + if stop != tc.wantStop || reason != tc.wantReason { + t.Fatalf("stop, reason = %v, %q; want %v, %q", stop, reason, tc.wantStop, tc.wantReason) + } + mu.Lock() + defer mu.Unlock() + if updates != tc.wantUpdates || event.BranchUpdated != (tc.wantUpdates > 0) { + t.Fatalf("update-branch calls = %d (BranchUpdated %v), want %d", updates, event.BranchUpdated, tc.wantUpdates) + } + }) + } +} + +// TestUpdateBranchAndSkipLeavesDependencyBotBranchToTheBot pins the lanes' +// GitHub-reported "behind" and required-checks-expected path: a dependency +// bot's branch holds as "behind" with no update-branch call, and an ordinary +// PR is still updated. +func TestUpdateBranchAndSkipLeavesDependencyBotBranchToTheBot(t *testing.T) { + const head = "sha-head" + cases := []struct { + name string + pr *gh.PullRequest + wantReason string + wantUpdates int + }{ + {name: "renovate bot", pr: currentBaseTestPR(false, "renovate/actions-checkout-5.x", "renovate[bot]", "behind"), wantReason: "behind"}, + {name: "mergeraptor bot", pr: currentBaseTestPR(false, "refresh-buildroot", "mergeraptor[bot]", "behind"), wantReason: "behind"}, + {name: "renovate head ref", pr: currentBaseTestPR(false, "renovate/go-deps", "castrojo", "behind"), wantReason: "behind"}, + {name: "ordinary PR", pr: currentBaseTestPR(false, "feature", "alice", "behind"), wantReason: "check-pending", wantUpdates: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var mu sync.Mutex + updates := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + switch { + case r.Method == http.MethodGet && r.URL.Path == "/repos/acme/widget/pulls/7": + _ = json.NewEncoder(w).Encode(map[string]any{"number": 7, "state": "open", "head": map[string]string{"sha": head}, "base": map[string]string{"ref": "main", "sha": "base1"}}) + case r.Method == http.MethodPut && r.URL.Path == "/repos/acme/widget/pulls/7/update-branch": + updates++ + w.WriteHeader(http.StatusAccepted) + _, _ = w.Write([]byte(`{"message":"Updating pull request branch."}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + + c := newAutoMergeSweepClient(srv.URL) + event, reason, err := c.updateBranchAndSkip(context.Background(), "acme/widget", "acme", "widget", 7, head, "behind", tc.pr) + if err != nil { + t.Fatalf("err = %v", err) + } + if reason != tc.wantReason { + t.Fatalf("reason = %q, want %q", reason, tc.wantReason) + } + mu.Lock() + defer mu.Unlock() + if updates != tc.wantUpdates || event.BranchUpdated != (tc.wantUpdates > 0) { + t.Fatalf("update-branch calls = %d (BranchUpdated %v), want %d", updates, event.BranchUpdated, tc.wantUpdates) + } + }) + } +} + func TestCurrentBaseGateNilEngine(t *testing.T) { var c *Engine if c.requireCurrentBaseFor("acme/widget") { diff --git a/src/pkg/github/automerge/automerge_merge_forward.go b/src/pkg/github/automerge/automerge_merge_forward.go index 3cdc7293df..05bfc2fde8 100644 --- a/src/pkg/github/automerge/automerge_merge_forward.go +++ b/src/pkg/github/automerge/automerge_merge_forward.go @@ -55,7 +55,8 @@ func (c *Engine) markMergeForwardAttempted(owner, repo string, number int, headS // as a new App-authored, signed-off merge commit (the GitHub merges API; no // human commit is rewritten) and the merge waits for CI on the new head. A // real conflict leaves the branch untouched and posts one note naming the -// files both sides changed. Every other case keeps the "conflicting" hold. +// files both sides changed. Every other case — a dependency bot's branch +// included, which the bot rebases itself — keeps the "conflicting" hold. // It is attempted once per head SHA. func (c *Engine) mergeForwardOrConflict(ctx context.Context, displayRepo, owner, repo string, pr *gh.PullRequest, number int) (AutoMergeSweepEvent, string, error) { if !c.mergeForwardTrustedHumanFor(owner+"/"+repo) || pr == nil || c.isForkPR(pr) { @@ -64,6 +65,9 @@ func (c *Engine) mergeForwardOrConflict(ctx context.Context, displayRepo, owner, if authorkind.FromLabels(labelNames(pr.Labels), c.stagePolicy().AuthorKindLabels) != authorkind.Human { return AutoMergeSweepEvent{}, "conflicting", nil } + if c.leaveBaseSyncToDependencyBot(displayRepo, owner, repo, pr, "merge-forward") { + return AutoMergeSweepEvent{}, "conflicting", nil + } headRef := strings.TrimSpace(pr.GetHead().GetRef()) baseRef := strings.TrimSpace(pr.GetBase().GetRef()) headSHA := strings.TrimSpace(pr.GetHead().GetSHA()) diff --git a/src/pkg/github/automerge/automerge_merge_forward_test.go b/src/pkg/github/automerge/automerge_merge_forward_test.go index b087ec1a58..92062f6167 100644 --- a/src/pkg/github/automerge/automerge_merge_forward_test.go +++ b/src/pkg/github/automerge/automerge_merge_forward_test.go @@ -33,6 +33,14 @@ func mergeForwardPR(fork bool, labels ...string) *gh.PullRequest { return pr } +// renovateMergeForwardPR is a same-repo `author/human` PR on a Renovate +// branch (Renovate run under a person's token): the head ref alone marks it. +func renovateMergeForwardPR() *gh.PullRequest { + pr := mergeForwardPR(false, "author/human") + pr.Head.Ref = gh.Ptr("renovate/go-deps") + return pr +} + type mergeForwardAPI struct { mu sync.Mutex mergeStatus int @@ -113,6 +121,7 @@ func TestMergeForwardOrConflict(t *testing.T) { {name: "unknown author keeps the hold", optIn: true, pr: mergeForwardPR(false), wantReason: "conflicting"}, {name: "nil pr", optIn: true, wantReason: "conflicting"}, {name: "clean merge pushes a merge commit", optIn: true, pr: mergeForwardPR(false, "author/human"), mergeStatus: http.StatusCreated, wantReason: "check-pending", wantUpdated: true, wantMerges: 1}, + {name: "dependency bot branch is left to the bot", optIn: true, pr: renovateMergeForwardPR(), mergeStatus: http.StatusCreated, wantReason: "conflicting"}, {name: "nothing to merge waits for github", optIn: true, pr: mergeForwardPR(false, "author/human"), mergeStatus: http.StatusNoContent, wantReason: "check-pending", wantMerges: 1}, {name: "conflict posts the files note", optIn: true, pr: mergeForwardPR(false, "author/human"), mergeStatus: http.StatusConflict, wantReason: "conflicting", wantMerges: 1, wantComment: true, wantFiles: true}, {name: "conflict note without files when compare fails", optIn: true, pr: mergeForwardPR(false, "author/human"), mergeStatus: http.StatusConflict, compareStatus: http.StatusInternalServerError, wantReason: "conflicting", wantMerges: 1, wantComment: true}, diff --git a/src/pkg/github/automerge/automerge_merge_train.go b/src/pkg/github/automerge/automerge_merge_train.go index 161648eb29..1323bf2ecc 100644 --- a/src/pkg/github/automerge/automerge_merge_train.go +++ b/src/pkg/github/automerge/automerge_merge_train.go @@ -845,7 +845,9 @@ func mergeTrainFrontReason(g *mergeTrainGroup, state string, attempt, maxAttempt // a conflicting front is sent to the rebase resolver (bounded by the loop // guard) and parked as rebasing; past the guard it parks for a person. // handled=false hands a clean or behind front to the lane's normal path, -// and a dirty one too when no resolver is wired. +// and a dirty one too when no resolver is wired or the branch belongs to a +// dependency bot (the bot resolves its own conflicts; a hive rebase push +// would stop it rebasing the branch). func (c *Engine) mergeTrainFront(ctx context.Context, plan *mergeTrainPlan, pr *gh.PullRequest) (reason string, handled bool) { if plan == nil || pr == nil { return "", false @@ -859,6 +861,9 @@ func (c *Engine) mergeTrainFront(ctx context.Context, plan *mergeTrainPlan, pr * if !mergeTrainDirty(m.MergeableState) { return "", false } + if c.leaveBaseSyncToDependencyBot(plan.displayRepo, plan.owner, plan.repo, pr, "merge-train-rebase") { + return "", false + } policy := c.mergeTrainPolicyNow() behind := c.mergeTrainLastFront(plan.owner, plan.repo, g.Base) attempts := c.mergeTrainAttempts(plan.owner, plan.repo, number, behind) @@ -884,7 +889,8 @@ func (c *Engine) mergeTrainFront(ctx context.Context, plan *mergeTrainPlan, pr * // mergeTrainAfterFrontMerge runs right after a train's front merged: every // sibling is read back and, as GitHub now reports it, updated (behind) or // sent for a rebase (dirty, within the loop guard). A sibling GitHub has -// not re-evaluated yet (unknown) is left to the next pass, which replans. +// not re-evaluated yet (unknown) is left to the next pass, which replans, +// and a dependency bot's branch is left to the bot. func (c *Engine) mergeTrainAfterFrontMerge(ctx context.Context, plan *mergeTrainPlan, front int) { if plan == nil { return @@ -908,6 +914,9 @@ func (c *Engine) mergeTrainAfterFrontMerge(ctx context.Context, plan *mergeTrain } state := strings.ToLower(strings.TrimSpace(live.GetMergeableState())) head := live.GetHead().GetSHA() + if (state == "behind" || mergeTrainDirty(state)) && c.leaveBaseSyncToDependencyBot(plan.displayRepo, plan.owner, plan.repo, live, "merge-train") { + continue + } switch { case state == "behind": if c.requireCurrentBaseFor(plan.owner + "/" + plan.repo) { diff --git a/src/pkg/github/automerge/automerge_merge_train_test.go b/src/pkg/github/automerge/automerge_merge_train_test.go index dd68e91a19..8b4eaa1c0c 100644 --- a/src/pkg/github/automerge/automerge_merge_train_test.go +++ b/src/pkg/github/automerge/automerge_merge_train_test.go @@ -206,6 +206,7 @@ type mergeTrainAPI struct { files map[int][]string state map[int]string heads map[int]string + refs map[int]string closed map[int]bool updates []int gets int @@ -238,8 +239,12 @@ func newMergeTrainServer(t *testing.T, api *mergeTrainAPI) *httptest.Server { if head == "" { head = "sha" + strconv.Itoa(n) } + ref := api.refs[n] + if ref == "" { + ref = "feat/" + strconv.Itoa(n) + } _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": state, "mergeable_state": api.state[n], - "head": map[string]any{"sha": head, "ref": "feat/" + strconv.Itoa(n), "repo": map[string]any{"full_name": "acme/widget"}}, + "head": map[string]any{"sha": head, "ref": ref, "repo": map[string]any{"full_name": "acme/widget"}}, "base": map[string]any{"ref": "v5", "repo": map[string]any{"full_name": "acme/widget"}}}) case r.Method == http.MethodPut && len(parts) == 2 && parts[1] == "update-branch": api.updates = append(api.updates, n) @@ -413,6 +418,89 @@ func TestMergeTrainAfterFrontMergeBehindAndDirty(t *testing.T) { } } +// TestMergeTrainLeavesDependencyBotBranchesToTheBot pins +// projectbluefin/utah#1097 on the merge train: once the front merges, a +// Renovate sibling — behind or dirty — gets neither update-branch nor a +// fixer rebase request, and a dirty Renovate front falls through to the +// lane's conflicting path without a rebase request. Ordinary siblings are +// still updated and rebased. +func TestMergeTrainLeavesDependencyBotBranchesToTheBot(t *testing.T) { + t0 := time.Date(2026, 11, 5, 9, 0, 0, 0, time.UTC) + api := &mergeTrainAPI{ + files: map[int][]string{40: {"a.go"}, 41: {"a.go"}, 42: {"a.go"}, 43: {"a.go"}, 44: {"a.go"}}, + state: map[int]string{40: "clean", 41: "clean", 42: "clean", 43: "clean", 44: "clean"}, + refs: map[int]string{42: "renovate/actions-checkout-5.x", 43: "renovate/go-deps"}, + } + srv := newMergeTrainServer(t, api) + defer srv.Close() + var mu sync.Mutex + var requests []RebaseRequest + resolver := RebaseResolverFunc(func(_ context.Context, req RebaseRequest) error { + mu.Lock() + defer mu.Unlock() + requests = append(requests, req) + return nil + }) + c, logs := newMergeTrainEngine(t, srv.URL, DefaultMergeTrainPolicy, resolver) + prs := []*gh.PullRequest{mtPR(40, t0, ""), mtPR(41, t0.Add(time.Minute), ""), mtPR(42, t0.Add(2*time.Minute), ""), mtPR(43, t0.Add(3*time.Minute), ""), mtPR(44, t0.Add(4*time.Minute), "")} + mtReady(c, "self", prs...) + plan := c.planMergeTrains(context.Background(), "self", "acme/widget", "acme", "widget", prs, func(*gh.PullRequest) string { return "" }) + if !plan.isFront(40) { + t.Fatalf("front = %v", plan.groups) + } + // The front merged: #41 (ordinary) and #42 (Renovate) are behind, #43 + // (Renovate) and #44 (ordinary) are dirty. + api.mu.Lock() + api.state[41], api.state[42], api.state[43], api.state[44] = "behind", "behind", "dirty", "dirty" + api.mu.Unlock() + c.mergeTrainAfterFrontMerge(context.Background(), plan, 40) + api.mu.Lock() + updates := append([]int(nil), api.updates...) + api.mu.Unlock() + if !reflect.DeepEqual(updates, []int{41}) { + t.Fatalf("update-branch on %v, want only the ordinary #41", updates) + } + mu.Lock() + got := append([]RebaseRequest(nil), requests...) + mu.Unlock() + if len(got) != 1 || got[0].Number != 44 { + t.Fatalf("rebase requests = %+v, want only the ordinary #44", got) + } + if !strings.Contains(logs.String(), "leaving the base sync to the bot") || !strings.Contains(logs.String(), "head_ref=renovate/go-deps") { + t.Fatalf("missing dependency-bot skip log\n%s", logs.String()) + } + + // A dirty Renovate front still riding the train under repair (an + // episode opened before this guard): no rebase request, the lane's + // conflicting path takes it. + frontAPI := &mergeTrainAPI{ + files: map[int][]string{50: {"a.go"}, 51: {"a.go"}}, + state: map[int]string{50: "dirty", 51: "dirty"}, + refs: map[int]string{50: "renovate/go-deps"}, + } + frontSrv := newMergeTrainServer(t, frontAPI) + defer frontSrv.Close() + fc, _ := newMergeTrainEngine(t, frontSrv.URL, MergeTrainPolicy{Enabled: true, MaxRebaseAttempts: 2}, resolver) + fronts := []*gh.PullRequest{mtPR(50, t0, ""), mtPR(51, t0.Add(time.Minute), "")} + fronts[0].Head.Ref = gh.Ptr("renovate/go-deps") + mtReady(fc, "self", fronts...) + fc.noteMergeTrainFrontMerged("acme", "widget", "v5", 49) + fc.bumpMergeTrainAttempts("acme", "widget", 50, 49) + fc.bumpMergeTrainAttempts("acme", "widget", 51, 49) + frontPlan := plan0(fc, fronts) + if !frontPlan.isFront(50) { + t.Fatalf("front = %+v, want #50", frontPlan.groups) + } + if reason, handled := fc.mergeTrainFront(context.Background(), frontPlan, fronts[0]); handled || reason != "" { + t.Fatalf("dirty Renovate front handled=%v reason=%q, want the lane's conflicting path", handled, reason) + } + mu.Lock() + defer mu.Unlock() + if len(requests) != 1 { + t.Fatalf("rebase requests after the Renovate front = %+v, want none added", requests) + } +} + func TestMergeTrainFrontRebaseLoopGuard(t *testing.T) { t0 := time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC) api := &mergeTrainAPI{ diff --git a/src/pkg/github/automerge/automerge_sweep_trusted.go b/src/pkg/github/automerge/automerge_sweep_trusted.go index 994b15b3a6..730e06c33b 100644 --- a/src/pkg/github/automerge/automerge_sweep_trusted.go +++ b/src/pkg/github/automerge/automerge_sweep_trusted.go @@ -135,7 +135,7 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, // state and not author work (hivecommons/hive#12607). return AutoMergeSweepEvent{}, autoMergeReasonBehindBudgetExhausted, nil } - return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, evaluatedHeadSHA, "behind", c.isForkPR(pr)) + return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, evaluatedHeadSHA, "behind", pr) } if mergeableState == "dirty" || mergeableState == "conflicting" { return AutoMergeSweepEvent{}, "conflicting", nil @@ -211,7 +211,7 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, if reviewReason := c.mergeReviewGate(ctx, displayRepo, owner, repo, lane, number, pr, evaluatedHeadSHA, priorApprover, priorChecked); reviewReason != "" { return AutoMergeSweepEvent{}, reviewReason, nil } - if ev, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, evaluatedHeadSHA, branchUpdateAllowed, autoMergeReasonBehindBudgetExhausted, c.isForkPR(pr), stageLaneSelf); stop { + if ev, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, evaluatedHeadSHA, branchUpdateAllowed, autoMergeReasonBehindBudgetExhausted, pr, stageLaneSelf); stop { return ev, reason, err } } @@ -293,7 +293,7 @@ func (c *Engine) trySweepSelfAuthoredPR(ctx context.Context, displayRepo, owner, if !branchUpdateAllowed { return AutoMergeSweepEvent{}, autoMergeReasonChecksExpected, nil } - return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, evaluatedHeadSHA, "required-checks-expected", c.isForkPR(pr)) + return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, evaluatedHeadSHA, "required-checks-expected", pr) } if refused := c.refusedMerge(attempt, err); refused != "" { return AutoMergeSweepEvent{}, refused, nil @@ -651,7 +651,7 @@ func (c *Engine) trySweepTrustedAuthorPR(ctx context.Context, displayRepo, owner if headSHA == "" { return AutoMergeSweepEvent{}, "missing-head-sha", nil } - return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "behind", c.isForkPR(pr)) + return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "behind", pr) } if mergeableState == "dirty" || mergeableState == "conflicting" { return c.mergeForwardOrConflict(ctx, displayRepo, owner, repo, pr, number) @@ -701,7 +701,7 @@ func (c *Engine) trySweepTrustedAuthorPR(ctx context.Context, displayRepo, owner if reviewReason := c.mergeReviewGate(ctx, displayRepo, owner, repo, stageLaneTrusted, number, pr, headSHA, priorApprover, priorChecked); reviewReason != "" { return AutoMergeSweepEvent{}, reviewReason, nil } - if ev, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, headSHA, true, "behind", c.isForkPR(pr), stageLaneTrusted); stop { + if ev, reason, stop, err := c.currentBaseGate(ctx, displayRepo, owner, repo, number, baseBranch, headSHA, true, "behind", pr, stageLaneTrusted); stop { return ev, reason, err } } @@ -753,7 +753,7 @@ func (c *Engine) trySweepTrustedAuthorPR(ctx context.Context, displayRepo, owner }) if err != nil { if c.requiredChecksExpected(attempt, err) { - return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "required-checks-expected", c.isForkPR(pr)) + return c.updateBranchAndSkip(ctx, displayRepo, owner, repo, number, headSHA, "required-checks-expected", pr) } if refused := c.refusedMerge(attempt, err); refused != "" { return AutoMergeSweepEvent{}, refused, nil @@ -812,7 +812,37 @@ func (c *Engine) isForkPR(pr *gh.PullRequest) bool { return headRepo != "" && baseRepo != "" && !strings.EqualFold(headRepo, baseRepo) } -func (c *Engine) updateBranchAndSkip(ctx context.Context, displayRepo, owner, repo string, number int, headSHA, reason string, fork bool) (AutoMergeSweepEvent, string, error) { +// leaveBaseSyncToDependencyBot reports whether pr's head branch belongs to a +// dependency bot (hgithub.DependencyBotBranch) and, if so, logs once per head +// and step that the hive leaves the base sync to the bot. Every automerge +// write that would put a hive commit on someone else's head to bring it up to +// date — update-branch, merge-forward, a merge-train rebase request — asks +// this first: Renovate stops rebasing a branch for good once another identity +// has committed to it (projectbluefin/utah#1097), and under strict freshness +// it rebases a behind branch itself. A nil PR is never a bot branch. +func (c *Engine) leaveBaseSyncToDependencyBot(displayRepo, owner, repo string, pr *gh.PullRequest, step string) bool { + if pr == nil { + return false + } + headRef, author := pr.GetHead().GetRef(), hgithub.SafeGetLogin(pr.GetUser()) + if !hgithub.DependencyBotBranch(headRef, author) { + return false + } + number, headSHA := pr.GetNumber(), pr.GetHead().GetSHA() + if c.markTerminalHoldLogged(owner, repo, number, headSHA, "dependency-bot:"+step) { + c.info("automerge: branch belongs to a dependency bot; leaving the base sync to the bot", + "repo", displayRepo, "pr", number, "head", headSHA, "head_ref", headRef, "author", author, "step", step) + } + return true +} + +// updateBranchAndSkip merges the base into pr's head with GitHub's +// update-branch. A dependency bot's branch is never updated: it holds as +// "behind" until the bot rebases it. +func (c *Engine) updateBranchAndSkip(ctx context.Context, displayRepo, owner, repo string, number int, headSHA, reason string, pr *gh.PullRequest) (AutoMergeSweepEvent, string, error) { + if c.leaveBaseSyncToDependencyBot(displayRepo, owner, repo, pr, "update-branch") { + return AutoMergeSweepEvent{}, "behind", nil + } if err := c.executeUpdateBranchEffect(ctx, owner, repo, number, headSHA, reason); err != nil { if wait := preparationWaitReason(err); wait != "" { return AutoMergeSweepEvent{}, wait, nil @@ -820,7 +850,7 @@ func (c *Engine) updateBranchAndSkip(ctx context.Context, displayRepo, owner, re if c.requireCurrentBaseFor(owner+"/"+repo) && hgithub.IsUpdateBranchStaleHead(err) { return AutoMergeSweepEvent{}, basePreparationPrefix + "snapshot-changed", nil } - switch classifyUpdateBranchError(err, fork) { + switch classifyUpdateBranchError(err, c.isForkPR(pr)) { case updateBranchUpToDate: return AutoMergeSweepEvent{}, "check-pending", nil case updateBranchForkNotEditable: diff --git a/src/pkg/github/dependency_bot.go b/src/pkg/github/dependency_bot.go new file mode 100644 index 0000000000..a368b62cf7 --- /dev/null +++ b/src/pkg/github/dependency_bot.go @@ -0,0 +1,32 @@ +package github + +import "strings" + +// dependencyBotAuthors are forge bots whose PRs are dependency bumps, not hive +// fix attempts. They carry the "[bot]" suffix that otherwise marks a PR as +// agent-authored, but nothing in the hive opened them and no hive agent is +// iterating on them. Mirrors the hub's default contribute deny-authors list +// (config: hub.contribute_deny_authors). +var dependencyBotAuthors = map[string]bool{ + "renovate[bot]": true, + "dependabot[bot]": true, + "mergeraptor[bot]": true, +} + +// IsDependencyBotAuthor reports whether login is one of the dependency bots. +func IsDependencyBotAuthor(login string) bool { + return dependencyBotAuthors[strings.ToLower(strings.TrimSpace(login))] +} + +// DependencyBotBranch reports whether a PR's head branch belongs to a +// dependency bot that keeps it up to date itself: a `renovate/` head ref (any +// Renovate deployment, whatever account it runs as) or a dependency-bot +// author. Renovate refuses to rebase a branch once another identity has +// committed to it, so every hive write that merges the base into such a +// branch — update-branch, a merges-API merge-forward, a fixer rebase — strands +// it behind its base for good (projectbluefin/utah#1097: three hive base +// merges, then "will not automatically rebase … does not recognize the last +// commit author"). Callers leave the base sync to the bot instead. +func DependencyBotBranch(headRef, author string) bool { + return strings.HasPrefix(strings.TrimSpace(headRef), "renovate/") || IsDependencyBotAuthor(author) +} diff --git a/src/pkg/github/dependency_bot_test.go b/src/pkg/github/dependency_bot_test.go new file mode 100644 index 0000000000..4db0dba783 --- /dev/null +++ b/src/pkg/github/dependency_bot_test.go @@ -0,0 +1,24 @@ +package github + +import "testing" + +func TestDependencyBotBranch(t *testing.T) { + for _, tc := range []struct { + headRef, author string + want bool + }{ + {headRef: "renovate/actions-checkout-5.x", author: "renovate[bot]", want: true}, + {headRef: "renovate/go-deps", author: "castrojo", want: true}, // Renovate under a person's token + {headRef: "dependabot/npm_and_yarn/x", author: "dependabot[bot]", want: true}, + {headRef: "refresh-buildroot", author: "mergeraptor[bot]", want: true}, + {headRef: "deps/bump", author: "Renovate[bot]", want: true}, + {headRef: "feature", author: "alice"}, + {headRef: "scanner/fix-1097", author: "hive-app[bot]"}, + {headRef: "fix/renovate/x", author: "alice"}, + {}, + } { + if got := DependencyBotBranch(tc.headRef, tc.author); got != tc.want { + t.Errorf("DependencyBotBranch(%q, %q) = %v, want %v", tc.headRef, tc.author, got, tc.want) + } + } +} diff --git a/src/pkg/github/merge_ci_gate_test.go b/src/pkg/github/merge_ci_gate_test.go index dde271d51f..cd958b46bb 100644 --- a/src/pkg/github/merge_ci_gate_test.go +++ b/src/pkg/github/merge_ci_gate_test.go @@ -24,6 +24,7 @@ type ciFixture struct { author string authorType string headRepo string + headRef string baseRepo string statuses []ciStatus checks []ciCheck @@ -114,7 +115,7 @@ func (f *ciFixture) serveCI(w http.ResponseWriter, r *http.Request) bool { "number": n, "state": "open", "user": map[string]any{"login": author, "type": authorType}, - "head": map[string]any{"sha": head, "repo": map[string]any{"full_name": headRepo}}, + "head": map[string]any{"sha": head, "ref": f.headRef, "repo": map[string]any{"full_name": headRepo}}, "base": map[string]any{"ref": "main", "repo": map[string]any{"full_name": baseRepo}}, } if f.updatedAt != "" { diff --git a/src/pkg/github/merge_request_watcher.go b/src/pkg/github/merge_request_watcher.go index cd8aa3796e..c7a8d6eeaf 100644 --- a/src/pkg/github/merge_request_watcher.go +++ b/src/pkg/github/merge_request_watcher.go @@ -474,9 +474,15 @@ func (c *Client) handleOneMergeRequest(ctx context.Context, path string, nowFn f } // Optional branch-update-first (resolves "behind main"). A failure here is - // not fatal — the merge attempt below will surface the real blocker. + // not fatal — the merge attempt below will surface the real blocker. A + // dependency bot's branch is never updated: the bot rebases it itself, + // and a hive merge commit would stop it doing so (DependencyBotBranch). if req.UpdateBranch { - if err := c.UpdateBranch(ctx, req.Repo, req.Number); err != nil { + headRef, author := destination.GetHead().GetRef(), SafeGetLogin(destination.GetUser()) + if DependencyBotBranch(headRef, author) { + c.logger.Info("merge-request watcher: update-branch skipped; the branch belongs to a dependency bot (continuing to merge attempt)", + slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("head_ref", headRef), slog.String("author", author)) + } else if err := c.UpdateBranch(ctx, req.Repo, req.Number); err != nil { c.logger.Info("merge-request watcher: update-branch failed (continuing to merge attempt)", slog.String("repo", req.Repo), slog.Int("number", req.Number), slog.String("error", err.Error())) } diff --git a/src/pkg/github/merge_request_watcher_test.go b/src/pkg/github/merge_request_watcher_test.go index 72c4554c0c..6ff6ec89cf 100644 --- a/src/pkg/github/merge_request_watcher_test.go +++ b/src/pkg/github/merge_request_watcher_test.go @@ -131,6 +131,64 @@ func TestMergeRequestWatcher_MergesAndConsumes(t *testing.T) { } } +// hive-merge --update-branch never merges the base into a dependency bot's +// branch (projectbluefin/utah#1097: Renovate stops rebasing a branch once +// the hive committed to it); the merge attempt still runs. An ordinary +// branch is still updated first. +func TestMergeRequestWatcher_UpdateBranchSkipsDependencyBotBranch(t *testing.T) { + for _, tc := range []struct { + name string + headRef string + author string + wantUpdates int32 + }{ + {name: "renovate head ref", headRef: "renovate/go-deps"}, + {name: "dependency bot author", headRef: "deps/bump", author: "dependabot[bot]"}, + {name: "ordinary branch", headRef: "feature", wantUpdates: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + var updates, merges atomic.Int32 + green := greenFixture() + green.headRef, green.author = tc.headRef, tc.author + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if green.serveCI(w, r) { + return + } + switch { + case r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/update-branch"): + updates.Add(1) + w.WriteHeader(http.StatusAccepted) + _, _ = io.WriteString(w, `{"message":"Updating pull request branch."}`) + case r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/merge"): + merges.Add(1) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"sha":"deadbeef","merged":true,"message":"Pull Request successfully merged"}`) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer srv.Close() + c := testMergeClient(t, srv.URL) + + dir := t.TempDir() + mergeRequestDirForTest = dir + defer func() { mergeRequestDirForTest = "" }() + + if _, err := WriteMergeRequest(dir, MergeRequest{Repo: "o/r", Number: 42, Method: "squash", Agent: "scanner", UpdateBranch: true}); err != nil { + t.Fatal(err) + } + c.ProcessMergeRequestsOnce(context.Background()) + + if got := updates.Load(); got != tc.wantUpdates { + t.Fatalf("update-branch calls = %d, want %d", got, tc.wantUpdates) + } + if got := merges.Load(); got != 1 { + t.Fatalf("merges = %d, want 1", got) + } + }) + } +} + // A nil authorizer must fail closed — no merge, request quarantined .denied. func TestMergeRequestWatcher_NilAuthzFailsClosed(t *testing.T) { merges := 0