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
---

### Added

- `merge.read-token-floor` (default 0.3): the pr-merge gate reads its review evidence (timeline, comments, review-lane runs with their attempts, jobs and annotations) with `GITHUB_TOKEN` only while that token has at least this share of its hourly core limit left. Below it, or when the limit cannot be read, those reads use the lane App token, as they did before. The floor is only an early switch: when one of those reads is refused for a rate limit (a 429, or a 403 naming one), the gate reads that candidate's evidence again with the lane App token and marks `GITHUB_TOKEN` spent in the run cache for later candidates. Either token reads the same data, so no gate decision changes. The value is read at the default branch head. The repository's `GITHUB_TOKEN` pool, 1,000 requests an hour shared by every job, ran out on 2026-10-23 once these reads moved onto it.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: patch
---

### Changed

- The unattended merge gate reads its review evidence under `BABYSIT_VERIFY_GH_TOKEN` only while that token's core bucket has at least `merge.read-token-floor` of its limit left (`PipelineConfig.read_token_floor`, default 0.3, taken from the default branch head). Below the floor, or when `GET /rate_limit` cannot be read, the reads keep the process (lane) token and a `read-token-floor:` line goes to stderr. A read under the read token refused for a rate limit (`babysit_gh.gh_rate_limited`: a 429, or a 403 naming one) makes `_lane_evidence` read everything again with the process token and record the token in `BABYSIT_RUN_CACHE` (`read-token-limited`), so later candidates skip it; any other refusal still raises. `babysit_whole_review._short_bucket` takes an optional `share` and `buckets`; whole-review requests keep `MIN_SHARE`.
14 changes: 14 additions & 0 deletions docs/conventions/pr-pipeline.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,20 @@ merge:
# 30-minute timeout with the minute before the loop and the closing steps
# (judgment).
gate-deferred-minutes: 20
# The share of GITHUB_TOKEN's core limit (GET /rate_limit) that must be
# left for the gate's review-evidence reads (timeline, comments, lane runs,
# attempts, jobs, annotations) to use it; below it, or when the limit cannot
# be read, they use the lane App token. An early switch only: a read refused
# for a rate limit also moves them to the lane App token for the rest of
# the run, since /rate_limit read 3934 of 5000 left while the token was
# already refused. Either token reads the same data, so no gate decision
# changes. The pool is 1,000 an hour per repository and shared by
# every job; moving these reads onto it added an estimated 600-1,500 an
# hour, and it ran out at 05:26Z on 2026-10-23, failing pr-merge's full-run
# dispatch on runs 39905758340, 39905868587 and 39906176584. 0.3 keeps 300
# for the dispatches, waits and post-merge checks, the share
# babysit_whole_review.py's MIN_SHARE keeps (judgment).
read-token-floor: 0.3
# Minutes a MED or HIGH reasons comment must stand unchanged at the head
# before the gate adds the human-gated label; 0 is no minimum. 60 is longer
# than a review lane's run (judgment), so a review still running at the
Expand Down
13 changes: 11 additions & 2 deletions docs/conventions/pr-pipeline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1339,8 +1339,17 @@ The lane token holds no Actions permission, so pr-merge.yml grants its job `acti
`BABYSIT_VERIFY_GH_TOKEN`; the reader uses it as `GH_TOKEN` for the artifact listing, the run
records, the download and the compare of a run's head to main (a `contents: read` call). The gate's
review-evidence reads use it too: the timeline, the comments, and the lane runs with their attempts,
jobs and annotations. Every other call, every write included, keeps the lane token. That job checks
out only main and runs no pull request code.
jobs and annotations. Two things send them back to the lane token, as before; both tokens read
the same data, so neither changes a gate decision. First, `GITHUB_TOKEN` must have at least
`merge.read-token-floor` of its core limit left by `GET /rate_limit` (default 0.3, read at the
default branch head; an unreadable limit counts as short). That is only an early switch: in the
05:26Z outage on 2026-10-23, `/rate_limit` showed 3,934 of 5,000 left while `GITHUB_TOKEN` was
already refused with "API rate limit exceeded for installation". Second, when any of those reads
is refused with a 429, or a 403 whose message names a rate limit, the gate reads all of that
candidate's evidence again with the lane token (they are all GETs). It records the refusal in
`BABYSIT_RUN_CACHE`, so later candidates in the run skip `GITHUB_TOKEN`. Any other refusal is not
retried. `GITHUB_TOKEN`'s pool is shared with the full-run dispatch and the post-merge checks. Every other call, every write
included, 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
Expand Down
7 changes: 7 additions & 0 deletions docs/conventions/pr-pipeline/pr-pipeline.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,13 @@
"minimum": 1,
"description": "Minutes the gate may read for the candidate the last run deferred at gate-candidate-minutes, gated first in its run; writes are never bounded, as there. A candidate stopped at this ceiling gets a warning annotation and goes back to the capped rotation, never deferred again. Keep it below the merge job's timeout-minutes less the closing steps. Absent: no limit."
},
"read-token-floor": {
"type": "number",
"minimum": 0,
"maximum": 1,
"default": 0.3,
"description": "Share of GITHUB_TOKEN's core limit, as GET /rate_limit reports it, that must be left, at or above which the pr-merge gate reads its review evidence (timeline, comments, review-lane runs with their attempts, jobs and annotations) with BABYSIT_VERIFY_GH_TOKEN; below it, or when /rate_limit cannot be read, those reads use the lane App token. It is an early switch only: /rate_limit can show room while GitHub already refuses the token, so a read refused with a 429, or a 403 naming a rate limit, also sends that candidate's evidence reads to the lane App token and marks the token spent for the rest of the run. Both tokens read the same data, so no gate decision changes. Read at the default branch head. Absent, or not a number from 0 to 1: 0.3."
},
"skip-unchanged": {
"type": "object",
"additionalProperties": false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ def gh_http_status(text: str) -> int | None:
return int(matches[-1]) if matches else None


def gh_rate_limited(text: str) -> bool:
"""Whether a `gh` failure message reports a rate limit: HTTP 429, or a 403
whose message names one ("API rate limit exceeded", "secondary rate
limit"). Any other 403 is a refusal, not a limit."""
status = gh_http_status(text)
return status == 429 or (status == 403 and "rate limit" in text.casefold())


def is_graphql_unavailable(failure: BaseException | str) -> bool:
"""Whether a failed GraphQL-backed `gh` call was refused the API itself.

Expand Down
140 changes: 120 additions & 20 deletions plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,11 @@

import argparse
import functools
import hashlib
import json
import os
import re
import sys
import time
from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass, replace
Expand Down Expand Up @@ -192,6 +194,7 @@
gh_capture,
gh_http_status,
gh_json,
gh_rate_limited,
normalized_rest_author,
parse_repo_number,
pull_request_commits_once,
Expand Down Expand Up @@ -2947,6 +2950,55 @@ class HeadPusherUnproven(Exception):
"""A head commit's pusher cannot be shown not to be a human."""


# The run cache section where a gate process records that the read token hit
# a rate limit, keyed by a digest of that token, so later candidates in the
# run read their evidence with the lane token without trying it first.
READ_TOKEN_LIMITED = "read-token-limited"


class ReadTokenLimited(RuntimeError):
"""A review-evidence read under the read token was refused for a rate
limit; the same GETs can be made with the lane token."""


def _token_key(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()


def _evidence_read_env(floor: float) -> dict[str, str] | None:
"""`env_overrides` for the review-evidence reads: the verdict reader's
token while its core bucket has at least `floor` of its limit left and no
earlier candidate in this run saw it rate limited, else None, the process
(lane) token. Both tokens read the same data, so the choice changes no
gate decision. A limit that cannot be read is treated as short; GET
/rate_limit spends no budget. The share is only an early switch: GitHub
can refuse the token while /rate_limit still shows room, which
`_lane_evidence` handles by reading again with the lane token."""
token = os.environ.get(verify_evidence.TOKEN_ENV)
if not token:
return None
if run_cache.get(READ_TOKEN_LIMITED, _token_key(token), None) is not None:
print(
f"read-token-floor: {verify_evidence.TOKEN_ENV} was rate limited earlier"
" in this run; the review-evidence reads use the lane token",
file=sys.stderr,
)
return None
env = {"GH_TOKEN": token}
try:
short = whole_review._short_bucket(env, share=floor, buckets=("core",))
except (RuntimeError, KeyError, TypeError, ValueError) as exc:
short = f"unreadable ({exc})"
if short is None:
return env
print(
f"read-token-floor: {verify_evidence.TOKEN_ENV} core {short} is under"
f" {floor}; the review-evidence reads use the lane token",
file=sys.stderr,
)
return None


def _lane_evidence(
repo: str,
number: int,
Expand All @@ -2955,6 +3007,39 @@ def _lane_evidence(
self_logins: frozenset[str],
permission: Callable[[str], str | None],
changed_paths: Sequence[str] | None,
read_floor: float = merge_policy.READ_TOKEN_FLOOR,
) -> tuple[tuple[LaneEvidence, ...], list[dict[str, Any]]]:
"""`_read_lane_evidence` under `_evidence_read_env`'s token. When a read
under the read token is refused for a rate limit, the run cache records
it for later candidates and every read is made again with the lane
token: all of them are GETs, so nothing is sent twice that changes
GitHub."""
args = (repo, number, pr, identity, self_logins, permission, changed_paths)
read_env = _evidence_read_env(read_floor)
if read_env is None:
return _read_lane_evidence(*args, None)
try:
return _read_lane_evidence(*args, read_env)
except ReadTokenLimited as exc:
run_cache.put(READ_TOKEN_LIMITED, _token_key(read_env["GH_TOKEN"]), True)
print(
f"read-token-floor: {verify_evidence.TOKEN_ENV} was rate limited"
f" ({str(exc)[-200:]}); reading the review evidence again with the"
" lane token",
file=sys.stderr,
)
return _read_lane_evidence(*args, None)


def _read_lane_evidence(
repo: str,
number: int,
pr: dict[str, Any],
identity: str,
self_logins: frozenset[str],
permission: Callable[[str], str | None],
changed_paths: Sequence[str] | None,
read_env: dict[str, str] | None,
) -> tuple[tuple[LaneEvidence, ...], list[dict[str, Any]]]:
"""Each lane's evidence for the pull request's head, and its comments.
`changed_paths` is `bind()`'s: None when the changed files are unproven.
Expand All @@ -2965,16 +3050,26 @@ def _lane_evidence(
finding away. A commit with no linked author or committer, or a head with
more commits than the list returns, raises `HeadPusherUnproven`. A retargeted base unbinds every lane.

The timeline, the comments and the lane runs are read under the verdict
reader's token when one is set, keeping them off the lane App's quota;
every read here is a GET."""
The timeline, the comments and the lane runs are read with `read_env`
(None: the process token), keeping them off the lane App's quota when it
names the verdict reader's token; every read here is a GET. A rate limit
on one of those reads raises `ReadTokenLimited`."""
head = json_object(pr.get("head"))
token = os.environ.get(verify_evidence.TOKEN_ENV)
read_env = {"GH_TOKEN": token} if token else None
timeline = fetch_paginated_api(
f"repos/{repo}/issues/{number}/timeline?per_page=100",
f"#{number} timeline",
env_overrides=read_env,

def under_read_env(read: Callable[[], Any]) -> Any:
try:
return read()
except RuntimeError as exc:
if read_env is not None and gh_rate_limited(str(exc)):
raise ReadTokenLimited(str(exc)) from exc
raise

timeline = under_read_env(
lambda: fetch_paginated_api(
f"repos/{repo}/issues/{number}/timeline?per_page=100",
f"#{number} timeline",
env_overrides=read_env,
)
)
commits = pull_request_commits_once(
repo,
Expand Down Expand Up @@ -3013,24 +3108,28 @@ def _lane_evidence(
}
excluded.add(str(json_object(pr.get("user")).get("login") or "").casefold())
excluded.discard("")
comments = fetch_paginated_api(
f"repos/{repo}/issues/{number}/comments?per_page=100",
f"#{number} comments",
env_overrides=read_env,
comments = under_read_env(
lambda: fetch_paginated_api(
f"repos/{repo}/issues/{number}/comments?per_page=100",
f"#{number} comments",
env_overrides=read_env,
)
)
try:
threads: list[Any] | None = fetch_review_threads(
repo, number, include_resolved=True
)
except GraphQLUnavailableError:
threads = None
runs = collect_lane_runs(
repo,
number,
str(head.get("ref")),
review_evidence.LANES.values(),
str(pr.get("created_at") or ""),
read_env,
runs = under_read_env(
lambda: collect_lane_runs(
repo,
number,
str(head.get("ref")),
review_evidence.LANES.values(),
str(pr.get("created_at") or ""),
read_env,
)
)

def human(actor: Any) -> bool:
Expand Down Expand Up @@ -3163,6 +3262,7 @@ def score_unattended(
[p for f in files for p in (f.path, f.previous_path) if p]
if complete
else None,
read_floor=config.read_token_floor,
)
except HeadPusherUnproven as exc:
# Fail closed: refused, and its own queued entry leaves.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,10 @@ def _rest_actor(actor: Any) -> dict[str, Any] | None:
# the verifier keeps refusing, not one noisy verdict (owner decision
# 2026-10-21).
MAX_VERIFY_FAILS = 3
# The default `merge.read-token-floor`: the share of GITHUB_TOKEN's core limit
# that must be left for the gate's review-evidence reads to use it, as
# babysit_whole_review.MIN_SHARE is for a whole-review request (judgment).
READ_TOKEN_FLOOR = 0.3


@dataclass(frozen=True)
Expand Down Expand Up @@ -557,6 +561,11 @@ class PipelineConfig:
# says (`babysit_verify_evidence`). Absent is `MAX_VERIFY_FAILS`; anything
# but a whole number of at least 1 is 1, so any earlier FAIL holds.
max_verify_fails: int = MAX_VERIFY_FAILS
# `merge.read-token-floor`: the review-evidence reads use the job's own
# token only while it has this share of its core limit left, else the
# lane token (babysit_merge `_evidence_read_env`). Absent, or anything but
# a number from 0 to 1, is `READ_TOKEN_FLOOR`.
read_token_floor: float = READ_TOKEN_FLOOR
# `merge.check-inputs`: git pathspecs of what the pull request checks
# read. When the base changed one since a pull request's merge base, the
# pr-merge lane updates its branch from the base instead of enqueuing it
Expand Down Expand Up @@ -721,6 +730,7 @@ def file_at(path: str, sha: str) -> str | None:
("merge.max-queue-ejections", False),
("merge.risk-escalation-minutes", False),
("merge.max-verify-fails", False),
("merge.read-token-floor", False),
("merge.check-inputs", True),
("adoption.idle-hours", False),
("adoption.spec-from-body-apps", True),
Expand Down Expand Up @@ -810,6 +820,12 @@ def switch(key: str) -> bool:
f"merge.max-verify-fails {verify_fails!r} is not a count of 1 or more"
)
verify_fails = "1"
floor = scalar("merge.read-token-floor")
if floor is not None and not (
re.fullmatch(r"0|1|0?\.[0-9]+|1\.0+", floor) and float(floor) <= 1
):
notes.append(f"merge.read-token-floor {floor!r} is not a number from 0 to 1")
floor = None
idle_text = scalar("adoption.idle-hours")
idle_hours: int | None = None
if idle_text is not None:
Expand Down Expand Up @@ -871,6 +887,7 @@ def switch(key: str) -> bool:
if escalation_minutes is not None
else RISK_ESCALATION_MINUTES,
max_verify_fails=int(verify_fails) if verify_fails else MAX_VERIFY_FAILS,
read_token_floor=float(floor) if floor is not None else READ_TOKEN_FLOOR,
check_inputs=tuple(values["merge.check-inputs"]),
adoption_idle_hours=idle_hours,
spec_from_body_apps=tuple(int(i) for i in body_apps),
Expand Down Expand Up @@ -952,6 +969,8 @@ def loop_rank(value: str | None) -> int:
# Read at main (owner decision Q22).
adoption_idle_hours=main.adoption_idle_hours,
spec_from_body_apps=main.spec_from_body_apps,
# Which token reads, never a decision: main's.
read_token_floor=main.read_token_floor,
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,19 @@ def _api(args: list[str], env: Mapping[str, str] | None = None) -> Any:
return json.loads(proc.stdout or "null")


def _short_bucket(env: Mapping[str, str] | None) -> str | None:
"""`bucket:remaining/limit` for the first bucket under `MIN_SHARE` of its
limit, else None. GET /rate_limit does not count against any bucket."""
def _short_bucket(
env: Mapping[str, str] | None,
share: float = MIN_SHARE,
buckets: Sequence[str] = ("core", "graphql"),
) -> str | None:
"""`bucket:remaining/limit` for the first of `buckets` under `share` of
its limit, else None. GET /rate_limit does not count against any bucket."""
resources = _api(["rate_limit"], env)["resources"]
for bucket in ("core", "graphql"):
for bucket in buckets:
left = int(resources[bucket]["remaining"])
limit = int(resources[bucket]["limit"])
# A limit of zero or less is no budget to judge against, so it refuses.
if limit <= 0 or left < MIN_SHARE * limit:
if limit <= 0 or left < share * limit:
return f"{bucket}:{left}/{limit}"
return None

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,18 @@ def test_http_status_reads_the_last_attempt(self) -> None:
self.assertEqual(gh.gh_http_status("(HTTP 502) ... (HTTP 403)"), 403)
self.assertIsNone(gh.gh_http_status("connection reset"))

def test_rate_limited_is_a_429_or_a_403_that_names_a_rate_limit(self) -> None:
for text, expected in (
("gh: API rate limit exceeded for installation ID 1. (HTTP 403)", True),
("gh: You have exceeded a secondary rate limit. (HTTP 403)", True),
("gh: Too Many Requests (HTTP 429)", True),
("gh: Resource not accessible by integration (HTTP 403)", False),
("gh: API rate limit exceeded (HTTP 502)", False),
("API rate limit exceeded, but no status", False),
):
with self.subTest(text=text):
self.assertIs(gh.gh_rate_limited(text), expected)


class ViewPrRestFallbackTests(unittest.TestCase):
"""`gh pr view --json` is GraphQL end to end, so the refusal takes out the
Expand Down
Loading
Loading