diff --git a/scripts/pr_review.py b/scripts/pr_review.py index 07a110266..d1b771bc3 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -774,7 +774,7 @@ def run_log_reading(state: str, line: str) -> str: def full_read(owner: str, repo: str, num: int, pr: dict | None = None) -> dict: - """The full payload with its changed files paged, read again while that list is unread.""" + """The full payload with its files paged, re-read while they are unread, and its push stamp.""" def read(held: dict | None = None) -> dict: fresh = gql(Q_FULL, owner, repo, num) if held is None else held @@ -782,7 +782,7 @@ def read(held: dict | None = None) -> dict: return fresh pr = backoff(read(pr), read, files_unread, delays=READ_RETRY_DELAYS) - return promotion.attach(pr, owner, repo, num, follow) + return promotion.attach(side.pushed(pr, gh_rest), owner, repo, num, follow) def reread_json(path: str, jq: str) -> object: @@ -1605,10 +1605,11 @@ def run_wait(owner: str, repo: str, a: argparse.Namespace, may_request: bool = T and (copilot is None or a.request or copilot.requests()) ) read_held = functools.partial(gql, Q_HELD, owner, repo, a.number) + logged = side.push_log(gh_rest) await_green = functools.partial(side.await_green, read_held, start, a, backoff) send = functools.partial(gh_graphql, M_COMMENT, subjectId=pr["id"]) ask = functools.partial(side.ask, read_held, a, send, mutated, may_request and pr, gh_rest) - ask("on-open") + asked = ask("on-open") waits = owed and side.holds_for_checks(copilot, a.request) checks_hold = await_green() if waits else "" fresh = gql(Q_LIVE, owner, repo, a.number) if waits and not checks_hold else pr @@ -1675,7 +1676,7 @@ def still_held(polled: dict, registration: bool = False) -> bool: a.check_stall, required_for(polled, owner, repo), ) - or (registration and grace_open(polled, nodes, now) is not None) + or (registration and grace_open(logged(polled), nodes, now) is not None) ) ) @@ -1723,7 +1724,7 @@ def read_live() -> tuple[bool, dict | None, list[str], bool]: live = functools.partial(live_state, owner, repo, a.number, a.min_rounds) backoff((done, answer, drift), live, lambda s: not any(s), start, a.timeout) - sent = ask("after-checks", await_green if polls else None) + sent = ask("after-checks", await_green if polls else None) or asked if regrace is not None: reread = functools.partial(held_read, regrace) polled = backoff(reread() if sent else polled, reread, regrace, start, a.timeout) diff --git a/scripts/pr_review_hold.py b/scripts/pr_review_hold.py index 0c69d0239..6b4a457f3 100644 --- a/scripts/pr_review_hold.py +++ b/scripts/pr_review_hold.py @@ -49,16 +49,24 @@ def side_asks(pr: dict, body: str) -> list[dict]: return sorted(asks, key=lambda n: n.get("createdAt") or "") +PUSHED_KEY = "_headPushedAt" + + def head_arrived(pr: dict) -> str: - """When the head reached the pull request, read as its earliest check suite's creation. + """When the head reached the pull request, the later of its push and its earliest suite. - GitHub creates a head's suites at the push, so a commit's own older timestamp never stands in. - Empty while no suite exists yet, which every reader here takes as a head that just arrived. + The push is the log's newest one ending at the head, where a stamp is attached. So a push back + to a commit checked before reads as that push. A suite is created at the push, or at the + opening where only the pull request runs checks. So it is never earlier than the arrival it + marks. A commit's own older timestamp never stands in. Empty while neither exists yet, which + every reader here takes as a head that just arrived. """ suites = (head_commit(pr).get("checkSuites") or {}).get("nodes") or [] stamps = [n["createdAt"] for n in suites if n.get("createdAt")] stamps += [n["since"] for n in check_nodes(pr) if n.get("since")] - return min(stamps) if stamps else "" + first, pushed = (min(stamps) if stamps else ""), pr.get(PUSHED_KEY) or "" + known = [(at, s) for s in (first, pushed) if (at := utc_instant(s)) is not None] + return max(known)[1] if known else first def hosted_check(node: dict) -> bool: @@ -87,14 +95,15 @@ def hosted_grace(pr: dict, nodes: list[dict]) -> tuple[datetime, datetime] | Non its conclusion never restarts the window. None where nothing anchors it. None also where a CodeRabbit or Qodo check that did not conclude SKIPPED began at or after the newest ask. Its own hold then decides. One older than the ask answers an earlier request, so it ends - nothing. A SKIPPED one is the reviewer declining an automatic review, which an ask can follow. + nothing. Nor does one whose start is unread, since nothing shows it answering the ask. A + SKIPPED one is the reviewer declining an automatic review, which an ask can follow. """ asks = [n.get("createdAt") or "" for body in ASK_BODIES for n in side_asks(pr, body)] newest = max((a for a in map(utc_instant, asks) if a is not None), default=None) def since_ask(node: dict) -> bool: since = utc_instant(node.get("since") or "") - return newest is None or since is None or since >= newest + return newest is None or (since is not None and since >= newest) if any( reviewer_check(n, vocab, login) diff --git a/scripts/pr_review_side.py b/scripts/pr_review_side.py index 8df0bfc7f..b104298f2 100644 --- a/scripts/pr_review_side.py +++ b/scripts/pr_review_side.py @@ -25,7 +25,7 @@ runs_open, utc_instant, ) -from pr_review_hold import head_arrived, hosted_check, side_asks, side_command +from pr_review_hold import PUSHED_KEY, head_arrived, hosted_check, side_asks, side_command from pr_review_payload import bot_entry, default_branch from pr_review_rounds import ( CODERABBIT_LOGIN, @@ -39,7 +39,6 @@ COMMENT_PATH = ("addComment", "commentEdge", "node") SIDE_LOGINS = {"coderabbit": CODERABBIT_LOGIN, "qodo": QODO_LOGIN} -PUSHED_KEY = "_headPushedAt" PUSHED_JQ = 'map(select(.after == "{}") | .timestamp) | max // empty' @@ -84,6 +83,27 @@ def pushed(pr: dict, rest: Callable[[str, str], CompletedProcess]) -> dict: return {**pr, PUSHED_KEY: proc.stdout.strip() if proc and proc.returncode == 0 else ""} +def push_log(rest: Callable[[str, str], CompletedProcess]) -> Callable[[dict], dict]: + """`pushed` keeping each head's stamp once read, for a poll that judges one head many times. + + The stamp does not move while the head holds. A read that failed or found no entry is not + kept, so a later poll still asks. The log can record a push after the poll began. + """ + found: dict[tuple, str] = {} + + def read(pr: dict) -> dict: + where = (pr.get("headRepository") or {}).get("nameWithOwner") + key = (where, pr.get("headRefName"), pr.get("headRefOid")) + if key in found: + return {**pr, PUSHED_KEY: found[key]} + stamped = pushed(pr, rest) + if stamped[PUSHED_KEY]: + found[key] = stamped[PUSHED_KEY] + return stamped + + return read + + def side_asked_on_head(pr: dict, body: str) -> bool: """Whether a request `body` was posted since the head was pushed, both stamps GitHub's own. diff --git a/tests/test_pr_review.py b/tests/test_pr_review.py index 0fb621801..2edd41fb2 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -5083,6 +5083,56 @@ def test_an_ask_this_wait_sent_is_read_back_before_the_grace_is_judged(self) -> self.assertEqual(code, self.cli(["wait", "7", "--timeout", "0"])) self.assertEqual(reads, len(gql.call_args_list)) + def test_an_on_open_ask_is_read_back_before_the_grace_is_judged(self) -> None: + """An ask sent before the poll moves the anchor too, though the after-checks one sent none. + + The snapshot the poll starts from was read before that ask, so judging it would release. + """ + done = {**check(started=real_ago(900)), "completedAt": real_ago(600)} + before = self.into(payload([review(oid=OLD)], checks=[done]), attest=True) + ask = { + "author": {"login": "maintainer"}, + "authorAssociation": "OWNER", + "createdAt": real_ago(5), + "body": "@coderabbitai review", + } + after = {**before, "comments": {**before["comments"]}} + after["comments"]["nodes"] = [*before["comments"]["nodes"], ask] + self.answer(before, before, after) + gql = self.enterContext(mock.patch.object(pr_review, "gql", side_effect=pr_review.gql)) + self.wire_history([hist_review(7, OVERVIEW + "\n" + COVERED)]) + with ( + mock.patch.object(pr_review.side, "ask", side_effect=lambda *a: a[6] == "on-open"), + mock.patch.object(pr_review.time, "sleep"), + ): + self.assertEqual(30, self.cli(["wait", "7", "--timeout", "0"])) + self.assertEqual(4, len(gql.call_args_list)) + self.assertIn("(registration grace until: ", self.out.getvalue()) + + def test_the_push_log_anchors_the_grace_on_a_head_pushed_again(self) -> None: + """A commit checked before keeps its old suites, so only the push log dates its new push.""" + done = {**check(started=real_ago(900)), "completedAt": real_ago(600)} + pr = self.into(payload([review(oid=OLD)], checks=[done]), attest=True) + pr = {**pr, "headRefName": "feature", "headRepository": {"nameWithOwner": "o/r"}} + for logged, code, reads in ((real_ago(10), 30, 2), ("", 0, 3)): + with self.subTest(logged=logged): + + def rest(path: str, *_: object, logged: str = logged, **__: object) -> object: + ok = "/activity?" in path and logged + out = logged if ok else "" + return subprocess.CompletedProcess([], 0 if ok else 1, out, "") + + self.answer(pr) + self.wire_history([hist_review(7, OVERVIEW + "\n" + COVERED)]) + with ( + mock.patch.object(pr_review, "gh_rest", side_effect=rest) as read, + mock.patch.object(pr_review.side, "ask", return_value=True), + mock.patch.object(pr_review.time, "sleep"), + ): + self.assertEqual(code, self.cli(["wait", "7", "--timeout", "0"])) + logs = [c for c in read.call_args_list if "/activity?" in c.args[0]] + self.assertEqual(reads, len(logs), "a found stamp is kept, a miss asked again") + def test_a_rate_limited_hosted_review_does_not_hold_an_attested_head(self) -> None: """The marker and both reply shapes end the wait, and the digest still reports the limit.""" for body in ( @@ -8345,6 +8395,60 @@ def test_a_hosted_check_older_than_the_newest_ask_leaves_the_window_open(self) - if got is not None: self.assertEqual(ago(120), pr_review_hold.stamp(got[0])) + def test_a_hosted_check_whose_start_is_unread_leaves_an_asked_window_open(self) -> None: + """A null `startedAt` cannot show the check answering the ask, so it ends nothing. + + With no ask on record any hosted check on the head still ends the window. + """ + settled = {**check(started=ago(900)), "completedAt": ago(600)} + for status, conclusion in (("QUEUED", ""), ("COMPLETED", "SUCCESS")): + with self.subTest(status=status): + unread = { + **check( + name="CodeRabbit", status=status, conclusion=conclusion, slug="coderabbitai" + ), + "startedAt": None, + } + got = self.window([settled, unread], [self.ask(ago(120))]) + assert got is not None + self.assertEqual(ago(120), pr_review_hold.stamp(got[0])) + self.assertIsNone(self.window([settled, unread])) + + def test_the_push_log_stamp_dates_the_head_over_its_older_suites(self) -> None: + """A push back to a commit checked before keeps that commit's suites, which predate it. + + A push older than the suites is a branch the pull request opened on later, so the suites + stand in. A stamp that does not parse is no stamp, so they stand in then as well. + """ + settled = {**check(started=ago(900)), "completedAt": ago(600)} + pr = payload([review()], checks=[settled]) + nodes = pr_review_checks.check_nodes(pr) + self.assertEqual(ago(900), pr_review_hold.head_arrived(pr)) + early = {**pr, pr_review_hold.PUSHED_KEY: ago(1200)} + self.assertEqual(ago(900), pr_review_hold.head_arrived(early)) + for logged, want in ((ago(30), ago(30)), ("not a stamp", ago(600)), ("", ago(600))): + with self.subTest(logged=logged): + pushed = {**pr, pr_review_hold.PUSHED_KEY: logged} + got = pr_review_hold.hosted_grace(pushed, nodes) + assert got is not None + self.assertEqual(want, pr_review_hold.stamp(got[0])) + + def test_the_push_log_keeps_a_found_stamp_and_asks_again_after_a_miss(self) -> None: + """A held poll reads one head many times, and the log can record its push mid-poll.""" + answers = iter( + [ + subprocess.CompletedProcess([], 1, "", "rate limited"), + subprocess.CompletedProcess([], 0, ago(30), ""), + ] + ) + rest = mock.Mock(side_effect=lambda *_: next(answers)) + read = pr_review.side.push_log(rest) + pr = {**payload([review()]), "headRefName": "feature"} + pr["headRepository"] = {"nameWithOwner": "o/r"} + got = [read(pr)[pr_review_hold.PUSHED_KEY] for _ in range(3)] + self.assertEqual(["", ago(30), ago(30)], got) + self.assertEqual(2, rest.call_count) + def test_the_grace_is_open_until_its_end_and_noted_either_way(self) -> None: settled = {**check(started=ago(900)), "completedAt": ago(30)} pr = payload([review()], checks=[settled])