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


##########
dev/merge_spark_pr.py:
##########
@@ -3568,6 +4158,47 @@ def main():
 
 
 __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]

Review Comment:
   **Non-blocking (P2):** `read_text()` with no encoding decodes with the 
locale's preferred encoding unless Python's UTF-8 mode is on, and this file 
already has em-dashes on six comment and docstring lines. Because 
`doctest.testmod()` runs this example before `main()` on every invocation, a 
committer whose locale cannot decode them can no longer start the script: the 
example raises `UnicodeDecodeError`, the self-test fails, and the entry point 
exits -1. That covers East Asian Windows code pages, legacy EUC, GBK and Big5 
locales, and an ASCII locale with UTF-8 mode off, on Python versions before 
3.15, where UTF-8 mode becomes the default. UTF-8 locales and a plain C locale, 
where Python turns UTF-8 mode on itself, are fine.
   
   In a run under `LC_ALL=C PYTHONCOERCECLOCALE=0 python3 -X utf8=0`, the base 
branch's self-test passed, while this head's failed 3 examples in 
`abort_entrypoint`, starting at this line; with only this line changed to 
`read_bytes()`, `abort_entrypoint` passed. `ast.parse` decodes bytes by the 
same PEP 263 rules the interpreter used to load the file:
   
   ```suggestion
       >>> entrypoint = ast.parse(Path(__file__).read_bytes()).body[-1]
   ```
   
   **Verification:**
   - **Regression:** With UTF-8 mode off and a preferred encoding that cannot 
decode the file's non-ASCII characters, such as ASCII or a Japanese or Chinese 
code page, the startup self-test passes and the script starts.
   - **Inspection:** No doctest or other code that runs before main() reads a 
file as text without an explicit encoding.



##########
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:
   Thanks, I checked this: with the flag set, `clean_up()` returns before 
running any git, so declining the JIRA prompt, a second error in `main()`'s 
`finally` blocks, and the entry point's handler all leave the pick branch and 
the edits alone, while an ordinary exit still cleans up. This review raises one 
related problem separately: the doctest's closing check that the startup 
self-test leaves the flag off cannot fail.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4576986606","thread_id":"inline:4576986606","verdict_sha256":"5df1fe3ef02a1e16928ec95b68ab06ffbccb197c9f152b6417fb1b2ef47e512f"}
 -->



##########
dev/merge_spark_pr.py:
##########
@@ -1368,6 +1924,27 @@ def cherry_pick(pr_num, merge_hash, default_branch, 
branch_names, target_ref, al
     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.
+    `record` gets each pair as it lands, so one survives a later pick that 
ends the run:

Review Comment:
   **Nit (P3):** `main()` no longer reads what `cherry_pick` returns: both 
calls discard it, and the merge comment, the JIRA branches, and the next 
default branch now come only from `record`. The rest of this paragraph still 
says the returned list is how "the main loop can advance its remaining-branches 
list correctly and record each backport commit for the merge comment", and 
names only a declined conflict as what shortens it, although declining a 
pre-push check now skips a branch too. The Upstream-First comment below 
likewise still says returning branch-M.x is what records it, with `record` as a 
backup for when the branch-M.N pick ends the run. A maintainer who reads this 
could drop `record=record` from a call in `main()`, which would silently leave 
those picks out of the merge comment and the JIRA update, or restore the old 
accumulation next to `record`, which would record each pick twice.
   
   The paragraph and that comment could say that each pick hands its pair to 
`record` once it returns, that `main()` uses only those pairs, that the 
returned list holds the same pairs and nothing reads it, and that a branch is 
skipped, with nothing recorded, when the committer declines to resolve a 
conflict or declines to push past a pre-push check.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576986612).
   
   See **Shared repair plan 1** in the review body.



##########
dev/merge_spark_pr.py:
##########
@@ -3568,6 +4158,47 @@ def main():
 
 
 __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):** This name resolves in the doctest's own copy of the module 
globals, which `testmod()` takes when it collects the tests, but 
`_restore_original_head` sets the flag with `global` in the live module dict 
that `clean_up()` reads. So the check always prints the collected `False` and 
cannot catch a leak. With `clean_up.__globals__['preserve_local_state'] = True` 
inserted just before this line, every startup doctest still passed and the live 
flag stayed `True`, so the real run would have started with every `clean_up()` 
a no-op. Today nothing leaks only because both `[a]`-answering examples run 
inside `patch.dict` over the module globals. Reading the live flag makes this 
check meaningful for `abort_entrypoint`:
   
   ```suggestion
       >>> clean_up.__globals__["preserve_local_state"]
   ```
   
   `testmod()` runs tests in name order, though, so `continue_maybe`'s 
`[a]bort` example runs after this one. To cover it as well, the entry point can 
treat a flag still set after `testmod()` returns as a failed self-test and exit 
before `main()`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576986606).
   
   **Verification:**
   - **Regression:** Leaving the live flag set before the closing check of 
abort_entrypoint makes that doctest fail.
   - **Regression:** Leaving the live flag set after any [a]-answering example, 
including continue_maybe's, which runs after abort_entrypoint, stops the script 
before main() with a self-test failure.
   - **Compatibility:** When no example leaks the flag, the script starts, an 
ordinary exit still restores the starting branch and deletes the PR_TOOL_* 
branches, and the self-test's replay of the entry point still shows an abort 
leaving git alone on every route out.



##########
dev/merge_spark_pr.py:
##########
@@ -1381,6 +1958,12 @@ 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):
+        pair = _do_cherry_pick(pr_num, merge_hash, ref)
+        if record:
+            record(pair)

Review Comment:
   **Nit (P3):** `record` runs only once `_do_cherry_pick` returns, which is 
after the `clean_up()` that follows the push. If that cleanup raises, for 
example because `git checkout` of the starting branch refuses over an 
uncommitted edit to a file that differs between the two branches, the push has 
landed but this line never runs, so that branch is missing from the merge 
comment and the JIRA update. Leaving that case out of this PR is fine, as you 
said in the earlier thread, but nothing here tells a reader so, and the 
docstring above says `record` gets each pair "as it lands". A TODO here naming 
the case, for example that a push whose post-push `clean_up()` raises is never 
recorded and that recording inside `_do_cherry_pick` right after `git.push` 
would cover it, would mark the gap as deliberate.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576986612).
   
   See **Shared repair plan 1** in the review body.



##########
dev/merge_spark_pr.py:
##########
@@ -3530,6 +4117,10 @@ def main():
     # 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.
+    def record(pair):

Review Comment:
   **Nit (P3):** This closure and its backport-only twin now decide what the 
merge comment and the JIRA update report, but no doctest reaches either. 
`main_titles` replaces `cherry_pick` with a stand-in that still returns 
`[('branch-4.x', 'd')]` and never calls `record`, leaves `post_merge_comment` 
unasserted, and checks only the title `update_jira_for_pr` receives. The one 
test of the channel, in `cherry_pick`'s docstring, exits on its second pick, so 
it pins only the first `[b]oth` pick.
   
   Each of these edits left every startup doctest passing: calling 
`_do_cherry_pick` directly instead of the recording wrapper at the plain pick, 
the `[o]nly` pick, or the second `[b]oth` pick; dropping `record=record` from 
the merge-path call; or dropping an append from either closure. No CI job runs 
these doctests, so the self-test is the only signal. Covering those pick sites 
in `cherry_pick`'s doctest, and giving a `main()` doctest a stand-in that calls 
the `record` it receives, including a run whose later pick exits, with 
assertions on the pairs `post_merge_comment` receives and the branches 
`update_jira_for_pr` receives, would make those regressions fail.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60471#discussion_r4576986612).
   
   **Verification:**
   - **Regression:** Recording is asserted at the plain, [o]nly, and returning 
second [b]oth pick sites, so routing any of them around the recording wrapper 
fails the self-test, and a skipped pick records nothing for its branch.
   - **Regression:** Through main(), on the merge path and on a backport-only 
run, the pairs the merge comment receives and the branches the JIRA update 
receives include every recorded pick, including one recorded before a later 
pick ends the run.



##########
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:
   Thanks, I checked the callback: every pick site goes through it, and both 
loops in `main()` now build the merge comment and the JIRA branches from it, so 
a branch-M.x pick reaches both when the branch-M.N half ends the run. Leaving 
the failed-cleanup case out of this PR is fine. This review raises three 
related points separately: a missing TODO for that deferred case, 
`cherry_pick`'s docstring still describing its return value as what the main 
loop records from, and doctest coverage of the recording through `main()` and 
on the other pick paths.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4576986612","thread_id":"inline:4576986612","verdict_sha256":"5df1fe3ef02a1e16928ec95b68ab06ffbccb197c9f152b6417fb1b2ef47e512f"}
 -->



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