From 0960ca6d86531605b02bc35d0b8846e65a05272a Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 19 Nov 2026 21:23:17 -0800 Subject: [PATCH 1/3] Hold the Registration Grace on an Unread Start, a Re-Pushed Head, and an On-Open Ask A hosted check whose startedAt is null no longer ends a grace an ask anchors, since nothing shows it answering the ask. head_arrived prefers the push-log stamp over the head's earliest suite, so a push back to a commit checked before dates from that push. full_read and the held poll's registration test attach the stamp. wait now counts an on-open ask as sent, so the grace is judged on a read taken after it. Co-Authored-By: Claude Opus 5.5 --- scripts/pr_review.py | 13 ++++--- scripts/pr_review_hold.py | 18 ++++++--- scripts/pr_review_side.py | 3 +- tests/test_pr_review.py | 82 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 12 deletions(-) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index 07a110266..6815ed894 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: @@ -1608,7 +1608,7 @@ def run_wait(owner: str, repo: str, a: argparse.Namespace, may_request: bool = T 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 +1675,10 @@ 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(side.pushed(polled, gh_rest), nodes, now) is not None + ) ) ) @@ -1723,7 +1726,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..071a40a05 100644 --- a/scripts/pr_review_hold.py +++ b/scripts/pr_review_hold.py @@ -49,12 +49,19 @@ 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, read as the push log's stamp where one is attached. - 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 log's newest push ending at the head counts, so a push back to a commit checked before + reads as that push. Without it the head's earliest check suite's creation stands in. GitHub + creates a head's suites at the push, and 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. """ + if utc_instant(pr.get(PUSHED_KEY) or "") is not None: + return pr[PUSHED_KEY] 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")] @@ -87,14 +94,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..daf535296 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' diff --git a/tests/test_pr_review.py b/tests/test_pr_review.py index 0fb621801..1345ddd37 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -5083,6 +5083,53 @@ 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 in ((real_ago(10), 30), ("", 0)): + 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), + mock.patch.object(pr_review.time, "sleep"), + ): + self.assertEqual(code, self.cli(["wait", "7", "--timeout", "0"])) + 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 +8392,41 @@ 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 stamp that does not parse is no stamp, so the suites stand in as they do without one. + """ + 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)) + 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_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]) From 052056c3a4be6f1dba5a7dec62d2025e4d618204 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 19 Nov 2026 21:36:12 -0800 Subject: [PATCH 2/3] Anchor on the Later of the Push and the Earliest Suite, Read the Push Log Once per Wait head_arrived takes the later of the push-log stamp and the earliest suite, so a pull request opened on a branch pushed earlier dates from the suites its opening ran, never earlier than before. The held wait caches the push-log read, so its registration test reads one head once. Co-Authored-By: Claude Opus 5.5 --- scripts/pr_review.py | 3 ++- scripts/pr_review_hold.py | 17 +++++++++-------- tests/test_pr_review.py | 10 ++++++++-- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index 6815ed894..79c8452b0 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -1605,6 +1605,7 @@ 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 = functools.cache(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) @@ -1677,7 +1678,7 @@ def still_held(polled: dict, registration: bool = False) -> bool: ) or ( registration - and grace_open(side.pushed(polled, gh_rest), nodes, now) is not None + and grace_open(side.pushed(polled, logged), nodes, now) is not None ) ) ) diff --git a/scripts/pr_review_hold.py b/scripts/pr_review_hold.py index 071a40a05..55147c031 100644 --- a/scripts/pr_review_hold.py +++ b/scripts/pr_review_hold.py @@ -53,19 +53,20 @@ def side_asks(pr: dict, body: str) -> list[dict]: def head_arrived(pr: dict) -> str: - """When the head reached the pull request, read as the push log's stamp where one is attached. + """When the head reached the pull request, the later of its push and its earliest suite. - The log's newest push ending at the head counts, so a push back to a commit checked before - reads as that push. Without it the head's earliest check suite's creation stands in. GitHub - creates a head's suites at the push, and 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. + 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. """ - if utc_instant(pr.get(PUSHED_KEY) or "") is not None: - return pr[PUSHED_KEY] 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 = min(stamps) if stamps else "" + known = [s for s in (first, pr.get(PUSHED_KEY) or "") if utc_instant(s) is not None] + return max(known, key=lambda s: utc_instant(s) or datetime.min) if known else first def hosted_check(node: dict) -> bool: diff --git a/tests/test_pr_review.py b/tests/test_pr_review.py index 1345ddd37..3893b379a 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -5125,10 +5125,13 @@ def rest(path: str, *_: object, logged: str = logged, **__: object) -> object: self.answer(pr) self.wire_history([hist_review(7, OVERVIEW + "\n" + COVERED)]) with ( - mock.patch.object(pr_review, "gh_rest", side_effect=rest), + 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(2, len(logs), "the held poll's reads of one head, then full_read") 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.""" @@ -8414,12 +8417,15 @@ def test_a_hosted_check_whose_start_is_unread_leaves_an_asked_window_open(self) 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 stamp that does not parse is no stamp, so the suites stand in as they do without one. + 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} From 2245dfc10aaf04eabd629cf2cf9fcb9eef44c199 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Thu, 19 Nov 2026 21:48:01 -0800 Subject: [PATCH 3/3] Keep Only a Found Push Stamp, Parse Each Arrival Instant Once The held wait's push-log reader keeps a head's stamp once found and asks again after a failed or empty read, since the log can record the push mid-poll. head_arrived parses each candidate instant once rather than keying max on a fallback no stamp reaches. Co-Authored-By: Claude Opus 5.5 --- scripts/pr_review.py | 7 ++----- scripts/pr_review_hold.py | 6 +++--- scripts/pr_review_side.py | 21 +++++++++++++++++++++ tests/test_pr_review.py | 20 ++++++++++++++++++-- 4 files changed, 44 insertions(+), 10 deletions(-) diff --git a/scripts/pr_review.py b/scripts/pr_review.py index 79c8452b0..d1b771bc3 100755 --- a/scripts/pr_review.py +++ b/scripts/pr_review.py @@ -1605,7 +1605,7 @@ 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 = functools.cache(gh_rest) + 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) @@ -1676,10 +1676,7 @@ def still_held(polled: dict, registration: bool = False) -> bool: a.check_stall, required_for(polled, owner, repo), ) - or ( - registration - and grace_open(side.pushed(polled, logged), nodes, now) is not None - ) + or (registration and grace_open(logged(polled), nodes, now) is not None) ) ) diff --git a/scripts/pr_review_hold.py b/scripts/pr_review_hold.py index 55147c031..6b4a457f3 100644 --- a/scripts/pr_review_hold.py +++ b/scripts/pr_review_hold.py @@ -64,9 +64,9 @@ def head_arrived(pr: dict) -> str: 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")] - first = min(stamps) if stamps else "" - known = [s for s in (first, pr.get(PUSHED_KEY) or "") if utc_instant(s) is not None] - return max(known, key=lambda s: utc_instant(s) or datetime.min) if known else first + 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: diff --git a/scripts/pr_review_side.py b/scripts/pr_review_side.py index daf535296..b104298f2 100644 --- a/scripts/pr_review_side.py +++ b/scripts/pr_review_side.py @@ -83,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 3893b379a..2edd41fb2 100755 --- a/tests/test_pr_review.py +++ b/tests/test_pr_review.py @@ -5114,7 +5114,7 @@ def test_the_push_log_anchors_the_grace_on_a_head_pushed_again(self) -> None: 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 in ((real_ago(10), 30), ("", 0)): + 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: @@ -5131,7 +5131,7 @@ def rest(path: str, *_: object, logged: str = logged, **__: object) -> object: ): 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(2, len(logs), "the held poll's reads of one head, then full_read") + 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.""" @@ -8433,6 +8433,22 @@ def test_the_push_log_stamp_dates_the_head_over_its_older_suites(self) -> None: 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])