diff --git a/.changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md b/.changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md new file mode 100644 index 00000000000..aa2ddaf8ec0 --- /dev/null +++ b/.changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md @@ -0,0 +1,7 @@ +--- +bump: patch +--- + +### Changed + +- `babysit-prs` merge gate: in the pr-merge lane, the verdict reader shares a FAIL's run record for two minutes and an untied FAIL's recorded head ref for the run (keyed by artifact id) across the run's gate processes, instead of reading them again for every candidate. A stale FAIL record still refuses, because a FAIL counts whether its run is running or finished and a re-run keeps every field that decides whether the run is pr-verify's; a PASS's run record is still read by each gate process, so a re-run that undoes a completed success never allows. On the `--unattended` path only, the default branch and the base's rules are also shared for two minutes, a failed read never; before an enqueue, any the gate took from the run cache are read again, and a change holds. diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index 0ca213b07e5..2fdcd514ee5 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -344,9 +344,10 @@ jobs: # allowed. BABYSIT_VERIFY_LISTING: ${{ runner.temp }}/verify-listing.json # Reads that are the same for every candidate (acting login, - # credential pass, permissions, trusted list, run heads on main, the - # queued entries a candidate kept) are shared here within their - # bounds (babysit_run_cache.py). + # credential pass, permissions, trusted list, run heads on main, + # FAIL run records, default branch, base rules, the queued entries + # a candidate kept) are shared here within their bounds + # (babysit_run_cache.py). BABYSIT_RUN_CACHE: ${{ runner.temp }}/babysit-run-cache.json REPO: ${{ github.repository }} OWNER: ${{ github.repository_owner }} diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index ef8b60e4789..2ae49e8620c 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -735,7 +735,15 @@ never shared. A run head found on main is shared for the run, since main's rules pushes; one not found is compared again. In the merge-queue sweep, a queued entry another candidate judged and kept is skipped only while the oldest read behind that judgment (its verdict listing, or a shared permission or trusted list) was taken at most two minutes ago; a gate always judges its own entry, a held entry is judged by every -candidate, and a failed dequeue keeps nothing. Without the variable nothing is shared. +candidate, and a failed dequeue keeps nothing. A FAIL's run record is reused for two minutes: a FAIL +counts whether its run is still running or finished, and a re-run keeps every field that decides +whether the run is pr-verify's, so a stale record never turns a FAIL away. A PASS's run record is +read by each gate process, because a re-run can undo a completed success. An untied FAIL's +recorded head ref is shared for the run under the artifact's id, since the contents an id names +never change (an overwrite uploads a new id). On the `--unattended` path only, the default branch +and the base's rules are reused for two minutes, and a failed read is never shared; before an +enqueue, a default branch or rules a gate took from the file are read again for the branch read, +and any change holds. An attended gate run reads both fresh. Without the variable nothing is shared. ## Trust-root paths diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py index 7572dd42ebe..05f1a69673a 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -523,6 +523,14 @@ def repository_default_branch(repo: str) -> str | None: self-login exemption in place rather than inventing a hold from missing evidence. """ + cached = ( + run_cache.get(merge_policy.DEFAULT_BRANCH_SECTION, repo, run_cache.MAX_AGE) + if SHARE_BASE_READS + else None + ) + if isinstance(cached, str) and cached: + merge_policy.SHARED_DEFAULT_BRANCHES.add(repo) + return cached try: data = gh_json(["api", f"repos/{repo}", "--jq", "{name: .default_branch}"]) except (RuntimeError, json.JSONDecodeError): @@ -530,10 +538,23 @@ def repository_default_branch(repo: str) -> str | None: if not is_json_object(data): return None name = data.get("name") - return str(name) if name else None + if not name: + return None + run_cache.put(merge_policy.DEFAULT_BRANCH_SECTION, repo, str(name)) + return str(name) + + +RULES_SECTION = "branch-rules" +# Whether this gate run may take the default branch and the base's rules +# from the run cache: the `--unattended` path only, whose enqueue reads them +# again (`main`). Every attended path reads them fresh. +SHARE_BASE_READS = False +# The rules this process took from the run cache, by the branch read, as +# summarized; `unattended_enqueue` reads each again before an enqueue. +SHARED_RULES: dict[str, dict[str, object]] = {} -def branch_rules(repo: str, branch: str) -> dict[str, object]: +def branch_rules(repo: str, branch: str, *, shared: bool = True) -> dict[str, object]: """Summarize the effective merge-governing rules for the base branch. Rulesets COMPOSE: `/rules/branches/{branch}` returns one rule of a given @@ -569,9 +590,19 @@ def branch_rules(repo: str, branch: str) -> dict[str, object]: # matches Go's url.PathEscape, which go-github uses for this endpoint # (github.com/google/go-github repos_rules.go, ListRulesForBranch). # gh 2.99.0 forwards that path unchanged. - rules = gh_json( - ["api", f"repos/{repo}/rules/branches/{quote(branch, safe='')}"] + key = f"{repo}|{branch}" + rules = ( + run_cache.get(RULES_SECTION, key, run_cache.MAX_AGE) + if shared and SHARE_BASE_READS + else None ) + cached = is_json_array(rules) + if not cached: + rules = gh_json( + ["api", f"repos/{repo}/rules/branches/{quote(branch, safe='')}"] + ) + if is_json_array(rules): + run_cache.put(RULES_SECTION, key, rules) except (RuntimeError, json.JSONDecodeError) as exc: # Rules are advisory context; a read failure must never fail the run. summary["error"] = f"could not read branch rules: {exc}" @@ -627,6 +658,8 @@ def branch_rules(repo: str, branch: str) -> dict[str, object]: summary["requiredContexts"] = sorted(required_contexts) summary["requiredApprovingReviews"] = required_reviews summary["requireThreadResolution"] = require_thread_resolution + if cached: + SHARED_RULES[branch] = summary return summary @@ -3347,6 +3380,21 @@ def hold(reason: str) -> int: step["optIn"] = opt_in if opt_in: return hold(f"ineligible:{opt_in}") + # An enqueue never rests on a read shared within the run: a default + # branch or base rules the gate took from the run cache are read again, + # and any change holds. + if repo in merge_policy.SHARED_DEFAULT_BRANCHES: + try: + default = merge_policy._default_branch(repo) + except merge_policy.PolicyReadError: + return hold(merge_policy.DEFAULT_BRANCH_UNREADABLE) + if default != branch: + return hold(f"base-not-default:{branch}") + if any( + branch_rules(repo, base, shared=False) != served + for base, served in list(SHARED_RULES.items()) + ): + return hold("the base branch's rules changed since the gate read them") proc = gh_capture( ["api", "-X", "POST", f"repos/{repo}/issues/{number}/comments"] + ["-f", f"body={postmerge.pin_comment(pin)}"] @@ -3431,6 +3479,10 @@ def build_settle(logins: Iterable[str], minutes: str) -> ReviewSettleConfig | No def main() -> int: configure_stdio() + # This gate run's own record of what it took from the run cache. + global SHARE_BASE_READS + SHARED_RULES.clear() + merge_policy.SHARED_DEFAULT_BRANCHES.clear() # allow_abbrev=False: the permission grants covering this gate state their # conditions as the literal presence or absence of a flag in the command # text -- above all "no --merge means check-only". Prefix abbreviation @@ -3640,6 +3692,7 @@ def main() -> int: ), ) args = parser.parse_args() + SHARE_BASE_READS = bool(args.unattended) def _refuse(message: str, code: int, **envelope: object) -> int: """Emit one refusal envelope on stdout and return its exit code. diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge_policy.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge_policy.py index db3e12367cd..d0331b53873 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge_policy.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge_policy.py @@ -1372,10 +1372,13 @@ def _foreign_refusal(pr: dict[str, Any], owner: str) -> str | None: LANE_CLASS = "C2" -def _base_refusal(owner: str, name: str, node: Mapping[str, Any]) -> str | None: +def _base_refusal( + owner: str, name: str, node: Mapping[str, Any], *, shared: bool = False +) -> str | None: """`base-not-default:` when the pull request's base is not the - default branch, read fresh. A failed read raises, which refuses.""" - branch = _default_branch(f"{owner}/{name}") + default branch, read fresh unless `shared` (`_default_branch`). A failed + read raises, which refuses.""" + branch = _default_branch(f"{owner}/{name}", shared=shared) base = node.get("baseRefName") return None if base == branch else f"base-not-default:{base}" @@ -1441,7 +1444,7 @@ class `LANE_CLASS`; no `work-class:` label is read. issue, refusal = _closing_issue(node, repo) if refusal is None: issue_number = issue["number"] - refusal = _base_refusal(owner, name, node) + refusal = _base_refusal(owner, name, node, shared=True) if refusal is None: refusal = _denied_path_refusal( owner, name, number, pr.get("changed_files"), denied_paths @@ -2106,7 +2109,24 @@ def entry_hold( # --- Composition ------------------------------------------------------------------------------ -def _default_branch(repo: str) -> str: +DEFAULT_BRANCH_SECTION = "default-branch" +# Repositories whose default branch this process took from the run cache; +# `unattended_enqueue` reads it again before an enqueue. +SHARED_DEFAULT_BRANCHES: set[str] = set() + + +def _default_branch(repo: str, *, shared: bool = False) -> str: + """The default branch's name. `shared` takes one another gate process of + the run read within `run_cache.MAX_AGE`; every read is saved for them, a + failed one never.""" + cached = ( + run_cache.get(DEFAULT_BRANCH_SECTION, repo, run_cache.MAX_AGE) + if shared + else None + ) + if isinstance(cached, str) and cached: + SHARED_DEFAULT_BRANCHES.add(repo) + return cached owner, name = _split_repo(repo) status, payload = _get(f"repos/{owner}/{name}") branch = ( @@ -2116,6 +2136,7 @@ def _default_branch(repo: str) -> str: ) if not isinstance(branch, str) or not branch: raise PolicyReadError(f"{repo}: the default branch could not be read") + run_cache.put(DEFAULT_BRANCH_SECTION, repo, branch) return branch @@ -2821,7 +2842,7 @@ def assess( # default branch only, so a merge into any other base would go unjudged. # An unreadable default branch is a stop (the identity's entries leave). try: - default = _default_branch(repo) + default = _default_branch(repo, shared=True) except PolicyReadError: return replace(stopped, reason=DEFAULT_BRANCH_UNREADABLE) if base_ref != default: diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_verify_evidence.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_verify_evidence.py index 981918dc7d1..350affa8d03 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_verify_evidence.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_verify_evidence.py @@ -124,6 +124,22 @@ # A run's standing: unreadable, foreign (not of verifier origin), origin (of # verifier origin, not a completed success), or counted (both). UNREAD, FOREIGN, ORIGIN, COUNTED = "unreadable", "foreign", "origin", "counted" +# The run cache's section of run records, and the fields `_run_state` reads. +RUN_SECTION = "run-record" +RECORD_SECTION = "fail-head-ref" +RUN_FIELDS = ( + "id", + "path", + "event", + "head_branch", + "head_sha", + "repository", + "head_repository", + "status", + "conclusion", + "run_attempt", + "run_started_at", +) class _Unreadable(Exception): @@ -240,6 +256,8 @@ class Reader: _listing_error: str | None = None _runs: dict[int, str] = field(default_factory=dict) _started: dict[int, Any] = field(default_factory=dict) + # Runs whose standing came from the run cache (`_run_state`). + _shared_runs: set[int] = field(default_factory=set) _on_branch: dict[str, bool] = field(default_factory=dict) _records: dict[tuple[int, str], dict[str, Any]] = field(default_factory=dict) _humans: frozenset[int] | None = None @@ -394,41 +412,74 @@ def _contains(self, sha: str) -> bool: run_cache.put("on-branch", key, True) return self._on_branch[sha] - def _run_state(self, run_id: int) -> str: - if run_id not in self._runs: - try: + def _run_state(self, run_id: int, *, shared: bool = False) -> str: + """The run's standing. A FAIL's run (`shared`) may be judged on a + record another gate process of the run read within + `run_cache.MAX_AGE`: a FAIL counts whether its run is origin or + counted, and origin rests only on fields a re-run keeps (id, path, + event, branch, repositories, head), never on status, conclusion or + attempt, so a stale record cannot turn a FAIL away. A PASS needs a + completed success, which a re-run can undo, so its run is read by + this process.""" + if run_id in self._runs and (shared or run_id not in self._shared_runs): + return self._runs[run_id] + key = f"{self.repo}|{run_id}" + record = run_cache.get(RUN_SECTION, key, run_cache.MAX_AGE) if shared else None + cached = is_json_object(record) + try: + if not cached: record = json_object( self._actions( ["api", f"repos/{self.repo}/actions/runs/{run_id}"], f"run {run_id}", ) ) - head = record.get("head_sha") - origin = ( - record.get("id") == run_id - and record.get("path") == WORKFLOW_PATH - and record.get("event") == "workflow_run" - and record.get("head_branch") == self.branch - and json_object(record.get("repository")).get("full_name") - == self.repo - and json_object(record.get("head_repository")).get("full_name") - == self.repo - and isinstance(head, str) - and merge_policy.SHA_RE.fullmatch(head) is not None - and self._contains(head) - ) - self._started[run_id] = record.get("run_started_at") - done = ( - record.get("status") == "completed" - and record.get("conclusion") == "success" - ) - self._runs[run_id] = ( - FOREIGN if not origin else COUNTED if done else ORIGIN - ) - except _Unreadable: - self._runs[run_id] = UNREAD + head = record.get("head_sha") + origin = ( + record.get("id") == run_id + and record.get("path") == WORKFLOW_PATH + and record.get("event") == "workflow_run" + and record.get("head_branch") == self.branch + and json_object(record.get("repository")).get("full_name") == self.repo + and json_object(record.get("head_repository")).get("full_name") + == self.repo + and isinstance(head, str) + and merge_policy.SHA_RE.fullmatch(head) is not None + and self._contains(head) + ) + except _Unreadable: + self._shared_runs.discard(run_id) + self._runs[run_id] = UNREAD + return UNREAD + if cached: + self._shared_runs.add(run_id) + else: + self._shared_runs.discard(run_id) + self._started[run_id] = record.get("run_started_at") + run_cache.put(RUN_SECTION, key, {k: record.get(k) for k in RUN_FIELDS}) + done = ( + record.get("status") == "completed" + and record.get("conclusion") == "success" + ) + self._runs[run_id] = FOREIGN if not origin else COUNTED if done else ORIGIN return self._runs[run_id] + def _head_ref(self, run_id: int, name: str, artifact_id: Any) -> Any: + """The head ref an untied FAIL's verdict.json records, shared by the + run's gate processes under the artifact's id: an id names contents + that never change (an overwrite uploads a new id), and a FAIL whose + artifact has since gone still refuses. An artifact with no id is not + shared.""" + shared = isinstance(artifact_id, int) and not isinstance(artifact_id, bool) + key = f"{self.repo}|{artifact_id}" + dated = run_cache.get_dated(RECORD_SECTION, key, None) if shared else None + if dated is not None and is_json_object(dated[0]): + return dated[0].get("head_ref") + record = self._record(run_id, name) + if shared: + run_cache.put(RECORD_SECTION, key, {"head_ref": record.get("head_ref")}) + return record.get("head_ref") + def _record(self, run_id: int, name: str) -> dict[str, Any]: """The artifact's verdict.json, downloaded once.""" key = (run_id, name) @@ -657,7 +708,7 @@ def _evidence(self, number: int, head: str, pr: dict[str, Any] | None) -> Eviden else: ignored += 1 continue - state = self._run_state(run_id) + state = self._run_state(run_id, shared=True) if state == FOREIGN: ignored += 1 continue @@ -669,7 +720,7 @@ def _evidence(self, number: int, head: str, pr: dict[str, Any] | None) -> Eviden continue if not tied: try: - recorded = self._record(run_id, name).get("head_ref") + recorded = self._head_ref(run_id, name, item.get("id")) except _Unreadable: unreadable = unreadable or f"record of {name}" continue diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_branch_rules.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_branch_rules.py index c1a19f0137b..fe188976930 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_branch_rules.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_branch_rules.py @@ -15,15 +15,22 @@ from __future__ import annotations +import contextlib +import io +import json import pathlib import sys +import tempfile import unittest +from datetime import UTC, datetime, timedelta from typing import Any from unittest import mock +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) import babysit_merge as merge +from repo_config_fake import RepoConfigFake HEAD = "a" * 40 # The base compare the freshness hold reads for an otherwise-ready PR. @@ -36,9 +43,7 @@ def _status_checks_rule(contexts: list[str]) -> dict[str, Any]: return { "type": "required_status_checks", - "parameters": { - "required_status_checks": [{"context": c} for c in contexts] - }, + "parameters": {"required_status_checks": [{"context": c} for c in contexts]}, } @@ -83,9 +88,7 @@ def test_contexts_from_every_ruleset_survive(self) -> None: _status_checks_rule(CI_GATE), _status_checks_rule(SECURITY_GATE), ) - self.assertEqual( - summary["requiredContexts"], sorted(CI_GATE + SECURITY_GATE) - ) + self.assertEqual(summary["requiredContexts"], sorted(CI_GATE + SECURITY_GATE)) def test_a_context_required_by_two_rulesets_is_reported_once(self) -> None: summary = _branch_rules( @@ -189,7 +192,13 @@ def gh_json(args: list[str]) -> Any: mock.patch.object(merge, "fetch_review_threads", return_value=[]), ): return merge.evaluate( - "owner/repo", PR_NUMBER, None, {"owner"}, frozenset(), False, False, + "owner/repo", + PR_NUMBER, + None, + {"owner"}, + frozenset(), + False, + False, ) def test_empty_trailing_rule_leaves_the_base_protected(self) -> None: @@ -199,9 +208,7 @@ def test_empty_trailing_rule_leaves_the_base_protected(self) -> None: _status_checks_rule([]), ) self.assertFalse(result["baseUnprotected"]) - self.assertEqual( - [b for b in result["blockers"] if "unprotected" in b], [] - ) + self.assertEqual([b for b in result["blockers"] if "unprotected" in b], []) def test_no_context_anywhere_still_reports_an_unprotected_base(self) -> None: result = self._evaluate(NO_REQUIRED_REVIEWS, _status_checks_rule([])) @@ -224,5 +231,112 @@ def test_a_plain_base_is_unchanged(self) -> None: gh.assert_called_once_with(["api", "repos/owner/repo/rules/branches/main"]) +class OneRunSharesTheBaseReads(unittest.TestCase): + """With `BABYSIT_RUN_CACHE` named, the base's rules and the default + branch are read once per run within `run_cache.MAX_AGE`; a failed read + is never shared, and `shared=False` reads the rules fresh.""" + + RULES = [_status_checks_rule(CI_GATE)] + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + # The `--unattended` path, which `main` lets share. + for patcher in ( + mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}), + mock.patch.object(merge, "SHARE_BASE_READS", True), + ): + patcher.start() + self.addCleanup(patcher.stop) + + def test_the_rules_are_read_once_per_run(self) -> None: + with mock.patch.object(merge, "gh_json", return_value=list(self.RULES)) as gh: + summaries = [merge.branch_rules("owner/repo", "main") for _ in range(3)] + merge.branch_rules("owner/repo", "main", shared=False) + self.assertEqual(gh.call_count, 2) + self.assertEqual(summaries[0], summaries[2]) + self.assertEqual(summaries[0]["requiredContexts"], sorted(CI_GATE)) + + def test_a_failed_rules_read_is_not_shared(self) -> None: + with mock.patch.object(merge, "gh_json", side_effect=RuntimeError("502")) as gh: + for _ in range(2): + self.assertIn("error", merge.branch_rules("owner/repo", "main")) + self.assertEqual(gh.call_count, 2) + + def test_rules_past_the_bound_are_read_again(self) -> None: + clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] + with ( + mock.patch.object(merge.run_cache, "now", side_effect=lambda: clock[0]), + mock.patch.object(merge, "gh_json", return_value=list(self.RULES)) as gh, + ): + merge.branch_rules("owner/repo", "main") + clock[0] += merge.run_cache.MAX_AGE + timedelta(seconds=1) + merge.branch_rules("owner/repo", "main") + self.assertEqual(gh.call_count, 2) + + def test_the_default_branch_is_read_once_per_run(self) -> None: + with mock.patch.object(merge, "gh_json", return_value={"name": "main"}) as gh: + names = [merge.repository_default_branch("owner/repo") for _ in range(3)] + self.assertEqual(names, ["main"] * 3) + self.assertEqual(gh.call_count, 1) + + def test_a_failed_default_branch_read_is_not_shared(self) -> None: + with mock.patch.object(merge, "gh_json", side_effect=RuntimeError("502")) as gh: + for _ in range(2): + self.assertIsNone(merge.repository_default_branch("owner/repo")) + self.assertEqual(gh.call_count, 2) + + +class AnAttendedGateReadsTheBaseFresh(unittest.TestCase): + """Without `--unattended`, a gate run never takes the base's rules or the + default branch from the run cache, whatever the cache holds.""" + + QUEUE = {"type": "merge_queue", "parameters": {}} + + def test_the_rules_and_the_default_branch_are_read_fresh(self) -> None: + RepoConfigFake().install(self) + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + fresh = [self.QUEUE, _status_checks_rule(["ci-status"])] + with mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}): + stale = [self.QUEUE, _status_checks_rule(["stale-check"])] + merge.run_cache.put(merge.RULES_SECTION, "owner/repo|main", stale) + merge.run_cache.put("default-branch", "owner/repo", "stale-default") + + def gh_json(args: list[str]) -> Any: + if args[0] == "api" and "/compare/" in args[1]: + return UP_TO_DATE + if args[:2] == ["pr", "view"]: + return _pr() + if args[0] == "api" and "/rules/branches/" in args[1]: + return list(fresh) + if args[0] == "api": + return {"name": "main"} + raise AssertionError(f"unexpected gh_json call: {args}") + + argv = ["babysit_merge.py", f"owner/repo#{PR_NUMBER}"] + out = io.StringIO() + with ( + mock.patch.object(sys, "argv", [*argv, "--allowed-owners", "owner"]), + mock.patch.object(merge, "gh_json", side_effect=gh_json), + mock.patch.object(merge, "resolve_authors", return_value=[]), + mock.patch.object(merge, "fetch_review_threads", return_value=[]), + mock.patch.object(merge, "fetch_pull_request_reviews", return_value=[]), + mock.patch.object(merge, "fetch_issue_comments", return_value=[]), + mock.patch.object( + merge, "fetch_pull_request_review_comments", return_value=[] + ), + contextlib.redirect_stdout(out), + ): + merge.main() + result = json.loads(out.getvalue()) + self.assertEqual(result["effectiveRules"]["requiredContexts"], ["ci-status"]) + self.assertEqual( + [b for b in result["blockers"] if "not the default branch" in b], [] + ) + + if __name__ == "__main__": unittest.main() diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_policy.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_policy.py index d06780f0df2..1170b521ba2 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_policy.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_policy.py @@ -3920,6 +3920,26 @@ def test_a_credential_refusal_is_read_again(self) -> None: ) self.assertEqual(self.reads(gh)[1], 2) + def test_the_default_branch_is_read_once_per_run(self) -> None: + gh = self.gh() + for _ in range(3): + self.candidate() + self.assertEqual(gh.calls.count(["api", f"repos/{REPO}"]), 1) + + def test_the_pre_enqueue_base_check_reads_the_default_branch_fresh(self) -> None: + gh = self.gh() + self.candidate() + policy._base_refusal("owner", "repo", {"baseRefName": "trunk"}) + self.assertEqual(gh.calls.count(["api", f"repos/{REPO}"]), 2) + + def test_a_failed_default_branch_read_is_not_shared(self) -> None: + gh = GhFake().install(self) + gh.rest[f"repos/{REPO}"] = 502 + for _ in range(2): + with self.assertRaises(policy.PolicyReadError): + policy._default_branch(REPO, shared=True) + self.assertEqual(gh.calls.count(["api", f"repos/{REPO}"]), 2) + def permission_reads(self, answer: Any, readers: int = 2) -> int: gh = GhFake().install(self) endpoint = f"repos/{REPO}/collaborators/{OPERATOR}/permission" diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py index 042629e9c67..ed72bb57452 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py @@ -386,7 +386,7 @@ def _lane_evidence(self, *args: Any) -> Any: raise self.lane_error return self.lanes, self.comments - def _default_branch(self, repo: str) -> str: + def _default_branch(self, repo: str, *, shared: bool = False) -> str: if self.default_branch is None: raise policy.PolicyReadError("the default branch could not be read") return self.default_branch @@ -490,7 +490,7 @@ def gh_json(args: list[str]) -> Any: mock.patch.object( policy, "_base_refusal", - side_effect=lambda *a: self.base_reads.append(a) or self.base_now, + side_effect=lambda *a, **k: self.base_reads.append(a) or self.base_now, ), *( [] @@ -640,6 +640,71 @@ def test_the_lane_takes_the_rung_cap_from_the_workflow(self) -> None: out["unattended"]["rungCap"], {"value": None, "reason": "no-cap"} ) + def shared_rules(self) -> None: + """A run cache holding the base's rules as an earlier candidate read + them (QUEUE_RULES).""" + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + patcher = mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}) + patcher.start() + self.addCleanup(patcher.stop) + merge.run_cache.put(merge.RULES_SECTION, "owner/repo|main", QUEUE_RULES) + + def test_rules_changed_since_the_shared_read_hold_the_enqueue(self) -> None: + self.shared_rules() + extra = { + "type": "required_status_checks", + "parameters": {"required_status_checks": [{"context": "new-check"}]}, + } + self.rules = [*QUEUE_RULES, extra] + code, out = self.lane() + self.assert_no_merge(code) + self.assertIn( + merge.UNATTENDED_REFUSED + + "the base branch's rules changed since the gate read them", + out["blockers"], + ) + + def test_rules_shared_for_another_landing_base_are_read_again(self) -> None: + # The gate read the rules of a landing base other than the pull + # request's base (a `rules_base` override): that base is the one + # read again before the enqueue. + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + patcher = mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}) + patcher.start() + self.addCleanup(patcher.stop) + merge.run_cache.put(merge.RULES_SECTION, "owner/repo|trunk", QUEUE_RULES) + real = merge.branch_rules + patcher = mock.patch.object( + merge, + "branch_rules", + side_effect=lambda repo, branch, **kw: real( + repo, "trunk" if kw.get("shared", True) else branch, **kw + ), + ) + patcher.start() + self.addCleanup(patcher.stop) + extra = { + "type": "required_status_checks", + "parameters": {"required_status_checks": [{"context": "new-check"}]}, + } + self.rules = [*QUEUE_RULES, extra] + code, out = self.lane() + self.assert_no_merge(code) + self.assertIn( + merge.UNATTENDED_REFUSED + + "the base branch's rules changed since the gate read them", + out["blockers"], + ) + + def test_unchanged_shared_rules_still_enqueue(self) -> None: + self.shared_rules() + code, out = self.lane() + self.assertEqual(code, 0, out["blockers"]) + def test_a_workflow_cap_below_the_rung_refuses(self) -> None: code, out = self.run_main( "--authority", "pr-merge", "--lane-kill-switch", "proceed", diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py index 6929dc80dd2..b1a23159bef 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py @@ -1078,6 +1078,82 @@ def test_the_trusted_list_is_read_once_within_the_bound(self) -> None: self.assertEqual(self.trusted_reads(fake), 2) +class OneRunSharesItsFailRunReads(unittest.TestCase): + """With `BABYSIT_RUN_CACHE` named, a FAIL's run record (for + `run_cache.MAX_AGE`) and an untied FAIL's recorded head ref are read + once per run. A PASS's run is read by every gate process, so a re-run + that undoes a completed success never allows on a shared record.""" + + OTHER = UNRELATED + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + patcher = mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}) + patcher.start() + self.addCleanup(patcher.stop) + + def other_fail(self) -> FakeGitHub: + """A pass at the head (run 1) and another PR's FAIL (run 2).""" + name = named(self.OTHER, "fail", 99) + fake = passing(artifact(name, 2), runs={2: run(2)}) + fake.records[name] = record(99, self.OTHER, head_ref="feat/other") + return fake + + @staticmethod + def run_reads(fake: FakeGitHub, run_id: int) -> int: + return sum( + any(a.endswith(f"/actions/runs/{run_id}") for a in c) for c in fake.calls + ) + + @staticmethod + def downloads(fake: FakeGitHub, run_id: int) -> int: + return sum(c[:3] == ["run", "download", str(run_id)] for c in fake.calls) + + def test_a_fail_run_and_its_record_are_read_once_per_run(self) -> None: + fake = self.other_fail() + for _ in range(3): + self.assertIsNone(read(fake).refusal) + self.assertEqual(self.run_reads(fake, 2), 1) + self.assertEqual(self.downloads(fake, 2), 1) + # The pass's run is read by every candidate. + self.assertEqual(self.run_reads(fake, 1), 3) + + def test_a_replaced_artifact_of_the_same_name_is_read_again(self) -> None: + # An overwrite uploads a new id under the same name: the head ref + # shared for the old id must not stand for the new contents. + fake = self.other_fail() + self.assertIsNone(read(fake).refusal) + name = named(self.OTHER, "fail", 99) + fake.artifacts[1] = {**fake.artifacts[1], "id": 21} + fake.records[name] = record(99, self.OTHER, head_ref="feat/x") + self.assertEqual(read(fake).refusal, "verify:earlier-fail") + self.assertEqual(self.downloads(fake, 2), 2) + + def test_a_fail_run_past_the_bound_is_read_again(self) -> None: + clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] + fake = self.other_fail() + with mock.patch.object(ve.run_cache, "now", side_effect=lambda: clock[0]): + read(fake) + clock[0] += ve.run_cache.MAX_AGE + timedelta(seconds=1) + read(fake) + self.assertEqual(self.run_reads(fake, 2), 2) + + def test_a_re_run_of_a_counted_pass_does_not_allow(self) -> None: + fake = passing() + self.assertIsNone(read(fake).refusal) + fake.runs[1] = run(1, status="in_progress", conclusion=None, run_attempt=2) + self.assertEqual(read(fake).refusal, "verify:missing") + + def test_a_re_run_of_a_fail_still_refuses_on_the_shared_record(self) -> None: + fake = passing(artifact(named(HEAD, "fail"), 2), runs={2: run(2)}) + self.assertEqual(read(fake).refusal, "verify:fail") + fake.runs[2] = run(2, status="in_progress", conclusion=None, run_attempt=2) + self.assertEqual(read(fake).refusal, "verify:fail") + self.assertEqual(self.run_reads(fake, 2), 1) + + # --- A transient listing failure is read again -------------------------------- # Every test runs without the backoff sleep; `judge` reads the waits off it.