This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new a8bae200d3e3 [SPARK-61331][INFRA] Read every page of the GitHub list
responses in merge_spark_pr.py
a8bae200d3e3 is described below
commit a8bae200d3e327ca22c04e0d6391445761615d67
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:45:44 2026 +0900
[SPARK-61331][INFRA] Read every page of the GitHub list responses in
merge_spark_pr.py
### What changes were proposed in this pull request?
`dev/merge_spark_pr.py` reads three GitHub list endpoints with `get_json`,
which returns only the first page of a list. GitHub puts 30 items on a page
unless the request asks for more.
This PR adds `get_json_pages`, which asks for 100 items per page
(`GITHUB_PAGE_SIZE`, the most GitHub allows) and follows the `rel="next"` URL
of each page's `Link` header until a page has none, as `gh api --paginate`
does. It is used for:
- the PR's events (`/issues/<n>/events`), where `find_merge_commit` looks
for the merge commit;
- the PR's commits (`/pulls/<n>/commits`), which give the co-authors and,
when the profile has none, the author's email;
- the repository's branches (`/branches`), which give the release branches
to pick into.
The request part of `get_json` moves into `open_github_url`, so that
`get_json_pages` can read each response's `Link` header. `main()` now reads the
events only for a closed PR, and the author's profile and the commits only when
it merges, since nothing else uses them. An open PR's events and a backported
PR's commits are no longer paged through only to be dropped.
### Why are the changes needed?
On a merged PR with more than 30 events, the `closed` event that carries
the merge commit is not on the first page. The script then finds no merge
commit and treats the PR as unmerged. Instead of offering a backport and the
JIRA update, it stops at "Pull request N is not mergeable in its current form.
Continue? (experts only!)". This happened with #60129, which has 38 events,
with the `closed` event 31st.
The same limit drops the commits after the 30th, so their authors get no
`Co-authored-by` trailer. It also caps the branches: apache/spark has 31 now,
so `master` is already off the first page, and a couple more release branches
would push a release branch off it too, so the script would stop offering it as
a pick target.
### Does this PR introduce _any_ user-facing change?
No. It changes only the committers' merge script.
### How was this patch tested?
- New doctests for `get_json_pages`, with a fake that sends GitHub-like
`Link` headers: three pages, the middle one shorter than the first, are all
read in order, and none of the last page's links back is followed; a one-page
list without a `Link` header costs one request; and a URL that already has a
query string gets the page size appended to it.
- The `main_titles` doctest, the one that drives `main()`, now serves
`get_json_pages` from its fake. Each run checks the release branches that
`main()` hands to `default_pick_branch`. It also checks that a merge reads no
events, and that a backport reads neither the commits nor the author's profile.
Breaking any of these on purpose makes the doctest fail. All doctests of the
script pass, 432 of them (426 before this change):
```
python3 -c 'import doctest, sys; sys.path.insert(0, "dev"); import
merge_spark_pr; print(doctest.testmod(merge_spark_pr))'
```
- Against GitHub, with the page size set to 10 to force several pages,
`get_json_pages` read as many items as `gh api --paginate`: 38 events of
#60129, 59 events and 32 commits of #59424, and 31 branches.
- Manually:
- `dev/merge_spark_pr.py --dry-run 60129` now prints "Pull request 60129
has already been merged, assuming you want to backport", finds the merge commit
`bb0d4b792e99` and reports "Already backported to: branch-4.x". Without this
change, it stopped at "Pull request 60129 is not mergeable in its current
form.".
- `--dry-run 60273`, this PR while it is open, reads through to the JIRA
check.
- `ruff check` and `ruff format --check` with ruff 0.14.8.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code (Claude Opus 5.5)
This pull request and its description were written by Isaac.
Closes #60273 from HyukjinKwon/merge-script-paging.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
skip-checks: true
---
dev/merge_spark_pr.py | 151 +++++++++++++++++++++++++++++++++++++-------------
1 file changed, 111 insertions(+), 40 deletions(-)
diff --git a/dev/merge_spark_pr.py b/dev/merge_spark_pr.py
index 039dda1e83f9..00200a8993d4 100755
--- a/dev/merge_spark_pr.py
+++ b/dev/merge_spark_pr.py
@@ -102,6 +102,9 @@ DRY_RUN_ENV = bool(os.environ.get("DRY_RUN"))
GITHUB_BASE = "https://github.com/apache/spark/pull"
GITHUB_COMMIT_BASE = "https://github.com/apache/spark/commit"
GITHUB_API_BASE = "https://api.github.com/repos/apache/spark"
+# Items per page that get_json_pages asks GitHub list endpoints for: the most
GitHub allows.
+# Without it, GitHub returns 30.
+GITHUB_PAGE_SIZE = 100
JIRA_BASE = "https://issues.apache.org/jira/browse"
JIRA_API_BASE = "https://issues.apache.org/jira"
# Prefix added to temporary branches
@@ -605,12 +608,13 @@ def get_input(prompt, options, bold=True,
ignore_case=True):
return option
-def get_json(url):
+def open_github_url(url):
+ """Open the GitHub API `url`, with GITHUB_OAUTH_KEY if set, and exit on an
HTTP error."""
try:
request = Request(url)
if GITHUB_OAUTH_KEY:
request.add_header("Authorization", "token %s" % GITHUB_OAUTH_KEY)
- return json.load(urlopen(request))
+ return urlopen(request)
except HTTPError as e:
if "X-RateLimit-Remaining" in e.headers and
e.headers["X-RateLimit-Remaining"] == "0":
print_error(
@@ -629,6 +633,65 @@ def get_json(url):
sys.exit(-1)
+def get_json(url):
+ return json.load(open_github_url(url))
+
+
+def get_json_pages(url):
+ """Return every item of the GitHub list endpoint at `url`, reading all of
its pages.
+
+ `get_json` reads only the first page, and GitHub fills it with 30 items
unless asked for
+ more. On a PR with a long history, that misses the `closed` event that
records the merge
+ commit, so a merged PR looks unmerged (#60129, with 38 events). It also
drops the commits
+ after the 30th, so their authors get no Co-authored-by, and the release
branches after
+ the 30th, so they cannot be picked into. Each page asks for
GITHUB_PAGE_SIZE items, and
+ reading follows the `rel="next"` URL of each page's `Link` header until a
page has none,
+ as `gh api --paginate` does, so a page with fewer items does not end the
read early.
+
+ >>> import io
+ >>> from unittest.mock import patch
+ >>> base = "https://api.github.com/repos/apache/spark"
+ >>> def read(path, *pages):
+ ... # Serve `pages` in order, with Link headers like the ones GitHub
sends.
+ ... requested = []
+ ... def links(*rels):
+ ... return ", ".join('<%s/p?page=%d>; rel="%s"' % (base, n, rel)
for rel, n in rels)
+ ... def open_page(page_url):
+ ... requested.append(page_url[len(base) :])
+ ... n = len(requested)
+ ... page = io.BytesIO(json.dumps(pages[n - 1]).encode())
+ ... page.headers = {}
+ ... if n < len(pages):
+ ... page.headers["Link"] = links(("next", n + 1), ("last",
len(pages)))
+ ... elif n > 1:
+ ... page.headers["Link"] = links(("prev", n - 1), ("first", 1))
+ ... return page
+ ... with patch.dict(get_json_pages.__globals__,
open_github_url=open_page):
+ ... return get_json_pages(base + path), requested
+
+ Every page is read in order, including the page after one with fewer
items, and the last
+ page's links back to earlier pages are not followed:
+
+ >>> read("/issues/1/events", ["a", "b"], ["c"], ["d", "e"])
+ (['a', 'b', 'c', 'd', 'e'], ['/issues/1/events?per_page=100', '/p?page=2',
'/p?page=3'])
+
+ A list that fits on one page comes without a Link header and costs one
request, and a URL
+ that already has a query string gets the page size appended to it:
+
+ >>> read("/branches?protected=false", ["master", "branch-4.x"])
+ (['master', 'branch-4.x'], ['/branches?protected=false&per_page=100'])
+ """
+ separator = "&" if "?" in url else "?"
+ url = "%s%sper_page=%d" % (url, separator, GITHUB_PAGE_SIZE)
+ items = []
+ while url is not None:
+ response = open_github_url(url)
+ items.extend(json.load(response))
+ next_link = re.search(r'<([^>]*)>;\s*rel="next"',
response.headers.get("Link") or "")
+ url = next_link.group(1) if next_link else None
+ return items
+
+
def merge_commit_candidates(pr_events):
"""Split `pr_events` into (closed_commits, referenced_commits), each
oldest-first.
@@ -724,9 +787,9 @@ def committed_title(pr_num: Union[int, str], message:
Optional[str]) -> Optional
class GitHub:
"""GitHub REST writes used by the merge script -- the single seam for PR
mutations.
- Reads go through the module-level get_json(); only the two mutations
(closing the PR and
- posting a comment) live here, so DryRunGitHub can override them without
touching any read
- path. main() constructs GitHub() normally and DryRunGitHub() for a dry run.
+ Reads go through the module-level get_json() and get_json_pages(); only
the two mutations
+ (closing the PR and posting a comment) live here, so DryRunGitHub can
override them without
+ touching any read path. main() constructs GitHub() normally and
DryRunGitHub() for a dry run.
"""
def close_pr(self, pr_num):
@@ -3189,7 +3252,7 @@ def main():
os.chdir(SPARK_HOME)
original_head = get_current_ref()
- branches = get_json("%s/branches" % GITHUB_API_BASE)
+ branches = get_json_pages("%s/branches" % GITHUB_API_BASE)
branch_names = list(filter(lambda x: x.startswith("branch-"), [x["name"]
for x in branches]))
branch_names = sorted(branch_names, key=semver_branch_rank, reverse=True)
@@ -3199,7 +3262,6 @@ def main():
pr_num = args.pr_num
print("Start to merge pull request #%s" % (pr_num))
pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num))
- pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num))
url = pr["url"]
title = pr["title"]
@@ -3216,6 +3278,7 @@ def main():
# merge as it could have been reverted earlier.
merge_hash, message = (None, None)
if pr["state"] == "closed":
+ pr_events = get_json_pages("%s/issues/%s/events" % (GITHUB_API_BASE,
pr_num))
merge_hash, message = find_merge_commit(pr_num, pr_events)
if merge_hash is not None:
print("Pull request %s has already been merged, assuming you want to
backport" % pr_num)
@@ -3252,37 +3315,6 @@ def main():
base_ref = pr["head"]["ref"]
pr_repo_desc = "%s/%s" % (user_login, base_ref)
- # Fetch PR author's GitHub profile and PR commits for commit attribution
- pr_author_info = get_json("https://api.github.com/users/%s" % user_login)
- pr_author_name = pr_author_info.get("name") or user_login
- pr_author_email = pr_author_info.get("email")
- pr_commits = get_json("%s/pulls/%s/commits" % (GITHUB_API_BASE, pr_num))
- if not pr_author_email:
- # If the GitHub profile has no public email, find the author's email
from the
- # PR's git commits. Only use it if GitHub links the commit to the PR
author's
- # account (meaning the email is verified on their GitHub account).
- for c in pr_commits:
- commit_author = c.get("author")
- if commit_author and commit_author.get("login") == user_login:
- pr_author_email = c["commit"]["author"]["email"]
- break
- if not pr_author_email:
- pr_author_email = "%[email protected]" %
(pr_author_info["id"], user_login)
- pr_author = "%s <%s>" % (pr_author_name, pr_author_email)
-
- # Collect co-authors: commit authors whose GitHub login differs from the
PR author.
- # This deduplicates the PR author (who may use multiple emails across
commits) by login.
- co_authors = []
- seen = set()
- for c in pr_commits:
- gh_author = c.get("author")
- if gh_author and gh_author.get("login") == user_login:
- continue
- raw = "%s <%s>" % (c["commit"]["author"]["name"],
c["commit"]["author"]["email"])
- if raw not in seen:
- seen.add(raw)
- co_authors.append(raw)
-
if merge_hash is not None:
# The change is already on target_ref and on any branch a previous run
backported it
# to, so exclude all of them: defaulting to one would cherry-pick an
empty commit.
@@ -3325,6 +3357,37 @@ def main():
update_jira_for_pr(pr_num, title, picked_refs)
sys.exit(0)
+ # Fetch PR author's GitHub profile and PR commits for commit attribution
+ pr_author_info = get_json("https://api.github.com/users/%s" % user_login)
+ pr_author_name = pr_author_info.get("name") or user_login
+ pr_author_email = pr_author_info.get("email")
+ pr_commits = get_json_pages("%s/pulls/%s/commits" % (GITHUB_API_BASE,
pr_num))
+ if not pr_author_email:
+ # If the GitHub profile has no public email, find the author's email
from the
+ # PR's git commits. Only use it if GitHub links the commit to the PR
author's
+ # account (meaning the email is verified on their GitHub account).
+ for c in pr_commits:
+ commit_author = c.get("author")
+ if commit_author and commit_author.get("login") == user_login:
+ pr_author_email = c["commit"]["author"]["email"]
+ break
+ if not pr_author_email:
+ pr_author_email = "%[email protected]" %
(pr_author_info["id"], user_login)
+ pr_author = "%s <%s>" % (pr_author_name, pr_author_email)
+
+ # Collect co-authors: commit authors whose GitHub login differs from the
PR author.
+ # This deduplicates the PR author (who may use multiple emails across
commits) by login.
+ co_authors = []
+ seen = set()
+ for c in pr_commits:
+ gh_author = c.get("author")
+ if gh_author and gh_author.get("login") == user_login:
+ continue
+ raw = "%s <%s>" % (c["commit"]["author"]["name"],
c["commit"]["author"]["email"])
+ if raw not in seen:
+ seen.add(raw)
+ co_authors.append(raw)
+
if not bool(pr["mergeable"]):
msg = (
"Pull request %s is not mergeable in its current form.\n" % pr_num
@@ -3951,7 +4014,9 @@ __test__ = {
... pr = {"url": "u", "title": pr_title, "draft": False, "body": "b",
... "base": {"ref": "master"}, "user": {"login": "x"}, "head":
{"ref": "h"},
... "state": "open" if message is None else "closed",
"mergeable": True}
+ ... requested = []
... def get_json(url):
+ ... requested.append(url)
... if url.endswith("/branches"):
... return [{"name": "master"}, {"name": "branch-4.x"}]
... if url.endswith("/pulls/1"):
@@ -3971,17 +4036,19 @@ __test__ = {
... merge, check = Mock(return_value="abc"), Mock()
... pick = Mock(side_effect=lambda *a, **k: print("picked") or
[("branch-4.x", "d")])
... found = (None, None) if message is None else ("abc", message)
+ ... pick_default = Mock(return_value="branch-4.x")
... with (
... patch.object(sys, "argv", ["merge_spark_pr.py", "1"]),
patch("os.chdir"),
... patch.dict(main.__globals__, DRY_RUN_ENV=False,
check_script_up_to_date=Mock(),
... initialize_jira=Mock(), asf_jira=Mock(),
jira_disabled=False,
... clean_up=Mock(),
get_current_ref=Mock(return_value="master"),
- ... get_json=get_json,
find_merge_commit=Mock(return_value=found),
+ ... get_json=get_json, get_json_pages=get_json,
+ ... find_merge_commit=Mock(return_value=found),
... git=Mock(), github=Mock(),
check_linked_jira_issues=check,
... continue_maybe=Mock(), get_input=ask,
merge_pr=merge,
... post_merge_comment=Mock(),
prompt_for_components=prompt,
... branches_with_merge_footer=Mock(return_value=[]),
- ... default_pick_branch=Mock(return_value="branch-4.x"),
+ ... default_pick_branch=pick_default,
... cherry_pick=pick, update_jira_for_pr=update,
print=Mock(),
... print_error=lambda msg: print(msg.splitlines()[0])),
... ):
@@ -3992,6 +4059,10 @@ __test__ = {
... code = e.code
... committed = merge.call_args.args[2] if merge.called else None
... assert committed == (check.call_args.args[1] if check.called else
None)
+ ... assert all(c.args[0] == ["branch-4.x"] for c in
pick_default.call_args_list)
+ ... # A merge reads no events, and a backport reads neither commits
nor the author.
+ ... unused = ("/issues/1/events",) if message is None else
("/pulls/1/commits", "/users/x")
+ ... assert not [url for url in requested if url.endswith(unused)],
requested
... return update.call_args.args[1], committed, prompt.called, code
A merge commits, checks, and updates JIRA from the prepared title:
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]