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


##########
dev/merge_spark_pr.py:
##########
@@ -1010,19 +1043,137 @@ class SkipCherryPick(Exception):
     """
 
 
-def continue_maybe(prompt, cherry=False):
+def continue_maybe(prompt: str, cherry: bool = False) -> None:
+    """Prompt to continue; on "no" either skip this cherry-pick (`cherry`) or 
exit the script.
+
+    `cherry` is the decline semantics, not a statement that a cherry-pick is 
mid-flight: the
+    pre-push checks run after the pick is committed, and declining there must 
still skip only
+    that branch. So the abort is attempted only when git says one is actually 
in progress.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+
+    Declining with `cherry` while a pick is mid-flight aborts the pick before 
skipping --
+    the first git call is the probe, the second the abort:
+
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=["", ""]) as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Resolved?", cherry=True)
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    >>> run.call_args_list[0]
+    call(['git', 'rev-parse', '--verify', '--quiet', 'CHERRY_PICK_HEAD'])
+    >>> run.call_args_list[1]
+    call('git cherry-pick --abort')
+    >>> run.call_count
+    2
+
+    After the pick is committed there is nothing to abort. A checkout git 
refuses over
+    uncommitted edits waits for the committer to stash them, then the branch 
is skipped:
+
+    >>> refused = subprocess.CalledProcessError(1, "git checkout")
+    >>> with (
+    ...     patch("builtins.input", side_effect=["", ""]) as inp,
+    ...     patch.object(git, "run", side_effect=[refused, refused, ""]) as 
run,
+    ...     patch.dict(continue_maybe.__globals__, original_head="master"),
+    ...     patch.object(sys.modules[__name__], "clean_up") as clean,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Push anyway?", cherry=True)
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    >>> [c.args[0] for c in run.call_args_list[1:]]
+    [['git', 'checkout', 'master'], ['git', 'checkout', 'master']]
+    >>> inp.call_count, clean.call_count
+    (2, 1)
+
+    A checkout git keeps refusing, e.g. over a stale index.lock, can be given 
up on:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["", "a"]),
+    ...     patch.object(git, "run", side_effect=[refused, refused]),
+    ...     patch.dict(continue_maybe.__globals__, original_head="master"),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Push anyway?", cherry=True)
+    ...         exited = False
+    ...     except SystemExit:
+    ...         exited = True
+    >>> exited
+    True
+    """
     if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
         if cherry:
-            try:
-                git.run("git cherry-pick --abort")
-            except Exception:
-                print_error("Unable to abort and get back to the state before 
cherry-pick")
+            if _cherry_pick_in_progress():
+                try:
+                    git.run("git cherry-pick --abort")
+                except Exception:
+                    print_error("Unable to abort and get back to the state 
before cherry-pick")
+            else:
+                _restore_original_head()
             print("Skipping this cherry-pick; the merge continues.")
             clean_up()
             raise SkipCherryPick()
         fail("Okay, exiting")
 
 
+def _cherry_pick_in_progress() -> bool:
+    """True if the repo is mid-cherry-pick. With --quiet, exit 1 is git's "no 
such ref" answer,
+    i.e. no pick in progress. Any other trouble answers "yes", so the caller 
still attempts
+    the abort, as if a pick were in progress.
+
+    >>> from unittest.mock import patch
+    >>> answers = []
+    >>> for failure in (None, subprocess.CalledProcessError(1, "g"),
+    ...                 subprocess.CalledProcessError(128, "g"), OSError("no 
git")):
+    ...     with patch.object(git, "run", side_effect=failure):
+    ...         answers.append(_cherry_pick_in_progress())
+    >>> answers
+    [True, False, True, True]
+    """
+    try:
+        git.run(["git", "rev-parse", "--verify", "--quiet", 
"CHERRY_PICK_HEAD"])
+        return True
+    except subprocess.CalledProcessError as e:
+        return e.returncode != 1
+    except Exception:
+        return True
+
+
+def _restore_original_head():
+    """Check out original_head, waiting for the committer while git refuses 
over local edits.
+
+    The committed pick is discarded by clean_up() afterwards; the edits are 
theirs to keep, and
+    any git carries over to original_head are listed."""
+    if "original_head" not in globals():
+        return
+    while True:
+        try:
+            carried = git.run(["git", "checkout", original_head]).strip()

Review Comment:
   **Nit (P3):** Besides the list of carried files, `git checkout` writes its 
upstream tracking report to stdout ("Your branch is up to date with 
'origin/master'.", or the ahead/behind advice) whenever `original_head` is a 
branch with an upstream, such as a local master tracking apache/master; only 
'Switched to branch' goes to stderr. A decline on a clean tree then prints 
'Uncommitted changes carried over to master:' followed by the tracking line, 
and real carried edits come mixed with it, so the committer has to run `git 
status` to learn what actually moved. The doctests mock the successful checkout 
as `''`, so they never see this output.
   
   Running the checkout with `--quiet`, which drops both the tracking report 
and the file list but still prints a refusal, and then printing the heading 
only when `git status --porcelain --untracked-files=no` lists something, shows 
exactly what was carried over. The doctests that pin the checkout arguments 
need the same update.
   
   **Verification:**
   - **Regression:** Restore a branch that has an upstream from a clean 
committed pick and check that no carried-over heading is printed.
   - **Behavior:** Restore with one carried edit and check that the listing 
names that file and contains no tracking text.
   - **Compatibility:** Refuse the checkout and check that git's reason and the 
retry prompt still appear and that the retry and abort answers behave as before.



##########
dev/merge_spark_pr.py:
##########
@@ -1010,19 +1043,137 @@ class SkipCherryPick(Exception):
     """
 
 
-def continue_maybe(prompt, cherry=False):
+def continue_maybe(prompt: str, cherry: bool = False) -> None:
+    """Prompt to continue; on "no" either skip this cherry-pick (`cherry`) or 
exit the script.
+
+    `cherry` is the decline semantics, not a statement that a cherry-pick is 
mid-flight: the
+    pre-push checks run after the pick is committed, and declining there must 
still skip only
+    that branch. So the abort is attempted only when git says one is actually 
in progress.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+
+    Declining with `cherry` while a pick is mid-flight aborts the pick before 
skipping --
+    the first git call is the probe, the second the abort:
+
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=["", ""]) as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Resolved?", cherry=True)
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    >>> run.call_args_list[0]
+    call(['git', 'rev-parse', '--verify', '--quiet', 'CHERRY_PICK_HEAD'])
+    >>> run.call_args_list[1]
+    call('git cherry-pick --abort')
+    >>> run.call_count
+    2
+
+    After the pick is committed there is nothing to abort. A checkout git 
refuses over
+    uncommitted edits waits for the committer to stash them, then the branch 
is skipped:
+
+    >>> refused = subprocess.CalledProcessError(1, "git checkout")
+    >>> with (
+    ...     patch("builtins.input", side_effect=["", ""]) as inp,
+    ...     patch.object(git, "run", side_effect=[refused, refused, ""]) as 
run,
+    ...     patch.dict(continue_maybe.__globals__, original_head="master"),
+    ...     patch.object(sys.modules[__name__], "clean_up") as clean,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Push anyway?", cherry=True)
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    >>> [c.args[0] for c in run.call_args_list[1:]]
+    [['git', 'checkout', 'master'], ['git', 'checkout', 'master']]
+    >>> inp.call_count, clean.call_count
+    (2, 1)
+
+    A checkout git keeps refusing, e.g. over a stale index.lock, can be given 
up on:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["", "a"]),
+    ...     patch.object(git, "run", side_effect=[refused, refused]),
+    ...     patch.dict(continue_maybe.__globals__, original_head="master"),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Push anyway?", cherry=True)
+    ...         exited = False
+    ...     except SystemExit:
+    ...         exited = True
+    >>> exited
+    True
+    """
     if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
         if cherry:
-            try:
-                git.run("git cherry-pick --abort")
-            except Exception:
-                print_error("Unable to abort and get back to the state before 
cherry-pick")
+            if _cherry_pick_in_progress():
+                try:
+                    git.run("git cherry-pick --abort")
+                except Exception:
+                    print_error("Unable to abort and get back to the state 
before cherry-pick")
+            else:
+                _restore_original_head()
             print("Skipping this cherry-pick; the merge continues.")
             clean_up()
             raise SkipCherryPick()
         fail("Okay, exiting")
 
 
+def _cherry_pick_in_progress() -> bool:
+    """True if the repo is mid-cherry-pick. With --quiet, exit 1 is git's "no 
such ref" answer,
+    i.e. no pick in progress. Any other trouble answers "yes", so the caller 
still attempts
+    the abort, as if a pick were in progress.
+
+    >>> from unittest.mock import patch
+    >>> answers = []
+    >>> for failure in (None, subprocess.CalledProcessError(1, "g"),
+    ...                 subprocess.CalledProcessError(128, "g"), OSError("no 
git")):
+    ...     with patch.object(git, "run", side_effect=failure):
+    ...         answers.append(_cherry_pick_in_progress())
+    >>> answers
+    [True, False, True, True]
+    """
+    try:
+        git.run(["git", "rev-parse", "--verify", "--quiet", 
"CHERRY_PICK_HEAD"])
+        return True
+    except subprocess.CalledProcessError as e:
+        return e.returncode != 1
+    except Exception:
+        return True
+
+
+def _restore_original_head():
+    """Check out original_head, waiting for the committer while git refuses 
over local edits.
+
+    The committed pick is discarded by clean_up() afterwards; the edits are 
theirs to keep, and
+    any git carries over to original_head are listed."""
+    if "original_head" not in globals():
+        return
+    while True:
+        try:
+            carried = git.run(["git", "checkout", original_head]).strip()
+            if carried:
+                print("Uncommitted changes carried over to %s:\n%s" % 
(original_head, carried))
+            return
+        except subprocess.CalledProcessError:
+            # git already printed why it refused.
+            prompt = "Stash or discard those changes elsewhere, then Enter to 
retry, or [a]bort: "
+            if get_input(prompt, ["", "a"]) == "a":
+                print_error("Okay, exiting; local edits and temporary branches 
are preserved.")
+                raise _PreserveLocalState(-1)

Review Comment:
   **Non-blocking (P2):** Only the entry point's `except _PreserveLocalState: 
raise` honors this exit. Before the exception gets there, it unwinds through 
`main()`'s `finally` blocks, where `update_jira_for_pr()` asks 'Would you like 
to update an associated JIRA?' whenever JIRA is reachable and the title has no 
[MINOR], [TRIVIAL], or [FOLLOWUP] tag. N is the default there, and the 
skip-post-merge-CI warning tells committers to answer N when they stop a pick 
to rerun, so this is the common route. N calls `fail()`, which runs 
`clean_up()`. While git still refuses, the retried `git checkout 
<original_head>` raises a `CalledProcessError` that replaces 
`_PreserveLocalState`, so the entry point's generic handler runs `clean_up()` 
again. The committer, just told that local state is preserved, sees the refused 
checkout tried twice more and a chained traceback, and the run exits 1. If they 
stashed in another terminal in the meantime, the retried checkout succeeds and 
`clean_up()` force-delete
 s the `PR_TOOL_*` branch holding the unpushed pick and any hand-resolved 
conflict. Any other exit raised in those blocks, such as `get_json()`'s 
`sys.exit(-1)` on a GitHub error, ends the same way. `abort_entrypoint` 
replaces `main()` with `_restore_original_head`, so no doctest reaches these 
blocks after an abort.
   
   Every one of these routes ends in `clean_up()`, so a module-level flag that 
`_restore_original_head` sets just before raising, and that makes `clean_up()` 
return without running git, keeps the promise on all of them. The doctests that 
answer [a] would need to restore the flag afterwards, so the startup self-test 
never leaves cleanup disabled for the real run.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576382614).
   
   **Verification:**
   - **Regression:** Drive an abort at the restore prompt through main()'s 
finally blocks, once declining the JIRA prompt and once with another exit 
raised there, such as a GitHub error while the merge loop checks the PR's 
state; check that no git command runs after the abort, the PR_TOOL_* branches 
are untouched, and the run exits with status -1.
   - **Regression:** Repeat with a checkout that would now succeed, as after a 
stash in another terminal, and check that the pick branch is still not deleted.
   - **Behavior:** Answer y at the JIRA prompt after an abort and check that 
JIRA is still updated and the run then exits with status -1 without cleanup.
   - **Compatibility:** After the startup doctests have run, check that an 
ordinary exit and a skipped branch still restore the original head and delete 
the PR_TOOL_* branches.



##########
dev/merge_spark_pr.py:
##########
@@ -1010,19 +1039,65 @@ class SkipCherryPick(Exception):
     """
 
 
-def continue_maybe(prompt, cherry=False):
+def continue_maybe(prompt: str, cherry: bool = False) -> None:
+    """Prompt to continue; on "no" either skip this cherry-pick (`cherry`) or 
exit the script.
+
+    `cherry` is the decline semantics, not a statement that a cherry-pick is 
mid-flight: the
+    pre-push checks run after the pick is committed, and declining there must 
still skip only
+    that branch. So the abort is attempted only when git says one is actually 
in progress.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+
+    Declining with `cherry` while a pick is mid-flight aborts the pick before 
skipping --
+    the first git call is the probe, the second the abort:
+
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=["", ""]) as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         continue_maybe("Resolved?", cherry=True)
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    >>> run.call_args_list[0]
+    call(['git', 'rev-parse', '--verify', '--quiet', 'CHERRY_PICK_HEAD'])
+    >>> run.call_args_list[1]
+    call('git cherry-pick --abort')
+    >>> run.call_count
+    2
+    """
     if get_input(f"{prompt} (y/N): ", ["y", "n", ""]) != "y":
         if cherry:
-            try:
-                git.run("git cherry-pick --abort")
-            except Exception:
-                print_error("Unable to abort and get back to the state before 
cherry-pick")
+            if _cherry_pick_in_progress():

Review Comment:
   Thanks, I checked the retry path: once the edit is stashed, the decline 
restores the original head, skips the branch, and still returns the branch-4.x 
pick. This review raises two related problems with the new `[a]bort` exit: the 
cleanup it promises to skip still runs from `main()`'s `finally` blocks, and an 
abort in the branch-M.N half of an Upstream-First pick leaves the 
already-pushed branch-M.x pick out of the merge comment and the JIRA update.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4576382614","thread_id":"inline:4576382614","verdict_sha256":"b9e515f11ad689065273f2db62f928ff6e1e6931788187e04ae1005a0cce80b5"}
 -->



##########
dev/merge_spark_pr.py:
##########
@@ -1270,6 +1815,9 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
     if updated_message != raw_message:
         amend_commit_message(updated_message)
 
+    maybe_binding_policy_warning(pick_ref, pick_head)

Review Comment:
   **Non-blocking (P2):** These checks also run on the branch-M.N half of an 
Upstream-First 'both' choice, after the branch-M.x pick has already been 
pushed. If one is declined and git refuses the checkout of the original head, 
`[a]bort` raises `_PreserveLocalState`, a `SystemExit` that `cherry_pick`'s 
`except SkipCherryPick` does not catch, so `picked` is never returned. 
`main()`'s `finally` blocks then run without the branch-M.x pair: a 
backport-only run posts no merge comment at all, a merge run posts one without 
the branch-M.x line, and the JIRA prompt's default fix versions leave out 
branch-M.x's release, while the committer is told only that local state is 
preserved. A rerun finds branch-M.x through its merge footer for the JIRA 
update, but the PR comment keeps the gap. The base branch already drops the 
record the same way when that pick ends through `fail()`, for example on a 
declined push prompt; the abort adds a new route to that loss.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576382614).
   
   **Recommended change:** Make main() own one list of the (branch, commit) 
pairs that land in the run, starting with the merge into the PR's base branch 
on a merge run and empty on a backport-only run, and pass it through 
cherry_pick() to _do_cherry_pick(), which appends its pair as soon as its push 
succeeds and before its own clean_up(). main()'s finally blocks then take the 
merge comment's lines from that list, and its loops add that list's branches, 
instead of the branches cherry_pick returns, to the ones they start with: the 
PR's base branch and, on a backport-only run, the branches an earlier run 
already picked into. The already-picked branches and the JIRA branches thus 
stay what they are today whenever every pick returns. Update the main() and 
cherry_pick doctests that build the record from returned picks, and add one for 
an Upstream-First 'both' choice whose second pick ends the run.
   
   **Why this works:** Because the push and its record happen in the same step, 
no exception raised after the push, whether the abort, fail(), or a failed 
cleanup, can separate them, and main()'s finally blocks, which run on every 
exit, see every branch that received the change.
   
   **Scope:** Record each backport push where main()'s finally blocks read it, 
at the moment the push succeeds.
   
   **Compatibility:** Skipping a branch, the rule that a skipped branch-M.x 
pick also skips branch-M.N, and the order of the merge comment's lines stay as 
they are, and the JIRA update and the next default branch still count the PR's 
base branch and the branches an earlier run already picked into.
   
   **Risks:** On the base branch's other routes that end the second pick of a 
'both' choice, such as a declined push prompt or a push error, the merge 
comment and the JIRA update now include the branch-M.x pick that landed; that 
is what cherry_pick's own comment intends, but it changes what those runs post. 
A pick whose push succeeded but whose later cleanup failed is now listed in the 
merge comment even though the run ends in a traceback.
   
   **Constraints:** A pair is recorded only after git push returns, so a failed 
push is never recorded; under a dry run the logged push counts as landed, as 
cherry_pick's return value does today. The loops keep deriving the next default 
branch from the same record, so a branch that already received the change is 
never offered again in the run.
   
   **Exclusions:**
   - A failure of merge_pr()'s own cleanup after the merge push, which happens 
before main() starts its record, is left as it is.
   
   **Success:** When the branch-M.N pick of an Upstream-First 'both' choice 
ends the run after branch-M.x was pushed, whether through the restore prompt's 
abort or through fail(), the merge comment lists branch-M.x and the JIRA update 
receives it. A run in which every pick lands records each branch once, in push 
order, as before. A skipped pick records nothing for its branch. A pick whose 
push succeeded stays recorded even when the cleanup after its push fails.
   
   **Verification:**
   - **Regression:** Drive an Upstream-First 'both' choice in which branch-M.x 
is pushed and the branch-M.N pick ends the run at the restore prompt's abort; 
check that the merge comment and the JIRA update both include branch-M.x.
   - **Regression:** Drive the same choice with the branch-M.N push prompt 
declined, and check that the merge comment and the JIRA update both include 
branch-M.x.
   - **Behavior:** Drive a run that picks two branches successfully and check 
that each is recorded once, in push order, and that neither is offered again as 
the next default.
   - **Behavior:** Decline a pre-push check on a clean tree and check that the 
skipped branch is not recorded and the run still offers the next branch.
   - **Behavior:** Make the cleanup after a successful push fail, as git 
refusing the checkout over a leftover edit does, and check that the merge 
comment and the JIRA update still include that branch.



##########
dev/merge_spark_pr.py:
##########
@@ -1010,19 +1043,137 @@ class SkipCherryPick(Exception):
     """
 
 
-def continue_maybe(prompt, cherry=False):
+def continue_maybe(prompt: str, cherry: bool = False) -> None:
+    """Prompt to continue; on "no" either skip this cherry-pick (`cherry`) or 
exit the script.
+
+    `cherry` is the decline semantics, not a statement that a cherry-pick is 
mid-flight: the
+    pre-push checks run after the pick is committed, and declining there must 
still skip only
+    that branch. So the abort is attempted only when git says one is actually 
in progress.

Review Comment:
   **Nit (P3):** `_cherry_pick_in_progress` answers True for every failure 
except git's exit 1, so the abort also runs when git could not answer at all, 
such as on exit 128 or an `OSError`, as that helper's docstring and doctest 
say. Read on its own, this sentence suggests that a failed probe takes the 
restore path instead. Stating the rule from the other side matches the code:
   
   ```suggestion
       that branch. So the abort is skipped only when git says no pick is in 
progress.
   ```
   
   **Verification:**
   - **Inspection:** The continue_maybe docstring no longer says the abort runs 
only when git reports a pick in progress, and what it says about a failed probe 
matches _cherry_pick_in_progress's docstring and doctest.



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