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
160 changes: 90 additions & 70 deletions .github/verify-pr-spike/spike.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#!/usr/bin/env python3
"""Test workflow script for #7127: the verify-pr Android steps on a Linux runner.

Builds the sample without the PR (its SDK change reverse-applied from its merge
commit) and with it, runs the skill's example flow on each build with the run
ids the workflow passes in, and records each side's crash event id from the
device log, with timings, disk usage and stale-bundle checks.
Runs from a checkout of main, against the `ref` checkout in $VERIFY_REF_DIR.
Builds the sample without the PR (its `packages/core` diff from $BASE_SHA
reverse-applied) and with it, rebuilding `packages/core` in between so each APK
bundles its own JavaScript, then runs the flow in $VERIFY_FLOW on each build
with the run ids the workflow passes in. Records timings, disk usage and bundle
checks. The fetch job finds the events by run id; no event id leaves this job.

Each subcommand is one workflow step. Results go to $RUNNER_TEMP/verify-pr-spike,
which the workflow uploads.
Expand All @@ -14,41 +16,55 @@
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import time
import zipfile
from pathlib import Path

REPO = Path(__file__).resolve().parents[2]
# The `ref` checkout: the code under test. This script comes from main.
REPO = Path(os.environ["VERIFY_REF_DIR"]).resolve()
SAMPLE = REPO / "samples" / "react-native"
FLOW = REPO / ".agents/skills/verify-pr/flows/examples/turbo-module-calls-then-native-crash.yml"
FLOWS = REPO / ".agents/skills/verify-pr/flows"
# Validated by the workflow against a fixed pattern under FLOWS.
FLOW = REPO / os.environ["VERIFY_FLOW"]
APP_ID = "io.sentry.reactnative.sample"
OUT = Path(os.environ["RUNNER_TEMP"]) / "verify-pr-spike"
RESULTS = OUT / "results.json"
PATCH = OUT / f"pr{os.environ['VERIFY_PR']}.patch"
SIDES = ("without", "with")
CORE = "packages/core"
CORE_SRC = f"{CORE}/src/"
# Same exclusions as the skill's patch (SKILL.md step 2).
PATCH_PATHS = (
CORE,
f":!{CORE}/test",
f":!{CORE}/RNSentryAndroidTester",
f":!{CORE}/RNSentryCocoaTester",
)
# Fetch depths to try until the merge base of $BASE_SHA and HEAD is present.
MERGE_BASE_DEPTHS = (50, 500, 5000)
# Gradle doesn't see packages/core/dist as an input of the JS bundle task, so it
# keeps the previous side's bundle unless these go (references/android.md).
REACT_OUTPUTS = (
"generated/assets/react/release",
"generated/res/react/release",
"generated/sourcemaps/react/release",
"intermediates/sourcemaps/react/release",
)
# A string literal from samples/react-native/src/verifyRun.ts, so it is in both
# bundles; the check is whether the skill's command reads the Hermes bundle on
# Linux at all.
BUNDLE_STRING = "verify.run_id"
# Time for queued envelopes to be sent after the flow, before the next install.
SEND_WAIT_SECONDS = 30
# `adb logcat -d` prints the threadtime format: date, time, pid, tid, level,
# tag, message.
LOGCAT_LINE = re.compile(
r"^\S+\s+\S+\s+(?P<pid>\d+)\s+(?P<tid>\d+)\s+[VDIWEF]\s+(?P<tag>\S+)\s*: (?P<msg>.*)$"
)
UNCAUGHT = "Uncaught exception received."
CAPTURING = re.compile(r"Capturing event: ([0-9a-f]{32})")


def load():
if RESULTS.exists():
return json.loads(RESULTS.read_text())
return {"timings": {}, "marks": {}, "disk": {}, "bundle": {}, "runs": {}}
return {"timings": {}, "marks": {}, "disk": {}, "patch": {}, "bundle": {}, "runs": {}}


def save(results):
Expand All @@ -65,9 +81,12 @@ def git(*args, **kwargs):
return run(["git", "-C", str(REPO), *args], **kwargs)


def git_out(*args):
return git(*args, capture_output=True, text=True).stdout.strip()


def short_head():
out = git("rev-parse", "--short", "HEAD", capture_output=True, text=True)
return out.stdout.strip()
return git_out("rev-parse", "--short", "HEAD")


def sha256(path):
Expand Down Expand Up @@ -100,19 +119,47 @@ def cmd_kvm(_args):
run(["sudo", "udevadm", "trigger", "--name-match=kvm"])


def cmd_flow(_args):
# Before any build: the flow must be a file on the ref branch, under FLOWS.
flow = FLOW.resolve()
if not flow.is_relative_to(FLOWS.resolve()) or not flow.is_file():
sys.exit(f"the flow is not a file under {FLOWS.relative_to(REPO)} on the ref branch")
print(f"flow: {FLOW.relative_to(REPO)}")


def fetch_merge_base(base, head):
"""Deepens the shallow checkout until `base...head` has a merge base."""
for depth in MERGE_BASE_DEPTHS:
git("fetch", "--no-tags", f"--depth={depth}", "origin", base, head)
found = subprocess.run(
["git", "-C", str(REPO), "merge-base", base, head],
capture_output=True, text=True, check=False,
)
if found.returncode == 0:
return found.stdout.strip()
sys.exit(f"no merge base of the base sha and HEAD within {MERGE_BASE_DEPTHS[-1]} commits")


def cmd_revert(_args):
merge_sha = os.environ["MERGE_SHA"].lower()
# The checkout is shallow; `git show` needs the merge commit and its parent.
git("fetch", "--no-tags", "--depth=2", "origin", merge_sha)
base = os.environ["BASE_SHA"].lower()
head = git_out("rev-parse", "HEAD")
merge_base = fetch_merge_base(base, head)
diff_range = f"{base}...HEAD"
OUT.mkdir(parents=True, exist_ok=True)
with PATCH.open("w") as patch:
git(
"show", "--format=", merge_sha, "--", "packages/core",
":!packages/core/test",
":!packages/core/RNSentryAndroidTester",
":!packages/core/RNSentryCocoaTester",
stdout=patch,
)
git("diff", diff_range, "--", *PATCH_PATHS, stdout=patch)
files = git_out("diff", "--name-only", diff_range, "--", *PATCH_PATHS).splitlines()
if not files:
sys.exit(f"git diff {diff_range} changes nothing under {CORE}")
results = load()
results["patch"] = {
"base_sha": base,
"merge_base": merge_base,
"head": head,
"files": files,
"changes_core_src": any(f.startswith(CORE_SRC) for f in files),
}
save(results)
git("apply", "-R", "--check", str(PATCH))
git("apply", "-R", str(PATCH))

Expand All @@ -125,6 +172,9 @@ def cmd_build(args):
side = args.side
env = dict(os.environ, RN_ARCHITECTURE="new", CONFIG="release")
start = time.time()
# Re-bundle from the packages/core/dist that the previous step just built.
for output in REACT_OUTPUTS:
shutil.rmtree(SAMPLE / "android/app/build" / output, ignore_errors=True)
# `yarn build-android-release` drops extra arguments, so call the script it
# wraps. x86_64 only: the emulator's ABI, instead of all four.
run(
Expand Down Expand Up @@ -164,30 +214,14 @@ def cmd_build(args):
save(results)


def crash_event_ids(logcat):
"""Ids of the crash events in a device log.

A crash event is one the Android SDK logs as `Capturing event: <id>` in the
next `Sentry` line from the same process and thread as `Uncaught exception
received.`. The other ids in the log, such as envelope files, transactions
and the session, are not on such a line.
"""
ids = []
crashed = set()
for line in logcat.splitlines():
match = LOGCAT_LINE.match(line)
if not match or match["tag"] != "Sentry":
continue
thread = (match["pid"], match["tid"])
message = match["msg"].strip()
if message == UNCAUGHT:
crashed.add(thread)
elif thread in crashed:
crashed.discard(thread)
capturing = CAPTURING.fullmatch(message)
if capturing:
ids.append(capturing[1])
return ids
def cmd_check_bundles(_args):
results = load()
identical = results["bundle"]["without"]["bundle_sha256"] == results["bundle"]["with"]["bundle_sha256"]
results["bundle"]["identical"] = identical
save(results)
print(f"the two JavaScript bundles are {'identical' if identical else 'different'}")
if identical and results["patch"]["changes_core_src"]:
sys.exit(f"the PR changes files under {CORE_SRC} but both APKs bundle the same JavaScript")


def adb(*args, **kwargs):
Expand All @@ -200,7 +234,8 @@ def run_side(side, results):
run_id = os.environ[f"RUN_ID_{side.upper()}"]
commit = short_head()
if side == "without":
commit = f"{commit}-{os.environ['MERGE_SHA'].lower()[:7]}"
# HEAD with its diff from the base sha reversed.
commit = f"{commit}-{os.environ['BASE_SHA'].lower()[:7]}"
run_dir = OUT / run_id
run_dir.mkdir(parents=True, exist_ok=True)
record = {"run_id": run_id, "commit": commit}
Expand Down Expand Up @@ -236,10 +271,6 @@ def run_side(side, results):
(run_dir / f"{run_id}.logcat").write_text(logcat, encoding="utf-8")
record["logcat_run_id_lines"] = logcat.count(run_id)
record["logcat_envelopes_sent"] = logcat.count("Envelope sent successfully")
ids = crash_event_ids(logcat)
record["crash_event_ids"] = ids
if len(ids) == 1:
record["crash_event_id"] = ids[0]
with (run_dir / "screencap.png").open("wb") as png:
adb("exec-out", "screencap", "-p", stdout=png)
# An all-black screenshot compresses to a few KB; a real one is much larger.
Expand All @@ -257,22 +288,11 @@ def cmd_run(_args):
for side in SIDES:
if run_side(side, results) != 0:
failures.append(f"the Maestro flow failed for {side}")
found = len(results["runs"][side]["crash_event_ids"])
if found != 1:
failures.append(f"{found} crash event ids in the {side} device log, expected 1")
save(results)
if failures:
sys.exit("; ".join(failures))


def cmd_outputs(_args):
# The only values the fetch job gets from this job.
runs = load()["runs"]
with open(os.environ["GITHUB_OUTPUT"], "a") as fh:
for side in SIDES:
fh.write(f"{side}_event_id={runs[side]['crash_event_id']}\n")


def cmd_summary(_args):
results = load()
marks = results["marks"]
Expand All @@ -294,9 +314,9 @@ def main():
sub.add_parser("disk").add_argument("label")
sub.add_parser("build").add_argument("side", choices=SIDES)
commands = {
"mark": cmd_mark, "disk": cmd_disk, "kvm": cmd_kvm, "revert": cmd_revert,
"restore": cmd_restore, "build": cmd_build, "run": cmd_run, "outputs": cmd_outputs,
"summary": cmd_summary,
"mark": cmd_mark, "disk": cmd_disk, "kvm": cmd_kvm, "flow": cmd_flow,
"revert": cmd_revert, "restore": cmd_restore, "build": cmd_build,
"check-bundles": cmd_check_bundles, "run": cmd_run, "summary": cmd_summary,
}
for name, handler in commands.items():
(sub.choices.get(name) or sub.add_parser(name)).set_defaults(handler=handler)
Expand Down
Loading
Loading