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
7 changes: 7 additions & 0 deletions .changes/source-control/perf-shared-reuse-binding-3c9e71a2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: patch
---

### Changed

- `babysit-prs` merge gate: `--postmerge-result` now reuses the run's shared post-merge answer when the default branch moved or the pull request's base has an older pipeline config, as long as the facts the answer depends on still hold. The base must give the same post-merge floor (read from its own config history when its newest config commit differs), and no merge the check would judge may have landed since the floor beyond those in the answer. When the answer reports no demotion, one REST call lists the issues updated since it was computed, and any issue a demotion-record filer opened, or any known record, refuses it as `demotion-changed`; before this, a record filed during the run went unseen. A new lane merge, a different floor, or an unreadable merge history still makes the pull request read its own. The skip reasons `main-moved` and `config-differs` become `new-merge:#N`, `merged-unreadable`, `merged-history-truncated` and `floor-differs`.
5 changes: 3 additions & 2 deletions .github/workflows/pr-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,9 @@ jobs:
# at PRs this lane put in the merge queue itself; merges by a person or
# by another App (a release PR, say) are not the lane's to check.
# It runs before the gate, which reuses its answer for every candidate
# while main's head and config are unchanged (--postmerge-result); a PR
# that merges during the run is in the gate's own `dispatch` output.
# whose base has the same floor while no lane merge has landed since
# (--postmerge-result); a PR that merges during the run is in the
# gate's own `dispatch` output.
- name: Check earlier lane merges
id: post-merge
if: steps.lane-token.outputs.token != ''
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3588,8 +3588,9 @@ def main() -> int:
help=(
"with --authority pr-merge, this run's babysit_postmerge.py report: "
"its demotion, floor and post-merge verdict stand in for this pull "
"request's own reads when bound to the current default-branch head "
"and config; unreadable or unbound, they are read as without it"
"request's own reads when its base has the same floor and no merge "
"the check would judge landed since; unreadable or unbound, they "
"are read as without it"
),
)
args = parser.parse_args()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2540,6 +2540,8 @@ class PostMergeGate:

# How old a shared post-merge answer may be: the pr-merge job's timeout.
SHARED_MAX_AGE = timedelta(minutes=30)
# Runner clocks may run ahead of GitHub's; `since` starts this much earlier.
SINCE_CLOCK_MARGIN = timedelta(minutes=5)


@dataclass(frozen=True)
Expand Down Expand Up @@ -2585,6 +2587,36 @@ def newest_config_commit(repo: str, sha: str) -> str:
return newest


def _demotion_changed(
owner: str, name: str, shared: SharedPostMerge, identity: str
) -> bool:
"""Whether anything `read_demotion` reads may differ from the shared
answer, in one REST call: an issue updated since the answer was computed
(which precedes its demotion read), less `SINCE_CLOCK_MARGIN`, that a
record filer opened, or that is a known record. Creating, editing,
closing or reopening an issue updates it, so no new or changed record
escapes. A full page or an unreadable
one counts as changed."""
since = (
(shared.computed_at - SINCE_CLOCK_MARGIN)
.astimezone(UTC)
.strftime("%Y-%m-%dT%H:%M:%SZ")
)
status, issues = _get(
f"repos/{owner}/{name}/issues?state=all&since={since}&per_page=100"
)
if status != 200 or not is_json_array(issues) or len(issues) >= 100:
return True
filers = {_login_key(DEMOTION_FILER), _login_key(identity)}
for issue in map(json_object, issues):
if "pull_request" in issue:
continue
author = _login_key(json_object(issue.get("user")).get("login"))
if author in filers or issue.get("number") in shared.demotion.records:
return True
return False


def shared_refusal(
repo: str,
shared: SharedPostMerge,
Expand All @@ -2594,12 +2626,23 @@ def shared_refusal(
identity: str,
self_logins: Collection[str],
lane: bool,
authority: str | None = None,
now: datetime | None = None,
) -> str | None:
"""Why `shared` may not stand in for this pull request's own reads, or
None: it must name the same identity, self logins and lane, be no older
than `SHARED_MAX_AGE`, have been computed at `branch`'s current head, and
share this base's newest pipeline-config commit (so the same floor)."""
than `SHARED_MAX_AGE`, have no demotion record filed or changed since
(`_demotion_changed`), give this base the floor its own read would
(`merged_since_floor` with the shared demotion), and judge every merge
the post-merge check would judge now.

The check judges `branch` from the floor, never the base, so the answer
holds for any base with that floor. A newer default-branch head changes
the answer only through a merge the check counts (`derive_auto_merge`);
one that is not in the answer makes this pull request read its own.
Later runs on already-counted merges are not re-read: an unverified one
still refuses through `in_flight`, and a verified one counts no run
created after it verified."""
age = (now or datetime.now(UTC)) - shared.computed_at
owner, name = _split_repo(repo)
checks = (
Expand All @@ -2615,15 +2658,44 @@ def shared_refusal(
refusal = next((text for refused, text in checks if refused), None)
if refusal:
return refusal
if not shared.demotion.active and _demotion_changed(owner, name, shared, identity):
return "demotion-changed"
try:
# The same newest config commit is the same floor; any other base
# walks its own config history to the floor it would read.
if newest_config_commit(
repo, base_sha
) != shared.config_sha and shared.floor != merged_since_floor(
repo, base_sha, shared.demotion, authority
):
return "floor-differs"
except PolicyReadError:
return "config-unreadable"
status, payload = _get(f"repos/{owner}/{name}/commits/{quote(branch, safe='')}")
head = payload.get("sha") if status == 200 and is_json_object(payload) else None
if head != shared.main_sha:
return "main-moved"
if head == shared.main_sha:
return None
counted = {
json_object(m).get("number")
for m in json_array(shared.gate.report.get("autoMerges"))
}
try:
if newest_config_commit(repo, base_sha) != shared.config_sha:
return "config-differs"
merges = _merged_since(owner, name, branch, shared.floor)
if merges is None:
return "merged-history-truncated"
for pr in merges:
# Treating no actor as human counts a superset of the check's
# merges, so no merge it would judge is missed.
merge = derive_auto_merge(
pr,
lambda actor: False,
identity,
lane_merges_only=shared.lane_merges_only,
)
if isinstance(merge, AutoMerge) and merge.number not in counted:
return f"new-merge:#{merge.number}"
except PolicyReadError:
return "config-unreadable"
return "merged-unreadable"
return None


Expand Down Expand Up @@ -2749,6 +2821,7 @@ def assess(
identity=resolved.login,
self_logins=self_logins,
lane=lane,
authority=authority,
)
details["postMergeShared"] = f"unused:{unusable}" if unusable else "used"
reuse = None if unusable else shared
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2958,16 +2958,26 @@ def bound(self) -> GhFake:
gh = self.readable()
gh.rest[f"repos/{REPO}/commits/trunk"] = {"sha": MAIN_SHA}
gh.rest[NEWEST_CONFIG] = [{"sha": CONFIG_SHA}]
self.computed_at = policy.datetime.now(policy.UTC)
gh.rest[self.issues_since()] = []
return gh

def issues_since(self) -> str:
"""The demotion re-read: issues updated since the answer, to the
second GitHub's `since` takes, less the clock margin."""
since = (self.computed_at - policy.SINCE_CLOCK_MARGIN).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
return f"repos/{REPO}/issues?state=all&since={since}&per_page=100"

def shared(self, gate_: policy.PostMergeGate, **overrides: Any) -> Any:
fields: dict[str, Any] = {
"main_sha": MAIN_SHA,
"config_sha": CONFIG_SHA,
"identity": IDENTITY,
"self_logins": frozenset(),
"lane_merges_only": True,
"computed_at": policy.datetime.now(policy.UTC),
"computed_at": self.computed_at,
"demotion": policy.Demotion(False, None, ()),
"floor": policy.datetime.fromisoformat(ENABLED_AT),
"gate": gate_,
Expand Down Expand Up @@ -3017,21 +3027,161 @@ def test_a_bound_answer_decides_as_the_fresh_reads_do(self) -> None:
if answer.refusal is None:
self.assertIs(flight.call_args.kwargs["verified"], verified)

def moved(self, merges: Any) -> GhFake:
"""Bound, but the default branch moved to a head that merged
`merges` (a PolicyRecentMerges answer) since the floor."""
gh = self.bound()
gh.rest[f"repos/{REPO}/commits/trunk"] = {"sha": "f" * 40}
gh.graphql["PolicyRecentMerges"] = merges
return gh

def test_a_moved_head_with_no_new_lane_merge_decides_as_the_fresh_reads_do(
self,
) -> None:
# The check judges only the identity's merges since the floor, so a
# person's merge, another App's, or one already in the answer moves
# the head without changing the answer.
counted = policy.PostMergeGate(
None, {"ok": True, "autoMerges": [{"number": 7}]}, lambda m: True
)
merges = merge_pages(
[
[
merged(9, user(OPERATOR), user(OPERATOR)),
merged(8, bot("release"), bot("release")),
merged(7, bot("agent-lanes"), None),
]
]
)
for head in ({"sha": "f" * 40}, 502):
with self.subTest(head=head):
self.moved(merges)
self.flight()
fresh = self.lane_assess(post_merge=lambda floor, who: counted)
gh = self.moved(merges)
gh.rest[f"repos/{REPO}/commits/trunk"] = head
self.flight()
never = mock.Mock(side_effect=AssertionError("read fresh"))
with mock.patch.object(policy, "read_demotion", never):
reused = self.lane_assess(
post_merge=never, shared=self.shared(counted)
)
self.assertEqual(reused.details["postMergeShared"], "used")
self.assertEqual(self.decided(reused), self.decided(fresh))

def test_a_base_behind_with_the_same_floor_decides_as_the_fresh_reads_do(
self,
) -> None:
# A later config commit on the default branch that keeps the path
# enabled leaves the floor where the base's own history puts it.
answer = gate("failure:canary#7708")
self.bound().rest[NEWEST_CONFIG] = [{"sha": "f" * 40}]
self.flight()
fresh = self.lane_assess(post_merge=lambda floor, who: answer)
self.bound().rest[NEWEST_CONFIG] = [{"sha": "f" * 40}]
self.flight()
never = mock.Mock(side_effect=AssertionError("read fresh"))
with mock.patch.object(policy, "read_demotion", never):
reused = self.lane_assess(post_merge=never, shared=self.shared(answer))
self.assertEqual(reused.details["postMergeShared"], "used")
self.assertEqual(self.decided(reused), self.decided(fresh))

def test_a_demotion_record_filed_since_the_answer_is_not_missed(self) -> None:
# The answer says not demoted; a record opened after it, an edit or
# close of a known record, an unreadable re-read, or a full page
# sends the pull request to its own demotion read.
record = {
"number": 90,
"user": {"login": "github-actions[bot]"},
"body": DEMOTION_BODY,
"state": "open",
}
known = {"number": 12, "user": {"login": OPERATOR}, "state": "closed"}
full = [
{"number": 1000 + n, "user": {"login": OPERATOR}, "state": "open"}
for n in range(100)
]
for issues, records in (
([record], ()),
([known], (12,)),
(502, ()),
(full, ()),
):
with self.subTest(issues=issues):
gh = self.bound()
gh.rest[self.issues_since()] = issues
self.flight()
reads = mock.Mock(wraps=policy.read_demotion)
seen: list[Any] = []
with mock.patch.object(policy, "read_demotion", reads):
result = self.lane_assess(
post_merge=lambda floor, who: seen.append(floor) or gate(),
shared=self.shared(
gate("failure:canary#1"),
demotion=policy.Demotion(False, None, records),
),
)
self.assertEqual(
result.details["postMergeShared"], "unused:demotion-changed"
)
reads.assert_called_once()
self.assertEqual(seen, [policy.datetime.fromisoformat(ENABLED_AT)])

def test_an_unrelated_issue_or_a_pull_request_leaves_the_answer_bound(
self,
) -> None:
gh = self.bound()
gh.rest[self.issues_since()] = [
{"number": 91, "user": {"login": OPERATOR}, "state": "open"},
{"number": 92, "user": {"login": IDENTITY}, "pull_request": {}},
]
self.flight()
never = mock.Mock(side_effect=AssertionError("read fresh"))
result = self.lane_assess(post_merge=never, shared=self.shared(gate()))
self.assertEqual(result.details["postMergeShared"], "used")

def test_a_demoted_answer_needs_no_re_read(self) -> None:
# Already demoted, the answer is the conservative one.
gh = self.bound()
del gh.rest[self.issues_since()]
self.flight()
demoted = policy.Demotion(True, "#5 open", (5,))
result = self.lane_assess(
post_merge=mock.Mock(side_effect=AssertionError("read fresh")),
shared=self.shared(gate(), demotion=demoted),
)
self.assertEqual(result.details["postMergeShared"], "used")

def test_an_unbound_answer_is_not_used(self) -> None:
late = policy.datetime.now(policy.UTC) - policy.timedelta(minutes=31)
for overrides, rest, reason in (
({}, {f"repos/{REPO}/commits/trunk": {"sha": "f" * 40}}, "main-moved"),
({}, {f"repos/{REPO}/commits/trunk": 502}, "main-moved"),
({}, {NEWEST_CONFIG: [{"sha": "f" * 40}]}, "config-differs"),
({}, {NEWEST_CONFIG: 404}, "config-unreadable"),
({"identity": "other[bot]"}, {}, "identity-differs"),
({"self_logins": frozenset({"x[bot]"})}, {}, "self-logins-differ"),
({"lane_merges_only": False}, {}, "lane-differs"),
({"computed_at": late}, {}, "stale"),
other_floor = policy.datetime.fromisoformat("2026-10-11T00:00:00Z")
lane_merge = merge_pages([[merged(7, bot("agent-lanes"), None)]])
moved = {f"repos/{REPO}/commits/trunk": {"sha": "f" * 40}}
for overrides, rest, graphql, reason in (
({}, moved, {"PolicyRecentMerges": lane_merge}, "new-merge:#7"),
({}, moved, {"PolicyRecentMerges": 502}, "merged-unreadable"),
(
{},
moved,
{"PolicyRecentMerges": merge_pages([[]], endless=True)},
"merged-history-truncated",
),
(
{"floor": other_floor},
{NEWEST_CONFIG: [{"sha": "f" * 40}]},
{},
"floor-differs",
),
({}, {NEWEST_CONFIG: 404}, {}, "config-unreadable"),
({"identity": "other[bot]"}, {}, {}, "identity-differs"),
({"self_logins": frozenset({"x[bot]"})}, {}, {}, "self-logins-differ"),
({"lane_merges_only": False}, {}, {}, "lane-differs"),
({"computed_at": late}, {}, {}, "stale"),
):
with self.subTest(reason=reason, rest=rest):
gh = self.bound()
gh.rest.update(rest)
gh.graphql.update(graphql)
self.flight()
seen: list[Any] = []
shared = self.shared(gate("failure:canary#1"), **overrides)
Expand Down
Loading