Skip to content
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: minor
---

### Added

- Adoption: a person's pull request skips the `idle-hours` wait when a trusted person's merge-queue enqueue was removed for failed checks (owner decision Q-REQ (a)). GitHub must have seen that head on the branch by the enqueue and not since, and no person may have commented or reviewed since the enqueue. The pr-merge gate records `eligibility.adoption` as `requeue-after-ejection` and then applies every gate rule unchanged, the `merge.max-queue-ejections` cap included.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
bump: minor
---

### Added

- The pr-merge gate adopts a person's pull request without the `adoption.idle-hours` wait when a person put it in the merge queue and the queue removed it for failed checks with no head change since. Four conditions apply:
- the enqueue's `actor` and `enqueuer` ids must both be `kind: human` on the trusted-actor list;
- GitHub must have seen this head on the branch by the enqueue and not since (its newest GitHub Actions check suite on the PR's branch is no later than that enqueue);
- no person may have commented, reviewed or commented inline since the enqueue;
- an unreadable queue, check-suite listing or discussion keeps the idle rule.

The gate then re-enqueues the pull request under every existing rule, including the `merge.max-queue-ejections` cap and the head pin, and records `eligibility.adoption` as `requeue-after-ejection`. `read_merge_queue` reports that enqueue and the removal's time as `ejectedEnqueue`.
31 changes: 30 additions & 1 deletion docs/conventions/pr-pipeline/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -951,7 +951,9 @@ except six:
or submitted the newest review since that pin), a recent `updatedAt` does not refuse, since the
pin comment and the enqueue refresh it; any other comment or review, such as a request to
wait, refuses again, as does an unreadable one. The head commit test and every hold still
apply. The decision records it as `eligibility.adoption` (`idle-owner:<hours>h`);
apply. A person's merge-queue enqueue that the queue removed for failed checks also excuses
both idle tests ([Adoption](#adoption)). The decision records it as `eligibility.adoption`
(`idle-owner:<hours>h`, or `requeue-after-ejection`);
every other gate applies unchanged. Any other author refuses `not-lane-authored`, and an owner pull
request that is not adopted refuses `not-adopted:<reason>`. The candidate listing adds each
trusted actor's open pull requests by its login on the list.
Expand Down Expand Up @@ -2253,6 +2255,33 @@ person opened. A PR is adopted when all of these hold:
- for a person's PR, its last update (`updatedAt`) and its head commit's committer date are both
at least `idle-hours` old. Neither one alone is enough. An App's PR does not wait.

A person's PR also skips the wait when a person put it in the merge queue and the queue removed
it for failed checks (owner decision Q-REQ (a)). The person's enqueue of that head stands in for
the idle wait, and grants nothing beyond it. In pr-merge, `babysit_merge_policy.ejected_enqueue`
reads the enqueue from `read_merge_queue`, and `requeued_by_person` accepts it only when all of
these hold:

- the PR's newest merge-queue event is a `RemovedFromMergeQueueEvent` with reason
`failed_checks`, with no pushed commit or force push after it;
- the `AddedToMergeQueueEvent` that queued the removed entry has an `actor` and an `enqueuer`
whose ids are both `kind: human` on the trusted-actor list. Logins and GitHub types are not
read, because GitHub types an App's enqueuer as a `User`;
- GitHub had seen this head on the branch by the enqueue, and not since. That check reads the
newest `created_at` of GitHub Actions' check suites for the head commit on the PR's head
branch, which must be no later than the enqueue. GitHub sets it when a push arrives. A commit
dated in the past but pushed after the removal therefore does not pass, and neither does a head
that was reset away and pushed back;
- no person has commented, reviewed or commented inline since the enqueue, counting a comment
edited since then. The lanes App and bots do not count. A request to wait, made before or after
the run failed, therefore keeps the idle rule, as a comment after the lane's pin does for its
own queued entry.

The only newer queue event allowed is the lane's own entry at this head, as described in
[The pr-merge lane](#the-pr-merge-lane). Anything else, or anything unreadable, falls back to the
idle rule. The decision records `requeue-after-ejection`. The gate then runs unchanged: every
hold, the verifier verdict, the head pin, and the `merge.max-queue-ejections` cap. If the lane's
own retry is removed too, its enqueue is not a person's, so the PR waits `idle-hours`.

An adopted PR that closes no issue in this repository is judged against its own title and body
when a person (a `kind: human` id on the trusted list, not merely a GitHub `User`) opened it or
an App in `spec-from-body-apps` did (an App whose bodies a script writes): resolve-pr gives the verifier that text as the spec, the verdict records `intent:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2179,10 +2179,45 @@ def pull_request_landed(repo: str, number: int) -> dict[str, Any]:
"mergeQueueEntry{state position} autoMergeRequest{enabledAt} "
f"timelineItems(last:{merge_policy.MAX_QUEUE_EJECTIONS_LIMIT},itemTypes:["
"REMOVED_FROM_MERGE_QUEUE_EVENT,PULL_REQUEST_COMMIT,HEAD_REF_FORCE_PUSHED_EVENT])"
"{nodes{__typename ... on RemovedFromMergeQueueEvent{reason}}}}}}"
"{nodes{__typename ... on RemovedFromMergeQueueEvent{reason}}} "
"queueEvents:timelineItems(last:3,itemTypes:[ADDED_TO_MERGE_QUEUE_EVENT,"
"REMOVED_FROM_MERGE_QUEUE_EVENT,PULL_REQUEST_COMMIT,HEAD_REF_FORCE_PUSHED_EVENT])"
"{nodes{__typename ... on RemovedFromMergeQueueEvent{reason createdAt} "
"... on AddedToMergeQueueEvent{createdAt "
"actor{__typename ... on User{databaseId} ... on Bot{databaseId}} "
"enqueuer{login databaseId}}}}}}}"
)
# A head change: a pushed commit or a force push.
HEAD_CHANGES = ("PullRequestCommit", "HeadRefForcePushedEvent")
ADDED = "AddedToMergeQueueEvent"
REMOVED = "RemovedFromMergeQueueEvent"


def _ejected_enqueue(pr: dict[str, Any]) -> dict[str, Any] | None:
"""The enqueue whose entry the merge queue then removed for failed checks,
with no head change since, read from the newest queue events and head
changes (`queueEvents`, oldest first): `{"enqueue": that
AddedToMergeQueueEvent, "removedAt": the removal's time, "requeued":
whether one newer enqueue follows the removal}`. None for any other order,
a malformed item, or no such removal. Head changes sort as
`_failed_ejections` reads them."""
nodes = json_object(pr.get("queueEvents")).get("nodes")
if not is_json_array(nodes):
return None
newest = [json_object(node) for node in reversed(nodes)]
requeued = bool(newest) and newest[0].get("__typename") == ADDED
removal, enqueue = (newest[requeued:] + [{}, {}])[:2]
if (
removal.get("__typename") != REMOVED
or removal.get("reason") != "failed_checks"
or enqueue.get("__typename") != ADDED
):
return None
return {
"enqueue": enqueue,
"removedAt": removal.get("createdAt"),
"requeued": requeued,
}


def _failed_ejections(pr: dict[str, Any]) -> int | None:
Expand Down Expand Up @@ -2269,6 +2304,7 @@ def read_merge_queue(repo: str, number: int) -> dict[str, Any]:
"position": entry.get("position") if entry else None,
"failedEjections": _failed_ejections(pr),
"lastRemovalReason": _last_removal_reason(pr),
"ejectedEnqueue": _ejected_enqueue(pr),
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2581,6 +2581,122 @@ def lane_queued_at_head(
return False


# The adoption a person's ejected enqueue grants (`requeued_by_person`).
REQUEUE_ADOPTION = "requeue-after-ejection"
# The idle refusals a person's ejected enqueue may stand in for.
FRESH_REFUSALS = ("updated-fresh", "head-fresh")


def ejected_enqueue(repo: str, number: int) -> Any:
"""`babysit_merge.read_merge_queue`'s `ejectedEnqueue` for the pull
request, or None when the queue cannot be read."""
from babysit_merge import read_merge_queue # noqa: PLC0415 - import cycle

queue = read_merge_queue(repo, number)
return None if queue.get("readError") else queue.get("ejectedEnqueue")


def requeued_by_person(
ejected: Any,
*,
human_ids: Collection[int],
head_last_seen: Callable[[], Any],
queued_at_head: Callable[[], bool],
quiet_since: Callable[[datetime], bool],
) -> bool:
"""Whether a person's merge-queue enqueue of this head stands in for the
idle wait (owner decision Q-REQ (a)): `ejected` (`ejected_enqueue`) is the
enqueue whose entry the queue removed for failed checks with no head
change since; its actor and its enqueuer are both a kind human id on the
trusted list (`human_ids`; never a login or a GitHub type, since GitHub
types an App's enqueuer a User); no other enqueue followed but the lane's
own entry at this head (`queued_at_head`); GitHub had seen this head on
the branch by the enqueue and not since (`head_last_seen`,
`_head_last_seen`), so it is the head the person queued; and no person has
spoken since the enqueue (`quiet_since`, `_quiet_since`), so a request to
wait, made before or after the run failed, keeps the idle rule. Anything
unreadable is False."""
item = json_object(ejected)
enqueue = json_object(item.get("enqueue"))
ids = [
json_object(enqueue.get(who)).get("databaseId") for who in ("actor", "enqueuer")
]
if not all(type(i) is int and i in human_ids for i in ids):
return False
requeued = item.get("requeued")
if requeued is not False and not (requeued is True and queued_at_head()):
return False
try:
_time(item.get("removedAt")) # a removal with no readable time refuses
enqueued = _time(enqueue.get("createdAt"))
return _time(head_last_seen()) <= enqueued and quiet_since(enqueued)
except PolicyReadError:
return False


def _head_last_seen(owner: str, name: str, pr: Mapping[str, Any]) -> str:
"""When GitHub last saw the pull request's head commit arrive on its head
branch: the newest `created_at` of GitHub Actions' check suites for that
commit whose `head_branch` is the pull request's. GitHub sets it when a
push arrives, unlike a commit's dates, which the pusher sets, and a head
pushed again (reset away and pushed back) gets a newer suite. No such
suite, a listing past one page, or an unreadable one raises."""
head = json_object(pr.get("head"))
sha, ref = str(head.get("sha") or ""), head.get("ref")
if not SHA_RE.fullmatch(sha) or not isinstance(ref, str) or not ref:
raise PolicyReadError(f"head {sha!r} on {ref!r} unreadable")
status, payload = _get(
f"repos/{owner}/{name}/commits/{sha}/check-suites"
f"?app_id={ACTIONS_APP_ID}&per_page=100"
)
listing = json_object(payload)
suites = json_array(listing.get("check_suites"))
if status != 200 or listing.get("total_count") != len(suites):
raise PolicyReadError(f"head {sha} check suites unreadable (status {status})")
seen = [
json_object(s).get("created_at")
for s in suites
if json_object(s).get("head_branch") == ref
]
if not seen:
raise PolicyReadError(f"head {sha} has no check suite on {ref}")
return max(seen, key=_time)


def _discussion(owner: str, name: str, number: int) -> list[dict[str, Any]]:
"""Every comment, review and inline review comment on the pull request,
over REST."""
return [
item
for kind in ("issues/{n}/comments", "pulls/{n}/reviews", "pulls/{n}/comments")
for item in _paginated(
f"repos/{owner}/{name}/{kind.format(n=number)}?per_page=100",
f"#{number} {kind.split('/')[-1]}",
)
]


def _quiet_since(
owner: str, name: str, number: int, identity: str, since: datetime
) -> bool:
"""Whether no person has commented, reviewed or commented inline on the
pull request at or after `since`, by when it was created, edited or
submitted. The agent identity, automation accounts and bots do not count;
a person's item with no readable time does. An unreadable discussion
raises."""
skip = {_login_key(identity), *AUTOMATION_LOGINS}
for item in _discussion(owner, name, number):
author = _rest_actor(item.get("user"))
login = str((author or {}).get("login") or "")
if actor_kind({"author": author}) != "human" or _login_key(login) in skip:
continue
stamps = [item.get(k) for k in ("created_at", "updated_at", "submitted_at")]
stamps = [s for s in stamps if s]
if not stamps or any(_time(s) >= since for s in stamps):
return False
return True


def lane_eligibility(
repo: str,
number: int,
Expand All @@ -2596,12 +2712,15 @@ def lane_eligibility(
human_gated: str | None = None,
now: datetime | None = None,
queued_at_head: Callable[[], bool] = lambda: False,
adoption_human_ids: Collection[int] = (),
ejected_enqueue: Callable[[], Any] = lambda: None,
) -> Eligibility:
"""Whether the pr-merge lane may consider a pull request: not a fork or a
dependency manager's, opened by the agent identity or adopted
(`adoption_refusal`, with `adoption_idle_hours`, `adoption_owner_ids`,
the resolved `human_gated` label and `queued_at_head`; None or empty
adopts nothing),
adopts nothing; a refusal only for not being idle is excused by
`requeued_by_person` over `ejected_enqueue()` and `adoption_human_ids`),
exactly one linked
issue in this repository (`_linked_issue`; the verifier verdict binds to
it), and a diff
Expand All @@ -2627,9 +2746,10 @@ class `LANE_CLASS`; no `work-class:` label is read, but the linked issue
# Anyone could name an issue in `Closes #N`; only a pull request the
# lane opened, or one it adopted, counts.
if not _lane_authored(node, agent_identity):
committed = lambda: _head_committed(owner, name, pr) # noqa: E731
not_adopted = adoption_refusal(
pr,
lambda: _head_committed(owner, name, pr),
committed,
idle_hours=adoption_idle_hours,
owner_ids=adoption_owner_ids,
human_gated=human_gated,
Expand All @@ -2638,9 +2758,20 @@ class `LANE_CLASS`; no `work-class:` label is read, but the linked issue
)
if not_adopted == AUTHOR_NOT_OWNER:
return Eligibility(False, "not-lane-authored")
if not_adopted:
if not_adopted in FRESH_REFUSALS and requeued_by_person(
ejected_enqueue(),
human_ids=adoption_human_ids,
head_last_seen=lambda: _head_last_seen(owner, name, pr),
queued_at_head=queued_at_head,
quiet_since=lambda since: _quiet_since(
owner, name, number, str(agent_identity or ""), since
),
):
adoption = REQUEUE_ADOPTION
elif not_adopted:
return Eligibility(False, f"not-adopted:{not_adopted}")
adoption = f"idle-owner:{adoption_idle_hours}h"
else:
adoption = f"idle-owner:{adoption_idle_hours}h"
issue, refusal = _linked_issue(node, repo)
if refusal is None:
issue_number = issue["number"]
Expand Down Expand Up @@ -3361,16 +3492,8 @@ def _human_blockers(owner: str, name: str, number: int, identity: str) -> list[s
comment, and a stranger's text must not dequeue the identity's entry."""
from babysit_merge import HUMAN_MERGE_VETO_RE # noqa: PLC0415 - import cycle

corpus = [
item
for kind in ("issues/{n}/comments", "pulls/{n}/reviews", "pulls/{n}/comments")
for item in _paginated(
f"repos/{owner}/{name}/{kind.format(n=number)}?per_page=100",
f"#{number} {kind.split('/')[-1]}",
)
]
found = set()
for item in corpus:
for item in _discussion(owner, name, number):
author = _rest_actor(item.get("user"))
login = str((author or {}).get("login") or "")
if actor_kind({"author": author}) != "human" or _login_key(login) in {
Expand Down Expand Up @@ -4805,6 +4928,8 @@ def assess(
inputs["identity"],
str(json_object(pr.get("head")).get("sha") or ""),
),
adoption_human_ids=trusted[1],
ejected_enqueue=lambda: ejected_enqueue(repo, number),
**readers,
)
promoted = True
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,61 @@ def test_the_newest_removal_reason_is_read_until_a_head_change(self) -> None:
result = self._read(_queue(timeline=timeline))
self.assertEqual(result["lastRemovalReason"], expected)

def test_the_enqueue_a_failed_checks_removal_ended_is_read(self) -> None:
added = {
"__typename": "AddedToMergeQueueEvent",
"createdAt": "2026-10-25T16:59:28Z",
"actor": {"__typename": "User", "databaseId": 5},
"enqueuer": {"databaseId": 5},
}
lane = {**added, "actor": {"__typename": "Bot", "databaseId": 9}}
at = "2026-10-25T17:03:28Z"
out = {**_removed(), "createdAt": at}

def found(enqueue: dict[str, Any], requeued: bool = False) -> dict[str, Any]:
return {"enqueue": enqueue, "removedAt": at, "requeued": requeued}

for events, expected in (
([COMMIT, added, out], found(added)),
([added, out, lane], found(added, True)),
([added, _removed("merge_conflict")], None),
([added, _removed("manually_removed")], None),
([_removed(), added, _removed("merged")], None),
([added, _removed(), COMMIT], None),
([added, _removed(), FORCE_PUSH], None),
([added, COMMIT, _removed()], None),
# The lane's retry ejected: its own enqueue, which no person made.
(
[added, _removed(), lane, out],
found(lane),
),
([_removed()], None),
([added], None),
([], None),
([None, added, out], found(added)),
([added, None, _removed()], None),
(None, None),
):
with self.subTest(events=events):
payload = _queue()
pr = payload["data"]["repository"]["pullRequest"]
pr["queueEvents"] = None if events is None else {"nodes": events}
result = self._read(payload)
self.assertEqual(result["ejectedEnqueue"], expected)
# The extra read leaves the ejection count and removal reason alone.
payload = _queue(timeline=[COMMIT, _removed()])
payload["data"]["repository"]["pullRequest"]["queueEvents"] = {
"nodes": [added, _removed()]
}
result = self._read(payload)
self.assertEqual(
(result["failedEjections"], result["lastRemovalReason"]),
(1, "failed_checks"),
)
self.assertIn("ADDED_TO_MERGE_QUEUE_EVENT", merge.MERGE_QUEUE_QUERY)
queue_events = merge.MERGE_QUEUE_QUERY.split("queueEvents:", 1)[1]
self.assertIn("RemovedFromMergeQueueEvent{reason createdAt}", queue_events)

def test_failed_merge_group_runs_are_the_pull_requests_own(self) -> None:
runs = {
"workflow_runs": [
Expand Down
Loading
Loading