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


##########
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:
   **Non-blocking (P2):** This runs only after `_do_cherry_pick` returns, and 
both landing exits call a plain `clean_up()` first: `[d]` right after the push 
to apache, `[p]` once `_land_via_fork` returns a marker. `clean_up()` starts 
with `git checkout <original_head>` through `check_output`, so when git refuses 
that checkout, for example over an unstaged edit left from a conflict 
resolution in a file that differs between branch-4.2 and master (the kind of 
leftover the compile check's dirty-tree warning says to "ignore this and carry 
on"), `CalledProcessError` leaves before the pick is recorded. `main()`'s 
`finally` then posts a Merge Summary without that branch, a direct push is also 
missing from the JIRA fix versions, and the run ends with a traceback instead 
of offering the next branch. The skip exits already wait out this refusal with 
`_restore_original_head()`, and `record` was added so that a landed pick 
survives a run that ends after it.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4577039831).
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Nit (P3):** This loop drops only empty and `skip-checks` paragraphs, so 
the trailer has to be in whatever paragraph is left last. A `[d]` pick of a 
backport-PR merge that carried the sampled skip-checks paragraph (about nine in 
ten merges into branch-4.x) doesn't keep it there: `git cherry-pick -sx` 
appends `(cherry picked from commit ...)` and the sign-off to that skip-checks 
paragraph, and `_set_skip_trailer(False)` then leaves them as a paragraph of 
their own after `Backport-PR: #M` and the merge's sign-off. For the landed 
pick, `backport_pr()` returns `None` and `has_merge_footer(pick, M)` is false, 
so `dev/pr_merge_status.py M` omits the branch the pick reached, while the same 
pick of an unsampled merge counts for #M. `merge_pr`'s credited-author scan 
already reads from the last footer on because of this split, but the shared 
reader doesn't, and no doctest feeds it such a pick.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4577039812).
   
   **Verification:**
   - **Regression:** A message shaped as git leaves a direct pick of a sampled 
backport-PR merge once the skip-checks trailer is removed, a trailer paragraph 
holding the merge's Backport-PR trailer and sign-off followed by a final 
paragraph holding only the pick's '(cherry picked from commit ...)' and 
Signed-off-by lines, reads as that backport PR and counts as merging both it 
and the original.
   - **Compatibility:** A pick of an unsampled backport-PR merge, a backport-PR 
merge with a trailing skip-checks paragraph, a chained message with two 
Backport-PR trailers, an ordinary pick with no Backport-PR trailer and a 
message that quotes a Backport-PR line before its footer all read as they do 
now.



##########
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:
   **Nit (P3):** doctest runs this test against its own copy of the module 
globals, taken before the examples run, so the bare name always reads that 
copy's `False`, while `_restore_original_head`'s `global preserve_local_state` 
writes the real module dictionary that `clean_up()` reads. If the flag ever 
outlived this test, every `clean_up()` of the real run after the startup 
doctests would do nothing and leave the `PR_TOOL_*` branches behind, and this 
check would still pass. Reading the flag through a function defined in the 
module checks the real one:
   
   ```suggestion
       >>> clean_up.__globals__["preserve_local_state"]
   ```
   
   **Verification:**
   - **Regression:** With the module's preserve_local_state left True after the 
abort doctest's loop, its closing check fails, and with the flag restored it 
passes.



##########
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:
   **Nit (P3):** With this second pattern, `dev/pr_merge_status.py` finds a 
merged backport PR by its `Backport-PR: #<pr>` trailer, since that commit keeps 
the original's `Closes #N from` footer and carries none of its own. The tool's 
module docstring still says backports are plain cherry-pick pushes and that it 
finds the commits carrying `Closes #<pr> from <author>/<branch>`, and its 
not-merged line reports `no "Closes #<pr> from " commit found`, so for a 
backport PR the text names a signal its merge never carries and leaves out the 
one the tool actually searched for. The answers themselves stay correct.
   
   **Verification:**
   - **Behavior:** For a closed PR with no matching commit, the not-merged line 
names both the 'Closes #<pr> from ' footer and the 'Backport-PR: #<pr>' trailer 
the tool searched for.
   - **Inspection:** The tool's module description explains how a merged 
backport PR is found and that a backport can land through a backport PR the 
merge script merges.



##########
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:
   **Nit (P3):** This stub returns a pending pair and never calls 
`kwargs["record"]`, and `main()` now discards `cherry_pick`'s return value, so 
no pick in this test reaches the ledger. The case "the pick that comes back 
pending is not landed" therefore holds whatever `main()` does with picks: 
dropping `record=` from either loop, recording a pending backport PR as landed, 
or removing `+ picks.commits` from the merge comment would all pass. The case 
was meaningful while `main()` recorded the return value; the switch to the 
callback left it unable to fail. These doctests are the script's only 
regression signal, since `dev/sparktestsupport/modules.py` keeps the file out 
of CI test selection.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60472#discussion_r4576372784).
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Nit (P3):** Both `main()` call sites now discard this return value: picks 
reach the next-pick default, the merge comment and the JIRA update only through 
`record`. This sentence, and the `[b]oth` comment's "still return branch-M.x so 
it is recorded", still describe the returned list as how `main()` records them, 
so a new call site written from them would lose a landed pick whenever a later 
pick ends the run.
   
   See **Shared repair plan 1** in the review body.



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