From 25de2c6edb213a0e1cd05d29afaf8f9afa2c8e56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 15:45:42 +0100 Subject: [PATCH 01/12] ci(performance): run reviewed fork commits on ADC --- .github/workflows/fork-performance.yml | 181 ++++++++++++++++++++++ scripts/performance/README.md | 8 + scripts/performance/fork/authorize.py | 57 +++++++ scripts/performance/fork/build-arm.sh | 14 ++ scripts/performance/fork/build.Dockerfile | 8 + scripts/performance/fork/build.sh | 30 ++++ scripts/performance/fork/export_apk.py | 15 ++ scripts/performance/fork/prefetch.sh | 16 ++ scripts/performance/fork/sign-apk.sh | 27 ++++ scripts/performance/prepare.py | 22 ++- scripts/performance/run.py | 19 ++- 11 files changed, 386 insertions(+), 11 deletions(-) create mode 100644 .github/workflows/fork-performance.yml create mode 100644 scripts/performance/fork/authorize.py create mode 100755 scripts/performance/fork/build-arm.sh create mode 100644 scripts/performance/fork/build.Dockerfile create mode 100755 scripts/performance/fork/build.sh create mode 100644 scripts/performance/fork/export_apk.py create mode 100755 scripts/performance/fork/prefetch.sh create mode 100755 scripts/performance/fork/sign-apk.sh diff --git a/.github/workflows/fork-performance.yml b/.github/workflows/fork-performance.yml new file mode 100644 index 000000000..ad69ba3f3 --- /dev/null +++ b/.github/workflows/fork-performance.yml @@ -0,0 +1,181 @@ +name: Fork performance check + +on: + issue_comment: + types: [created] + +permissions: {} + +jobs: + authorize: + if: github.event.issue.pull_request && (github.event.comment.body == '/check' || startsWith(github.event.comment.body, '/check ')) + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read + statuses: write + outputs: + base: ${{ steps.request.outputs.base }} + head: ${{ steps.request.outputs.head }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - id: request + name: Resolve the authorized fork revision + env: + GH_TOKEN: ${{ github.token }} + run: python3 -I scripts/performance/fork/authorize.py + - name: Mark the reviewed commit pending + env: + GH_TOKEN: ${{ github.token }} + HEAD_SHA: ${{ steps.request.outputs.head }} + run: | + gh api --silent "repos/$GITHUB_REPOSITORY/statuses/$HEAD_SHA" -f state=pending \ + -f context='ADC /check' -f description='Building the reviewed APKs' \ + -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + - name: Fetch published PerfKit dependencies + env: + PERF_MAVEN_USER: ${{ secrets.PERF_MAVEN_USER }} + PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} + run: bash scripts/performance/fork/prefetch.sh + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: fork-check-maven + path: ${{ runner.temp }}/maven + if-no-files-found: error + overwrite: true + retention-days: 1 + + build: + needs: authorize + permissions: + contents: read + strategy: + matrix: + arm: [baseline, candidate] + runs-on: ubuntu-24.04 + timeout-minutes: 180 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: trusted + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: source + ref: ${{ matrix.arm == 'baseline' && needs.authorize.outputs.base || needs.authorize.outputs.head }} + persist-credentials: false + submodules: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: fork-check-maven + path: maven + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.4 + - name: Prepare Android tooling + run: | + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'build-tools;35.0.0' 'build-tools;36.0.0' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools + - name: Build the Release APK in an isolated container + env: + ARM: ${{ matrix.arm }} + run: bash trusted/scripts/performance/fork/build.sh "$ARM" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: fork-check-${{ matrix.arm }}-apk + path: ${{ runner.temp }}/${{ matrix.arm }}.apk + if-no-files-found: error + compression-level: 0 + overwrite: true + retention-days: 1 + + compare: + needs: [authorize, build] + permissions: + contents: read + runs-on: ubuntu-24.04 + timeout-minutes: 60 + env: + BASE_SHA: ${{ needs.authorize.outputs.base }} + HEAD_SHA: ${{ needs.authorize.outputs.head }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + pattern: fork-check-*-apk + merge-multiple: true + path: apks + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.4 + - name: Install trusted driver dependencies + run: | + bun install --frozen-lockfile --ignore-scripts + echo "$ANDROID_HOME/platform-tools" >> "$GITHUB_PATH" + - uses: margelo/adc@09956980c08fe6790198c721fc0a9da500778407 # v0.5.1 + with: + api-key: ${{ secrets.ADC_API_KEY }} + name: /check PR ${{ github.event.issue.number }} ${{ github.run_id }} + form-factor: phone + api-level: '35' + width: '720' + height: '1600' + dpi: '320' + command: | + marker=$(cat /proc/sys/kernel/random/uuid) + printf '::stop-commands::%s\n' "$marker" + trap 'printf "::%s::\n" "$marker"' EXIT + python3 scripts/performance/run.py --staged-fixture scripts/performance/workloads.tsx \ + --baseline "$BASE_SHA" apks/baseline.apk --candidate "$HEAD_SHA" apks/candidate.apk \ + --pairs 64 --fixed --thread-counters --output results + - name: Report the paired changes + run: | + printf 'Base %s · candidate %s\n\n' "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_STEP_SUMMARY" + python3 scripts/performance/thread-counters/analyze_fixed.py --markdown results > results/report.md + cat results/report.md >> "$GITHUB_STEP_SUMMARY" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + if: ${{ !cancelled() && hashFiles('results/session.json') != '' }} + with: + name: fork-check-readings + path: results + overwrite: true + retention-days: 7 + + status: + needs: [authorize, build, compare] + if: always() && needs.authorize.outputs.head != '' + runs-on: ubuntu-24.04 + permissions: + pull-requests: read + statuses: write + steps: + - name: Publish the result on the reviewed commit + env: + GH_TOKEN: ${{ github.token }} + BASE_SHA: ${{ needs.authorize.outputs.base }} + HEAD_SHA: ${{ needs.authorize.outputs.head }} + PR_NUMBER: ${{ github.event.issue.number }} + OUTCOME: ${{ needs.compare.result }} + run: | + state=failure + description='Build or ADC measurements did not finish successfully' + if [ "$OUTCOME" = success ]; then + pull=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + if jq -e --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \ + '.state == "open" and .base.sha == $base and .head.sha == $head' <<< "$pull" >/dev/null; then + state=success + description='Measurements complete; see intervals in the run summary' + else + state=error + description='PR revisions changed; review and request a new check' + fi + fi + gh api --silent "repos/$GITHUB_REPOSITORY/statuses/$HEAD_SHA" -f state="$state" \ + -f context='ADC /check' -f description="$description" \ + -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" diff --git a/scripts/performance/README.md b/scripts/performance/README.md index ad62366c9..bef1f2af9 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -28,6 +28,14 @@ adc run --purpose ci --form-factor phone --api-level 35 --width 720 --height 160 python3 scripts/performance/analyze.py --session ../performance-run/session.json ../performance-run/raw.jsonl ``` +## Running a fork PR with /check + +A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary and downloadable readings. A successful run means the comparison completed. Read the intervals before merging. + +The upstream workflow pins the base and head from GitHub. A trusted job downloads the published PerfKit Maven artifacts with the same package reader as the internal benchmark. Each arm builds in its own disposable GitHub-hosted VM. The isolated build container sees the source, Android toolchain and dependency files, with public network access for package downloads. Git submodules resolve inside the container. Host credentials, Actions runtime files, Docker sockets, shared caches and private network services are outside the build. The host exports one size-limited regular APK, verifies its package and application UID, and signs each arm with a fresh key. A fresh trusted runner executes the upstream driver against those APKs on ADC. Fork code controls its own Android process and can misrepresent its timings. Review the code and benchmark behavior before treating results as evidence. + +This private repository disables ordinary workflows from fork PRs in Actions settings. Keep that setting while other workflows run on persistent self-hosted machines. Before making the repository public, restrict the runner groups to trusted workflow refs or move fork builds to isolated hosted runners. A condition inside a fork-editable workflow cannot enforce that runner policy. [GitHub Actions security guidance](https://docs.github.com/en/actions/reference/security/secure-use) + ## AWS Device Farm physical calibration Build both package IDs from the same Git revision with the Release steps above. The physical calibration runs A/A first and then increases candidate MMKV read passes from 128 to 141. Each comparison gets its own warmups and stopping decisions on the same phone. The test package contains both signed APKs, the compiled Linux launcher and the Python wheels for an offline test host. diff --git a/scripts/performance/fork/authorize.py b/scripts/performance/fork/authorize.py new file mode 100644 index 000000000..c9ada2885 --- /dev/null +++ b/scripts/performance/fork/authorize.py @@ -0,0 +1,57 @@ +"""Resolve a maintainer's /check to immutable base and fork commits.""" + +import json +import os +from pathlib import Path +import re +import subprocess + + +def api(path, *options): + response = subprocess.check_output(["gh", "api", *options, path], text=True) + return json.loads(response) + + +def authorize(event, repository, lookup=api): + comment = event["comment"] + command = re.fullmatch(r"/check(?: ([0-9a-fA-F]{40}))?", comment["body"].strip()) + if command is None: + raise ValueError("Use /check after approving the current revision, or /check followed by its full commit SHA.") + number = event["issue"]["number"] + user = comment["user"]["login"] + permission = lookup(f"repos/{repository}/collaborators/{user}/permission") + if permission["user"]["permissions"].get("push") is not True: + raise ValueError("Only maintainers with write access can request a device.") + path = f"repos/{repository}/pulls/{number}" + pull = lookup(path) + if pull["state"] != "open" or pull["base"]["repo"]["full_name"] != repository: + raise ValueError("Expected an open pull request against this repository.") + if pull["head"]["repo"] is None or pull["head"]["repo"]["id"] == pull["base"]["repo"]["id"]: + raise ValueError("Use /check on a fork pull request.") + base = pull["base"]["sha"] + head = pull["head"]["sha"] + if not all(re.fullmatch(r"[0-9a-f]{40}", sha) for sha in (base, head)): + raise ValueError("GitHub did not return immutable commit IDs.") + requested = command.group(1) + if requested is not None: + if requested.lower() != head: + raise ValueError("The requested SHA is no longer the current head of this PR.") + else: + pages = lookup(f"{path}/reviews?per_page=100", "--paginate", "--slurp") + decisions = [review for page in pages for review in page + if review["user"]["id"] == comment["user"]["id"] + and review["state"] in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED")] + latest = max(decisions, key=lambda review: review["id"], default=None) + if latest is None or latest["state"] != "APPROVED" or latest["commit_id"] != head: + raise ValueError("Approve the current commit first or specify the reviewed commit with /check .") + return base, head + + +if __name__ == "__main__": + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) + try: + base, head = authorize(event, os.environ["GITHUB_REPOSITORY"]) + except ValueError as error: + raise SystemExit(str(error)) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(f"base={base}\nhead={head}\n") diff --git a/scripts/performance/fork/build-arm.sh b/scripts/performance/fork/build-arm.sh new file mode 100755 index 000000000..14878c58c --- /dev/null +++ b/scripts/performance/fork/build-arm.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Only source files and toolchains have mounts. Compilers and lifecycle scripts run here. +cp -R /source checkout +cd checkout +git submodule update --init --depth 1 --recursive +python3 -I /benchmark/prepare.py "$PWD" "$1" --local-maven /maven +bun install +cd apps/example +bun run android --release --build-only --abi arm64-v8a +metadata=.nitro/android/apks/release.json +apk=$(jq -er '.elements | select(length == 1) | .[0].outputFile' "$metadata") +cp "$apk" /home/ubuntu/app.apk diff --git a/scripts/performance/fork/build.Dockerfile b/scripts/performance/fork/build.Dockerfile new file mode 100644 index 000000000..b617039b0 --- /dev/null +++ b/scripts/performance/fork/build.Dockerfile @@ -0,0 +1,8 @@ +FROM ubuntu:24.04@sha256:562111b88caa79c71391c0c4d3c2114a7d5c35915c20561fd893cb1e07929e6b +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + build-essential ca-certificates clang cmake curl file git jq libicu-dev libreadline-dev zlib1g-dev ninja-build nodejs \ + openjdk-17-jdk-headless python3 rsync unzip zip && rm -rf /var/lib/apt/lists/* +ENV ANDROID_HOME=/opt/android JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 \ + CC=clang CXX=clang++ CMAKE_BUILD_PARALLEL_LEVEL=2 +USER ubuntu +WORKDIR /home/ubuntu diff --git a/scripts/performance/fork/build.sh b/scripts/performance/fork/build.sh new file mode 100755 index 000000000..9559b2898 --- /dev/null +++ b/scripts/performance/fork/build.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail + +arm=$1 +root="$GITHUB_WORKSPACE" +benchmark="$root/trusted/scripts/performance" +docker build --tag nitro-fork-builder - < "$benchmark/fork/build.Dockerfile" +# Block runner, private networks and the cloud instance metadata endpoint. Public +# registries remain reachable for npm, Gradle and anonymous Git submodules. +docker network create --ipv6=false -o com.docker.network.bridge.name=nitro-build nitro-build +sudo iptables -I INPUT -i nitro-build -j DROP +for network in 0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16 172.16.0.0/12 192.168.0.0/16 168.63.129.16/32; do + sudo iptables -I DOCKER-USER -i nitro-build -d "$network" -j DROP +done + +# stdout is controlled by the fork. Disable Actions workflow commands in this log. +marker=$(cat /proc/sys/kernel/random/uuid) +printf '::stop-commands::%s\n' "$marker" +trap 'printf "::%s::\n" "$marker"' EXIT +docker run --name nitro-fork-arm --network nitro-build --cap-drop ALL \ + --security-opt no-new-privileges --pids-limit 4096 \ + --mount "type=bind,src=$root/source,dst=/source,readonly" \ + --mount "type=bind,src=$benchmark,dst=/benchmark,readonly" \ + --mount "type=bind,src=$root/maven,dst=/maven,readonly" \ + --mount "type=bind,src=$ANDROID_HOME,dst=/opt/android,readonly" \ + --mount "type=bind,src=$(realpath "$(command -v bun)"),dst=/usr/local/bin/bun,readonly" \ + nitro-fork-builder bash /benchmark/fork/build-arm.sh "$arm" + +docker cp nitro-fork-arm:/home/ubuntu/app.apk - | python3 -I "$benchmark/fork/export_apk.py" "$RUNNER_TEMP/exported.apk" +bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/exported.apk" "$RUNNER_TEMP/$arm.apk" diff --git a/scripts/performance/fork/export_apk.py b/scripts/performance/fork/export_apk.py new file mode 100644 index 000000000..9bf8d5bd6 --- /dev/null +++ b/scripts/performance/fork/export_apk.py @@ -0,0 +1,15 @@ +"""Copy one regular APK from docker cp's stdout to a known host path.""" + +import shutil +import sys +import tarfile + + +with tarfile.open(fileobj=sys.stdin.buffer, mode="r|") as archive: + member = archive.next() + if member is None or member.name != "app.apk" or not member.isfile() or not 0 < member.size <= 256 * 1024 * 1024: + raise SystemExit("The build must produce one regular APK of at most 256 MiB.") + with archive.extractfile(member) as source, open(sys.argv[1], "xb") as target: + shutil.copyfileobj(source, target) + if archive.next() is not None: + raise SystemExit("Unexpected additional entries in the APK export.") diff --git a/scripts/performance/fork/prefetch.sh b/scripts/performance/fork/prefetch.sh new file mode 100755 index 000000000..4fb7b7b24 --- /dev/null +++ b/scripts/performance/fork/prefetch.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${PERF_MAVEN_USER:?Set the PerfKit package reader in the repository Actions secrets}" +: "${PERF_MAVEN_TOKEN:?Set the token with read access to the PerfKit GitHub Packages}" +version=$(python3 scripts/performance/prepare.py --sdk-version) +registry=https://maven.pkg.github.com/callstackincubator/performance-analytics +for artifact in performance-analytics-android performance-analytics-core-cpp; do + path="com/callstack/$artifact/$version" + mkdir -p "$RUNNER_TEMP/maven/$path" + for extension in pom module aar; do + file="$path/$artifact-$version.$extension" + curl --silent --show-error --fail --location --proto '=https' --retry 3 \ + --user "$PERF_MAVEN_USER:$PERF_MAVEN_TOKEN" "$registry/$file" --output "$RUNNER_TEMP/maven/$file" + done +done diff --git a/scripts/performance/fork/sign-apk.sh b/scripts/performance/fork/sign-apk.sh new file mode 100755 index 000000000..5018c0ff7 --- /dev/null +++ b/scripts/performance/fork/sign-apk.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Verify the manifest outside the fork's build, then install with a fresh app identity. +arm=$1 +apk=$2 +destination=$3 +manifest="$RUNNER_TEMP/$arm-manifest.xml" +"$ANDROID_HOME/cmdline-tools/latest/bin/apkanalyzer" manifest print "$apk" > "$manifest" +python3 -I - "$manifest" "$arm" <<'PY' +import sys +from xml.etree import ElementTree + +root = ElementTree.parse(sys.argv[1]).getroot() +android = "{http://schemas.android.com/apk/res/android}" +if root.get("package") != "com.margelo.reactnitro.example." + sys.argv[2] or root.get(android + "sharedUserId"): + raise SystemExit("Expected the benchmark package with its own application UID.") +app = root.find("application") +if app is None or app.get(android + "debuggable", "false") != "false" or root.find("instrumentation") is not None: + raise SystemExit("Expected a non-debuggable application APK.") +PY +key="$RUNNER_TEMP/$arm.jks" +keytool -genkeypair -alias benchmark -keyalg RSA -keysize 2048 -validity 2 \ + -keystore "$key" -storepass ephemeral -keypass ephemeral -dname "CN=ADC benchmark" -noprompt +signer="$ANDROID_HOME/build-tools/36.0.0/apksigner" +"$signer" sign --ks "$key" --ks-pass pass:ephemeral --key-pass pass:ephemeral --v4-signing-enabled false --out "$destination" "$apk" +"$signer" verify "$destination" diff --git a/scripts/performance/prepare.py b/scripts/performance/prepare.py index f7eb30e48..619e500ae 100644 --- a/scripts/performance/prepare.py +++ b/scripts/performance/prepare.py @@ -14,11 +14,7 @@ exclusiveContent { forRepository { maven { - url = uri("https://maven.pkg.github.com/callstackincubator/performance-analytics") - credentials { - username = providers.environmentVariable("PERF_MAVEN_USER").get() - password = providers.environmentVariable("PERF_MAVEN_TOKEN").get() - } +MAVEN_SOURCE } } filter { includeGroup("com.callstack") } @@ -26,6 +22,13 @@ } """ +GITHUB_PACKAGES = """ url = uri("https://maven.pkg.github.com/callstackincubator/performance-analytics") + credentials { + username = providers.environmentVariable("PERF_MAVEN_USER").get() + password = providers.environmentVariable("PERF_MAVEN_TOKEN").get() + }""" + + APP_ID = """ android.defaultConfig { val arm = rootProject.file("../.nitro/performance/arm").readText().trim() @@ -51,6 +54,8 @@ def append_once(path, addition): parser.add_argument("arm", choices=("baseline", "candidate")) parser.add_argument("--workload", type=Path, default=default_workload, help="Harness workload to embed in both APKs") +parser.add_argument("--local-maven", type=Path, help="Read the PerfKit artifacts from an offline Maven repository") +parser.add_argument("--sdk-version", action="version", version=SDK_VERSION) args = parser.parse_args() checkout = args.checkout.resolve() @@ -59,7 +64,12 @@ def append_once(path, addition): manifest = json.loads(package.read_text()) manifest["dependencies"]["@callstack/performance-analytics-react-nitro"] = SDK_VERSION package.write_text(json.dumps(manifest, indent=2) + "\n") -append_once(app / "android/settings.gradle.kts", MAVEN_REPOSITORY) +if args.local_maven: + local_uri = args.local_maven.resolve().as_uri() + maven_source = f' url = uri("{local_uri}")' +else: + maven_source = GITHUB_PACKAGES +append_once(app / "android/settings.gradle.kts", MAVEN_REPOSITORY.replace("MAVEN_SOURCE", maven_source)) append_once(app / "android/app/build.gradle.kts", APP_ID.replace("SDK_VERSION", SDK_VERSION)) stage = app / ".nitro/performance" stage.mkdir(parents=True, exist_ok=True) diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 3cc5c6b00..20347fe99 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -4,6 +4,7 @@ import hashlib import json import os +import re from datetime import datetime, timezone from pathlib import Path import subprocess @@ -38,14 +39,21 @@ def write_json(path, value): path.write_text(json.dumps(value, indent=2) + "\n") -def describe_apks(builds): +def describe_apks(builds, staged_fixture=None): arms = {} for variant in VARIANTS: root, apk = builds[variant] - fixture = root / WORKLOAD + if staged_fixture is None: + fixture = root / WORKLOAD + revision = output(["git", "-C", root, "rev-parse", "HEAD"]) + else: + fixture = staged_fixture + revision = str(root) + if not re.fullmatch(r"[a-f0-9]{40}", revision): + raise ValueError(f"Expected the immutable {variant} commit SHA for a prebuilt APK") arms[variant] = { "applicationId": f"com.margelo.reactnitro.example.{variant}", - "ref": output(["git", "-C", root, "rev-parse", "HEAD"]), + "ref": revision, "apkSha256": sha256(apk), "fixtureSha256": sha256(fixture), } @@ -58,7 +66,8 @@ def describe_apks(builds): def main(): parser = argparse.ArgumentParser(description=__doc__) for variant in VARIANTS: - parser.add_argument(f"--{variant}", required=True, nargs=2, type=Path, metavar=("CHECKOUT", "APK")) + parser.add_argument(f"--{variant}", required=True, nargs=2, type=Path, metavar=("CHECKOUT_OR_SHA", "APK")) + parser.add_argument("--staged-fixture", type=Path, help="Trusted fixture for prebuilt APKs, with a commit SHA per arm") parser.add_argument("--pairs", type=int, default=DEFAULT_MAX_PAIRS, help="Maximum number of measured pairs") parser.add_argument("--target-pp", type=float, default=5.0, help="Precision target in percentage points") parser.add_argument("--thread-counters", action="store_true", help="Open PerfKit thread windows in each workload") @@ -81,7 +90,7 @@ def main(): lease = os.environ["ADC_LEASE_ID"] builds = {variant: getattr(args, variant) for variant in VARIANTS} try: - arms = describe_apks(builds) + arms = describe_apks(builds, args.staged_fixture) except ValueError as error: parser.error(str(error)) for variant, arm in arms.items(): From 694dce509e6bde3efe8410d6fbfb82b15bb8d33c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 15:45:53 +0100 Subject: [PATCH 02/12] ci(performance): verify fork APKs before upload --- scripts/performance/fork/build.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/performance/fork/build.sh b/scripts/performance/fork/build.sh index 9559b2898..81e756ba8 100755 --- a/scripts/performance/fork/build.sh +++ b/scripts/performance/fork/build.sh @@ -27,4 +27,5 @@ docker run --name nitro-fork-arm --network nitro-build --cap-drop ALL \ nitro-fork-builder bash /benchmark/fork/build-arm.sh "$arm" docker cp nitro-fork-arm:/home/ubuntu/app.apk - | python3 -I "$benchmark/fork/export_apk.py" "$RUNNER_TEMP/exported.apk" -bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/exported.apk" "$RUNNER_TEMP/$arm.apk" +bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/exported.apk" "$RUNNER_TEMP/$arm-from-build.apk" +bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/$arm-from-build.apk" "$RUNNER_TEMP/$arm.apk" From 435684e56a5ada36f1e440d0482e5c46bc9ab560 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 15:49:49 +0100 Subject: [PATCH 03/12] fix(ci): sign each exported benchmark APK once --- scripts/performance/fork/build.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/performance/fork/build.sh b/scripts/performance/fork/build.sh index 81e756ba8..9559b2898 100755 --- a/scripts/performance/fork/build.sh +++ b/scripts/performance/fork/build.sh @@ -27,5 +27,4 @@ docker run --name nitro-fork-arm --network nitro-build --cap-drop ALL \ nitro-fork-builder bash /benchmark/fork/build-arm.sh "$arm" docker cp nitro-fork-arm:/home/ubuntu/app.apk - | python3 -I "$benchmark/fork/export_apk.py" "$RUNNER_TEMP/exported.apk" -bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/exported.apk" "$RUNNER_TEMP/$arm-from-build.apk" -bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/$arm-from-build.apk" "$RUNNER_TEMP/$arm.apk" +bash "$benchmark/fork/sign-apk.sh" "$arm" "$RUNNER_TEMP/exported.apk" "$RUNNER_TEMP/$arm.apk" From 6314b400420f2a4d31d68f2fbecf71776f798b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 16:31:11 +0100 Subject: [PATCH 04/12] ci(performance): run fork checks on private runners and CI storage --- .github/workflows/fork-performance.yml | 106 ++++++++++++++++--------- scripts/performance/README.md | 6 +- 2 files changed, 72 insertions(+), 40 deletions(-) diff --git a/.github/workflows/fork-performance.yml b/.github/workflows/fork-performance.yml index ad69ba3f3..f65248048 100644 --- a/.github/workflows/fork-performance.yml +++ b/.github/workflows/fork-performance.yml @@ -9,7 +9,7 @@ permissions: {} jobs: authorize: if: github.event.issue.pull_request && (github.event.comment.body == '/check' || startsWith(github.event.comment.body, '/check ')) - runs-on: ubuntu-24.04 + runs-on: [self-hosted, linux, X64, hetzner-cx23] permissions: contents: read pull-requests: read @@ -17,11 +17,22 @@ jobs: outputs: base: ${{ steps.request.outputs.base }} head: ${{ steps.request.outputs.head }} + storage_uri: ${{ steps.storage.outputs.uri }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.sha }} persist-credentials: false + - &github-cli + name: Install GitHub CLI for this job + run: | + directory=$(mktemp -d "$RUNNER_TEMP/gh.XXXXXX") + asset=gh_2.106.0_linux_amd64 + curl --fail --silent --show-error --location --retry 3 \ + "https://github.com/cli/cli/releases/download/v2.106.0/$asset.tar.gz" -o "$directory/gh.tar.gz" + (cd "$directory" && echo 'a476449fa9625413c54a3734eded62e9e480e49f421ff08e7f3b3879c059a033 gh.tar.gz' | sha256sum --check) + tar -xzf "$directory/gh.tar.gz" -C "$directory" --strip-components=2 "$asset/bin/gh" + echo "$directory" >> "$GITHUB_PATH" - id: request name: Resolve the authorized fork revision env: @@ -39,23 +50,33 @@ jobs: env: PERF_MAVEN_USER: ${{ secrets.PERF_MAVEN_USER }} PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} - run: bash scripts/performance/fork/prefetch.sh - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: fork-check-maven - path: ${{ runner.temp }}/maven - if-no-files-found: error - overwrite: true - retention-days: 1 + run: | + rm -rf -- "$RUNNER_TEMP/maven" + bash scripts/performance/fork/prefetch.sh + - name: Upload PerfKit files to CI storage + id: storage + env: &ci-storage + AWS_ACCESS_KEY_ID: ${{ secrets.CI_S3_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.CI_S3_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: garage + AWS_ENDPOINT_URL_S3: ${{ vars.CI_S3_ENDPOINT_URL }} + CI_S3_BUCKET: ${{ vars.CI_S3_BUCKET }} + run: | + uri="s3://$CI_S3_BUCKET/runs/$GITHUB_RUN_ID/$GITHUB_RUN_ATTEMPT/fork-performance" + aws s3 cp "$RUNNER_TEMP/maven/" "$uri/maven/" --recursive --no-follow-symlinks --only-show-errors + echo "uri=$uri" >> "$GITHUB_OUTPUT" build: needs: authorize permissions: contents: read + env: + AUTH_STORAGE_URI: ${{ needs.authorize.outputs.storage_uri }} + ARM: ${{ matrix.arm }} strategy: matrix: arm: [baseline, candidate] - runs-on: ubuntu-24.04 + runs-on: [self-hosted, linux, X64, nitro-fork-build] timeout-minutes: 180 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 @@ -69,10 +90,12 @@ jobs: ref: ${{ matrix.arm == 'baseline' && needs.authorize.outputs.base || needs.authorize.outputs.head }} persist-credentials: false submodules: false - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: fork-check-maven - path: maven + - name: Download PerfKit files from CI storage + env: *ci-storage + run: | + rm -rf -- maven + mkdir maven + aws s3 cp "$AUTH_STORAGE_URI/maven/" maven/ --recursive --only-show-errors - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.4 @@ -80,37 +103,42 @@ jobs: run: | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'build-tools;35.0.0' 'build-tools;36.0.0' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools - name: Build the Release APK in an isolated container - env: - ARM: ${{ matrix.arm }} run: bash trusted/scripts/performance/fork/build.sh "$ARM" - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: fork-check-${{ matrix.arm }}-apk - path: ${{ runner.temp }}/${{ matrix.arm }}.apk - if-no-files-found: error - compression-level: 0 - overwrite: true - retention-days: 1 + - name: Upload signed APK to CI storage + env: *ci-storage + run: | + uri="s3://$CI_S3_BUCKET/runs/$GITHUB_RUN_ID/$GITHUB_RUN_ATTEMPT/fork-performance/$ARM.apk" + aws s3 cp "$RUNNER_TEMP/$ARM.apk" "$uri" --only-show-errors + # A partial matrix rerun can produce each arm in a different attempt. + printf '%s\n' "$GITHUB_RUN_ATTEMPT" | aws s3 cp - "$AUTH_STORAGE_URI/$ARM.attempt" --only-show-errors compare: needs: [authorize, build] permissions: contents: read - runs-on: ubuntu-24.04 + runs-on: [self-hosted, linux, X64, hetzner-cx23] timeout-minutes: 60 env: BASE_SHA: ${{ needs.authorize.outputs.base }} HEAD_SHA: ${{ needs.authorize.outputs.head }} + AUTH_STORAGE_URI: ${{ needs.authorize.outputs.storage_uri }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: ref: ${{ github.sha }} persist-credentials: false - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - pattern: fork-check-*-apk - merge-multiple: true - path: apks + - name: Download signed APKs from CI storage + id: apks + env: *ci-storage + run: | + rm -rf -- apks results + mkdir apks + for arm in baseline candidate; do + attempt=$(aws s3 cp "$AUTH_STORAGE_URI/$arm.attempt" - --only-show-errors) + [[ "$attempt" =~ ^[1-9][0-9]*$ ]] + uri="s3://$CI_S3_BUCKET/runs/$GITHUB_RUN_ID/$attempt/fork-performance/$arm.apk" + aws s3 cp "$uri" "apks/$arm.apk" --only-show-errors + done - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: 1.4.4 @@ -139,22 +167,24 @@ jobs: printf 'Base %s · candidate %s\n\n' "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_STEP_SUMMARY" python3 scripts/performance/thread-counters/analyze_fixed.py --markdown results > results/report.md cat results/report.md >> "$GITHUB_STEP_SUMMARY" - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - if: ${{ !cancelled() && hashFiles('results/session.json') != '' }} - with: - name: fork-check-readings - path: results - overwrite: true - retention-days: 7 + - name: Upload benchmark readings to CI storage + if: ${{ !cancelled() && steps.apks.outcome == 'success' && hashFiles('results/session.json') != '' }} + env: *ci-storage + run: | + uri="s3://$CI_S3_BUCKET/runs/$GITHUB_RUN_ID/$GITHUB_RUN_ATTEMPT/fork-performance/results/" + aws s3 cp results/ "$uri" --recursive --no-follow-symlinks --only-show-errors --exclude '*' \ + --include session.json --include raw.jsonl --include report.md --include 'warmup-*.json' --include 'pair-*.json' + printf '\nRaw measurements in %s\n' "$uri" >> "$GITHUB_STEP_SUMMARY" status: needs: [authorize, build, compare] if: always() && needs.authorize.outputs.head != '' - runs-on: ubuntu-24.04 + runs-on: [self-hosted, linux, X64, hetzner-cx23] permissions: pull-requests: read statuses: write steps: + - *github-cli - name: Publish the result on the reviewed commit env: GH_TOKEN: ${{ github.token }} diff --git a/scripts/performance/README.md b/scripts/performance/README.md index bef1f2af9..1566ecd83 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -30,9 +30,11 @@ python3 scripts/performance/analyze.py --session ../performance-run/session.json ## Running a fork PR with /check -A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary and downloadable readings. A successful run means the comparison completed. Read the intervals before merging. +A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary. The summary gives the path to the raw readings in private CI storage, where run artifacts expire after one day. A successful run means the comparison completed. Read the intervals before merging. -The upstream workflow pins the base and head from GitHub. A trusted job downloads the published PerfKit Maven artifacts with the same package reader as the internal benchmark. Each arm builds in its own disposable GitHub-hosted VM. The isolated build container sees the source, Android toolchain and dependency files, with public network access for package downloads. Git submodules resolve inside the container. Host credentials, Actions runtime files, Docker sockets, shared caches and private network services are outside the build. The host exports one size-limited regular APK, verifies its package and application UID, and signs each arm with a fresh key. A fresh trusted runner executes the upstream driver against those APKs on ADC. Fork code controls its own Android process and can misrepresent its timings. Review the code and benchmark behavior before treating results as evidence. +The authorize, compare and status jobs use the private Linux x64 pool labeled `hetzner-cx23`. The authorize job pins the base and head from GitHub, downloads the PerfKit Maven dependencies and stages them in the private CI bucket. Each revision builds on its own self-hosted Linux x64 VM labeled `nitro-fork-build`. Assign this label to single-job workers that are destroyed after use. They need Docker, permission to configure its network firewall, the Android SDK, JDK 17 and the private CI storage connection. + +The build container receives the source, Android toolchain and dependency files. It resolves public dependencies and Git submodules with public network access. Host credentials, Actions runtime files, Docker sockets, shared caches and private network services stay outside the container. The host exports one size-limited regular APK, verifies its package and application UID, signs it with a fresh key and uploads it to CI storage. The trusted upstream driver then runs both APKs on ADC. Fork code controls its Android process and can misrepresent its timings. Review the code and benchmark behavior before treating results as evidence. This private repository disables ordinary workflows from fork PRs in Actions settings. Keep that setting while other workflows run on persistent self-hosted machines. Before making the repository public, restrict the runner groups to trusted workflow refs or move fork builds to isolated hosted runners. A condition inside a fork-editable workflow cannot enforce that runner policy. [GitHub Actions security guidance](https://docs.github.com/en/actions/reference/security/secure-use) From 91c5fb190d6f534defea7849c2a513f57af5bfda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 16:55:05 +0100 Subject: [PATCH 05/12] ci(performance): build fork APKs on single-job Hetzner runners --- .github/workflows/fork-performance.yml | 52 ++- .github/workflows/fork-worker.yml | 76 ++++ scripts/performance/README.md | 8 +- scripts/performance/fork/bootstrap-runner.sh | 54 +++ scripts/performance/fork/hetzner_runner.py | 368 +++++++++++++++++++ 5 files changed, 540 insertions(+), 18 deletions(-) create mode 100644 .github/workflows/fork-worker.yml create mode 100755 scripts/performance/fork/bootstrap-runner.sh create mode 100644 scripts/performance/fork/hetzner_runner.py diff --git a/.github/workflows/fork-performance.yml b/.github/workflows/fork-performance.yml index f65248048..c8ccd3cb3 100644 --- a/.github/workflows/fork-performance.yml +++ b/.github/workflows/fork-performance.yml @@ -3,6 +3,8 @@ name: Fork performance check on: issue_comment: types: [created] + schedule: + - cron: '41 * * * *' permissions: {} @@ -68,42 +70,42 @@ jobs: build: needs: authorize + environment: nitro-fork-infrastructure + concurrency: + group: nitro-fork-hetzner-worker + queue: max permissions: contents: read + actions: write env: AUTH_STORAGE_URI: ${{ needs.authorize.outputs.storage_uri }} ARM: ${{ matrix.arm }} strategy: + fail-fast: false matrix: arm: [baseline, candidate] - runs-on: [self-hosted, linux, X64, nitro-fork-build] - timeout-minutes: 180 + runs-on: [self-hosted, linux, X64, hetzner-cx23] + timeout-minutes: 210 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - path: trusted ref: ${{ github.sha }} persist-credentials: false - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - path: source - ref: ${{ matrix.arm == 'baseline' && needs.authorize.outputs.base || needs.authorize.outputs.head }} - persist-credentials: false - submodules: false - name: Download PerfKit files from CI storage env: *ci-storage run: | rm -rf -- maven mkdir maven aws s3 cp "$AUTH_STORAGE_URI/maven/" maven/ --recursive --only-show-errors - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.4 - - name: Prepare Android tooling + - name: Build on a single-job Hetzner runner + env: + HETZNER_FORK_TOKEN: ${{ secrets.HETZNER_FORK_TOKEN }} + FORK_RUNNER_ADMIN_TOKEN: ${{ secrets.FORK_RUNNER_ADMIN_TOKEN }} + ACTIONS_TOKEN: ${{ github.token }} + SOURCE_SHA: ${{ matrix.arm == 'baseline' && needs.authorize.outputs.base || needs.authorize.outputs.head }} run: | - "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'build-tools;35.0.0' 'build-tools;36.0.0' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools - - name: Build the Release APK in an isolated container - run: bash trusted/scripts/performance/fork/build.sh "$ARM" + python3 -I scripts/performance/fork/hetzner_runner.py build --arm "$ARM" --source-sha "$SOURCE_SHA" \ + --maven "$GITHUB_WORKSPACE/maven" --output "$RUNNER_TEMP/$ARM.apk" - name: Upload signed APK to CI storage env: *ci-storage run: | @@ -209,3 +211,21 @@ jobs: gh api --silent "repos/$GITHUB_REPOSITORY/statuses/$HEAD_SHA" -f state="$state" \ -f context='ADC /check' -f description="$description" \ -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + + reap: + if: github.event_name == 'schedule' + runs-on: [self-hosted, linux, X64, hetzner-cx23] + environment: nitro-fork-infrastructure + permissions: + contents: read + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Remove expired fork build workers + env: + HETZNER_FORK_TOKEN: ${{ secrets.HETZNER_FORK_TOKEN }} + FORK_RUNNER_ADMIN_TOKEN: ${{ secrets.FORK_RUNNER_ADMIN_TOKEN }} + run: python3 -I scripts/performance/fork/hetzner_runner.py reap diff --git a/.github/workflows/fork-worker.yml b/.github/workflows/fork-worker.yml new file mode 100644 index 000000000..a37c1f2a2 --- /dev/null +++ b/.github/workflows/fork-worker.yml @@ -0,0 +1,76 @@ +name: Fork APK worker +run-name: Fork worker ${{ inputs.job_label }} + +on: + workflow_dispatch: + inputs: + job_label: + description: Unique label of the single-job VM + required: true + type: string + control_sha: + description: Default-branch workflow commit that authorized the build + required: true + type: string + source_sha: + description: Reviewed source commit to build + required: true + type: string + arm: + description: APK identity + required: true + type: choice + options: [baseline, candidate] + +permissions: + contents: read + +jobs: + build: + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && startsWith(inputs.job_label, 'nitro-fork-') + runs-on: [self-hosted, linux, X64, nitro-fork-build, "${{ inputs.job_label }}"] + timeout-minutes: 150 + env: + ARM: ${{ inputs.arm }} + steps: + - name: Verify the requested revisions + env: + JOB_LABEL: ${{ inputs.job_label }} + SOURCE_SHA: ${{ inputs.source_sha }} + CONTROL_SHA: ${{ inputs.control_sha }} + GH_TOKEN: ${{ github.token }} + run: | + set -o pipefail + [[ "$JOB_LABEL" =~ ^nitro-fork-[0-9a-f]{32}$ ]] + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$CONTROL_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$ARM" == baseline || "$ARM" == candidate ]] + if [[ "$CONTROL_SHA" != "$GITHUB_SHA" ]]; then + curl --silent --show-error --fail --retry 3 -H "Authorization: Bearer $GH_TOKEN" \ + "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/compare/$CONTROL_SHA...$GITHUB_SHA?per_page=1" \ + | jq --slurp --exit-status --arg sha "$CONTROL_SHA" 'length == 1 and .[0].merge_base_commit.sha == $sha' >/dev/null + fi + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: trusted + ref: ${{ inputs.control_sha }} + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + path: source + ref: ${{ inputs.source_sha }} + submodules: false + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.4 + - name: Prepare build dependencies + run: | + cp -R /opt/nitro-fork/maven maven + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'build-tools;35.0.0' 'build-tools;36.0.0' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools + - name: Build and sign the Release APK + run: | + bash trusted/scripts/performance/fork/build.sh "$ARM" + apk="$RUNNER_TEMP/$ARM.apk" + [[ -f "$apk" && ! -L "$apk" ]] + install -m 0600 "$apk" /home/nitro-runner/output.apk diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 1566ecd83..d7b8e12b6 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -32,9 +32,13 @@ python3 scripts/performance/analyze.py --session ../performance-run/session.json A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary. The summary gives the path to the raw readings in private CI storage, where run artifacts expire after one day. A successful run means the comparison completed. Read the intervals before merging. -The authorize, compare and status jobs use the private Linux x64 pool labeled `hetzner-cx23`. The authorize job pins the base and head from GitHub, downloads the PerfKit Maven dependencies and stages them in the private CI bucket. Each revision builds on its own self-hosted Linux x64 VM labeled `nitro-fork-build`. Assign this label to single-job workers that are destroyed after use. They need Docker, permission to configure its network firewall, the Android SDK, JDK 17 and the private CI storage connection. +The private `hetzner-cx23` runners authorize the request, supervise the builds and run the comparison. Builds share one queue across PRs so only one disposable VM is needed at a time. Each build gets a fresh Hetzner CX43 in Falkenstein in the `HetznerDefault` project. The supervisor stages the six PerfKit Maven files over SSH, registers the VM with GitHub for one job and calls the worker workflow with a unique label. The worker builds the reviewed commit in a container, validates the APK and applies a fresh signing key. The supervisor verifies which runner finished the job, collects the APK over SSH, uploads it to private CI storage and deletes the VM. An hourly cleanup removes abandoned project VMs older than 3½ hours after checking their repository label, name and ownership. -The build container receives the source, Android toolchain and dependency files. It resolves public dependencies and Git submodules with public network access. Host credentials, Actions runtime files, Docker sockets, shared caches and private network services stay outside the container. The host exports one size-limited regular APK, verifies its package and application UID, signs it with a fresh key and uploads it to CI storage. The trusted upstream driver then runs both APKs on ADC. Fork code controls its Android process and can misrepresent its timings. Review the code and benchmark behavior before treating results as evidence. +Only the persistent supervisors have access to the cloud and runner-management credentials. The worker has read access to the source repository for checkout. The fork's build container receives the source tree, Android toolchain and dependency files. It has public network access for dependencies and submodules. The trusted upstream driver runs the signed apps on ADC. Fork code can misrepresent its timings, so review the implementation before relying on the measurements. + +#### Credentials for the supervisors + +Use a GitHub Environment named `nitro-fork-infrastructure` restricted to the default branch. Store a dedicated read/write API token for the intended Hetzner project as `HETZNER_FORK_TOKEN`. Store a GitHub fine-grained access token scoped to this repository with the **Administration: write** permission as `FORK_RUNNER_ADMIN_TOKEN`. GitHub requires this permission to issue single-job runner registrations. The existing ADC, Maven and private CI storage credentials stay in their respective upstream workflow steps. [GitHub runner registration](https://docs.github.com/en/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository) This private repository disables ordinary workflows from fork PRs in Actions settings. Keep that setting while other workflows run on persistent self-hosted machines. Before making the repository public, restrict the runner groups to trusted workflow refs or move fork builds to isolated hosted runners. A condition inside a fork-editable workflow cannot enforce that runner policy. [GitHub Actions security guidance](https://docs.github.com/en/actions/reference/security/secure-use) diff --git a/scripts/performance/fork/bootstrap-runner.sh b/scripts/performance/fork/bootstrap-runner.sh new file mode 100755 index 000000000..3beeec7a5 --- /dev/null +++ b/scripts/performance/fork/bootstrap-runner.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Run as root on a new Ubuntu 24.04 x64 VM before issuing its one-job credential. +set -euo pipefail + +export DEBIAN_FRONTEND=noninteractive +apt-get -o Acquire::Retries=3 update -qq +apt-get -o DPkg::Lock::Timeout=180 -o Acquire::Retries=3 install -y --no-install-recommends \ + ca-certificates curl docker.io git iptables jq libicu74 openjdk-21-jdk-headless python3 sudo unzip +systemctl enable --now docker + +useradd --create-home --shell /bin/bash --groups docker nitro-runner +printf '%s\n' 'nitro-runner ALL=(root) NOPASSWD: /usr/sbin/iptables' > /etc/sudoers.d/nitro-runner +chmod 0440 /etc/sudoers.d/nitro-runner +visudo --check --file=/etc/sudoers.d/nitro-runner + +downloads=$(mktemp -d) +cd "$downloads" +runner=actions-runner-linux-x64-2.338.2.tar.gz +curl --fail --silent --show-error --location --retry 3 -o "$runner" "https://github.com/actions/runner/releases/download/v2.338.2/$runner" +echo "baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40 $runner" | sha256sum --check +runner_dir=/home/nitro-runner/actions-runner +install -d -o nitro-runner -g nitro-runner "$runner_dir" +tar --extract --gzip --file="$runner" --directory="$runner_dir" --no-same-owner +chown -R nitro-runner:nitro-runner "$runner_dir" +rm -- "$runner" + +sdk=commandlinetools-linux-15859902_latest.zip +curl --fail --silent --show-error --location --retry 3 -o "$sdk" "https://dl.google.com/android/repository/$sdk" +echo "4e4c464f145a7512b57d088ac6c278c03c9eea610886b35a5e0804e74eedf583 $sdk" | sha256sum --check +mkdir -p /opt/android-sdk/cmdline-tools +unzip -q "$sdk" -d /opt/android-sdk/cmdline-tools +mv /opt/android-sdk/cmdline-tools/cmdline-tools /opt/android-sdk/cmdline-tools/latest +rm -- "$sdk" +cd / +rmdir "$downloads" +chown -R nitro-runner:nitro-runner /opt/android-sdk +# sdkmanager closes its input after the final license. Use its exit status for this pipeline. +(set +o pipefail; yes | runuser -u nitro-runner -- /opt/android-sdk/cmdline-tools/latest/bin/sdkmanager --sdk_root=/opt/android-sdk --licenses >/dev/null) + +cat > /usr/local/sbin/nitro-start-runner <<'START' +#!/usr/bin/env bash +set -euo pipefail +cd /home/nitro-runner/actions-runner +exec runuser -u nitro-runner -- env -i \ + HOME=/home/nitro-runner USER=nitro-runner PATH=/usr/local/bin:/usr/bin:/bin \ + JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 ANDROID_HOME=/opt/android-sdk \ + bash -euc ' + ACTIONS_RUNNER_INPUT_JITCONFIG=$(cat) + test -n "$ACTIONS_RUNNER_INPUT_JITCONFIG" + export ACTIONS_RUNNER_INPUT_JITCONFIG + exec ./run.sh + ' +START +chmod 0755 /usr/local/sbin/nitro-start-runner diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py new file mode 100644 index 000000000..d43896beb --- /dev/null +++ b/scripts/performance/fork/hetzner_runner.py @@ -0,0 +1,368 @@ +"""Build one reviewed revision on one disposable Hetzner VM, or reap expired VMs.""" +import argparse +import base64 +import hashlib +import ipaddress +import json +import os +from pathlib import Path +import re +import resource +import secrets +import signal +import subprocess +import tempfile +import time +from datetime import datetime, timedelta, timezone +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + + +REPO = "margelo/react-nitro" +REPOSITORY_ID = "1373493776" +WORKFLOW = "fork-worker.yml" +OWNER = {"managed-by": "nitro-fork-check", "github-repo-id": REPOSITORY_ID} +# Includes cold provisioning and the Android build. Reaping starts after this deadline. +BUILD_SECONDS = 3 * 60 * 60 +MAX_APK = 256 * 1024 * 1024 +BOOTSTRAP = Path(__file__).with_name("bootstrap-runner.sh") + + +class Api: + def __init__(self, url, token, github=False): + self.url = url + self.headers = {"Authorization": "Bearer " + token, "Content-Type": "application/json"} + if github: + self.headers.update({"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2026-03-10"}) + + def request(self, method, path, body=None, *, missing_ok=False): + data = json.dumps(body).encode() if body is not None else None + req = Request(self.url + path, data=data, headers=self.headers, method=method) + for attempt in range(3): + try: + with urlopen(req, timeout=30) as response: + payload = response.read() + break + except HTTPError as error: + if missing_ok and error.code == 404: + return None + if method != "GET" or attempt == 2 or error.code not in (429, 502, 503, 504): + # Error bodies can contain credentials or runner user-data. + raise RuntimeError(f"{method} {path}: HTTP {error.code}") from None + except (URLError, TimeoutError): + if method != "GET" or attempt == 2: + raise + time.sleep(2 ** attempt) + return json.loads(payload) if payload else {} + + +def name_for(key): + return "nitro-fork-" + key + + +def labels_for(key, arm): + return {**OWNER, "worker": key, "arm": arm} + + +def owned(server, key, arm): + labels = server["labels"] + return (re.fullmatch("[0-9a-f]{32}", key) is not None + and arm in ("baseline", "candidate") and server["name"] == name_for(key) + and labels_for(key, arm).items() <= labels.items()) + + +def remaining(deadline): + seconds = deadline - time.monotonic() + if seconds <= 0: + raise TimeoutError("The disposable build exceeded its deadline") + return seconds + + +def wait(deadline, interval=5): + time.sleep(min(interval, remaining(deadline))) + + +def keys(directory, key): + def generate(name): + path = directory / name + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "", "-f", path], check=True) + public = path.with_suffix(".pub").read_text().strip() + return path, public + + identity, public = generate("client") + host, host_public = generate("host") + known = directory / "known_hosts" + alias = name_for(key) + known.write_text(f"{alias} {host_public}\n") + # JSON is valid YAML. This supplies only keys specific to this disposable VM. + config = {"disable_root": False, "ssh_pwauth": False, + "users": [{"name": "root", "lock_passwd": True, "ssh_authorized_keys": [public]}], + "ssh_keys": {"ed25519_private": host.read_text(), "ed25519_public": host_public}} + user_data = "#cloud-config\n" + json.dumps(config) + ssh = ["ssh", "-F", "/dev/null", "-i", str(identity), "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", + "-o", f"HostKeyAlias={alias}", "-o", f"UserKnownHostsFile={known}", "-o", "GlobalKnownHostsFile=/dev/null", + "-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlgorithms=ssh-ed25519", + "-o", "ConnectTimeout=5", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=4"] + return user_data, ssh + + +def find_server(cloud, key): + query = urlencode({"name": name_for(key)}) + matches = cloud.request("GET", "/servers?" + query)["servers"] + return matches[0] if matches else None + + +def delete_server(cloud, server_id, key, arm): + path = f"/servers/{server_id}" + result = cloud.request("GET", path, missing_ok=True) + if result is None: + return + if not owned(result["server"], key, arm): + raise RuntimeError("Refusing to delete a server whose identity or ownership differs") + cloud.request("DELETE", path, missing_ok=True) + deadline = time.monotonic() + 120 + while cloud.request("GET", path, missing_ok=True) is not None: + wait(deadline, 3) + print(f"Deleted Hetzner server {server_id} ({name_for(key)})", flush=True) + + +def remove_runner(admin, name, runner_id=None): + if runner_id is None: + data = admin.request("GET", "/actions/runners?" + urlencode({"name": name})) + runners = [item for item in data["runners"] if item["name"] == name] + if len(runners) != 1: + if runners: + raise RuntimeError("Multiple registrations match one disposable runner") + return + runner_id = runners[0]["id"] + path = f"/actions/runners/{runner_id}" + runner = admin.request("GET", path, missing_ok=True) + if runner is None: + return + if runner["name"] != name or name not in [label["name"] for label in runner["labels"]]: + raise RuntimeError("Refusing to remove an unrelated runner") + admin.request("DELETE", path, missing_ok=True) + + +def ready(ssh): + deadline = time.monotonic() + 5 * 60 + while True: + probe = subprocess.run([*ssh, "true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) + if probe.returncode == 0: + break + wait(deadline) + subprocess.run([*ssh, "cloud-init status --wait"], timeout=240, check=True) + + +def stage(ssh, maven): + with BOOTSTRAP.open("rb") as script: + subprocess.run([*ssh, "bash -se"], stdin=script, timeout=30 * 60, check=True) + with tempfile.TemporaryFile() as dependencies: + subprocess.run(["tar", "-C", maven, "-cf", "-", "."], stdout=dependencies, check=True) + dependencies.seek(0) + subprocess.run([*ssh, "mkdir -p /opt/nitro-fork/maven && tar -xf - -C /opt/nitro-fork/maven"], + stdin=dependencies, timeout=180, check=True) + + +def receive(ssh, command, destination, limit, timeout): + def limit_output_size(): + # Limit the local receiver even if the guest ignores the requested command. + resource.setrlimit(resource.RLIMIT_FSIZE, (limit + 1, limit + 1)) + + subprocess.run([*ssh, command], stdout=destination, stderr=subprocess.DEVNULL, + preexec_fn=limit_output_size, timeout=timeout, check=True) + if destination.tell() > limit: + raise ValueError("Worker response exceeded the allowed size") + + +def collect_apk(ssh, output): + source = "/home/nitro-runner/output.apk" + check = f"test -f {source} && test ! -L {source} && stat --format='%s' {source} && sha256sum {source}" + with tempfile.TemporaryFile() as metadata: + receive(ssh, check, metadata, limit=256, timeout=120) + metadata.seek(0) + info = metadata.read().decode("ascii").splitlines() + if len(info) != 2: + raise ValueError("Invalid signed APK metadata") + size = int(info[0]) + digest, filename = info[1].split() + if not 0 < size <= MAX_APK or filename != source or re.fullmatch("[0-9a-f]{64}", digest) is None: + raise ValueError("Invalid signed APK on worker") + with tempfile.NamedTemporaryFile(dir=output.parent) as staged: + receive(ssh, "cat " + source, staged, limit=size, timeout=300) + if staged.tell() != size: + raise ValueError("Truncated APK transfer") + staged.seek(0) + checksum = hashlib.sha256() + for block in iter(lambda: staged.read(1024 * 1024), b""): + checksum.update(block) + if checksum.hexdigest() != digest: + raise ValueError("Signed APK checksum mismatch") + os.link(staged.name, output) + print(f"Signed APK SHA-256 {digest}", flush=True) + + +def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): + path = f"/actions/runs/{run_id}" + disconnected = None + while True: + run = actions.request("GET", path) + if run["event"] != "workflow_dispatch" or run["head_branch"] != branch or run["display_title"] != "Fork worker " + name: + raise RuntimeError("Unexpected worker workflow identity") + if run["status"] == "completed": + break + if listener.poll() is not None: + if disconnected is None: + disconnected = time.monotonic() + elif time.monotonic() > disconnected + 60: + raise RuntimeError("Worker disconnected before GitHub recorded completion") + wait(deadline, 15) + if run["conclusion"] != "success": + raise RuntimeError(f"Worker workflow {run_id} finished with {run['conclusion']}") + jobs = actions.request("GET", path + "/jobs")["jobs"] + if len(jobs) != 1 or jobs[0]["name"] != "build" or jobs[0]["conclusion"] != "success": + raise RuntimeError("Expected exactly one successful worker build") + if jobs[0]["runner_id"] != runner_id or jobs[0]["runner_name"] != name: + raise RuntimeError("The worker build ran on a different machine") + + +def build(args, cloud, admin): + actions = Api("https://api.github.com/repos/" + REPO, os.environ["ACTIONS_TOKEN"], github=True) + control = os.environ["GITHUB_SHA"] + if any(re.fullmatch("[0-9a-f]{40}", value) is None for value in (control, args.source_sha)): + raise ValueError("Expected full immutable commit SHAs") + if not args.maven.is_dir() or args.output.exists(): + raise ValueError("Expected a staged Maven directory and a new APK destination") + branch = actions.request("GET", "")["default_branch"] + key = secrets.token_hex(16) + name = name_for(key) + server = None + runner_id = None + run_id = None + deadline = time.monotonic() + BUILD_SECONDS + print(f"Provisioning {name} for {args.arm}", flush=True) + + with tempfile.TemporaryDirectory() as directory: + user_data, ssh = keys(Path(directory), key) + try: + params = {"name": name, "location": "fsn1", "image": "ubuntu-24.04", "server_type": "cx43", + "public_net": {"enable_ipv4": True, "enable_ipv6": False}, "user_data": user_data, + "labels": labels_for(key, args.arm)} + server = cloud.request("POST", "/servers", params)["server"] + address = ipaddress.IPv4Address(server["public_net"]["ipv4"]["ip"]) + ssh.append("root@" + str(address)) + ready(ssh) + stage(ssh, args.maven) + jit = admin.request("POST", "/actions/runners/generate-jitconfig", { + "name": name, "runner_group_id": 1, + "labels": ["self-hosted", "linux", "X64", "nitro-fork-build", name], "work_folder": "_work"}) + runner_id = jit["runner"]["id"] + # Keep the short-lived JIT value off the command line and out of cloud-init metadata. + credential = jit.pop("encoded_jit_config").encode() + base64.b64decode(credential, validate=True) + with subprocess.Popen([*ssh, "/usr/local/sbin/nitro-start-runner"], stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as listener: + try: + listener.stdin.write(credential) + listener.stdin.close() + online_deadline = time.monotonic() + 180 + while True: + status = admin.request("GET", f"/actions/runners/{runner_id}") + if status["status"] == "online": + break + if listener.poll() is not None: + raise RuntimeError("The one-job runner failed to start") + wait(online_deadline) + inputs = {"arm": args.arm, "source_sha": args.source_sha, "control_sha": control, "job_label": name} + dispatch = actions.request("POST", f"/actions/workflows/{WORKFLOW}/dispatches", + {"ref": branch, "inputs": inputs}) + run_id = int(dispatch["workflow_run_id"]) + print(f"Worker run https://github.com/{REPO}/actions/runs/{run_id}", flush=True) + verify_job(actions, run_id, runner_id, name, branch, deadline, listener) + run_id = None + collect_apk(ssh, args.output) + finally: + if listener.poll() is None: + listener.kill() + finally: + # Signal interruption or an ambiguous POST can leave a server without a local ID. + # Never retry creation. Resolve this job's unique name and verify its labels. + if server is None: + find_deadline = time.monotonic() + 45 + while server is None and time.monotonic() < find_deadline: + server = find_server(cloud, key) + if server is None: + time.sleep(3) + try: + if server: + delete_server(cloud, server["id"], key, args.arm) + finally: + try: + remove_runner(admin, name, runner_id) + finally: + if run_id is not None: + run = actions.request("GET", f"/actions/runs/{run_id}", missing_ok=True) + if run is not None and run["status"] != "completed": + actions.request("POST", f"/actions/runs/{run_id}/cancel") + + +def reap(cloud, admin): + cutoff = datetime.now(timezone.utc) - timedelta(seconds=BUILD_SECONDS + 1800) + selector = ",".join(f"{k}={v}" for k, v in OWNER.items()) + page = 1 + expired = [] + while page: + query = urlencode({"label_selector": selector, "page": page, "per_page": 50}) + result = cloud.request("GET", "/servers?" + query) + for server in result["servers"]: + key = server["labels"].get("worker", "") + arm = server["labels"].get("arm", "") + created = datetime.fromisoformat(server["created"].replace("Z", "+00:00")) + if created < cutoff and owned(server, key, arm): + expired.append((server["id"], key, arm)) + page = result["meta"]["pagination"]["next_page"] + failures = [] + for server_id, key, arm in expired: + try: + delete_server(cloud, server_id, key, arm) + remove_runner(admin, name_for(key)) + except (RuntimeError, OSError) as error: + failures.append(f"{server_id}: {error}") + if failures: + raise RuntimeError("Incomplete cleanup: " + ", ".join(failures)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + create = commands.add_parser("build") + create.add_argument("--arm", required=True, choices=("baseline", "candidate")) + create.add_argument("--source-sha", required=True) + create.add_argument("--maven", required=True, type=Path) + create.add_argument("--output", required=True, type=Path) + commands.add_parser("reap") + args = parser.parse_args() + if os.environ.get("GITHUB_REPOSITORY") != REPO or os.environ.get("GITHUB_REPOSITORY_ID") != REPOSITORY_ID: + parser.error("Run from the trusted react-nitro repository") + required = ["HETZNER_FORK_TOKEN", "FORK_RUNNER_ADMIN_TOKEN"] + if args.command == "build": + required.append("ACTIONS_TOKEN") + for name in required: + if not os.environ.get(name): + parser.error(f"Missing {name} on the trusted controller") + cloud = Api("https://api.hetzner.cloud/v1", os.environ["HETZNER_FORK_TOKEN"]) + admin = Api("https://api.github.com/repos/" + REPO, os.environ["FORK_RUNNER_ADMIN_TOKEN"], github=True) + + def stop(_signal, _frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, stop) + if args.command == "build": + build(args, cloud, admin) + else: + reap(cloud, admin) + + +if __name__ == "__main__": + main() From ed8a241fc73569347f49852e69d4c9659854a308 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 16:55:38 +0100 Subject: [PATCH 06/12] fix(ci): reap expired VMs during GitHub credential rotation --- scripts/performance/fork/hetzner_runner.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index d43896beb..385504a49 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -326,6 +326,8 @@ def reap(cloud, admin): for server_id, key, arm in expired: try: delete_server(cloud, server_id, key, arm) + if admin is None: + raise RuntimeError("VM deleted; checking the GitHub registration requires FORK_RUNNER_ADMIN_TOKEN") remove_runner(admin, name_for(key)) except (RuntimeError, OSError) as error: failures.append(f"{server_id}: {error}") @@ -345,14 +347,15 @@ def main(): args = parser.parse_args() if os.environ.get("GITHUB_REPOSITORY") != REPO or os.environ.get("GITHUB_REPOSITORY_ID") != REPOSITORY_ID: parser.error("Run from the trusted react-nitro repository") - required = ["HETZNER_FORK_TOKEN", "FORK_RUNNER_ADMIN_TOKEN"] + required = ["HETZNER_FORK_TOKEN"] if args.command == "build": - required.append("ACTIONS_TOKEN") + required.extend(["FORK_RUNNER_ADMIN_TOKEN", "ACTIONS_TOKEN"]) for name in required: if not os.environ.get(name): parser.error(f"Missing {name} on the trusted controller") cloud = Api("https://api.hetzner.cloud/v1", os.environ["HETZNER_FORK_TOKEN"]) - admin = Api("https://api.github.com/repos/" + REPO, os.environ["FORK_RUNNER_ADMIN_TOKEN"], github=True) + admin_token = os.environ.get("FORK_RUNNER_ADMIN_TOKEN") + admin = Api("https://api.github.com/repos/" + REPO, admin_token, github=True) if admin_token else None def stop(_signal, _frame): raise KeyboardInterrupt From 3ca4cebaec1ffd3b6c188fe58a3a9701c07f84a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 17:16:57 +0100 Subject: [PATCH 07/12] fix(ci): validate key-only access on fresh Hetzner workers --- scripts/performance/fork/hetzner_runner.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index 385504a49..4041d12ae 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -98,6 +98,9 @@ def generate(name): # JSON is valid YAML. This supplies only keys specific to this disposable VM. config = {"disable_root": False, "ssh_pwauth": False, "users": [{"name": "root", "lock_passwd": True, "ssh_authorized_keys": [public]}], + # Hetzner expires the initial root password after cloud-init creates the user. + # Lock it at final boot and allow noninteractive access with the disposable key. + "runcmd": [["passwd", "--lock", "root"], ["chage", "--lastday", "-1", "root"]], "ssh_keys": {"ed25519_private": host.read_text(), "ed25519_public": host_public}} user_data = "#cloud-config\n" + json.dumps(config) ssh = ["ssh", "-F", "/dev/null", "-i", str(identity), "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", @@ -152,7 +155,19 @@ def ready(ssh): if probe.returncode == 0: break wait(deadline) - subprocess.run([*ssh, "cloud-init status --wait"], timeout=240, check=True) + boot = subprocess.run([*ssh, "cloud-init status --wait --format json"], timeout=240, capture_output=True) + if boot.returncode not in (0, 2): + boot.check_returncode() + status = json.loads(boot.stdout) + if status["status"] != "done" or status["errors"]: + raise RuntimeError("Cloud-init did not complete successfully") + # Hetzner's Ubuntu image uses deprecated cloud-init password configuration. + # Exit 2 also covers operational warnings, which must still stop provisioning. + warnings = status["recoverable_errors"] + if (warnings or boot.returncode == 2) and set(warnings) != {"DEPRECATED"}: + raise RuntimeError("Cloud-init reported an unexpected warning category") + check_access = "sshd -T | grep -qx 'passwordauthentication no' && test \"$(passwd -S root | cut -d' ' -f2)\" = L" + subprocess.run([*ssh, check_access], timeout=15, check=True) def stage(ssh, maven): From fc2dd87afa1369ba19a7565261220d8b312e85ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 17:21:47 +0100 Subject: [PATCH 08/12] fix(ci): verify completed worker jobs before collecting artifacts --- scripts/performance/fork/hetzner_runner.py | 57 ++++++++++++++++------ 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index 4041d12ae..ac33964a7 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -140,11 +140,16 @@ def remove_runner(admin, name, runner_id=None): return runner_id = runners[0]["id"] path = f"/actions/runners/{runner_id}" - runner = admin.request("GET", path, missing_ok=True) - if runner is None: - return - if runner["name"] != name or name not in [label["name"] for label in runner["labels"]]: - raise RuntimeError("Refusing to remove an unrelated runner") + deadline = time.monotonic() + 120 + while True: + runner = admin.request("GET", path, missing_ok=True) + if runner is None: + return + if runner["name"] != name or name not in [label["name"] for label in runner["labels"]]: + raise RuntimeError("Refusing to remove an unrelated runner") + if not runner.get("busy"): + break + wait(deadline, 5) admin.request("DELETE", path, missing_ok=True) @@ -223,8 +228,6 @@ def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): disconnected = None while True: run = actions.request("GET", path) - if run["event"] != "workflow_dispatch" or run["head_branch"] != branch or run["display_title"] != "Fork worker " + name: - raise RuntimeError("Unexpected worker workflow identity") if run["status"] == "completed": break if listener.poll() is not None: @@ -233,6 +236,9 @@ def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): elif time.monotonic() > disconnected + 60: raise RuntimeError("Worker disconnected before GitHub recorded completion") wait(deadline, 15) + # The ID comes from dispatch. GitHub can still be populating metadata on the first poll. + if run["event"] != "workflow_dispatch" or run["head_branch"] != branch or run["display_title"] != "Fork worker " + name: + raise RuntimeError("Unexpected worker workflow identity") if run["conclusion"] != "success": raise RuntimeError(f"Worker workflow {run_id} finished with {run['conclusion']}") jobs = actions.request("GET", path + "/jobs")["jobs"] @@ -242,6 +248,27 @@ def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): raise RuntimeError("The worker build ran on a different machine") +def cancel_active_run(actions, run_id): + path = f"/actions/runs/{run_id}" + run = actions.request("GET", path, missing_ok=True) + if run is None or run["status"] == "completed": + return + try: + actions.request("POST", path + "/cancel") + except RuntimeError: + # Completion can race the cancellation request. + run = actions.request("GET", path, missing_ok=True) + if run is None or run["status"] == "completed": + return + raise + deadline = time.monotonic() + 120 + while True: + run = actions.request("GET", path, missing_ok=True) + if run is None or run["status"] == "completed": + return + wait(deadline, 5) + + def build(args, cloud, admin): actions = Api("https://api.github.com/repos/" + REPO, os.environ["ACTIONS_TOKEN"], github=True) control = os.environ["GITHUB_SHA"] @@ -298,8 +325,12 @@ def build(args, cloud, admin): run_id = None collect_apk(ssh, args.output) finally: - if listener.poll() is None: - listener.kill() + try: + if run_id is not None: + cancel_active_run(actions, run_id) + finally: + if listener.poll() is None: + listener.kill() finally: # Signal interruption or an ambiguous POST can leave a server without a local ID. # Never retry creation. Resolve this job's unique name and verify its labels. @@ -313,13 +344,7 @@ def build(args, cloud, admin): if server: delete_server(cloud, server["id"], key, args.arm) finally: - try: - remove_runner(admin, name, runner_id) - finally: - if run_id is not None: - run = actions.request("GET", f"/actions/runs/{run_id}", missing_ok=True) - if run is not None and run["status"] != "completed": - actions.request("POST", f"/actions/runs/{run_id}/cancel") + remove_runner(admin, name, runner_id) def reap(cloud, admin): From dc27709ef7716e5af0c141ba29ce3426b1c1a0e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 17:25:17 +0100 Subject: [PATCH 09/12] fix(ci): wait for dispatched runs to become visible --- scripts/performance/fork/hetzner_runner.py | 34 ++++++++++++++++------ 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index ac33964a7..ca131de12 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -223,25 +223,41 @@ def collect_apk(ssh, output): print(f"Signed APK SHA-256 {digest}", flush=True) +def dispatched_run(actions, run_id): + # A successful dispatch can return its immutable ID before the run GET is available. + deadline = time.monotonic() + 120 + path = f"/actions/runs/{run_id}" + while True: + run = actions.request("GET", path, missing_ok=True) + if run is not None: + return run + wait(deadline, 3) + + def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): path = f"/actions/runs/{run_id}" + run = dispatched_run(actions, run_id) disconnected = None - while True: - run = actions.request("GET", path) - if run["status"] == "completed": - break + while run["status"] != "completed": if listener.poll() is not None: if disconnected is None: disconnected = time.monotonic() elif time.monotonic() > disconnected + 60: raise RuntimeError("Worker disconnected before GitHub recorded completion") wait(deadline, 15) + run = actions.request("GET", path) # The ID comes from dispatch. GitHub can still be populating metadata on the first poll. if run["event"] != "workflow_dispatch" or run["head_branch"] != branch or run["display_title"] != "Fork worker " + name: raise RuntimeError("Unexpected worker workflow identity") if run["conclusion"] != "success": raise RuntimeError(f"Worker workflow {run_id} finished with {run['conclusion']}") - jobs = actions.request("GET", path + "/jobs")["jobs"] + jobs_deadline = min(deadline, time.monotonic() + 120) + while True: + page = actions.request("GET", path + "/jobs", missing_ok=True) + jobs = page["jobs"] if page else [] + if jobs and all(job.get("conclusion") is not None for job in jobs): + break + wait(jobs_deadline, 3) if len(jobs) != 1 or jobs[0]["name"] != "build" or jobs[0]["conclusion"] != "success": raise RuntimeError("Expected exactly one successful worker build") if jobs[0]["runner_id"] != runner_id or jobs[0]["runner_name"] != name: @@ -250,8 +266,8 @@ def verify_job(actions, run_id, runner_id, name, branch, deadline, listener): def cancel_active_run(actions, run_id): path = f"/actions/runs/{run_id}" - run = actions.request("GET", path, missing_ok=True) - if run is None or run["status"] == "completed": + run = dispatched_run(actions, run_id) + if run["status"] == "completed": return try: actions.request("POST", path + "/cancel") @@ -310,8 +326,8 @@ def build(args, cloud, admin): listener.stdin.close() online_deadline = time.monotonic() + 180 while True: - status = admin.request("GET", f"/actions/runners/{runner_id}") - if status["status"] == "online": + status = admin.request("GET", f"/actions/runners/{runner_id}", missing_ok=True) + if status is not None and status["status"] == "online": break if listener.poll() is not None: raise RuntimeError("The one-job runner failed to start") From 11c638e6da2d77d5044d9439d670fcc271500d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 17:43:30 +0100 Subject: [PATCH 10/12] ci(performance): use a CX33 for reviewed fork builds --- scripts/performance/README.md | 4 +++- scripts/performance/fork/hetzner_runner.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/performance/README.md b/scripts/performance/README.md index d7b8e12b6..2679d65f2 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -32,7 +32,9 @@ python3 scripts/performance/analyze.py --session ../performance-run/session.json A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary. The summary gives the path to the raw readings in private CI storage, where run artifacts expire after one day. A successful run means the comparison completed. Read the intervals before merging. -The private `hetzner-cx23` runners authorize the request, supervise the builds and run the comparison. Builds share one queue across PRs so only one disposable VM is needed at a time. Each build gets a fresh Hetzner CX43 in Falkenstein in the `HetznerDefault` project. The supervisor stages the six PerfKit Maven files over SSH, registers the VM with GitHub for one job and calls the worker workflow with a unique label. The worker builds the reviewed commit in a container, validates the APK and applies a fresh signing key. The supervisor verifies which runner finished the job, collects the APK over SSH, uploads it to private CI storage and deletes the VM. An hourly cleanup removes abandoned project VMs older than 3½ hours after checking their repository label, name and ownership. +The private `hetzner-cx23` runners authorize the request, supervise the builds and run the comparison. Builds share one queue across PRs so only one disposable VM is needed at a time. Each build gets a fresh Hetzner CX33 (4 shared vCPUs, 8 GB RAM) in Falkenstein in the `HetznerDefault` project. The supervisor stages the six PerfKit Maven files over SSH, registers the VM with GitHub for one job and calls the worker workflow with a unique label. The worker builds the reviewed commit in a container, validates the APK and applies a fresh signing key. The supervisor verifies which runner finished the job, collects the APK over SSH, uploads it to private CI storage and deletes the VM. An hourly cleanup removes abandoned project VMs older than 3½ hours after checking their repository label, name and ownership. + +One cold ARM64 candidate build took 15 min 38 s in GitHub Actions and 17 min 17 s from provisioning through cleanup. The resulting APK passed signature verification with debugging disabled. [CX33 Release build](https://github.com/margelo/react-nitro/actions/runs/46461949749) Only the persistent supervisors have access to the cloud and runner-management credentials. The worker has read access to the source repository for checkout. The fork's build container receives the source tree, Android toolchain and dependency files. It has public network access for dependencies and submodules. The trusted upstream driver runs the signed apps on ADC. Fork code can misrepresent its timings, so review the implementation before relying on the measurements. diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index ca131de12..87faa6213 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -304,7 +304,7 @@ def build(args, cloud, admin): with tempfile.TemporaryDirectory() as directory: user_data, ssh = keys(Path(directory), key) try: - params = {"name": name, "location": "fsn1", "image": "ubuntu-24.04", "server_type": "cx43", + params = {"name": name, "location": "fsn1", "image": "ubuntu-24.04", "server_type": "cx33", "public_net": {"enable_ipv4": True, "enable_ipv6": False}, "user_data": user_data, "labels": labels_for(key, args.arm)} server = cloud.request("POST", "/servers", params)["server"] From 7b687d60bff3dc4540ed56bc76ba9282aa968119 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Thu, 3 Dec 2026 15:33:18 +0100 Subject: [PATCH 11/12] fix(ci): recognize the renamed Nitro UI repository for fork checks --- scripts/performance/README.md | 2 +- scripts/performance/fork/hetzner_runner.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 2679d65f2..5faf14489 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -34,7 +34,7 @@ A maintainer with repository write access can comment `/check ` The private `hetzner-cx23` runners authorize the request, supervise the builds and run the comparison. Builds share one queue across PRs so only one disposable VM is needed at a time. Each build gets a fresh Hetzner CX33 (4 shared vCPUs, 8 GB RAM) in Falkenstein in the `HetznerDefault` project. The supervisor stages the six PerfKit Maven files over SSH, registers the VM with GitHub for one job and calls the worker workflow with a unique label. The worker builds the reviewed commit in a container, validates the APK and applies a fresh signing key. The supervisor verifies which runner finished the job, collects the APK over SSH, uploads it to private CI storage and deletes the VM. An hourly cleanup removes abandoned project VMs older than 3½ hours after checking their repository label, name and ownership. -One cold ARM64 candidate build took 15 min 38 s in GitHub Actions and 17 min 17 s from provisioning through cleanup. The resulting APK passed signature verification with debugging disabled. [CX33 Release build](https://github.com/margelo/react-nitro/actions/runs/46461949749) +One cold ARM64 candidate build took 15 min 38 s in GitHub Actions and 17 min 17 s from provisioning through cleanup. The resulting APK passed signature verification with debugging disabled. [CX33 Release build](https://github.com/margelo/nitro-ui/actions/runs/46461949749) Only the persistent supervisors have access to the cloud and runner-management credentials. The worker has read access to the source repository for checkout. The fork's build container receives the source tree, Android toolchain and dependency files. It has public network access for dependencies and submodules. The trusted upstream driver runs the signed apps on ADC. Fork code can misrepresent its timings, so review the implementation before relying on the measurements. diff --git a/scripts/performance/fork/hetzner_runner.py b/scripts/performance/fork/hetzner_runner.py index 87faa6213..b2bd61011 100644 --- a/scripts/performance/fork/hetzner_runner.py +++ b/scripts/performance/fork/hetzner_runner.py @@ -19,7 +19,7 @@ from urllib.request import Request, urlopen -REPO = "margelo/react-nitro" +REPO = "margelo/nitro-ui" REPOSITORY_ID = "1373493776" WORKFLOW = "fork-worker.yml" OWNER = {"managed-by": "nitro-fork-check", "github-repo-id": REPOSITORY_ID} @@ -402,7 +402,7 @@ def main(): commands.add_parser("reap") args = parser.parse_args() if os.environ.get("GITHUB_REPOSITORY") != REPO or os.environ.get("GITHUB_REPOSITORY_ID") != REPOSITORY_ID: - parser.error("Run from the trusted react-nitro repository") + parser.error("Run from the trusted nitro-ui repository") required = ["HETZNER_FORK_TOKEN"] if args.command == "build": required.extend(["FORK_RUNNER_ADMIN_TOKEN", "ACTIONS_TOKEN"]) From 67d5ff3e533e6ba7f27edaeb61001b7b1c9b1419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Thu, 3 Dec 2026 16:33:42 +0100 Subject: [PATCH 12/12] ci(performance): prefetch fork dependencies with the upstream job token --- .github/workflows/fork-performance.yml | 5 +++-- scripts/performance/README.md | 4 ++-- scripts/performance/fork/prefetch.sh | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/workflows/fork-performance.yml b/.github/workflows/fork-performance.yml index c8ccd3cb3..2d20b8eb6 100644 --- a/.github/workflows/fork-performance.yml +++ b/.github/workflows/fork-performance.yml @@ -14,6 +14,7 @@ jobs: runs-on: [self-hosted, linux, X64, hetzner-cx23] permissions: contents: read + packages: read pull-requests: read statuses: write outputs: @@ -50,8 +51,8 @@ jobs: -f target_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - name: Fetch published PerfKit dependencies env: - PERF_MAVEN_USER: ${{ secrets.PERF_MAVEN_USER }} - PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} + PERF_MAVEN_USER: ${{ github.actor }} + PERF_MAVEN_TOKEN: ${{ github.token }} run: | rm -rf -- "$RUNNER_TEMP/maven" bash scripts/performance/fork/prefetch.sh diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 67d212d38..4d4b5e528 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -40,9 +40,9 @@ Only the persistent supervisors have access to the cloud and runner-management c #### Credentials for the supervisors -Use a GitHub Environment named `nitro-fork-infrastructure` restricted to the default branch. Store a dedicated read/write API token for the intended Hetzner project as `HETZNER_FORK_TOKEN`. Store a GitHub fine-grained access token scoped to this repository with the **Administration: write** permission as `FORK_RUNNER_ADMIN_TOKEN`. GitHub requires this permission to issue single-job runner registrations. The existing ADC, Maven and private CI storage credentials stay in their respective upstream workflow steps. [GitHub runner registration](https://docs.github.com/en/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository) +Use a GitHub Environment named `nitro-fork-infrastructure` restricted to the default branch. Store a dedicated read/write API token for the intended Hetzner project as `HETZNER_FORK_TOKEN`. Store a GitHub fine-grained access token scoped to this repository with the **Administration: write** permission as `FORK_RUNNER_ADMIN_TOKEN`. GitHub requires this permission to issue single-job runner registrations. The upstream authorization job downloads the six Maven files with its automatic `GITHUB_TOKEN` and `packages: read`. Only the files reach the fork build container. ADC and private CI storage credentials stay in their respective upstream steps. [GitHub runner registration](https://docs.github.com/en/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository) -This private repository disables ordinary workflows from fork PRs in Actions settings. Keep that setting while other workflows run on persistent self-hosted machines. Before making the repository public, restrict the runner groups to trusted workflow refs or move fork builds to isolated hosted runners. A condition inside a fork-editable workflow cannot enforce that runner policy. [GitHub Actions security guidance](https://docs.github.com/en/actions/reference/security/secure-use) +On this public repository, restrict access to persistent self-hosted runners to trusted workflow refs. Run fork code on disposable workers. A condition inside a fork-editable workflow cannot enforce that runner policy. [GitHub Actions security guidance](https://docs.github.com/en/actions/reference/security/secure-use) ## AWS Device Farm physical calibration diff --git a/scripts/performance/fork/prefetch.sh b/scripts/performance/fork/prefetch.sh index 4fb7b7b24..a3aaf9dc3 100755 --- a/scripts/performance/fork/prefetch.sh +++ b/scripts/performance/fork/prefetch.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -: "${PERF_MAVEN_USER:?Set the PerfKit package reader in the repository Actions secrets}" -: "${PERF_MAVEN_TOKEN:?Set the token with read access to the PerfKit GitHub Packages}" +: "${PERF_MAVEN_USER:?Set the GitHub actor for the package download}" +: "${PERF_MAVEN_TOKEN:?Set the GitHub job token with packages: read}" version=$(python3 scripts/performance/prepare.py --sdk-version) registry=https://maven.pkg.github.com/callstackincubator/performance-analytics for artifact in performance-analytics-android performance-analytics-core-cpp; do