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
12 changes: 12 additions & 0 deletions docs/src/content/docs/contributing/integration-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,18 @@ python -m scripts.merge_queue.runner tick # one pass; state in ~/.apm-queue
python -m scripts.merge_queue.runner metrics # shadow summary from events.jsonl
```

Landing is off by default. `--land` (`scripts/merge_queue/landing.py`) also
admin-merges proven trains in launch order with
`gh pr merge --merge --admin --match-head-commit`. It does so only when main's
tree is the tree the member was proven on, and the merge commit must carry the
proven tree. Any drift, or a merge to main that the runner did not make, HALTs
landing and records the reason in `landing.json`; trains keep testing. Two
failed admin probes in a row pause landing until elevation returns.
Before merging, `closure.py` requires the issues GitHub will close
(`closingIssuesReferences` plus closing keywords in commit messages) to equal the
ticket's `fixes`; a mismatch ejects the train unmerged. After the merge it closes
any fix GitHub left open and retargets stacked PRs.

### Windows unit hang diagnostics

The Windows unit steps in `.github/workflows/build-release.yml` and the PR
Expand Down
5 changes: 5 additions & 0 deletions scripts/merge_queue/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ def get(self, path: str, params: Mapping[str, Any] | None = None) -> Any: ...

def post(self, path: str, body: Mapping[str, Any]) -> Response: ...

def patch(self, path: str, body: Mapping[str, Any]) -> Response: ...

def delete(self, path: str) -> Response: ...


Expand Down Expand Up @@ -79,5 +81,8 @@ def get(self, path: str, params: Mapping[str, Any] | None = None) -> Any:
def post(self, path: str, body: Mapping[str, Any]) -> Response:
return self._run(["-X", "POST", path, "--input", "-"], body)

def patch(self, path: str, body: Mapping[str, Any]) -> Response:
return self._run(["-X", "PATCH", path, "--input", "-"], body)

def delete(self, path: str) -> Response:
return self._run(["-X", "DELETE", path])
87 changes: 87 additions & 0 deletions scripts/merge_queue/closure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Closure audit: a landing closes exactly the issues its ticket fixes.

Before the merge, what GitHub will close (the PR's ``closingIssuesReferences`` plus
closing keywords in its commit messages) must equal the ticket's ``fixes``; a
mismatch ejects the train before anything merges. After the merge, the runner closes
any fix GitHub left open and retargets PRs stacked on the landed branch. Failed
writes stay pending and are retried on the next tick.
"""

from __future__ import annotations

import re
from dataclasses import dataclass

from scripts.merge_queue.api import REPO, Api, get_all

CLOSING_QUERY = (
"query($owner: String!, $name: String!, $pr: Int!) {"
" repository(owner: $owner, name: $name) { pullRequest(number: $pr) {"
" closingIssuesReferences(first: 50) { nodes { number } } } } }"
)
_KEYWORD = re.compile(r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+#(\d+)\b", re.IGNORECASE)
_OK = (200, 201, 204)


@dataclass(frozen=True)
class Audit:
pr: int
fixes: tuple[int, ...]
closing: tuple[int, ...]

@property
def missing(self) -> list[int]:
"""Declared fixes GitHub will not close."""
return sorted(set(self.fixes) - set(self.closing))

@property
def extra(self) -> list[int]:
"""Issues GitHub will close that the ticket does not fix."""
return sorted(set(self.closing) - set(self.fixes))

@property
def clean(self) -> bool:
return not self.missing and not self.extra


def closing_references(api: Api, pr: int) -> tuple[int, ...]:
"""Issues the merge will close: linked or body references, plus commit keywords."""
owner, name = REPO.split("/")
response = api.post(
"graphql",
{"query": CLOSING_QUERY, "variables": {"owner": owner, "name": name, "pr": pr}},
)
body = response.body if isinstance(response.body, dict) else {}
if response.status != 200 or body.get("errors") or not body.get("data"):
raise RuntimeError(f"closingIssuesReferences for #{pr} failed: {response.body}")
nodes = body["data"]["repository"]["pullRequest"]["closingIssuesReferences"]["nodes"]
numbers = {int(node["number"]) for node in nodes}
for commit in get_all(api, f"repos/{REPO}/pulls/{pr}/commits"):
numbers.update(int(n) for n in _KEYWORD.findall(commit["commit"]["message"]))
return tuple(sorted(numbers))


def audit(api: Api, pr: int, fixes: tuple[int, ...]) -> Audit:
return Audit(pr, tuple(sorted(fixes)), closing_references(api, pr))


def settle(api: Api, fixes: tuple[int, ...], head_branch: str) -> tuple[list[str], bool]:
"""After a clean merge: close fixes GitHub left open and retarget stacked PRs.

Returns the actions taken and whether every write succeeded.
"""
actions: list[str] = []
ok = True
for issue in fixes:
path = f"repos/{REPO}/issues/{issue}"
if api.get(path).get("state") == "closed":
continue
done = api.patch(path, {"state": "closed", "state_reason": "completed"}).status in _OK
actions.append(f"close #{issue}: {'ok' if done else 'failed'}")
ok = ok and done
for child in get_all(api, f"repos/{REPO}/pulls", {"state": "open", "base": head_branch}):
number = int(child["number"])
done = api.patch(f"repos/{REPO}/pulls/{number}", {"base": "main"}).status in _OK
actions.append(f"retarget #{number}: {'ok' if done else 'failed'}")
ok = ok and done
return actions, ok
Loading