spark-test commented on code in PR #60472:
URL: https://github.com/apache/spark/pull/60472#discussion_r4623465144


##########
dev/spark_merge_footer.py:
##########
@@ -193,6 +266,8 @@ def branches_with_merge_footer(pr_num, remote, run_git):
             "--fixed-strings",
             "--grep",
             merge_footer_trailer(pr_num),
+            "--grep",
+            backport_pr_trailer(pr_num),

Review Comment:
   Thanks, confirmed: the not-merged line now names both trailers, and the 
module description explains the Backport-PR trailer. Two related points still 
need a change, and this review raises each of them separately: nothing runs the 
new doctest on main() unless someone invokes it by hand, and the new 
description says every backport PR keeps the original's trailer, which holds 
only for a backport PR that the merge script opened.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4582305104","thread_id":"inline:4582305104","verdict_sha256":"575f619aa474f3ad30fbf91f25b20daba339ff84716a6d69bffc8ccb7324fd56"}
 -->



##########
dev/merge_spark_pr.py:
##########
@@ -1747,67 +2088,614 @@ def merge_pr(pr_num, target_ref, title, body, 
pr_repo_desc, pr_author, co_author
     return merge_hash
 
 
-def _do_cherry_pick(pr_num, merge_hash, pick_ref, record=None):
-    """Cherry-pick `merge_hash` onto `pick_ref` and push.
+def _set_skip_trailer(skip):
+    """Amend HEAD so it carries the skip trailer exactly when `skip`; leave it 
be otherwise,
+    so a retried push sends the same commit. Reads HEAD afresh, keeping any 
amend made since.
+    """
+    current = git.run(["git", "log", "-1", "--format=%B"])
+    wanted = remove_inherited_post_merge_ci_skip(current)
+    if skip:
+        wanted = append_post_merge_ci_skip(wanted)
+    # %B ends in one more newline than the helpers return.
+    if wanted.rstrip("\n") != current.rstrip("\n"):
+        amend_commit_message(wanted)
+
+
+def _pick_message(commit_body):
+    """A backport's message as both _backport_of (from the PR body) and 
merge_pr's soft check
+    (from the branch's commits) read it: LF line ends, no skip-checks, no 
mentions, no edge
+    whitespace. Mentions are stripped as merge_pr does for any body, keeping 
the @ inside
+    e-mail addresses.
+
+    >>> _pick_message("Fix @bob\\r\\nA <[email protected]>\\n\\n\\nskip-checks: 
true\\n")
+    'Fix bob\\nA <[email protected]>'
+    """
+    body = remove_inherited_post_merge_ci_skip(commit_body.replace("\r\n", 
"\n").strip() + "\n")
+    return _MENTION_RE.sub("", body).strip()
+
+
+def _backport_pr_branch(pr_num, pick_ref):
+    """Fork branch name for a backport PR: stable, PR-traceable, 
branch-suffixed.
+
+    >>> _backport_pr_branch(123, "branch-4.2")
+    'backport-pr123-branch-4.2'
+    >>> _backport_pr_branch(9, "branch-3.5")
+    'backport-pr9-branch-3.5'
+    """
+    return "backport-pr%s-%s" % (pr_num, pick_ref)
+
+
+def _backport_pr_title(pick_ref, title):
+    """PR title for a backport PR: the merged title with its version tag set 
to the target.
+
+    The tag goes where Title.parse expects one, so the script can still merge 
the result.
+    Revert/Reapply and other unparseable titles stay verbatim.
+
+    >>> _backport_pr_title("branch-4.2", "[SPARK-1234][SQL] Fix a thing")
+    '[SPARK-1234][4.2][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.x", "[SPARK-1234][4.X][SQL] Fix a thing")
+    '[SPARK-1234][4.X][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.2", "[SPARK-1234][4.X][SQL] Fix a thing")
+    '[SPARK-1234][4.2][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.2", "[MINOR] Fix typo")
+    '[MINOR][4.2] Fix typo'
+    >>> _backport_pr_title("branch-4.2-preview", "[MINOR] Fix typo")
+    '[MINOR] Fix typo'
+    >>> _backport_pr_title("branch-4.2", 'Revert "[SPARK-1234][SQL] Fix"')
+    'Revert "[SPARK-1234][SQL] Fix"'
+    >>> all(
+    ...     Title.parse(_backport_pr_title("branch-4.2", t))
+    ...     for t in ("[SPARK-1234][SQL] Fix", "[MINOR] Fix typo")
+    ... )
+    True
+    """
+    try:
+        parsed = Title.parse(title)
+    except ValueError:
+        return title
+    version = pick_ref[len("branch-") :].upper()
+    if not _VERSION_TAG_RE.match(version):
+        return title
+    others = [c for c in parsed.components if not _VERSION_TAG_RE.match(c)]
+    return str(Title(parsed.leading, [version] + others, parsed.text))
+
+
+def _remote_repo(url):
+    """`owner/repo` named by a git remote URL, or None.
+
+    >>> _remote_repo("[email protected]:me/spark.git")
+    'me/spark'
+    >>> _remote_repo("https://github.com/apache/spark.git";)
+    'apache/spark'
+    >>> _remote_repo("ssh://[email protected]:443/me/spark.git")
+    'me/spark'
+    >>> _remote_repo("git@github-work:me/spark")
+    'me/spark'
+    >>> _remote_repo("https://gitbox.apache.org/repos/asf/spark.git";)
+    'asf/spark'
+    >>> _remote_repo("") is None
+    True
+    """
+    m = re.search(r"[:/]([^/:]+)/([^/:]+?)(?:\.git)?/?$", url)
+    return "%s/%s" % m.groups() if m else None
+
+
+def _remote_url(name):
+    try:
+        return git.run(["git", "remote", "get-url", name]).strip()
+    except Exception:
+        return ""
+
+
+def _remote_push_urls(name):
+    # Where `git push <name>` really goes: pushurl and pushInsteadOf apply.
+    try:
+        return git.run(["git", "remote", "get-url", "--push", "--all", 
name]).split()
+    except Exception:
+        return []
+
+
+def _fork_owner(pushing=True):
+    """GitHub owner of the fork remote, for a backport PR's `head`. ValueError 
if unusable.
 
-    Returns the (pushed ref, pushed commit hash) pair, which `record` also 
gets, right after
-    the push and before the cleanup that can raise. Raises `SkipCherryPick` 
when the
-    committer declines to resolve a conflict, after aborting the pick, or 
declines a pre-push
-    check. The pick is committed by then, so nothing is aborted: it and its 
temporary branch
-    are discarded, and uncommitted edits must be stashed first (see 
continue_maybe).
+    The fork is checked by the repository its URL names, not the remote name: 
an `origin` that
+    was never repointed off apache/spark would otherwise get the backport 
branch and the PR.
+    A read-only caller passes pushing=False to skip the push-URL check.
 
-    Both pre-push checks run once, in order, before the push prompt; the 
binding-policy one
-    gets the target branch and its tip from before the pick. A declined check 
pushes nothing:
+    The env knobs are pinned so a committer's own settings cannot fail these 
at startup:
+
+    >>> from unittest.mock import patch
+    >>> def remotes(fork, owner=""):
+    ...     urls = {"apache": "https://gitbox.apache.org/repos/asf/spark.git";,
+    ...             "apache-github": "https://github.com/apache/spark.git";, 
"origin": fork}
+    ...     return patch.multiple(sys.modules[__name__], _remote_url=urls.get, 
FORK_OWNER=owner,
+    ...                           FORK_REMOTE_NAME="origin", 
PUSH_REMOTE_NAME="apache",
+    ...                           PR_REMOTE_NAME="apache-github")
+    >>> def owner_of(fork, owner="", push=None):
+    ...     pushes = patch.object(sys.modules[__name__], "_remote_push_urls",
+    ...                           lambda name: [fork] if push is None else 
push)
+    ...     with remotes(fork, owner), pushes:
+    ...         try:
+    ...             return _fork_owner()
+    ...         except ValueError as e:
+    ...             return "refused" if "is the Apache repo" in str(e) else 
str(e)
+    >>> owner_of("ssh://[email protected]:443/me/spark.git")
+    'me'
+    >>> [owner_of(f, owner="me") for f in (
+    ...     "[email protected]:apache/spark.git",
+    ...     "https://gitbox.apache.org/repos/asf/spark.git";,
+    ...     "git@gh:Apache/Spark",
+    ... )]
+    ['refused', 'refused', 'refused']
+
+    The branch goes to the push URLs, so they must name the fork too:
+
+    >>> apache = "[email protected]:apache/spark.git"
+    >>> "pushes to " + apache in owner_of("[email protected]:me/spark.git", 
push=[apache])
+    True
+    >>> owner_of("[email protected]:me/spark.git", 
push=["https://github.com/Me/spark.git";])
+    'me'
+
+    A github.com URL names its owner; FORK_OWNER only fills in for a host 
alias:
+
+    >>> owner_of("[email protected]:me/spark.git", owner="someone-else")
+    'me'
+    >>> owner_of("git@gh-alias:me/spark.git", owner="Me")
+    'Me'
+    >>> owner_of("git@gh-alias:me/spark.git").startswith("Cannot tell the 
GitHub owner")
+    True
+    """
+    url = _remote_url(FORK_REMOTE_NAME)
+    repo = _remote_repo(url)
+    if repo is None:
+        raise ValueError(
+            "No usable %s remote (%r). Set FORK_REMOTE_NAME to your fork's 
remote."
+            % (FORK_REMOTE_NAME, url)
+        )
+    apache = {"apache/spark"} | {
+        (_remote_repo(_remote_url(r)) or "").lower() for r in 
(PUSH_REMOTE_NAME, PR_REMOTE_NAME)
+    }
+    if repo.lower() in apache:
+        raise ValueError(
+            "%s remote (%s) is the Apache repo, not a fork. Set 
FORK_REMOTE_NAME to your "
+            "fork's remote." % (FORK_REMOTE_NAME, url)
+        )
+    for push_url in _remote_push_urls(FORK_REMOTE_NAME) if pushing else []:
+        if (_remote_repo(push_url) or "").lower() != repo.lower():
+            raise ValueError(
+                "%s remote fetches from %s but pushes to %s. Point both at 
your fork."
+                % (FORK_REMOTE_NAME, url, push_url)
+            )
+    if "github.com" in url:
+        return repo.split("/")[0]
+    if FORK_OWNER:
+        return FORK_OWNER
+    raise ValueError(
+        "Cannot tell the GitHub owner of %s remote (%s); set FORK_OWNER to 
your GitHub login."
+        % (FORK_REMOTE_NAME, url)
+    )
+
+
+def _landing_choice(pick_branch_name, pick_ref):
+    """Ask how a finished pick lands: [d]irect push, [p] fork + PR, or [s]kip 
(default).
+
+    Only asked with --prompt-for-branches-during-backport; without it 
_do_cherry_pick keeps the
+    plain continue_maybe push prompt.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import patch
+    >>> def choose(answer):
+    ...     with patch("builtins.input", return_value=answer), 
redirect_stdout(StringIO()):
+    ...         return _landing_choice("PR_TOOL_PICK_PR_1_BRANCH-4.2", 
"branch-4.2")
+    >>> choose(""), choose("p"), choose("d")
+    ('s', 'p', 'd')
+    """
+    return get_input(
+        "Pick complete (local ref %s). How should it land?\n"
+        "  [d] Push directly to %s/%s\n"
+        "  [p] Push to your fork (%s) and open a backport PR against %s (for 
CI)\n"
+        "  [s] Skip this branch (default)\n"
+        "Choose [d/p/s]: "
+        % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref, FORK_REMOTE_NAME, 
pick_ref),
+        {"d": ["d", "direct"], "p": ["p", "pr"], "s": ["s", "skip", ""]},
+    )
+
+
+def _land_via_fork(pr_num, pick_ref, pick_branch_name, title):
+    """Push the pick to the fork and open a backport PR against `pick_ref`.
+
+    Returns the PR URL, or a `fork:<owner>:<branch>` marker if the push worked 
but the PR did
+    not open. Either failure offers _manual_backport_pr, whose pasted URL 
wins. Returns None,
+    having pushed nothing, when the fork is unusable or the push fails and no 
URL was pasted,
+    so the caller can retry, push directly, or skip. The fork branch is 
script-owned and
+    force-pushed (only after _fork_owner vetted the destination), so a retry 
updates it. When a
+    backport PR is already open from it, commits may have been added there 
(fixups), so the
+    committer is asked first; declining keeps that PR untouched and returns 
its URL.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import Mock, patch
+    >>> def land(owner, created, push_error=None, pasted="", pr=7, 
body="body\\n", found=None):
+    ...     with (
+    ...         patch("builtins.input", return_value=pasted),
+    ...         patch.multiple(
+    ...             sys.modules[__name__], 
_fork_owner=Mock(side_effect=[owner]),
+    ...             FORK_REMOTE_NAME="origin",
+    ...         ),
+    ...         patch.object(git, "push", side_effect=push_error) as push,
+    ...         patch.object(git, "run", return_value=body),
+    ...         patch.object(github, "open_pr", return_value=found),
+    ...         patch.object(github, "create_pr", return_value=created) as 
create,
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         marker = _land_via_fork(pr, "branch-4.2", "PICK", 
"[SPARK-1][SQL] Fix")
+    ...     return marker, push.call_args_list, create.call_args_list
+    >>> marker, pushes, creates = land("me", {"html_url": 
"https://github.com/apache/spark/pull/9"})
+    >>> marker
+    'https://github.com/apache/spark/pull/9'
+    >>> pushes
+    [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)]
+    >>> creates[0].args[:3]
+    ('branch-4.2', 'me:backport-pr7-branch-4.2', '[SPARK-1][4.2][SQL] Fix')
+    >>> creates[0].args[3]
+    'Backport-of: #7\\n\\nbody'
+    >>> land("me", None)[0]
+    'fork:me:backport-pr7-branch-4.2'
+    >>> land("me", None, push_error=OSError("rejected"))
+    (None, [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)], [])
+    >>> land(ValueError("origin is the Apache repo"), None)
+    (None, [], [])
+    >>> land("me", None, pasted="https://github.com/apache/spark/pull/10";)[0]
+    'https://github.com/apache/spark/pull/10'
+
+    An open backport PR from that branch is only force-pushed over once the 
committer agrees:
+
+    >>> found = {"html_url": "https://github.com/apache/spark/pull/8"}
+    >>> land("me", None, pasted="n", found=found)
+    ('https://github.com/apache/spark/pull/8', [], [])
+    >>> marker, pushes, creates = land("me", found, pasted="y", found=found)
+    >>> marker, len(pushes), len(creates)
+    ('https://github.com/apache/spark/pull/8', 1, 1)
+
+    From a run on #9, itself a merged backport of #7, the new PR still names 
#7:
+
+    >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A 
<[email protected]>\\nBackport-PR: #9\\n"
+    >>> _, pushes, creates = land("me", None, pr=9, body=footer)
+    >>> pushes[0].args[2], creates[0].args[3].splitlines()[0]
+    ('backport-pr7-branch-4.2', 'Backport-of: #7')
+    >>> _backport_of(creates[0].args[3], "backport-pr7-branch-4.2", 
"branch-4.2")[::2]
+    (7, 'A <[email protected]>')
+
+    The pick's skip-checks trailer is not carried into the PR body:
+
+    >>> land("me", None, body="body\\n\\n\\nskip-checks: 
true\\n")[2][0].args[3]
+    'Backport-of: #7\\n\\nbody'
+
+    The dry-run seam fakes both effects, so a dry run takes the success branch:
+
+    >>> with redirect_stdout(StringIO()) as out:
+    ...     DryRunGit().push("origin", "PICK", "backport-pr7-branch-4.2", 
force=True)
+    ...     created = DryRunGitHub().create_pr("branch-4.2", "me:b", "t", "b")
+    >>> created["html_url"]
+    'https://github.com/apache/spark/pull/DRY-RUN'
+    >>> "would push PICK to origin:backport-pr7-branch-4.2 (forced)" in 
out.getvalue()
+    True
+    """
+    # The pick's own message is what GitHub would prefill for a single-commit 
branch. Its @s
+    # were stripped when the merge commit was built, so it fires no mention 
mails. The marker
+    # lets merge_pr keep the original message, footer and author when this PR 
is merged.
+    # merge_pr adds the skip trailer afresh, per the commit count when the PR 
merges.
+    pr_body = remove_inherited_post_merge_ci_skip(
+        git.run(["git", "log", "-1", "--format=%b", pick_branch_name])
+    ).strip()
+    # A run on a merged backport PR picks a commit whose footer names the 
original PR, and
+    # _backport_of only accepts a marker naming that one.
+    pr_num = merge_footer_pr(pr_body) or pr_num
+    pr_body = "Backport-of: #%s\n\n%s" % (pr_num, pr_body)
+    backport_branch = _backport_pr_branch(pr_num, pick_ref)
+    pr_title = _backport_pr_title(pick_ref, title)
+    push = "git push <your fork> %s:%s" % (pick_branch_name, backport_branch)
+    try:
+        owner = _fork_owner()
+    except Exception as e:
+        print_error("Could not push the pick to your fork: %s" % e)
+        return _manual_backport_pr(pick_ref, pr_title, pr_body, push=push)
+    head = "%s:%s" % (owner, backport_branch)
+    existing = github.open_pr(pick_ref, head)

Review Comment:
   **Non-blocking (P2):** `open_pr` returns `None` for a failed lookup as well 
as for no open PR, as its docstring says, so when this read fails, on a network 
error, a 5xx or a rate-limit 403, the question below is skipped and line 2416 
force-pushes `backport-pr<N>-<branch>` anyway. If that branch's backport PR is 
open and carries a fixup pushed after CI failed, the fixup disappears from the 
PR without the confirmation this change added for that case; the only sign is 
the lookup's error line printed just before the push. Telling a failed lookup 
apart from an empty result here, and asking before the push when the lookup 
failed, keeps the promise in `_land_via_fork`'s docstring, while `create_pr` 
and `pending_fork_backports` can keep reading a failure as no PR found.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60472#discussion_r4620879990), 
[2](https://github.com/apache/spark/pull/60472#pullrequestreview-5965198181).
   
   **Verification:**
   - **Regression:** A [p] landing whose open-PR lookup fails asks before 
pushing; answering no pushes nothing to the fork and opens or updates no PR, 
and answering yes force-pushes once and goes on to open or update the backport 
PR.
   - **Compatibility:** A [p] landing whose lookup finds an open PR still asks 
and keeps that PR on no, a lookup that finds no PR pushes without asking, and a 
failed lookup while opening the PR or while looking for an earlier run's 
backport PRs still reads as no PR found.



##########
dev/merge_spark_pr.py:
##########
@@ -1573,6 +1743,47 @@ def maybe_binding_policy_warning(ref: str, base_head: 
str) -> None:
     continue_maybe("Push to %s anyway? (experts only!)" % ref, True)
 
 
+# First line of a backport PR body opened by _land_via_fork; the rest is the 
pick's message.
+_BACKPORT_MARKER_RE = re.compile(r"^Backport-of: #(\d+)\n\n")
+# An @ that starts a GitHub mention, not one inside an e-mail address; see 
_pick_message.
+_MENTION_RE = re.compile(r"(?<![\w.+-])@")
+
+
+def _backport_of(body, head_ref, target_ref):
+    """(original PR, original message, primary author) if this is a backport 
PR, else None.
+
+    Needs the marker, a merge footer for that same PR, and the script's own 
head branch for
+    this target, so a body that merely quotes a footer, or pastes one into a 
PR against
+    master, is not taken for a backport. The message is read with 
_pick_message, the same
+    reading merge_pr's soft check applies to the branch's commits, so the two 
compare equal.
+
+    >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A 
<[email protected]>\\nSigned-off-by: C <[email protected]>"
+    >>> message = "Fix it.\\n\\n" + footer + "\\n(cherry picked from commit 
abc)"
+    >>> crlf = "Backport-of: #7\\r\\n\\r\\n" + message.replace("\\n", "\\r\\n")
+    >>> _backport_of(crlf, "backport-pr7-branch-4.2", "branch-4.2")[::2]
+    (7, 'A <[email protected]>')
+    >>> _backport_of("Backport-of: #7\\n\\nHi @bob.\\n\\n" + message, 
"backport-pr7-branch-4.2",
+    ...              "branch-4.2")[1].splitlines()[0]
+    'Hi bob.'
+    >>> [_backport_of(b, h, "branch-4.2") for b, h in (
+    ...     ("Backport-of: #8\\n\\n" + message, "backport-pr8-branch-4.2"),  # 
footer is #7's
+    ...     ("Backport-of: #7\\n\\n" + message, "my-feature"),  # not the 
script's branch
+    ...     (message, "backport-pr7-branch-4.2"),
+    ...     (None, "backport-pr7-branch-4.2"),
+    ... )]
+    [None, None, None, None]
+    """
+    body = (body or "").replace("\r\n", "\n")
+    m = _BACKPORT_MARKER_RE.match(body)
+    if not m or head_ref != _backport_pr_branch(m.group(1), target_ref):
+        return None
+    message = _pick_message(body[m.end() :])
+    if merge_footer_pr(message) != int(m.group(1)):
+        return None
+    authors = re.findall(r"^(?:Lead-authored-by|Authored-by): (.+)$", message, 
re.MULTILINE)
+    return int(m.group(1)), message, authors[-1]

Review Comment:
   **Nit (P3):** The footer check above accepts any line starting 
`Authored-by:` or `Lead-authored-by:` after `Closes #N from`, but this regex 
also needs a space and a value, and it searches the whole message rather than 
the footer just validated. Calling `_backport_of` on a body from 
`backport-pr7-branch-4.2` whose own footer reads `Authored-by:A <[email protected]>`, 
a bare `Authored-by:`, or `Lead-authored-by:` followed by a tab raises 
`IndexError` here, and `main()` makes that call before the merge prompt, so the 
run ends in a traceback. When the same body also quotes an earlier footer, such 
as the `Reverts:` paragraph with `Authored-by: Q <[email protected]>` that 
`merge_pr`'s doctest uses, the call returns `Q <[email protected]>` instead, and 
`merge_pr` would commit with that author and no author prompt. Only a 
hand-edited body gets here, since `[p]` always writes the line with a space. 
Reading the author from this body's own footer, and merging the PR as a regular 
one when that line cannot be read, covers 
 both:
   
   ```suggestion
       # The author of this body's own footer: a footer quoted earlier in it 
does not count.
       footer = message[message.rfind(merge_footer_trailer(m.group(1))) :]
       authors = re.findall(r"^(?:Lead-authored-by|Authored-by): (.+)$", 
footer, re.MULTILINE)
       if not authors:
           print_warning(
               "Backport-of #%s: its footer has no readable author line, so it 
is merged as a "
               "regular PR." % m.group(1)
           )
           return None
       return int(m.group(1)), message, authors[0]
   ```
   
   **Verification:**
   - **Regression:** A Backport-of body from the script's own head branch whose 
footer's author line is 'Authored-by:A <[email protected]>', a bare 'Authored-by:', or 
'Lead-authored-by:' followed by a tab is not taken for a backport and raises no 
error, also when the body quotes an earlier footer whose author line reads 
'Authored-by: Q <[email protected]>'.
   - **Compatibility:** Bodies whose footer reads 'Authored-by: A <[email protected]>' 
or 'Lead-authored-by: L <[email protected]>', including after a quoted earlier footer, 
still yield the same original PR, message and author as before.



##########
dev/pr_merge_status.py:
##########
@@ -30,12 +30,14 @@
 
 Spark merges with dev/merge_spark_pr.py rather than the GitHub button, so a 
merged PR
 shows up as "Closed" (not "Merged") with empty merge metadata, and backports 
are plain
-cherry-pick pushes. This script does not rely on that metadata. The merge 
script writes
-a closing trailer "Closes #<pr> from <author>/<branch>" into the master 
commit, and
-every cherry-pick of it to a maintenance branch retains that trailer; the 
script finds
-the commits carrying it and reports each branch that contains one. It reports 
the
-mechanical facts only -- whether a change *should* have been backported is a 
judgement
-call and is NOT made here.
+cherry-pick pushes or backport PRs that the merge script merges. This script 
does not rely
+on that metadata. The merge script writes a closing trailer "Closes #<pr> from
+<author>/<branch>" into the master commit, and every cherry-pick of it to a 
maintenance
+branch retains that trailer. A backport PR keeps the original's trailer and 
adds
+"Backport-PR: #<backport-pr>", so it is found by that number and counts for 
the original too.

Review Comment:
   **Nit (P3):** Only a backport PR that `_backport_of` recognizes keeps the 
original's trailer: one the merge script opened, with a `Backport-of: #<pr>` 
body from its `backport-pr<pr>-<branch>` head branch. `merge_pr` gives any 
other backport PR, such as one opened by hand against a release branch, its own 
`Closes #<backport-pr> from` footer (`dev/merge_spark_pr.py` line 2054), so the 
original's report does not list the branch it reached. Agents are sent to this 
tool for merge-status questions, so the description should say which backport 
PRs count for the original:
   
   ```suggestion
   branch retains that trailer. A backport PR that the merge script opened 
(body starting with
   "Backport-of: #<pr>", head branch backport-pr<pr>-<branch>) keeps the 
original's trailer and
   adds "Backport-PR: #<backport-pr>", so it is found by that number and counts 
for the original
   too. Any other backport PR gets its own "Closes" trailer and counts only for 
itself.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4582305104).
   
   **Verification:**
   - **Inspection:** The merge-status tool's module description no longer says 
that every backport PR keeps the original's trailer: it limits that to backport 
PRs whose body starts with the Backport-of marker and says other backport PRs 
are found under their own number.



##########
dev/merge_spark_pr.py:
##########
@@ -1747,67 +2088,614 @@ def merge_pr(pr_num, target_ref, title, body, 
pr_repo_desc, pr_author, co_author
     return merge_hash
 
 
-def _do_cherry_pick(pr_num, merge_hash, pick_ref, record=None):
-    """Cherry-pick `merge_hash` onto `pick_ref` and push.
+def _set_skip_trailer(skip):
+    """Amend HEAD so it carries the skip trailer exactly when `skip`; leave it 
be otherwise,
+    so a retried push sends the same commit. Reads HEAD afresh, keeping any 
amend made since.
+    """
+    current = git.run(["git", "log", "-1", "--format=%B"])
+    wanted = remove_inherited_post_merge_ci_skip(current)
+    if skip:
+        wanted = append_post_merge_ci_skip(wanted)
+    # %B ends in one more newline than the helpers return.
+    if wanted.rstrip("\n") != current.rstrip("\n"):
+        amend_commit_message(wanted)
+
+
+def _pick_message(commit_body):
+    """A backport's message as both _backport_of (from the PR body) and 
merge_pr's soft check
+    (from the branch's commits) read it: LF line ends, no skip-checks, no 
mentions, no edge
+    whitespace. Mentions are stripped as merge_pr does for any body, keeping 
the @ inside
+    e-mail addresses.
+
+    >>> _pick_message("Fix @bob\\r\\nA <[email protected]>\\n\\n\\nskip-checks: 
true\\n")
+    'Fix bob\\nA <[email protected]>'
+    """
+    body = remove_inherited_post_merge_ci_skip(commit_body.replace("\r\n", 
"\n").strip() + "\n")
+    return _MENTION_RE.sub("", body).strip()
+
+
+def _backport_pr_branch(pr_num, pick_ref):
+    """Fork branch name for a backport PR: stable, PR-traceable, 
branch-suffixed.
+
+    >>> _backport_pr_branch(123, "branch-4.2")
+    'backport-pr123-branch-4.2'
+    >>> _backport_pr_branch(9, "branch-3.5")
+    'backport-pr9-branch-3.5'
+    """
+    return "backport-pr%s-%s" % (pr_num, pick_ref)
+
+
+def _backport_pr_title(pick_ref, title):
+    """PR title for a backport PR: the merged title with its version tag set 
to the target.
+
+    The tag goes where Title.parse expects one, so the script can still merge 
the result.
+    Revert/Reapply and other unparseable titles stay verbatim.
+
+    >>> _backport_pr_title("branch-4.2", "[SPARK-1234][SQL] Fix a thing")
+    '[SPARK-1234][4.2][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.x", "[SPARK-1234][4.X][SQL] Fix a thing")
+    '[SPARK-1234][4.X][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.2", "[SPARK-1234][4.X][SQL] Fix a thing")
+    '[SPARK-1234][4.2][SQL] Fix a thing'
+    >>> _backport_pr_title("branch-4.2", "[MINOR] Fix typo")
+    '[MINOR][4.2] Fix typo'
+    >>> _backport_pr_title("branch-4.2-preview", "[MINOR] Fix typo")
+    '[MINOR] Fix typo'
+    >>> _backport_pr_title("branch-4.2", 'Revert "[SPARK-1234][SQL] Fix"')
+    'Revert "[SPARK-1234][SQL] Fix"'
+    >>> all(
+    ...     Title.parse(_backport_pr_title("branch-4.2", t))
+    ...     for t in ("[SPARK-1234][SQL] Fix", "[MINOR] Fix typo")
+    ... )
+    True
+    """
+    try:
+        parsed = Title.parse(title)
+    except ValueError:
+        return title
+    version = pick_ref[len("branch-") :].upper()
+    if not _VERSION_TAG_RE.match(version):
+        return title
+    others = [c for c in parsed.components if not _VERSION_TAG_RE.match(c)]
+    return str(Title(parsed.leading, [version] + others, parsed.text))
+
+
+def _remote_repo(url):
+    """`owner/repo` named by a git remote URL, or None.
+
+    >>> _remote_repo("[email protected]:me/spark.git")
+    'me/spark'
+    >>> _remote_repo("https://github.com/apache/spark.git";)
+    'apache/spark'
+    >>> _remote_repo("ssh://[email protected]:443/me/spark.git")
+    'me/spark'
+    >>> _remote_repo("git@github-work:me/spark")
+    'me/spark'
+    >>> _remote_repo("https://gitbox.apache.org/repos/asf/spark.git";)
+    'asf/spark'
+    >>> _remote_repo("") is None
+    True
+    """
+    m = re.search(r"[:/]([^/:]+)/([^/:]+?)(?:\.git)?/?$", url)
+    return "%s/%s" % m.groups() if m else None
+
+
+def _remote_url(name):
+    try:
+        return git.run(["git", "remote", "get-url", name]).strip()
+    except Exception:
+        return ""
+
+
+def _remote_push_urls(name):
+    # Where `git push <name>` really goes: pushurl and pushInsteadOf apply.
+    try:
+        return git.run(["git", "remote", "get-url", "--push", "--all", 
name]).split()
+    except Exception:
+        return []
+
+
+def _fork_owner(pushing=True):
+    """GitHub owner of the fork remote, for a backport PR's `head`. ValueError 
if unusable.
 
-    Returns the (pushed ref, pushed commit hash) pair, which `record` also 
gets, right after
-    the push and before the cleanup that can raise. Raises `SkipCherryPick` 
when the
-    committer declines to resolve a conflict, after aborting the pick, or 
declines a pre-push
-    check. The pick is committed by then, so nothing is aborted: it and its 
temporary branch
-    are discarded, and uncommitted edits must be stashed first (see 
continue_maybe).
+    The fork is checked by the repository its URL names, not the remote name: 
an `origin` that
+    was never repointed off apache/spark would otherwise get the backport 
branch and the PR.
+    A read-only caller passes pushing=False to skip the push-URL check.
 
-    Both pre-push checks run once, in order, before the push prompt; the 
binding-policy one
-    gets the target branch and its tip from before the pick. A declined check 
pushes nothing:
+    The env knobs are pinned so a committer's own settings cannot fail these 
at startup:
+
+    >>> from unittest.mock import patch
+    >>> def remotes(fork, owner=""):
+    ...     urls = {"apache": "https://gitbox.apache.org/repos/asf/spark.git";,
+    ...             "apache-github": "https://github.com/apache/spark.git";, 
"origin": fork}
+    ...     return patch.multiple(sys.modules[__name__], _remote_url=urls.get, 
FORK_OWNER=owner,
+    ...                           FORK_REMOTE_NAME="origin", 
PUSH_REMOTE_NAME="apache",
+    ...                           PR_REMOTE_NAME="apache-github")
+    >>> def owner_of(fork, owner="", push=None):
+    ...     pushes = patch.object(sys.modules[__name__], "_remote_push_urls",
+    ...                           lambda name: [fork] if push is None else 
push)
+    ...     with remotes(fork, owner), pushes:
+    ...         try:
+    ...             return _fork_owner()
+    ...         except ValueError as e:
+    ...             return "refused" if "is the Apache repo" in str(e) else 
str(e)
+    >>> owner_of("ssh://[email protected]:443/me/spark.git")
+    'me'
+    >>> [owner_of(f, owner="me") for f in (
+    ...     "[email protected]:apache/spark.git",
+    ...     "https://gitbox.apache.org/repos/asf/spark.git";,
+    ...     "git@gh:Apache/Spark",
+    ... )]
+    ['refused', 'refused', 'refused']
+
+    The branch goes to the push URLs, so they must name the fork too:
+
+    >>> apache = "[email protected]:apache/spark.git"
+    >>> "pushes to " + apache in owner_of("[email protected]:me/spark.git", 
push=[apache])
+    True
+    >>> owner_of("[email protected]:me/spark.git", 
push=["https://github.com/Me/spark.git";])
+    'me'
+
+    A github.com URL names its owner; FORK_OWNER only fills in for a host 
alias:
+
+    >>> owner_of("[email protected]:me/spark.git", owner="someone-else")
+    'me'
+    >>> owner_of("git@gh-alias:me/spark.git", owner="Me")
+    'Me'
+    >>> owner_of("git@gh-alias:me/spark.git").startswith("Cannot tell the 
GitHub owner")
+    True
+    """
+    url = _remote_url(FORK_REMOTE_NAME)
+    repo = _remote_repo(url)
+    if repo is None:
+        raise ValueError(
+            "No usable %s remote (%r). Set FORK_REMOTE_NAME to your fork's 
remote."
+            % (FORK_REMOTE_NAME, url)
+        )
+    apache = {"apache/spark"} | {
+        (_remote_repo(_remote_url(r)) or "").lower() for r in 
(PUSH_REMOTE_NAME, PR_REMOTE_NAME)
+    }
+    if repo.lower() in apache:
+        raise ValueError(
+            "%s remote (%s) is the Apache repo, not a fork. Set 
FORK_REMOTE_NAME to your "
+            "fork's remote." % (FORK_REMOTE_NAME, url)
+        )
+    for push_url in _remote_push_urls(FORK_REMOTE_NAME) if pushing else []:
+        if (_remote_repo(push_url) or "").lower() != repo.lower():
+            raise ValueError(
+                "%s remote fetches from %s but pushes to %s. Point both at 
your fork."
+                % (FORK_REMOTE_NAME, url, push_url)
+            )
+    if "github.com" in url:
+        return repo.split("/")[0]
+    if FORK_OWNER:
+        return FORK_OWNER
+    raise ValueError(
+        "Cannot tell the GitHub owner of %s remote (%s); set FORK_OWNER to 
your GitHub login."
+        % (FORK_REMOTE_NAME, url)
+    )
+
+
+def _landing_choice(pick_branch_name, pick_ref):
+    """Ask how a finished pick lands: [d]irect push, [p] fork + PR, or [s]kip 
(default).
+
+    Only asked with --prompt-for-branches-during-backport; without it 
_do_cherry_pick keeps the
+    plain continue_maybe push prompt.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import patch
+    >>> def choose(answer):
+    ...     with patch("builtins.input", return_value=answer), 
redirect_stdout(StringIO()):
+    ...         return _landing_choice("PR_TOOL_PICK_PR_1_BRANCH-4.2", 
"branch-4.2")
+    >>> choose(""), choose("p"), choose("d")
+    ('s', 'p', 'd')
+    """
+    return get_input(
+        "Pick complete (local ref %s). How should it land?\n"
+        "  [d] Push directly to %s/%s\n"
+        "  [p] Push to your fork (%s) and open a backport PR against %s (for 
CI)\n"
+        "  [s] Skip this branch (default)\n"
+        "Choose [d/p/s]: "
+        % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref, FORK_REMOTE_NAME, 
pick_ref),
+        {"d": ["d", "direct"], "p": ["p", "pr"], "s": ["s", "skip", ""]},
+    )
+
+
+def _land_via_fork(pr_num, pick_ref, pick_branch_name, title):
+    """Push the pick to the fork and open a backport PR against `pick_ref`.
+
+    Returns the PR URL, or a `fork:<owner>:<branch>` marker if the push worked 
but the PR did
+    not open. Either failure offers _manual_backport_pr, whose pasted URL 
wins. Returns None,
+    having pushed nothing, when the fork is unusable or the push fails and no 
URL was pasted,
+    so the caller can retry, push directly, or skip. The fork branch is 
script-owned and
+    force-pushed (only after _fork_owner vetted the destination), so a retry 
updates it. When a
+    backport PR is already open from it, commits may have been added there 
(fixups), so the
+    committer is asked first; declining keeps that PR untouched and returns 
its URL.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import Mock, patch
+    >>> def land(owner, created, push_error=None, pasted="", pr=7, 
body="body\\n", found=None):
+    ...     with (
+    ...         patch("builtins.input", return_value=pasted),
+    ...         patch.multiple(
+    ...             sys.modules[__name__], 
_fork_owner=Mock(side_effect=[owner]),
+    ...             FORK_REMOTE_NAME="origin",
+    ...         ),
+    ...         patch.object(git, "push", side_effect=push_error) as push,
+    ...         patch.object(git, "run", return_value=body),
+    ...         patch.object(github, "open_pr", return_value=found),
+    ...         patch.object(github, "create_pr", return_value=created) as 
create,
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         marker = _land_via_fork(pr, "branch-4.2", "PICK", 
"[SPARK-1][SQL] Fix")
+    ...     return marker, push.call_args_list, create.call_args_list
+    >>> marker, pushes, creates = land("me", {"html_url": 
"https://github.com/apache/spark/pull/9"})
+    >>> marker
+    'https://github.com/apache/spark/pull/9'
+    >>> pushes
+    [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)]
+    >>> creates[0].args[:3]
+    ('branch-4.2', 'me:backport-pr7-branch-4.2', '[SPARK-1][4.2][SQL] Fix')
+    >>> creates[0].args[3]
+    'Backport-of: #7\\n\\nbody'
+    >>> land("me", None)[0]
+    'fork:me:backport-pr7-branch-4.2'
+    >>> land("me", None, push_error=OSError("rejected"))
+    (None, [call('origin', 'PICK', 'backport-pr7-branch-4.2', force=True)], [])
+    >>> land(ValueError("origin is the Apache repo"), None)
+    (None, [], [])
+    >>> land("me", None, pasted="https://github.com/apache/spark/pull/10";)[0]
+    'https://github.com/apache/spark/pull/10'
+
+    An open backport PR from that branch is only force-pushed over once the 
committer agrees:
+
+    >>> found = {"html_url": "https://github.com/apache/spark/pull/8"}
+    >>> land("me", None, pasted="n", found=found)
+    ('https://github.com/apache/spark/pull/8', [], [])
+    >>> marker, pushes, creates = land("me", found, pasted="y", found=found)
+    >>> marker, len(pushes), len(creates)
+    ('https://github.com/apache/spark/pull/8', 1, 1)
+
+    From a run on #9, itself a merged backport of #7, the new PR still names 
#7:
+
+    >>> footer = "Closes #7 from a/b.\\n\\nAuthored-by: A 
<[email protected]>\\nBackport-PR: #9\\n"
+    >>> _, pushes, creates = land("me", None, pr=9, body=footer)
+    >>> pushes[0].args[2], creates[0].args[3].splitlines()[0]
+    ('backport-pr7-branch-4.2', 'Backport-of: #7')
+    >>> _backport_of(creates[0].args[3], "backport-pr7-branch-4.2", 
"branch-4.2")[::2]
+    (7, 'A <[email protected]>')
+
+    The pick's skip-checks trailer is not carried into the PR body:
+
+    >>> land("me", None, body="body\\n\\n\\nskip-checks: 
true\\n")[2][0].args[3]
+    'Backport-of: #7\\n\\nbody'
+
+    The dry-run seam fakes both effects, so a dry run takes the success branch:
+
+    >>> with redirect_stdout(StringIO()) as out:
+    ...     DryRunGit().push("origin", "PICK", "backport-pr7-branch-4.2", 
force=True)
+    ...     created = DryRunGitHub().create_pr("branch-4.2", "me:b", "t", "b")
+    >>> created["html_url"]
+    'https://github.com/apache/spark/pull/DRY-RUN'
+    >>> "would push PICK to origin:backport-pr7-branch-4.2 (forced)" in 
out.getvalue()
+    True
+    """
+    # The pick's own message is what GitHub would prefill for a single-commit 
branch. Its @s
+    # were stripped when the merge commit was built, so it fires no mention 
mails. The marker
+    # lets merge_pr keep the original message, footer and author when this PR 
is merged.
+    # merge_pr adds the skip trailer afresh, per the commit count when the PR 
merges.
+    pr_body = remove_inherited_post_merge_ci_skip(
+        git.run(["git", "log", "-1", "--format=%b", pick_branch_name])
+    ).strip()
+    # A run on a merged backport PR picks a commit whose footer names the 
original PR, and
+    # _backport_of only accepts a marker naming that one.
+    pr_num = merge_footer_pr(pr_body) or pr_num
+    pr_body = "Backport-of: #%s\n\n%s" % (pr_num, pr_body)
+    backport_branch = _backport_pr_branch(pr_num, pick_ref)
+    pr_title = _backport_pr_title(pick_ref, title)
+    push = "git push <your fork> %s:%s" % (pick_branch_name, backport_branch)
+    try:
+        owner = _fork_owner()
+    except Exception as e:
+        print_error("Could not push the pick to your fork: %s" % e)
+        return _manual_backport_pr(pick_ref, pr_title, pr_body, push=push)
+    head = "%s:%s" % (owner, backport_branch)
+    existing = github.open_pr(pick_ref, head)
+    if existing:
+        prompt = (
+            "Backport PR %s is already open from %s. Force-push this pick over 
it? Commits "
+            "added to it since it was opened, such as fixups, are lost."
+            % (existing["html_url"], head)
+        )
+        if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
+            print("Keeping %s as it is." % existing["html_url"])
+            return existing["html_url"]
+    try:
+        git.push(FORK_REMOTE_NAME, pick_branch_name, backport_branch, 
force=True)
+    except Exception as e:
+        print_error("Could not push the pick to your fork: %s" % e)
+        return _manual_backport_pr(pick_ref, pr_title, pr_body, push=push)
+    created = github.create_pr(pick_ref, head, pr_title, pr_body)
+    if created and created.get("html_url"):
+        print("Backport PR for #%s against %s: %s" % (pr_num, pick_ref, 
created["html_url"]))
+        return created["html_url"]
+    print_error("Backport PR was not opened (see above); the pick is on %s." % 
head)
+    return _manual_backport_pr(pick_ref, pr_title, pr_body, head=head) or 
"fork:%s" % head
+
+
+def _manual_backport_pr(pick_ref, title, body, push=None, head=None):
+    """Walk the committer through opening the backport PR by hand; the URL 
pasted, or None.
+
+    `push` is the command still needed to get the pick onto the fork; `head` 
is the fork
+    branch when it is already there.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import patch
+    >>> with (
+    ...     patch("builtins.input", 
return_value="https://github.com/apache/spark/pull/9";),
+    ...     redirect_stdout(StringIO()) as out,
+    ... ):
+    ...     url = _manual_backport_pr("branch-4.2", "T", "Backport-of: #7", 
head="me:b")
+    >>> url
+    'https://github.com/apache/spark/pull/9'
+    >>> "compare/branch-4.2...me:b?expand=1" in out.getvalue()
+    True
+    >>> with patch("builtins.input", return_value=""), 
redirect_stdout(StringIO()) as out:
+    ...     url = _manual_backport_pr("branch-4.2", "T", "B", push="git push 
<your fork> P:b")
+    >>> url is None, "git push <your fork> P:b" in out.getvalue()
+    (True, True)
+    """
+    print("To open the backport PR by hand, against %s:" % pick_ref)
+    if push:
+        print("  %s  (before you skip: the local ref goes away with it)" % 
push)
+        print("  then open a PR from that branch")
+    if head:
+        print("  https://github.com/apache/spark/compare/%s...%s?expand=1"; % 
(pick_ref, head))
+    print(
+        "Title:\n%s\nBody (keep the Backport-of line; merging with this script 
uses it to "
+        "keep the original author):\n%s" % (title, body)
+    )
+    url = get_input(
+        "Paste the backport PR URL once it is open (Enter to skip): ",
+        r"^(https://github\.com/apache/spark/pull/\d+)?$",
+        ignore_case=False,
+    )
+    return url or None
+
+
+def _landed(marker):
+    """Whether a pick's marker means it landed on the Apache branch.
+
+    A direct push returns a bare commit hash (landed); the backport-PR paths 
return a PR URL
+    (`https://`) or a `fork:` marker (PR not opened), both pending.
+
+    >>> [_landed(m) for m in ("deadbeef", "https://x/pull/9";, 
"fork:o:backport-pr1-branch-4.2")]
+    [True, False, False]
+    """
+    return not marker.startswith(("https://";, "fork:"))
+
+
+class _PickLedger:
+    """Where the change is during a run, for main()'s two pick loops.
+
+    `landed` (the merge sink, footer branches, direct pushes) drives 
Upstream-First and JIRA
+    fix versions, so neither treats an open backport PR as having the change. 
`pending` maps
+    branches with only a backport PR, from this run or an earlier one, to 
their markers.
+    `seen()` is both, kept out of the prompt default. `commits` is this run's 
picks.
+
+    >>> picks = _PickLedger(["master"], pending={"branch-4.1": 
"https://x/pull/8"})
+    >>> picks.record([("branch-4.x", "abc"), ("branch-4.3", 
"https://x/pull/9";)])
+    >>> picks.record([("branch-4.2", "fork:me:backport-pr7-branch-4.2")])
+    >>> picks.landed, sorted(picks.pending)
+    (['master', 'branch-4.x'], ['branch-4.1', 'branch-4.2', 'branch-4.3'])
+    >>> sorted(picks.seen())
+    ['branch-4.1', 'branch-4.2', 'branch-4.3', 'branch-4.x', 'master']
+    >>> [ref for ref, _ in picks.commits]
+    ['branch-4.x', 'branch-4.3', 'branch-4.2']
+    >>> picks.record([("branch-4.1", "def")])
+    >>> picks.landed[-1], "branch-4.1" in picks.pending
+    ('branch-4.1', False)
+    """
+
+    def __init__(self, landed, pending=None):
+        self.landed = list(landed)
+        self.pending = dict(pending or {})
+        self.commits = []
+
+    def seen(self):
+        return tuple(self.landed) + tuple(self.pending)
+
+    def record(self, picked):
+        for ref, marker in picked:
+            if _landed(marker):
+                self.landed.append(ref)
+                self.pending.pop(ref, None)
+            else:
+                self.pending[ref] = marker
+        self.commits += picked
+
+
+def _finish_landed(record, pair):
+    """Record a landed pick, then leave its branch. Both can fail or stop the 
run ([a]bort),
+    so the pick is recorded first."""
+    if record:
+        record(pair)
+    _restore_original_head()
+    clean_up()
+
+
+def _do_cherry_pick(pr_num, merge_hash, pick_ref, title="", 
pending_sibling=None, record=None):
+    """Cherry-pick `merge_hash` onto `pick_ref` and land it.
+
+    Returns (pick_ref, marker), where the marker says how it landed (see 
_landed):
+    a commit hash for a direct push (landed), a PR URL for a backport PR, or
+    `fork:<owner>:<branch>` when the fork push worked but the PR did not open 
(both pending).
+    `record` gets that pair as soon as it lands, before the checkout and 
cleanup that follow.
+    `pending_sibling` is the (branch-M.x, marker) whose backport is only 
pending; a direct push
+    then needs an explicit maintenance-only confirmation. Raises 
`SkipCherryPick` when the
+    committer declines to resolve a conflict (after aborting the pick), 
declines the
+    binding-policy or compile-check prompt, or answers [s]kip at the landing 
prompt. Past the
+    conflict nothing is aborted: the committed pick and its temporary branch 
are discarded,
+    and uncommitted edits must be stashed first (see continue_maybe). A failed 
fork landing
+    or direct push returns to the landing prompt with the pick kept.
 
     >>> from contextlib import redirect_stdout
     >>> from io import StringIO
     >>> from unittest.mock import Mock, call, patch
-    >>> last_policy_call = last_record_call = None
-    >>> def pick(**effects):
-    ...     steps = Mock()
-    ...     steps.prompt.return_value = "y"
-    ...     for name, effect in effects.items():
-    ...         getattr(steps, name).side_effect = effect
+    >>> policy, compile_check = Mock(), Mock()
+    >>> def land(answers, via_fork=(), push_error=None):
     ...     tip = ["pre\\n"]
     ...     def run(cmd):
     ...         if "cherry-pick" in cmd:
-    ...             tip[0] = "post\\n"
+    ...             tip[0] = "head\\n"
     ...         return tip[0]
     ...     with (
-    ...         patch("builtins.input", steps.prompt),
+    ...         patch("builtins.input", side_effect=answers),
     ...         patch.object(git, "run", side_effect=run),
+    ...         patch.object(
+    ...             sys.modules[__name__], "should_skip_post_merge_ci", 
return_value=False
+    ...         ),
+    ...         patch.object(git, "push", side_effect=push_error) as push,
+    ...         patch.multiple(sys.modules[__name__], 
maybe_binding_policy_warning=policy,
+    ...                        maybe_compile_check=compile_check, 
clean_up=Mock(),
+    ...                        _land_via_fork=Mock(side_effect=via_fork),
+    ...                        PROMPT_FOR_BRANCHES_DURING_BACKPORT=True),
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         try:
+    ...             return _do_cherry_pick(1, "feed", "branch-4.2"), 
push.call_args_list
+    ...         except SkipCherryPick:
+    ...             return "skipped", push.call_args_list
+    >>> land(["p"], via_fork=["https://x/pull/9";])
+    (('branch-4.2', 'https://x/pull/9'), [])
+    >>> land(["p", "s"], via_fork=[None])
+    ('skipped', [])
+    >>> result, pushes = land(["d"])
+    >>> result, pushes == [call(PUSH_REMOTE_NAME, 
"PR_TOOL_PICK_PR_1_BRANCH-4.2", "branch-4.2")]
+    (('branch-4.2', 'head'), True)
+    >>> land(["d", "s"], push_error=OSError("rejected"))[0]
+    'skipped'
+
+    Each pre-push check ran once per pick, the binding-policy one against the 
pre-pick head:
+
+    >>> policy.call_args_list == [call("branch-4.2", "pre")] * 4
+    True
+    >>> compile_check.call_args_list == [call(pushes[0].args[1])] * 4
+    True
+
+    Every exit restores the original checkout, waiting out local edits, before 
cleaning up. A
+    landing is recorded before both, so a refused checkout or an [a]bort there 
loses nothing;
+    a skip, and a landing that fails, record nothing:
+
+    >>> def leaves(answers, via_fork=("https://x/pull/9";,), **effects):
+    ...     steps = Mock()
+    ...     steps.fork.side_effect = via_fork
+    ...     for name, effect in effects.items():
+    ...         getattr(steps, name).side_effect = effect
+    ...     with (
+    ...         patch("builtins.input", side_effect=answers),
+    ...         patch.object(git, "run", return_value="abc\\n"),
     ...         patch.object(git, "push", steps.push),
-    ...         patch.multiple(sys.modules[__name__], clean_up=steps.clean_up,
+    ...         patch.multiple(sys.modules[__name__], 
maybe_binding_policy_warning=Mock(),
+    ...                        maybe_compile_check=Mock(), 
clean_up=steps.clean_up,
+    ...                        _restore_original_head=steps.restore, 
_land_via_fork=steps.fork,
     ...                        
should_skip_post_merge_ci=Mock(return_value=False),
-    ...                        maybe_compile_check=steps.compile,
-    ...                        maybe_binding_policy_warning=steps.policy),
+    ...                        PROMPT_FOR_BRANCHES_DURING_BACKPORT=True),
     ...         redirect_stdout(StringIO()),
     ...     ):
     ...         try:
-    ...             result = _do_cherry_pick(1, "feed", "branch-4.2", 
steps.record)
-    ...         except SkipCherryPick:
-    ...             result = "skipped"
-    ...         except (SystemExit, subprocess.CalledProcessError) as e:
-    ...             result = type(e).__name__
-    ...     global last_policy_call, last_record_call
-    ...     last_policy_call, last_record_call = steps.policy.call_args, 
steps.record.call_args
-    ...     return result, [name for name, _, _ in steps.mock_calls]
-    >>> pick()
-    (('branch-4.2', 'post'), ['policy', 'compile', 'prompt', 'push', 'record', 
'clean_up'])
-    >>> last_record_call
-    call(('branch-4.2', 'post'))
-    >>> pick(compile=SkipCherryPick())
-    ('skipped', ['policy', 'compile'])
-    >>> last_policy_call
-    call('branch-4.2', 'pre')
-
-    A push that lands is recorded before the cleanup after it, so a cleanup 
that raises loses
-    nothing; a push that fails is not recorded:
-
-    >>> pick(clean_up=subprocess.CalledProcessError(1, "git checkout"))
-    ('CalledProcessError', ['policy', 'compile', 'prompt', 'push', 'record', 
'clean_up'])
-    >>> pick(push=OSError("no route"))
-    ('SystemExit', ['policy', 'compile', 'prompt', 'push', 'clean_up'])
+    ...             _do_cherry_pick(1, "feed", "branch-4.2", 
record=steps.record)
+    ...         except (SkipCherryPick, SystemExit):
+    ...             pass
+    ...     return [name for name, _, _ in steps.mock_calls], [
+    ...         c.args[0] for c in steps.record.call_args_list]
+    >>> leaves(["s"])
+    (['restore', 'clean_up'], [])
+    >>> leaves(["p"])
+    (['fork', 'record', 'restore', 'clean_up'], [('branch-4.2', 
'https://x/pull/9')])
+    >>> leaves(["d"])
+    (['push', 'record', 'restore', 'clean_up'], [('branch-4.2', 'abc')])
+    >>> leaves(["p", "s"], via_fork=[None])
+    (['fork', 'restore', 'clean_up'], [])
+    >>> leaves(["d", "s"], push=OSError("rejected"))
+    (['push', 'restore', 'clean_up'], [])
+    >>> leaves(["d"], restore=SystemExit(-1))
+    (['push', 'record', 'restore'], [('branch-4.2', 'abc')])
+    >>> leaves(["p"], restore=SystemExit(-1))
+    (['fork', 'record', 'restore'], [('branch-4.2', 'https://x/pull/9')])
+
+    A sampled pick carries the skip trailer only when pushed to apache, so [p] 
always sends
+    the fork a head without it. Both keep an amend the committer made during 
the checks.
+
+    >>> amends = []
+    >>> def sampled(answers, push_error=None):
+    ...     amends.clear()
+    ...     head = {"message": "Fix\\n\\nCloses #1 from a/b.\\n"}
+    ...     def committer_amends(*args):  # e.g. after the dirty-tree warning
+    ...         head["message"] = "Fixed\\n\\nCloses #1 from a/b.\\n"
+    ...     def run(cmd):
+    ...         if cmd[:3] == ["git", "commit", "--amend"]:
+    ...             assert "--only" in cmd, cmd  # staged edits stay out of 
the push
+    ...             amends.append(cmd)
+    ...             head["message"] = cmd[-1]
+    ...         return head["message"] + "\\n" if "--format=%B" in cmd else 
"head\\n"
+    ...     pushed = []
+    ...     def push(remote, *args, force=False):
+    ...         where = "apache" if remote == PUSH_REMOTE_NAME and not force 
else remote
+    ...         message = head["message"]
+    ...         pushed.append((where, 
message.count(POST_MERGE_CI_SKIP_TRAILER), message[:5]))
+    ...         if push_error and len(pushed) == 1:
+    ...             raise push_error
+    ...     def fork(*args):
+    ...         push("fork")
+    ...         return "https://x/pull/9";
+    ...     with (
+    ...         patch("builtins.input", side_effect=answers),
+    ...         patch.object(git, "run", side_effect=run),
+    ...         patch.object(git, "push", side_effect=push),
+    ...         patch.multiple(sys.modules[__name__], 
maybe_binding_policy_warning=Mock(),
+    ...                        maybe_compile_check=committer_amends, 
clean_up=Mock(),
+    ...                        
should_skip_post_merge_ci=Mock(return_value=True),
+    ...                        _land_via_fork=fork, 
PROMPT_FOR_BRANCHES_DURING_BACKPORT=True),
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         _do_cherry_pick(1, "feed", "branch-4.x")
+    ...     return pushed
+    >>> sampled(["p"]), len(amends)
+    ([('fork', 0, 'Fixed')], 0)
+    >>> sampled(["d"]), len(amends)
+    ([('apache', 1, 'Fixed')], 1)
+
+    A retried [d] pushes the same commit, in case the failed push did land:
+
+    >>> sampled(["d", "d"], push_error=OSError("rejected")), len(amends)
+    ([('apache', 1, 'Fixed'), ('apache', 1, 'Fixed')], 1)
+    >>> sampled(["d", "p"], push_error=OSError("rejected"))
+    [('apache', 1, 'Fixed'), ('fork', 0, 'Fixed')]
+
+    Without --prompt-for-branches-during-backport the push prompt is the plain 
y/N one: N
+    skips the branch, and a failed push ends the run instead of asking again:
+
+    >>> def plain(answer, push_error=None):
+    ...     with (
+    ...         patch("builtins.input", return_value=answer),
+    ...         patch.object(git, "run", return_value="abc\\n"),
+    ...         patch.object(git, "push", side_effect=push_error) as push,
+    ...         patch.multiple(sys.modules[__name__], 
maybe_binding_policy_warning=Mock(),
+    ...                        maybe_compile_check=Mock(), clean_up=Mock(),
+    ...                        _restore_original_head=Mock(), 
_land_via_fork=Mock(),
+    ...                        
should_skip_post_merge_ci=Mock(return_value=False)),
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         try:
+    ...             return _do_cherry_pick(1, "feed", "branch-4.2"), 
push.call_count
+    ...         except (SkipCherryPick, SystemExit) as e:
+    ...             return type(e).__name__, push.call_count
+    >>> plain("y"), plain("n"), plain("y", push_error=OSError("rejected"))

Review Comment:
   **Nit (P3):** This is the only case that exercises the push prompt without 
`--prompt-for-branches-during-backport`, the path every committer takes by 
default, and it passes no `record`, turns sampling off and checks only the 
returned pair and the push count. `land()`, `leaves()` and `sampled()` all 
patch the flag on, no case in either mode has a pre-push check decline, and 
`sampled()` answers every `git rev-parse` with the same `head`. So no doctest 
would fail if the flag-off exit stopped recording its pick, which drops it from 
the merge summary and the JIRA fix versions, or recorded it only after the 
cleanup; if a sampled flag-off push lost its skip trailer; if a declined 
compile check still landed the pick; or if the pushed hash were read before the 
landing-time amend. The merge base's `pick()` doctest asserted the order, the 
recorded pair and a declined check for the then only landing path, and because 
CI skips `dev/` maintainer tools, these startup doctests are the script's on
 ly regression signal.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4582305067).
   
   **Verification:**
   - **Regression:** With the flag off, a landed push hands its pair to the 
record callback before the checkout is restored and the temporary branches are 
cleaned up, and a failed push records nothing; removing or reordering that 
record makes a case fail.
   - **Regression:** A sampled pick pushed with the flag off carries exactly 
one skip trailer, and a sampled direct push, with the flag off or through [d], 
returns and records the commit the landing-time amend created rather than the 
one before it.
   - **Regression:** When the binding-policy check or the compile check raises 
SkipCherryPick, nothing is pushed to the Apache remote or the fork and nothing 
is recorded, with the flag off and with it on.



##########
dev/merge_spark_pr.py:
##########
@@ -1856,30 +2744,70 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref, 
record=None):
         else:
             print("Cherry-pick already completed manually; continuing with the 
backport.")
 
-    raw_message = git.run(["git", "log", "-1", "--format=%B"])
-    updated_message = remove_inherited_post_merge_ci_skip(raw_message)
-    if skip_post_merge_ci:
-        updated_message = append_post_merge_ci_skip(updated_message)
-    if updated_message != raw_message:
-        amend_commit_message(updated_message)
+    _set_skip_trailer(False)
 
     maybe_binding_policy_warning(pick_ref, pick_head)
     maybe_compile_check(pick_branch_name)
 
-    continue_maybe(
-        "Pick complete (local ref %s). Push to %s?" % (pick_branch_name, 
PUSH_REMOTE_NAME)
-    )
+    if not PROMPT_FOR_BRANCHES_DURING_BACKPORT:
+        # The fork is never used: N skips this branch and a failed push ends 
the run, as
+        # before the backport-PR path existed.
+        continue_maybe(
+            "Pick complete (local ref %s). Push to %s?" % (pick_branch_name, 
PUSH_REMOTE_NAME),
+            True,

Review Comment:
   **Nit (P3):** With the `cherry` argument, N or Enter at this prompt restores 
the checkout, prints `Skipping this cherry-pick; the merge continues.` and goes 
on to the next-branch question, so the run can end with status 0; the base 
branch called `continue_maybe` without it, so declining printed `Okay, exiting` 
and ended the run with status -1. Nothing is pushed either way, but the flag's 
off state no longer matches the base branch, although the reply to the 
maintainer's review said the flag-off path would go back to `continue_maybe`, 
and the comment above and the `plain()` doctest present the skip as the old 
behavior. Dropping the argument restores the exit. The script refuses to start 
when a doctest fails, so update `plain()` with it: the second entry of the 
expected tuple at line 2698 becomes `('SystemExit', 0)`, and the prose at lines 
2679-2680 should say that N ends the run.
   
   ```suggestion
           # The fork is never used: declining, like a failed push, ends the 
run, as before the
           # backport-PR path existed.
           continue_maybe(
               "Pick complete (local ref %s). Push to %s?" % (pick_branch_name, 
PUSH_REMOTE_NAME),
   ```
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60472#discussion_r4620880016), 
[2](https://github.com/apache/spark/pull/60472#pullrequestreview-5965198181).
   
   **Verification:**
   - **Regression:** With the flag off, declining the push prompt with N and 
with Enter ends the run with exit status -1 and pushes nothing, as on the base 
branch.
   - **Compatibility:** With the flag off, answering y pushes the pick once and 
returns it, and a failed push ends the run; with the flag on, [s] at the 
landing prompt still skips only that branch and the run continues to the 
next-branch prompt.



##########
dev/merge_spark_pr.py:
##########
@@ -4119,21 +5277,26 @@ def record(pair):
                     default,
                     branch_names,
                     target_ref,
-                    already_picked=tuple(picked_refs),
-                    record=record,
+                    already_picked=tuple(picks.landed),
+                    title=title,
+                    pending=picks.pending,
+                    record=lambda pair: picks.record([pair]),
                 )
                 prompt = "Would you like to pick %s into another branch?" % 
merge_hash
                 if get_input(f"\n{prompt} (y/N): ", ["y", "n", ""]) != "y":
                     break
         finally:
             # Report whatever was pushed even if a later pick is aborted, 
since the earlier
-            # pushes have already landed.
-            if picked_commits:
-                post_merge_comment(pr_num, picked_commits)
+            # pushes have already happened.
+            if picks.commits:
+                post_merge_comment(pr_num, picks.commits)
+                if str(original) != str(pr_num):

Review Comment:
   **Nit (P3):** `original` differs from `pr_num` whenever the found commit's 
footer names another PR, which also happens when `find_merge_commit` returns 
the closed-event commit of another PR's merge, the case `committed_title`'s 
docstring describes. A backport run on `#1` whose found commit is `#3`'s merge, 
made from a body that said `Closes #1`, would post `**Merge Summary (via 
backport PR #1):**` on `#3` and notify its participants, although `#1` is not a 
backport of `#3`; the base branch posted only on the PR being run. Seeding from 
the footer's PR still matches the commit being picked, so only this comment 
needs the stricter condition that the commit's final `Backport-PR` trailer 
names this PR, which `has_merge_footer` checks once `original` names another PR:
   
   ```suggestion
                   if str(original) != str(pr_num) and 
has_merge_footer(message, pr_num):
   ```
   
   **Verification:**
   - **Regression:** For a closed PR whose found commit is another PR's merge 
without a Backport-PR trailer, a run that records a pick posts exactly one 
summary, on the PR being run, without a via label.
   - **Behavior:** For a merged backport PR whose final trailer names it, a run 
that records a pick posts its summary on itself and a summary headed with its 
number on the original PR.
   - **Regression:** For a regular merged PR whose footer names itself, a run 
that records a pick posts exactly one summary, so comparing the two PR numbers 
without normalizing their integer and string forms would make the case fail.



##########
dev/pr_merge_status.py:
##########
@@ -194,6 +200,23 @@ def display_key(name):
 
 
 def main():
+    """Prints where the PR in argv landed.

Review Comment:
   **Nit (P3):** Nothing executes this doctest: the entry point at line 276 
only calls `main()`, `dev/sparktestsupport/modules.py` lists this file among 
the maintainer tools CI ignores, and the always-run 
`dev/sparktestsupport/tests/test_doctests.py` collects only `sparktestsupport` 
modules. The two tools that share the footer reader run theirs, 
`dev/merge_spark_pr.py` before `main()` and `dev/spark_merge_footer.py` when 
executed, so reverting the not-merged line would fail this doctest only for 
someone who runs `python3 -m doctest` on the file. Running `doctest.testmod()` 
from the entry point before `main()`, and exiting non-zero when it fails, as 
the merge script does, makes it a real guard; the doctest already replaces `gh` 
and `git`, so it needs no network.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4582305104).
   
   **Verification:**
   - **Regression:** With the not-merged line changed to name only the Closes 
footer, running the merge-status tool exits non-zero on the doctest failure 
before reporting anything.
   - **Compatibility:** With its doctests passing, the merge-status tool prints 
the same report and returns the same exit status as before for an open PR, a 
merged PR and a PR closed without merging.



-- 
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]

Reply via email to