diff --git a/.github/merge-gate/gate.py b/.github/merge-gate/gate.py deleted file mode 100644 index 84b7ded22f84..000000000000 --- a/.github/merge-gate/gate.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env python3 -"""merge-gate: merge-safety decisions from Garnet execution behavior, at the PR gate. - -Runs in GitHub Actions. Triggered when garnet-runtime-review[bot] posts a -Runtime Review comment on a PR (or manually via workflow_dispatch). - -Reads the execution profile from the Runtime Review comment, infers PR type -from changed files, evaluates v1 merge-safety assertions, posts MERGE / HOLD / -AUDIT / UNDETERMINABLE as one PR comment, updated in place on every new record. -Fails closed: a record that is not finalized, not bound to the PR head, or not -declared complete is UNDETERMINABLE, never MERGE. - -v1 policy scope: dependency PRs (manifest/lockfile-only changes). -""" -import json -import os -import re -import subprocess -import sys - -MARKER = "" -BOT = "garnet-runtime-review[bot]" - -DEST_RULES = [ - (r"^registry\.npmjs\.org$", "package registry", "ok"), - (r"^npmjs\.org$", "package registry", "ok"), - (r".*\.npmjs\.org$", "package registry", "ok"), - (r"^registry\.yarnpkg\.com$", "package registry", "ok"), - (r"^nodejs\.org$", "toolchain download", "ok"), - (r"^github\.com$", "source host", "ok"), - (r"^codeload\.github\.com$", "source host", "ok"), - (r"^release-assets\.githubusercontent\.com$", "release assets", "ok"), - (r"^objects\.githubusercontent\.com$", "release assets", "ok"), - (r"^api\.github\.com$", "CI api", "ok"), - (r".*\.ubuntu\.com$", "os updates", "infra"), - (r".*\.microsoft\.com$", "runner infra", "infra"), - (r".*\.windows\.net$", "runner infra", "infra"), - (r"^storage\.googleapis\.com$", "runner infra", "infra"), - (r"^169\.254\.169\.254$", "cloud metadata", "infra"), - (r"^168\.63\.129\.16$", "cloud metadata", "infra"), - (r"^localhost$", "local resolver", "infra"), - (r"^ip6-allrouters$", "local network", "infra"), - (r"^\d+\.\d+\.\d+\.\d+$", "raw ip", "review"), - (r".*\.github\.com$", "github infra", "infra"), -] -INFRA_PROCS = re.compile(r"hosted-compute|systemd|python3", re.I) -SUSPICIOUS_PROCS = re.compile( - r"(curl|wget).*(sh|bash)|chmod\s+\+x|/tmp/.*(exec|run)|\.sh\s*$", re.I -) - - -def gh(method, path, fields=None): - cmd = ["gh", "api", "-X", method, path] - for k, v in (fields or {}).items(): - cmd += ["-f", f"{k}={v}"] - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode != 0: - raise RuntimeError(f"gh api {method} {path}: {r.stderr[:300]}") - return json.loads(r.stdout) if r.stdout.strip() else {} - - -def classify(domain, chain=()): - if any(INFRA_PROCS.search(p) for p in chain): - return "runner infra", "infra" - d = domain.replace("[.]", ".") - for pat, cat, verdict in DEST_RULES: - if re.match(pat, d): - return cat, verdict - return "unknown", "review" - - -def parse_profile(body): - m = re.search(r"garnet:summary (\{.*?\}) -->", body) - summary = json.loads(m.group(1)) if m else {} - pre = re.search(r"
(.*?)", body, re.S) - tree = pre.group(1) if pre else "" - dests, stack, step_ctx = [], [], "" - for line in tree.split("\n"): - sm = re.search(r"\(step:\s*"([^&]+)"\)", line) - if sm: - step_ctx = sm.group(1) - pm = re.search(r"([^<]+)", line) - if pm and "○" not in line: - indent = len(line) - len(line.lstrip(" │├└─")) - while stack and stack[-1][0] >= indent: - stack.pop() - stack.append((indent, pm.group(1))) - dm = re.search(r"○\s+([a-z0-9\.\-\[\]]+)", line) - if dm: - dests.append({ - "domain": dm.group(1).replace("[.]", "."), - "chain": [p for _, p in stack], - "step": step_ctx, - }) - seen, uniq = set(), [] - for d in dests: - if d["domain"] not in seen: - seen.add(d["domain"]) - uniq.append(d) - return {"summary": summary, "destinations": uniq} - - -def pr_type(owner, repo, pr): - files = gh("GET", f"/repos/{owner}/{repo}/pulls/{pr}/files?per_page=100") - names = [f["filename"] for f in files] - if not names: - return "empty" - if all(re.search( - r"(package\.json|pnpm-lock\.yaml|yarn\.lock|package-lock\.json|pnpm-workspace\.yaml)$", n - ) for n in names): - return "dependency" - if all("test" in n or "e2e" in n for n in names): - return "test" - return "general" - - -def evaluate(profile, ptype): - findings = [] - dests, summary = profile["destinations"], profile["summary"] - if not dests: - return [("hold", "No execution destinations recorded — nothing to judge.")] - for d in dests: - cat, verdict = classify(d["domain"], d["chain"]) - chain = " → ".join(d["chain"][-3:]) if d["chain"] else "?" - if verdict == "review": - findings.append(("hold", - f"Unknown destination `{d['domain']}` ({cat}) reached via {chain}" - + (f" during step \"{d['step']}\"" if d["step"] else "") + ".")) - for d in dests: - if SUSPICIOUS_PROCS.search(" ".join(d["chain"])): - findings.append(("hold", - f"Suspicious execution pattern in chain: {' '.join(d['chain'])}.")) - return findings - - -def evidence_gaps(summary, head): - gaps = [] - if summary.get("status") != "finalized": - gaps.append(f"record status is `{summary.get('status', 'missing')}`, not finalized") - if summary.get("commit") != head: - gaps.append(f"record is bound to `{str(summary.get('commit', 'missing'))[:12]}`, not the PR head `{head[:12]}`") - if summary.get("capture_quality") != "complete": - gaps.append(f"capture is `{summary.get('capture_quality', 'undeclared')}`, not declared complete") - incomplete = summary.get("incomplete") - if not isinstance(incomplete, int) or incomplete > 0: - gaps.append(f"{incomplete if isinstance(incomplete, int) else 'unknown'} job(s) recorded incompletely") - return gaps - - -def decide(findings, ptype, gaps=()): - holds = [t for s, t in findings if s == "hold"] - if holds: - return ("HOLD" if ptype == "dependency" else "AUDIT"), holds, list(gaps) - if gaps: - return "UNDETERMINABLE", [], list(gaps) - if ptype != "dependency": - return "AUDIT", holds, [] - return ("HOLD", holds, []) if holds else ("MERGE", [], []) - - -def render(profile, ptype, decision, holds, gaps, head): - s = profile["summary"] - jobs = s.get("jobs") - dests = s.get("destinations") - lines = [MARKER, f"## Merge gate: **{decision}**", "", - f"Head `{head[:12]}` · {jobs if isinstance(jobs, int) else 'unknown'} jobs · " - f"{dests if isinstance(dests, int) else len(profile['destinations'])} destinations · " - f"recorded {s.get('recorded', 'time unknown')}.", - f"PR type inferred from changed files: **{ptype}**.", ""] - if gaps: - lines += ["Evidence gaps (no MERGE until these clear):", ""] - lines += [f"- {g}" for g in gaps] + [""] - if decision == "UNDETERMINABLE": - lines += ["No destination needs review, but the record is not complete enough to call this safe.", ""] - elif decision == "MERGE": - lines += ["Every observed destination classifies as expected package/CI " - "infrastructure. Nothing in the execution behavior contradicts the diff.", ""] - elif decision == "AUDIT": - lines += ["v1 policy is scoped to dependency PRs, so this is an audit, not a verdict. " - "Destinations outside the dependency allowlist:", ""] - lines += [f"- {h}" for h in holds] + [""] - else: - lines += ["### Findings requiring review", ""] - lines += [f"- {h}" for h in holds] + [""] - lines += ["_Garnet reports; the reviewer decides._"] - return "\n".join(lines) - - -def main(): - owner_repo, pr = sys.argv[1], sys.argv[2] - owner, repo = owner_repo.split("/") - head = gh("GET", f"/repos/{owner}/{repo}/pulls/{pr}")["head"]["sha"] - comments = gh("GET", f"/repos/{owner}/{repo}/issues/{pr}/comments?per_page=100") - reviews = [c["body"] for c in comments if c["user"]["login"] == BOT and "garnet:summary" in c["body"]] - if not reviews: - print("no Runtime Review comment found; skipping") - return - profile = parse_profile(reviews[-1]) - ptype = pr_type(owner, repo, pr) - gaps = evidence_gaps(profile["summary"], head) - decision, holds, gaps = decide(evaluate(profile, ptype), ptype, gaps) - body = render(profile, ptype, decision, holds, gaps, head) - mine = [c for c in comments if MARKER in c["body"]] - if mine: - if mine[-1]["body"] == body: - print("gate comment already current") - return - gh("PATCH", f"/repos/{owner}/{repo}/issues/comments/{mine[-1]['id']}", {"body": body}) - else: - gh("POST", f"/repos/{owner}/{repo}/issues/{pr}/comments", {"body": body}) - print(f"{decision} for {owner_repo}#{pr} at {head[:12]}") - - -if __name__ == "__main__": - main() diff --git a/.github/scripts/shadow_mirror/mirror.py b/.github/scripts/shadow_mirror/mirror.py new file mode 100644 index 000000000000..b1d96217f67e --- /dev/null +++ b/.github/scripts/shadow_mirror/mirror.py @@ -0,0 +1,445 @@ +"""Replay upstream dependencies with isolated Garnet recording.""" + +import argparse +import base64 +import datetime +import hashlib +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +FORK = "garnet-labs/sentry-javascript" +SOURCE = "getsentry/sentry-javascript" +BRANCH = "develop" +LOOKBACK_DAYS = 10 +WORKFLOW = "garnet-record.yml" +MARKER = re.compile( + r"" +) +DEPENDENCY_BOTS = {"dependabot[bot]": 49699333, "renovate[bot]": 29139614} +ROOT_INPUTS = {"package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".npmrc"} +WORKSPACE_ROOTS = {"packages", "dev-packages"} +CI_SKIP = re.compile( + r"\[(skip ci|ci skip|no ci|skip actions|actions skip)\]", re.IGNORECASE +) +DISCOVERY = """ +query ($search: String!, $cursor: String) { + search(query: $search, type: ISSUE, first: 50, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { ... on PullRequest { number } } + } +} +""" +class APIError(RuntimeError): + def __init__(self, method, path, status, detail): + super().__init__(f"{method} {path}: HTTP {status}: {detail}") + self.status = status + + +class API: + def __init__(self, token, dry_run): + self.token = token + self.dry_run = dry_run + + def call(self, repo, path, method="GET", data=None): + if method != "GET" and (self.dry_run or repo != FORK): + raise ValueError("Only live writes to the mirror repository are allowed") + return self._request(f"repos/{repo}/{path}", method, data) + + def _request(self, path, method, data): + request = urllib.request.Request( + f"https://api.github.com/{path}", + data=json.dumps(data).encode() if data is not None else None, + headers={ + "Authorization": f"Bearer {self.token}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "Content-Type": "application/json", + }, + method=method, + ) + try: + with urllib.request.urlopen(request, timeout=60) as response: + raw = response.read() + return json.loads(raw) if raw else None + except urllib.error.HTTPError as error: + raise APIError(method, path, error.code, error.read().decode()) from error + + def pages(self, repo, path): + separator = "&" if "?" in path else "?" + for page in range(1, 1000): + items = self.call(repo, f"{path}{separator}per_page=100&page={page}") + yield from items + if len(items) < 100: + return + raise RuntimeError(f"Pagination limit reached: {path}") + + def write(self, path, data, method="POST"): + return self.call(FORK, path, method, data) + + def dependency_candidates(self, now=None): + since = (now or datetime.datetime.now(datetime.timezone.utc)) - datetime.timedelta( + days=LOOKBACK_DAYS + ) + authors = " ".join( + f"author:app/{login.removesuffix('[bot]')}" for login in DEPENDENCY_BOTS + ) + for scope in ("is:open", f"is:merged merged:>={since:%Y-%m-%dT%H:%M:%SZ}"): + cursor = None + while True: + search = f"repo:{SOURCE} is:pr {scope} {authors}" + result = self._request( + "graphql", + "POST", + {"query": DISCOVERY, "variables": {"search": search, "cursor": cursor}}, + ) + if result.get("errors"): + raise RuntimeError(f'GitHub discovery: {result["errors"]}') + page = result["data"]["search"] + yield from (pr["number"] for pr in page["nodes"] if pr) + if not page["pageInfo"]["hasNextPage"]: + break + cursor = page["pageInfo"]["endCursor"] + + +def dependency_file(path): + parts = path.split("/") + return path in ROOT_INPUTS or ( + len(parts) == 3 and parts[0] in WORKSPACE_ROOTS and parts[2] == "package.json" + ) + + +def dependency_bot(pr): + author = pr.get("user") or {} + return ( + DEPENDENCY_BOTS.get(author.get("login")) == author.get("id") + and author.get("type") == "Bot" + and ((pr.get("head") or {}).get("repo") or {}).get("full_name") == SOURCE + ) + + +def is_dependency_pr(pr, files): + if not files or pr["changed_files"] != len(files) or not dependency_bot(pr): + return False + return any( + dependency_file(file["filename"]) + or dependency_file(file.get("previous_filename", "")) + for file in files + ) + + +def recently_merged(pr, now=None): + if not pr.get("merged_at"): + return False + merged = datetime.datetime.fromisoformat(pr["merged_at"].replace("Z", "+00:00")) + now = now or datetime.datetime.now(datetime.timezone.utc) + return now - merged <= datetime.timedelta(days=LOOKBACK_DAYS) + + +def scrub_title(title): + title = re.sub(r"https?://\S+|www\.\S+|#\d+", "", title) + title = re.sub(re.escape(SOURCE), "", title, flags=re.IGNORECASE) + title = re.sub(r"(? 1 else "" + base_ref = f"shadow/base/{number}{suffix}" + head_ref = f"shadow/pr/{number}{suffix}" + existing = history.get(revision) + baseline = self.get_ref(base_ref) + if (existing and (existing["state"] != "open" or not baseline)) or ( + baseline + and api.call(FORK, f"git/commits/{baseline}")["message"] + != baseline_message + ): + revision += 1 + else: + break + + if existing and MARKER.search(existing["body"]).groups()[1:] == ( + upstream_head, + upstream_base, + ): + self.close(history, "superseded", keep=existing["number"]) + return { + "status": "unchanged", + "url": existing["html_url"], + } + + if not baseline: + baseline = self.commit(self.tree(upstream_base), [], baseline_message) + self.create_ref(base_ref, baseline) + if not self.baseline_started(base_ref, baseline): + return {"status": "baseline pending", "base_ref": base_ref} + + parent = self.get_ref(head_ref) + tree = self.tree(upstream_head) + title = scrub_title(pr["title"]) + if parent and api.call(FORK, f"git/commits/{parent}")["tree"]["sha"] == tree: + head = parent + else: + head = self.commit(tree, [parent or baseline], title) + if parent: + api.write( + f"git/refs/heads/{head_ref}", {"sha": head, "force": False}, "PATCH" + ) + else: + self.create_ref(head_ref, head) + + names = ( + " " + + json.dumps(file["filename"], ensure_ascii=False).replace("<", r"\u003c") + for file in files + ) + body = "\n".join( + [ + "Source files changed (only the Garnet recorder is retained under `.github/workflows`):", + "", + *names, + "", + f"Mirror base `{baseline}` → head `{head}`", + "", + f"", + ] + ) + data = {"title": title, "body": body} + if existing: + result = api.write(f'pulls/{existing["number"]}', data, "PATCH") + else: + result = api.write( + "pulls", {**data, "head": head_ref, "base": base_ref} + ) + self.close(history, "superseded", keep=result["number"]) + return { + "status": "updated" if existing else "created", + "url": result["html_url"], + } + + def get_ref(self, name): + try: + return self.api.call(FORK, f"git/ref/heads/{name}")["object"]["sha"] + except APIError as error: + if error.status != 404: + raise + return None + + def create_ref(self, name, sha): + self.api.write("git/refs", {"ref": f"refs/heads/{name}", "sha": sha}) + + def baseline_started(self, branch, sha): + query = urllib.parse.urlencode({"branch": branch, "head_sha": sha}) + path = f"actions/workflows/{WORKFLOW}/runs?{query}" + for attempt in range(12): + if attempt: + time.sleep(5) + if self.api.call(FORK, path)["workflow_runs"]: + return True + if attempt == 5: + self.api.write( + f"actions/workflows/{WORKFLOW}/dispatches", {"ref": branch} + ) + return False + + def tree(self, sha): + api = self.api + root = api.call(FORK, f"git/commits/{sha}")["tree"]["sha"] + entries = api.call(FORK, f"git/trees/{root}")["tree"] + github = next( + ( + e["sha"] + for e in entries + if e["path"] == ".github" and e["type"] == "tree" + ), + None, + ) + workflows = api.write( + "git/trees", + { + "tree": [ + { + "path": WORKFLOW, + "mode": "100644", + "type": "blob", + "content": self.workflow, + } + ] + }, + )["sha"] + replacement = { + "tree": [ + { + "path": "workflows", + "mode": "040000", + "type": "tree", + "sha": workflows, + } + ] + } + if github: + replacement["base_tree"] = github + github = api.write("git/trees", replacement)["sha"] + return api.write( + "git/trees", + { + "base_tree": root, + "tree": [ + {"path": ".github", "mode": "040000", "type": "tree", "sha": github}, + ], + }, + )["sha"] + + def commit(self, tree, parents, message): + return self.api.write( + "git/commits", {"tree": tree, "parents": parents, "message": message} + )["sha"] + +def main(): + parser = argparse.ArgumentParser() + sync = parser.add_subparsers(dest="command", required=True).add_parser("sync") + sync.add_argument("--pr", type=int, action="append") + sync.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + token = os.environ.get("SHADOW_MIRROR_TOKEN") or os.environ.get("GH_TOKEN") + if not token: + parser.error("Set SHADOW_MIRROR_TOKEN or GH_TOKEN") + api = API(token, args.dry_run) + mirror = Mirror(api) + numbers = args.pr + if not numbers: + numbers = list(api.dependency_candidates()) + numbers.extend( + number + for number, history in mirror.mirrors.items() + if any(pr["state"] == "open" for pr in history.values()) + ) + for number in dict.fromkeys(numbers): + try: + result = mirror.sync(number) + except (APIError, OSError, ValueError) as error: + sys.stdout.write( + json.dumps({"pr": number, "status": "error", "error": str(error)}) + + "\n" + ) + return 1 + sys.stdout.write(json.dumps({"pr": number, **result}) + "\n") + sys.stdout.flush() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/shadow_mirror/test_mirror.py b/.github/scripts/shadow_mirror/test_mirror.py new file mode 100644 index 000000000000..0386c9158afa --- /dev/null +++ b/.github/scripts/shadow_mirror/test_mirror.py @@ -0,0 +1,381 @@ +import base64 +import datetime +import io +import json +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import Mock, call, patch + +from mirror import ( + API, + FORK, + SOURCE, + WORKFLOW, + APIError, + Mirror, + is_dependency_pr, + recently_merged, + main, + mirror_revision, + recording_workflow, + scrub_title, +) + + +DEPENDABOT = {"login": "dependabot[bot]", "id": 49699333, "type": "Bot"} +UPSTREAM_HEAD = {"repo": {"full_name": SOURCE}} + + +class DiscoveryTest(unittest.TestCase): + def test_installed_workspace_inputs_qualify(self): + for path in ( + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "packages/nextjs/package.json", + "dev-packages/rollup-utils/package.json", + ): + with self.subTest(path=path): + pr = {"changed_files": 1, "user": DEPENDABOT, "head": UPSTREAM_HEAD} + self.assertTrue(is_dependency_pr(pr, [{"filename": path}])) + + def test_unrecorded_inputs_do_not_qualify(self): + for path in ( + "dev-packages/e2e-tests/test-applications/nextjs-15/package.json", + "dev-packages/e2e-tests/test-applications/nextjs-15/pnpm-lock.yaml", + ".github/workflows/build.yml", + "packages/nextjs/src/index.ts", + ): + with self.subTest(path=path): + pr = {"changed_files": 1, "user": DEPENDABOT, "head": UPSTREAM_HEAD} + self.assertFalse(is_dependency_pr(pr, [{"filename": path}])) + + def test_only_named_upstream_bots_qualify(self): + files = [{"filename": "README.md"}, {"filename": "pnpm-lock.yaml"}] + for user, head, qualified in ( + (DEPENDABOT, UPSTREAM_HEAD, True), + ({"login": "renovate[bot]", "id": 29139614, "type": "Bot"}, UPSTREAM_HEAD, True), + ({"login": "dependabot[bot]", "id": 1, "type": "Bot"}, UPSTREAM_HEAD, False), + ({"login": "dependabot[bot]", "id": 49699333, "type": "User"}, UPSTREAM_HEAD, False), + ({"login": "developer", "id": 2, "type": "User"}, UPSTREAM_HEAD, False), + (DEPENDABOT, {"repo": {"full_name": "someone/fork"}}, False), + ): + with self.subTest(user=user, head=head): + pr = {"changed_files": 2, "user": user, "head": head} + self.assertEqual(is_dependency_pr(pr, files), qualified) + pr = {"changed_files": 2, "user": DEPENDABOT, "head": UPSTREAM_HEAD} + self.assertFalse(is_dependency_pr(pr, files[:1])) + + def test_recently_merged_uses_lookback(self): + now = datetime.datetime(2026, 11, 27, tzinfo=datetime.timezone.utc) + self.assertTrue(recently_merged({"merged_at": "2026-11-18T00:00:00Z"}, now)) + self.assertFalse(recently_merged({"merged_at": "2026-11-16T00:00:00Z"}, now)) + self.assertFalse(recently_merged({"merged_at": None}, now)) + + def test_candidates_cover_open_and_recently_merged_bot_changes(self): + api = API("unused", True) + + def page(numbers, cursor=None): + return { + "data": { + "search": { + "nodes": [{"number": n} for n in numbers] + [{}], + "pageInfo": {"hasNextPage": bool(cursor), "endCursor": cursor}, + } + } + } + + api._request = Mock(side_effect=[page([1], "next"), page([2]), page([3])]) + now = datetime.datetime(2026, 11, 27, tzinfo=datetime.timezone.utc) + self.assertEqual(list(api.dependency_candidates(now)), [1, 2, 3]) + searches = [c.args[-1]["variables"]["search"] for c in api._request.call_args_list] + self.assertTrue(all(f"repo:{SOURCE} is:pr" in q for q in searches)) + self.assertTrue(all("author:app/dependabot author:app/renovate" in q for q in searches)) + self.assertIn("is:open", searches[0]) + self.assertEqual(api._request.call_args_list[1].args[-1]["variables"]["cursor"], "next") + self.assertIn("is:merged merged:>=2026-11-17T00:00:00Z", searches[2]) + + def test_upstream_and_dry_run_writes_are_blocked(self): + for api, repo in ((API("unused", False), SOURCE), (API("unused", True), FORK)): + with self.assertRaisesRegex(ValueError, "live writes to the mirror"): + api.call(repo, "pulls", "POST", {}) + + def test_scrub_title_removes_upstream_references(self): + self.assertEqual( + scrub_title( + f"Bump @scope/name [skip ci] {SOURCE}#123 @person https://github.com/{SOURCE}/pull/123" + ), + "Bump @scope/name", + ) + + def test_scrub_title_cannot_recreate_ci_skip_directives(self): + for directive in ( + "[skip ci]", + "[ci\tskip]", + "[No\nCI]", + "[skip @user actions]", + "[actions [skip ci] skip]", + ): + with self.subTest(directive=directive): + self.assertEqual( + scrub_title(f"Bump fastapi {directive}"), "Bump fastapi" + ) + + def test_mirror_revision_requires_exact_same_repo_pair(self): + pr = { + "base": {"repo": {"full_name": FORK}, "ref": "shadow/base/1-r2"}, + "head": {"repo": {"full_name": FORK}, "ref": "shadow/pr/1-r2"}, + } + self.assertEqual(mirror_revision(pr, 1), 2) + self.assertIsNone(mirror_revision(pr, 2)) + self.assertIsNone( + mirror_revision({**pr, "head": {**pr["head"], "ref": "shadow/pr/1"}}, 1) + ) + pr["head"]["repo"]["full_name"] = SOURCE + self.assertIsNone(mirror_revision(pr, 1)) + + +class ReplayTest(unittest.TestCase): + def setUp(self): + self.api = Mock(dry_run=False) + self.api.pages.return_value = [] + self.mirror = Mirror(self.api) + self.api.reset_mock() + self.source_base = "a" * 40 + self.merge_base = "b" * 40 + self.source_head = "c" * 40 + self.pr = { + "state": "open", + "title": "Bump fastapi", + "changed_files": 1, + "user": DEPENDABOT, + "base": {"sha": self.source_base}, + "head": {"sha": self.source_head, "repo": {"full_name": SOURCE}}, + } + self.files = [{"filename": "pnpm-lock.yaml"}] + self.workflow_path = ( + Path(__file__).resolve().parents[2] / "workflows" / WORKFLOW + ) + + def test_baseline_uses_merge_base_and_head_uses_original_head(self): + def read(repo, path): + if path == "pulls/1": + return self.pr + if path == f"compare/{self.source_base}...{self.source_head}": + return {"merge_base_commit": {"sha": self.merge_base}} + if path.startswith("contents/"): + return { + "content": base64.b64encode( + self.workflow_path.read_bytes() + ).decode() + } + if path.startswith("git/ref/"): + raise APIError("GET", path, 404, "missing ref") + if path.startswith("actions/"): + return {"workflow_runs": [{"id": 1}]} + raise AssertionError((repo, path)) + + self.api.call.side_effect = read + self.pr.update(changed_files=2) + self.files.append( + {"filename": "/package.json"} + ) + self.api.pages.side_effect = [self.files, []] + self.api.write.side_effect = [ + {"sha": "baseline"}, + {}, + {"sha": "head"}, + {}, + {"number": 2, "html_url": "https://github.com/garnet-labs/sentry-javascript/pull/2"}, + {}, + ] + with patch.object( + self.mirror, "tree", side_effect=["base-tree", "head-tree"] + ) as tree: + self.assertEqual(self.mirror.sync(1)["status"], "created") + self.assertEqual( + tree.call_args_list, [call(self.merge_base), call(self.source_head)] + ) + writes = self.api.write.call_args_list + self.assertEqual( + [write.args[0] for write in writes], + [ + "git/commits", + "git/refs", + "git/commits", + "git/refs", + "pulls", + ], + ) + self.assertEqual(writes[0].args[1]["parents"], []) + self.assertEqual(writes[2].args[1]["parents"], ["baseline"]) + self.assertEqual(writes[4].args[1]["base"], "shadow/base/1") + self.assertEqual(writes[4].args[1]["head"], "shadow/pr/1") + self.assertNotIn("draft", writes[4].args[1]) + self.assertNotIn( + "", writes[4].args[1]["body"] + ) + + def test_changed_base_creates_new_pair_without_updating_open_refs(self): + old = {"state": "open", "number": 5, "body": "original"} + self.mirror.workflow = "trusted workflow" + self.api.call.return_value = {"message": "old baseline"} + self.api.write.side_effect = [ + {"sha": "new-base"}, + {}, + {"sha": "new-head"}, + {}, + {"number": 6, "html_url": "new mirror"}, + {}, + {}, + ] + with ( + patch.object( + self.mirror, "get_ref", side_effect=["old-baseline", None, None] + ), + patch.object(self.mirror, "tree", side_effect=["base-tree", "head-tree"]), + patch.object(self.mirror, "baseline_started", return_value=True), + ): + self.assertEqual( + self.mirror.replay(1, self.pr, self.files, self.merge_base, {1: old})[ + "status" + ], + "created", + ) + writes = self.api.write.call_args_list + self.assertEqual( + writes[1], + call("git/refs", {"ref": "refs/heads/shadow/base/1-r2", "sha": "new-base"}), + ) + self.assertEqual( + writes[3], + call("git/refs", {"ref": "refs/heads/shadow/pr/1-r2", "sha": "new-head"}), + ) + self.assertEqual(writes[-1], call("pulls/5", {"state": "closed"}, "PATCH")) + + def test_dry_run_never_writes(self): + self.api.dry_run = True + self.api.call.side_effect = [ + self.pr, + self.pr, + {"merge_base_commit": {"sha": self.merge_base}}, + ] + self.api.pages.return_value = self.files + self.assertEqual( + self.mirror.sync(1), + { + "status": "dry-run", + "upstream_base": self.merge_base, + "upstream_head": self.source_head, + "files": ["pnpm-lock.yaml"], + }, + ) + self.api.write.assert_not_called() + + def test_missing_upstream_pr_does_not_abort_batch(self): + self.api.dry_run = True + self.api.call.side_effect = [ + APIError("GET", "pulls/1", 404, "Not Found"), + self.pr, + self.pr, + {"merge_base_commit": {"sha": self.merge_base}}, + ] + self.api.pages.side_effect = [[], self.files] + with ( + patch("mirror.API", return_value=self.api), + patch( + "mirror.sys.argv", + ["mirror", "sync", "--dry-run", "--pr", "1", "--pr", "2"], + ), + patch.dict("mirror.os.environ", {"SHADOW_MIRROR_TOKEN": "unused"}), + redirect_stdout(io.StringIO()) as stdout, + ): + self.assertEqual(main(), 0) + results = [json.loads(line) for line in stdout.getvalue().splitlines()] + self.assertEqual( + [(r["pr"], r["status"]) for r in results], [(1, "skipped"), (2, "dry-run")] + ) + self.assertEqual(results[0]["reason"], "upstream PR not found") + self.api.write.assert_not_called() + + def test_replaced_tree_has_only_the_recorder_in_workflows(self): + self.mirror.workflow = "trusted workflow" + self.api.call.side_effect = [ + {"tree": {"sha": "original-root"}}, + {"tree": [{"path": ".github", "type": "tree", "sha": "original-github"}]}, + ] + self.api.write.side_effect = [ + {"sha": "workflows"}, + {"sha": "github"}, + {"sha": "root"}, + ] + self.assertEqual(self.mirror.tree(self.merge_base), "root") + self.assertEqual( + self.api.write.call_args_list, + [ + call( + "git/trees", + { + "tree": [ + { + "path": WORKFLOW, + "mode": "100644", + "type": "blob", + "content": "trusted workflow", + } + ] + }, + ), + call( + "git/trees", + { + "tree": [ + { + "path": "workflows", + "mode": "040000", + "type": "tree", + "sha": "workflows", + } + ], + "base_tree": "original-github", + }, + ), + call( + "git/trees", + { + "base_tree": "original-root", + "tree": [ + { + "path": ".github", + "mode": "040000", + "type": "tree", + "sha": "github", + } + ], + }, + ), + ], + ) + + def test_recorder_runs_on_base_and_can_be_dispatched(self): + workflow = recording_workflow(self.workflow_path.read_text()) + self.assertIn("branches: ['develop', 'record-base/**', 'shadow/base/**']", workflow) + self.assertIn(" pull_request:\n workflow_dispatch:\n", workflow) + self.assertIn(" if: github.event_name != 'pull_request' || ", workflow) + self.assertIn(" dep-install:", workflow) + self.assertIn("id-token: write", workflow) + self.assertEqual(workflow.count("persist-credentials: false"), 1) + with self.assertRaises(ValueError): + recording_workflow(workflow.replace("persist-credentials: false", "")) + + def test_baseline_can_be_dispatched_if_ref_creation_does_not_trigger_it(self): + self.api.call.side_effect = [{"workflow_runs": []}] * 6 + [ + {"workflow_runs": [{"id": 1}]} + ] + with patch("mirror.time.sleep"): + self.assertTrue(self.mirror.baseline_started("shadow/base/1", "base-sha")) + self.api.write.assert_called_once_with( + f"actions/workflows/{WORKFLOW}/dispatches", {"ref": "shadow/base/1"} + ) + diff --git a/.github/workflows/garnet-shadow-mirror.yml b/.github/workflows/garnet-shadow-mirror.yml new file mode 100644 index 000000000000..027599071f9b --- /dev/null +++ b/.github/workflows/garnet-shadow-mirror.yml @@ -0,0 +1,72 @@ +name: Shadow dependency mirror +on: + pull_request: + paths: + - .github/scripts/shadow_mirror/** + - .github/workflows/garnet-shadow-mirror.yml + - .github/workflows/garnet-record.yml + schedule: + - cron: '*/30 * * * *' + workflow_dispatch: + inputs: + prs: + description: Optional space-separated change numbers + required: false + type: string +permissions: {} +concurrency: + group: shadow-dependency-mirror + cancel-in-progress: false +jobs: + test: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + - name: Test shadow mirror + run: python3 -m unittest discover -s .github/scripts/shadow_mirror + + sync: + if: github.repository == 'garnet-labs/sentry-javascript' && github.event_name != 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + env: + PRS: ${{ inputs.prs }} + steps: + - name: Check authentication + id: auth + env: + SHADOW_MIRROR_TOKEN: ${{ secrets.SHADOW_MIRROR_TOKEN }} + run: | + if [ -z "$SHADOW_MIRROR_TOKEN" ]; then + echo '::error::Set the SHADOW_MIRROR_TOKEN secret to a PAT with write access to Contents, Pull requests, Actions, and Workflows.' + exit 1 + else + echo 'enabled=true' >> "$GITHUB_OUTPUT" + fi + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + if: steps.auth.outputs.enabled == 'true' + with: + sparse-checkout: .github/scripts/shadow_mirror + sparse-checkout-cone-mode: false + persist-credentials: false + - name: Sync dependency changes + if: steps.auth.outputs.enabled == 'true' + env: + SHADOW_MIRROR_TOKEN: ${{ secrets.SHADOW_MIRROR_TOKEN }} + shell: bash + run: | + set -euo pipefail + args=() + for pr in $PRS; do + [[ "$pr" =~ ^[0-9]+$ ]] || { echo 'Invalid change number'; exit 1; } + args+=(--pr "$pr") + done + python3 .github/scripts/shadow_mirror/mirror.py sync "${args[@]}" diff --git a/.github/workflows/merge-gate.yml b/.github/workflows/merge-gate.yml deleted file mode 100644 index f86e11d05fe4..000000000000 --- a/.github/workflows/merge-gate.yml +++ /dev/null @@ -1,44 +0,0 @@ -# Merge gate (POC) -# Evaluates the Garnet execution profile on a PR and posts a MERGE / HOLD / AUDIT -# decision. Fires when garnet-runtime-review[bot] posts a Runtime Review, or when -# someone comments /merge-gate on a PR. Manual re-runs via workflow_dispatch. -# Proof of concept only. Garnet reports; the reviewer decides. -name: Merge gate - -on: - issue_comment: - types: [created, edited] - workflow_dispatch: - inputs: - pr: - description: "PR number to gate" - required: true - -permissions: - contents: read - issues: write - pull-requests: write - -jobs: - gate: - if: > - github.event_name == 'workflow_dispatch' || - (github.event.issue.pull_request && ( - github.event.comment.user.login == 'garnet-runtime-review[bot]' || - contains(github.event.comment.body, '/merge-gate') - )) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - sparse-checkout: .github/merge-gate - sparse-checkout-cone-mode: false - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - name: Run merge gate - run: | - PR="${{ inputs.pr || github.event.issue.number }}" - python3 .github/merge-gate/gate.py "${{ github.repository }}" "$PR" - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}