From af53554f1ea307d828a11b0f77d66f7d4455bfa6 Mon Sep 17 00:00:00 2001 From: Chandler Carruth Date: Fri, 20 Nov 2026 17:47:40 +0000 Subject: [PATCH] Keep the changes link on dependent PR comments until rebase/merge (#8163) Previously, the dependent PR workflow updated the comment as soon as all dependency PRs were merged in a way that removed the changes link that helps with identifying the start of review. If the PR hadn't yet been rebased or merged trunk, this made it hard to review again. =/ This PR fixes it by detecting when we haven't rebased or merged far enough to just review the PR as a whole, and preserves the review link. And once `trunk` _has_ been merged far enough (or PR has been rebased), updates the comment again to reflect that. This requires persisting the `review_base` in the hidden JSON of the comment, and somewhat more interesting API queries to manage this. Docs are also updated. Assisted-by: Antigravity with Gemini --- docs/project/pull_request_workflow.md | 3 +- github_tools/check_dependent_pr.py | 145 +++++++++++++++++--- github_tools/check_dependent_pr_test.py | 169 +++++++++++++++++++++++- 3 files changed, 297 insertions(+), 20 deletions(-) diff --git a/docs/project/pull_request_workflow.md b/docs/project/pull_request_workflow.md index 5deed1691c27..e3202619e1e8 100644 --- a/docs/project/pull_request_workflow.md +++ b/docs/project/pull_request_workflow.md @@ -117,7 +117,8 @@ commits: request's commits, and leaves its status `pending` so it doesn't merge before its dependencies. - Once those pull requests merge, the check removes the `dependent` label, - updates the comment, and marks the status `success`. + updates the comment (preserving the review link until the pull request is + rebased or merges `trunk`), and marks the status `success`. If the check becomes stale, editing the pull request description runs it again. Contributors with write access can also re-run the workflow job from the check's diff --git a/github_tools/check_dependent_pr.py b/github_tools/check_dependent_pr.py index 266f89248277..2ff84ef5a0df 100755 --- a/github_tools/check_dependent_pr.py +++ b/github_tools/check_dependent_pr.py @@ -104,6 +104,9 @@ query GetPrDetails($prNumber: Int!) { nodes { commit { oid + parents { + totalCount + } } } } @@ -119,6 +122,18 @@ query GetPrDetails($prNumber: Int!) { } """ +_QUERY_PR_MERGE_COMMIT = """ +query GetPrMergeCommit($prNumber: Int!) { + repository(owner: "carbon-language", name: "carbon-lang") { + pullRequest(number: $prNumber) { + mergeCommit { + oid + } + } + } +} +""" + _QUERY_LABEL = """ { repository(owner: "carbon-language", name: "carbon-lang") { @@ -198,17 +213,29 @@ def _parse_pr_number(x: Any) -> Optional[int]: return None +def _parse_oid(value: Any, field: str, pr_number: int) -> Optional[str]: + """Parses and validates an optional 40-character hex commit OID.""" + if value is None: + return None + if isinstance(value, str) and re.fullmatch(r"[0-9a-fA-F]{40}", value): + return value + raise ValueError( + f"PR #{pr_number}: Invalid commit OID format in '{field}': {value}" + ) + + def _parse_and_validate_state( json_str: str, open_pr_numbers: set[int], max_merged_pr: int = 10000, pr_number: int = 0, -) -> tuple[list[int], list[int], list[int], Optional[str]]: +) -> tuple[list[int], list[int], list[int], Optional[str], Optional[str]]: """Parses and validates the state from a JSON string.""" parsed_open: list[int] = [] parsed_merged: list[int] = [] parsed_ignored: list[int] = [] first_commit: Optional[str] = None + review_base: Optional[str] = None raw_state = json.loads(json_str) if not isinstance(raw_state, dict): @@ -261,17 +288,58 @@ def _parse_and_validate_state( else: parsed_ignored.append(val) if "first_commit" in raw_state: - fc = raw_state["first_commit"] - if fc is None: - first_commit = None - elif isinstance(fc, str) and re.fullmatch(r"[0-9a-fA-F]{40}", fc): - first_commit = fc - else: - raise ValueError( - f"PR #{pr_number}: Invalid commit OID format in " - f"'first_commit': {fc}" + first_commit = _parse_oid( + raw_state["first_commit"], "first_commit", pr_number + ) + if "review_base" in raw_state: + review_base = _parse_oid( + raw_state["review_base"], "review_base", pr_number + ) + return ( + parsed_open, + parsed_merged, + parsed_ignored, + first_commit, + review_base, + ) + + +def _are_merged_deps_in_head( + client: github_helpers.Client, + head_oid: str, + merged_deps: list[int], + token: str, +) -> bool: + """Returns true if every merged dep's merge commit is in `head_oid`.""" + headers = { + "Authorization": f"bearer {token}", + "Accept": "application/vnd.github.v3+json", + } + for dep in merged_deps: + res = client.execute( + _QUERY_PR_MERGE_COMMIT, variable_values={"prNumber": dep} + ) + pr = res["repository"]["pullRequest"] + merge_oid = ( + pr["mergeCommit"]["oid"] if pr and pr.get("mergeCommit") else None + ) + if not merge_oid: + return False + url = ( + "https://api.github.com/repos/carbon-language/carbon-lang/" + f"compare/{merge_oid}...{head_oid}" + ) + try: + response = requests.get( + url, headers=headers, params={"per_page": 1}, timeout=30 ) - return parsed_open, parsed_merged, parsed_ignored, first_commit + response.raise_for_status() + if response.json().get("status") not in ("ahead", "identical"): + return False + except Exception as e: + _print_err(f"Error comparing {merge_oid[:8]}...{head_oid[:8]}: {e}") + return False + return True def _set_commit_status( @@ -390,6 +458,7 @@ def _process_pr( parsed_merged_deps: list[int] = [] parsed_ignored_deps: list[int] = [] previous_first_commit: Optional[str] = None + previous_review_base: Optional[str] = None matching_comment = None for comment in comments: @@ -410,9 +479,16 @@ def _process_pr( parsed_merged_deps, parsed_ignored_deps, previous_first_commit, + previous_review_base, ) = _parse_and_validate_state( body[start:end], open_pr_numbers, max_merged_pr, pr_number ) + # Preserve the review link from comments created before `review_base` + # was persisted in the JSON state. + if previous_review_base is None: + match = re.search(r"/changes/([0-9a-fA-F]{40})\.\.HEAD\)", body) + if match: + previous_review_base = match.group(1) has_dependent_label = any(label["name"] == "dependent" for label in labels) @@ -475,6 +551,8 @@ def _process_pr( description = "This PR has no open dependencies" first_non_dep_oid = None + review_base: Optional[str] = None + any_later_dep_oids = False if open_deps: dep_oids = set() for d in open_deps: @@ -499,10 +577,9 @@ def _process_pr( # Find the most recent commit in the current PR that is also in the # last dependency PR. - last_dep_head_oid = None for oid in reversed(current_oids): if oid in last_dep_oids: - last_dep_head_oid = oid + review_base = oid break # Detect non-linear history: any commit in the current PR that is in @@ -510,6 +587,25 @@ def _process_pr( any_later_dep_oids = any( oid in dep_oids and oid not in last_dep_oids for oid in current_oids ) + elif ( + not ignored_deps + and merged_deps + and previous_review_base + and previous_review_base in current_oids + ): + # After dependencies squash-merge into `trunk`, their commits still + # appear in this PR's diff until this PR is rebased (dropping + # `previous_review_base`) or merges `trunk` past every merged + # dependency. + base_idx = current_oids.index(previous_review_base) + has_merge_after_base = any( + c["commit"].get("parents", {}).get("totalCount", 1) > 1 + for c in commits[base_idx + 1 :] + ) + if not has_merge_after_base or not _are_merged_deps_in_head( + client, pr_node["headRefOid"], merged_deps, token + ): + review_base = previous_review_base # Construct new comment timestamp = datetime.datetime.now(datetime.timezone.utc).strftime( @@ -520,6 +616,8 @@ def _process_pr( "merged": merged_deps, "first_commit": first_non_dep_oid, } + if review_base: + new_state["review_base"] = review_base if ignored_deps: new_state["ignored"] = ignored_deps state_json = json.dumps(new_state) @@ -528,10 +626,10 @@ def _process_pr( if open_deps: pr_list_str = ", ".join([f"#{num}" for num in open_deps]) - if last_dep_head_oid: + if review_base: changes_url = ( "https://github.com/carbon-language/carbon-lang/pull/" - f"{pr_number}/changes/{last_dep_head_oid}..HEAD" + f"{pr_number}/changes/{review_base}..HEAD" ) comment_body += ( f"Depends on {pr_list_str}, start review with " @@ -552,7 +650,21 @@ def _process_pr( ignored_str = ", ".join([f"#{num}" for num in ignored_deps]) comment_body += f"Dependency check overridden (ignoring {ignored_str})." elif merged_deps: - comment_body += "All dependency PRs are merged." + if review_base: + changes_url = ( + "https://github.com/carbon-language/carbon-lang/pull/" + f"{pr_number}/changes/{review_base}..HEAD" + ) + comment_body += ( + "All dependency PRs are merged. Until this PR is rebased or " + "merges `trunk`, start review with " + f"[these changes]({changes_url})." + ) + else: + comment_body += ( + "All dependency PRs are merged; the full set of changes is now " + "ready to review." + ) else: comment_body += "No open dependency PRs." @@ -602,6 +714,7 @@ def _process_pr( and merged_deps == parsed_merged_deps and ignored_deps == parsed_ignored_deps and first_non_dep_oid == previous_first_commit + and review_base == previous_review_base ): return diff --git a/github_tools/check_dependent_pr_test.py b/github_tools/check_dependent_pr_test.py index c0f240c6f41c..50a197c1d932 100644 --- a/github_tools/check_dependent_pr_test.py +++ b/github_tools/check_dependent_pr_test.py @@ -47,7 +47,9 @@ class TestCheckDependentPR(unittest.TestCase): merged_deps: list[int] = None, first_commit: str = None, ignored_deps: list[int] = None, + review_base: str = None, comment_id: str = "comment_id", + extra_body: str = "", ) -> dict[str, str]: """Builds a boilerplate PR comment.""" state: dict[str, Any] = { @@ -56,11 +58,16 @@ class TestCheckDependentPR(unittest.TestCase): } if first_commit: state["first_commit"] = first_commit + if review_base: + state["review_base"] = review_base if ignored_deps: state["ignored"] = ignored_deps + body = f"" + if extra_body: + body += f"\n{extra_body}" return { "id": comment_id, - "body": f"", + "body": body, } def _make_pr_response( @@ -70,6 +77,7 @@ class TestCheckDependentPR(unittest.TestCase): commits: list[str], comments: list[dict[str, str]] = None, has_dependent_label: bool = False, + merge_commits: set[str] = None, ) -> dict[str, Any]: """Builds a boilerplate GitHub response for a PR.""" labels = ( @@ -77,6 +85,7 @@ class TestCheckDependentPR(unittest.TestCase): if has_dependent_label else [] ) + merge_set = merge_commits or set() return { "repository": { "pullRequest": { @@ -84,7 +93,19 @@ class TestCheckDependentPR(unittest.TestCase): "headRefOid": head_ref_oid, "labels": {"nodes": labels}, "commits": { - "nodes": [{"commit": {"oid": oid}} for oid in commits] + "nodes": [ + { + "commit": { + "oid": oid, + "parents": { + "totalCount": ( + 2 if oid in merge_set else 1 + ) + }, + } + } + for oid in commits + ] }, "comments": {"nodes": comments if comments else []}, } @@ -262,7 +283,11 @@ class TestCheckDependentPR(unittest.TestCase): pr_id="pr_6", head_ref_oid=_OID2, commits=[_OID1, _OID2], - comments=[self._make_comment(open_deps=[1], first_commit=_OID2)], + comments=[ + self._make_comment( + open_deps=[1], first_commit=_OID2, review_base=_OID1 + ) + ], has_dependent_label=True, ) check_dependent_pr._process_pr( @@ -679,6 +704,144 @@ class TestCheckDependentPR(unittest.TestCase): _OID2, "success", "This PR has no open dependencies" ) + def test_process_pr_preserves_link_on_merge_and_clears_on_rebase( + self, + ) -> None: + # Existing comment from before `review_base` was stored in JSON still + # preserves the link when the dependency merges. + legacy_link = ( + "Depends on #1, start review with " + "[these changes](https://github.com/carbon-language/carbon-lang/" + f"pull/3/changes/{_OID1}..HEAD)" + ) + self.mock_client.execute.return_value = self._make_pr_response( + pr_id="pr_3", + head_ref_oid=_OID2, + commits=[_OID1, _OID2], + comments=[ + self._make_comment(open_deps=[1], extra_body=legacy_link) + ], + has_dependent_label=True, + ) + check_dependent_pr._process_pr( + self.mock_client, + pr_number=3, + pr_to_commits={3: {_OID1, _OID2}}, + pr_to_head={3: _OID2}, + open_pr_numbers={3}, + label_id="label_dependent", + token="test_token", + ) + calls = self.mock_client.execute.call_args_list + body = calls[2][1]["variable_values"]["body"] + self.assertIn(f'"review_base": "{_OID1}"', body) + self.assertIn(f"/pull/3/changes/{_OID1}..HEAD", body) + self._assert_status( + _OID2, "success", "This PR has no open dependencies" + ) + + # Rebasing drops `_OID1` from the PR commits, clearing the link. + self.mock_post.reset_mock() + self.mock_client.reset_mock() + self.mock_client.execute.return_value = self._make_pr_response( + pr_id="pr_3", + head_ref_oid=_OID3, + commits=[_OID3], + comments=[ + self._make_comment( + open_deps=[], merged_deps=[1], review_base=_OID1 + ) + ], + ) + check_dependent_pr._process_pr( + self.mock_client, + pr_number=3, + pr_to_commits={3: {_OID3}}, + pr_to_head={3: _OID3}, + open_pr_numbers={3}, + label_id="label_dependent", + token="test_token", + ) + body = self.mock_client.execute.call_args_list[1][1]["variable_values"][ + "body" + ] + self.assertNotIn("/changes/", body) + self.assertIn("full set of changes is now ready to review", body) + self.assertNotIn("review_base", body) + + def test_process_pr_clears_link_only_when_trunk_merge_includes_dep( + self, + ) -> None: + dep_merge_resp = { + "repository": {"pullRequest": {"mergeCommit": {"oid": _OID9}}} + } + + # Merging a stale `trunk` (before dep #1 merged -> `diverged`) keeps + # the review link. + self.mock_client.execute.side_effect = [ + self._make_pr_response( + pr_id="pr_3", + head_ref_oid=_OID3, + commits=[_OID1, _OID2, _OID3], + comments=[ + self._make_comment( + open_deps=[], merged_deps=[1], review_base=_OID1 + ) + ], + merge_commits={_OID3}, + ), + dep_merge_resp, + ] + with mock.patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = {"status": "diverged"} + check_dependent_pr._process_pr( + self.mock_client, + pr_number=3, + pr_to_commits={3: {_OID1, _OID2, _OID3}}, + pr_to_head={3: _OID3}, + open_pr_numbers={3}, + label_id="label_dependent", + token="test_token", + ) + # Comment state unchanged (review_base stayed `_OID1`), so no update. + self.assertEqual(self.mock_client.execute.call_count, 2) + + # Merging `trunk` after dep #1 landed (`ahead`) clears the link. + self.mock_post.reset_mock() + self.mock_client.reset_mock() + self.mock_client.execute.side_effect = [ + self._make_pr_response( + pr_id="pr_3", + head_ref_oid=_OID4, + commits=[_OID1, _OID2, _OID3, _OID4], + comments=[ + self._make_comment( + open_deps=[], merged_deps=[1], review_base=_OID1 + ) + ], + merge_commits={_OID3, _OID4}, + ), + dep_merge_resp, + {}, + ] + with mock.patch("requests.get") as mock_get: + mock_get.return_value.json.return_value = {"status": "ahead"} + check_dependent_pr._process_pr( + self.mock_client, + pr_number=3, + pr_to_commits={3: {_OID1, _OID2, _OID3, _OID4}}, + pr_to_head={3: _OID4}, + open_pr_numbers={3}, + label_id="label_dependent", + token="test_token", + ) + body = self.mock_client.execute.call_args_list[2][1]["variable_values"][ + "body" + ] + self.assertNotIn("/changes/", body) + self.assertIn("full set of changes is now ready to review", body) + self.assertNotIn("review_base", body) + def test_set_commit_status_links_workflow_run(self) -> None: with mock.patch.dict( os.environ,