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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: patch
---

### Changed

- `babysit-prs` merge gate: in the pr-merge lane, the verdict reader shares a FAIL's run record for two minutes and an untied FAIL's recorded head ref for the run (keyed by artifact id) across the run's gate processes, instead of reading them again for every candidate. A stale FAIL record still refuses, because a FAIL counts whether its run is running or finished and a re-run keeps every field that decides whether the run is pr-verify's; a PASS's run record is still read by each gate process, so a re-run that undoes a completed success never allows. On the `--unattended` path only, the default branch and the base's rules are also shared for two minutes, a failed read never; before an enqueue, any the gate took from the run cache are read again, and a change holds.
7 changes: 4 additions & 3 deletions .github/workflows/pr-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
10 changes: 9 additions & 1 deletion docs/conventions/pr-pipeline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,15 @@ never shared. A run head found on main is shared for the run, since main's rules
pushes; one not found is compared again. In the merge-queue sweep, a queued entry another candidate
judged and kept is skipped only while the oldest read behind that judgment (its verdict listing, or a
shared permission or trusted list) was taken at most two minutes ago; a gate always judges its own entry, a held entry is judged by every
candidate, and a failed dequeue keeps nothing. Without the variable nothing is shared.
candidate, and a failed dequeue keeps nothing. A FAIL's run record is reused for two minutes: a FAIL
counts whether its run is still running or finished, and a re-run keeps every field that decides
whether the run is pr-verify's, so a stale record never turns a FAIL away. A PASS's run record is
read by each gate process, because a re-run can undo a completed success. An untied FAIL's
recorded head ref is shared for the run under the artifact's id, since the contents an id names
never change (an overwrite uploads a new id). On the `--unattended` path only, the default branch
and the base's rules are reused for two minutes, and a failed read is never shared; before an
enqueue, a default branch or rules a gate took from the file are read again for the branch read,
and any change holds. An attended gate run reads both fresh. Without the variable nothing is shared.

## Trust-root paths

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -523,17 +523,38 @@ def repository_default_branch(repo: str) -> str | None:
self-login exemption in place rather than inventing a hold from missing
evidence.
"""
cached = (
run_cache.get(merge_policy.DEFAULT_BRANCH_SECTION, repo, run_cache.MAX_AGE)
if SHARE_BASE_READS
else None
)
if isinstance(cached, str) and cached:
merge_policy.SHARED_DEFAULT_BRANCHES.add(repo)
return cached
try:
data = gh_json(["api", f"repos/{repo}", "--jq", "{name: .default_branch}"])
except (RuntimeError, json.JSONDecodeError):
return None
if not is_json_object(data):
return None
name = data.get("name")
return str(name) if name else None
if not name:
return None
run_cache.put(merge_policy.DEFAULT_BRANCH_SECTION, repo, str(name))
return str(name)


RULES_SECTION = "branch-rules"
# Whether this gate run may take the default branch and the base's rules
# from the run cache: the `--unattended` path only, whose enqueue reads them
# again (`main`). Every attended path reads them fresh.
SHARE_BASE_READS = False
# The rules this process took from the run cache, by the branch read, as
# summarized; `unattended_enqueue` reads each again before an enqueue.
SHARED_RULES: dict[str, dict[str, object]] = {}


def branch_rules(repo: str, branch: str) -> dict[str, object]:
def branch_rules(repo: str, branch: str, *, shared: bool = True) -> dict[str, object]:
"""Summarize the effective merge-governing rules for the base branch.

Rulesets COMPOSE: `/rules/branches/{branch}` returns one rule of a given
Expand Down Expand Up @@ -569,9 +590,19 @@ def branch_rules(repo: str, branch: str) -> dict[str, object]:
# matches Go's url.PathEscape, which go-github uses for this endpoint
# (github.com/google/go-github repos_rules.go, ListRulesForBranch).
# gh 2.99.0 forwards that path unchanged.
rules = gh_json(
["api", f"repos/{repo}/rules/branches/{quote(branch, safe='')}"]
key = f"{repo}|{branch}"
rules = (
run_cache.get(RULES_SECTION, key, run_cache.MAX_AGE)
if shared and SHARE_BASE_READS
else None
)
cached = is_json_array(rules)
if not cached:
rules = gh_json(
["api", f"repos/{repo}/rules/branches/{quote(branch, safe='')}"]
)
if is_json_array(rules):
run_cache.put(RULES_SECTION, key, rules)
except (RuntimeError, json.JSONDecodeError) as exc:
# Rules are advisory context; a read failure must never fail the run.
summary["error"] = f"could not read branch rules: {exc}"
Expand Down Expand Up @@ -627,6 +658,8 @@ def branch_rules(repo: str, branch: str) -> dict[str, object]:
summary["requiredContexts"] = sorted(required_contexts)
summary["requiredApprovingReviews"] = required_reviews
summary["requireThreadResolution"] = require_thread_resolution
if cached:
SHARED_RULES[branch] = summary
return summary


Expand Down Expand Up @@ -3347,6 +3380,21 @@ def hold(reason: str) -> int:
step["optIn"] = opt_in
if opt_in:
return hold(f"ineligible:{opt_in}")
# An enqueue never rests on a read shared within the run: a default
# branch or base rules the gate took from the run cache are read again,
# and any change holds.
if repo in merge_policy.SHARED_DEFAULT_BRANCHES:
try:
default = merge_policy._default_branch(repo)
except merge_policy.PolicyReadError:
return hold(merge_policy.DEFAULT_BRANCH_UNREADABLE)
if default != branch:
return hold(f"base-not-default:{branch}")
if any(
branch_rules(repo, base, shared=False) != served
for base, served in list(SHARED_RULES.items())
):
return hold("the base branch's rules changed since the gate read them")
proc = gh_capture(
["api", "-X", "POST", f"repos/{repo}/issues/{number}/comments"]
+ ["-f", f"body={postmerge.pin_comment(pin)}"]
Expand Down Expand Up @@ -3431,6 +3479,10 @@ def build_settle(logins: Iterable[str], minutes: str) -> ReviewSettleConfig | No

def main() -> int:
configure_stdio()
# This gate run's own record of what it took from the run cache.
global SHARE_BASE_READS
SHARED_RULES.clear()
merge_policy.SHARED_DEFAULT_BRANCHES.clear()
# allow_abbrev=False: the permission grants covering this gate state their
# conditions as the literal presence or absence of a flag in the command
# text -- above all "no --merge means check-only". Prefix abbreviation
Expand Down Expand Up @@ -3640,6 +3692,7 @@ def main() -> int:
),
)
args = parser.parse_args()
SHARE_BASE_READS = bool(args.unattended)

def _refuse(message: str, code: int, **envelope: object) -> int:
"""Emit one refusal envelope on stdout and return its exit code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:<ref>` 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}"

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 = (
Expand All @@ -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


Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -394,41 +412,74 @@ def _contains(self, sha: str) -> bool:
run_cache.put("on-branch", key, True)
return self._on_branch[sha]

def _run_state(self, run_id: int) -> str:
if run_id not in self._runs:
try:
def _run_state(self, run_id: int, *, shared: bool = False) -> str:
"""The run's standing. A FAIL's run (`shared`) may be judged on a
record another gate process of the run read within
`run_cache.MAX_AGE`: a FAIL counts whether its run is origin or
counted, and origin rests only on fields a re-run keeps (id, path,
event, branch, repositories, head), never on status, conclusion or
attempt, so a stale record cannot turn a FAIL away. A PASS needs a
completed success, which a re-run can undo, so its run is read by
this process."""
if run_id in self._runs and (shared or run_id not in self._shared_runs):
return self._runs[run_id]
key = f"{self.repo}|{run_id}"
record = run_cache.get(RUN_SECTION, key, run_cache.MAX_AGE) if shared else None
cached = is_json_object(record)
try:
if not cached:
record = json_object(
self._actions(
["api", f"repos/{self.repo}/actions/runs/{run_id}"],
f"run {run_id}",
)
)
head = record.get("head_sha")
origin = (
record.get("id") == run_id
and record.get("path") == WORKFLOW_PATH
and record.get("event") == "workflow_run"
and record.get("head_branch") == self.branch
and json_object(record.get("repository")).get("full_name")
== self.repo
and json_object(record.get("head_repository")).get("full_name")
== self.repo
and isinstance(head, str)
and merge_policy.SHA_RE.fullmatch(head) is not None
and self._contains(head)
)
self._started[run_id] = record.get("run_started_at")
done = (
record.get("status") == "completed"
and record.get("conclusion") == "success"
)
self._runs[run_id] = (
FOREIGN if not origin else COUNTED if done else ORIGIN
)
except _Unreadable:
self._runs[run_id] = UNREAD
head = record.get("head_sha")
origin = (
record.get("id") == run_id
and record.get("path") == WORKFLOW_PATH
and record.get("event") == "workflow_run"
and record.get("head_branch") == self.branch
and json_object(record.get("repository")).get("full_name") == self.repo
and json_object(record.get("head_repository")).get("full_name")
== self.repo
and isinstance(head, str)
and merge_policy.SHA_RE.fullmatch(head) is not None
and self._contains(head)
)
except _Unreadable:
self._shared_runs.discard(run_id)
self._runs[run_id] = UNREAD
return UNREAD
if cached:
self._shared_runs.add(run_id)
else:
self._shared_runs.discard(run_id)
self._started[run_id] = record.get("run_started_at")
run_cache.put(RUN_SECTION, key, {k: record.get(k) for k in RUN_FIELDS})
done = (
record.get("status") == "completed"
and record.get("conclusion") == "success"
)
self._runs[run_id] = FOREIGN if not origin else COUNTED if done else ORIGIN
return self._runs[run_id]

def _head_ref(self, run_id: int, name: str, artifact_id: Any) -> Any:
"""The head ref an untied FAIL's verdict.json records, shared by the
run's gate processes under the artifact's id: an id names contents
that never change (an overwrite uploads a new id), and a FAIL whose
artifact has since gone still refuses. An artifact with no id is not
shared."""
shared = isinstance(artifact_id, int) and not isinstance(artifact_id, bool)
key = f"{self.repo}|{artifact_id}"
dated = run_cache.get_dated(RECORD_SECTION, key, None) if shared else None
if dated is not None and is_json_object(dated[0]):
return dated[0].get("head_ref")
record = self._record(run_id, name)
if shared:
run_cache.put(RECORD_SECTION, key, {"head_ref": record.get("head_ref")})
return record.get("head_ref")

def _record(self, run_id: int, name: str) -> dict[str, Any]:
"""The artifact's verdict.json, downloaded once."""
key = (run_id, name)
Expand Down Expand Up @@ -657,7 +708,7 @@ def _evidence(self, number: int, head: str, pr: dict[str, Any] | None) -> Eviden
else:
ignored += 1
continue
state = self._run_state(run_id)
state = self._run_state(run_id, shared=True)
if state == FOREIGN:
ignored += 1
continue
Expand All @@ -669,7 +720,7 @@ def _evidence(self, number: int, head: str, pr: dict[str, Any] | None) -> Eviden
continue
if not tied:
try:
recorded = self._record(run_id, name).get("head_ref")
recorded = self._head_ref(run_id, name, item.get("id"))
except _Unreadable:
unreadable = unreadable or f"record of {name}"
continue
Expand Down
Loading
Loading