holdenk commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4584876276
##########
dev/merge_spark_pr.py:
##########
@@ -1381,7 +3016,20 @@ def cherry_pick(pr_num, merge_hash, default_branch,
branch_names, target_ref, al
f"Valid branches: {valid_branches}. Please try again."
)
+ def pick(ref, pending_sibling=None):
+ pair = _do_cherry_pick(
+ pr_num, merge_hash, ref, title=title,
pending_sibling=pending_sibling
+ )
+ if record:
+ record(pair)
Review Comment:
Fixed in 55e614a6e6e (the record half came in with the merge, 89a4ecda6df).
`[p]` and `[d]` now go through `_finish_landed`: record the pair, then
`_restore_original_head()` (waits for the committer to stash, as `[s]` does),
then `clean_up()`. A refused checkout no longer drops the pick or ends the run,
and `[a]bort` there leaves the pick recorded for `main()`'s finally blocks,
with the local state kept.
The `_do_cherry_pick` doctest pins the order for both exits, a restore that
aborts after the landing, and that a skip or a failed landing records nothing.
Checked by mutation: no restore, record after restore, record after clean_up,
never recording, and bypassing the helper at either exit each fail it.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
dev/spark_merge_footer.py:
##########
@@ -108,8 +122,41 @@ def merge_footer_pr(message):
return int(matches[-1]) if matches else None
+def backport_pr(message):
+ """The backport PR merged by `message`, or None: a `Backport-PR` trailer
in the final
+ paragraph, after the generated footer, so one quoted in a body does not
count.
+
+ >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A
<[email protected]>\\nSigned-off-by: C <[email protected]>"
+ >>> backport_pr("Fix\\n\\n%s\\nBackport-PR: #9\\nSigned-off-by: M
<[email protected]>" % footer)
+ 9
+ >>> backport_pr("Fix\\n\\nBackport-PR: #9\\n\\n" + footer) is None
+ True
+ >>> backport_pr("Fix\\n\\nBackport-PR: #9") is None
+ True
+
+ A backport of a merged backport PR carries both trailers; the last one is
the PR merged:
+
+ >>> chained = "Fix\\n\\n%s\\nBackport-PR: #9\\nBackport-PR: #10" % footer
+ >>> backport_pr(chained), has_merge_footer(chained, 10),
has_merge_footer(chained, 9)
+ (10, True, False)
+
+ A trailing `skip-checks` paragraph, added for the post-merge CI sampling,
does not hide it:
+
+ >>> backport_pr("Fix\\n\\n%s\\nBackport-PR: #9\\n\\n\\nskip-checks:
true\\n" % footer)
+ 9
+ """
+ matches = list(_MERGE_FOOTER_RE.finditer(message))
+ if not matches:
+ return None
+ paragraphs = [p.strip() for p in message[matches[-1].start()
:].split("\n\n")]
+ while paragraphs and (not paragraphs[-1] or
paragraphs[-1].lower().startswith("skip-checks:")):
Review Comment:
Fixed in 55e614a6e6e. Reproduced with real git first: `cherry-pick -sx` of a
sampled backport-PR merge, then `remove_inherited_post_merge_ci_skip`, leaves
`(cherry picked from commit ...)` and the sign-off as a paragraph of their own
and `backport_pr` returned None. `backport_pr` now skips trailing paragraphs
made only of `skip-checks:`, `(cherry picked from commit` and `Signed-off-by:`
lines.
Doctests: that picked shape reads as #9 and counts for both #9 and #7; a
pick of an unsampled merge, an ordinary pick and a trailer quoted before the
footer read as before; and one example in `remove_inherited_post_merge_ci_skip`
derives the shape from the real function. Reverting the rule fails the footer
module's own doctest and that one.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
dev/merge_spark_pr.py:
##########
@@ -3518,56 +5166,97 @@ def main():
print("title\t%s\nsource\t%s\ntarget\t%s\nurl\t%s" % (title, pr_repo_desc,
target_ref, url))
continue_maybe("Proceed with merging pull request #%s?" % pr_num)
- merged_refs = [target_ref]
-
merge_hash = merge_pr(pr_num, target_ref, title, body, pr_repo_desc,
pr_author, co_authors)
- # Ordered (branch, commit_hash) pairs for the merge comment: the merge
sink first,
- # then each cherry-pick target as it is picked.
- merged_commits = [(target_ref, merge_hash)]
-
- # merged_refs drives both the next prompt default and the already_picked
set passed to
- # cherry_pick, so each grows with every cherry-pick -- including branches
consumed by the
- # Upstream-First two-branch path inside cherry_pick (e.g. picking
branch-M.x + branch-M.N
- # in a single prompt). It starts with target_ref, the merge sink, never to
be re-picked.
+ # target_ref, the merge sink, is never to be re-picked.
+ picks = _PickLedger([target_ref])
pick_prompt = "Would you like to pick %s into another branch?" % merge_hash
# Always record the merge summary for what actually landed, even if a later
# cherry-pick is aborted or cancelled: the merge into the target branch has
# already been pushed, so cancelling a backport must not drop that line.
try:
+ # Seeded inside the try: the fork lookups can stall, and the merge is
already pushed.
+ # A merged backport PR inherits the original's branches: the default
skips them, and
+ # [p] on a typed pending one updates its PR.
+ if backport:
+ picks = _seed_picks(backport[0], target_ref, branch_names)
while get_input(f"\n{pick_prompt} (y/N): ", ["y", "n", ""]) == "y":
- default = default_pick_branch(branch_names, tuple(merged_refs))
+ default = default_pick_branch(branch_names, picks.seen())
if default is None:
- print("Every known release branch already contains #%s;
nothing to pick." % pr_num)
+ print(
+ "Every release branch has #%s or a backport PR of it;
nothing to pick." % pr_num
+ )
break
- picked = cherry_pick(
+ cherry_pick(
pr_num,
merge_hash,
default,
branch_names,
target_ref,
- already_picked=tuple(merged_refs),
+ already_picked=tuple(picks.landed),
+ title=title,
+ pending=picks.pending,
+ record=lambda pair: picks.record([pair]),
)
- merged_refs = merged_refs + [ref for ref, _ in picked]
- merged_commits = merged_commits + picked
finally:
- if merged_commits:
- # The "Closes #N" keyword in the commit message only auto-closes
the PR when the
- # commit lands on the default branch. For merges into other
branches (e.g.
- # branch-X.Y backport PRs), GitHub leaves the PR open, so close it
through the API.
- pr_state = get_json("%s/pulls/%s" % (GITHUB_API_BASE,
pr_num)).get("state")
- if pr_state != "closed":
- close_message = "PR #%s is still open after push; closing it
explicitly." % pr_num
- print("\n%s\n" % bold(close_message))
- github.close_pr(pr_num)
- # Record every branch that successfully received the change on the
PR.
- post_merge_comment(pr_num, merged_commits)
+ # The "Closes #N" keyword in the commit message only auto-closes the
PR when the
+ # commit lands on the default branch. For merges into other branches
(e.g.
+ # branch-X.Y backport PRs), GitHub leaves the PR open, so close it
through the API.
+ pr_state = get_json("%s/pulls/%s" % (GITHUB_API_BASE,
pr_num)).get("state")
+ if pr_state != "closed":
+ close_message = "PR #%s is still open after push; closing it
explicitly." % pr_num
+ print("\n%s\n" % bold(close_message))
+ github.close_pr(pr_num)
+ # Record every branch that received the change, or has a backport PR,
on the PR:
+ # the merge sink first, then each cherry-pick as it was picked.
+ post_merge_comment(pr_num, [(target_ref, merge_hash)] + picks.commits)
# This is deliberately in the finally block: once the target branch
has been pushed,
# cancelling a later cherry-pick must not bypass the JIRA update
decision.
- update_jira_for_pr(pr_num, title, merged_refs)
+ update_jira_for_pr(pr_num, title, picks.landed)
__test__ = {
+ "abort_entrypoint": """
+ After [a]bort at the checkout-retry prompt no git runs again, by any route
out: the CLI
+ handler, or a fail() in main()'s finally blocks such as declining the JIRA
prompt. An
+ ordinary exit still cleans up.
+
+ >>> import ast, doctest
+ >>> from pathlib import Path
+ >>> from contextlib import redirect_stdout
+ >>> from io import StringIO
+ >>> from unittest.mock import patch
+ >>> entrypoint = ast.parse(Path(__file__).read_text()).body[-1]
+ >>> code = compile(ast.Module(body=[entrypoint], type_ignores=[]),
__file__, "exec")
+ >>> refused = subprocess.CalledProcessError(1, "git checkout")
+ >>> def abort_then_fail():
+ ... try:
+ ... _restore_original_head()
+ ... finally:
+ ... fail("Okay, exiting")
+ >>> def ordinary_exit():
+ ... raise SystemExit(-1)
+ >>> for entry in (_restore_original_head, abort_then_fail, ordinary_exit):
+ ... with (
+ ... patch.object(doctest, "testmod", return_value=(0, 0)),
+ ... patch.dict(clean_up.__globals__, original_head="master",
+ ... preserve_local_state=False),
+ ... patch.object(git, "run", side_effect=refused) as run,
+ ... patch("builtins.input", side_effect=["a"]),
redirect_stdout(StringIO()),
+ ... ):
+ ... try:
+ ... exec(code, dict(globals(), __name__="__main__",
main=entry))
+ ... except BaseException as e:
+ ... ended = getattr(e, "code", type(e).__name__)
+ ... cmds = [c.args[0] if isinstance(c.args[0], str) else "
".join(c.args[0])
+ ... for c in run.call_args_list]
+ ... print(entry.__name__, [cmd.split()[1] for cmd in cmds], ended)
+ _restore_original_head ['checkout'] -1
+ abort_then_fail ['checkout'] -1
+ ordinary_exit ['checkout'] CalledProcessError
+ >>> preserve_local_state
Review Comment:
Fixed in 7ebc62246db, merged here in 89a4ecda6df: the closing check reads
`clean_up.__globals__["preserve_local_state"]`, and the entry point exits
before `main()` if the flag is still set after `testmod()`. Leaking the flag
before the closing check fails the fixed doctest and still passed the bare-name
one.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
dev/merge_spark_pr.py:
##########
@@ -1355,20 +2873,137 @@ def _upstream_first_sibling(target_ref, pick_ref,
branch_names, already_picked):
return None
-def cherry_pick(pr_num, merge_hash, default_branch, branch_names, target_ref,
already_picked=()):
+def cherry_pick(
+ pr_num,
+ merge_hash,
+ default_branch,
+ branch_names,
+ target_ref,
+ already_picked=(),
+ title="",
+ pending=None,
+ record=None,
+):
"""Prompt for a target branch and cherry-pick `merge_hash` onto it.
Enforces the Upstream-First policy (see header comment) via
`_upstream_first_sibling`: when the PR was merged into master and the
committer
types a branch-M.N target while branch-M.x is also a known release branch
AND
- has not already received this commit, prompt to confirm whether to pick
into
+ has not landed this commit (`already_picked`), prompt to confirm whether
to pick into
BOTH (the policy-compliant default) or branch-M.N only (treated as a
- maintenance-only bugfix). Returns the list of (ref, commit_hash) pairs
actually
- picked into, so the main loop can advance its remaining-branches list
correctly
- and record each backport commit for the merge comment. The list is empty
(or, for the
- Upstream-First two-branch path, holds only what landed) when the committer
declines to
- resolve a conflict, so the caller simply offers the next branch and still
resolves JIRA.
+ maintenance-only bugfix). If branch-M.x only has a pending backport
(`pending` maps
+ ref -> marker), it is not picked again; branch-M.N alone may still go to a
backport PR,
+ but a direct push needs the maintenance-only confirmation. The same holds
inside the
+ both-branches path when branch-M.x goes to a backport PR.
+
+ Returns the (ref, marker) pairs picked, markers as in `_do_cherry_pick`,
so the main loop
Review Comment:
Fixed in 7ebc62246db, merged here in 89a4ecda6df: the `cherry_pick`
docstring and the `[b]oth` comment now name `record` as how `main()` learns of
picks, list both skip conditions, and say the returned list repeats the
recorded pairs and nothing reads it. Pick sites, including the pending-sibling
one, are covered by a doctest that fails if any of them bypasses `record`.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
##########
dev/merge_spark_pr.py:
##########
@@ -4113,6 +5802,95 @@ def main():
pass
pass
""",
+ "main_ledgers": """
+ What main() passes on as landed and pending. Only landed branches are
already_picked and
+ reach JIRA; pending ones go to the pick and stay out of the default. A
merged backport PR,
+ whether merged in this run or an earlier one, starts from the original
PR's branches.
+
+ >>> import sys
+ >>> from unittest.mock import Mock, patch
+ >>> footer = "\\n\\nFix\\n\\nCloses #7 from x/h.\\n\\nAuthored-by: X <x@x>"
+ >>> def run(base="master", head="h", body="b", message=None,
interrupt=False):
+ ... pr = {"url": "u", "title": "[SPARK-1][SQL] Fix", "draft": False,
"body": body,
+ ... "base": {"ref": base}, "user": {"login": "x"}, "head":
{"ref": head},
+ ... "state": "open" if message is None else "closed",
"mergeable": True}
+ ... def get_json(url):
+ ... if url.endswith("/branches"):
+ ... names = ("master", "branch-4.x", "branch-4.2",
"branch-4.1")
+ ... return [{"name": b} for b in names]
+ ... if url.endswith("/pulls/1"):
+ ... return pr
+ ... if url.endswith("/pulls/1/commits"):
+ ... return [{"author": {"login": login}, "commit": {"author": {
+ ... "name": name, "email": email}}} for login, name, email
in
+ ... (("x", "X", "x@x"), ("f", "F", "f@f"))]
+ ... if url.endswith("/users/x"):
+ ... return {"name": "X", "email": "x@x", "id": 1}
+ ... return []
+ ... answers = iter(["y", "n"]) # one more pick on the merge path,
then stop
+ ... def ask(prompt, *args, **kwargs):
+ ... return next(answers) if "into another branch" in prompt else
"n"
+ ... picked = [] # the ledger is live, so snapshot what each pick is
handed
+ ... def pick(*args, already_picked, pending, **kwargs):
Review Comment:
Fixed in 55e614a6e6e: the `main_ledgers` stub now calls the `record` it is
handed, and `run()` asserts the pending pick reaches the merge summary while
JIRA still gets only landed branches. Checked by mutation: dropping `record=`
from either loop, recording a pending pick as landed, and dropping
`picks.commits` from either comment each fail. `main_records` (from #60471)
covers landed picks through the same loops.
---
<sub>馃 Posted by an AI agent (Claude Code 路 skill `none`) on behalf of
@holdenk.</sub>
<!-- agent-attribution v1: agent=claude-code; skill=none; operator=holdenk
-->
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]