Skip to content

Fix backports stranded by a merged cherry-pick, and stop re-cloning per CherryPick tick - #118235

Merged
fm4v merged 12 commits into
masterfrom
nik/cherry-pick-loop
Sep 7, 2026
Merged

fm4v merged 12 commits into
masterfrom
nik/cherry-pick-loop

Conversation

@fm4v

@fm4v fm4v commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Recover stranded backports, reuse the checkout across scheduled passes, and retry untouched conflicting cherry-picks when their release branch gains the missing prerequisites.

A merged cherry-pick can leave changes on a backport/* branch after the original PR has received pr-backports-created, so the ordinary search never revisits it. BackportPRs.reconcile_backport_branches checks those branches for completed cherry-picks without a backport PR and returns the original PR to processing. It rechecks the requested release labels and respects open or closed cherry-picks. Batched lookups require the exact head repository and base branch, follow all pages, and reject null or partial API responses instead of treating them as absent PRs.

cherry_pick.py --loop runs passes on a 20-minute cadence within a 170-minute window, amortizing the full checkout across passes. The workflow invokes Python directly. Python refreshes clients and credentials each pass, restores the originally selected commit, and removes only automation branches created during this run. It checks a monotonic deadline before starting each pass and caps sleeps at that deadline. Three consecutive failures end the loop, and any failed pass makes the job fail even if a later pass succeeds. Single-run invocation remains the default. A pass already running at the deadline is allowed to finish, subject to the workflow's overall timeout.

ReleaseBranch._retry_cherrypick uses git merge-tree --write-tree to resolve against the current release snapshot without changing the checkout or index, including renamed files. It requires an untouched cherry-pick head and generated base, then updates both remote refs atomically with leases against the exact inspected SHAs. Concurrent edits reject the push. Persistent conflicts remain for manual resolution, other Git failures propagate, and already-applied changes close the empty cherry-pick. A changed head, including an earlier successful retry, remains for humans to handle if it conflicts again.

Backport preparation pins one release SHA for both its resolved tree and final commit parent. Finalization fetches the current backport branch and protects its squash push with an explicit lease.

Git 2.38 or newer is required and checked before credentials or API mutations. Existing Ubuntu 22.04 runners have Git 2.34.1, as confirmed in this CherryPick run; live execution requires the separate runner-image upgrade to be deployed. Selecting this branch for a manual workflow run still operates on real repository backports.

Validation: 34 focused throwaway checks passed, covering local bare remotes, stale and moving refs, concurrent updates, atomic rejection, renamed files, healing and finalization, persistent conflicts, already-applied changes, dry runs, strict lookup errors, repository/base filtering and pagination, loop timing, failure exits, checkout/stash preservation, and token cache refresh. One check uses read-only live GitHub queries. Black and Ruff passed; Pylint has no new diagnostics relative to the original PR head.

Related: https://github.com/ClickHouse/clickhouse-private/pull/72922

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Recover stranded backports and improve cherry-pick retry and scheduling reliability.


Workflow [PR]
Sync PR [sync-upstream/pr/118235]

Version info

  • Merged into: 26.9.1.927 (included in 26.9 and later)

fm4v added 2 commits September 5, 2026 11:21
A backport PR is only ever created while processing the original PR, and the original is dropped from `receive_prs_for_backport` for good once it carries `pr-backports-created`. A cherry-pick PR merged after that label was set therefore leaves its resolution stranded on the `backport/*` branch with nothing pointing at it, and nothing brings the original back: `check_open_prs` is the only recovery path and it looks exclusively at cherry-pick PRs that are open at the moment a run starts.

That is how ClickHouse/clickhouse-private#63472 lost its 26.2 and 26.4 backports for a month. The bot auto-closed both cherry-pick PRs after 10 days of inactivity, which `process` reads as "discarded" and which stamped `pr-backports-created`. They were then reopened and merged on 2026-08-03 inside windows of 10 min 34 s and 4 min 32 s, and no run overlapped either window, since a `CherryPick` run takes 37 min at the median. The backports were only created on 2026-09-04, after a label sync happened to drop the label.

Every backport reaches a release branch through a `backport/<release>/<PR>` branch, which makes the set of those branches a complete work list. `reconcile_backport_branches` walks it before the search and puts back into the process any original PR whose branch carries changes and has no backport PR, independently of when, how fast or by whom the cherry-pick was merged.

A branch is actionable only when the cherry-pick work on it is finished: an open cherry-pick PR is still waiting for a human, and a closed one is a decision not to backport. Changes are detected against the merge base with the release branch, the same commit `create_backport` squashes onto, so the answer does not flip as the release branch moves on. The target releases are re-checked against the original PR's current labels so a backport nobody asked for is never recreated.

Enumeration is local git, and the PR lookups are batched through the new `GitHub.get_pull_states_by_head_refs`, so a run costs 4 `git for-each-ref` calls and about 5 GraphQL requests. Measured against the current repository state: 360 backport branches for the 4 active releases, 233 without a backport PR, all of them correctly non-actionable (185 with a closed cherry-pick, 48 with an open one), and 0 git inspections. Replaying the state of 2026-08-03 flags both `63472` branches and recovers the PR.
The runner is ephemeral, so `actions/checkout` re-fetches the whole repository on every run. Measured on a private-fork run of the same workflow: 25.3 min total, of which `git init` plus `git fetch --prune +refs/heads/* +refs/tags/*` took 1052 s, leaving 7 min 16 s of actual work. 70% of every run is the clone, and it is paid again 20 minutes later.

That also made the cron a fiction. Runs took 37 min at the median and 53 min at p90, so the real cadence was the run time, and because the `cherry-pick` concurrency group only keeps one pending run, 17 of 60 consecutive runs were cancelled without ever starting a job.

Loop inside a single job for ~2h50m instead, running an iteration every 20 minutes. The clone is amortised over the window, ~9% of the job instead of ~70%, and every iteration after the first re-fetches into a warm repository in about a second. The 20-minute cron is kept: a tick that fires during the loop is the successor that starts as soon as the loop exits, and it is what restarts the loop within 20 minutes if a run dies early. `timeout-minutes: 200` bounds a hung iteration.

Two details the loop has to handle that a fresh checkout gave for free:

- `clear_repo` in `git_helper` puts `HEAD` back, but the local branches a run creates are left behind, and a stale `backport/<release>/<PR>` makes the next iteration's `git pull --ff-only` fail once its remote counterpart has moved. Every iteration returns the working copy to the state a fresh checkout produces.
- A failing iteration no longer ends the job, since that would forfeit the rest of the window and force another cold clone. `cherry_pick.py` already reports the error through `CIBuddy`; the loop counts failures, gives up after 3 consecutive ones so a broken environment does not spin for three hours, and fails the job at the end if any iteration failed.

The loop body was exercised against a stub in a throwaway repository: all-succeed reaches the deadline and exits 0, all-fail breaks after exactly 3 consecutive failures and exits 1, a single failure resets the consecutive counter and still fails the job, and a quiet iteration that creates no branches does not trip `set -e` in the cleanup pipeline.
@clickhouse-gh

clickhouse-gh Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [944c0e9]

Summary: ✅


AI Review

Summary

This PR improves the cherry-pick automation by reusing one checkout across scheduled passes, recovering stranded backports, and retrying conflicting cherry-picks against the latest release branch. The recovery path is headed in the right direction, but the current version still has one blocker that would stop the workflow on the existing runners and one remaining repo-scoping gap in the sibling batched lookup used for version stamping.

Findings

❌ Blockers

  • [tests/ci/cherry_pick.py:1602-1608, tests/ci/cherry_pick.py:1688-1691, .github/workflows/cherry_pick.yml:27-54] The new loop/workflow path now hard-requires Git 2.38 before doing any work, but the style-checker-aarch64 runner this workflow still targets reports Git 2.34.1. Because the version check is at main, this does not only disable _retry_cherrypick; it makes every scheduled/manual cherry-pick run fail immediately, so backport creation stops entirely until the runner image is upgraded.
  • Suggested fix: keep the old checkout-based retry path on current runners, or gate the new merge-tree --write-tree path on the detected Git version instead of aborting the whole automation.

⚠️ Majors

  • [tests/ci/github_helper.py:358-394, tests/ci/pr_version_info.py:395-420] reconcile_backport_branches now uses a repo-scoped lookup, but get_backport_merge_commits still uses the old unscoped pullRequests(headRefName: ...) query and still tolerates partial GraphQL responses. scan_backport_versions relies on that helper to stamp Backported to sections, so a fork reusing the same backport/<release>/<PR> branch name, or a partial GraphQL error, can still make us silently report the wrong or incomplete release versions on the original PR and linked issues.
  • Suggested fix: apply the same headRepository/baseRefName filtering and allow_partial=False handling to get_backport_merge_commits, or route both callers through one shared helper so the repo-scoping and fail-closed behavior stay consistent.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 5, 2026
fm4v added 3 commits September 5, 2026 11:33
A cherry-pick PR's two branches are frozen at the moment the conflict was found: the base is `release/X` head from back then, plus an empty `-s ours` merge of the original PR's first parent. Conflicts are very often caused by a prerequisite backport that has not landed yet rather than by real divergence, and when that prerequisite does land the base still lacks it, so GitHub keeps reporting `CONFLICTING` forever. `process` only looked at `cherrypick_pr.mergeable`, saw false and went straight to assign-and-ping; nothing ever re-tested the merge against the current release branch.

Recovering was entirely manual and required no judgement: close the cherry-pick PR, delete its branch, remove `pr-cherrypick` and `do not test`, and check the original PR for a stale `pr-backports-created`, so the bot would build it again from scratch. In the case that prompted this, roughly 19 of the 37 hours between the prerequisite landing and the backport merging were spent waiting for someone to do exactly that.

`_retry_cherrypick` now rebuilds both branches against the current release branch head at the top of the conflict path. If the merge is clean it force-pushes them, comments on the PR saying why, and re-enters `process` so the ordinary merge and `create_backport` path finishes the job. `retried` bounds it to one extra pass, for the window where GitHub has not recomputed `mergeable` yet; that window is also polled briefly, and if it stays unknown the next run merges the PR.

The retry force-pushes the cherry-pick branch, so it must never overwrite a partial resolution. It runs only when the head is still exactly the original merge commit, which is the sole condition strictly required; when the base is still a generated merge of a release branch commit with the PR's first parent; and when the release branch has actually moved since the last attempt. Any of those failing logs the reason and leaves the PR alone. If the rebuilt merge turns out to be empty, the release branch already carries the change, so the PR is closed with a comment exactly as `create_cherrypick` does in the same situation.

`create_cherrypick` is refactored into `_prepare_backport_branch`, `_try_merge_backport_into_cherrypick` and `_cherrypick_is_empty` so the retry reuses it rather than duplicating the merge recipe. No behaviour change on that path. `_prepare_backport_branch` takes the base to build on so the retry can use the freshly fetched remote-tracking ref instead of a possibly stale local release branch.

The conflicting paths are now logged when a merge attempt fails. They name what a human would have to resolve and are the input for identifying the missing prerequisite later.

Plan: tmp/cherry-pick-self-healing-plan.md (not committed).
…levant

Measured against the live private queue: one retry costs ~22 s, almost all of it the working-tree swap between master and a release branch, which rewrites 50k+ files twice per PR. The "release branch unchanged" gate does not contain that, because release branches take commits several times a day, so for a genuinely conflicting cherry-pick the gate passes on nearly every run. With around 50 conflicting cherry-picks open in the private repo that is roughly 18 minutes added to every pass, against ~7 minutes of real work.

A merge conflict can only land in a file the PR itself touches, so if nothing arrived on the release branch in those paths since the last attempt, the merge cannot come out differently. Two tree diffs decide that in milliseconds and no working tree is touched. Paths are intersected in Python rather than passed as a pathspec, so a PR touching thousands of files cannot overflow the command line, `--no-renames` makes a rename appear as both its old and its new path, which can only make the check less eager to skip, and `-z` is used because plain `--name-only` leaves spaces unquoted.

The retry now only pays for itself when something plausibly relevant landed.
`ruff` does not count `# type:` comments as usage, so `Dict` and `Tuple`, used only in two such comments, were reported as unused imports and the style check failed. Use real annotations, which the file already does elsewhere (`self.release_branches: List[str] = []`).

Verified with the command the job runs: `ruff check --output-format=concise --quiet`, and through the job itself, `PYTHONPATH=./ci:. python3 ci/jobs/check_style.py --test ruff`.
Comment thread tests/ci/github_helper.py Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). label Sep 5, 2026
fm4v added 5 commits September 5, 2026 19:48
Use the same release commit for merge preparation and the parent passed
to `create_backport_from_resolved_tree`, even if a retry refreshes the
remote release ref while its local branch stays stale.

Related: #118235
Reject concurrent human updates to either ref and publish both updates
together. Also require the generated base tree to remain untouched.

Related: #118235
Replace the literal path filter with `git merge-tree`, which handles
renames without rewriting the working tree. Propagate failures other
than conflicts. Fetch the healed base before finalizing its backport,
and protect the squash push with a lease.

Related: #118235
Request strict GraphQL responses for `get_pull_states_by_head_refs` and
propagate missing repository, connection, or node-list data. Only a
successful empty connection means that no PR exists.

Related: #118235
Filter `get_pull_states_by_head_refs` by the expected base branch and
exact head repository identity. Follow every connection cursor so fork
PRs cannot hide the relevant automation PR on a later page.

Related: #118235
Comment thread tests/ci/cherry_pick.py
try:
result = git_runner(
f"{GIT_PREFIX} -c merge.renameLimit=999999 merge-tree "
f"--write-tree --name-only -z --no-messages {head} {refreshed_base}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_retry_cherrypick now depends on the 2-argument git merge-tree --write-tree interface. In the current CI environment I can reproduce this command exiting 129 with usage: git merge-tree <base-tree> <branch1> <branch2> (git --version reports 2.34.1). Because this handler only treats return code 1 as a merge conflict, the first conflicting cherry-pick that reaches this branch will raise out of _retry_cherrypick, fail the whole iteration, and never self-heal. Please either keep the checkout-based merge path on the current runners or gate this on a Git version that supports the newer merge-tree form.

pull Bot pushed a commit to erickirt/ClickHouse that referenced this pull request Sep 5, 2026
The style check is the cheapest CI job to reproduce locally and the most common reason an otherwise finished pull request comes back red. Waiting for CI to report it costs a full round-trip to learn something a local command answers in a second, and an agent has no reason to spend that.

Document the invocation, which is not discoverable: `ci/jobs/check_style.py` imports `praktika`, so it needs `PYTHONPATH=./ci:.`, and it writes its environment into `ci/tmp`, so it fails with `FileNotFoundError: ./ci/tmp/environment.json` unless that directory exists. Neither is mentioned anywhere. Also record the sub-check names for `--test`, that `--test` matches a case-insensitive substring, and which sub-checks matter for which kind of change.

Two Python-specific traps are called out because both cost a CI round-trip in ClickHouse#118235: `ruff` does not count `# type:` comments as usage, so a `typing` import used only in a type comment fails F401 as an unused import, and `black` is configured in `pyproject.toml` but enforced by no CI job, so time spent on `black` diffs is wasted.

`.claude/CLAUDE.md` is what `AGENTS.md` symlinks to, so this reaches both.

Verified by following it: `--test ruff`, `--test whitespace_check` and `--test catch_all` all pass on this change.
fm4v added 2 commits September 6, 2026 09:33
Restore the selected commit between iterations, clean up only newly
created automation branches, and check the monotonic deadline before
starting another pass. Propagate iteration failures to the job status.
Check the required Git version before credentials or API mutations.

Related: #118235
Allow `get_best_robot_token` to explicitly refresh its process-wide cache
and request a refresh from each `run_once` pass. Preserve cached behavior
for other callers while allowing token rotation and rate-limit selection
throughout a long-running backport job.

Related: #118235
Comment thread tests/ci/github_helper.py
}
)
aliases.append(
f"b{i}: pullRequests(headRefName:$head{i}, baseRefName:$base{i}, "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes the repo/base scoping problem for reconcile_backport_branches, but get_backport_merge_commits a few lines above still uses the old unscoped pullRequests(headRefName: ...) query and still accepts partial GraphQL responses. scan_backport_versions depends on that helper when it writes Backported to sections, so a fork reusing the same backport/<release>/<PR> branch name, or a partial GraphQL error, can still make us silently stamp the wrong or incomplete release list on the original PR / linked issues.

Please apply the same headRepository and baseRefName filtering there, and make that path fail closed on partial GraphQL errors as well, instead of keeping two different batched lookup implementations.

@fm4v
fm4v added this pull request to the merge queue Sep 7, 2026
Merged via the queue into master with commit 5b696db Sep 7, 2026
174 checks passed
@fm4v
fm4v deleted the nik/cherry-pick-loop branch September 7, 2026 19:45
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Sep 8, 2026
Bootstrap the selected script with a shallow checkout and fetch complete
history for the default branch, active releases, and their automation refs.
Refresh and prune that scope each iteration before changing PR state.

Related: ClickHouse#118235
Related: https://github.com/ClickHouse/ClickHouse/actions/runs/34156878118/job/101850435619
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ci-infrastructure CI/CD pipelines (GitHub Actions, CI scripts, runners). pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants