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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ mirrors skipped validation as success. `actions/queue-completion` notifies this
trusted reconciler from dispatched queue runs. Retain the caller's existing
`Queue completion callback` name and event guard.

After observing a queued bot PR, reconciliation waits up to 55 seconds for the
live front entry's validation ref. GitHub can acknowledge admission before that
ref exists; old refs do not satisfy readiness for a different queued commit.
Empty queues do not wait. Keep scheduled reconciliation as a backup for longer
GitHub delays; exhaustion emits a warning and never invents passing checks.

The queue fallback remains necessary with current `GITHUB_TOKEN` admission.
Replacing it requires an installed GitHub App and proof that app-authenticated
admission produces native merge-group checks. No app key is required for this
Expand Down
73 changes: 62 additions & 11 deletions scripts/reconcile-queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,20 @@ def graphql(query: str, **variables: str) -> dict[str, Any]:
return result["data"]


def admit(pr: dict[str, Any]) -> None:
"""Admit one eligible PR once its required checks pass."""
def admit(pr: dict[str, Any]) -> bool:
"""Admit one eligible PR once its required checks pass.

Returns:
Whether this trusted PR is now queued and may need a validation ref.

"""
trusted = pr["user"]["login"] == "dependabot[bot]" or (
REPOSITORY == "nix-forge/nixpkgs-personal"
and pr["user"]["login"] == "github-actions[bot]"
and pr["head"]["ref"] == "automation/package-updates"
)
if not trusted or pr["draft"] or pr["head"]["repo"]["full_name"] != REPOSITORY:
return
return False
number, sha = pr["number"], pr["head"]["sha"]
# Workflow and privileged automation updates require a human decision.
page = 1
Expand All @@ -81,7 +86,7 @@ def admit(pr: dict[str, Any]) -> None:
for item in files
):
print(f"PR #{number}: automation changes require maintainer review")
return
return False
if len(files) < PAGE_SIZE:
break
page += 1
Expand All @@ -90,13 +95,13 @@ def admit(pr: dict[str, Any]) -> None:
id=pr["node_id"],
)["node"]
if state["mergeQueueEntry"]:
return
return True
# Once admitted, a rejected head needs a fix or deliberate requeue.
# Never keep rebuilding the same failing merge group indefinitely.
statuses = api(f"repos/{REPOSITORY}/commits/{sha}/status")["statuses"]
if any(status["context"] == ADMISSION for status in statuses):
print(f"PR #{number}: already admitted this head; leave rejection for review")
return
return False
checks = subprocess.run(
[
GH,
Expand All @@ -119,13 +124,13 @@ def admit(pr: dict[str, Any]) -> None:
checks.check_returncode()
if checks.returncode in {1, 8}:
print(f"PR #{number}: required checks are not passing yet")
return
return False
checks.check_returncode()
required = json.loads(checks.stdout)
if not required or any(
check["bucket"] not in {"pass", "skipping"} for check in required
):
return
return False
try:
graphql(
"mutation($id:ID!,$sha:GitObjectID!) { enqueuePullRequest(input:"
Expand All @@ -138,7 +143,7 @@ def admit(pr: dict[str, Any]) -> None:
print(
f"PR #{number}: admission refused: {getattr(error, 'stderr', None) or str(error)}"
)
return
return False
api(
f"repos/{REPOSITORY}/statuses/{sha}",
"POST",
Expand All @@ -150,6 +155,8 @@ def admit(pr: dict[str, Any]) -> None:
)
print(f"PR #{number}: admitted {sha}")

return True


def wait_for_source_run(run_id: str) -> None:
"""Wait briefly for the dispatch callback's own workflow to finish.
Expand All @@ -171,6 +178,25 @@ def wait_for_source_run(run_id: str) -> None:
print(f"Source run {run_id} is still running; reconcile other ready entries")


def front_queue_entry() -> dict[str, Any] | None:
"""Read the live front entry without assuming the queue ref naming scheme.

Returns:
The entry, whose head may still be pending, or None for an empty queue.

"""
owner, name = REPOSITORY.split("/", 1)
repository = graphql(
"query($owner:String!,$name:String!) { repository(owner:$owner,name:$name) { "
'mergeQueue(branch:"main") { entries(first:1) { nodes { headCommit { oid } } } } } }',
owner=owner,
name=name,
)["repository"]
merge_queue = repository["mergeQueue"]
entries = merge_queue["entries"]["nodes"] if merge_queue else []
return entries[0] if entries else None


def main() -> None:
"""Reconcile open automation PRs, then start missing queue validation.

Expand All @@ -181,20 +207,45 @@ def main() -> None:
wait_for_source_run(os.environ.get("SOURCE_RUN_ID", ""))

# Pagination is bounded by GitHub's repository PR limit, not a waiting loop.
queue_expected = False
page = 1
while True:
pulls = api(
f"repos/{REPOSITORY}/pulls?state=open&base=main&per_page={PAGE_SIZE}&page={page}"
)
for pr in pulls:
admit(pr)
queue_expected = admit(pr) or queue_expected
if len(pulls) < PAGE_SIZE:
break
page += 1

# GITHUB_TOKEN enqueue events do not start merge_group workflows. Explicit
# dispatch is supported. Discover queue refs and validate their exact SHA.
refs = api(f"repos/{REPOSITORY}/git/matching-refs/heads/gh-readonly-queue/main/")
# Enqueue acknowledgement can precede ref creation. GITHUB_TOKEN will not
# trigger another workflow for us, and scheduled runs can be delayed.
for attempt in range(12):
refs = api(
f"repos/{REPOSITORY}/git/matching-refs/heads/gh-readonly-queue/main/"
)
if not queue_expected:
break
# Old refs can linger after a merge. Wait for the live front entry,
# not merely any ref in the queue namespace. PRs behind it wait for
# its completion callback rather than consuming another polling loop.
front = front_queue_entry()
if front is None:
refs = []
break
head = front["headCommit"]
if head and any(entry["object"]["sha"] == head["oid"] for entry in refs):
break
if attempt == 11:
print(
"::warning::Queued PR has no visible validation ref after 55 seconds; "
"a later reconciliation must retry discovery"
)
break
time.sleep(5)
for entry in refs:
try:
dispatch_entry(entry)
Expand Down
133 changes: 133 additions & 0 deletions tests/test_reconcile_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ def run_queue(self, check_code: int = 0) -> Any:
queue, "graphql", return_value={"node": {"mergeQueueEntry": None}}
) as graphql,
patch.object(queue.subprocess, "run", return_value=result),
patch.object(queue.time, "sleep"),
patch.object(
queue,
"front_queue_entry",
return_value={"headCommit": {"oid": "group"}},
),
):
queue.main()
return graphql
Expand Down Expand Up @@ -143,6 +149,82 @@ def test_admission_is_bound_to_reviewed_head(self) -> None:
self.assertEqual(graphql.call_args.kwargs, {"id": "PR_7", "sha": "head"})
self.assertEqual(self.writes[0][1]["context"], queue.ADMISSION)

def test_absent_queue_ref_wait_is_bounded(self) -> None:
"""A delayed or blocked queue must not keep the runner alive indefinitely."""
with patch.object(queue.time, "sleep") as sleep:
result = subprocess.CompletedProcess([], 0, '[{"bucket":"pass"}]')
with (
patch.object(queue, "api", side_effect=self.api) as api,
patch.object(
queue, "graphql", return_value={"node": {"mergeQueueEntry": None}}
),
patch.object(queue.subprocess, "run", return_value=result),
patch.object(
queue, "front_queue_entry", return_value={"headCommit": None}
),
):
queue.main()
self.assertEqual(sleep.call_count, 11)
self.assertEqual(
sum("matching-refs" in call.args[0] for call in api.call_args_list), 12
)
self.assertFalse(any(path.endswith("/dispatches") for path, _ in self.writes))

def test_empty_queue_does_not_wait(self) -> None:
"""Drafts and untrusted PRs do not justify polling for a queue ref."""
self.pr["draft"] = True
with (
patch.object(queue, "api", side_effect=self.api),
patch.object(queue.time, "sleep") as sleep,
):
queue.main()
sleep.assert_not_called()
self.assertEqual(self.writes, [])

def test_new_admission_waits_for_queue_ref_before_dispatch(self) -> None:
"""GitHub may acknowledge enqueue before publishing its validation ref."""
entry = {
"ref": "refs/heads/gh-readonly-queue/main/pr-7-base",
"object": {"sha": "group"},
}
reads = 0

def delayed_api(path: str, method: str = "GET", data: object = None) -> Any:
nonlocal reads
if "matching-refs" in path:
reads += 1
return [] if reads == 1 else [entry]
return self.api(path, method, data)

result = subprocess.CompletedProcess([], 0, '[{"bucket":"pass"}]')
with (
patch.object(queue, "api", side_effect=delayed_api),
patch.object(
queue, "graphql", return_value={"node": {"mergeQueueEntry": None}}
),
patch.object(queue.subprocess, "run", return_value=result),
patch.object(queue.time, "sleep"),
patch.object(
queue,
"front_queue_entry",
return_value={"headCommit": {"oid": "group"}},
),
):
queue.main()
dispatches = [
data for path, data in self.writes if path.endswith("/dispatches")
]
self.assertEqual(
dispatches,
[
{"ref": "gh-readonly-queue/main/pr-7-base"},
{
"ref": "gh-readonly-queue/main/pr-7-base",
"inputs": {"base_ref": "base", "head_ref": "group"},
},
],
)

def test_missing_merge_group_events_dispatch_exact_queue_commit(self) -> None:
"""Verify missing merge group events dispatch exact queue commit."""
self.pr["draft"] = True
Expand All @@ -159,6 +241,51 @@ def test_missing_merge_group_events_dispatch_exact_queue_commit(self) -> None:
self.writes[1][1]["inputs"], {"base_ref": "base", "head_ref": "group"}
)

def test_queue_removed_during_discovery_does_not_dispatch_stale_refs(self) -> None:
"""Queue cancellation should end discovery without launching obsolete work."""
self.refs = [
{"ref": "refs/heads/gh-readonly-queue/main/old", "object": {"sha": "old"}}
]
with (
patch.object(queue, "api", side_effect=self.api),
patch.object(queue, "admit", return_value=True),
patch.object(queue, "front_queue_entry", return_value=None),
patch.object(queue, "dispatch_entry") as dispatch,
patch.object(queue.time, "sleep") as sleep,
):
queue.main()
sleep.assert_not_called()
dispatch.assert_not_called()

def test_old_ref_does_not_hide_delayed_front_entry(self) -> None:
"""A lingering ref must not satisfy readiness for a different queue head."""
old = {"ref": "refs/heads/gh-readonly-queue/main/old", "object": {"sha": "old"}}
live = {
"ref": "refs/heads/gh-readonly-queue/main/live",
"object": {"sha": "group"},
}
reads = iter([[old], [old, live]])

def delayed_api(path: str, method: str = "GET", data: object = None) -> Any:
if "matching-refs" in path:
return next(reads)
return self.api(path, method, data)

with (
patch.object(queue, "api", side_effect=delayed_api),
patch.object(queue, "admit", return_value=True),
patch.object(
queue,
"front_queue_entry",
return_value={"headCommit": {"oid": "group"}},
),
patch.object(queue, "dispatch_entry") as dispatch,
patch.object(queue.time, "sleep") as sleep,
):
queue.main()
sleep.assert_called_once_with(5)
self.assertIn(unittest.mock.call(live), dispatch.call_args_list)

def test_existing_queue_runs_are_not_duplicated(self) -> None:
"""Verify existing queue runs are not duplicated."""
self.pr["draft"] = True
Expand Down Expand Up @@ -186,6 +313,12 @@ def test_admission_error_does_not_stop_dispatch(self) -> None:
],
),
patch.object(queue.subprocess, "run", return_value=result),
patch.object(queue.time, "sleep"),
patch.object(
queue,
"front_queue_entry",
return_value={"headCommit": {"oid": "group"}},
),
):
queue.main()
self.assertEqual(self.writes, [])
Expand Down
Loading