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


##########
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:
   **Non-blocking (P2):** With the pick already committed, 
`_cherry_pick_in_progress()` returns False here, so no abort runs, and nothing 
else resets the working tree before `clean_up()` runs `git checkout 
<original_head>`. git refuses that checkout while a staged or unstaged edit 
touches a file that differs between the pick and the branch the script started 
from. `CalledProcessError` then escapes instead of `SkipCherryPick`. Both new 
push-anyway prompts invite such an edit: the binding-policy remedy asks the 
committer to drop the call and the import, and a failed compile invites a fix.
   
   A scratch repro showed it. master and branch-4.1 differed in one file, the 
pick was committed on `PR_TOOL_PICK_PR_1_BRANCH-4.1`, and that file was edited, 
staged or unstaged. Declining printed 'Skipping this cherry-pick; the merge 
continues.', then `git checkout master` was refused and `CalledProcessError` 
escaped. HEAD stayed on the pick branch and the temporary branch was kept. A 
clean tree, and an edit to a file both branches share, each skipped normally.
   
   Because `cherry_pick` only catches `SkipCherryPick`, no further branches are 
offered. When this is the branch-M.N half of an Upstream-First pair, say 
branch-4.x then branch-4.1, `cherry_pick` also never returns the branch-4.x 
pick it pushed moments earlier. That pick is then missing from the merge 
comment and from the branches the JIRA update proposes fix versions for. The 
base branch's skip path already failed this way in one corner: declining 
'Finished?' after finishing a conflicted pick by hand. These prompts reach it 
in ordinary flows.
   
   See **Shared repair plan 1** in the review body.



##########
dev/merge_spark_pr.py:
##########
@@ -1035,6 +1110,353 @@ def clean_up():
             git.run("git branch -D %s" % branch)
 
 
+def maybe_compile_check(ref_name: str) -> None:
+    """Offer to run a clean SBT compile of main and test sources before 
pushing `ref_name`.
+
+    `ref_name` is the checked-out cherry-pick, so a clean compile here catches 
a mis-resolved
+    conflict, or a PR that bit-rotted against the target branch, before it 
lands. It is a smoke
+    test (see COMPILE_CHECK_CMD), not CI: modules behind other profiles are 
not compiled.
+    Declining skips the check. A red build asks rather than aborts, because a 
non-zero sbt is
+    as easily a JDK the branch rejects or a failed download as it is the 
backport; declining
+    there skips this branch (see continue_maybe). Output streams so a long 
compile does not
+    look like a hang.
+
+    What is compiled is the working tree, not the commit: a file re-edited 
after the merge
+    commit, or an untracked source file left over from a manual conflict 
resolution, compiles
+    here and is absent from the push. (A resolved-but-never-`git add`ed 
conflict is NOT the
+    case -- the commit itself fails while files are unmerged, so the check is 
never reached.)
+    So warn when the tree is dirty rather than report a green that is about 
something else,
+    and name the remedy (`git add` + `git commit --amend`) since the fix is 
the commit, not
+    the build.
+
+    Declining runs no build and no git -- the git.run mock raises if a 
regression moves a
+    git call above the prompt, which otherwise would run real git in the 
committer's repo on
+    every startup (doctest.testmod() runs on invocation):
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=AssertionError("should not 
run git")),
+    ...     patch("subprocess.call") as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> run.call_count
+    0
+
+    Accepting runs the SBT compile once, from the repo root, with an explicit 
-P so SparkBuild
+    does not fall back to `-Psbt`; a green build returns quietly. The two git 
calls are pinned
+    too -- transposing them or dropping --porcelain would otherwise stay green:
+
+    >>> with (
+    ...     patch("builtins.input", return_value="y"),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", ""]) as grun,
+    ...     patch("subprocess.call", return_value=0) as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> grun.call_args_list[0]
+    call(['git', 'rev-parse', '--show-toplevel'])
+    >>> grun.call_args_list[1]
+    call(['git', 'status', '--porcelain'])
+    >>> run.call_count
+    1
+    >>> run.call_args[0][0][0], run.call_args[0][0][-1]
+    ('build/sbt', ';clean;compile;Test/compile')
+    >>> [a for a in run.call_args[0][0] if a.startswith("-P")]
+    ['-Phive']
+    >>> run.call_args[1]["cwd"]
+    '/repo'
+
+    A dirty tree still builds, but warns first -- and the warning names the 
remedy
+    (`git add` + `git commit --amend`) alongside the porcelain output:
+
+    >>> with (
+    ...     patch("builtins.input", return_value="y"),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", " M 
foo.scala\\n"]),
+    ...     patch("subprocess.call", return_value=0),
+    ...     redirect_stdout(StringIO()) as out,
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> "git commit --amend" in out.getvalue()
+    True
+    >>> "M foo.scala" in out.getvalue()  # porcelain output is strip()ed 
before printing
+    True
+    >>> "Compile check passed." in out.getvalue()
+    True
+
+    The experts-only override continues past a red build:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["y", "y"]),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", ""]),
+    ...     patch("subprocess.call", return_value=1),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+    Ctrl-C during the build, and a build/sbt that cannot be run at all, are 
"did not pass" and
+    get the same override prompt -- never a traceback, which would reach the 
top-level handler
+    and let clean_up() delete the unpushed pick:
+
+    >>> for boom in (KeyboardInterrupt(), OSError("no build/sbt")):
+    ...     with (
+    ...         patch("builtins.input", side_effect=["y", "y"]),
+    ...         patch.object(git, "run", side_effect=["/repo\\n", ""]),
+    ...         patch("subprocess.call", side_effect=boom),
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+    Declining the override skips just this branch instead of exiting:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["y", ""]),
+    ...     patch.object(
+    ...         git, "run", side_effect=["/repo\\n", "", 
subprocess.CalledProcessError(1, "g")]
+    ...     ),
+    ...     patch("subprocess.call", return_value=1),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    """
+    # The command is too long to read inside a prompt, so print it on its own 
line first.
+    # shlex.join quotes the ";clean;..." argument, so the printed line can be 
copy-pasted
+    # into a shell without the semicolons splitting it into four commands.
+    print("Optional pre-push check: %s" % shlex.join(COMPILE_CHECK_CMD))
+    print("Note: 'clean' deletes every module's build output, including under 
--dry-run.")
+    prompt = "Run an optional clean compile on %s before pushing? (y/N): " % 
ref_name
+    if get_input(prompt, ["y", "n", ""]) != "y":
+        return
+    # build/sbt is repo-relative and SPARK_HOME defaults to the cwd, which is 
dev/ when the
+    # script is run as ./merge_spark_pr.py per its own usage line. Ask git for 
the root instead.
+    root = git.run(["git", "rev-parse", "--show-toplevel"]).strip()
+    dirty = git.run(["git", "status", "--porcelain"]).strip()

Review Comment:
   **Nit (P3):** `git status --porcelain` follows the committer's 
`status.showUntrackedFiles` setting, and with it set to `no` untracked files 
are not listed. The warning then stays silent for an untracked source file left 
over from a conflict resolution, the exact case the docstring names at lines 
1124-1130. The check reports a plain 'Compile check passed.' for a tree that 
the pushed commit lacks, and the branch's CI finds the missing file only after 
the push. Passing `--untracked-files=normal` here makes the listing independent 
of that setting. The doctest at line 1163 that pins this call needs the same 
update.
   
   **Verification:**
   - **Regression:** In a repository whose configuration sets 
status.showUntrackedFiles=no and that has an untracked source file, the check's 
status call lists that file.
   - **Behavior:** The doctest that pins the status call asserts the 
untracked-files option, so removing it fails the doctest.



##########
dev/merge_spark_pr.py:
##########
@@ -1213,8 +1635,31 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
     """Cherry-pick `merge_hash` onto `pick_ref` and push.
 
     Returns the (pushed ref, pushed commit hash) pair. Raises `SkipCherryPick` 
if the
-    cherry-pick conflicts and the committer declines to resolve it, after 
attempting to
-    abort the cherry-pick and restore the working tree.
+    cherry-pick conflicts and the committer declines to resolve it, or 
declines a pre-push
+    check, after attempting to abort the cherry-pick and restore the working 
tree.

Review Comment:
   **Nit (P3):** For a declined pre-push check this clause is wrong. The pick 
is already committed, so `continue_maybe`'s probe finds no `CHERRY_PICK_HEAD` 
and attempts no abort, as its own docstring says at lines 1045-1047. 
`clean_up()` then only checks out the original head, which carries uncommitted 
edits along or refuses to switch over them, and force-deletes the `PR_TOOL_*` 
branches. The docstring should say that no abort runs here and that the 
committed pick, with any hand-resolved conflicts, is discarded. Saying the 
working tree is restored suggests a reset that never happens.
   
   See **Shared repair plan 1** in the review body.



##########
dev/merge_spark_pr.py:
##########
@@ -1035,6 +1110,353 @@ def clean_up():
             git.run("git branch -D %s" % branch)
 
 
+def maybe_compile_check(ref_name: str) -> None:
+    """Offer to run a clean SBT compile of main and test sources before 
pushing `ref_name`.
+
+    `ref_name` is the checked-out cherry-pick, so a clean compile here catches 
a mis-resolved
+    conflict, or a PR that bit-rotted against the target branch, before it 
lands. It is a smoke
+    test (see COMPILE_CHECK_CMD), not CI: modules behind other profiles are 
not compiled.
+    Declining skips the check. A red build asks rather than aborts, because a 
non-zero sbt is
+    as easily a JDK the branch rejects or a failed download as it is the 
backport; declining
+    there skips this branch (see continue_maybe). Output streams so a long 
compile does not
+    look like a hang.
+
+    What is compiled is the working tree, not the commit: a file re-edited 
after the merge
+    commit, or an untracked source file left over from a manual conflict 
resolution, compiles
+    here and is absent from the push. (A resolved-but-never-`git add`ed 
conflict is NOT the
+    case -- the commit itself fails while files are unmerged, so the check is 
never reached.)
+    So warn when the tree is dirty rather than report a green that is about 
something else,
+    and name the remedy (`git add` + `git commit --amend`) since the fix is 
the commit, not
+    the build.
+
+    Declining runs no build and no git -- the git.run mock raises if a 
regression moves a
+    git call above the prompt, which otherwise would run real git in the 
committer's repo on
+    every startup (doctest.testmod() runs on invocation):
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=AssertionError("should not 
run git")),
+    ...     patch("subprocess.call") as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> run.call_count
+    0
+
+    Accepting runs the SBT compile once, from the repo root, with an explicit 
-P so SparkBuild
+    does not fall back to `-Psbt`; a green build returns quietly. The two git 
calls are pinned
+    too -- transposing them or dropping --porcelain would otherwise stay green:
+
+    >>> with (
+    ...     patch("builtins.input", return_value="y"),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", ""]) as grun,
+    ...     patch("subprocess.call", return_value=0) as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> grun.call_args_list[0]
+    call(['git', 'rev-parse', '--show-toplevel'])
+    >>> grun.call_args_list[1]
+    call(['git', 'status', '--porcelain'])
+    >>> run.call_count
+    1
+    >>> run.call_args[0][0][0], run.call_args[0][0][-1]
+    ('build/sbt', ';clean;compile;Test/compile')
+    >>> [a for a in run.call_args[0][0] if a.startswith("-P")]
+    ['-Phive']
+    >>> run.call_args[1]["cwd"]
+    '/repo'
+
+    A dirty tree still builds, but warns first -- and the warning names the 
remedy
+    (`git add` + `git commit --amend`) alongside the porcelain output:
+
+    >>> with (
+    ...     patch("builtins.input", return_value="y"),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", " M 
foo.scala\\n"]),
+    ...     patch("subprocess.call", return_value=0),
+    ...     redirect_stdout(StringIO()) as out,
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> "git commit --amend" in out.getvalue()
+    True
+    >>> "M foo.scala" in out.getvalue()  # porcelain output is strip()ed 
before printing
+    True
+    >>> "Compile check passed." in out.getvalue()
+    True
+
+    The experts-only override continues past a red build:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["y", "y"]),
+    ...     patch.object(git, "run", side_effect=["/repo\\n", ""]),
+    ...     patch("subprocess.call", return_value=1),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+    Ctrl-C during the build, and a build/sbt that cannot be run at all, are 
"did not pass" and
+    get the same override prompt -- never a traceback, which would reach the 
top-level handler
+    and let clean_up() delete the unpushed pick:
+
+    >>> for boom in (KeyboardInterrupt(), OSError("no build/sbt")):
+    ...     with (
+    ...         patch("builtins.input", side_effect=["y", "y"]),
+    ...         patch.object(git, "run", side_effect=["/repo\\n", ""]),
+    ...         patch("subprocess.call", side_effect=boom),
+    ...         redirect_stdout(StringIO()),
+    ...     ):
+    ...         maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+
+    Declining the override skips just this branch instead of exiting:
+
+    >>> with (
+    ...     patch("builtins.input", side_effect=["y", ""]),
+    ...     patch.object(
+    ...         git, "run", side_effect=["/repo\\n", "", 
subprocess.CalledProcessError(1, "g")]
+    ...     ),
+    ...     patch("subprocess.call", return_value=1),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+    """
+    # The command is too long to read inside a prompt, so print it on its own 
line first.
+    # shlex.join quotes the ";clean;..." argument, so the printed line can be 
copy-pasted
+    # into a shell without the semicolons splitting it into four commands.
+    print("Optional pre-push check: %s" % shlex.join(COMPILE_CHECK_CMD))
+    print("Note: 'clean' deletes every module's build output, including under 
--dry-run.")
+    prompt = "Run an optional clean compile on %s before pushing? (y/N): " % 
ref_name
+    if get_input(prompt, ["y", "n", ""]) != "y":
+        return
+    # build/sbt is repo-relative and SPARK_HOME defaults to the cwd, which is 
dev/ when the
+    # script is run as ./merge_spark_pr.py per its own usage line. Ask git for 
the root instead.
+    root = git.run(["git", "rev-parse", "--show-toplevel"]).strip()
+    dirty = git.run(["git", "status", "--porcelain"]).strip()
+    if dirty:
+        print_error(
+            "Working tree is not clean, so what compiles below is not exactly 
the commit that "
+            "would be pushed -- the uncommitted or untracked changes below 
compile here but "
+            "are not in the push. If any of them belong in the pick, 'git add' 
them and "
+            "'git commit --amend' before pushing; if they are unrelated 
scratch, ignore this "
+            "and carry on:\n%s" % dirty
+        )
+    try:
+        status = subprocess.call(COMPILE_CHECK_CMD, cwd=root)
+    except KeyboardInterrupt:
+        # Interrupting the build must not unwind into the top-level handler: 
clean_up() there
+        # force-deletes the PR_TOOL_* branch holding the unpushed commit and 
any hand-resolved
+        # conflicts. Treat it as "the check did not finish" and let the 
committer decide.
+        print_error("Compile check interrupted.")
+    except OSError as e:
+        print_error("Could not run %s in %s: %s" % (COMPILE_CHECK_CMD[0], 
root, e))
+    else:
+        if status == 0:
+            print("Compile check passed.")
+            return
+        print_error(
+            "Compile check exited %d. That is the backport, or your toolchain 
-- a JDK this "
+            "branch rejects and a failed dependency download look the same 
here." % status
+        )
+    continue_maybe(
+        "Compile check did not pass on %s. Push anyway? (experts only!)" % 
ref_name, True
+    )
+
+
+def _is_pre_binding_policy_branch(ref: str) -> bool:
+    """True if `ref` is a Spark branch that predates the ConfigBindingPolicy 
API (4.2+).
+
+    master and branch-M.x (M >= 4) carry the API; branch-4.0/branch-4.1 and 
any branch-3.x
+    do not. Ranking is semver_branch_rank's job -- branch-M.x sorts above 
every branch-M.N,
+    and a ref it cannot classify as a maintenance branch gets its (-1, -1) 
sentinel. Those
+    refs are treated as carrying the API: fail-open, so master, a tag, or a 
custom ref never
+    raises a false warning -- none of them is a pre-4.2 branch anyway.
+
+    >>> _is_pre_binding_policy_branch("master")
+    False
+    >>> _is_pre_binding_policy_branch("branch-4.x")
+    False
+    >>> _is_pre_binding_policy_branch("branch-4.2")
+    False
+    >>> [_is_pre_binding_policy_branch(b) for b in ("branch-4.1", 
"branch-4.0", "branch-3.x")]
+    [True, True, True]
+    >>> _is_pre_binding_policy_branch("branch-3.5")
+    True
+    >>> _is_pre_binding_policy_branch("HEAD")
+    False
+    >>> _is_pre_binding_policy_branch("my-custom-ref")
+    False
+    """
+    rank = semver_branch_rank(ref)
+    return rank != (-1, -1) and rank < (4, 2)
+
+
+def _added_binding_policy_tokens(diff: str) -> list[str]:
+    """Return the sorted subset of BINDING_POLICY_PATTERNS matched on added 
(``+``) lines.
+
+    Only scans lines the diff added (a leading ``+`` that is not the ``+++ `` 
file header --
+    the trailing space keeps an added line whose own text starts with ``++`` 
counted, apart
+    from the ``++ <space>`` case no real Scala/Java line starts with), so a 
cherry-pick that
+    *removes* a stray .withBindingPolicy is not flagged. Matching uses the
+    precise patterns from BINDING_POLICY_PATTERNS, so a comment that merely 
mentions
+    ``withBindingPolicy`` (no leading dot, no call) is not flagged; 
``ConfigBindingPolicy`` in
+    a comment still can match, which is fine -- the prompt is advisory.
+
+    >>> _added_binding_policy_tokens(
+    ...     "+++ b/foo\\n"
+    ...     "+.withBindingPolicy(X)\\n"
+    ...     "-.withBindingPolicy(Y)\\n"
+    ...     "+import ...ConfigBindingPolicy\\n"
+    ...     "+// see withBindingPolicy usage\\n"
+    ...     " context\\n"
+    ... )
+    ['ConfigBindingPolicy', 'withBindingPolicy']
+    >>> _added_binding_policy_tokens("-.withBindingPolicy(X)\\n")
+    []
+    >>> _added_binding_policy_tokens("+// mentions ConfigBindingPolicy in a 
comment\\n")
+    ['ConfigBindingPolicy']
+    >>> _added_binding_policy_tokens("")
+    []
+    """
+    found = set()
+    for line in diff.splitlines():
+        if line.startswith("+") and not line.startswith("+++ "):
+            for token, pattern in BINDING_POLICY_PATTERNS:
+                if pattern.search(line):
+                    found.add(token)
+    return sorted(found)
+
+
+def maybe_binding_policy_warning(ref: str, base_head: str) -> None:
+    """Warn before pushing to a pre-4.2 `ref` a cherry-pick that adds 
ConfigBindingPolicy.
+
+    A cherry-pick onto branch-4.1/4.0/3.x that introduces 
``.withBindingPolicy(...)`` or
+    ``ConfigBindingPolicy`` will not compile there (the API arrived in 
SPARK-55928, 4.2+).
+    This is a git-diff + grep pre-push check: it diffs `base_head` (the branch 
tip before the
+    pick) against HEAD restricted to Scala/Java sources, scans only the added 
lines for the
+    precise patterns in BINDING_POLICY_PATTERNS, and on a hit prints the 
remedy and asks the
+    committer to confirm the push; declining skips this branch (see 
continue_maybe). No-op on
+    branches that carry the API. Only backports are checked: a PR opened 
straight against a
+    maintenance branch already ran that branch's CI.
+
+    The diff is forced plain: without --no-color a committer with ``color.ui = 
always`` gets
+    added lines behind an ANSI escape, no line starts with "+", and the check 
reports nothing
+    while looking like it ran. Like branches_with_merge_footer, a git failure 
only warns: this
+    runs after the merge has already been pushed.
+
+    `never` below is how these tests assert "does not prompt": a bare input 
mock would return a
+    MagicMock that get_input's loop never accepts, so a regressed guard would 
hang the script at
+    startup -- doctest.testmod() runs on every invocation -- instead of 
failing.
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import patch
+    >>> never = AssertionError("should not prompt")
+
+    No-op on a branch that carries the API (no diff fetched, no prompt):
+
+    >>> with (
+    ...     patch.object(git, "run") as run,
+    ...     patch("builtins.input", side_effect=never),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_binding_policy_warning("branch-4.2", "deadbeef")
+    >>> run.call_count
+    0
+
+    No-op when the change added none of the tokens. The git command is pinned 
here because
+    nothing else in these tests would notice it being wrong -- transposing the 
two endpoints
+    inverts the whole check, and dropping the pathspec or --no-color silently 
defeats it:
+
+    >>> with (
+    ...     patch.object(git, "run", return_value="+ unrelated change\\n") as 
run,
+    ...     patch("builtins.input", side_effect=never),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_binding_policy_warning("branch-4.1", "deadbeef")
+    >>> run.call_args[0][0][:6]
+    ['git', 'diff', '--no-color', '--no-ext-diff', 'deadbeef', 'HEAD']
+    >>> run.call_args[0][0][6:]
+    ['--', ':(top)*.scala', ':(top)*.java']
+
+    Warns and prompts when the change adds a token on a pre-4.2 branch; 
accepting continues
+    (no abort), so input is called once by the continue_maybe prompt:
+
+    >>> with (
+    ...     patch.object(git, "run", return_value="+.withBindingPolicy(X)\\n"),
+    ...     patch("builtins.input", return_value="y") as inp,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_binding_policy_warning("branch-4.1", "deadbeef")
+    >>> inp.call_count
+    1
+
+    Declining skips just that branch, so an already-pushed branch-M.x pick
+    and the JIRA resolution survive (the second git.run is the 
CHERRY_PICK_HEAD probe):
+
+    >>> with (
+    ...     patch.object(
+    ...         git,
+    ...         "run",
+    ...         side_effect=[
+    ...             "+.withBindingPolicy(X)\\n",
+    ...             subprocess.CalledProcessError(1, "git"),
+    ...         ],
+    ...     ),
+    ...     patch("builtins.input", return_value=""),
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     try:
+    ...         maybe_binding_policy_warning("branch-4.1", "deadbeef")
+    ...         skipped = False
+    ...     except SkipCherryPick:
+    ...         skipped = True
+    >>> skipped
+    True
+
+    A git failure warns and scans nothing rather than aborting a half-pushed 
merge:
+
+    >>> with (
+    ...     patch.object(git, "run", side_effect=OSError("git is sad")),
+    ...     patch("builtins.input", side_effect=never),
+    ...     redirect_stdout(StringIO()) as out,
+    ... ):
+    ...     maybe_binding_policy_warning("branch-4.1", "deadbeef")
+    >>> "git is sad" in out.getvalue()
+    True
+    """
+    if not _is_pre_binding_policy_branch(ref):
+        return
+    try:
+        diff = git.run(
+            ["git", "diff", "--no-color", "--no-ext-diff", base_head, "HEAD", 
"--"]

Review Comment:
   **Nit (P3):** This argv turns off color and external diff drivers but not 
`diff.relative`. With `diff.relative=true` in a committer's config, `git diff` 
limits its output to the current directory whatever the `:(top)` magic says. 
Run from `dev/`, as the usage line has it and where `SPARK_HOME` defaults, the 
scan then gets an empty diff, so a pre-4.2 backport that adds 
`.withBindingPolicy(...)` is never flagged. That is the 'scan nothing while 
looking like it ran' case the comment on `BINDING_POLICY_PATHSPECS` says the 
pathspecs prevent. Adding `-c diff.relative=false` before `diff` closes it; the 
script already does the same with `-c commit.cleanup=scissors`, and 
`--no-relative` also works. The doctest that pins `argv[:6]` at line 1385 needs 
the same update.
   
   **Verification:**
   - **Regression:** In a repository whose configuration sets 
diff.relative=true, run the check's diff from a subdirectory with no Scala or 
Java files and confirm the added .withBindingPolicy(...) line is reported.
   - **Behavior:** The doctest that pins the diff argv asserts the 
diff.relative override, so removing it fails the doctest.



##########
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():
+                try:
+                    git.run("git cherry-pick --abort")
+                except Exception:
+                    print_error("Unable to abort and get back to the state 
before cherry-pick")
             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 and keeps the pre-change behaviour."""

Review Comment:
   **Nit (P3):** 'the pre-change behaviour' points at this PR's diff, which a 
reader of the merged file can't see. The sentence already says what happens, so 
it can just finish the thought:
   
   ```suggestion
       the abort, as if a pick were in progress."""
   ```
   
   **Verification:**
   - **Inspection:** The docstring no longer refers to pre-change behaviour and 
says the caller attempts the abort when the probe cannot tell.



##########
dev/merge_spark_pr.py:
##########
@@ -1213,8 +1635,31 @@ def _do_cherry_pick(pr_num, merge_hash, pick_ref):
     """Cherry-pick `merge_hash` onto `pick_ref` and push.
 
     Returns the (pushed ref, pushed commit hash) pair. Raises `SkipCherryPick` 
if the
-    cherry-pick conflicts and the committer declines to resolve it, after 
attempting to
-    abort the cherry-pick and restore the working tree.
+    cherry-pick conflicts and the committer declines to resolve it, or 
declines a pre-push
+    check, after attempting to abort the cherry-pick and restore the working 
tree.
+
+    Both pre-push checks run once, before the push prompt, and a declined 
check pushes nothing:
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import Mock, patch
+    >>> def pick(check=Mock()):
+    ...     with (
+    ...         patch("builtins.input", return_value="y"),
+    ...         patch.object(git, "run", return_value="head\\n"),
+    ...         patch.object(git, "push") as push,
+    ...         patch.multiple(sys.modules[__name__], clean_up=Mock(), 
maybe_compile_check=check,
+    ...                        maybe_binding_policy_warning=Mock()),

Review Comment:
   **Nit (P3):** This `Mock()` is never inspected, and `git.run` answers 
`'head'` to every call, so the doctest can't tell whether the binding-policy 
check runs, with which arguments, or when. It would stay green if line 1718 
passed `pick_branch_name` instead of `pick_ref`. That edit would silently 
disable the warning on every pre-4.2 backport, because 
`_is_pre_binding_policy_branch('PR_TOOL_PICK_PR_1_BRANCH-4.1')` is False. It 
would also stay green if the call were deleted or `maybe_compile_check` ran 
twice. CI never runs these doctests, since `dev/sparktestsupport/modules.py` 
lists the script under maintainer tools, and the `main()` doctest mocks 
`cherry_pick`. That leaves this example as the only check on that wiring. Three 
changes would make the opening claim true: assert the mock's call with the 
target branch and the pre-pick head, give `git.run` distinct answers so that 
head is identifiable, and check the call's order against the push prompt.
   
   **Verification:**
   - **Regression:** Each of these edits to the pick step makes the doctest 
fail: passing the local branch name to the binding-policy check, passing a head 
read after the pick, deleting the call, calling it after the push prompt, and 
calling the compile check twice.
   - **Behavior:** A binding-policy decline in the pick-flow doctest raises the 
skip and pushes nothing.



##########
dev/merge_spark_pr.py:
##########
@@ -1035,6 +1110,353 @@ def clean_up():
             git.run("git branch -D %s" % branch)
 
 
+def maybe_compile_check(ref_name: str) -> None:
+    """Offer to run a clean SBT compile of main and test sources before 
pushing `ref_name`.
+
+    `ref_name` is the checked-out cherry-pick, so a clean compile here catches 
a mis-resolved
+    conflict, or a PR that bit-rotted against the target branch, before it 
lands. It is a smoke
+    test (see COMPILE_CHECK_CMD), not CI: modules behind other profiles are 
not compiled.
+    Declining skips the check. A red build asks rather than aborts, because a 
non-zero sbt is
+    as easily a JDK the branch rejects or a failed download as it is the 
backport; declining
+    there skips this branch (see continue_maybe). Output streams so a long 
compile does not
+    look like a hang.
+
+    What is compiled is the working tree, not the commit: a file re-edited 
after the merge
+    commit, or an untracked source file left over from a manual conflict 
resolution, compiles
+    here and is absent from the push. (A resolved-but-never-`git add`ed 
conflict is NOT the
+    case -- the commit itself fails while files are unmerged, so the check is 
never reached.)
+    So warn when the tree is dirty rather than report a green that is about 
something else,
+    and name the remedy (`git add` + `git commit --amend`) since the fix is 
the commit, not
+    the build.
+
+    Declining runs no build and no git -- the git.run mock raises if a 
regression moves a
+    git call above the prompt, which otherwise would run real git in the 
committer's repo on
+    every startup (doctest.testmod() runs on invocation):
+
+    >>> from contextlib import redirect_stdout
+    >>> from io import StringIO
+    >>> from unittest.mock import call, patch
+    >>> with (
+    ...     patch("builtins.input", return_value=""),
+    ...     patch.object(git, "run", side_effect=AssertionError("should not 
run git")),
+    ...     patch("subprocess.call") as run,
+    ...     redirect_stdout(StringIO()),
+    ... ):
+    ...     maybe_compile_check("PR_TOOL_PICK_PR_1_BRANCH-4.1")
+    >>> run.call_count
+    0
+
+    Accepting runs the SBT compile once, from the repo root, with an explicit 
-P so SparkBuild
+    does not fall back to `-Psbt`; a green build returns quietly. The two git 
calls are pinned
+    too -- transposing them or dropping --porcelain would otherwise stay green:
+
+    >>> with (
+    ...     patch("builtins.input", return_value="y"),

Review Comment:
   **Nit (P3):** `return_value='y'` answers any number of prompts, so these 
green-build examples can't show that 'a green build returns quietly'. If the 
`return` after 'Compile check passed.' at line 1263 were deleted, every green 
build would land on 'Compile check did not pass ... Push anyway?', whose 
default answer skips the branch, and these examples would still pass. The 
Ctrl-C/OSError loop at lines 1204-1211 has the mirror gap: it never checks that 
its second `'y'` was used, so returning right after 'Compile check 
interrupted.' would also stay green. Two changes would pin the prompt sequence: 
a one-answer `side_effect`, or an `input.call_count` assertion, here, and a 
call-count check plus a decline variant in that loop.
   
   **Verification:**
   - **Regression:** Removing the return after a passing build, or returning 
right after an interrupted or unrunnable build, makes the compile-check 
doctests fail.
   - **Behavior:** Declining the override after an interrupted build and after 
an unrunnable build each raise the skip.



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

Review Comment:
   **Nit (P3):** This example covers only a decline while a pick is in 
progress. The new no-pick branch is reached only by the decline examples of 
`maybe_compile_check` and `maybe_binding_policy_warning`, and they assert only 
that `SkipCherryPick` was raised. If line 1077 became `if 
_cherry_pick_in_progress() or True:`, the extra abort would exhaust their 
`git.run` side_effect, and the `except Exception` here would swallow the 
`StopIteration`, so they would still pass. The same holds if 
`_cherry_pick_in_progress` answered False on an unexpected exit status or 
exception, which would skip the abort during a real conflict. Two kinds of 
example would pin both: a no-pick decline that asserts no `git cherry-pick 
--abort` call, and probe examples for exit 1, exit 128 and an `OSError`.
   
   **Verification:**
   - **Regression:** Forcing the abort when no pick is in progress, and making 
the probe answer False for an unexpected exit status or exception, each make 
the doctests fail.
   - **Behavior:** The probe returns False for git's exit status 1 and True for 
any other failure.



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