Skip to content

Commit eed3b8c

Browse files
committed
fix(review): skip non-collaborators when requesting reviewers
Signed-off-by: Jim Meyer <jimeyer@nvidia.com>
1 parent 7cfa0c0 commit eed3b8c

4 files changed

Lines changed: 269 additions & 15 deletions

File tree

‎.agents/skills/watch-github-actions/SKILL.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,12 @@ gh run list --json databaseId,status,headBranch,url --jq '.[] | {id: .databaseId
125125

126126
## View Job Logs
127127

128+
For `Review Readiness`, the reconciliation JSON reports `skipped_non_collaborators`:
129+
these roster members cannot receive GitHub review requests. Read and triage
130+
collaborators remain eligible. GitHub API failures identify the operation and HTTP
131+
status; reviewer-request failures also identify the submitted reviewers. Resolve
132+
roster membership/access separately from area/topic label validation failures.
133+
128134
For Kubernetes app-listener E2E failures during kind setup, inspect the uploaded
129135
`results/app-listener/cni-setup/` evidence. It includes node and Calico pod
130136
descriptions, events, and current/previous container logs. A CNI rollout timeout

‎CONTRIBUTING.md‎

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

7373
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.
7474

75-
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.
75+
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 matching repository collaborators from [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. GitHub requires collaborator membership for review requests; routing reports non-collaborator roster members in `skipped_non_collaborators` and requests the remaining eligible reviewers. Manual reviewer choices and people who have commented or reviewed are preserved. Propose roster membership changes through a reviewed PR.
7676

7777
If your pull request has been idle, ask for a reviewer in the pull request or in the CNCF Slack channel rather than waiting.
7878

‎tasks/scripts/check_review_readiness.py‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
1212
Preview with --repo OWNER/REPO --pr NUMBER; add --apply to update requests.
1313
For newly opened PRs, --label-accepted-work also adds state:accepted if qualified.
14-
Request all matching roster members, excluding the author. Preserve
15-
manual choices, unknown request provenance, and anyone who commented or reviewed.
14+
Request matching repository collaborators, excluding the author. Report roster
15+
members GitHub cannot request. Preserve manual choices, unknown request provenance,
16+
and anyone who commented or reviewed.
1617
The parser and planning helpers are importable. No state is stored between runs.
1718
"""
1819

@@ -40,6 +41,7 @@ class ReviewPlan:
4041
remove: tuple[str, ...]
4142
accepted_work: bool | None = None
4243
add_labels: tuple[str, ...] = ()
44+
skipped_non_collaborators: tuple[str, ...] = ()
4345

4446

4547
def parse_reviewers(markdown: str) -> dict[str, set[str]]:
@@ -162,19 +164,41 @@ def plan_review_requests(
162164
)
163165

164166

167+
class GitHubApiError(subprocess.CalledProcessError):
168+
"""Keep HTTP error handling compatible while reporting safe diagnostics."""
169+
170+
def __init__(self, error: subprocess.CalledProcessError, message: str):
171+
super().__init__(
172+
error.returncode, error.cmd, output=error.output, stderr=error.stderr
173+
)
174+
self.message = message
175+
176+
def __str__(self) -> str:
177+
return self.message
178+
179+
165180
def _api(path: str, *, method: str = "GET", data=None, pages: bool = False):
166181
command = ["gh", "api", path, "--method", method]
167182
if pages:
168183
command.extend(["--paginate", "--slurp"])
169184
if data is not None:
170185
command.extend(["--input", "-"])
171-
result = subprocess.run(
172-
command,
173-
input=json.dumps(data) if data is not None else None,
174-
capture_output=True,
175-
text=True,
176-
check=True,
177-
)
186+
try:
187+
result = subprocess.run(
188+
command,
189+
input=json.dumps(data) if data is not None else None,
190+
capture_output=True,
191+
text=True,
192+
check=True,
193+
)
194+
except subprocess.CalledProcessError as exc:
195+
# Do not echo raw responses: other API operations can contain PR text.
196+
status = re.search(r"\(HTTP (\d{3})\)", exc.stderr or "")
197+
detail = f"HTTP {status[1]}" if status else f"exit {exc.returncode}"
198+
message = f"GitHub API {method} {path} failed ({detail})"
199+
if path.endswith("/requested_reviewers") and data:
200+
message += "; reviewers: " + ", ".join(data.get("reviewers", []))
201+
raise GitHubApiError(exc, message) from exc
178202
value = json.loads(result.stdout) if result.stdout.strip() else None
179203
if pages:
180204
if not isinstance(value, list) or not all(
@@ -257,6 +281,23 @@ def check_review_readiness(
257281
accepted_work=accepted,
258282
add_labels=add_labels,
259283
)
284+
if plan.add:
285+
# Public read access alone does not make an account requestable. GitHub
286+
# rejects an entire batch containing a non-collaborator with HTTP 422.
287+
collaborators = {
288+
member["login"].lower()
289+
for member in _api(
290+
f"repos/{repository}/collaborators?per_page=100&affiliation=all",
291+
pages=True,
292+
)
293+
}
294+
plan = replace(
295+
plan,
296+
add=tuple(login for login in plan.add if login in collaborators),
297+
skipped_non_collaborators=tuple(
298+
login for login in plan.add if login not in collaborators
299+
),
300+
)
260301
if apply:
261302
endpoint = f"{pull}/requested_reviewers"
262303
if plan.add:

‎tasks/scripts/check_review_readiness_test.py‎

Lines changed: 212 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,181 @@ def test_new_automatic_request_after_removal_is_not_protected(self):
222222

223223

224224
class GitHubTests(unittest.TestCase):
225+
def test_api_failure_reports_operation_status_and_reviewers_without_raw_output(
226+
self,
227+
):
228+
error = subprocess.CalledProcessError(
229+
1,
230+
["gh", "api"],
231+
output='{"message":"sensitive-response-body"}',
232+
stderr="gh: sensitive-response-body (HTTP 422)",
233+
)
234+
with (
235+
mock.patch.object(routing.subprocess, "run", side_effect=error),
236+
self.assertRaises(subprocess.CalledProcessError) as raised,
237+
):
238+
routing._api(
239+
f"{PULL}/requested_reviewers",
240+
method="POST",
241+
data={"reviewers": ["alice", "bob"]},
242+
)
243+
message = str(raised.exception)
244+
for expected in (
245+
"POST",
246+
f"{PULL}/requested_reviewers",
247+
"HTTP 422",
248+
"alice",
249+
"bob",
250+
):
251+
self.assertIn(expected, message)
252+
self.assertNotIn("sensitive-response-body", message)
253+
254+
def test_mixed_roster_requests_collaborators_from_every_page_in_preview_and_apply(
255+
self,
256+
):
257+
for apply in (False, True):
258+
with self.subTest(apply=apply):
259+
writes = []
260+
261+
def github(command, *, writes=writes, **kwargs):
262+
endpoint = command[2]
263+
method = command[command.index("--method") + 1]
264+
if endpoint == PULL:
265+
result = pr("area:runtime", author="author")
266+
elif "/collaborators?" in endpoint:
267+
self.assertIn("--paginate", command)
268+
self.assertIn("--slurp", command)
269+
result = [
270+
[
271+
{
272+
"login": "READ-MEMBER",
273+
"permissions": {"pull": True, "push": False},
274+
}
275+
],
276+
[
277+
{
278+
"login": "triage-member",
279+
"permissions": {
280+
"pull": True,
281+
"push": False,
282+
"triage": True,
283+
},
284+
}
285+
],
286+
]
287+
elif endpoint.endswith("/requested_reviewers") and method == "POST":
288+
writes.append(json.loads(kwargs["input"]))
289+
result = {}
290+
else:
291+
result = [[]]
292+
return subprocess.CompletedProcess(
293+
command, 0, stdout=json.dumps(result), stderr=""
294+
)
295+
296+
with mock.patch.object(routing.subprocess, "run", side_effect=github):
297+
plan = routing.check_review_readiness(
298+
{
299+
"area:runtime": {
300+
"read-member",
301+
"triage-member",
302+
"non-collaborator",
303+
}
304+
},
305+
REPO,
306+
42,
307+
apply=apply,
308+
)
309+
assert plan is not None
310+
self.assertEqual(plan.add, ("read-member", "triage-member"))
311+
self.assertEqual(plan.skipped_non_collaborators, ("non-collaborator",))
312+
self.assertEqual(
313+
writes,
314+
[{"reviewers": ["read-member", "triage-member"]}] if apply else [],
315+
)
316+
317+
def test_all_non_collaborators_are_reported_without_request_or_removal(self):
318+
with (
319+
mock.patch.object(
320+
routing, "_api", side_effect=[pr("area:runtime"), []]
321+
) as api,
322+
mock.patch.object(routing, "_load_reviewers", return_value=reviewers()),
323+
):
324+
plan = routing.check_review_readiness(CATEGORIES, REPO, 42, apply=True)
325+
assert plan is not None
326+
self.assertEqual(plan.add, ())
327+
self.assertEqual(plan.skipped_non_collaborators, ("alice", "bob"))
328+
self.assertTrue(
329+
all(
330+
call.kwargs.get("method", "GET") == "GET" for call in api.call_args_list
331+
)
332+
)
333+
334+
def test_collaborator_filter_does_not_remove_selected_existing_reviewers(self):
335+
value = pr("area:runtime", requested=("alice",))
336+
with (
337+
mock.patch.object(routing, "_api", side_effect=[value, []]) as api,
338+
mock.patch.object(
339+
routing, "_load_reviewers", return_value=reviewers(requested=("alice",))
340+
),
341+
):
342+
plan = routing.check_review_readiness(CATEGORIES, REPO, 42, apply=True)
343+
assert plan is not None
344+
self.assertEqual(plan.remove, ())
345+
self.assertEqual(plan.skipped_non_collaborators, ("bob",))
346+
self.assertTrue(
347+
all(
348+
call.kwargs.get("method", "GET") == "GET" for call in api.call_args_list
349+
)
350+
)
351+
352+
def test_api_preserves_404_for_the_shared_accepted_work_checker(self):
353+
error = subprocess.CalledProcessError(
354+
1, "gh", stderr="gh: Not Found (HTTP 404)"
355+
)
356+
closing_issues = {
357+
"data": {
358+
"repository": {
359+
"pullRequest": {
360+
"closingIssuesReferences": {
361+
"nodes": [],
362+
"pageInfo": {"hasNextPage": False, "endCursor": None},
363+
}
364+
}
365+
}
366+
}
367+
}
368+
with mock.patch.object(
369+
routing.subprocess,
370+
"run",
371+
side_effect=[
372+
error,
373+
subprocess.CompletedProcess([], 0, stdout=json.dumps(closing_issues)),
374+
],
375+
):
376+
self.assertFalse(
377+
routing.check_pr_accepted_work(
378+
REPO, pr(), {"maintainer"}, api=routing._api
379+
)
380+
)
381+
382+
def test_collaborator_lookup_failure_stops_reviewer_writes(self):
383+
error = subprocess.CalledProcessError(
384+
1, "gh", stderr="gh: forbidden (HTTP 403)"
385+
)
386+
with (
387+
mock.patch.object(
388+
routing, "_api", side_effect=[pr("area:runtime"), error]
389+
) as api,
390+
mock.patch.object(routing, "_load_reviewers", return_value=reviewers()),
391+
self.assertRaises(subprocess.CalledProcessError),
392+
):
393+
routing.check_review_readiness(CATEGORIES, REPO, 42, apply=True)
394+
self.assertTrue(
395+
all(
396+
call.kwargs.get("method", "GET") == "GET" for call in api.call_args_list
397+
)
398+
)
399+
225400
def test_api_rejects_empty_paginated_response(self):
226401
with mock.patch.object(routing.subprocess, "run") as run:
227402
run.return_value.stdout = ""
@@ -261,8 +436,29 @@ def test_loads_all_engagement_and_timeline_feeds(self):
261436

262437
class ReconciliationTests(unittest.TestCase):
263438
def run_routing(self, categories, *, snapshots, responses, apply=True):
439+
responses = iter(responses)
440+
441+
def github(path, **_kwargs):
442+
if "/collaborators?" in path:
443+
return [
444+
{"login": login}
445+
for login in (
446+
"alice",
447+
"bob",
448+
"carol",
449+
"dave",
450+
"read-member",
451+
"triage-member",
452+
"outside-collaborator",
453+
)
454+
]
455+
response = next(responses)
456+
if isinstance(response, Exception):
457+
raise response
458+
return response
459+
264460
with (
265-
mock.patch.object(routing, "_api", side_effect=responses) as api,
461+
mock.patch.object(routing, "_api", side_effect=github) as api,
266462
mock.patch.object(
267463
routing, "_load_reviewers", side_effect=snapshots
268464
) as load,
@@ -278,13 +474,13 @@ def test_initial_assignment_excludes_author_without_extra_refresh(self):
278474
)
279475
self.assertEqual(plan, routing.ReviewPlan(("bob", "carol"), ()))
280476
load.assert_called_once()
281-
self.assertEqual(api.call_count, 2)
477+
self.assertEqual(api.call_count, 3)
282478
self.assertEqual(
283479
api.call_args.kwargs,
284480
{"method": "POST", "data": {"reviewers": ["bob", "carol"]}},
285481
)
286482

287-
def test_requests_roster_members_without_permission_lookups(self):
483+
def test_requests_read_triage_and_outside_collaborators_without_write_checks(self):
288484
members = {"read-member", "triage-member", "outside-collaborator"}
289485
categories = {"area:runtime": members}
290486
plan, api, _ = self.run_routing(
@@ -297,6 +493,10 @@ def test_requests_roster_members_without_permission_lookups(self):
297493
api.call_args_list,
298494
[
299495
mock.call(PULL),
496+
mock.call(
497+
"repos/owner/repo/collaborators?per_page=100&affiliation=all",
498+
pages=True,
499+
),
300500
mock.call(
301501
f"{PULL}/requested_reviewers",
302502
method="POST",
@@ -333,7 +533,11 @@ def test_preview_makes_no_changes(self):
333533
apply=False,
334534
)
335535
self.assertEqual(plan.add, ("dave",))
336-
api.assert_called_once_with(PULL)
536+
self.assertTrue(
537+
all(
538+
call.kwargs.get("method", "GET") == "GET" for call in api.call_args_list
539+
)
540+
)
337541

338542
def test_refresh_before_removal_protects_new_manual_choices_and_engagement(self):
339543
before = pr("area:build", requested=("alice", "bob", "carol"))
@@ -496,7 +700,9 @@ def test_closed_pr_is_never_classified_or_labeled(self):
496700
def test_labels_and_requests_reviewers_for_a_classified_ready_pr(self):
497701
with (
498702
mock.patch.object(
499-
routing, "_api", side_effect=[pr("area:build"), None, None]
703+
routing,
704+
"_api",
705+
side_effect=[pr("area:build"), None, [{"login": "dave"}], None],
500706
) as api,
501707
mock.patch.object(routing, "check_pr_accepted_work", return_value=True),
502708
mock.patch.object(routing, "_load_reviewers", return_value=reviewers()),
@@ -637,6 +843,7 @@ def test_emits_plan_and_passes_apply_option(self):
637843
"remove": [],
638844
"accepted_work": None,
639845
"add_labels": [],
846+
"skipped_non_collaborators": [],
640847
},
641848
)
642849
check.assert_called_once_with(

0 commit comments

Comments
 (0)