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
4 changes: 4 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ jobs:
run: python3 -c "import json; json.load(open('repos.json'))"

- name: unit tests
# the tests default to /data/review, which cannot be created here; any
# machine without it needs REVIEW_TEST_DIR
env:
REVIEW_TEST_DIR: ${{ runner.temp }}
run: |
fail=0
for t in runner/tests/test_*.py; do
Expand Down
7 changes: 5 additions & 2 deletions repos.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"post_comments false means review and report it, but hold the comment for a",
" human rather than posting to someone else's project.",
"house_rules ardupilot | fork | upstream | none - whose conventions a",
" finding should be judged against."
" finding should be judged against.",
"pin_check the CI job whose log reports failed submodule pins; discovery",
" reads it on a failed run and gives the pins in ci.pin_check."
],
"submodule_sweep": {
"source": "ardupilot/.gitmodules",
Expand All @@ -37,7 +39,8 @@
"discovery": "main",
"post_comments": true,
"house_rules": "ardupilot",
"notes": "The main repo. Its PRs are keyed by bare number."
"pin_check": "check-merge-commits",
"notes": "The main repo. Its PRs are keyed by bare number. Submodule pins: CI's check-merge-commits job (check_submodule_references_exist in Tools/scripts/check_branch_conventions.py) checks a master-targeting PR's submodule pins against each submodule's default branch. The runner reads that job's log for the reviewed head and lists the pins it reported as failed in ci.pin_check.failures (commit, path, sha prefix and reason). A pin listed there with reason ahead or diverged exists in the submodule's repository but is not yet merged. If the PR leaves that submodule's url in .gitmodules unchanged, it must not affect the verdict: rely on that failing check, give a finding that rests only on the pin not yet being reachable blocking false and actionable false, and mention it at most as one line among the minor findings, saying check-merge-commits fails on it. A pin not listed there was not caught by CI, whatever the job's overall state: the job fails for many other reasons, and the check skips PRs to other branches, runs the PR head's copy of the script and passes when the GitHub API errors. Judge such a pin normally, as every pin when failures is null or ci.pin_check is absent, and a listed pin with reason missing or other, or whose submodule url the PR changes (CI then checked it against the repository the PR names, such as a fork). A missing pin names a commit the submodule's repository does not have, and still blocks even though CI caught it. Problems with what the pinned commit contains, or with the change that pins it, are judged as usual and can still affect the verdict."
},
{
"repo": "ArduPilot/ardupilot_wiki",
Expand Down
67 changes: 64 additions & 3 deletions runner/bin/review_discovery.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Finite discovery snapshots and per-claim refresh, without GitHub mutations."""

import base64
import copy
from datetime import datetime, timedelta
import importlib.util
from pathlib import Path
Expand Down Expand Up @@ -107,6 +108,9 @@ def __init__(self, github, config, store=None):
self._clone_locks = {}
self._swept = None
self._comments = {}
# a finished job's log never changes (a re-run is a new job id), so
# the pins parsed from it are kept for this discovery's lifetime
self._pin_logs = {}
self.unparsed = [] # manifest keys no repository claims

def swept(self):
Expand Down Expand Up @@ -753,6 +757,7 @@ def _candidate(self, pr, mode, manifests=None):
]
else:
destinations += [f"page:{endpoint}/UserReviews/{quote(mode.lstrip('@'), safe='')}.html"]
ci, checks = self.ci_state(repo, head)
candidate = dict(
pr=pr,
repository=repo,
Expand All @@ -768,7 +773,7 @@ def _candidate(self, pr, mode, manifests=None):
labels=labels,
draft=meta["draft"],
open=meta["state"] == "open",
ci=self.ci(repo, head),
ci=ci,
previous_comment=previous,
previous_section=old.get("section"),
previous_manifest_head=old.get("head"),
Expand Down Expand Up @@ -827,13 +832,23 @@ def classify(value, reason):
return classify("REUSE", "head already told")
elif mode != "pr" and same_head(head, old.get("head")):
return classify("REUSE", "manifest head unchanged")
# Like the thread, the pin check's log (a whole job log, through gh and
# past the HTTP cache) is read only for a PR that will be reviewed.
self.add_pin_check(candidate["ci"], repo, checks)
try:
self.snapshot_diff(candidate, previous["told_head"] if mode == "followup" else None)
except (OSError, subprocess.TimeoutExpired) as error:
return classify("DEFERRED", "diff unavailable: " + str(error))
return candidate

def ci(self, repo, head):
result, checks = self.ci_state(repo, head)
self.add_pin_check(result, repo, checks)
return result

def ci_state(self, repo, head):
"""CI's overall state on head, and the check runs it came from (None
when they could not be read)."""
observed = datetime.now(ZoneInfo("UTC")).isoformat()
try:
status = self.gh.request(f"repos/{repo}/commits/{head}/status")
Expand All @@ -857,8 +872,54 @@ def ci(self, repo, head):
else "none"
)
except OSError:
value = "unknown"
return dict(state=value, head=head, at=observed)
value, checks = "unknown", None
return dict(state=value, head=head, at=observed), checks

def add_pin_check(self, result, repo, checks):
job = (self.repos.get(repo.lower()) or {}).get("pin_check")
if job and checks is not None:
result["pin_check"] = self.pin_check(repo, job, checks)

# A failed submodule pin in ArduPilot's check_branch_conventions.py log:
# <stamp> \x1b[31m✗\x1b[0m <commit> references <path>@<sha>: <why>
# SKIP (~) and PASS (✓) lines have the same shape and are not failures.
PIN_FAIL = re.compile(r"^(?:\S+ )?(?:\x1b\[[0-9;]*m)?\u2717(?:\x1b\[[0-9;]*m)? ([0-9a-f]{7,40}) "
r"references ([\w./-]{1,200})@([0-9a-f]{7,40}): (.*)$", re.M)
# "(it is ahead of master)" before ArduPilot's 182796ab64f (2026-11-17);
# CI runs the PR head's copy of the script, so older branches still say it
PIN_REASON = (("(diverged)", "diverged"), ("(it is ahead", "ahead"),
("not found in canonical repo", "missing"))

def pin_check(self, repo, job, checks):
"""The pins CI's submodule check failed on this head, read from the log
of the job named for the repository (repos.json pin_check). The job
fails for many other reasons, and the check passes when GitHub's API
errors, so only a pin its log reports as failed shows CI caught it.
failures is None when the log could not be read. Only fixed-format
fields are kept: the log echoes paths from the PR's own .gitmodules."""
runs = [x for x in checks if x.get("name") == job]
if not runs:
return dict(job=job, state="missing", failures=None)
run = max(runs, key=lambda x: x.get("id", 0)) # a re-run is the newer id
if run.get("status") != "completed":
return dict(job=job, state="running", failures=None)
if run.get("conclusion") != "failure":
return dict(job=job, state=run.get("conclusion") or "unknown", failures=[])
key = (repo.lower(), run.get("id"))
if key in self._pin_logs:
return dict(job=job, state="failure", failures=copy.deepcopy(self._pin_logs[key]))
try:
log = self.gh.job_log(repo, run["id"])
except (OSError, KeyError, ValueError) as error:
return dict(job=job, state="failure", failures=None, error=str(error)[:200])
failures = []
for m in self.PIN_FAIL.finditer(log):
reason = next((name for text, name in self.PIN_REASON if text in m[4]), "other")
failure = dict(commit=m[1], path=m[2], sha=m[3], reason=reason)
if failure not in failures:
failures.append(failure)
self._pin_logs[key] = copy.deepcopy(failures)
return dict(job=job, state="failure", failures=failures)

def snapshot_diff(self, candidate, old=None):
clone = self.config.get("reference_clones", {}).get(candidate["repository"])
Expand Down
15 changes: 12 additions & 3 deletions runner/bin/review_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,17 @@ def expire():
state["done"] = True
watchdog.cancel()

def job_log(self, repo, job, deadline=None):
"""An Actions job's log, as text. GitHub answers with a redirect to a
presigned URL in its blob storage. The pinned connection rightly
refuses to follow that, since it would carry the token there; gh
follows it and sends no token to the storage host."""
return self.request(f"repos/{repo}/actions/jobs/{int(job)}/logs", text=True,
deadline=deadline, via_gh=True)

def request(
self, endpoint, *, account="read", method="GET", payload=None, deadline=None, text=False
self, endpoint, *, account="read", method="GET", payload=None, deadline=None, text=False,
via_gh=False,
):
query = (payload or {}).get("query", "").lstrip()
kind = review_metrics.github_class(endpoint, method, query)
Expand Down Expand Up @@ -325,8 +334,8 @@ def remaining():
# only the read account: identity checks and writes for the
# comment and project accounts go through gh, with the
# credentials gh holds at that moment
if (self.http_cache and method == "GET" and endpoint != "graphql" and self.mode != "replay"
and account == "read" and not settings):
if (self.http_cache and not via_gh and method == "GET" and endpoint != "graphql"
and self.mode != "replay" and account == "read" and not settings):
try:
response = self.http_get(endpoint, account, env, timeout, text)
review_metrics.count("github", kind, time.monotonic() - started)
Expand Down
20 changes: 19 additions & 1 deletion runner/bin/review_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
.f-issue .tag{background:#bc4c00}
.f-note .tag{background:#0969da}
.f-good .tag{background:#1a7f37}
.fid{font-family:monospace;font-size:85%;color:#57606a;margin-right:6px}
.v-approve{color:#1a7f37;font-weight:700}
.v-comment{color:#9a6700;font-weight:700}
.v-request{color:#cf222e;font-weight:700}
Expand Down Expand Up @@ -233,12 +234,29 @@ def core(bundle):
+ "<span>Reviewed by: Claude + Codex cold pass + Codex validation, reconciled by Claude</span>"
+ ("<span>Reviewed " + escape(date) + "</span>" if date else "") + "</p>\n")
out += '<p class="summary">' + escape(final.get("summary", "")) + "</p>\n"
findings = [x for x in final.get("outcomes", []) if x.get("disposition") != "refuted"]
outcomes = final.get("outcomes", [])
# A merged finding is reported once, on the finding it was merged into,
# as the verdict counts it (review_schema: outcomes not refuted or
# merged). Showing it again gave the same blocker two or three items.
target = {x.get("id"): x.get("target") for x in outcomes if x.get("disposition") == "merged"}
also = {}
for ident in target:
survivor, seen = ident, set()
while survivor in target and survivor not in seen: # the schema forbids cycles
seen.add(survivor)
survivor = target[survivor]
also.setdefault(survivor, []).append(ident)
findings = [x for x in outcomes if x.get("disposition") not in ("refuted", "merged")]
if findings:
out += '<ul class="findings">\n'
for x in findings:
cls, tag = FINDING[(bool(x.get("blocking")), bool(x.get("actionable")))]
# the id, because rationales refer to one another by it
ident = escape(str(x.get("id", "")))
if also.get(x.get("id")):
ident += " (also " + ", ".join(escape(str(i)) for i in also[x.get("id")]) + ")"
out += ('<li class="' + cls + '"><span class="tag">' + tag + "</span> "
+ '<span class="fid">' + ident + "</span> "
+ escape(x.get("rationale", "")) + "</li>\n")
out += "</ul>\n"
out += markdown(final.get("section_md", ""))
Expand Down
33 changes: 33 additions & 0 deletions runner/tests/mutate.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,30 @@
'runner/bin/review_render.py',
'if any(item not in sections for item in expected):',
'if False:'),
('pinfailonly',
'runner/bin/review_discovery.py',
r'(?:\x1b\[[0-9;]*m)?\u2717(?:\x1b\[[0-9;]*m)?',
r'(?:\x1b\[[0-9;]*m)?\S(?:\x1b\[[0-9;]*m)?'),
('pinjobfailed',
'runner/bin/review_discovery.py',
'if run.get("conclusion") != "failure":',
'if False:'),
('pinreuse',
'runner/bin/review_discovery.py',
'ci, checks = self.ci_state(repo, head)',
'ci, checks = self.ci(repo, head), None'),
('pincache',
'runner/bin/review_discovery.py',
'if key in self._pin_logs:',
'if False:'),
('pinaheadold',
'runner/bin/review_discovery.py',
'("(it is ahead", "ahead")',
'("(it is ahead)", "ahead")'),
('rendermerged',
'runner/bin/review_render.py',
'if x.get("disposition") not in ("refuted", "merged")]',
'if x.get("disposition") != "refuted"]'),
('publisheddigest',
'runner/bin/review_delivery.py',
'if served["page_digest"] != expected["page_digest"]:',
Expand Down Expand Up @@ -1005,6 +1029,12 @@
'publisheddigest': 'LocalPublication.test_http_success_with_wrong_page_digest_is_not_publication',
'publishretained': 'LocalPublication.test_comment_requires_retained_generation_page',
'renderidentity': 'RenderContract.test_digest_and_section_identity_are_checked',
'pinfailonly': 'PinCheck.test_only_pins_the_log_reports_as_failed_are_listed',
'pinjobfailed': 'PinCheck.test_a_job_that_did_not_fail_is_not_read',
'pinreuse': 'PinCheck.test_the_log_is_read_only_for_a_pr_that_will_be_reviewed_and_only_once',
'pincache': 'PinCheck.test_the_log_is_read_only_for_a_pr_that_will_be_reviewed_and_only_once',
'pinaheadold': 'PinCheck.test_only_pins_the_log_reports_as_failed_are_listed',
'rendermerged': 'RenderContract.test_a_merged_finding_is_shown_once_on_its_survivor_with_ids',
'renderpagedigest': 'RenderContract.test_digest_and_section_identity_are_checked',
'rendersectiondigest': 'RenderContract.test_section_digest_is_checked_even_with_valid_page_digest',
'saveratelimit': 'PhaseController.test_save_does_not_rewrite_unchanged_state_every_tick'})
Expand Down Expand Up @@ -1365,6 +1395,9 @@ def main():
selected = [m for m in M if not only or m[0] in only]
test_env = {"HOME": home, "PATH": "/usr/bin:/bin", "TMPDIR": work,
"PYTHONDONTWRITEBYTECODE": "1"}
# a machine without /data/review runs the tests under REVIEW_TEST_DIR
if os.environ.get("REVIEW_TEST_DIR"):
test_env["REVIEW_TEST_DIR"] = os.environ["REVIEW_TEST_DIR"]
tests = sorted(t for t in os.listdir(os.path.join(SRC, "runner/tests"))
if t.startswith("test_") and t.endswith(".py"))
try:
Expand Down
8 changes: 6 additions & 2 deletions runner/tests/review_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@


def workspace(case):
Path("/data/review/supervisor-tests").mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix="core-", dir="/data/review/supervisor-tests"))
# /data/review by default, for a box that has it (/tmp may be RAM there);
# anywhere else REVIEW_TEST_DIR must be set, as CI sets it, and as the
# other tests already read it
base = Path(os.environ.get("REVIEW_TEST_DIR", "/data/review")) / "supervisor-tests"
base.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix="core-", dir=base))
case.addCleanup(shutil.rmtree, root, True)
return root

Expand Down
Loading
Loading