From 7d1725b77456dec64b841e7f99dc066af9de7b9a Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:35:21 -0400 Subject: [PATCH 1/7] perf(source-control): read the pr-verify artifact listing once per pr-merge run pr-merge.yml runs babysit_merge.py once per candidate, and each run built its own verify_evidence.Reader, which pages repos/{repo}/actions/artifacts?per_page=100 in full. The repository holds about 3,006 artifacts (about 31 pages), so a run with 27 candidates spent about 840 listing requests on github.token, whose limit is 1,000 requests an hour per repository. Gate runs now hit the 30-minute job timeout; run 39089472370 was cancelled after 11 candidates. The API's name filter matches whole names only and a FAIL counts under any pull request number and head (and by recorded head branch), so the names the reader needs are not known per candidate. Instead the gate step sets BABYSIT_VERIFY_LISTING: the first candidate saves its listing there and later candidates, and their queued-entry checks, read it. A saved listing can only lack artifacts uploaded since it was taken, so a refusal on it stands. A candidate it would allow is judged again on a listing of its own before it is allowed, and that listing replaces the saved one. A failed listing is never saved, a missing or malformed file is read from the API, and the run-record and download reads are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../perf-verify-listing-once-9a4c2e17.md | 7 ++ .github/workflows/pr-merge.yml | 4 + docs/conventions/pr-pipeline/README.md | 12 ++- .../babysit-prs/scripts/babysit_merge.py | 5 + .../scripts/babysit_verify_evidence.py | 73 ++++++++++++-- .../tests/test_babysit_verify_evidence.py | 98 +++++++++++++++++++ 6 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 .changes/source-control/perf-verify-listing-once-9a4c2e17.md diff --git a/.changes/source-control/perf-verify-listing-once-9a4c2e17.md b/.changes/source-control/perf-verify-listing-once-9a4c2e17.md new file mode 100644 index 00000000000..ff01a7efd24 --- /dev/null +++ b/.changes/source-control/perf-verify-listing-once-9a4c2e17.md @@ -0,0 +1,7 @@ +--- +bump: patch +--- + +### Changed + +- `babysit-prs` merge gate: in the pr-merge lane the verdict reader pages the repository's artifact listing once per run instead of once per candidate. When `BABYSIT_VERIFY_LISTING` names a file, the first candidate saves its listing there and later candidates, and their queued-entry checks, read it. A refusal on the saved listing stands; a candidate it would allow is judged again on a listing of its own, which replaces the saved one. A failed listing is never saved, and a missing or malformed file is read from the API. The pr-merge workflow sets the variable for its gate loop. Without it nothing changes. diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index faf5aa2bb57..614536a219a 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -338,6 +338,10 @@ jobs: # GH_TOKEN (babysit_verify_evidence.py); the job runs main's code # alone, never a PR's. BABYSIT_VERIFY_GH_TOKEN: ${{ github.token }} + # The first candidate saves its artifact listing here and the rest + # of the run reads it; a candidate the saved listing would allow + # lists again before it is allowed. + BABYSIT_VERIFY_LISTING: ${{ runner.temp }}/verify-listing.json REPO: ${{ github.repository }} OWNER: ${{ github.repository_owner }} SCRIPT: ${{ steps.config.outputs.script }} diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index d62876fdb17..e25384a0f23 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -710,11 +710,15 @@ by merging in person: the verdict is not a check run and stays out of `ci-status checks (github-iac ADR 0011), so a human merge needs `ci-status` alone. A queued entry without an allowing verdict at its live head leaves the queue. A dependency manager's pull request (a `Bot` account with a dependency manager's login; a `User` named like one is judged) needs no verdict: the lane decides it in its Dependabot class before the verdict is read, or refuses it, and -its queued entry is not held for one. The gate lists every repository artifact once per -candidate run, since pr-merge.yml runs the gate once per candidate. A listing that got a 5xx or a fast +its queued entry is not held for one. pr-merge.yml runs the gate once per candidate and names a file +in `BABYSIT_VERIFY_LISTING`: the first candidate lists every repository artifact and saves the +listing there, and later candidates and their queued-entry checks read it instead of paging again. +A saved listing can only lack artifacts uploaded since, so a refusal on it stands; a candidate it +would allow is judged again on a listing of its own before it is allowed, which is saved in turn. +A listing that got a 5xx or a fast network error is read again, three reads in all with backoff, all inside the one gh timeout a single -read would get; any other failure, a timeout, a 429 or a rate-limit 403 included, is not. A failed listing is kept for -that run as well: the pull request and every queued entry refuse `verify:unreadable` without the +read would get; any other failure, a timeout, a 429 or a rate-limit 403 included, is not. A failed listing is never +saved, and is kept for that candidate's gate run: the pull request and every queued entry refuse `verify:unreadable` without the listing being paged again, so a listing outage holds the whole queue rather than merging blind. The lane token holds no Actions permission, so pr-merge.yml grants its job `actions: read` and passes the job's `GITHUB_TOKEN` as `BABYSIT_VERIFY_GH_TOKEN`; the reader uses it as `GH_TOKEN` for the artifact listing, the run 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 90109591d49..132ec2cc171 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -2892,6 +2892,11 @@ def score_unattended( ): reader = verify_evidence.Reader(repo, str(inputs["branch"])) verdict = reader.evidence(number, str(details["headSha"]), pr) + if verdict.refusal is None and reader.saved: + # The run's saved listing lacks anything uploaded since; allow + # only on a listing of this gate run's own. + reader.refresh() + verdict = reader.evidence(number, str(details["headSha"]), pr) details["verify"] = verdict.report() inputs["verify_reader"] = reader if verdict.refusal: 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 f3ac50c0488..24702c1c354 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 @@ -40,17 +40,24 @@ `verify:too-old`, `verify:earlier-fail`, `verify:spec-changed` and `verify:untrusted-spec` need a human, who merges in person. Any read that fails refuses (`verify:unreadable`). The repository's artifacts are listed once per -`Reader`, which pr-merge.yml builds once per candidate gate run, every page, -and filtered on the name here: the API's name filter matches whole names only. -A listing that got a 5xx or a fast network error is read again after each of -`LISTING_WAITS`, every read inside one gh timeout in all; any other failure, a -timeout, a 429 or a rate-limit 403 included, is not. A failed listing is kept -as well, so one outage refuses every entry of the run without paging again: -it holds the whole queue rather than merging blind. +`Reader`, every page, and filtered on the name here: the API's name filter +matches whole names only, and a FAIL counts under any number and head. +pr-merge.yml builds one `Reader` per candidate gate run and names a file in +`LISTING_ENV`: a successful listing is saved there, and later candidates of +the run read it instead of paging again. A listing taken earlier in the run +can only lack later uploads, so a refusal on it stands; before the gate's own +candidate is allowed on it, babysit_merge.py calls `refresh()` and judges it +again on a listing of its own. A listing that got a 5xx or a fast network +error is read again after each of `LISTING_WAITS`, every read inside one gh +timeout in all; any other failure, a timeout, a 429 or a rate-limit 403 +included, is not. A failed listing is never saved, and is kept as well, so one +outage refuses every entry of the gate run without paging again: it holds the +whole queue rather than merging blind. """ from __future__ import annotations +import contextlib import json import os import re @@ -70,6 +77,7 @@ WORKFLOW_PATH = ".github/workflows/pr-verify.yml" TRUSTED_ACTORS_PATH = ".github/standards/trusted-actors/trusted-actors.json" TOKEN_ENV = "BABYSIT_VERIFY_GH_TOKEN" +LISTING_ENV = "BABYSIT_VERIFY_LISTING" NAME_RE = re.compile(r"pr-verify-([1-9][0-9]*)-([0-9a-f]{40})-(pass|pass-notes|fail)") PASSES = ("pass", "pass-notes") # Artifacts last at most 90 days in this repository (the retention maximum, @@ -204,7 +212,13 @@ class Reader: actions_token: str | None = field( default_factory=lambda: os.environ.get(TOKEN_ENV) or None ) + # The run's saved listing (`LISTING_ENV`), when pr-merge.yml names one. + listing_path: str | None = field( + default_factory=lambda: os.environ.get(LISTING_ENV) or None + ) _artifacts: list[dict[str, Any]] | None = None + _saved: bool = False # `_artifacts` came from `listing_path` + _own: bool = False # `refresh()` asked for a listing of this Reader's own _listing_error: str | None = None _runs: dict[int, str] = field(default_factory=dict) _started: dict[int, Any] = field(default_factory=dict) @@ -213,11 +227,15 @@ class Reader: _humans: frozenset[int] | None = None def _listing(self) -> list[dict[str, Any]]: - """Every repository artifact, read once: a failed read is kept too, - so one outage refuses each later entry without paging again.""" + """Every repository artifact, read once (from the run's saved listing + when there is one): a failed read is kept too, so one outage refuses + each later entry without paging again.""" if self._listing_error is not None: raise _Unreadable(self._listing_error) listing = self._artifacts + if listing is None: + listing = None if self._own else self._load_saved() + self._saved = listing is not None if listing is None: try: listing = flatten_paginated_items( @@ -226,9 +244,44 @@ def _listing(self) -> list[dict[str, Any]]: except (_Unreadable, RuntimeError) as exc: self._listing_error = str(exc) raise _Unreadable(self._listing_error) from exc - self._artifacts = listing + self._save(listing) + self._artifacts = listing + return listing + + @property + def saved(self) -> bool: + """Whether the listing judged on was read from `listing_path`.""" + return self._saved + + def refresh(self) -> None: + """Drop a saved listing: the next judgment pages the API itself (and + saves that listing for the rest of the run).""" + if self._saved: + self._artifacts, self._saved, self._own = None, False, True + + def _load_saved(self) -> list[dict[str, Any]] | None: + """The run's saved listing; a missing or malformed file is none, so + the listing is read from the API instead.""" + if not self.listing_path: + return None + try: + listing = json.loads(Path(self.listing_path).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not is_json_array(listing) or not all(map(is_json_object, listing)): + return None return listing + def _save(self, listing: list[dict[str, Any]]) -> None: + """Best effort: a failed write leaves the next candidate to list.""" + if not self.listing_path: + return + path = Path(self.listing_path) + tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") + with contextlib.suppress(OSError): + tmp.write_text(json.dumps(listing), encoding="utf-8") + os.replace(tmp, path) + def _read_listing(self) -> Any: """The listing payload, read again after a 5xx or a fast network error while time is left: every read and wait fits in the one gh 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 7bb7258469d..90f8a54944a 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 @@ -25,6 +25,7 @@ import pathlib import subprocess import sys +import tempfile import unittest from datetime import UTC, datetime from typing import Any @@ -883,6 +884,74 @@ def test_a_failed_listing_refuses_every_entry_and_is_not_read_per_entry( self.assertEqual(len(listings), len(ve.LISTING_WAITS) + 1) +def listings(fake: FakeGitHub) -> int: + return sum(any("actions/artifacts" in a for a in c) for c in fake.calls) + + +class TheListingIsReadOncePerRun(unittest.TestCase): + """pr-merge.yml runs one gate, so one `Reader`, per candidate and names a + file in `BABYSIT_VERIFY_LISTING`: the run pages the artifact listing once, + and a saved listing never allows on its own.""" + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.path = str(pathlib.Path(tmp.name, "verify-listing.json")) + patcher = mock.patch.dict("os.environ", {"BABYSIT_VERIFY_LISTING": self.path}) + patcher.start() + self.addCleanup(patcher.stop) + + def gate(self, fake: FakeGitHub) -> tuple[ve.Reader, ve.Evidence]: + """One candidate's gate run: a fresh Reader.""" + with mock.patch.object(postmerge, "gh_capture", side_effect=fake): + reader = ve.Reader(REPO, "main", now=NOW) + return reader, reader.evidence(PR, HEAD, pull()) + + def test_candidates_of_one_run_share_one_listing(self) -> None: + fake = FakeGitHub([artifact(named(HEAD, "fail"), 1)], {1: run(1)}) + for _ in range(3): + _, evidence = self.gate(fake) + self.assertEqual(evidence.refusal, "verify:fail") + self.assertEqual(listings(fake), 1) + + def test_an_allow_on_the_saved_listing_sees_a_later_fail(self) -> None: + first, _ = self.gate(passing()) + self.assertFalse(first.saved) + fake = passing(artifact(named(HEAD, "fail"), 2), runs={2: run(2)}) + with mock.patch.object(postmerge, "gh_capture", side_effect=fake): + reader = ve.Reader(REPO, "main", now=NOW) + self.assertIsNone(reader.evidence(PR, HEAD, pull()).refusal) + self.assertTrue(reader.saved) + reader.refresh() + self.assertEqual(reader.evidence(PR, HEAD, pull()).refusal, "verify:fail") + self.assertFalse(reader.saved) + self.assertEqual(listings(fake), 1) + # The fresher listing is saved for the rest of the run. + _, evidence = self.gate(fake) + self.assertEqual(evidence.refusal, "verify:fail") + self.assertEqual(listings(fake), 1) + + def test_a_failed_listing_is_not_saved(self) -> None: + fake = passing() + fake.fail = {"actions/artifacts"} + _, evidence = self.gate(fake) + self.assertEqual(evidence.refusal, "verify:unreadable") + self.assertFalse(pathlib.Path(self.path).exists()) + fake.fail = set() + _, evidence = self.gate(fake) + self.assertIsNone(evidence.refusal) + + def test_a_malformed_saved_listing_is_read_from_the_api(self) -> None: + for text in ("not json", '{"artifacts": []}', "[1]"): + with self.subTest(text): + pathlib.Path(self.path).write_text(text) + fake = passing() + reader, evidence = self.gate(fake) + self.assertIsNone(evidence.refusal) + self.assertFalse(reader.saved) + self.assertEqual(listings(fake), 1) + + # --- A transient listing failure is read again -------------------------------- # Every test runs without the backoff sleep; `judge` reads the waits off it. @@ -1227,6 +1296,35 @@ def test_a_pass_at_the_head_enqueues(self) -> None: self.read.assert_called_once_with(unattended.PR, unattended.HEAD) self.assertIn("verify", out["unattended"]) + def saved_listing(self) -> mock.Mock: + """The reader judged on the run's saved listing; returns `refresh`.""" + patcher = mock.patch.object(ve.Reader, "saved", new=True) + patcher.start() + self.addCleanup(patcher.stop) + patcher = mock.patch.object(ve.Reader, "refresh") + refresh = patcher.start() + self.addCleanup(patcher.stop) + return refresh + + def test_an_allow_on_the_saved_listing_is_judged_again_on_its_own(self) -> None: + # A FAIL uploaded after the run saved its listing still refuses. + refresh = self.saved_listing() + self.read.side_effect = [evidence(None), evidence("verify:fail")] + code, out = self.lane() + self.assert_no_merge(code) + self.assertEqual(out["unattended"]["reason"], "verify:fail") + refresh.assert_called_once_with() + self.assertEqual(self.read.call_count, 2) + + def test_a_refusal_on_the_saved_listing_stands_without_a_listing(self) -> None: + refresh = self.saved_listing() + self.verdicts[unattended.PR] = evidence("verify:missing") + code, out = self.lane() + self.assert_no_merge(code) + self.assertEqual(out["unattended"]["reason"], "verify:missing") + refresh.assert_not_called() + self.read.assert_called_once_with(unattended.PR, unattended.HEAD) + def test_a_fail_refuses_and_dequeues_its_own_entry(self) -> None: self.verdicts[unattended.PR] = evidence("verify:fail") self.queued = [unattended.PR] From 45a03970445b82ce16b727c4b07dc9c55feee8e2 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:41:44 -0400 Subject: [PATCH 2/7] fix(source-control): bound the verify listing's age at two minutes Queued-entry holds judged every queued entry on the run's first saved listing. pr-verify is not a required check, so a queued pull request whose FAIL was uploaded mid-run could land during a run of up to 30 minutes. The saved listing now carries fetchedAt, the time its read began. No judgment, of a candidate or a queued entry, uses a listing, saved or in memory, begun more than LISTING_MAX_AGE (two minutes) before it: an older one, or a saved file with no zoned fetchedAt, is read again and saved. Holds are judged inside each candidate's gate process, so a one-time hold refresh would need a cross-process marker; an age bound needs none. Age-driven listings are at most one per two minutes, 16 in a 30-minute run, plus one for each candidate the saved listing would allow. Co-Authored-By: Claude Opus 5.5 --- .../perf-verify-listing-once-9a4c2e17.md | 2 +- .github/workflows/pr-merge.yml | 5 +- docs/conventions/pr-pipeline/README.md | 3 +- .../scripts/babysit_verify_evidence.py | 88 +++++++++++++------ .../tests/test_babysit_verify_evidence.py | 64 +++++++++++++- 5 files changed, 129 insertions(+), 33 deletions(-) diff --git a/.changes/source-control/perf-verify-listing-once-9a4c2e17.md b/.changes/source-control/perf-verify-listing-once-9a4c2e17.md index ff01a7efd24..1476a4d49ec 100644 --- a/.changes/source-control/perf-verify-listing-once-9a4c2e17.md +++ b/.changes/source-control/perf-verify-listing-once-9a4c2e17.md @@ -4,4 +4,4 @@ bump: patch ### Changed -- `babysit-prs` merge gate: in the pr-merge lane the verdict reader pages the repository's artifact listing once per run instead of once per candidate. When `BABYSIT_VERIFY_LISTING` names a file, the first candidate saves its listing there and later candidates, and their queued-entry checks, read it. A refusal on the saved listing stands; a candidate it would allow is judged again on a listing of its own, which replaces the saved one. A failed listing is never saved, and a missing or malformed file is read from the API. The pr-merge workflow sets the variable for its gate loop. Without it nothing changes. +- `babysit-prs` merge gate: in the pr-merge lane the verdict reader pages the repository's artifact listing once per run instead of once per candidate. When `BABYSIT_VERIFY_LISTING` names a file, the first candidate saves its listing there and later candidates, and their queued-entry checks, read it. No judgment, of a candidate or a queued entry, uses a listing (saved or in memory) begun more than two minutes before it; an older one is read again and saved. A refusal on the saved listing stands; a candidate it would allow is judged again on a listing of its own, which replaces the saved one. A failed listing is never saved, and a missing or malformed file is read from the API. The pr-merge workflow sets the variable for its gate loop. Without it nothing changes. diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index 614536a219a..112f07e30be 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -339,8 +339,9 @@ jobs: # alone, never a PR's. BABYSIT_VERIFY_GH_TOKEN: ${{ github.token }} # The first candidate saves its artifact listing here and the rest - # of the run reads it; a candidate the saved listing would allow - # lists again before it is allowed. + # of the run reads it while it is under two minutes old; a + # candidate the saved listing would allow lists again before it is + # allowed. BABYSIT_VERIFY_LISTING: ${{ runner.temp }}/verify-listing.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 e25384a0f23..a891972bc69 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -713,7 +713,8 @@ account with a dependency manager's login; a `User` named like one is judged) ne its queued entry is not held for one. pr-merge.yml runs the gate once per candidate and names a file in `BABYSIT_VERIFY_LISTING`: the first candidate lists every repository artifact and saves the listing there, and later candidates and their queued-entry checks read it instead of paging again. -A saved listing can only lack artifacts uploaded since, so a refusal on it stands; a candidate it +No judgment, of a candidate or a queued entry, uses a listing (saved or in memory) begun more than +two minutes before it: an older one is read again and saved. A saved listing can only lack artifacts uploaded since, so a refusal on it stands; a candidate it would allow is judged again on a listing of its own before it is allowed, which is saved in turn. A listing that got a 5xx or a fast network error is read again, three reads in all with backoff, all inside the one gh timeout a single 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 24702c1c354..56f5c722327 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 @@ -44,7 +44,9 @@ matches whole names only, and a FAIL counts under any number and head. pr-merge.yml builds one `Reader` per candidate gate run and names a file in `LISTING_ENV`: a successful listing is saved there, and later candidates of -the run read it instead of paging again. A listing taken earlier in the run +the run read it instead of paging again. No judgment uses a listing, saved +or in memory, begun more than `LISTING_MAX_AGE` before it: an older one is +read again and saved. A listing taken earlier in the run can only lack later uploads, so a refusal on it stands; before the gate's own candidate is allowed on it, babysit_merge.py calls `refresh()` and judges it again on a listing of its own. A listing that got a 5xx or a fast network @@ -88,6 +90,10 @@ COMMITS_CAP = 250 # The waits before the second and third listing reads (judgment). LISTING_WAITS = (2.0, 4.0) +# The oldest listing any judgment uses, saved or in memory. pr-verify is not a +# required check, so a queued entry whose FAIL lands mid-run must be held +# before the merge queue can land it (judgment). +LISTING_MAX_AGE = timedelta(minutes=2) # How gh reports a request that never got an HTTP response: its own # "error connecting to " for a failed lookup, else Go's net/http error. NETWORK_ERRORS = ( @@ -147,6 +153,18 @@ def _listing_clock() -> float: return time.monotonic() +def _wall_clock() -> datetime: + return datetime.now(UTC) + + +def _recent(fetched_at: datetime | None) -> bool: + """A listing begun at most `LISTING_MAX_AGE` ago; a time with no zone, or + one in the future, is not.""" + if fetched_at is None or fetched_at.tzinfo is None: + return False + return timedelta(0) <= _wall_clock() - fetched_at <= LISTING_MAX_AGE + + def dependency_bot(user: Any) -> bool: """A REST user that is a Bot account with a dependency manager's login; a User named like one is not. resolve-pr.mjs `isDependencyManager` is its @@ -217,6 +235,7 @@ class Reader: default_factory=lambda: os.environ.get(LISTING_ENV) or None ) _artifacts: list[dict[str, Any]] | None = None + _fetched_at: datetime | None = None # when `_artifacts` began to be read _saved: bool = False # `_artifacts` came from `listing_path` _own: bool = False # `refresh()` asked for a listing of this Reader's own _listing_error: str | None = None @@ -227,25 +246,30 @@ class Reader: _humans: frozenset[int] | None = None def _listing(self) -> list[dict[str, Any]]: - """Every repository artifact, read once (from the run's saved listing - when there is one): a failed read is kept too, so one outage refuses - each later entry without paging again.""" + """Every repository artifact, read at most `LISTING_MAX_AGE` before + this judgment (from the run's saved listing when it is that recent): a + failed read is kept too, so one outage refuses each later entry + without paging again.""" if self._listing_error is not None: raise _Unreadable(self._listing_error) - listing = self._artifacts - if listing is None: - listing = None if self._own else self._load_saved() - self._saved = listing is not None - if listing is None: - try: - listing = flatten_paginated_items( - self._read_listing(), "repository artifacts", items_key="artifacts" - ) - except (_Unreadable, RuntimeError) as exc: - self._listing_error = str(exc) - raise _Unreadable(self._listing_error) from exc - self._save(listing) - self._artifacts = listing + if self._artifacts is not None and _recent(self._fetched_at): + return self._artifacts + saved = None if self._own else self._load_saved() + if saved is not None: + self._fetched_at, self._artifacts = saved + self._saved = True + return self._artifacts + fetched_at = _wall_clock() + try: + listing = flatten_paginated_items( + self._read_listing(), "repository artifacts", items_key="artifacts" + ) + except (_Unreadable, RuntimeError) as exc: + self._listing_error = str(exc) + raise _Unreadable(self._listing_error) from exc + self._artifacts, self._fetched_at = listing, fetched_at + self._saved = self._own = False + self._save(listing, fetched_at) return listing @property @@ -259,27 +283,37 @@ def refresh(self) -> None: if self._saved: self._artifacts, self._saved, self._own = None, False, True - def _load_saved(self) -> list[dict[str, Any]] | None: - """The run's saved listing; a missing or malformed file is none, so - the listing is read from the API instead.""" + def _load_saved(self) -> tuple[datetime, list[dict[str, Any]]] | None: + """The run's saved listing and when it began to be read. A missing or + malformed file, or one with no `fetchedAt` within `LISTING_MAX_AGE`, + is none, so the listing is read from the API instead.""" if not self.listing_path: return None try: - listing = json.loads(Path(self.listing_path).read_text(encoding="utf-8")) - except (OSError, ValueError): + saved = json_object( + json.loads(Path(self.listing_path).read_text(encoding="utf-8")) + ) + fetched_at = datetime.fromisoformat(saved["fetchedAt"]) + except (OSError, ValueError, KeyError, TypeError): return None - if not is_json_array(listing) or not all(map(is_json_object, listing)): + listing = saved.get("artifacts") + if ( + not _recent(fetched_at) + or not is_json_array(listing) + or not all(map(is_json_object, listing)) + ): return None - return listing + return fetched_at, listing - def _save(self, listing: list[dict[str, Any]]) -> None: + def _save(self, listing: list[dict[str, Any]], fetched_at: datetime) -> None: """Best effort: a failed write leaves the next candidate to list.""" if not self.listing_path: return path = Path(self.listing_path) tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") + payload = {"fetchedAt": fetched_at.isoformat(), "artifacts": listing} with contextlib.suppress(OSError): - tmp.write_text(json.dumps(listing), encoding="utf-8") + tmp.write_text(json.dumps(payload), encoding="utf-8") os.replace(tmp, path) def _read_listing(self) -> Any: 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 90f8a54944a..9e16ebc6eff 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 @@ -27,7 +27,7 @@ import sys import tempfile import unittest -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from unittest import mock @@ -941,8 +941,68 @@ def test_a_failed_listing_is_not_saved(self) -> None: _, evidence = self.gate(fake) self.assertIsNone(evidence.refusal) + def hold(self, fake: FakeGitHub) -> str | None: + """A later candidate's gate run judging PR 41 as a queued entry.""" + with ( + mock.patch.object(policy, "pull_request", return_value=pull()), + mock.patch.object(postmerge, "gh_capture", side_effect=fake), + ): + return ve.Reader(REPO, "main", now=NOW).queued_hold(PR) + + def failed_since(self) -> FakeGitHub: + """The pass the saved listing holds, and a FAIL at the head since.""" + return passing(artifact(named(HEAD, "fail"), 2), runs={2: run(2)}) + + def test_a_saved_listing_without_its_time_is_not_used_for_a_hold(self) -> None: + pathlib.Path(self.path).write_text(json.dumps(passing().artifacts)) + fake = self.failed_since() + self.assertEqual(self.hold(fake), "verify:fail") + self.assertEqual(listings(fake), 1) + + def test_a_saved_listing_past_the_bound_is_not_used(self) -> None: + clock = [datetime(2026, 10, 16, 12, 0, tzinfo=UTC)] + with mock.patch.object(ve, "_wall_clock", side_effect=lambda: clock[0]): + self.gate(passing()) + clock[0] += ve.LISTING_MAX_AGE + timedelta(seconds=1) + fake = self.failed_since() + self.assertEqual(self.hold(fake), "verify:fail") + self.assertEqual(listings(fake), 1) + # The listing that hold read is saved and recent: the candidate + # after it reads it, and the FAIL refuses that candidate too. + _, evidence = self.gate(fake) + self.assertEqual(evidence.refusal, "verify:fail") + self.assertEqual(listings(fake), 1) + + def test_a_listing_in_memory_past_the_bound_is_read_again(self) -> None: + clock = [datetime(2026, 10, 16, 12, 0, tzinfo=UTC)] + fake = passing() + with ( + mock.patch.object(ve, "_wall_clock", side_effect=lambda: clock[0]), + mock.patch.object(policy, "pull_request", return_value=pull()), + mock.patch.object(postmerge, "gh_capture", side_effect=fake), + ): + reader = ve.Reader(REPO, "main", now=NOW) + self.assertIsNone(reader.evidence(PR, HEAD, pull()).refusal) + clock[0] += ve.LISTING_MAX_AGE + self.assertIsNone(reader.queued_hold(PR)) + self.assertEqual(listings(fake), 1) + fake.artifacts.append(artifact(named(HEAD, "fail"), 2)) + fake.runs[2] = run(2) + clock[0] += timedelta(seconds=1) + self.assertEqual(reader.queued_hold(PR), "verify:fail") + self.assertEqual(listings(fake), 2) + def test_a_malformed_saved_listing_is_read_from_the_api(self) -> None: - for text in ("not json", '{"artifacts": []}', "[1]"): + recent = datetime.now(UTC).isoformat() + for text in ( + "not json", + "[]", + '{"artifacts": []}', + json.dumps({"fetchedAt": "yesterday", "artifacts": []}), + json.dumps({"fetchedAt": "2026-10-16T12:00:00", "artifacts": []}), + json.dumps({"fetchedAt": recent, "artifacts": [1]}), + json.dumps({"fetchedAt": recent}), + ): with self.subTest(text): pathlib.Path(self.path).write_text(text) fake = passing() From 5fb4fd8b8afad97980461e631defbca332727a41 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:01:30 -0400 Subject: [PATCH 3/7] fix(source-control): relist the verify listing only for a candidate still unrefused score_unattended re-paged the artifact listing for every candidate the saved listing allowed, including one already refused by the policy or its risk score. Such a candidate is not enqueued, so a fresh listing decides nothing for it and costs about 31 requests on github.token. Refresh only while the candidate's reason is still None. Co-Authored-By: Claude Opus 5.5 --- .../skills/babysit-prs/scripts/babysit_merge.py | 5 +++-- .../scripts/tests/test_babysit_verify_evidence.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) 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 132ec2cc171..ace440c860f 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -2892,9 +2892,10 @@ def score_unattended( ): reader = verify_evidence.Reader(repo, str(inputs["branch"])) verdict = reader.evidence(number, str(details["headSha"]), pr) - if verdict.refusal is None and reader.saved: + if verdict.refusal is None and reason is None and reader.saved: # The run's saved listing lacks anything uploaded since; allow - # only on a listing of this gate run's own. + # only on a listing of this gate run's own. A candidate refused + # already is not enqueued, so it does not page the listing again. reader.refresh() verdict = reader.evidence(number, str(details["headSha"]), pr) details["verify"] = verdict.report() 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 9e16ebc6eff..5202a932b7b 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 @@ -1376,6 +1376,17 @@ def test_an_allow_on_the_saved_listing_is_judged_again_on_its_own(self) -> None: refresh.assert_called_once_with() self.assertEqual(self.read.call_count, 2) + def test_a_candidate_refused_otherwise_does_not_list_again(self) -> None: + # Already refused, it is not enqueued: an allow on the saved listing + # decides nothing, so it pages nothing. + refresh = self.saved_listing() + self.lanes = unattended.UNBOUND + code, out = self.lane() + self.assert_no_merge(code) + self.assertTrue(out["unattended"]["reason"].startswith("risk:")) + refresh.assert_not_called() + self.read.assert_called_once_with(unattended.PR, unattended.HEAD) + def test_a_refusal_on_the_saved_listing_stands_without_a_listing(self) -> None: refresh = self.saved_listing() self.verdicts[unattended.PR] = evidence("verify:missing") From db667f4dacc365a009fb7ab79622f9fdd436bde1 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:14:02 -0400 Subject: [PATCH 4/7] perf(source-control): run pr-merge's per-run reads once, not per candidate pr-merge.yml starts babysit_merge.py once per candidate, so reads that are the same for every candidate ran up to 27 times a run. A new per-run file, named in BABYSIT_RUN_CACHE (babysit_run_cache.py, atomic replace), lets the gate processes share them: - Merge-queue sweep: a queued entry another candidate judged and kept is skipped while the reads behind that judgment, its verdict listing included, began at most two minutes ago (the #7954 bound). A gate always judges its own entry; a held entry is judged by every candidate; a failed dequeue keeps nothing; the stop path is unchanged. - Acting login and the gh auth status pass: reused only under the same credentials (a digest of gh's token variables and hosts.yml); a refusal is read again. - Collaborator permissions and the trusted-actor list: reused for two minutes; a failed read is never shared. - Verifier compares of a run head to main: moved to the job's GITHUB_TOKEN (contents: read) and shared for the run when the head is on main (main's ruleset forbids force pushes); a head not found is compared again. Without the variable nothing is shared and behavior is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../perf-pr-merge-once-per-run-3b7d91e4.md | 7 ++ .github/workflows/pr-merge.yml | 5 + docs/conventions/pr-pipeline/README.md | 14 ++- .../babysit-prs/scripts/babysit_merge.py | 65 ++++++++--- .../scripts/babysit_merge_policy.py | 36 +++++- .../babysit-prs/scripts/babysit_run_cache.py | 106 ++++++++++++++++++ .../scripts/babysit_verify_evidence.py | 34 +++++- .../tests/test_babysit_merge_policy.py | 90 +++++++++++++++ .../tests/test_babysit_merge_unattended.py | 69 +++++++++++- .../tests/test_babysit_verify_evidence.py | 100 ++++++++++++++++- 10 files changed, 493 insertions(+), 33 deletions(-) create mode 100644 .changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md create mode 100644 plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py diff --git a/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md b/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md new file mode 100644 index 00000000000..1228850e3e0 --- /dev/null +++ b/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md @@ -0,0 +1,7 @@ +--- +bump: patch +--- + +### Changed + +- `babysit-prs` merge gate: in the pr-merge lane, reads that are the same for every candidate are shared by the run's gate processes through the file `BABYSIT_RUN_CACHE` names, instead of being repeated per candidate. The acting login and a credential pass are reused only under the same credentials; a credential refusal is read again. A collaborator permission and the trusted-actor list are reused for two minutes, and a failed read is never shared. A run head found on main is shared for the run; one not found is compared again. The merge-queue sweep skips a queued entry another candidate judged and kept only while the reads behind that judgment, its verdict listing included, began at most two minutes ago; a gate always judges its own entry, and a held entry or a failed dequeue keeps nothing. The verdict reader's compares of a run head to main now use the job's `GITHUB_TOKEN`, off the lane App's quota. Without the variable nothing changes. diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index 112f07e30be..0ca213b07e5 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -343,6 +343,11 @@ jobs: # candidate the saved listing would allow lists again before it is # 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). + BABYSIT_RUN_CACHE: ${{ runner.temp }}/babysit-run-cache.json REPO: ${{ github.repository }} OWNER: ${{ github.repository_owner }} SCRIPT: ${{ steps.config.outputs.script }} diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index a891972bc69..f77016c778d 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -723,8 +723,18 @@ saved, and is kept for that candidate's gate run: the pull request and every que listing being paged again, so a listing outage holds the whole queue rather than merging blind. The lane token holds no Actions permission, so pr-merge.yml grants its job `actions: read` and passes the job's `GITHUB_TOKEN` as `BABYSIT_VERIFY_GH_TOKEN`; the reader uses it as `GH_TOKEN` for the artifact listing, the run -records and the download alone, and every other call keeps the lane token. That job checks out only -main and runs no pull request code. +records, the download and the compare of a run's head to main (a `contents: read` call) alone, and +every other call keeps the lane token. That job checks out only main and runs no pull request code. + +pr-merge.yml also names a file in `BABYSIT_RUN_CACHE`, where the run's gate processes share reads +that are the same for every candidate. The acting login and a credential pass are reused only under +the same credentials (`gh`'s token variables and `hosts.yml`); a credential refusal is read again. A +collaborator permission and the trusted-actor list are reused for two minutes, and a failed read is +never shared. A run head found on main is shared for the run, since main's ruleset forbids force +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 reads behind that judgment, its verdict listing included, +began 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. ## 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 ace440c860f..ac047220716 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -141,6 +141,7 @@ import babysit_postmerge as postmerge import babysit_review_evidence as review_evidence import babysit_risk +import babysit_run_cache as run_cache import babysit_verify_evidence as verify_evidence import babysit_repo_config as repo_policy from babysit_state import resolve_state_dir, state_lock, write_state @@ -2634,6 +2635,8 @@ def queued_entry_hold( "rung-off:", merge_policy.DEFAULT_BRANCH_UNREADABLE, ) +# The run-cache section of queued entries a gate process judged and kept. +SWEEP = "queue-sweep" UNATTENDED_QUEUE_QUERY = ( "query($o:String!,$r:String!,$b:String!){repository(owner:$o,name:$r){" "mergeQueue(branch:$b){entries(first:100){totalCount nodes{enqueuedAt position " @@ -3081,6 +3084,25 @@ def _queued_verify_hold(verifier: verify_evidence.Reader, number: int) -> str | return verify_evidence.UNREADABLE +def _sweep_key(repo: str, branch: str, identity: str, number: int) -> str: + return f"{repo}|{branch}|{identity.casefold()}|{number}" + + +def _kept_recently(repo: str, branch: str, identity: str, number: int) -> bool: + """Whether a gate process of this run kept the queued entry on reads, its + verdict listing included, begun at most `run_cache.MAX_AGE` ago: the + bound every judgment of an entry already keeps.""" + stamp = run_cache.get(SWEEP, _sweep_key(repo, branch, identity, number), None) + try: + at = datetime.fromisoformat(stamp) + except (TypeError, ValueError): + return False + return ( + at.tzinfo is not None + and timedelta(0) <= run_cache.now() - at <= run_cache.MAX_AGE + ) + + def unattended_writes( repo: str, number: int, policy: merge_policy.UnattendedPolicy ) -> dict[str, Any]: @@ -3116,23 +3138,31 @@ def unattended_writes( and config.require_verifier_verdict else None ) + # When each kept entry's reads began (`_kept_recently`). + kept_at: dict[int, datetime] = {} + + def judge(n: int) -> str | None: + began = run_cache.now() + hold = merge_policy.entry_hold( + repo, + n, + identity, + self_logins=inputs.get("self_logins") or frozenset(), + permission=inputs.get("permission"), + ) or ( + _queued_verify_hold(verifier, n) + if verifier is not None and n != number + else None + ) + listed = verifier.listed_at if verifier is not None else None + kept_at[n] = min(began, listed) if listed else began + return hold + report["holds"] = { n: hold for n in queued - if ( - hold := merge_policy.entry_hold( - repo, - n, - identity, - self_logins=inputs.get("self_logins") or frozenset(), - permission=inputs.get("permission"), - ) - or ( - _queued_verify_hold(verifier, n) - if verifier is not None and n != number - else None - ) - ) + if (n == number or not _kept_recently(repo, branch, identity, n)) + and (hold := judge(n)) } # This run's own read of a queued entry also counts: the pull # request it just found ineligible, above the rung, unpromoted @@ -3154,6 +3184,13 @@ def unattended_writes( report["errors"].append( f"{unknown} queue entries have an unknown enqueuer" ) + # Only an entry this process judged and kept, never its own (which + # its gate judges in full) or one it skipped. + for n, at in kept_at.items() if numbers is not None else (): + if n != number and n not in numbers: + run_cache.put( + SWEEP, _sweep_key(repo, branch, identity, n), at.isoformat() + ) except (postmerge.PostMergeReadError, postmerge.PostMergeWriteError) as exc: report["errors"].append(f"dequeue: {exc}") # A stopped path (demoted, capped off, switched off) merges nothing, so a 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 c7cf037f5b9..09b26540d03 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 @@ -41,6 +41,7 @@ import babysit_dependabot as dependabot import babysit_repo_config as repo_config +import babysit_run_cache as run_cache from babysit_classify import ( actor_kind, has_blocking_severity, @@ -750,12 +751,19 @@ def rung_cap(repo: str, *, authority: str, lane_value: str | None = None) -> Run def permission_reader(repo: str) -> Permission: - """A cached reader of a login's repository permission (`admin`, `write`, ...).""" + """A cached reader of a login's repository permission (`admin`, `write`, ...). + A permission read in the last `run_cache.MAX_AGE` by another gate process + of the run is reused; a failed read is never shared.""" owner, name = _split_repo(repo) cache: dict[str, str | None] = {} def read(login: str) -> str | None: if login not in cache: + key = f"{owner}/{name}|{login.casefold()}" + shared = run_cache.get("permission", key, run_cache.MAX_AGE) + if isinstance(shared, str): + cache[login] = shared + return shared status, payload = _get( f"repos/{owner}/{name}/collaborators/{login}/permission" ) @@ -765,6 +773,8 @@ def read(login: str) -> str | None: else None ) cache[login] = value if isinstance(value, str) else None + if isinstance(value, str): + run_cache.put("permission", key, value) return cache[login] return read @@ -2768,16 +2778,30 @@ def assess( ) if enabled_authority(config) != authority: return stopped + # The acting login and the credential chokepoint depend on the + # credentials alone: a gate process of the same run with the same ones + # reuses a login read and a pass (`run_cache.credentials`). + held = run_cache.credentials() if acting_login is None: - try: - acting_login = read_acting_login() - except PolicyReadError: - acting_login = None + acting_login = run_cache.get("acting-login", held, None) + if not isinstance(acting_login, str): + try: + acting_login = read_acting_login() + run_cache.put("acting-login", held, acting_login) + except PolicyReadError: + acting_login = None resolved = resolve_identity(identity, acting_login, self_logins) details["identity"] = resolved.login if resolved.reason or resolved.login is None: return replace(stopped, reason=resolved.reason) - credentials = credential_refusal(resolved.login) + passed = f"{held}|{resolved.login.casefold()}" + credentials = ( + None + if run_cache.get("identity-only", passed, None) is True + else credential_refusal(resolved.login) + ) + if credentials is None: + run_cache.put("identity-only", passed, True) details["credentials"] = credentials or "identity-only" if credentials: return replace(stopped, reason=f"credentials:{credentials}") diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py new file mode 100644 index 00000000000..0e7dc85717f --- /dev/null +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py @@ -0,0 +1,106 @@ +"""Reads one pr-merge run shares across its gate processes. + +pr-merge.yml runs babysit_merge.py once per candidate and names a file in +`ENV`. A reader looks a value up here before asking GitHub and saves what it +read; with no file named, nothing is shared and every read happens as before. +A caller passes the oldest value it accepts (`MAX_AGE` for anything that can +change during a run, None for a value that cannot). A missing, malformed or +unwritable file, or an entry too old or dated in the future, is a miss, so +the reader asks GitHub: the file never refuses or allows anything itself. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +ENV = "BABYSIT_RUN_CACHE" +# The oldest shared value that can change during a run, and the oldest +# artifact listing the verdict reader judges on (judgment): pr-verify is not a +# required check, so a queued entry whose FAIL lands mid-run must be held +# before the merge queue can land it. +MAX_AGE = timedelta(minutes=2) +# What gh reads its credentials from: these variables and hosts.yml. +CREDENTIAL_ENV = ( + "GH_TOKEN", + "GITHUB_TOKEN", + "GH_ENTERPRISE_TOKEN", + "GITHUB_ENTERPRISE_TOKEN", + "GH_HOST", + "GH_CONFIG_DIR", +) + + +def now() -> datetime: + return datetime.now(UTC) + + +def _path() -> Path | None: + name = os.environ.get(ENV) + return Path(name) if name else None + + +def _load(path: Path) -> dict[str, Any]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def get(section: str, key: str, max_age: timedelta | None) -> Any: + """The value saved under `section` and `key` at most `max_age` ago (None: + any time this run), or None.""" + path = _path() + if path is None: + return None + entry = _load(path).get(section, {}) + entry = entry.get(key) if isinstance(entry, dict) else None + if not isinstance(entry, dict): + return None + try: + at = datetime.fromisoformat(entry["at"]) + except (KeyError, TypeError, ValueError): + return None + if at.tzinfo is None: + return None + age = now() - at + if age < timedelta(0) or (max_age is not None and age > max_age): + return None + return entry.get("value") + + +def put(section: str, key: str, value: Any) -> None: + """Save `value`, replacing the file whole. Best effort: a failed write + leaves the next process to read GitHub.""" + path = _path() + if path is None: + return + data = _load(path) + entries = data.get(section) + if not isinstance(entries, dict): + entries = data[section] = {} + entries[key] = {"at": now().isoformat(), "value": value} + tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") + with contextlib.suppress(OSError): + tmp.write_text(json.dumps(data), encoding="utf-8") + os.replace(tmp, path) + + +def credentials() -> str: + """A digest of everything gh reads its credentials from, so a value read + with one set of credentials is never reused under another.""" + digest = hashlib.sha256() + for name in CREDENTIAL_ENV: + digest.update(f"{name}={os.environ.get(name, '')}\0".encode()) + config = os.environ.get("GH_CONFIG_DIR") or str( + Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "gh" + ) + with contextlib.suppress(OSError): + digest.update(Path(config, "hosts.yml").read_bytes()) + return digest.hexdigest() 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 56f5c722327..3bc59adfdfa 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 @@ -72,6 +72,7 @@ import babysit_merge_policy as merge_policy import babysit_postmerge as postmerge +import babysit_run_cache as run_cache from babysit_classify import is_dependency_author from babysit_gh import flatten_paginated_items, gh_http_status, gh_timeout_seconds from babysit_util import is_json_array, is_json_object, json_array, json_object @@ -90,10 +91,8 @@ COMMITS_CAP = 250 # The waits before the second and third listing reads (judgment). LISTING_WAITS = (2.0, 4.0) -# The oldest listing any judgment uses, saved or in memory. pr-verify is not a -# required check, so a queued entry whose FAIL lands mid-run must be held -# before the merge queue can land it (judgment). -LISTING_MAX_AGE = timedelta(minutes=2) +# The oldest listing any judgment uses, saved or in memory (see the bound). +LISTING_MAX_AGE = run_cache.MAX_AGE # How gh reports a request that never got an HTTP response: its own # "error connecting to " for a failed lookup, else Go's net/http error. NETWORK_ERRORS = ( @@ -225,7 +224,7 @@ class Reader: branch: str now: datetime | None = None # The token for the Actions reads (artifact listing, run records, - # download): pr-merge.yml passes the job's GITHUB_TOKEN, which holds + # download) and the run heads' compares: pr-merge.yml passes the job's GITHUB_TOKEN, which holds # `actions: read`, while the lane token it runs gh with holds none. actions_token: str | None = field( default_factory=lambda: os.environ.get(TOKEN_ENV) or None @@ -272,6 +271,11 @@ def _listing(self) -> list[dict[str, Any]]: self._save(listing, fetched_at) return listing + @property + def listed_at(self) -> datetime | None: + """When the listing last judged on began to be read.""" + return self._fetched_at + @property def saved(self) -> bool: """Whether the listing judged on was read from `listing_path`.""" @@ -366,14 +370,24 @@ def _actions( raise _Unreadable(f"{label}: {exc}") from exc def _contains(self, sha: str) -> bool: + """Whether the branch holds `sha`, read under the Actions token (a + contents read). A yes stays true while the branch only moves forward + (main's ruleset forbids force pushes), so the run shares it; a no is + read again by each gate process.""" if sha not in self._on_branch: + key = f"{self.repo}|{sha}...{self.branch}" + if run_cache.get("on-branch", key, None) is True: + self._on_branch[sha] = True + return True compare = json_object( - _read( + self._actions( ["api", f"repos/{self.repo}/compare/{sha}...{self.branch}"], f"compare {sha[:12]}...{self.branch}", ) ) self._on_branch[sha] = compare.get("status") in ("ahead", "identical") + if self._on_branch[sha]: + run_cache.put("on-branch", key, True) return self._on_branch[sha] def _run_state(self, run_id: int) -> str: @@ -436,6 +450,13 @@ def _record(self, run_id: int, name: str) -> dict[str, Any]: return self._records[key] def _trusted_humans(self) -> frozenset[int]: + """The trusted list's human ids at the branch, shared by the run's + gate processes for `run_cache.MAX_AGE`.""" + key = f"{self.repo}@{self.branch}" + if self._humans is None: + shared = run_cache.get("trusted-humans", key, run_cache.MAX_AGE) + if is_json_array(shared): + self._humans = frozenset(i for i in shared if type(i) is int) humans = self._humans if humans is None: listing = json_object( @@ -458,6 +479,7 @@ def _trusted_humans(self) -> frozenset[int]: if a.get("kind") == "human" and isinstance(a.get("id"), int) ) self._humans = humans + run_cache.put("trusted-humans", key, sorted(humans)) return humans def _trusted_actor(self, kind: Any, actor_id: Any, login: Any, author: str) -> bool: 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 5ffbdd536fb..d06780f0df2 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 @@ -21,6 +21,7 @@ import sys import tempfile import unittest +from datetime import UTC, datetime, timedelta from typing import Any from unittest import mock @@ -3856,5 +3857,94 @@ def test_the_rung_still_binds_the_class(self) -> None: self.assertEqual(result.reason, "rung-off:rungCap") +class OneRunSharesItsCredentialReads(unittest.TestCase): + """pr-merge.yml runs one gate process per candidate and names a file in + `BABYSIT_RUN_CACHE`: the acting login, a credential pass and permissions + are read once for the run, never across other credentials, and a refusal + or failed read is never shared.""" + + fake = Assess.fake + readable = Assess.readable + all_clear = Assess.all_clear + + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + env = {"BABYSIT_RUN_CACHE": str(pathlib.Path(tmp.name, "run.json"))} + patcher = mock.patch.dict("os.environ", {**env, "GH_TOKEN": "lane"}) + patcher.start() + self.addCleanup(patcher.stop) + + def gh(self) -> GhFake: + gh = self.readable() + gh.graphql["PolicyViewer"] = {"viewer": {"login": IDENTITY}} + self.all_clear() + return gh + + def candidate(self) -> policy.UnattendedPolicy: + """One candidate's gate process, with nothing passed in.""" + return policy.assess( + REPO, 1, post_merge=lambda floor, who: gate(), promotion=lambda s: PROMOTED + ) + + def reads(self, gh: GhFake) -> tuple[int, int]: + viewer = sum("query PolicyViewer" in " ".join(c) for c in gh.calls) + return viewer, gh.calls.count(["auth", "status", "--json", "hosts"]) + + def test_candidates_of_one_run_read_them_once(self) -> None: + gh = self.gh() + for _ in range(3): + self.assertIsNone(self.candidate().reason) + self.assertEqual(self.reads(gh), (1, 1)) + + def test_other_credentials_read_them_again(self) -> None: + gh = self.gh() + self.candidate() + with mock.patch.dict("os.environ", {"GH_TOKEN": "another"}): + self.candidate() + self.assertEqual(self.reads(gh), (2, 2)) + + def test_a_credential_refusal_is_read_again(self) -> None: + gh = self.gh() + gh.rest["status"] = { + "hosts": { + "github.com": [ + *IDENTITY_ONLY["hosts"]["github.com"], + {"login": OPERATOR, "active": False, "host": "github.com"}, + ] + } + } + for _ in range(2): + self.assertEqual( + self.candidate().reason, "credentials:other-account-listed" + ) + self.assertEqual(self.reads(gh)[1], 2) + + def permission_reads(self, answer: Any, readers: int = 2) -> int: + gh = GhFake().install(self) + endpoint = f"repos/{REPO}/collaborators/{OPERATOR}/permission" + gh.rest[endpoint] = answer + for _ in range(readers): + policy.permission_reader(REPO)(OPERATOR) + return gh.calls.count(["api", endpoint]) + + def test_a_permission_is_read_once_per_run(self) -> None: + self.assertEqual(self.permission_reads({"permission": "admin"}, 3), 1) + + def test_a_failed_permission_read_is_not_shared(self) -> None: + self.assertEqual(self.permission_reads(404), 2) + + def test_a_permission_past_the_bound_is_read_again(self) -> None: + clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] + with mock.patch.object(policy.run_cache, "now", side_effect=lambda: clock[0]): + gh = GhFake().install(self) + endpoint = f"repos/{REPO}/collaborators/{OPERATOR}/permission" + gh.rest[endpoint] = {"permission": "admin"} + policy.permission_reader(REPO)(OPERATOR) + clock[0] += policy.run_cache.MAX_AGE + timedelta(seconds=1) + policy.permission_reader(REPO)(OPERATOR) + self.assertEqual(gh.calls.count(["api", endpoint]), 2) + + if __name__ == "__main__": unittest.main() 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 1f1ce9b3a1f..85439c5c391 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 @@ -23,7 +23,7 @@ import sys import tempfile import unittest -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from unittest import mock @@ -335,6 +335,9 @@ def setUp(self) -> None: self.entries = [entry(PR, "2026-10-12T10:00:00Z", "PR_self")] self.queued: list[int] = [] self.holds: dict[int, str] = {} + # Every queued entry the sweep judged, in order. + self.hold_reads: list[int] = [] + self.dequeue_error: Exception | None = None self.prior: dict[str, Any] | None = None self.log: list[str] = [] self.rules = QUEUE_RULES @@ -506,7 +509,9 @@ def gh_json(args: list[str]) -> Any: mock.patch.object( policy, "entry_hold", - side_effect=lambda r, n, i, **_: self.holds.get(n), + side_effect=lambda r, n, i, **_: ( + self.hold_reads.append(n) or self.holds.get(n) + ), ), mock.patch.object(merge, "_lane_evidence", side_effect=self._lane_evidence), mock.patch.object( @@ -573,6 +578,8 @@ def _async_merge(self, repo: str, number: int, **kwargs: Any) -> dict[str, Any]: def _dequeue(self, repo: str, branch: str, identity: str, **kwargs: Any) -> int: numbers = kwargs.get("numbers") self.log.append(f"dequeue:{sorted(numbers) if numbers is not None else 'all'}") + if self.dequeue_error is not None: + raise self.dequeue_error return 0 def assert_no_merge(self, code: int) -> None: @@ -1313,6 +1320,64 @@ def test_a_non_default_base_still_holds_the_identitys_entries(self) -> None: self.assertEqual(self.log, ["dequeue:[5]"]) +class TheQueueSweepIsSharedPerRun(Unattended): + """pr-merge.yml runs one gate process per candidate and names a file in + `BABYSIT_RUN_CACHE`: another queued entry one process judged and kept is + not judged again by the next within the bound, and nothing else is + shared. Each `run_main` here is one candidate's gate process.""" + + def setUp(self) -> None: + super().setUp() + 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) + self.flight = policy.InFlight(False, "identity-entry-queued:#5") + self.queued = [PR, 5] + + def candidates(self, count: int) -> None: + for _ in range(count): + code, _ = self.run_main() + self.assert_no_merge(code) + + def test_a_kept_entry_is_judged_once_across_candidates(self) -> None: + self.candidates(3) + self.assertEqual(self.hold_reads.count(5), 1) + # A gate always judges its own entry. + self.assertEqual(self.hold_reads.count(PR), 3) + self.assertEqual(self.log, []) + + def test_a_kept_entry_is_judged_again_past_the_bound(self) -> None: + clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] + with mock.patch("babysit_run_cache.now", side_effect=lambda: clock[0]): + self.candidates(1) + clock[0] += merge.run_cache.MAX_AGE + self.candidates(1) + clock[0] += timedelta(seconds=1) + self.candidates(1) + self.assertEqual(self.hold_reads.count(5), 2) + + def test_a_held_entry_is_judged_by_every_candidate(self) -> None: + self.holds = {5: "do-not-merge"} + self.candidates(2) + self.assertEqual(self.hold_reads.count(5), 2) + self.assertEqual(self.log, ["dequeue:[5]", "dequeue:[5]"]) + + def test_a_failed_dequeue_keeps_nothing(self) -> None: + self.queued = [PR, 5, 6] + self.holds = {6: "do-not-merge"} + self.dequeue_error = postmerge.PostMergeWriteError("dequeue #6: boom") + self.candidates(2) + self.assertEqual(self.hold_reads.count(5), 2) + + def test_without_the_file_every_candidate_judges_every_entry(self) -> None: + with mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": ""}): + self.candidates(2) + self.assertEqual(self.hold_reads.count(5), 2) + + class GateReviewFixes(Unattended): """Phase 13 Fable gate findings, red first.""" 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 5202a932b7b..cc1ae533f15 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 @@ -826,10 +826,12 @@ def test_anyone_elses_entry_is_judged(self) -> None: class ActionsReadsUseTheActionsToken(unittest.TestCase): """The lane token holds no Actions permission, so the artifact listing, - the run records and the download run under `BABYSIT_VERIFY_GH_TOKEN`; - every other read keeps the process token.""" + the run records and the download run under `BABYSIT_VERIFY_GH_TOKEN`, as + do the run heads' compares to the branch (a contents read the job token + serves, kept off the lane App's quota); every other read keeps the + process token.""" - ACTIONS = ("actions/artifacts", "actions/runs/", "run download") + ACTIONS = ("actions/artifacts", "actions/runs/", "run download", "/compare/") def reads(self, reader: ve.Reader) -> dict[str, Any]: fake = passing() @@ -1012,6 +1014,53 @@ def test_a_malformed_saved_listing_is_read_from_the_api(self) -> None: self.assertEqual(listings(fake), 1) +class OneRunSharesItsVerifierReads(unittest.TestCase): + """With `BABYSIT_RUN_CACHE` named, the gate processes of one run share a + run head found on the branch and the trusted-actor list (for its bound); + a head not found on the branch is compared again.""" + + 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) + + @staticmethod + def compares(fake: FakeGitHub, sha: str) -> int: + return sum(f"/compare/{sha}..." in " ".join(c) for c in fake.calls) + + @staticmethod + def trusted_reads(fake: FakeGitHub) -> int: + return sum(any("/contents/" in a for a in c) for c in fake.calls) + + def candidates(self, fake: FakeGitHub, count: int) -> None: + for _ in range(count): + self.assertIsNone(read(fake).refusal) + + def test_a_head_on_the_branch_is_compared_once_per_run(self) -> None: + fake = passing() + self.candidates(fake, 3) + self.assertEqual(self.compares(fake, MAIN_SHA), 1) + + def test_a_head_off_the_branch_is_compared_by_every_candidate(self) -> None: + off = "d" * 40 + fake = passing(artifact(named(HEAD, "fail"), 2), runs={2: run(2, head_sha=off)}) + self.candidates(fake, 2) + self.assertEqual(self.compares(fake, off), 2) + + def test_the_trusted_list_is_read_once_within_the_bound(self) -> None: + clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] + fake = passing() + with mock.patch.object(ve.run_cache, "now", side_effect=lambda: clock[0]): + self.candidates(fake, 2) + self.assertEqual(self.trusted_reads(fake), 1) + clock[0] += ve.run_cache.MAX_AGE + timedelta(seconds=1) + self.candidates(fake, 1) + self.assertEqual(self.trusted_reads(fake), 2) + + # --- A transient listing failure is read again -------------------------------- # Every test runs without the backoff sleep; `judge` reads the waits off it. @@ -1614,5 +1663,50 @@ def test_any_other_value_requires_a_verdict(self) -> None: self.assertTrue(any("require-verifier-verdict" in n for n in config.notes)) +class TheSweepKeepsTheListingBound(unattended.Unattended): + """A queued entry another candidate kept is skipped only while the + listing its verdict was judged on is within the bound.""" + + def setUp(self) -> None: + super().setUp() + self.config = policy.PipelineConfig( + unattended.BASE, "C2", "pr-merge", unattended.IDENTITY, 200, + (".github/**",), "c2-mechanical", require_verifier_verdict=True, + ) # fmt: skip + self.opt_in_recheck = "not-lane-authored-or-opted-in" + self.promotion = policy.Promotion(None, "resolver-failed") + self.kill = [] + self.flight = policy.InFlight(False, "identity-entry-queued:#5") + self.queued = [unattended.PR, 5] + self.clock = datetime(2026, 10, 18, 12, 0, tzinfo=UTC) + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + path = str(pathlib.Path(tmp.name, "run.json")) + self.reads: list[int] = [] + listed = self.clock - timedelta(seconds=90) + for patcher in ( + mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}), + mock.patch.object(ve.run_cache, "now", side_effect=lambda: self.clock), + mock.patch.object(ve.Reader, "listed_at", new=listed), + mock.patch.object( + ve.Reader, + "evidence", + side_effect=lambda n, head, pr=None: ( + self.reads.append(n) or evidence(None) + ), + ), + ): + patcher.start() + self.addCleanup(patcher.stop) + + def test_the_skip_ends_when_the_judged_listing_passes_the_bound(self) -> None: + for seconds in (0, 29, 31): + self.clock = datetime(2026, 10, 18, 12, 0, seconds, tzinfo=UTC) + code, _ = unattended.LaneMode.lane(self) + self.assert_no_merge(code) + # Judged at 12:00:00 on a listing from 11:58:30: skipped at :29, not :31. + self.assertEqual(self.reads.count(5), 2) + + if __name__ == "__main__": unittest.main() From a0bf1886669fd8294c07fd2bbae678a337880840 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:24:12 -0400 Subject: [PATCH 5/7] fix(source-control): date a kept queue entry by its oldest shared read The sweep recorded a kept entry at the time its judgment began, but the judgment can use a permission or trusted list another gate process shared up to two minutes earlier, so a skip could rest on reads about four minutes old. babysit_run_cache now has track() and note(): the permission reader, the trusted-list reader and the verdict listing note when each answer was read, and the sweep records the oldest of those as the entry's kept time. The skip bound now covers the judgment's oldest input. Co-Authored-By: Claude Opus 5.5 --- .../perf-pr-merge-once-per-run-3b7d91e4.md | 2 +- docs/conventions/pr-pipeline/README.md | 4 +- .../babysit-prs/scripts/babysit_merge.py | 37 +++++++++-------- .../scripts/babysit_merge_policy.py | 38 +++++++++-------- .../babysit-prs/scripts/babysit_run_cache.py | 41 ++++++++++++++++--- .../scripts/babysit_verify_evidence.py | 29 ++++++++----- .../tests/test_babysit_merge_unattended.py | 32 +++++++++++++-- .../tests/test_babysit_verify_evidence.py | 21 +++++++++- 8 files changed, 147 insertions(+), 57 deletions(-) diff --git a/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md b/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md index 1228850e3e0..7400c731ef2 100644 --- a/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md +++ b/.changes/source-control/perf-pr-merge-once-per-run-3b7d91e4.md @@ -4,4 +4,4 @@ bump: patch ### Changed -- `babysit-prs` merge gate: in the pr-merge lane, reads that are the same for every candidate are shared by the run's gate processes through the file `BABYSIT_RUN_CACHE` names, instead of being repeated per candidate. The acting login and a credential pass are reused only under the same credentials; a credential refusal is read again. A collaborator permission and the trusted-actor list are reused for two minutes, and a failed read is never shared. A run head found on main is shared for the run; one not found is compared again. The merge-queue sweep skips a queued entry another candidate judged and kept only while the reads behind that judgment, its verdict listing included, began at most two minutes ago; a gate always judges its own entry, and a held entry or a failed dequeue keeps nothing. The verdict reader's compares of a run head to main now use the job's `GITHUB_TOKEN`, off the lane App's quota. Without the variable nothing changes. +- `babysit-prs` merge gate: in the pr-merge lane, reads that are the same for every candidate are shared by the run's gate processes through the file `BABYSIT_RUN_CACHE` names, instead of being repeated per candidate. The acting login and a credential pass are reused only under the same credentials; a credential refusal is read again. A collaborator permission and the trusted-actor list are reused for two minutes, and a failed read is never shared. A run head found on main is shared for the run; one not found is compared again. The merge-queue sweep skips a queued entry another candidate judged and kept 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, and a held entry or a failed dequeue keeps nothing. The verdict reader's compares of a run head to main now use the job's `GITHUB_TOKEN`, off the lane App's quota. Without the variable nothing changes. diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index f77016c778d..b5e0f4c25ad 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -732,8 +732,8 @@ the same credentials (`gh`'s token variables and `hosts.yml`); a credential refu collaborator permission and the trusted-actor list are reused for two minutes, and a failed read is never shared. A run head found on main is shared for the run, since main's ruleset forbids force 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 reads behind that judgment, its verdict listing included, -began at most two minutes ago; a gate always judges its own entry, a held entry is judged by every +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. ## 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 ac047220716..7572dd42ebe 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -3089,9 +3089,10 @@ def _sweep_key(repo: str, branch: str, identity: str, number: int) -> str: def _kept_recently(repo: str, branch: str, identity: str, number: int) -> bool: - """Whether a gate process of this run kept the queued entry on reads, its - verdict listing included, begun at most `run_cache.MAX_AGE` ago: the - bound every judgment of an entry already keeps.""" + """Whether a gate process of this run kept the queued entry on reads + taken at most `run_cache.MAX_AGE` ago, dated by its oldest input (a + shared permission, trusted list or verdict listing included): the bound + every judgment of an entry already keeps.""" stamp = run_cache.get(SWEEP, _sweep_key(repo, branch, identity, number), None) try: at = datetime.fromisoformat(stamp) @@ -3142,20 +3143,22 @@ def unattended_writes( kept_at: dict[int, datetime] = {} def judge(n: int) -> str | None: - began = run_cache.now() - hold = merge_policy.entry_hold( - repo, - n, - identity, - self_logins=inputs.get("self_logins") or frozenset(), - permission=inputs.get("permission"), - ) or ( - _queued_verify_hold(verifier, n) - if verifier is not None and n != number - else None - ) - listed = verifier.listed_at if verifier is not None else None - kept_at[n] = min(began, listed) if listed else began + # Dated by its oldest input: a shared permission, trusted + # list or verdict listing may predate the judgment. + with run_cache.track() as taken: + began = run_cache.now() + hold = merge_policy.entry_hold( + repo, + n, + identity, + self_logins=inputs.get("self_logins") or frozenset(), + permission=inputs.get("permission"), + ) or ( + _queued_verify_hold(verifier, n) + if verifier is not None and n != number + else None + ) + kept_at[n] = min([began, *taken]) return hold report["holds"] = { 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 09b26540d03..db3e12367cd 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 @@ -753,29 +753,33 @@ def rung_cap(repo: str, *, authority: str, lane_value: str | None = None) -> Run def permission_reader(repo: str) -> Permission: """A cached reader of a login's repository permission (`admin`, `write`, ...). A permission read in the last `run_cache.MAX_AGE` by another gate process - of the run is reused; a failed read is never shared.""" + of the run is reused; a failed read is never shared. Each answer notes + when it was read (`run_cache.note`).""" owner, name = _split_repo(repo) - cache: dict[str, str | None] = {} + cache: dict[str, tuple[str | None, datetime]] = {} def read(login: str) -> str | None: if login not in cache: key = f"{owner}/{name}|{login.casefold()}" - shared = run_cache.get("permission", key, run_cache.MAX_AGE) - if isinstance(shared, str): + shared = run_cache.get_dated("permission", key, run_cache.MAX_AGE) + if shared is not None and isinstance(shared[0], str): cache[login] = shared - return shared - status, payload = _get( - f"repos/{owner}/{name}/collaborators/{login}/permission" - ) - value = ( - payload.get("permission") - if status == 200 and is_json_object(payload) - else None - ) - cache[login] = value if isinstance(value, str) else None - if isinstance(value, str): - run_cache.put("permission", key, value) - return cache[login] + else: + at = run_cache.now() + status, payload = _get( + f"repos/{owner}/{name}/collaborators/{login}/permission" + ) + value = ( + payload.get("permission") + if status == 200 and is_json_object(payload) + else None + ) + cache[login] = (value if isinstance(value, str) else None, at) + if isinstance(value, str): + run_cache.put("permission", key, value, at) + value, at = cache[login] + run_cache.note(at) + return value return read diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py index 0e7dc85717f..727541de87f 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_run_cache.py @@ -15,6 +15,7 @@ import hashlib import json import os +from collections.abc import Iterator from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -53,9 +54,39 @@ def _load(path: Path) -> dict[str, Any]: return data if isinstance(data, dict) else {} +# The open `track()` lists. +_trackers: list[list[datetime]] = [] + + +@contextlib.contextmanager +def track() -> Iterator[list[datetime]]: + """Collect, while open, when each read a reader serves was taken + (`note`), so a judgment can be dated by its oldest input.""" + taken: list[datetime] = [] + _trackers.append(taken) + try: + yield taken + finally: + _trackers.remove(taken) + + +def note(at: datetime) -> None: + """Record that a value read at `at` was just served.""" + for taken in _trackers: + taken.append(at) + + def get(section: str, key: str, max_age: timedelta | None) -> Any: """The value saved under `section` and `key` at most `max_age` ago (None: any time this run), or None.""" + dated = get_dated(section, key, max_age) + return None if dated is None else dated[0] + + +def get_dated( + section: str, key: str, max_age: timedelta | None +) -> tuple[Any, datetime] | None: + """`get`, with when the value was saved.""" path = _path() if path is None: return None @@ -72,12 +103,12 @@ def get(section: str, key: str, max_age: timedelta | None) -> Any: age = now() - at if age < timedelta(0) or (max_age is not None and age > max_age): return None - return entry.get("value") + return entry.get("value"), at -def put(section: str, key: str, value: Any) -> None: - """Save `value`, replacing the file whole. Best effort: a failed write - leaves the next process to read GitHub.""" +def put(section: str, key: str, value: Any, at: datetime | None = None) -> None: + """Save `value`, read at `at` (now by default), replacing the file whole. + Best effort: a failed write leaves the next process to read GitHub.""" path = _path() if path is None: return @@ -85,7 +116,7 @@ def put(section: str, key: str, value: Any) -> None: entries = data.get(section) if not isinstance(entries, dict): entries = data[section] = {} - entries[key] = {"at": now().isoformat(), "value": value} + entries[key] = {"at": (at or now()).isoformat(), "value": value} tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") with contextlib.suppress(OSError): tmp.write_text(json.dumps(data), encoding="utf-8") 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 3bc59adfdfa..981918dc7d1 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 @@ -243,8 +243,17 @@ class Reader: _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 + _humans_at: datetime | None = None # when `_humans` was read def _listing(self) -> list[dict[str, Any]]: + """`_current_listing`, noting when it began to be read + (`run_cache.note`).""" + listing = self._current_listing() + if self._fetched_at is not None: + run_cache.note(self._fetched_at) + return listing + + def _current_listing(self) -> list[dict[str, Any]]: """Every repository artifact, read at most `LISTING_MAX_AGE` before this judgment (from the run's saved listing when it is that recent): a failed read is kept too, so one outage refuses each later entry @@ -271,11 +280,6 @@ def _listing(self) -> list[dict[str, Any]]: self._save(listing, fetched_at) return listing - @property - def listed_at(self) -> datetime | None: - """When the listing last judged on began to be read.""" - return self._fetched_at - @property def saved(self) -> bool: """Whether the listing judged on was read from `listing_path`.""" @@ -451,14 +455,17 @@ def _record(self, run_id: int, name: str) -> dict[str, Any]: def _trusted_humans(self) -> frozenset[int]: """The trusted list's human ids at the branch, shared by the run's - gate processes for `run_cache.MAX_AGE`.""" + gate processes for `run_cache.MAX_AGE`; each answer notes when it + was read (`run_cache.note`).""" key = f"{self.repo}@{self.branch}" if self._humans is None: - shared = run_cache.get("trusted-humans", key, run_cache.MAX_AGE) - if is_json_array(shared): - self._humans = frozenset(i for i in shared if type(i) is int) + shared = run_cache.get_dated("trusted-humans", key, run_cache.MAX_AGE) + if shared is not None and is_json_array(shared[0]): + self._humans = frozenset(i for i in shared[0] if type(i) is int) + self._humans_at = shared[1] humans = self._humans if humans is None: + self._humans_at = run_cache.now() listing = json_object( _read( [ @@ -479,7 +486,9 @@ def _trusted_humans(self) -> frozenset[int]: if a.get("kind") == "human" and isinstance(a.get("id"), int) ) self._humans = humans - run_cache.put("trusted-humans", key, sorted(humans)) + run_cache.put("trusted-humans", key, sorted(humans), self._humans_at) + if self._humans_at is not None: + run_cache.note(self._humans_at) return humans def _trusted_actor(self, kind: Any, actor_id: Any, login: Any, author: str) -> bool: 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 85439c5c391..042629e9c67 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 @@ -43,6 +43,7 @@ HEAD = fixtures.HEAD BASE = "c" * 40 PR = fixtures.PR_NUMBER +OPERATOR_LOGIN = "operator" IDENTITY = "agent-lanes[bot]" INERT = policy.UnattendedPolicy(reason="authority-unconfigured") INERT_BLOCKER = "unattended merge refused: authority-unconfigured" @@ -338,6 +339,10 @@ def setUp(self) -> None: # Every queued entry the sweep judged, in order. self.hold_reads: list[int] = [] self.dequeue_error: Exception | None = None + # The permission reader the policy builds, and what a queued entry's + # hold read does with its keyword arguments first. + self.permission_reader: Any = lambda repo: lambda login: "write" + self.hold_hook: Any = lambda kwargs: None self.prior: dict[str, Any] | None = None self.log: list[str] = [] self.rules = QUEUE_RULES @@ -459,7 +464,7 @@ def gh_json(args: list[str]) -> Any: policy, "read_kill_switch", side_effect=lambda repo: kills.pop(0) ), mock.patch.object( - policy, "permission_reader", return_value=lambda login: "write" + policy, "permission_reader", side_effect=self.permission_reader ), mock.patch.object(policy, "read_demotion", return_value=self.demotion), mock.patch.object( @@ -509,8 +514,8 @@ def gh_json(args: list[str]) -> Any: mock.patch.object( policy, "entry_hold", - side_effect=lambda r, n, i, **_: ( - self.hold_reads.append(n) or self.holds.get(n) + side_effect=lambda r, n, i, **kw: ( + self.hold_reads.append(n) or self.hold_hook(kw) or self.holds.get(n) ), ), mock.patch.object(merge, "_lane_evidence", side_effect=self._lane_evidence), @@ -1372,6 +1377,27 @@ def test_a_failed_dequeue_keeps_nothing(self) -> None: self.candidates(2) self.assertEqual(self.hold_reads.count(5), 2) + def test_a_kept_entry_is_dated_by_its_oldest_shared_read(self) -> None: + # The hold read uses a permission another process shared 90 s before + # the judgment, so the entry is kept as of then and judged again by + # the candidate 31 s later. + self.permission_reader = policy.permission_reader + self.hold_hook = lambda kwargs: kwargs["permission"](OPERATOR_LOGIN) and None + start = datetime(2026, 10, 18, 12, 0, tzinfo=UTC) + clock = [start - timedelta(seconds=90)] + with ( + mock.patch("babysit_run_cache.now", side_effect=lambda: clock[0]), + mock.patch.object( + policy, "_get", return_value=(200, {"permission": "write"}) + ), + ): + merge.run_cache.put("permission", f"owner/repo|{OPERATOR_LOGIN}", "write") + for seconds in (90, 121): + clock[0] = start - timedelta(seconds=90) + timedelta(seconds=seconds) + self.candidates(1) + self.assertEqual(self.hold_reads.count(5), 2) + self.assertEqual(self.log, []) # kept both times, never dequeued + def test_without_the_file_every_candidate_judges_every_entry(self) -> None: with mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": ""}): self.candidates(2) 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 cc1ae533f15..6929dc80dd2 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 @@ -1050,6 +1050,23 @@ def test_a_head_off_the_branch_is_compared_by_every_candidate(self) -> None: self.candidates(fake, 2) self.assertEqual(self.compares(fake, off), 2) + def test_a_judgment_notes_its_oldest_shared_read(self) -> None: + # The trusted list another process read 90 s ago dates the judgment. + clock = [datetime(2026, 10, 18, 11, 58, 30, tzinfo=UTC)] + fake = passing() + with ( + mock.patch.object(ve.run_cache, "now", side_effect=lambda: clock[0]), + mock.patch.object(ve, "_wall_clock", side_effect=lambda: clock[0]), + ): + self.candidates(fake, 1) + listed_before = clock[0] + clock[0] += timedelta(seconds=90) + with ve.run_cache.track() as taken: + self.candidates(fake, 1) + self.assertEqual(self.trusted_reads(fake), 1) + self.assertEqual(min(taken), listed_before) + self.assertIn(clock[0], taken) # this process's own listing + def test_the_trusted_list_is_read_once_within_the_bound(self) -> None: clock = [datetime(2026, 10, 18, 12, 0, tzinfo=UTC)] fake = passing() @@ -1687,12 +1704,12 @@ def setUp(self) -> None: for patcher in ( mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}), mock.patch.object(ve.run_cache, "now", side_effect=lambda: self.clock), - mock.patch.object(ve.Reader, "listed_at", new=listed), + # The verdict is judged on a listing begun 90 s before the run. mock.patch.object( ve.Reader, "evidence", side_effect=lambda n, head, pr=None: ( - self.reads.append(n) or evidence(None) + self.reads.append(n) or ve.run_cache.note(listed) or evidence(None) ), ), ): From de4cfb2c6d4cae164873f9d79550e98e965de928 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:30:29 -0400 Subject: [PATCH 6/7] perf(source-control): share pr-merge's FAIL run records and base reads per run The verdict reader reads the run record of every live FAIL artifact in the repository, and downloads an untied FAIL's verdict.json, for every candidate, all on github.token. The gate also reads the default branch and the base's rules once per candidate. Through babysit_run_cache: - A FAIL's run record is shared for two minutes. 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); status, conclusion and attempt never change a FAIL's outcome, so a stale record cannot turn a refusal into an allow. A PASS's run is still 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: an artifact's contents never change, and a FAIL whose artifact has gone still refuses. - The default branch (policy and repository_default_branch) and branch_rules are shared for two minutes; a failed read is never shared. The pre-enqueue base check stays fresh, and before an enqueue a default branch or rules a gate took from the cache are read again; any change holds. Co-Authored-By: Claude Opus 5.5 --- ...erf-pr-merge-share-run-records-7c2e5a19.md | 7 ++ .github/workflows/pr-merge.yml | 7 +- docs/conventions/pr-pipeline/README.md | 9 +- .../babysit-prs/scripts/babysit_merge.py | 47 +++++++- .../scripts/babysit_merge_policy.py | 33 +++++- .../scripts/babysit_verify_evidence.py | 105 +++++++++++++----- .../tests/test_babysit_merge_branch_rules.py | 75 +++++++++++-- .../tests/test_babysit_merge_policy.py | 20 ++++ .../tests/test_babysit_merge_unattended.py | 35 +++++- .../tests/test_babysit_verify_evidence.py | 65 +++++++++++ 10 files changed, 347 insertions(+), 56 deletions(-) create mode 100644 .changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md 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..0f1c747699d --- /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 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. 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 b5e0f4c25ad..65d8a15f67b 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -734,7 +734,14 @@ 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, since an artifact's contents never change. 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, and any change +holds. 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..68504984eb8 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,10 @@ 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 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 +534,19 @@ 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" +# Branches whose rules this process took from the run cache; +# `unattended_enqueue` reads them again before an enqueue. +SHARED_RULES: set[str] = set() -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 +582,16 @@ 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 else None + if is_json_array(rules): + SHARED_RULES.add(branch) + else: + 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}" @@ -3347,6 +3367,20 @@ 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 branch in SHARED_RULES and branch_rules( + repo, branch, shared=False + ) != result.get("effectiveRules"): + 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 +3465,9 @@ 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. + 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 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..15fbb785572 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,70 @@ 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) -> Any: + """The head ref an untied FAIL's verdict.json records, shared by the + run's gate processes: an artifact's contents never change, and a + FAIL whose artifact has since gone still refuses.""" + key = f"{self.repo}|{run_id}|{name}" + dated = run_cache.get_dated(RECORD_SECTION, key, None) + if dated is not None and is_json_object(dated[0]): + return dated[0].get("head_ref") + record = self._record(run_id, name) + 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 +704,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 +716,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) 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..849f5e32dc9 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 @@ -17,7 +17,9 @@ import pathlib import sys +import tempfile import unittest +from datetime import UTC, datetime, timedelta from typing import Any from unittest import mock @@ -36,9 +38,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 +83,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 +187,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 +203,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 +226,58 @@ 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")) + patcher = mock.patch.dict("os.environ", {"BABYSIT_RUN_CACHE": path}) + 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) + + 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..569f707f34b 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,37 @@ 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_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..64be8ae2603 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,71 @@ 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_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. From 3a0e4fc9da3d01fbc20552a2a14681ab768fb8f7 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:46:14 -0400 Subject: [PATCH 7/7] fix(source-control): address #8034 review nits on shared base reads - The pre-enqueue re-read now covers every branch whose rules the gate took from the run cache, keyed by the branch actually read (a rules_base landing base included), and compares the fresh summary with the one served. - The default branch and the base's rules come from the run cache only on the --unattended path, whose enqueue reads them again; every attended gate run reads them fresh. - An untied FAIL's shared head ref is keyed by artifact id, not name: an id names immutable contents, and upload-artifact's overwrite uploads a new id under the same name. Co-Authored-By: Claude Opus 5.5 --- ...erf-pr-merge-share-run-records-7c2e5a19.md | 2 +- docs/conventions/pr-pipeline/README.md | 9 +-- .../babysit-prs/scripts/babysit_merge.py | 38 +++++++---- .../scripts/babysit_verify_evidence.py | 18 +++-- .../tests/test_babysit_merge_branch_rules.py | 65 ++++++++++++++++++- .../tests/test_babysit_merge_unattended.py | 34 ++++++++++ .../tests/test_babysit_verify_evidence.py | 11 ++++ 7 files changed, 151 insertions(+), 26 deletions(-) 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 index 0f1c747699d..aa2ddaf8ec0 100644 --- a/.changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md +++ b/.changes/source-control/perf-pr-merge-share-run-records-7c2e5a19.md @@ -4,4 +4,4 @@ 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 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. 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. +- `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/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index 45a33453b59..2ae49e8620c 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -739,10 +739,11 @@ candidate, and a failed dequeue keeps nothing. A FAIL's run record is reused for 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, since an artifact's contents never change. 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, and any change -holds. Without the variable nothing is shared. +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 68504984eb8..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,7 +523,11 @@ 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) + 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 @@ -541,9 +545,13 @@ def repository_default_branch(repo: str) -> str | None: RULES_SECTION = "branch-rules" -# Branches whose rules this process took from the run cache; -# `unattended_enqueue` reads them again before an enqueue. -SHARED_RULES: set[str] = set() +# 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, *, shared: bool = True) -> dict[str, object]: @@ -583,10 +591,13 @@ def branch_rules(repo: str, branch: str, *, shared: bool = True) -> dict[str, ob # (github.com/google/go-github repos_rules.go, ListRulesForBranch). # gh 2.99.0 forwards that path unchanged. key = f"{repo}|{branch}" - rules = run_cache.get(RULES_SECTION, key, run_cache.MAX_AGE) if shared else None - if is_json_array(rules): - SHARED_RULES.add(branch) - else: + 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='')}"] ) @@ -647,6 +658,8 @@ def branch_rules(repo: str, branch: str, *, shared: bool = True) -> dict[str, ob summary["requiredContexts"] = sorted(required_contexts) summary["requiredApprovingReviews"] = required_reviews summary["requireThreadResolution"] = require_thread_resolution + if cached: + SHARED_RULES[branch] = summary return summary @@ -3377,9 +3390,10 @@ def hold(reason: str) -> int: return hold(merge_policy.DEFAULT_BRANCH_UNREADABLE) if default != branch: return hold(f"base-not-default:{branch}") - if branch in SHARED_RULES and branch_rules( - repo, branch, shared=False - ) != result.get("effectiveRules"): + 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"] @@ -3466,6 +3480,7 @@ 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 @@ -3677,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_verify_evidence.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_verify_evidence.py index 15fbb785572..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 @@ -464,16 +464,20 @@ def _run_state(self, run_id: int, *, shared: bool = False) -> str: 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) -> Any: + 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: an artifact's contents never change, and a - FAIL whose artifact has since gone still refuses.""" - key = f"{self.repo}|{run_id}|{name}" - dated = run_cache.get_dated(RECORD_SECTION, key, None) + 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) - run_cache.put(RECORD_SECTION, key, {"head_ref": record.get("head_ref")}) + 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]: @@ -716,7 +720,7 @@ def _evidence(self, number: int, head: str, pr: dict[str, Any] | None) -> Eviden continue if not tied: try: - recorded = self._head_ref(run_id, name) + 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 849f5e32dc9..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,6 +15,9 @@ from __future__ import annotations +import contextlib +import io +import json import pathlib import sys import tempfile @@ -23,9 +26,11 @@ 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. @@ -237,9 +242,13 @@ 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) + # 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: @@ -279,5 +288,55 @@ def test_a_failed_default_branch_read_is_not_shared(self) -> None: 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_unattended.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py index 569f707f34b..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 @@ -666,6 +666,40 @@ def test_rules_changed_since_the_shared_read_hold_the_enqueue(self) -> None: 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() 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 64be8ae2603..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 @@ -1120,6 +1120,17 @@ def test_a_fail_run_and_its_record_are_read_once_per_run(self) -> None: # 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()