Skip to content

Commit d912de7

Browse files
authored
fix(review): note reviewer assignment failures without failing the check (#5845)
* fix(review): note reviewer assignment failures without failing the check When GitHub rejects a reviewer request or removal, Review Readiness now posts or updates one PR comment with the error, emits a warning annotation, and exits 0. PR label errors still fail the check. Closes #5840 Signed-off-by: Jim Meyer <jimeyer@nvidia.com> * docs(review): shorten the reviewer routing paragraph Signed-off-by: Jim Meyer <jimeyer@nvidia.com> --------- Signed-off-by: Jim Meyer <jimeyer@nvidia.com>
1 parent b20c144 commit d912de7

3 files changed

Lines changed: 187 additions & 25 deletions

File tree

‎CONTRIBUTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ Every pull request must be approved by someone listed in [MAINTAINERS.md](MAINTA
6363

6464
Pull requests that touch the enforcement machinery or reviewer routing — anything under `.github/workflows/`, `.github/actions/`, `MAINTAINERS.md`, `REVIEWERS.md`, `.github/CODEOWNERS`, or the enforcement and reviewer-routing scripts in `tasks/scripts/` — additionally require a code owner's approval, listed in [.github/CODEOWNERS](.github/CODEOWNERS). The status check reads its inputs from `main`, but a workflow triggered by a review runs the pull request's own copy of the workflow file, so GitHub's native code owner requirement is what keeps a change from disabling the gate that would have blocked it.
6565

66-
Once your pull request represents [accepted work](#accepted-work), apply exactly one `area:` label and any relevant `topic:` labels. Follow [Labeling and Notifications](#labeling-and-notifications) before applying classification labels. The [reviewer routing workflow](.github/workflows/review-readiness.yml) requests all matching members of [REVIEWERS.md](REVIEWERS.md), excluding the author, when a PR opens ready for review, leaves draft status, or gains or loses an area/topic label. Reviewers do not need repository write access to receive requests or review PRs. Manual reviewer choices and people who have commented or reviewed are preserved. Propose roster membership changes through a reviewed PR.
66+
Once your pull request represents [accepted work](#accepted-work), it needs exactly one `area:` label and any relevant `topic:` labels; see [Labeling and Notifications](#labeling-and-notifications) for guidance. The [reviewer routing workflow](.github/workflows/review-readiness.yml) adds reviewers from [REVIEWERS.md](REVIEWERS.md) based on these labels.
6767

6868
Branch Checks requires accounts in `REVIEWERS.md` to appear in the repository collaborator list or have confirmed write or admin permission. Public read access alone does not qualify; read and triage accounts must appear in the collaborator list.
6969

‎tasks/scripts/check_review_readiness.py‎

Lines changed: 88 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
For newly opened PRs, --label-accepted-work also adds state:accepted if qualified.
1414
Request all matching roster members, excluding the author. Preserve
1515
manual choices, unknown request provenance, and anyone who commented or reviewed.
16+
A failed reviewer request or removal is noted on the PR and does not fail the run.
1617
The parser and planning helpers are importable. No state is stored between runs.
1718
"""
1819

@@ -33,6 +34,7 @@
3334
HEADER = ["Name", "GitHub ID", "Company/Organization"]
3435
LABEL = re.compile(r"(?:area|topic):[a-z0-9]+(?:[-:][a-z0-9]+)*")
3536
PROFILE = re.compile(r"\[@([a-z0-9-]+)\]\(https://github\.com/([a-z0-9-]+)/?\)", re.I)
37+
ASSIGNMENT_MARKER = "<!-- openshell-review-readiness:assignment-failure -->"
3638
ADD_LABEL = """mutation($input: AddLabelsToLabelableInput!) {
3739
addLabelsToLabelable(input: $input) { labelable { __typename } }
3840
}"""
@@ -52,6 +54,8 @@ def _api_action(method: str, path: str) -> str:
5254
)
5355
if path.endswith("/labels") and method == "POST":
5456
return "Adding labels"
57+
if "/comments" in path and method in {"POST", "PATCH"}:
58+
return "Commenting on the PR"
5559
if method == "GET":
5660
return "Reading the PR from GitHub"
5761
return "A GitHub API call"
@@ -87,15 +91,23 @@ def describe_failure(exc: Exception) -> tuple[str, str]:
8791
return "error", str(exc)
8892

8993

90-
def report_failure(exc: Exception, *, stream=None, env=None) -> None:
91-
"""Print the failure, plus an Actions error annotation when in Actions."""
94+
def _report(level: str, category: str, message: str, *, stream=None, env=None) -> None:
9295
stream = sys.stderr if stream is None else stream
9396
env = os.environ if env is None else env
94-
category, message = describe_failure(exc)
9597
print(f"Review readiness: {message}", file=stream)
9698
if env.get("GITHUB_ACTIONS") == "true":
9799
title = _escape_annotation(f"Review Readiness: {category}", prop=True)
98-
print(f"::error title={title}::{_escape_annotation(message)}", file=stream)
100+
print(f"::{level} title={title}::{_escape_annotation(message)}", file=stream)
101+
102+
103+
def report_failure(exc: Exception, *, stream=None, env=None) -> None:
104+
"""Print the failure, plus an Actions error annotation when in Actions."""
105+
_report("error", *describe_failure(exc), stream=stream, env=env)
106+
107+
108+
def report_assignment_failure(message: str, *, stream=None, env=None) -> None:
109+
"""Print a reviewer assignment failure as a warning that passes the check."""
110+
_report("warning", "reviewer assignment", message, stream=stream, env=env)
99111

100112

101113
@dataclass(frozen=True)
@@ -104,6 +116,7 @@ class ReviewPlan:
104116
remove: tuple[str, ...]
105117
accepted_work: bool | None = None
106118
add_labels: tuple[str, ...] = ()
119+
assignment_error: str = ""
107120

108121

109122
def parse_reviewers(markdown: str) -> dict[str, set[str]]:
@@ -314,6 +327,65 @@ def _add_accepted_label(repository: str, pr: dict, evidence: dict) -> None:
314327
raise ValueError("Could not apply accepted-work label with evidence")
315328

316329

330+
def assignment_failure_comment(message: str, run_url: str = "") -> str:
331+
"""Return the PR comment body for a failed reviewer request or removal."""
332+
rerun = f"re-run the [workflow]({run_url})" if run_url else "re-run the check"
333+
return (
334+
f"{ASSIGNMENT_MARKER}\n"
335+
"Review Readiness could not update reviewer requests for this PR. "
336+
"This does not fail the check. A maintainer can request reviewers "
337+
f"directly, or fix the cause and {rerun}.\n\n"
338+
f"```text\n{message}\n```\n"
339+
)
340+
341+
342+
def _note_assignment_failure(repository: str, number: int, message: str) -> None:
343+
"""Create or update the single assignment-failure comment on the PR."""
344+
root = f"repos/{repository}"
345+
server, run = os.environ.get("GITHUB_SERVER_URL"), os.environ.get("GITHUB_RUN_ID")
346+
run_url = f"{server}/{repository}/actions/runs/{run}" if server and run else ""
347+
body = assignment_failure_comment(message, run_url)
348+
comments = _api(f"{root}/issues/{number}/comments?per_page=100", pages=True)
349+
existing = next(
350+
(
351+
comment
352+
for comment in comments
353+
if (comment.get("user") or {}).get("type") == "Bot"
354+
and (comment.get("body") or "").startswith(ASSIGNMENT_MARKER)
355+
),
356+
None,
357+
)
358+
if existing:
359+
_api(
360+
f"{root}/issues/comments/{existing['id']}",
361+
method="PATCH",
362+
data={"body": body},
363+
)
364+
else:
365+
_api(f"{root}/issues/{number}/comments", method="POST", data={"body": body})
366+
367+
368+
def _apply_review_requests(
369+
repository: str, number: int, pr: dict, selected: set[str], plan: ReviewPlan
370+
) -> ReviewPlan:
371+
pull = f"repos/{repository}/pulls/{number}"
372+
endpoint = f"{pull}/requested_reviewers"
373+
if plan.add:
374+
_api(endpoint, method="POST", data={"reviewers": list(plan.add)})
375+
if plan.remove:
376+
# Re-read human choices and engagement immediately before removals.
377+
latest = _api(pull)
378+
if _routing_key(latest) != _routing_key(pr):
379+
raise ValueError("PR routing changed; rerun reconciliation")
380+
refreshed = plan_review_requests(
381+
selected, **_load_reviewers(repository, number, latest)
382+
)
383+
plan = replace(plan, remove=refreshed.remove)
384+
if plan.remove:
385+
_api(endpoint, method="DELETE", data={"reviewers": list(plan.remove)})
386+
return plan
387+
388+
317389
def check_review_readiness(
318390
categories: dict[str, set[str]],
319391
repository: str,
@@ -357,20 +429,16 @@ def check_review_readiness(
357429
add_labels=add_labels,
358430
)
359431
if apply:
360-
endpoint = f"{pull}/requested_reviewers"
361-
if plan.add:
362-
_api(endpoint, method="POST", data={"reviewers": list(plan.add)})
363-
if plan.remove:
364-
# Re-read human choices and engagement immediately before removals.
365-
latest = _api(pull)
366-
if _routing_key(latest) != _routing_key(pr):
367-
raise ValueError("PR routing changed; rerun reconciliation")
368-
refreshed = plan_review_requests(
369-
selected, **_load_reviewers(repository, number, latest)
370-
)
371-
plan = replace(plan, remove=refreshed.remove)
372-
if plan.remove:
373-
_api(endpoint, method="DELETE", data={"reviewers": list(plan.remove)})
432+
try:
433+
plan = _apply_review_requests(repository, number, pr, selected, plan)
434+
except subprocess.CalledProcessError as exc:
435+
# Roster or GitHub problems are not the PR's fault; note them instead.
436+
message = describe_failure(exc)[1]
437+
try:
438+
_note_assignment_failure(repository, number, message)
439+
except (subprocess.CalledProcessError, ValueError) as comment_exc:
440+
message += f" {describe_failure(comment_exc)[1]}"
441+
plan = replace(plan, assignment_error=message)
374442
return plan
375443

376444

@@ -416,6 +484,8 @@ def main(argv: list[str] | None = None) -> int:
416484
) as exc:
417485
report_failure(exc)
418486
return 1
487+
if plan is not None and plan.assignment_error:
488+
report_assignment_failure(plan.assignment_error)
419489
print(
420490
json.dumps(
421491
asdict(plan) if plan is not None else {"skipped": "closed or draft PR"}

‎tasks/scripts/check_review_readiness_test.py‎

Lines changed: 98 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -444,12 +444,19 @@ def test_retry_after_partial_failure_uses_updated_github_metadata(self):
444444
reviewers(requested=("alice",)),
445445
reviewers(requested=("alice", "dave")),
446446
]
447-
with self.assertRaises(subprocess.CalledProcessError):
448-
self.run_routing(
449-
CATEGORIES,
450-
snapshots=snapshots,
451-
responses=[before, None, after, subprocess.CalledProcessError(1, "gh")],
452-
)
447+
failed, _, _ = self.run_routing(
448+
CATEGORIES,
449+
snapshots=snapshots,
450+
responses=[
451+
before,
452+
None,
453+
after,
454+
subprocess.CalledProcessError(1, "gh"),
455+
[],
456+
None,
457+
],
458+
)
459+
self.assertTrue(failed.assignment_error)
453460
plan, api, _ = self.run_routing(
454461
CATEGORIES, snapshots=[snapshots[1]] * 2, responses=[after, after, None]
455462
)
@@ -459,6 +466,90 @@ def test_retry_after_partial_failure_uses_updated_github_metadata(self):
459466
)
460467

461468

469+
class AssignmentFailureTests(unittest.TestCase):
470+
COMMENTS = "repos/owner/repo/issues/42/comments"
471+
REJECTED = subprocess.CalledProcessError(
472+
1,
473+
["gh", "api", f"{PULL}/requested_reviewers", "--method", "POST"],
474+
stderr="gh: Reviews may only be requested from collaborators. (HTTP 422)\n",
475+
)
476+
477+
def run_routing(self, responses):
478+
with (
479+
mock.patch.dict(os.environ, {}, clear=True),
480+
mock.patch.object(routing, "_api", side_effect=responses) as api,
481+
mock.patch.object(routing, "_load_reviewers", return_value=reviewers()),
482+
):
483+
plan = routing.check_review_readiness(CATEGORIES, REPO, 42, apply=True)
484+
return plan, api
485+
486+
def test_rejected_request_is_noted_on_the_pr_without_failing(self):
487+
plan, api = self.run_routing([pr("area:build"), self.REJECTED, [], None])
488+
self.assertEqual(plan.add, ("dave",))
489+
self.assertIn("Requesting reviewers failed", plan.assignment_error)
490+
self.assertIn("HTTP 422", plan.assignment_error)
491+
comment = api.call_args
492+
self.assertEqual(comment.args, (self.COMMENTS,))
493+
self.assertEqual(comment.kwargs["method"], "POST")
494+
body = comment.kwargs["data"]["body"]
495+
self.assertTrue(body.startswith(routing.ASSIGNMENT_MARKER))
496+
self.assertIn("HTTP 422", body)
497+
self.assertNotIn(
498+
"DELETE", [call.kwargs.get("method") for call in api.call_args_list]
499+
)
500+
501+
def test_repeated_failure_updates_the_existing_bot_comment(self):
502+
marked = routing.ASSIGNMENT_MARKER + "\nold"
503+
comments = [
504+
{"id": 7, "user": {"type": "User"}, "body": marked},
505+
{"id": 9, "user": {"type": "Bot"}, "body": marked},
506+
]
507+
_, api = self.run_routing([pr("area:build"), self.REJECTED, comments, None])
508+
self.assertEqual(api.call_args.args, ("repos/owner/repo/issues/comments/9",))
509+
self.assertEqual(api.call_args.kwargs["method"], "PATCH")
510+
511+
def test_comment_failure_is_reported_without_failing(self):
512+
denied = subprocess.CalledProcessError(
513+
1,
514+
["gh", "api", self.COMMENTS, "--method", "POST"],
515+
stderr="gh: Resource not accessible by integration (HTTP 403)",
516+
)
517+
plan, _ = self.run_routing([pr("area:build"), self.REJECTED, [], denied])
518+
self.assertIn("HTTP 422", plan.assignment_error)
519+
self.assertIn("Commenting on the PR failed", plan.assignment_error)
520+
521+
def test_comment_links_the_workflow_run(self):
522+
body = routing.assignment_failure_comment("x", "https://github.test/run/1")
523+
self.assertIn("[workflow](https://github.test/run/1)", body)
524+
self.assertIn("re-run the check", routing.assignment_failure_comment("x"))
525+
526+
def test_label_errors_still_fail(self):
527+
with self.assertRaises(routing.LabelRoutingError):
528+
self.run_routing([pr("area:build", "area:runtime")])
529+
530+
def test_cli_passes_with_a_warning_annotation(self):
531+
plan = routing.ReviewPlan(("dave",), (), assignment_error="boom")
532+
errors, output = io.StringIO(), io.StringIO()
533+
with (
534+
mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}),
535+
mock.patch.object(routing, "check_review_readiness", return_value=plan),
536+
tempfile.TemporaryDirectory() as directory,
537+
contextlib.redirect_stderr(errors),
538+
contextlib.redirect_stdout(output),
539+
):
540+
path = Path(directory) / "REVIEWERS.md"
541+
path.write_text(DOCUMENT, encoding="utf-8")
542+
result = routing.main(
543+
["--reviewers", str(path), "--repo", REPO, "--pr", "42", "--apply"]
544+
)
545+
self.assertEqual(result, 0)
546+
self.assertIn(
547+
"::warning title=Review Readiness%3A reviewer assignment::boom",
548+
errors.getvalue(),
549+
)
550+
self.assertEqual(json.loads(output.getvalue())["assignment_error"], "boom")
551+
552+
462553
class AcceptedWorkIntegrationTests(unittest.TestCase):
463554
def test_accepted_label_event_carries_structured_rationale(self):
464555
with (
@@ -877,6 +968,7 @@ def test_emits_plan_and_passes_apply_option(self):
877968
"remove": [],
878969
"accepted_work": None,
879970
"add_labels": [],
971+
"assignment_error": "",
880972
},
881973
)
882974
check.assert_called_once_with(

0 commit comments

Comments
 (0)