Skip to content
Draft
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
232 changes: 232 additions & 0 deletions .github/workflows/fork-performance.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
name: Fork performance check

on:
issue_comment:
types: [created]
schedule:
- cron: '41 * * * *'

permissions: {}

jobs:
authorize:
if: github.event.issue.pull_request && (github.event.comment.body == '/check' || startsWith(github.event.comment.body, '/check '))
runs-on: [self-hosted, linux, X64, hetzner-cx23]
permissions:
contents: read
packages: read
pull-requests: read
statuses: write
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:
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: ${{ github.actor }}
PERF_MAVEN_TOKEN: ${{ github.token }}
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
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, hetzner-cx23]
timeout-minutes: 210
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: ${{ github.sha }}
persist-credentials: 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
- 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: |
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: |
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: [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
- 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
- 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"
- 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: [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 }}
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"

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
76 changes: 76 additions & 0 deletions .github/workflows/fork-worker.yml
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions scripts/performance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ 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 <full commit SHA>` 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 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/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.

#### 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 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)

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

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.
Expand Down
57 changes: 57 additions & 0 deletions scripts/performance/fork/authorize.py
Original file line number Diff line number Diff line change
@@ -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 <full SHA>.")
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")
Loading
Loading