Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions scripts/test_triage_pr.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
"""Unit tests for scripts/triage_pr.py."""
import contextlib
import io
import json
import os
import sys
import tempfile
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(__file__))
import triage_pr as tp
Expand Down Expand Up @@ -131,6 +136,104 @@ def test_managed_labels_conflict_and_failed_pr_check(self):
self.assertNotIn("needs:nvidia-test", labels)


class TestBuildFeedSearch(unittest.TestCase):
def test_query_does_not_use_status_success(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing runs these tests in CI: ci.yml runs scripts/test.ps1 (cargo only), and pr-check.yml runs only pr_check.py. If status:success is added back later, everything stays green. A step such as python3 -m unittest discover -s scripts -p 'test_*.py' is needed for this to act as a regression guard.

q = tp.build_feed_search_query("xcl-dev/xcl")
self.assertNotIn("status:success", q)
self.assertIn("repo:xcl-dev/xcl", q)
self.assertIn("-is:draft", q)
self.assertIn("base:main", q)

def test_superseded_pr_description_failure_does_not_block_gates(self):
runs = [
{"name": tp.PR_CHECK_NAME, "conclusion": "FAILURE", "completed_at": "2026-11-28T21:37:00Z"},
{"name": tp.PR_CHECK_NAME, "conclusion": "SUCCESS", "completed_at": "2026-11-28T22:10:00Z"},
{"name": tp.CI_CHECK_NAME, "conclusion": "SUCCESS", "completed_at": "2026-11-28T22:11:00Z"},
]
ci, pr = tp.extract_gate_statuses(runs)
self.assertEqual((ci, pr), ("SUCCESS", "SUCCESS"))


class FakeGitHub(tp.GitHubClient):
"""Serves canned GraphQL answers and records the search string cmd_build_feed sends."""

def __init__(self, prs: list[dict], details: dict[int, dict]):
super().__init__("test-token")
self.prs = prs
self.details = details
self.search_queries: list[str] = []

def graphql(self, query, variables=None):
if query == tp.STAGE_A_QUERY:
self.search_queries.append(variables["q"])
return {"search": {"pageInfo": {"hasNextPage": False, "endCursor": None}, "nodes": self.prs}}
return {"repository": {f"pr_{n}": d for n, d in self.details.items()}}


def _check_run(name, conclusion, completed_at):
return {"name": name, "conclusion": conclusion, "status": "COMPLETED",
"completedAt": completed_at, "startedAt": completed_at}


def _pr_node(number, runs):
return {
"number": number, "title": f"Scripts: change {number}", "url": f"https://example.invalid/pull/{number}",
"isDraft": False, "baseRefName": "main", "headRefOid": f"{number:040x}",
"updatedAt": "2026-11-28T22:30:00Z", "author": {"login": "contributor"},
"labels": {"nodes": []},
"commits": {"nodes": [{"commit": {"statusCheckRollup": {"contexts": {"nodes": runs}}}}]},
}


def _details(path):
return {"mergeable": "MERGEABLE", "body": "", "files": {"nodes": [{"path": path}]}, "comments": {"nodes": []}}


class TestBuildFeedEndToEnd(unittest.TestCase):
"""cmd_build_feed against a fake GitHub: the #3246 scenario, without the network."""

def run_feed(self, prs, details):
gh = FakeGitHub(prs, details)
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "queue.json")
with mock.patch.dict(os.environ, {"ANTHROPIC_API_KEY": ""}), contextlib.redirect_stdout(io.StringIO()):
tp.cmd_build_feed(gh, "xcl-dev/xcl", out, max_pages=1, sync_labels=False)
with open(out, encoding="utf-8") as f:
return gh, json.load(f)

def test_feed_keeps_pr_whose_description_check_failed_then_passed(self):
# 101: PR description failed, was fixed, and every latest check is green (the #3246 case).
# 102: the latest PR description run is still failing, so it must stay out.
# 103: CI is still pending, so it must stay out.
prs = [
_pr_node(101, [
_check_run(tp.PR_CHECK_NAME, "FAILURE", "2026-11-28T21:37:00Z"),
_check_run(tp.PR_CHECK_NAME, "SUCCESS", "2026-11-28T22:10:00Z"),
_check_run(tp.CI_CHECK_NAME, "SUCCESS", "2026-11-28T22:11:00Z"),
]),
_pr_node(102, [
_check_run(tp.PR_CHECK_NAME, "SUCCESS", "2026-11-28T21:37:00Z"),
_check_run(tp.PR_CHECK_NAME, "FAILURE", "2026-11-28T22:10:00Z"),
_check_run(tp.CI_CHECK_NAME, "SUCCESS", "2026-11-28T22:11:00Z"),
]),
_pr_node(103, [
_check_run(tp.PR_CHECK_NAME, "SUCCESS", "2026-11-28T22:10:00Z"),
{"name": tp.CI_CHECK_NAME, "conclusion": None, "status": "IN_PROGRESS",
"completedAt": None, "startedAt": "2026-11-28T22:11:00Z"},
]),
]
details = {n: _details("scripts/triage_pr.py") for n in (101, 102, 103)}

gh, feed = self.run_feed(prs, details)

self.assertEqual(gh.search_queries, [tp.build_feed_search_query("xcl-dev/xcl")])
self.assertNotIn("status:success", gh.search_queries[0])
self.assertEqual(feed["counts"]["total_open_scanned"], 3)
self.assertEqual(feed["counts"]["gate_passing_candidates"], 1)
self.assertEqual([item["number"] for item in feed["items"]], [101])
self.assertEqual(feed["ready_to_merge"], [])


class TestLlmTriageValidation(unittest.TestCase):
def test_parses_fenced_json_and_normalizes(self):
raw = """```json
Expand Down
20 changes: 14 additions & 6 deletions scripts/triage_pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,19 @@ def parse_merge_checks(
}


def build_feed_search_query(repo: str) -> str:
"""GitHub search for open, non-draft PRs against main that the feed may consider.

Must not include ``status:success``: GitHub counts every check run on the head commit,
including superseded failures, so PRs whose description check failed once and passed on
retry stay ``status:failure`` in search even when the rollup is green (#3246).
"""
return (
f"repo:{repo} is:pr is:open -is:draft base:main "
f"-label:duplicate -label:off-goal sort:updated-desc"
)


def extract_gate_statuses(check_runs: list[dict[str, Any]]) -> tuple[str, str]:
"""Return (ci_state, pr_check_state) using the latest check run per check name."""
latest: dict[str, dict[str, Any]] = {}
Expand Down Expand Up @@ -716,12 +729,7 @@ def cmd_build_feed(
max_llm_calls: int = DEFAULT_MAX_LLM_CALLS,
) -> None:
owner, name = repo.split("/", 1)
# Do NOT use `status:success` in GitHub search: its search index lags/drops newly opened PRs
# and misses PRs with unrelated non-required check runs. Filter directly on live CheckRuns below.
search_q = (
f"repo:{repo} is:pr is:open -is:draft base:main "
f"-label:duplicate -label:off-goal sort:updated-desc"
)
search_q = build_feed_search_query(repo)
cursor = None
all_open: list[dict[str, Any]] = []

Expand Down
Loading