From c1d876f6dd0e65219299f7f5b1ed05e6dc238364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sun, 29 Nov 2026 20:05:11 +0100 Subject: [PATCH 1/9] test(performance): compare Android harness workloads on ADC --- .github/workflows/android-performance.yml | 114 ++++++++++++++ scripts/performance/README.md | 43 +++++ scripts/performance/analyze.py | 183 ++++++++++++++++++++++ scripts/performance/install.py | 67 ++++++++ scripts/performance/launch.ts | 116 ++++++++++++++ scripts/performance/prepare.py | 56 +++++++ scripts/performance/run.py | 129 +++++++++++++++ scripts/performance/workloads.tsx | 61 ++++++++ 8 files changed, 769 insertions(+) create mode 100644 .github/workflows/android-performance.yml create mode 100644 scripts/performance/README.md create mode 100644 scripts/performance/analyze.py create mode 100644 scripts/performance/install.py create mode 100644 scripts/performance/launch.ts create mode 100644 scripts/performance/prepare.py create mode 100644 scripts/performance/run.py create mode 100644 scripts/performance/workloads.tsx diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml new file mode 100644 index 000000000..440917f3b --- /dev/null +++ b/.github/workflows/android-performance.yml @@ -0,0 +1,114 @@ +name: Android performance (ADC) + +on: + workflow_dispatch: + inputs: + baseline: + description: Baseline Git ref + default: main + required: true + candidate: + description: Candidate Git ref (defaults to the workflow revision) + pairs: + description: Measured pairs on the same device (even number) + default: '24' + required: true + pull_request: + +permissions: + contents: read + +jobs: + compare: + if: github.event_name == 'workflow_dispatch' || (vars.ENABLE_ANDROID_PERFORMANCE == 'true' && github.event.pull_request.head.repo.full_name == github.repository) + runs-on: [self-hosted, linux, X64, hetzner-cx23] + timeout-minutes: 240 + env: + CC: clang + CXX: clang++ + CMAKE_BUILD_PARALLEL_LEVEL: 2 + PAIRS: ${{ inputs.pairs || '24' }} + steps: + - uses: actions/checkout@v7 + with: + path: experiment + persist-credentials: false + + - uses: actions/checkout@v7 + with: + ref: ${{ inputs.baseline || github.event.pull_request.base.sha }} + path: baseline + submodules: recursive + persist-credentials: false + + - uses: actions/checkout@v7 + with: + ref: ${{ inputs.candidate || github.event.pull_request.head.sha || github.sha }} + path: candidate + submodules: recursive + persist-credentials: false + + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.4 + + - uses: actions/setup-python@v6 + with: + python-version: '3.10' + + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '17' + + - name: Install Android build tools + run: | + "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools + echo "$ANDROID_HOME/platform-tools" >> "$GITHUB_PATH" + + - name: Build the instrumented APK from each revision + env: + PERF_MAVEN_USER: ${{ secrets.PERF_MAVEN_USER }} + PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} + run: | + (cd experiment && bun install --frozen-lockfile --ignore-scripts) + for arm in baseline candidate; do + python3 experiment/scripts/performance/prepare.py "$arm" "$arm" + (cd "$arm" && bun install && cd apps/example && bun run android --build-only) + metadata="$arm/apps/example/.nitro/android/apks/debug.json" + id=$(jq -er .applicationId "$metadata") + test "$id" = "com.margelo.reactnitro.example.$arm" + apk=$(jq -er '.elements | select(length == 1) | .[0].outputFile' "$metadata") + cp "$apk" "$arm.apk" + done + + - uses: margelo/adc@09956980c08fe6790198c721fc0a9da500778407 # v0.5.1 + with: + api-key: ${{ secrets.ADC_API_KEY }} + name: React Nitro performance ${{ github.run_id }}-${{ github.run_attempt }} + form-factor: phone + api-level: '35' + width: '720' + height: '1600' + dpi: '320' + command: | + python3 experiment/scripts/performance/run.py --pairs "$PAIRS" \ + --baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results + + - name: Summarize paired changes + run: | + python3 experiment/scripts/performance/analyze.py --expect-pairs "$PAIRS" experiment/results/raw.jsonl > experiment/results/report.md + cat experiment/results/report.md >> "$GITHUB_STEP_SUMMARY" + + - name: Save readings and SDK sessions to CI storage + if: ${{ !cancelled() && hashFiles('experiment/results/session.json') != '' }} + env: + 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/performance/" + aws s3 cp experiment/results/ "$uri" --recursive --only-show-errors + echo "Raw measurements: \`$uri\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/scripts/performance/README.md b/scripts/performance/README.md new file mode 100644 index 000000000..d8003208c --- /dev/null +++ b/scripts/performance/README.md @@ -0,0 +1,43 @@ +# Android performance on ADC + +The Android performance workflow builds the example app from two Git revisions. It stages the same Harness test and Callstack Performance Analytics SDK 0.1.0 into both builds. Each revision supplies its own JavaScript packages and native code. The baseline and candidate APKs have separate package IDs and stay installed throughout one ADC lease. + +To compare a PR, enable the repository variable `ENABLE_ANDROID_PERFORMANCE=true`. Same-repository PRs compare the base and head SHAs. The workflow also accepts two refs through `workflow_dispatch`. Set both inputs to the same commit for an A/A calibration. The Maven download needs repository secrets `PERF_MAVEN_USER` and `PERF_MAVEN_TOKEN` for a user with read access to the SDK's GitHub Packages. The ADC and S3 credentials are shared with the functional E2E workflow. + +The runner warms up both packages, starts a fresh process for each measurement, and alternates pairs in AB, BA order. The Debug Harness runs 32,768 native MMKV reads and 12 React commits that update 48 rows. The app times those two operations with its monotonic clock. The SDK separately records process CPU and PSS. CPU counts process-wide work between the SDK samples surrounding the test, including the one-second settling period and SDK activity. PSS is the final snapshot. The measured React commits can precede presentation on the display. + +Callstack's Nitro adapter exposes `init` and `flushNow`. The host uses ADB reverse for Harness and receives the timed workload result on loopback. It reads the flushed SDK session from the Debug app's private directory via `adb exec-out run-as`, checks sample timestamps and saves the original payload with each launch. This prototype depends on the storage layout in SDK 0.1.0. + +The GitHub job summary shows each variant's median and variation, paired changes, an interval by lease and separate results for each launch order. Raw readings, build SHAs, APK and fixture hashes, device properties, SDK sessions and warmups go to the existing private CI bucket. Failed or partial runs preserve the data produced up to the failure. The job reports performance differences without a pass/fail threshold. Test, instrumentation and incomplete-run failures fail the job. + +## Calibration on November 29, 2026 + +Two A/A runs of 24 pairs on separate ADC Android 15 arm64 VMs used commit `b4d118ea`. The MMKV time changed by +1.2% (95% interval −7.0% to +4.8%) and +0.3% (−2.0% to +2.8%). The React update time changed by −0.7% and +1.7%. The measured launches took about 7½ minutes per VM. The default is 24 pairs. A small timing threshold still needs calibration across further devices and days. + +On a third VM, increasing only the candidate's MMKV reads by 25% raised its time by 20.0% (+17.5% to +35.5%) across 20 pairs. The unchanged React workload moved +0.3%. A fourth VM compared the same main revision with PR #717 (`ac356ba5`, optimized Debug Hermes). Across 12 pairs MMKV time fell 90.5%, React update time fell 85.1%, and process CPU time fell 57.4%. [PR #717](https://github.com/margelo/react-nitro/pull/717) + +## Run the same experiment outside Actions + +Use two expendable checkouts of the revisions to test. Run the following from a third checkout with the prototype and its Bun dependencies installed. The preparation step changes the example app and its dependency lock in the expendable checkouts. Set the two Maven credential variables in the build environment, initialize submodules and use the Android toolchain from the existing example CI. + +```sh +for arm in baseline candidate; do + root="../$arm" + git -C "$root" submodule update --init --recursive + python3 scripts/performance/prepare.py "$root" "$arm" + (cd "$root" && bun install && cd apps/example && bun run android --build-only) + metadata="$root/apps/example/.nitro/android/apks/debug.json" + cp "$(jq -er '.elements[0].outputFile' "$metadata")" "../$arm.apk" +done + +adc run --purpose ci --form-factor phone --api-level 35 --width 720 --height 1600 --dpi 320 -- \ + python3 scripts/performance/run.py --pairs 24 --output ../performance-run \ + --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk +python3 scripts/performance/analyze.py --expect-pairs 24 ../performance-run/raw.jsonl +``` + +For a positive control, copy the staged fixture from the candidate's `apps/example/.nitro/performance/` directory, increase `readPasses` from 128 to 160, and pass the copy's path to `run.py --control-fixture`. The runner records the differing workload hashes. This exercises detection of 25% additional MMKV reads. + +## Incomplete local runs + +During calibration on macOS, the Harness selected a port where an existing process on IPv4 loopback answered the app's request for `/client.js` with HTTP 404. The launch timed out before the benchmark ran. The raw JSONL stopped at 23 of 40 measurements and the analyzer rejected the incomplete series. The experiment was repeated from warmup on a fresh lease. When investigating a similar failure, save the Android dev error and check the host listener with `lsof -nP -iTCP: -sTCP:LISTEN`. diff --git a/scripts/performance/analyze.py b/scripts/performance/analyze.py new file mode 100644 index 000000000..fa535ceba --- /dev/null +++ b/scripts/performance/analyze.py @@ -0,0 +1,183 @@ +"""Summarize interleaved Android performance measurements as GitHub Markdown.""" + +import argparse +import json +import math +import statistics +from pathlib import Path + + +def add_sample(sessions, row): + if not isinstance(row, dict): + raise ValueError("expected a JSON object") + session = row.get("session") + pair = row.get("pair") + position = row.get("position") + variant = row.get("variant") + metrics = row.get("metrics") + if not isinstance(session, str) or not session.strip(): + raise ValueError("expected a session identifier") + if type(pair) is not int or pair < 1: + raise ValueError("expected a positive pair number") + if type(position) is not int or position not in (1, 2): + raise ValueError("expected position 1 or 2") + if variant not in ("baseline", "candidate"): + raise ValueError("expected variant baseline or candidate") + if not isinstance(metrics, dict) or not metrics: + raise ValueError("expected a nonempty metrics object") + for name, value in metrics.items(): + if not name or type(value) not in (int, float) or not math.isfinite(value): + raise ValueError(f"invalid numeric metric {name!r}") + + pairs = sessions.setdefault(session, {}) + launches = pairs.setdefault(pair, {}) + if position in launches: + raise ValueError(f"duplicate launch in {session}, pair {pair}, position {position}") + launches[position] = (variant, metrics) + + +def read_sessions(paths): + sessions = {} + for path in paths: + with path.open() as source: + for line_number, line in enumerate(source, 1): + try: + row = json.loads(line) + add_sample(sessions, row) + except ValueError as error: + raise ValueError(f"{path}:{line_number}: {error}") from error + if not sessions: + raise ValueError("no measurements") + return sessions + + +def ordered_pairs(pairs, expected_count): + count = len(pairs) + if expected_count is not None and count != expected_count: + raise ValueError(f"expected {expected_count} pairs, found {count}") + if count < 2 or count % 2 or min(pairs) != 1 or max(pairs) != count: + raise ValueError("expected an even number of consecutive pairs starting at 1") + + previous_first = None + names = None + samples = [] + for number in range(1, count + 1): + launches = pairs[number] + if len(launches) != 2: + raise ValueError(f"pair {number} is incomplete") + first, first_metrics = launches[1] + second, second_metrics = launches[2] + if first == second or first == previous_first: + raise ValueError(f"pair {number} violates the alternating AB/BA order") + previous_first = first + if names is None: + names = first_metrics.keys() + if first_metrics.keys() != names or second_metrics.keys() != names: + raise ValueError(f"pair {number} has inconsistent metric names") + samples.append((first, {first: first_metrics, second: second_metrics})) + return samples + + +def median_interval(blocks): + # The two tails of Binomial(n, 0.5) determine the order statistics + # that cover the population median with at least 95% confidence. + n = len(blocks) + outcomes = 2 ** n + tail = 0 + rank = 0 + for index in range(n // 2): + tail += math.comb(n, index) + if 40 * tail > outcomes: + break + rank += 1 + if rank == 0: + return None + ordered = sorted(blocks) + return ordered[rank - 1], ordered[-rank] + + +def level(values): + median = statistics.median(values) + mean = statistics.fmean(values) + if mean <= 0: + return f"{median:.5g} (CV n/a)" + deviation = statistics.stdev(values) + return f"{median:.5g} ({deviation / mean:.1%})" + + +def metric_row(name, samples): + baseline = [arms["baseline"][name] for _, arms in samples] + candidate = [arms["candidate"][name] for _, arms in samples] + relative = min(baseline) > 0 and min(candidate) > 0 + changes = [] + by_order = {"baseline": [], "candidate": []} + for (first, _), a, b in zip(samples, baseline, candidate): + change = math.log(b) - math.log(a) if relative else b - a + changes.append(change) + by_order[first].append(change) + + def display(change): + if relative: + ratio_change = math.expm1(change) + return f"{ratio_change:+.2%}" + return f"{change:+.5g}" + + blocks = [(ab + ba) / 2 for ab, ba in zip(changes[::2], changes[1::2])] + estimate = statistics.median(blocks) + interval = median_interval(blocks) + bounds = "n/a" + if interval is not None: + low, high = interval + bounds = f"{display(low)} to {display(high)}" + deciles = statistics.quantiles(changes, n=10, method="inclusive") + ab_median = statistics.median(by_order["baseline"]) + ba_median = statistics.median(by_order["candidate"]) + return ( + f"| {name} | {level(baseline)} | {level(candidate)} | {display(estimate)} | {bounds} " + f"| {display(deciles[0])} to {display(deciles[-1])} " + f"| {display(ab_median)} / {display(ba_median)} |" + ) + + +def report(sessions, expected_count): + lines = ["## Paired Android performance"] + for session, pairs in sessions.items(): + try: + samples = ordered_pairs(pairs, expected_count) + except ValueError as error: + raise ValueError(f"{session}: {error}") from error + lines.extend([ + "", + f"### {session} ({len(samples)} pairs)", + "", + "| Metric | Baseline median (CV) | Candidate median (CV) | Change | 95% interval " + "| Pair P10 to P90 | AB / BA medians |", + "|---|---:|---:|---:|---:|---:|---:|", + ]) + _, first = samples[0] + for name in sorted(first["baseline"]): + lines.append(metric_row(name, samples)) + lines.extend([ + "", + "Positive change means the candidate value is higher. Each adjacent AB/BA block " + "contributes one mean log ratio. Change is the median across blocks, converted to percent. " + "Metrics containing zero or negative readings use absolute differences in the metric's units.", + "", + "CV is the sample standard deviation divided by the mean. Pair P10 to P90 shows the " + "spread of individual paired changes. AB runs the baseline first and BA runs the candidate first. " + "The rank-based interval assumes independent blocks within a session and requires at least 12 pairs.", + ]) + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("raw", nargs="+", type=Path, help="one JSONL sample per measured launch") + parser.add_argument("--expect-pairs", type=int, help="planned measured pairs per session") + args = parser.parse_args() + try: + sessions = read_sessions(args.raw) + markdown = report(sessions, args.expect_pairs) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + print(markdown) diff --git a/scripts/performance/install.py b/scripts/performance/install.py new file mode 100644 index 000000000..d9c73cc14 --- /dev/null +++ b/scripts/performance/install.py @@ -0,0 +1,67 @@ +import re +import subprocess +import time +from xml.etree import ElementTree + + +PLAY_PROTECT = "com.android.vending/com.google.android.finsky.protectdialogs.activity.PlayProtectDialogsActivity" + + +def upload_consent_button(xml): + try: + screen = ElementTree.fromstring(xml) + except ElementTree.ParseError: + return None + nodes = screen.findall(".//node[@package='com.android.vending']") + labels = {node.get("text"): node for node in nodes} + if "Send app for a security check?" not in labels or "Don't send" not in labels: + return None + button = labels["Don't send"] + bounds = re.fullmatch(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", button.get("bounds", "")) + if bounds is None or button.get("enabled") != "true": + return None + left, top, right, bottom = map(int, bounds.groups()) + return (left + right) // 2, (top + bottom) // 2 + + +def focused_window(adb): + return subprocess.check_output([*adb, "shell", "dumpsys window | sed -n '/mCurrentFocus/p'"], timeout=10, text=True) + + +def decline_optional_upload(adb): + focus = focused_window(adb) + if PLAY_PROTECT not in focus: + return + path = "/data/local/tmp/nitro-install-consent.xml" + dump = f"rm -f {path} && uiautomator dump {path} >/dev/null && cat {path}" + try: + snapshot = subprocess.run([*adb, "shell", dump], capture_output=True, timeout=15) + except subprocess.TimeoutExpired: + return + if snapshot.returncode: + return + button = upload_consent_button(snapshot.stdout) + if button is not None and focused_window(adb) == focus: + x, y = button + subprocess.run([*adb, "shell", "input", "tap", str(x), str(y)], check=True, timeout=10) + print("Declined optional Play Protect APK upload", flush=True) + + +def install(adb, apk): + deadline = time.monotonic() + 300 + command = [*adb, "install", "-r", apk] + with subprocess.Popen(command) as process: + try: + while time.monotonic() < deadline: + try: + status = process.wait(timeout=5) + except subprocess.TimeoutExpired: + decline_optional_upload(adb) + continue + if status: + raise subprocess.CalledProcessError(status, command) + return + raise TimeoutError(f"Android did not finish installing {apk} within 300 seconds") + finally: + if process.poll() is None: + process.kill() diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts new file mode 100644 index 000000000..79de24a45 --- /dev/null +++ b/scripts/performance/launch.ts @@ -0,0 +1,116 @@ +import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { z } from 'zod' + +const argumentsSchema = z.tuple([ + z.string(), z.string(), z.enum(['com.margelo.reactnitro.example.baseline', 'com.margelo.reactnitro.example.candidate']), z.string(), +]).rest(z.string()) +const [checkout, serial, applicationId, output, controlFixture] = argumentsSchema.parse(process.argv.slice(2)) +const resultSchema = z.object({ + startedAt: z.number(), endedAt: z.number(), mmkvReadMs: z.number().positive(), renderUpdateMs: z.number().positive(), +}) +const sampleSchema = z.looseObject({ + type: z.string(), timestamp: z.number(), metrics: z.record(z.string(), z.number()), +}) +const sessionSchema = z.looseObject({ sessionId: z.string().uuid(), samples: z.array(sampleSchema) }) +const app = resolve(checkout, 'apps/example') +const devicePort = 9875 + +async function adb(...command: string[]) { + const proc = Bun.spawn(['adb', '-s', serial, ...command], { stdout: 'pipe', stderr: 'inherit' }) + const stream = new Response(proc.stdout) + const output = await stream.text() + const code = await proc.exited + if (code !== 0) throw new Error(`adb ${command.join(' ')} exited with ${code}`) + return output.trim() +} + +async function readSdkSession() { + const directory = 'files/margelo-analytics/current' + const files = await adb('shell', 'run-as', applicationId, 'ls', directory) + if (files === '') return + const name = /^session-([a-f0-9-]+)\.json$/.exec(files) + if (name === null) throw new Error(`Unexpected active SDK session files: ${files}`) + const content = await adb('exec-out', 'run-as', applicationId, 'cat', `${directory}/${files}`) + // The SDK writes its first session file asynchronously, in place. + if (!content.endsWith('}')) return + const json: unknown = JSON.parse(content) + const session = sessionSchema.parse(json) + if (session.sessionId !== name[1]) throw new Error('SDK filename and session ID disagree') + return session +} + +async function readMetrics(result: z.infer) { + const deadline = performance.now() + 15_000 + while (performance.now() < deadline) { + const sdk = await readSdkSession() + if (sdk !== undefined) { + const before = sdk.samples.findLast((s) => s.type === 'cpu' && s.timestamp <= result.startedAt) + const after = sdk.samples.find((s) => s.type === 'cpu' && s.timestamp >= result.endedAt) + const memory = sdk.samples.find((s) => s.type === 'memory' && s.timestamp === after?.timestamp) + if (before !== undefined && after !== undefined && memory !== undefined) { + const start = z.number().nonnegative().parse(before.metrics.cpuTotalTimeMs) + const end = z.number().positive().parse(after.metrics.cpuTotalTimeMs) + const processCpuMs = end - start + if (processCpuMs <= 0) throw new Error('SDK process CPU counter did not advance') + const processPssBytes = z.number().positive().parse(memory.metrics.processPssBytes) + return { + metrics: { mmkvReadMs: result.mmkvReadMs, renderUpdateMs: result.renderUpdateMs, processCpuMs: processCpuMs, processPssBytes: processPssBytes }, + window: { startedAt: result.startedAt, endedAt: result.endedAt, sdkStartedAt: before.timestamp, sdkEndedAt: after.timestamp }, + sdk: sdk, + } + } + } + await Bun.sleep(100) + } + throw new Error('SDK did not persist CPU and memory samples bracketing this workload') +} + +const hostPath = Bun.resolveSync('react-nitro-harness/host', app) +const harness: typeof import('../../packages/react-nitro-harness/src/host') = await import(hostPath) +const staging = join(app, '.nitro/performance') +const runs = join(staging, '.runs') +await mkdir(runs, { recursive: true }) +const run = await mkdtemp(join(runs, 'launch-')) +let result: Awaited> | undefined +const receiver = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (request.method !== 'POST') return new Response(null, { status: 405 }) + if (url.pathname === '/api/v1/sessions') return new Response(null, { status: 201 }) + if (url.pathname !== '/result') return new Response(null, { status: 404 }) + const json: unknown = await request.json() + const timings = resultSchema.parse(json) + result = await readMetrics(timings) + return new Response('OK') + }, +}) +let harnessPort: number | undefined +try { + const fixture = controlFixture ?? join(staging, 'workloads.android.harness.tsx') + const target = join(run, 'workloads.android.harness.tsx') + await copyFile(fixture, target) + const summary = await harness.runHarness({ + root: run, entry: join(app, 'src/index.tsx'), platform: 'android', patterns: [], ignored: [], + testNamePattern: undefined, launchTimeout: 90_000, testTimeout: 60_000, + async launch(serverURL, port) { + harnessPort = port + await adb('reverse', `tcp:${devicePort}`, `tcp:${receiver.port}`) + await adb('reverse', `tcp:${port}`, `tcp:${port}`) + const component = `${applicationId}/com.margelo.reactnitro.example.MainActivity` + await adb('shell', 'am', 'start', '-W', '-S', '-n', component, '--es', 'ReactNitroDevServerURL', serverURL) + }, + }) + if (summary.files.failed || summary.tests.passed !== 1 || result === undefined) throw new Error('Incomplete Android benchmark') + const serialized = JSON.stringify(result) + await Bun.write(output, serialized) +} finally { + receiver.stop(true) + await rm(run, { recursive: true }) + if (harnessPort !== undefined) { + await adb('reverse', '--remove', `tcp:${harnessPort}`) + await adb('reverse', '--remove', `tcp:${devicePort}`) + } +} diff --git a/scripts/performance/prepare.py b/scripts/performance/prepare.py new file mode 100644 index 000000000..24e89d461 --- /dev/null +++ b/scripts/performance/prepare.py @@ -0,0 +1,56 @@ +"""Stage the benchmark in an expendable checkout of the revision being measured.""" + +import argparse +import json +from pathlib import Path +import shutil + + +MAVEN_REPOSITORY = """ +dependencyResolutionManagement.repositories { + 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() + } + } + } + filter { includeGroup("com.callstack") } + } +} +""" + +APP_ID = """ +android.defaultConfig { + val arm = rootProject.file("../.nitro/performance/arm").readText().trim() + applicationIdSuffix = ".$arm" +} +""" + + +def append_once(path, addition): + contents = path.read_text() + if addition not in contents: + path.write_text(contents + addition) + + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument("checkout", type=Path) +parser.add_argument("arm", choices=("baseline", "candidate")) +args = parser.parse_args() + +app = args.checkout.resolve() / "apps/example" +package = app / "package.json" +manifest = json.loads(package.read_text()) +manifest["dependencies"]["@callstack/performance-analytics-react-nitro"] = "0.1.0" +package.write_text(json.dumps(manifest, indent=2) + "\n") +append_once(app / "android/settings.gradle.kts", MAVEN_REPOSITORY) +append_once(app / "android/app/build.gradle.kts", APP_ID) +stage = app / ".nitro/performance" +stage.mkdir(parents=True, exist_ok=True) +(stage / "arm").write_text(args.arm + "\n") +source = Path(__file__).resolve().with_name("workloads.tsx") +shutil.copyfile(source, stage / "workloads.android.harness.tsx") diff --git a/scripts/performance/run.py b/scripts/performance/run.py new file mode 100644 index 000000000..6aa33b393 --- /dev/null +++ b/scripts/performance/run.py @@ -0,0 +1,129 @@ +"""Install both instrumented APKs and run a paired Harness experiment on one ADC lease.""" + +import argparse +import hashlib +import json +import os +from datetime import datetime, timezone +from pathlib import Path +import subprocess + +from install import install + + +HERE = Path(__file__).resolve().parent +WORKLOAD = Path("apps/example/.nitro/performance/workloads.android.harness.tsx") +VARIANTS = ("baseline", "candidate") + + +def output(command): + return subprocess.check_output(command, text=True, timeout=120).strip() + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def sha256(path): + digest = hashlib.sha256() + with path.open("rb") as data: + for chunk in iter(lambda: data.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2) + "\n") + + +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("--pairs", type=int, default=12) + parser.add_argument("--first", choices=VARIANTS, default="baseline") + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--control-fixture", type=Path, help="Candidate-only fixture for a labeled positive control") + args = parser.parse_args() + if args.pairs < 2 or args.pairs % 2: + parser.error("--pairs must be a positive even number") + serial = os.environ["ANDROID_SERIAL"] + lease = os.environ["ADC_LEASE_ID"] + adb = ["adb", "-s", serial] + arms = {} + for variant in VARIANTS: + root, apk = getattr(args, variant) + fixture = root / WORKLOAD + if variant == "candidate" and args.control_fixture is not None: + fixture = args.control_fixture + arms[variant] = { + "applicationId": f"com.margelo.reactnitro.example.{variant}", + "ref": output(["git", "-C", root, "rev-parse", "HEAD"]), + "apkSha256": sha256(apk), + "fixtureSha256": sha256(fixture), + } + same_workload = arms["baseline"]["fixtureSha256"] == arms["candidate"]["fixtureSha256"] + if same_workload != (args.control_fixture is None): + parser.error("Ordinary comparisons require identical fixtures, positive controls require different fixtures") + + args.output.mkdir(parents=True, exist_ok=False) + leases = json.loads(output(["adc", "leases"]))["leases"] + device = next(item["device_id"] for item in leases if item["id"] == lease) + props = ("ro.build.fingerprint", "ro.product.cpu.abi", "ro.product.model", "ro.hardware", "ro.build.version.sdk") + metadata = { + "started": now(), "lease": lease, "deviceId": device, + "properties": {key: output([*adb, "shell", "getprop", key]) for key in props}, + "cpusOnline": output([*adb, "shell", "cat", "/sys/devices/system/cpu/online"]), + "pairs": args.pairs, "first": args.first, "positiveControl": args.control_fixture is not None, + "arms": arms, + } + write_json(args.output / "session.json", metadata) + + for variant in VARIANTS: + _, apk = getattr(args, variant) + install(adb, apk) + package = arms[variant]["applicationId"] + path = output([*adb, "shell", "pm", "path", package]) + if not path.startswith("package:") or "\n" in path: + raise ValueError(f"APK did not install as {package}") + installed_apk = path.removeprefix("package:") + checksum = output([*adb, "shell", "sha256sum", installed_apk]) + if checksum.split()[0] != arms[variant]["apkSha256"]: + raise ValueError(f"The installed {package} differs from {apk}") + cleared = output([*adb, "shell", "pm", "clear", package]) + if cleared != "Success": + raise ValueError(f"Could not clear {package} before warmup: {cleared}") + + first = VARIANTS if args.first == "baseline" else VARIANTS[::-1] + with (args.output / "raw.jsonl").open("x") as raw: + for pair in range(args.pairs + 1): + # Pair zero warms both arms. Reverse the order for each subsequent pair. + order = first if pair % 2 else first[::-1] + for position, variant in enumerate(order, start=1): + root, _ = getattr(args, variant) + package = arms[variant]["applicationId"] + name = f"pair-{pair:02d}-{position}-{variant}" if pair else f"warmup-{variant}" + result_file = args.output / f"{name}.json" + command = ["bun", HERE / "launch.ts", root.resolve(), serial, package, result_file.resolve()] + if variant == "candidate" and args.control_fixture is not None: + command.append(args.control_fixture.resolve()) + started = now() + print(f"{started} {name}", flush=True) + try: + subprocess.run(command, check=True, timeout=180) + finally: + subprocess.run([*adb, "shell", "am", "force-stop", package], check=True, timeout=30) + result = json.loads(result_file.read_text()) + if pair: + row = { + "session": lease, "pair": pair, "position": position, "variant": variant, + "started": started, "finished": now(), "metrics": result["metrics"], + } + raw.write(json.dumps(row, allow_nan=False) + "\n") + raw.flush() + metadata["finished"] = now() + write_json(args.output / "session.json", metadata) + + +if __name__ == "__main__": + main() diff --git a/scripts/performance/workloads.tsx b/scripts/performance/workloads.tsx new file mode 100644 index 000000000..6e13858ac --- /dev/null +++ b/scripts/performance/workloads.tsx @@ -0,0 +1,61 @@ +import { PerformanceAnalytics } from '@callstack/performance-analytics-react-nitro' +import { expect, it, render } from 'react-nitro-harness' +import { MMKV } from 'react-nitro-mmkv' +import { Text, View } from 'react-nitro-renderer' + +const rows = Array.from({ length: 48 }, (_, index) => index) +const keys = Array.from({ length: 256 }, (_, index) => `item-${index}`) +const readPasses = 128 +const resultHost = 'http://127.0.0.1:9875' + +function Rows({ revision }: { revision: number }) { + return ( + + {rows.map((row) => ( + + {`Row ${row}, revision ${revision}`} + + ))} + + ) +} + +it('measures MMKV reads and React commits on Android', async () => { + const store = new MMKV({ id: 'adc-performance' }) + for (const [value, key] of keys.entries()) store.set(key, value) + const tree = await render() + + PerformanceAnalytics.init({ + host: resultHost, + apiKey: 'ps_local_benchmark', + sampleIntervalMs: 60_000, + autoInjectFCP: false, + enableTouchTracking: false, + }) + // The SDK captures its first CPU and memory samples asynchronously upon setup. + await new Promise((resolve) => setTimeout(resolve, 1000)) + const startedAt = Date.now() + const readStart = performance.now() + let checksum = 0 + for (let pass = 0; pass < readPasses; pass++) { + for (const key of keys) { + const value = store.getNumber(key) + if (value === undefined) throw new Error(`Missing MMKV key ${key}`) + checksum += value + } + } + const mmkvReadMs = performance.now() - readStart + const expected = readPasses * keys.length * (keys.length - 1) / 2 + expect(checksum).toBe(expected) + + const renderStart = performance.now() + for (let revision = 1; revision <= 12; revision++) { + await tree.rerender() + } + const renderUpdateMs = performance.now() - renderStart + const endedAt = Date.now() + PerformanceAnalytics.flushNow() + const body = JSON.stringify({ startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs }) + const response = await fetch(`${resultHost}/result`, { method: 'POST', body: body }) + expect(response.ok).toBe(true) +}, 60_000) From 71d9617492510ea8a2abd017459059405c2d09c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sun, 29 Nov 2026 20:47:24 +0100 Subject: [PATCH 2/9] test(performance): run paired Harness benchmarks in Android Release --- .github/workflows/android-performance.yml | 29 ++- scripts/performance/BenchmarkSnapshot.kt | 16 ++ scripts/performance/README.md | 50 ++--- scripts/performance/analyze.py | 201 +++++++++---------- scripts/performance/entry.tsx | 67 +++++++ scripts/performance/launch.ts | 194 ++++++++++-------- scripts/performance/precision.py | 229 ++++++++++++++++++++++ scripts/performance/prepare.py | 40 +++- scripts/performance/run.py | 47 +++-- scripts/performance/workloads.tsx | 84 ++++---- 10 files changed, 681 insertions(+), 276 deletions(-) create mode 100644 scripts/performance/BenchmarkSnapshot.kt create mode 100644 scripts/performance/entry.tsx create mode 100644 scripts/performance/precision.py diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index 440917f3b..1a846d08d 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -9,9 +9,16 @@ on: required: true candidate: description: Candidate Git ref (defaults to the workflow revision) + workload: + description: Repository-relative Harness workload to embed in both apps + default: scripts/performance/workloads.tsx pairs: - description: Measured pairs on the same device (even number) - default: '24' + description: Maximum measured pairs on the same device (even, at least 20) + default: '64' + required: true + precision: + description: Required precision for both timing effects in percentage points + default: '5' required: true pull_request: @@ -27,7 +34,9 @@ jobs: CC: clang CXX: clang++ CMAKE_BUILD_PARALLEL_LEVEL: 2 - PAIRS: ${{ inputs.pairs || '24' }} + PAIRS: ${{ inputs.pairs || '64' }} + TARGET_PP: ${{ inputs.precision || '5' }} + WORKLOAD: ${{ inputs.workload || 'scripts/performance/workloads.tsx' }} steps: - uses: actions/checkout@v7 with: @@ -66,19 +75,21 @@ jobs: "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" 'platforms;android-36' 'ndk;29.0.14206865' 'cmake;3.22.1' platform-tools echo "$ANDROID_HOME/platform-tools" >> "$GITHUB_PATH" - - name: Build the instrumented APK from each revision + - name: Build the Release benchmark APK from each revision env: PERF_MAVEN_USER: ${{ secrets.PERF_MAVEN_USER }} PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} run: | (cd experiment && bun install --frozen-lockfile --ignore-scripts) for arm in baseline candidate; do - python3 experiment/scripts/performance/prepare.py "$arm" "$arm" - (cd "$arm" && bun install && cd apps/example && bun run android --build-only) - metadata="$arm/apps/example/.nitro/android/apks/debug.json" + python3 experiment/scripts/performance/prepare.py "$arm" "$arm" --workload "experiment/$WORKLOAD" + (cd "$arm" && bun install && cd apps/example && bun run android --release --build-only --abi arm64-v8a) + metadata="$arm/apps/example/.nitro/android/apks/release.json" id=$(jq -er .applicationId "$metadata") test "$id" = "com.margelo.reactnitro.example.$arm" apk=$(jq -er '.elements | select(length == 1) | .[0].outputFile' "$metadata") + debuggable=$("$ANDROID_HOME/cmdline-tools/latest/bin/apkanalyzer" manifest debuggable "$apk") + test "$debuggable" = false cp "$apk" "$arm.apk" done @@ -92,12 +103,12 @@ jobs: height: '1600' dpi: '320' command: | - python3 experiment/scripts/performance/run.py --pairs "$PAIRS" \ + python3 experiment/scripts/performance/run.py --pairs "$PAIRS" --target-pp "$TARGET_PP" \ --baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results - name: Summarize paired changes run: | - python3 experiment/scripts/performance/analyze.py --expect-pairs "$PAIRS" experiment/results/raw.jsonl > experiment/results/report.md + python3 experiment/scripts/performance/analyze.py --session experiment/results/session.json experiment/results/raw.jsonl > experiment/results/report.md cat experiment/results/report.md >> "$GITHUB_STEP_SUMMARY" - name: Save readings and SDK sessions to CI storage diff --git a/scripts/performance/BenchmarkSnapshot.kt b/scripts/performance/BenchmarkSnapshot.kt new file mode 100644 index 000000000..a1aba6c33 --- /dev/null +++ b/scripts/performance/BenchmarkSnapshot.kt @@ -0,0 +1,16 @@ +package com.margelo.reactnitro.example + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Base64 +import com.callstack.performanceanalytics.CallstackPerformanceAnalytics + +class BenchmarkSnapshot : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val files = CallstackPerformanceAnalytics.readStoredPayloadFilesForDebug(context) + val session = files.current.singleOrNull() ?: return + val bytes = session.content.toByteArray(Charsets.UTF_8) + resultData = Base64.encodeToString(bytes, Base64.NO_WRAP) + } +} diff --git a/scripts/performance/README.md b/scripts/performance/README.md index d8003208c..43af4c5f6 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -1,43 +1,45 @@ -# Android performance on ADC +# Paired Release benchmarks on ADC -The Android performance workflow builds the example app from two Git revisions. It stages the same Harness test and Callstack Performance Analytics SDK 0.1.0 into both builds. Each revision supplies its own JavaScript packages and native code. The baseline and candidate APKs have separate package IDs and stay installed throughout one ADC lease. +The workflow builds the example app from the PR base and head. Each APK embeds the same benchmark entry and workload, compiled with that revision's Android Release pipeline. React, its reconciler and the Nitro renderer run through Static Hermes. The benchmark app loads its optimized Hermes bytecode from the APK. It uses the existing Harness test collector, executor, assertions and render root. The regular functional E2E suite has its own entry. -To compare a PR, enable the repository variable `ENABLE_ANDROID_PERFORMANCE=true`. Same-repository PRs compare the base and head SHAs. The workflow also accepts two refs through `workflow_dispatch`. Set both inputs to the same commit for an A/A calibration. The Maven download needs repository secrets `PERF_MAVEN_USER` and `PERF_MAVEN_TOKEN` for a user with read access to the SDK's GitHub Packages. The ADC and S3 credentials are shared with the functional E2E workflow. +## Running the comparison -The runner warms up both packages, starts a fresh process for each measurement, and alternates pairs in AB, BA order. The Debug Harness runs 32,768 native MMKV reads and 12 React commits that update 48 rows. The app times those two operations with its monotonic clock. The SDK separately records process CPU and PSS. CPU counts process-wide work between the SDK samples surrounding the test, including the one-second settling period and SDK activity. PSS is the final snapshot. The measured React commits can precede presentation on the display. +Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. The build uses `PERF_MAVEN_USER` and `PERF_MAVEN_TOKEN` with read access to the SDK's GitHub Packages, plus the existing ADC and CI S3 credentials. -Callstack's Nitro adapter exposes `init` and `flushNow`. The host uses ADB reverse for Harness and receives the timed workload result on loopback. It reads the flushed SDK session from the Debug app's private directory via `adb exec-out run-as`, checks sample timestamps and saves the original payload with each launch. This prototype depends on the storage layout in SDK 0.1.0. +The optional `workload` dispatch input selects a repository-relative fixture from the workflow revision for both builds. Locally, pass the same `--workload path/to/workloads.tsx` to both invocations of `prepare.py`. The driver checks the fixture digest on every launch. The default fixture shows the Harness registration and the two timing fields used by the stopping rule. -The GitHub job summary shows each variant's median and variation, paired changes, an interval by lease and separate results for each launch order. Raw readings, build SHAs, APK and fixture hashes, device properties, SDK sessions and warmups go to the existing private CI bucket. Failed or partial runs preserve the data produced up to the failure. The job reports performance differences without a pass/fail threshold. Test, instrumentation and incomplete-run failures fail the job. - -## Calibration on November 29, 2026 - -Two A/A runs of 24 pairs on separate ADC Android 15 arm64 VMs used commit `b4d118ea`. The MMKV time changed by +1.2% (95% interval −7.0% to +4.8%) and +0.3% (−2.0% to +2.8%). The React update time changed by −0.7% and +1.7%. The measured launches took about 7½ minutes per VM. The default is 24 pairs. A small timing threshold still needs calibration across further devices and days. - -On a third VM, increasing only the candidate's MMKV reads by 25% raised its time by 20.0% (+17.5% to +35.5%) across 20 pairs. The unchanged React workload moved +0.3%. A fourth VM compared the same main revision with PR #717 (`ac356ba5`, optimized Debug Hermes). Across 12 pairs MMKV time fell 90.5%, React update time fell 85.1%, and process CPU time fell 57.4%. [PR #717](https://github.com/margelo/react-nitro/pull/717) - -## Run the same experiment outside Actions - -Use two expendable checkouts of the revisions to test. Run the following from a third checkout with the prototype and its Bun dependencies installed. The preparation step changes the example app and its dependency lock in the expendable checkouts. Set the two Maven credential variables in the build environment, initialize submodules and use the Android toolchain from the existing example CI. +For a local run, use expendable baseline and candidate checkouts next to the prototype checkout. Preparation stages the SDK, app entry and benchmark-only Android receiver in each checkout. Set the Maven variables in the build environment and use the same Android toolchain as example CI. ```sh for arm in baseline candidate; do root="../$arm" git -C "$root" submodule update --init --recursive python3 scripts/performance/prepare.py "$root" "$arm" - (cd "$root" && bun install && cd apps/example && bun run android --build-only) - metadata="$root/apps/example/.nitro/android/apks/debug.json" + (cd "$root" && bun install && cd apps/example && bun run android --release --build-only --abi arm64-v8a) + metadata="$root/apps/example/.nitro/android/apks/release.json" cp "$(jq -er '.elements[0].outputFile' "$metadata")" "../$arm.apk" done - +bun install --frozen-lockfile --ignore-scripts adc run --purpose ci --form-factor phone --api-level 35 --width 720 --height 1600 --dpi 320 -- \ - python3 scripts/performance/run.py --pairs 24 --output ../performance-run \ + python3 scripts/performance/run.py --pairs 64 --target-pp 5 --output ../performance-run \ --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk -python3 scripts/performance/analyze.py --expect-pairs 24 ../performance-run/raw.jsonl +python3 scripts/performance/analyze.py --session ../performance-run/session.json ../performance-run/raw.jsonl ``` -For a positive control, copy the staged fixture from the candidate's `apps/example/.nitro/performance/` directory, increase `readPasses` from 128 to 160, and pass the copy's path to `run.py --control-fixture`. The runner records the differing workload hashes. This exercises detection of 25% additional MMKV reads. +## Measurements + +Both package IDs stay installed on one leased VM. The driver checks the installed APK hashes, clears both packages, warms up each arm and starts a fresh process for every measurement. Each adjacent pair of launches alternates AB, BA. 32,768 MMKV reads and twelve React commits updating 48 rows are timed on the device. React timing ends at commit. Display presentation is a different measurement. + +For each launch, the CI host forwards a loopback port with ADB. The app returns a unique launch nonce, the embedded workload digest, the compiled Static Hermes framework ID and the actual read count. A benchmark-only broadcast receiver restricted to Android's DUMP permission reads the SDK's current session through its native API. The host acknowledges SDK CPU snapshots bracketing the workload and saves the final PSS sample. The process CPU delta also includes work between those samples outside the two timed sections. The APK can run with the debuggable flag disabled. + +During an earlier Debug calibration on macOS, another service answered the shared Harness host's IPv4 request for `/client.js` with HTTP 404. That run ended after 23 of 40 planned launches. The Release prototype binds its CI receiver directly to `127.0.0.1:0` and forwards the port assigned to that open socket. + +Set both refs to the same commit for an A/A calibration. For a positive control, add `--candidate-read-passes 141` to increase the candidate's MMKV passes from 128 to 141 (10.15625% more reads) with the same APK and bytecode. Use `--fixed` to collect every planned pair and replay earlier decisions. Keep interrupted series separate and restart a complete campaign on a fresh lease. + +## Precision and stopping + +The default maximum is 64 measured pairs, plus one warmup per arm. At 20, 24, 32, 48 and 64 pairs, the runner estimates the change in the two primary timings. Each AB/BA block contributes one average log ratio. The estimate is the median of those blocks, expressed as a percent change. For a higher ceiling, the additional predefined looks are 96, 128, 192 and 256 pairs. An even ceiling of at least 20 includes the preceding looks and the chosen ceiling. The interval calculation uses that entire schedule from the start. -## Incomplete local runs +A two-sided order-statistic interval uses the binomial sign distribution. The total error budget is 5% per lease across the two primary metrics and all planned looks (Bonferroni). The rule assumes independent blocks with a common median effect within the lease. Both endpoints must be within the requested number of percentage points of the estimate for both timings before the run may stop early. At the cap the run reports any remaining uncertainty. Serial correlation, device drift and differences between host days limit transfer of an interval to future leases. [Median confidence limits](https://itl.nist.gov/div898/software/dataplot/refman1/auxillar/mediancl.htm) · [Simultaneous confidence intervals](https://online.stat.psu.edu/stat505/Lesson05) -During calibration on macOS, the Harness selected a port where an existing process on IPv4 loopback answered the app's request for `/client.js` with HTTP 404. The launch timed out before the benchmark ran. The raw JSONL stopped at 23 of 40 measurements and the analyzer rejected the incomplete series. The experiment was repeated from warmup on a fresh lease. When investigating a similar failure, save the Android dev error and check the host listener with `lsof -nP -iTCP: -sTCP:LISTEN`. +The practical comparison band is ±5%. An interval wholly above +5% signals a regression, wholly below −5% signals an improvement, and wholly inside the band supports practical equivalence. Crossing a boundary leaves that decision open even if the estimate is precise. SDK CPU and PSS are secondary observations. The job publishes the result in the GitHub summary and writes per-launch JSON, SDK data and checkpoint decisions to the private CI bucket. Performance classifications are advisory. Build errors, failed Harness tests and incomplete sessions fail the job. diff --git a/scripts/performance/analyze.py b/scripts/performance/analyze.py index fa535ceba..6eb66cd3f 100644 --- a/scripts/performance/analyze.py +++ b/scripts/performance/analyze.py @@ -6,94 +6,10 @@ import statistics from pathlib import Path - -def add_sample(sessions, row): - if not isinstance(row, dict): - raise ValueError("expected a JSON object") - session = row.get("session") - pair = row.get("pair") - position = row.get("position") - variant = row.get("variant") - metrics = row.get("metrics") - if not isinstance(session, str) or not session.strip(): - raise ValueError("expected a session identifier") - if type(pair) is not int or pair < 1: - raise ValueError("expected a positive pair number") - if type(position) is not int or position not in (1, 2): - raise ValueError("expected position 1 or 2") - if variant not in ("baseline", "candidate"): - raise ValueError("expected variant baseline or candidate") - if not isinstance(metrics, dict) or not metrics: - raise ValueError("expected a nonempty metrics object") - for name, value in metrics.items(): - if not name or type(value) not in (int, float) or not math.isfinite(value): - raise ValueError(f"invalid numeric metric {name!r}") - - pairs = sessions.setdefault(session, {}) - launches = pairs.setdefault(pair, {}) - if position in launches: - raise ValueError(f"duplicate launch in {session}, pair {pair}, position {position}") - launches[position] = (variant, metrics) - - -def read_sessions(paths): - sessions = {} - for path in paths: - with path.open() as source: - for line_number, line in enumerate(source, 1): - try: - row = json.loads(line) - add_sample(sessions, row) - except ValueError as error: - raise ValueError(f"{path}:{line_number}: {error}") from error - if not sessions: - raise ValueError("no measurements") - return sessions - - -def ordered_pairs(pairs, expected_count): - count = len(pairs) - if expected_count is not None and count != expected_count: - raise ValueError(f"expected {expected_count} pairs, found {count}") - if count < 2 or count % 2 or min(pairs) != 1 or max(pairs) != count: - raise ValueError("expected an even number of consecutive pairs starting at 1") - - previous_first = None - names = None - samples = [] - for number in range(1, count + 1): - launches = pairs[number] - if len(launches) != 2: - raise ValueError(f"pair {number} is incomplete") - first, first_metrics = launches[1] - second, second_metrics = launches[2] - if first == second or first == previous_first: - raise ValueError(f"pair {number} violates the alternating AB/BA order") - previous_first = first - if names is None: - names = first_metrics.keys() - if first_metrics.keys() != names or second_metrics.keys() != names: - raise ValueError(f"pair {number} has inconsistent metric names") - samples.append((first, {first: first_metrics, second: second_metrics})) - return samples - - -def median_interval(blocks): - # The two tails of Binomial(n, 0.5) determine the order statistics - # that cover the population median with at least 95% confidence. - n = len(blocks) - outcomes = 2 ** n - tail = 0 - rank = 0 - for index in range(n // 2): - tail += math.comb(n, index) - if 40 * tail > outcomes: - break - rank += 1 - if rank == 0: - return None - ordered = sorted(blocks) - return ordered[rank - 1], ordered[-rank] +from precision import ( + PrecisionPlan, balanced_blocks, evaluate_samples, median_interval, + metric_changes, ordered_pairs, read_sessions, +) def level(values): @@ -105,15 +21,12 @@ def level(values): return f"{median:.5g} ({deviation / mean:.1%})" -def metric_row(name, samples): +def metric_row(name, samples, decision): baseline = [arms["baseline"][name] for _, arms in samples] candidate = [arms["candidate"][name] for _, arms in samples] - relative = min(baseline) > 0 and min(candidate) > 0 - changes = [] + relative, changes = metric_changes(samples, name) by_order = {"baseline": [], "candidate": []} - for (first, _), a, b in zip(samples, baseline, candidate): - change = math.log(b) - math.log(a) if relative else b - a - changes.append(change) + for (first, _), change in zip(samples, changes): by_order[first].append(change) def display(change): @@ -122,13 +35,21 @@ def display(change): return f"{ratio_change:+.2%}" return f"{change:+.5g}" - blocks = [(ab + ba) / 2 for ab, ba in zip(changes[::2], changes[1::2])] + blocks = balanced_blocks(changes) estimate = statistics.median(blocks) - interval = median_interval(blocks) bounds = "n/a" - if interval is not None: - low, high = interval - bounds = f"{display(low)} to {display(high)}" + if decision is None: + interval = median_interval(blocks) + if interval is not None: + low, high = interval + bounds = f"{display(low)} to {display(high)}" + elif name in decision["metrics"]: + primary = decision["metrics"][name] + low, high = primary["lowerPct"], primary["upperPct"] + if low is not None: + bounds = f"{low:+.2f}% to {high:+.2f}% ({primary['classification']})" + else: + bounds = "descriptive" deciles = statistics.quantiles(changes, n=10, method="inclusive") ab_median = statistics.median(by_order["baseline"]) ba_median = statistics.median(by_order["candidate"]) @@ -139,24 +60,35 @@ def display(change): ) -def report(sessions, expected_count): +def report(sessions, expected_count, decisions=None): lines = ["## Paired Android performance"] for session, pairs in sessions.items(): try: samples = ordered_pairs(pairs, expected_count) except ValueError as error: raise ValueError(f"{session}: {error}") from error + decision = decisions.get(session) if decisions else None + interval_label = "Simultaneous 95% interval" if decision else "95% interval" lines.extend([ "", f"### {session} ({len(samples)} pairs)", "", - "| Metric | Baseline median (CV) | Candidate median (CV) | Change | 95% interval " + "| Metric | Baseline median (CV) | Candidate median (CV) | Change | " + interval_label + " " "| Pair P10 to P90 | AB / BA medians |", "|---|---:|---:|---:|---:|---:|---:|", ]) _, first = samples[0] for name in sorted(first["baseline"]): - lines.append(metric_row(name, samples)) + lines.append(metric_row(name, samples, decision)) + if decision: + precision_reached = decision["reason"] == "precision_reached" + outcome = "met" if precision_reached else "unmet" + lines.extend([ + "", f"At {decision['pairs']} pairs, the joint ±{decision['targetPp']:g} percentage-point " + f"precision target is {outcome}. Practical equivalence " + f"requires the whole interval to fit inside ±{decision['equivalencePp']:g}%.", + ]) + lines.extend([ "", "Positive change means the candidate value is higher. Each adjacent AB/BA block " @@ -165,19 +97,78 @@ def report(sessions, expected_count): "", "CV is the sample standard deviation divided by the mean. Pair P10 to P90 shows the " "spread of individual paired changes. AB runs the baseline first and BA runs the candidate first. " - "The rank-based interval assumes independent blocks within a session and requires at least 12 pairs.", + "Rank intervals assume independent blocks with a common median within the lease.", ]) + if decisions: + lines.extend([ + "", "Primary intervals allocate the 5% familywise error budget equally across the " + "prespecified looks and both timings. CPU and PSS are descriptive. Drift or serial " + "dependence between blocks can affect coverage.", + ]) return "\n".join(lines) +def verify_session(metadata, sessions): + lease = metadata["lease"] + if not metadata.get("finished") or lease not in sessions: + raise ValueError(f"{lease}: session is unfinished or missing from the raw measurements") + maximum = metadata["pairs"] + if metadata.get("precisionPlan") is None: + if metadata.get("adaptive") or metadata.get("completedPairs", maximum) != maximum: + raise ValueError(f"{lease}: incomplete or unplanned adaptive session") + ordered_pairs(sessions[lease], maximum) + return None + config = metadata["precisionPlan"] + plan = PrecisionPlan(max_pairs=config["maxPairs"], target_pp=config["targetPp"], + equivalence_pp=config["equivalencePp"]) + if config != plan.as_dict() or maximum != plan.max_pairs: + raise ValueError(f"{lease}: inconsistent precision plan") + samples = ordered_pairs(sessions[lease], metadata["completedPairs"]) + if samples[0][0] != metadata["first"]: + raise ValueError(f"{lease}: recorded launch order differs from the plan") + adaptive = metadata["adaptive"] + if type(adaptive) is not bool: + raise ValueError(f"{lease}: expected an adaptive or fixed-horizon experiment") + checkpoints = [] + for count in plan.looks: + if count > len(samples): + break + decision = evaluate_samples(samples[:count], plan) + checkpoints.append((count, decision["reason"])) + if adaptive and decision["stop"]: + break + if not checkpoints or checkpoints[-1][0] != len(samples): + raise ValueError(f"{lease}: measurements ended outside the allowed stopping rule") + if (adaptive and not decision["stop"]) or (not adaptive and len(samples) != maximum): + raise ValueError(f"{lease}: data ended before the required stopping point") + saved = [(look["pairs"], look["reason"]) for look in metadata["precisionLooks"]] + if saved != checkpoints: + raise ValueError(f"{lease}: stored and recomputed precision checkpoints differ") + return decision + + if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("raw", nargs="+", type=Path, help="one JSONL sample per measured launch") parser.add_argument("--expect-pairs", type=int, help="planned measured pairs per session") + parser.add_argument("--session", type=Path, help="validate run completion and preregistered looks") args = parser.parse_args() try: sessions = read_sessions(args.raw) - markdown = report(sessions, args.expect_pairs) - except (OSError, ValueError) as error: + if args.session is not None and len(sessions) != 1: + raise ValueError("--session requires one lease") + if args.session is not None: + paths = [args.session] + else: + paths = {path.with_name("session.json") for path in args.raw} + paths = [path for path in paths if path.is_file()] + decisions = {} + for path in paths: + metadata = json.loads(path.read_text()) + decision = verify_session(metadata, sessions) + if decision is not None: + decisions[metadata["lease"]] = decision + markdown = report(sessions, args.expect_pairs, decisions) + except (KeyError, OSError, TypeError, ValueError) as error: parser.exit(1, f"{error}\n") print(markdown) diff --git a/scripts/performance/entry.tsx b/scripts/performance/entry.tsx new file mode 100644 index 000000000..a6502eb37 --- /dev/null +++ b/scripts/performance/entry.tsx @@ -0,0 +1,67 @@ +import 'react-nitro-runtime' +import { useEffect } from 'react' +import { Application, renderRoot, ViewController, Window } from 'react-nitro-renderer' +import { finishCollection, resetCollection } from '../../../../packages/react-nitro-harness/src/collect' +import { execute, serializeError } from '../../../../packages/react-nitro-harness/src/execute' +import { restoreAllMocks } from '../../../../packages/react-nitro-harness/src/mock' +import type { TestResultMessage } from '../../../../packages/react-nitro-harness/src/protocol' +import { cleanup, HarnessRoot } from '../../../../packages/react-nitro-harness/src/render' +import { captureUncaughtErrors, takeUncaughtErrors } from '../../../../packages/react-nitro-harness/src/uncaught' +import { fixtureSha256 } from './provenance' +import { post, registerWorkloads, resultHost } from './workloads' + +async function run() { + const config = await fetch(`${resultHost}/config`) + const text = await config.text() + const [nonce, count] = text.split(' ') + if (nonce === undefined || count === undefined) throw new Error('Missing benchmark configuration') + + try { + if (__DEV__) throw new Error('The benchmark requires a production bundle') + const framework: unknown = Reflect.get(globalThis, '__reactNitroFramework') + if (typeof framework !== 'object' || framework === null || !('id' in framework) || typeof framework.id !== 'string') { + throw new Error('The benchmark requires the compiled Static Hermes framework') + } + const readPasses = Number(count) + if (!Number.isSafeInteger(readPasses) || readPasses < 1) throw new Error('Invalid MMKV pass count') + captureUncaughtErrors() + const root = resetCollection() + registerWorkloads(nonce, readPasses) + finishCollection() + const tests: TestResultMessage[] = [] + const fileErrors = await execute(root, { + testTimeout: 60_000, + testNamePattern: undefined, + async onTestStart() {}, + async onTestResult(path, status, duration, errors) { + tests.push({ type: 'test-result', path: path, status: status, duration: duration, errors: errors }) + }, + async afterEachTest() { + restoreAllMocks() + await cleanup() + }, + takeUncaughtErrors: () => takeUncaughtErrors(serializeError), + }) + await post('/complete', { + nonce: nonce, fixtureSha256: fixtureSha256, staticFrameworkId: framework.id, readPasses: readPasses, + tests: tests, fileErrors: fileErrors, + }) + } catch (error) { + const detail = serializeError(error) + await post('/failure', { nonce: nonce, error: detail }) + } +} + +function BenchmarkRoot() { + useEffect(() => { + run().catch((error: unknown) => console.error(error)) + }, []) + return +} + +Application.registerRoot((scene) => { + const controller = new ViewController() + controller.view.setBackgroundColor(0xffffffff) + renderRoot(, controller) + return new Window(scene, controller) +}) diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts index 79de24a45..7b1f5cf12 100644 --- a/scripts/performance/launch.ts +++ b/scripts/performance/launch.ts @@ -1,116 +1,140 @@ -import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises' -import { join, resolve } from 'node:path' import { z } from 'zod' -const argumentsSchema = z.tuple([ - z.string(), z.string(), z.enum(['com.margelo.reactnitro.example.baseline', 'com.margelo.reactnitro.example.candidate']), z.string(), -]).rest(z.string()) -const [checkout, serial, applicationId, output, controlFixture] = argumentsSchema.parse(process.argv.slice(2)) -const resultSchema = z.object({ +const argsSchema = z.tuple([ + z.string(), z.enum(['com.margelo.reactnitro.example.baseline', 'com.margelo.reactnitro.example.candidate']), + z.string(), z.coerce.number().int().positive().optional(), +]) +const [serial, applicationId, output, readPasses = 128] = argsSchema.parse(process.argv.slice(2)) +const nonce = crypto.randomUUID() +const base = z.object({ nonce: z.literal(nonce) }) +const beforeSchema = base.extend({ requestedAt: z.number() }) +const timingSchema = base.extend({ startedAt: z.number(), endedAt: z.number(), mmkvReadMs: z.number().positive(), renderUpdateMs: z.number().positive(), }) -const sampleSchema = z.looseObject({ - type: z.string(), timestamp: z.number(), metrics: z.record(z.string(), z.number()), +const errorSchema = z.object({ message: z.string(), stack: z.string() }) +const completedSchema = base.extend({ + tests: z.array(z.object({ status: z.string(), errors: z.array(errorSchema), path: z.array(z.string()), duration: z.number() })), + fileErrors: z.array(errorSchema), + fixtureSha256: z.string().regex(/^[a-f0-9]{64}$/), + staticFrameworkId: z.string().regex(/^[a-f0-9]{64}$/), + readPasses: z.literal(readPasses), +}) +const sessionSchema = z.looseObject({ + sessionId: z.string().uuid(), + samples: z.array(z.looseObject({ type: z.string(), timestamp: z.number(), metrics: z.record(z.string(), z.number()) })), }) -const sessionSchema = z.looseObject({ sessionId: z.string().uuid(), samples: z.array(sampleSchema) }) -const app = resolve(checkout, 'apps/example') -const devicePort = 9875 async function adb(...command: string[]) { const proc = Bun.spawn(['adb', '-s', serial, ...command], { stdout: 'pipe', stderr: 'inherit' }) const stream = new Response(proc.stdout) - const output = await stream.text() + const contents = await stream.text() const code = await proc.exited if (code !== 0) throw new Error(`adb ${command.join(' ')} exited with ${code}`) - return output.trim() -} - -async function readSdkSession() { - const directory = 'files/margelo-analytics/current' - const files = await adb('shell', 'run-as', applicationId, 'ls', directory) - if (files === '') return - const name = /^session-([a-f0-9-]+)\.json$/.exec(files) - if (name === null) throw new Error(`Unexpected active SDK session files: ${files}`) - const content = await adb('exec-out', 'run-as', applicationId, 'cat', `${directory}/${files}`) - // The SDK writes its first session file asynchronously, in place. - if (!content.endsWith('}')) return - const json: unknown = JSON.parse(content) - const session = sessionSchema.parse(json) - if (session.sessionId !== name[1]) throw new Error('SDK filename and session ID disagree') - return session + return contents.trim() } -async function readMetrics(result: z.infer) { +async function snapshotAtOrAfter(timestamp: number) { + const receiver = `${applicationId}/com.margelo.reactnitro.example.BenchmarkSnapshot` const deadline = performance.now() + 15_000 while (performance.now() < deadline) { - const sdk = await readSdkSession() - if (sdk !== undefined) { - const before = sdk.samples.findLast((s) => s.type === 'cpu' && s.timestamp <= result.startedAt) - const after = sdk.samples.find((s) => s.type === 'cpu' && s.timestamp >= result.endedAt) - const memory = sdk.samples.find((s) => s.type === 'memory' && s.timestamp === after?.timestamp) - if (before !== undefined && after !== undefined && memory !== undefined) { - const start = z.number().nonnegative().parse(before.metrics.cpuTotalTimeMs) - const end = z.number().positive().parse(after.metrics.cpuTotalTimeMs) - const processCpuMs = end - start - if (processCpuMs <= 0) throw new Error('SDK process CPU counter did not advance') - const processPssBytes = z.number().positive().parse(memory.metrics.processPssBytes) - return { - metrics: { mmkvReadMs: result.mmkvReadMs, renderUpdateMs: result.renderUpdateMs, processCpuMs: processCpuMs, processPssBytes: processPssBytes }, - window: { startedAt: result.startedAt, endedAt: result.endedAt, sdkStartedAt: before.timestamp, sdkEndedAt: after.timestamp }, - sdk: sdk, - } - } + const response = await adb('shell', 'am', 'broadcast', '--receiver-foreground', '-n', receiver) + const result = /^Broadcast completed: result=0(?:, data="([A-Za-z0-9+/=]+)")?$/m.exec(response) + if (result === null) throw new Error(`Android rejected the SDK snapshot request: ${response.slice(0, 300)}`) + const encoded = result[1] + if (encoded !== undefined) { + const bytes = Buffer.from(encoded, 'base64') + const content = bytes.toString('utf8') + const json: unknown = JSON.parse(content) + const sdk = sessionSchema.parse(json) + const cpu = sdk.samples.findLast((s) => s.type === 'cpu' && s.timestamp >= timestamp) + if (cpu !== undefined) return { sdk: sdk, cpu: cpu } } await Bun.sleep(100) } - throw new Error('SDK did not persist CPU and memory samples bracketing this workload') + throw new Error('The SDK did not produce the requested CPU sample') +} + +type Snapshot = Awaited> + +function measure(before: Snapshot, after: Snapshot, timings: z.infer) { + if (before.sdk.sessionId !== after.sdk.sessionId || before.cpu.timestamp > timings.startedAt || timings.startedAt > timings.endedAt) { + throw new Error('The SDK snapshots do not bracket this workload in one session') + } + const memory = after.sdk.samples.find((s) => s.type === 'memory' && s.timestamp === after.cpu.timestamp) + const processPssBytes = z.number().positive().parse(memory?.metrics.processPssBytes) + const start = z.number().nonnegative().parse(before.cpu.metrics.cpuTotalTimeMs) + const end = z.number().positive().parse(after.cpu.metrics.cpuTotalTimeMs) + const processCpuMs = end - start + if (processCpuMs <= 0) throw new Error('SDK process CPU counter did not advance') + return { + metrics: { mmkvReadMs: timings.mmkvReadMs, renderUpdateMs: timings.renderUpdateMs, processCpuMs: processCpuMs, processPssBytes: processPssBytes }, + window: { startedAt: timings.startedAt, endedAt: timings.endedAt, sdkStartedAt: before.cpu.timestamp, sdkEndedAt: after.cpu.timestamp }, + sdk: after.sdk, + } } -const hostPath = Bun.resolveSync('react-nitro-harness/host', app) -const harness: typeof import('../../packages/react-nitro-harness/src/host') = await import(hostPath) -const staging = join(app, '.nitro/performance') -const runs = join(staging, '.runs') -await mkdir(runs, { recursive: true }) -const run = await mkdtemp(join(runs, 'launch-')) -let result: Awaited> | undefined +let before: Snapshot | undefined +let readings: ReturnType | undefined +const completion = Promise.withResolvers | Error>() const receiver = Bun.serve({ - hostname: '127.0.0.1', - port: 0, + hostname: '127.0.0.1', port: 0, idleTimeout: 60, async fetch(request) { const url = new URL(request.url) + if (url.pathname === '/config' && request.method === 'GET') return new Response(`${nonce} ${readPasses}`) if (request.method !== 'POST') return new Response(null, { status: 405 }) if (url.pathname === '/api/v1/sessions') return new Response(null, { status: 201 }) - if (url.pathname !== '/result') return new Response(null, { status: 404 }) - const json: unknown = await request.json() - const timings = resultSchema.parse(json) - result = await readMetrics(timings) - return new Response('OK') + try { + const json: unknown = await request.json() + switch (url.pathname) { + case '/before': { + const start = beforeSchema.parse(json) + before = await snapshotAtOrAfter(start.requestedAt) + break + } + case '/result': { + if (before === undefined) throw new Error('Missing initial SDK sample') + const timings = timingSchema.parse(json) + const after = await snapshotAtOrAfter(timings.endedAt) + readings = measure(before, after, timings) + break + } + case '/complete': { + const report = completedSchema.parse(json) + completion.resolve(report) + break + } + case '/failure': { + const failure = base.extend({ error: errorSchema }).parse(json) + throw new Error(failure.error.stack) + } + default: + return new Response(null, { status: 404 }) + } + return new Response('OK') + } catch (error) { + const cause = error instanceof Error ? error : new Error(String(error)) + completion.resolve(cause) + return new Response(cause.message, { status: 500 }) + } }, }) -let harnessPort: number | undefined + +const devicePort = 'tcp:9875' +const deadline = setTimeout(() => completion.resolve(new Error('Release benchmark timed out')), 120_000) try { - const fixture = controlFixture ?? join(staging, 'workloads.android.harness.tsx') - const target = join(run, 'workloads.android.harness.tsx') - await copyFile(fixture, target) - const summary = await harness.runHarness({ - root: run, entry: join(app, 'src/index.tsx'), platform: 'android', patterns: [], ignored: [], - testNamePattern: undefined, launchTimeout: 90_000, testTimeout: 60_000, - async launch(serverURL, port) { - harnessPort = port - await adb('reverse', `tcp:${devicePort}`, `tcp:${receiver.port}`) - await adb('reverse', `tcp:${port}`, `tcp:${port}`) - const component = `${applicationId}/com.margelo.reactnitro.example.MainActivity` - await adb('shell', 'am', 'start', '-W', '-S', '-n', component, '--es', 'ReactNitroDevServerURL', serverURL) - }, - }) - if (summary.files.failed || summary.tests.passed !== 1 || result === undefined) throw new Error('Incomplete Android benchmark') - const serialized = JSON.stringify(result) + await adb('reverse', devicePort, `tcp:${receiver.port}`) + const component = `${applicationId}/com.margelo.reactnitro.example.MainActivity` + await adb('shell', 'am', 'start', '-W', '-S', '-n', component) + const report = await completion.promise + if (report instanceof Error) throw report + if (report.tests.length !== 1 || report.tests[0]?.status !== 'passed' || report.fileErrors.length !== 0) { + throw new Error(`Harness failed: ${JSON.stringify(report)}`) + } + if (readings === undefined) throw new Error('The release benchmark finished without SDK readings') + const serialized = JSON.stringify({ ...report, ...readings }) await Bun.write(output, serialized) } finally { - receiver.stop(true) - await rm(run, { recursive: true }) - if (harnessPort !== undefined) { - await adb('reverse', '--remove', `tcp:${harnessPort}`) - await adb('reverse', '--remove', `tcp:${devicePort}`) - } + clearTimeout(deadline) + await receiver.stop() + await adb('reverse', '--remove', devicePort) } diff --git a/scripts/performance/precision.py b/scripts/performance/precision.py new file mode 100644 index 000000000..02082fe6c --- /dev/null +++ b/scripts/performance/precision.py @@ -0,0 +1,229 @@ +"""Sequential precision for a median change across complete AB/BA blocks.""" + +import argparse +from dataclasses import dataclass +import json +import math +from pathlib import Path +import statistics + + +PRIMARY_METRICS = ("mmkvReadMs", "renderUpdateMs") +PLANNED_LOOKS = (20, 24, 32, 48, 64, 96, 128, 192, 256) + + +def add_sample(sessions, row): + if not isinstance(row, dict): + raise ValueError("expected a JSON object") + session = row.get("session") + pair = row.get("pair") + position = row.get("position") + variant = row.get("variant") + metrics = row.get("metrics") + if not isinstance(session, str) or not session.strip(): + raise ValueError("expected a session identifier") + if type(pair) is not int or pair < 1: + raise ValueError("expected a positive pair number") + if type(position) is not int or position not in (1, 2): + raise ValueError("expected position 1 or 2") + if variant not in ("baseline", "candidate"): + raise ValueError("expected variant baseline or candidate") + if not isinstance(metrics, dict) or not metrics: + raise ValueError("expected a nonempty metrics object") + for name, value in metrics.items(): + if not name or type(value) not in (int, float) or not math.isfinite(value): + raise ValueError(f"invalid numeric metric {name!r}") + + pairs = sessions.setdefault(session, {}) + launches = pairs.setdefault(pair, {}) + if position in launches: + raise ValueError(f"duplicate launch in {session}, pair {pair}, position {position}") + launches[position] = (variant, metrics) + + +def read_sessions(paths): + sessions = {} + for path in paths: + with path.open() as source: + for line_number, line in enumerate(source, 1): + try: + row = json.loads(line) + add_sample(sessions, row) + except ValueError as error: + raise ValueError(f"{path}:{line_number}: {error}") from error + if not sessions: + raise ValueError("no measurements") + return sessions + + +def ordered_pairs(pairs, expected_count): + count = len(pairs) + if expected_count is not None and count != expected_count: + raise ValueError(f"expected {expected_count} pairs, found {count}") + if count < 2 or count % 2 or min(pairs) != 1 or max(pairs) != count: + raise ValueError("expected an even number of consecutive pairs starting at 1") + + previous_first = None + names = None + samples = [] + for number in range(1, count + 1): + launches = pairs[number] + if len(launches) != 2: + raise ValueError(f"pair {number} is incomplete") + first, first_metrics = launches[1] + second, second_metrics = launches[2] + if first == second or first == previous_first: + raise ValueError(f"pair {number} violates the alternating AB/BA order") + previous_first = first + if names is None: + names = first_metrics.keys() + if first_metrics.keys() != names or second_metrics.keys() != names: + raise ValueError(f"pair {number} has inconsistent metric names") + samples.append((first, {first: first_metrics, second: second_metrics})) + return samples + + +def median_interval(blocks, comparisons=1): + # The two tails of Binomial(n, 0.5) determine the order statistics + # that cover the population median at alpha = 0.05 / comparisons. + n = len(blocks) + outcomes = 2 ** n + tail = 0 + rank = 0 + for index in range(n // 2): + tail += math.comb(n, index) + if 40 * comparisons * tail > outcomes: + break + rank += 1 + if rank == 0: + return None + ordered = sorted(blocks) + return ordered[rank - 1], ordered[-rank] + + +def metric_changes(samples, name): + baseline = [arms["baseline"][name] for _, arms in samples] + candidate = [arms["candidate"][name] for _, arms in samples] + relative = min(baseline) > 0 and min(candidate) > 0 + if relative: + changes = [math.log(b) - math.log(a) for a, b in zip(baseline, candidate)] + else: + changes = [b - a for a, b in zip(baseline, candidate)] + return relative, changes + + +def balanced_blocks(changes): + return [(ab + ba) / 2 for ab, ba in zip(changes[::2], changes[1::2])] + + +@dataclass(frozen=True) +class PrecisionPlan: + max_pairs: int = 64 + target_pp: float = 5.0 + equivalence_pp: float = 5.0 + + def __post_init__(self): + if type(self.max_pairs) is not int or self.max_pairs < PLANNED_LOOKS[0] or self.max_pairs % 2: + raise ValueError("maximum pairs must be even and at least 20") + for value in (self.target_pp, self.equivalence_pp): + if type(value) not in (int, float) or not math.isfinite(value) or value <= 0: + raise ValueError("precision and equivalence margins must be finite and positive") + + @property + def looks(self): + return [n for n in PLANNED_LOOKS if n < self.max_pairs] + [self.max_pairs] + + def as_dict(self): + return { + "looks": self.looks, + "maxPairs": self.max_pairs, + "targetPp": self.target_pp, + "equivalencePp": self.equivalence_pp, + "primaryMetrics": list(PRIMARY_METRICS), + "familywiseConfidence": 0.95, + } + + +def compare_margin(value, margin): + # Log and exponential round trips can move an exact boundary by a few ulps. + if math.isclose(abs(value), margin, rel_tol=1e-12): + value = math.copysign(margin, value) + if value > margin: + return 1 + if value < -margin: + return -1 + return 0 + + +def evaluate_samples(samples, plan): + count = len(samples) + if count not in plan.looks: + raise ValueError(f"{count} pairs is outside the planned looks {plan.looks}") + comparisons = len(plan.looks) * len(PRIMARY_METRICS) + results = {} + for name in PRIMARY_METRICS: + if name not in samples[0][1]["baseline"]: + raise ValueError(f"missing primary metric {name}") + relative, changes = metric_changes(samples, name) + if not relative: + raise ValueError(f"relative precision requires strictly positive values for {name}") + blocks = balanced_blocks(changes) + estimate = statistics.median(blocks) + interval = median_interval(blocks, comparisons) + change = 100 * math.expm1(estimate) + low = None + high = None + radius = None + classification = "inconclusive" + if interval is not None: + low = 100 * math.expm1(interval[0]) + high = 100 * math.expm1(interval[1]) + radius = max(change - low, high - change) + low_side = compare_margin(low, plan.equivalence_pp) + high_side = compare_margin(high, plan.equivalence_pp) + if low_side > 0: + classification = "regression" + elif high_side < 0: + classification = "improvement" + elif low_side == 0 and high_side == 0: + classification = "equivalent" + results[name] = { + "changePct": change, "lowerPct": low, "upperPct": high, + "radiusPp": radius, "classification": classification, + } + + precise = all(metric["radiusPp"] is not None and metric["radiusPp"] <= plan.target_pp + for metric in results.values()) + if precise: + reason = "precision_reached" + elif count == plan.max_pairs: + reason = "maximum_reached" + else: + reason = "continue" + return { + **plan.as_dict(), "pairs": count, "blocks": count // 2, + "metrics": results, "stop": reason != "continue", "reason": reason, + } + + +def evaluate_precision(raw_path, plan): + sessions = read_sessions([Path(raw_path)]) + if len(sessions) != 1: + raise ValueError("a precision decision requires exactly one session") + pairs, = sessions.values() + samples = ordered_pairs(pairs, None) + return evaluate_samples(samples, plan) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("raw", type=Path) + parser.add_argument("--target-pp", type=float, default=5.0) + parser.add_argument("--max-pairs", type=int, default=64) + args = parser.parse_args() + try: + plan = PrecisionPlan(max_pairs=args.max_pairs, target_pp=args.target_pp) + decision = evaluate_precision(args.raw, plan) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + print(json.dumps(decision, indent=2, allow_nan=False)) diff --git a/scripts/performance/prepare.py b/scripts/performance/prepare.py index 24e89d461..6061dbdd7 100644 --- a/scripts/performance/prepare.py +++ b/scripts/performance/prepare.py @@ -1,6 +1,7 @@ """Stage the benchmark in an expendable checkout of the revision being measured.""" import argparse +import hashlib import json from pathlib import Path import shutil @@ -28,6 +29,10 @@ val arm = rootProject.file("../.nitro/performance/arm").readText().trim() applicationIdSuffix = ".$arm" } + +dependencies { + releaseImplementation("com.callstack:performance-analytics-android:0.1.0") +} """ @@ -40,6 +45,8 @@ def append_once(path, addition): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("checkout", type=Path) parser.add_argument("arm", choices=("baseline", "candidate")) +parser.add_argument("--workload", type=Path, default=Path(__file__).with_name("workloads.tsx"), + help="Harness workload to embed in both APKs") args = parser.parse_args() app = args.checkout.resolve() / "apps/example" @@ -52,5 +59,34 @@ def append_once(path, addition): stage = app / ".nitro/performance" stage.mkdir(parents=True, exist_ok=True) (stage / "arm").write_text(args.arm + "\n") -source = Path(__file__).resolve().with_name("workloads.tsx") -shutil.copyfile(source, stage / "workloads.android.harness.tsx") +sources = Path(__file__).resolve().parent +benchmark = app / "src/performance" +benchmark.mkdir(parents=True, exist_ok=True) +shutil.copyfile(sources / "entry.tsx", benchmark / "entry.tsx") +workload = benchmark / "workloads.tsx" +shutil.copyfile(args.workload, workload) +digest = hashlib.sha256(workload.read_bytes()).hexdigest() +(benchmark / "provenance.ts").write_text(f"export const fixtureSha256 = '{digest}'\n") +config_path = app / "app.json" +config = json.loads(config_path.read_text()) +config["entry"] = "src/performance/entry.tsx" +config_path.write_text(json.dumps(config, indent=2) + "\n") + +release = app / "android/app/src/release" +kotlin = release / "java/com/margelo/reactnitro/example" +kotlin.mkdir(parents=True, exist_ok=True) +shutil.copyfile(sources / "BenchmarkSnapshot.kt", kotlin / "BenchmarkSnapshot.kt") +xml = release / "res/xml" +xml.mkdir(parents=True, exist_ok=True) +(xml / "benchmark_network.xml").write_text(""" + + 127.0.0.1 + + +""") +(release / "AndroidManifest.xml").write_text(""" + + + + +""") diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 6aa33b393..7d5cc65c9 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -9,10 +9,11 @@ import subprocess from install import install +from precision import PrecisionPlan, evaluate_precision HERE = Path(__file__).resolve().parent -WORKLOAD = Path("apps/example/.nitro/performance/workloads.android.harness.tsx") +WORKLOAD = Path("apps/example/src/performance/workloads.tsx") VARIANTS = ("baseline", "candidate") @@ -40,13 +41,23 @@ 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("--pairs", type=int, default=12) + parser.add_argument("--pairs", type=int, default=64, 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("--fixed", action="store_true", help="Complete every pair for calibration") + parser.add_argument("--candidate-read-passes", type=int, default=128, help="128 for ordinary PR comparisons") parser.add_argument("--first", choices=VARIANTS, default="baseline") parser.add_argument("--output", required=True, type=Path) - parser.add_argument("--control-fixture", type=Path, help="Candidate-only fixture for a labeled positive control") args = parser.parse_args() if args.pairs < 2 or args.pairs % 2: parser.error("--pairs must be a positive even number") + if args.candidate_read_passes <= 0: + parser.error("--candidate-read-passes must be positive") + plan = None + if args.pairs >= 20 or not args.fixed: + try: + plan = PrecisionPlan(max_pairs=args.pairs, target_pp=args.target_pp) + except ValueError as error: + parser.error(str(error)) serial = os.environ["ANDROID_SERIAL"] lease = os.environ["ADC_LEASE_ID"] adb = ["adb", "-s", serial] @@ -54,17 +65,16 @@ def main(): for variant in VARIANTS: root, apk = getattr(args, variant) fixture = root / WORKLOAD - if variant == "candidate" and args.control_fixture is not None: - fixture = args.control_fixture arms[variant] = { "applicationId": f"com.margelo.reactnitro.example.{variant}", "ref": output(["git", "-C", root, "rev-parse", "HEAD"]), "apkSha256": sha256(apk), "fixtureSha256": sha256(fixture), + "readPasses": args.candidate_read_passes if variant == "candidate" else 128, } same_workload = arms["baseline"]["fixtureSha256"] == arms["candidate"]["fixtureSha256"] - if same_workload != (args.control_fixture is None): - parser.error("Ordinary comparisons require identical fixtures, positive controls require different fixtures") + if not same_workload: + parser.error("The baseline and candidate must embed the same workload source") args.output.mkdir(parents=True, exist_ok=False) leases = json.loads(output(["adc", "leases"]))["leases"] @@ -74,7 +84,9 @@ def main(): "started": now(), "lease": lease, "deviceId": device, "properties": {key: output([*adb, "shell", "getprop", key]) for key in props}, "cpusOnline": output([*adb, "shell", "cat", "/sys/devices/system/cpu/online"]), - "pairs": args.pairs, "first": args.first, "positiveControl": args.control_fixture is not None, + "pairs": args.pairs, "first": args.first, "positiveControl": args.candidate_read_passes != 128, + "buildType": "release", "adaptive": not args.fixed, + "precisionPlan": plan.as_dict() if plan else None, "precisionLooks": [], "arms": arms, } write_json(args.output / "session.json", metadata) @@ -95,18 +107,17 @@ def main(): raise ValueError(f"Could not clear {package} before warmup: {cleared}") first = VARIANTS if args.first == "baseline" else VARIANTS[::-1] - with (args.output / "raw.jsonl").open("x") as raw: + raw_path = args.output / "raw.jsonl" + with raw_path.open("x") as raw: for pair in range(args.pairs + 1): # Pair zero warms both arms. Reverse the order for each subsequent pair. order = first if pair % 2 else first[::-1] for position, variant in enumerate(order, start=1): - root, _ = getattr(args, variant) package = arms[variant]["applicationId"] name = f"pair-{pair:02d}-{position}-{variant}" if pair else f"warmup-{variant}" result_file = args.output / f"{name}.json" - command = ["bun", HERE / "launch.ts", root.resolve(), serial, package, result_file.resolve()] - if variant == "candidate" and args.control_fixture is not None: - command.append(args.control_fixture.resolve()) + passes = arms[variant]["readPasses"] + command = ["bun", HERE / "launch.ts", serial, package, result_file.resolve(), str(passes)] started = now() print(f"{started} {name}", flush=True) try: @@ -114,6 +125,8 @@ def main(): finally: subprocess.run([*adb, "shell", "am", "force-stop", package], check=True, timeout=30) result = json.loads(result_file.read_text()) + if result["fixtureSha256"] != arms[variant]["fixtureSha256"] or result["readPasses"] != passes: + raise ValueError(f"{name} ran a different workload from the planned one") if pair: row = { "session": lease, "pair": pair, "position": position, "variant": variant, @@ -121,6 +134,14 @@ def main(): } raw.write(json.dumps(row, allow_nan=False) + "\n") raw.flush() + if plan is not None and pair in plan.looks: + decision = evaluate_precision(raw_path, plan) + metadata["precisionLooks"].append(decision) + write_json(args.output / "session.json", metadata) + print(f"After {pair} pairs: {decision['reason']}", flush=True) + if metadata["adaptive"] and decision["stop"]: + break + metadata["completedPairs"] = pair metadata["finished"] = now() write_json(args.output / "session.json", metadata) diff --git a/scripts/performance/workloads.tsx b/scripts/performance/workloads.tsx index 6e13858ac..359ef2ac9 100644 --- a/scripts/performance/workloads.tsx +++ b/scripts/performance/workloads.tsx @@ -5,8 +5,7 @@ import { Text, View } from 'react-nitro-renderer' const rows = Array.from({ length: 48 }, (_, index) => index) const keys = Array.from({ length: 256 }, (_, index) => `item-${index}`) -const readPasses = 128 -const resultHost = 'http://127.0.0.1:9875' +export const resultHost = 'http://127.0.0.1:9875' function Rows({ revision }: { revision: number }) { return ( @@ -20,42 +19,51 @@ function Rows({ revision }: { revision: number }) { ) } -it('measures MMKV reads and React commits on Android', async () => { - const store = new MMKV({ id: 'adc-performance' }) - for (const [value, key] of keys.entries()) store.set(key, value) - const tree = await render() +export async function post(route: string, message: object) { + const body = JSON.stringify(message) + const response = await fetch(resultHost + route, { method: 'POST', body: body }) + if (!response.ok) throw new Error(`Benchmark host rejected ${route}: ${response.status}`) +} + +export function registerWorkloads(nonce: string, readPasses: number) { + it('measures MMKV reads and React commits on Android', async () => { + const store = new MMKV({ id: 'adc-performance' }) + for (const [value, key] of keys.entries()) store.set(key, value) + const tree = await render() - PerformanceAnalytics.init({ - host: resultHost, - apiKey: 'ps_local_benchmark', - sampleIntervalMs: 60_000, - autoInjectFCP: false, - enableTouchTracking: false, - }) - // The SDK captures its first CPU and memory samples asynchronously upon setup. - await new Promise((resolve) => setTimeout(resolve, 1000)) - const startedAt = Date.now() - const readStart = performance.now() - let checksum = 0 - for (let pass = 0; pass < readPasses; pass++) { - for (const key of keys) { - const value = store.getNumber(key) - if (value === undefined) throw new Error(`Missing MMKV key ${key}`) - checksum += value + PerformanceAnalytics.init({ + host: resultHost, + apiKey: 'ps_local_benchmark', + sampleIntervalMs: 60_000, + autoInjectFCP: false, + enableTouchTracking: false, + }) + const requestedAt = Date.now() + PerformanceAnalytics.flushNow() + await post('/before', { nonce: nonce, requestedAt: requestedAt }) + const startedAt = Date.now() + const readStart = performance.now() + let checksum = 0 + for (let pass = 0; pass < readPasses; pass++) { + for (const key of keys) { + const value = store.getNumber(key) + if (value === undefined) throw new Error(`Missing MMKV key ${key}`) + checksum += value + } } - } - const mmkvReadMs = performance.now() - readStart - const expected = readPasses * keys.length * (keys.length - 1) / 2 - expect(checksum).toBe(expected) + const mmkvReadMs = performance.now() - readStart + const expected = readPasses * keys.length * (keys.length - 1) / 2 + expect(checksum).toBe(expected) - const renderStart = performance.now() - for (let revision = 1; revision <= 12; revision++) { - await tree.rerender() - } - const renderUpdateMs = performance.now() - renderStart - const endedAt = Date.now() - PerformanceAnalytics.flushNow() - const body = JSON.stringify({ startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs }) - const response = await fetch(`${resultHost}/result`, { method: 'POST', body: body }) - expect(response.ok).toBe(true) -}, 60_000) + const renderStart = performance.now() + for (let revision = 1; revision <= 12; revision++) { + await tree.rerender() + } + const renderUpdateMs = performance.now() - renderStart + const endedAt = Date.now() + PerformanceAnalytics.flushNow() + await post('/result', { + nonce: nonce, startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs, + }) + }, 60_000) +} From fbf3a908c1e28598a9cd9d5904d5e65e4252c3cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sun, 29 Nov 2026 20:57:57 +0100 Subject: [PATCH 3/9] test(performance): select the calibrated sustained workload for CI --- .github/workflows/android-performance.yml | 4 ++-- scripts/performance/README.md | 21 +++++++++++++++++---- scripts/performance/launch.ts | 5 ++++- scripts/performance/precision.py | 5 +++-- scripts/performance/run.py | 4 ++-- scripts/performance/workloads.tsx | 7 ++++--- 6 files changed, 32 insertions(+), 14 deletions(-) diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index 1a846d08d..bbe6d9cda 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -14,7 +14,7 @@ on: default: scripts/performance/workloads.tsx pairs: description: Maximum measured pairs on the same device (even, at least 20) - default: '64' + default: '256' required: true precision: description: Required precision for both timing effects in percentage points @@ -34,7 +34,7 @@ jobs: CC: clang CXX: clang++ CMAKE_BUILD_PARALLEL_LEVEL: 2 - PAIRS: ${{ inputs.pairs || '64' }} + PAIRS: ${{ inputs.pairs || '256' }} TARGET_PP: ${{ inputs.precision || '5' }} WORKLOAD: ${{ inputs.workload || 'scripts/performance/workloads.tsx' }} steps: diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 43af4c5f6..228610dd2 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -21,25 +21,38 @@ for arm in baseline candidate; do done bun install --frozen-lockfile --ignore-scripts adc run --purpose ci --form-factor phone --api-level 35 --width 720 --height 1600 --dpi 320 -- \ - python3 scripts/performance/run.py --pairs 64 --target-pp 5 --output ../performance-run \ + python3 scripts/performance/run.py --pairs 256 --target-pp 5 --output ../performance-run \ --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk python3 scripts/performance/analyze.py --session ../performance-run/session.json ../performance-run/raw.jsonl ``` ## Measurements -Both package IDs stay installed on one leased VM. The driver checks the installed APK hashes, clears both packages, warms up each arm and starts a fresh process for every measurement. Each adjacent pair of launches alternates AB, BA. 32,768 MMKV reads and twelve React commits updating 48 rows are timed on the device. React timing ends at commit. Display presentation is a different measurement. +Both package IDs stay installed on one leased VM. The driver checks the installed APK hashes, clears both packages, warms up each arm and starts a fresh process for every measurement. Each adjacent pair of launches alternates AB, BA. The default sustained workload times 262,144 MMKV reads and 96 React commits updating 48 rows on the device. React timing ends at commit. Display presentation is a different measurement. For each launch, the CI host forwards a loopback port with ADB. The app returns a unique launch nonce, the embedded workload digest, the compiled Static Hermes framework ID and the actual read count. A benchmark-only broadcast receiver restricted to Android's DUMP permission reads the SDK's current session through its native API. The host acknowledges SDK CPU snapshots bracketing the workload and saves the final PSS sample. The process CPU delta also includes work between those samples outside the two timed sections. The APK can run with the debuggable flag disabled. During an earlier Debug calibration on macOS, another service answered the shared Harness host's IPv4 request for `/client.js` with HTTP 404. That run ended after 23 of 40 planned launches. The Release prototype binds its CI receiver directly to `127.0.0.1:0` and forwards the port assigned to that open socket. -Set both refs to the same commit for an A/A calibration. For a positive control, add `--candidate-read-passes 141` to increase the candidate's MMKV passes from 128 to 141 (10.15625% more reads) with the same APK and bytecode. Use `--fixed` to collect every planned pair and replay earlier decisions. Keep interrupted series separate and restart a complete campaign on a fresh lease. +Set both refs to the same commit for an A/A calibration. For a positive control, add `--candidate-read-passes 141` to increase the candidate's reads from 262,144 to 288,768 (10.15625% more reads) with the same APK and bytecode. Use `--fixed` to collect every planned pair and replay earlier decisions. Keep interrupted series separate and restart a complete campaign on a fresh lease. ## Precision and stopping -The default maximum is 64 measured pairs, plus one warmup per arm. At 20, 24, 32, 48 and 64 pairs, the runner estimates the change in the two primary timings. Each AB/BA block contributes one average log ratio. The estimate is the median of those blocks, expressed as a percent change. For a higher ceiling, the additional predefined looks are 96, 128, 192 and 256 pairs. An even ceiling of at least 20 includes the preceding looks and the chosen ceiling. The interval calculation uses that entire schedule from the start. +The default maximum is 256 measured pairs, plus one warmup per arm. The runner estimates the two timing changes after 20, 24, 32, 48, 64, 96, 128, 192 and 256 pairs. Each AB/BA block contributes one average log ratio. The estimate is the median of those blocks, expressed as a percent change. An even ceiling of at least 20 includes the preceding looks and the chosen ceiling. The interval calculation uses the entire selected schedule from the start. A two-sided order-statistic interval uses the binomial sign distribution. The total error budget is 5% per lease across the two primary metrics and all planned looks (Bonferroni). The rule assumes independent blocks with a common median effect within the lease. Both endpoints must be within the requested number of percentage points of the estimate for both timings before the run may stop early. At the cap the run reports any remaining uncertainty. Serial correlation, device drift and differences between host days limit transfer of an interval to future leases. [Median confidence limits](https://itl.nist.gov/div898/software/dataplot/refman1/auxillar/mediancl.htm) · [Simultaneous confidence intervals](https://online.stat.psu.edu/stat505/Lesson05) The practical comparison band is ±5%. An interval wholly above +5% signals a regression, wholly below −5% signals an improvement, and wholly inside the band supports practical equivalence. Crossing a boundary leaves that decision open even if the estimate is precise. SDK CPU and PSS are secondary observations. The job publishes the result in the GitHub summary and writes per-launch JSON, SDK data and checkpoint decisions to the private CI bucket. Performance classifications are advisory. Build errors, failed Harness tests and incomplete sessions fail the job. + +## ADC Release calibration + +On November 29, 2026, three A/A comparisons and two MMKV positive controls each completed 64 pairs on separate Android 15 ARM64 ADC VMs. The original workload of 32,768 MMKV reads and twelve React commits took about four minutes of measurement per lease. No calibration run reached joint precision of ±10 percentage points at any planned look. Extending the short A/A series to 256 pairs still left a 12.5-point radius for the less precise metric. + +The default uses eight times as much timed work per launch. Two subsequent adaptive comparisons ran with a 256-pair ceiling and a ±5-point target. One measured identical code, the other added 10.15625% more MMKV operations to the candidate. A pair is two measured app starts. The times below exclude installation and warmup. + +| Sustained workload | First jointly precise look | Measurement time | MMKV change and interval | React change and interval | +|---|---:|---:|---:|---:| +| Identical code | 256 pairs | 16 min 46 s | 0.00% [−4.74%, +4.35%] | +0.30% [−0.84%, +1.37%] | +| Extra MMKV reads | 192 pairs | 12 min 50 s | +7.45% [+2.90%, +12.22%] | −0.86% [−2.35%, +0.58%] | + +React alone first reached the precision target at 48 pairs in both adaptive runs, about 3 min 13 s of measured launches. The positive control's MMKV interval supports a slowdown and overlaps the practical +5% threshold. Hardware scheduling, workload and testing day can change the required pair count. Keep classifications advisory when setting up a new workload. These observations describe throughput across many operations. Use a dedicated short fixture to measure a single interaction. diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts index 7b1f5cf12..e4304716d 100644 --- a/scripts/performance/launch.ts +++ b/scripts/performance/launch.ts @@ -29,7 +29,10 @@ async function adb(...command: string[]) { const stream = new Response(proc.stdout) const contents = await stream.text() const code = await proc.exited - if (code !== 0) throw new Error(`adb ${command.join(' ')} exited with ${code}`) + if (code !== 0) { + const diagnostic = contents.trim().slice(0, 500) + throw new Error(`adb ${command.join(' ')} exited with ${code}: ${diagnostic}`) + } return contents.trim() } diff --git a/scripts/performance/precision.py b/scripts/performance/precision.py index 02082fe6c..9b04a228f 100644 --- a/scripts/performance/precision.py +++ b/scripts/performance/precision.py @@ -10,6 +10,7 @@ PRIMARY_METRICS = ("mmkvReadMs", "renderUpdateMs") PLANNED_LOOKS = (20, 24, 32, 48, 64, 96, 128, 192, 256) +DEFAULT_MAX_PAIRS = 256 def add_sample(sessions, row): @@ -118,7 +119,7 @@ def balanced_blocks(changes): @dataclass(frozen=True) class PrecisionPlan: - max_pairs: int = 64 + max_pairs: int = DEFAULT_MAX_PAIRS target_pp: float = 5.0 equivalence_pp: float = 5.0 @@ -219,7 +220,7 @@ def evaluate_precision(raw_path, plan): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("raw", type=Path) parser.add_argument("--target-pp", type=float, default=5.0) - parser.add_argument("--max-pairs", type=int, default=64) + parser.add_argument("--max-pairs", type=int, default=DEFAULT_MAX_PAIRS) args = parser.parse_args() try: plan = PrecisionPlan(max_pairs=args.max_pairs, target_pp=args.target_pp) diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 7d5cc65c9..3d21cbc22 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -9,7 +9,7 @@ import subprocess from install import install -from precision import PrecisionPlan, evaluate_precision +from precision import DEFAULT_MAX_PAIRS, PrecisionPlan, evaluate_precision HERE = Path(__file__).resolve().parent @@ -41,7 +41,7 @@ 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("--pairs", type=int, default=64, help="Maximum number of measured pairs") + 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("--fixed", action="store_true", help="Complete every pair for calibration") parser.add_argument("--candidate-read-passes", type=int, default=128, help="128 for ordinary PR comparisons") diff --git a/scripts/performance/workloads.tsx b/scripts/performance/workloads.tsx index 359ef2ac9..b6f2c6171 100644 --- a/scripts/performance/workloads.tsx +++ b/scripts/performance/workloads.tsx @@ -42,9 +42,10 @@ export function registerWorkloads(nonce: string, readPasses: number) { PerformanceAnalytics.flushNow() await post('/before', { nonce: nonce, requestedAt: requestedAt }) const startedAt = Date.now() + const totalPasses = readPasses * 8 const readStart = performance.now() let checksum = 0 - for (let pass = 0; pass < readPasses; pass++) { + for (let pass = 0; pass < totalPasses; pass++) { for (const key of keys) { const value = store.getNumber(key) if (value === undefined) throw new Error(`Missing MMKV key ${key}`) @@ -52,11 +53,11 @@ export function registerWorkloads(nonce: string, readPasses: number) { } } const mmkvReadMs = performance.now() - readStart - const expected = readPasses * keys.length * (keys.length - 1) / 2 + const expected = totalPasses * keys.length * (keys.length - 1) / 2 expect(checksum).toBe(expected) const renderStart = performance.now() - for (let revision = 1; revision <= 12; revision++) { + for (let revision = 1; revision <= 96; revision++) { await tree.rerender() } const renderUpdateMs = performance.now() - renderStart From a5703f36f0a2fe615ce2ed04b3a02cb5c88b0dbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 10:22:56 +0100 Subject: [PATCH 4/9] test(performance): package the paired benchmark for physical Device Farm runs --- scripts/performance/README.md | 27 +++++++ scripts/performance/devicefarm/benchmark.py | 77 +++++++++++++++++++ .../performance/devicefarm/requirements.txt | 4 + scripts/performance/devicefarm/study.json | 10 +++ scripts/performance/devicefarm/test-spec.yml | 17 ++++ scripts/performance/pack_devicefarm.py | 71 +++++++++++++++++ scripts/performance/run.py | 77 +++++++++++-------- 7 files changed, 252 insertions(+), 31 deletions(-) create mode 100644 scripts/performance/devicefarm/benchmark.py create mode 100644 scripts/performance/devicefarm/requirements.txt create mode 100644 scripts/performance/devicefarm/study.json create mode 100644 scripts/performance/devicefarm/test-spec.yml create mode 100644 scripts/performance/pack_devicefarm.py diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 228610dd2..7b3fba6d8 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -26,6 +26,33 @@ 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 ``` +## 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. + +```sh +python3 scripts/performance/pack_devicefarm.py \ + --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk \ + --output ../paired-tests.zip +``` + +The package records Git refs, fixture and APK hashes, and the checkpoint schedule from `devicefarm/study.json`. Supply `--study path/to/study.json` to use a different registered calibration. A supplied `apkSHA256` pins both artifacts before packaging. + +Upload the baseline APK as `ANDROID_APP`, `paired-tests.zip` as `APPIUM_PYTHON_TEST_PACKAGE`, and `devicefarm/test-spec.yml` as `APPIUM_PYTHON_TEST_SPEC` in one Oregon Device Farm project. Set the three upload ARNs below after their status is `SUCCEEDED`. Set `PROJECT_ARN` to the project and `DEVICE_ARN` to one physical ARM64 Android handset, preferably Android 15 for comparison with ADC. The following command schedules one job on an existing unmetered Android automated-testing slot. [AWS upload instructions](https://docs.aws.amazon.com/devicefarm/latest/developerguide/how-to-create-test-run.html) · [AWS device slots](https://docs.aws.amazon.com/devicefarm/latest/developerguide/how-to-purchase-device-slots.html) + +```sh +export AWS_REGION=us-west-2 +settings=$(aws devicefarm get-account-settings --output json) && + jq -e '.accountSettings.unmeteredDevices.ANDROID > 0' <<<"$settings" >/dev/null && + aws devicefarm schedule-run --project-arn "$PROJECT_ARN" --app-arn "$APP_ARN" \ + --device-selection-configuration "maxDevices=1,filters=[{attribute=ARN,operator=EQUALS,values=[$DEVICE_ARN]}]" \ + --test "type=APPIUM_PYTHON,testPackageArn=$TEST_PACKAGE_ARN,testSpecArn=$TEST_SPEC_ARN" \ + --configuration billingMethod=UNMETERED \ + --execution-configuration jobTimeoutMinutes=120,videoCapture=false,skipAppResign=true +``` + +Download the job's customer artifacts. Under `performance/`, `device.json` records the AWS job and physical device identity, and `aa.zip` and `control.zip` contain each comparison's raw timings, SDK sessions and report. Each test archives its available files when it exits, including after a failed launch. + ## Measurements Both package IDs stay installed on one leased VM. The driver checks the installed APK hashes, clears both packages, warms up each arm and starts a fresh process for every measurement. Each adjacent pair of launches alternates AB, BA. The default sustained workload times 262,144 MMKV reads and 96 React commits updating 48 rows on the device. React timing ends at commit. Display presentation is a different measurement. diff --git a/scripts/performance/devicefarm/benchmark.py b/scripts/performance/devicefarm/benchmark.py new file mode 100644 index 000000000..89d22481c --- /dev/null +++ b/scripts/performance/devicefarm/benchmark.py @@ -0,0 +1,77 @@ +"""Two independent Release calibrations on the physical Android phone attached to this job.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys + +import pytest + + +PACKAGE = Path(__file__).resolve().parents[1] + + +@pytest.fixture(scope="module") +def device(): + from run import output, write_json + + directory = Path(os.environ["DEVICEFARM_LOG_DIR"]) / "performance" + directory.mkdir() + for filename in ("plan.json", "arms.json"): + shutil.copyfile(PACKAGE / filename, directory / filename) + + # The dedicated test host has one ADB device. AWS also reports a physical device identifier. + serial = output(["adb", "get-serialno"]) + adb = ["adb", "-s", serial] + properties = {} + for key in ("ro.product.cpu.abi", "ro.hardware", "ro.build.fingerprint", "ro.product.model", + "ro.kernel.qemu", "ro.boot.qemu", "ro.product.manufacturer", "ro.build.version.sdk"): + properties[key] = output([*adb, "shell", "getprop", key]) + provider = {} + for key in ("PROJECT_ARN", "RUN_ARN", "JOB_NUMBER", "DEVICE_ARN", "DEVICE_UDID", "DEVICE_NAME", "DEVICE_OS_VERSION"): + provider[key] = os.environ["DEVICEFARM_" + key] + write_json(directory / "device.json", {"aws": provider, "adbSerial": serial, "properties": properties}) + if properties["ro.product.cpu.abi"] != "arm64-v8a": + raise ValueError("The paired Release APKs require arm64-v8a") + if properties["ro.kernel.qemu"] == "1" or properties["ro.boot.qemu"] == "1": + raise ValueError("AWS job attached an emulator") + return serial, provider, directory + + +@pytest.mark.parametrize(("trial_id", "name"), [("A/A", "aa"), ("positive-control", "control")], ids=["aa", "control"]) +def test_release_performance(device, trial_id, name): + from precision import PrecisionPlan + from run import run_experiment, sha256 + + serial, provider, root = device + study = json.loads((PACKAGE / "plan.json").read_text()) + arms = json.loads((PACKAGE / "arms.json").read_text()) + plan = PrecisionPlan(max_pairs=study["maxPairsPerTrial"], target_pp=study["targetRadiusPp"], + equivalence_pp=study["equivalenceBandPp"]) + if plan.looks != study["looks"]: + raise ValueError("Packaged runner and registered precision plan disagree") + if arms["baseline"]["fixtureSha256"] != arms["candidate"]["fixtureSha256"]: + raise ValueError("Arms use different workloads") + trial = next(item for item in study["arms"] if item["trial"] == trial_id) + apks = {} + for arm, description in arms.items(): + apk = PACKAGE / (arm + ".apk") + expected = study["apkSHA256"][arm] + if description["apkSha256"] != expected or sha256(apk) != expected: + raise ValueError(f"{arm} APK differs from the registered artifact") + apks[arm] = apk + description["readPasses"] = trial[arm + "ReadPasses"] + + session = f'{provider["RUN_ARN"]}/job-{provider["JOB_NUMBER"]}/{name}' + directory = root / name + try: + run_experiment(arms, apks, serial=serial, session=session, device=provider["DEVICE_UDID"], directory=directory, + first=trial["first"], max_pairs=plan.max_pairs, adaptive=True, plan=plan, launcher=[PACKAGE / "launch"]) + with (directory / "report.md").open("x") as report: + subprocess.run([sys.executable, PACKAGE / "analyze.py", "--session", directory / "session.json", + directory / "raw.jsonl"], stdout=report, check=True) + finally: + if directory.is_dir(): + shutil.make_archive(str(directory), "zip", root_dir=root, base_dir=name) diff --git a/scripts/performance/devicefarm/requirements.txt b/scripts/performance/devicefarm/requirements.txt new file mode 100644 index 000000000..00d725d6f --- /dev/null +++ b/scripts/performance/devicefarm/requirements.txt @@ -0,0 +1,4 @@ +pytest==8.3.5 +iniconfig==2.3.1 +packaging==26.4 +pluggy==1.7.0 diff --git a/scripts/performance/devicefarm/study.json b/scripts/performance/devicefarm/study.json new file mode 100644 index 000000000..3ec741ed1 --- /dev/null +++ b/scripts/performance/devicefarm/study.json @@ -0,0 +1,10 @@ +{ + "arms": [ + {"trial": "A/A", "first": "candidate", "baselineReadPasses": 128, "candidateReadPasses": 128}, + {"trial": "positive-control", "first": "baseline", "baselineReadPasses": 128, "candidateReadPasses": 141} + ], + "maxPairsPerTrial": 256, + "targetRadiusPp": 5, + "equivalenceBandPp": 5, + "looks": [20, 24, 32, 48, 64, 96, 128, 192, 256] +} diff --git a/scripts/performance/devicefarm/test-spec.yml b/scripts/performance/devicefarm/test-spec.yml new file mode 100644 index 000000000..e7a70824b --- /dev/null +++ b/scripts/performance/devicefarm/test-spec.yml @@ -0,0 +1,17 @@ +version: 0.1 +android_test_host: amazon_linux_2023 + +phases: + install: + commands: + - devicefarm-cli use python 3.12 + - cd "$DEVICEFARM_TEST_PACKAGE_PATH" + - python3 -m venv /tmp/nitro-performance-venv + - /tmp/nitro-performance-venv/bin/python -m pip install --no-index --find-links=wheelhouse -r requirements.txt + - chmod +x launch + test: + commands: + - cd "$DEVICEFARM_TEST_PACKAGE_PATH" + - /tmp/nitro-performance-venv/bin/python -m pytest -s --junitxml="$DEVICEFARM_LOG_DIR/performance-junit.xml" tests/test_performance.py +artifacts: + - $DEVICEFARM_LOG_DIR diff --git a/scripts/performance/pack_devicefarm.py b/scripts/performance/pack_devicefarm.py new file mode 100644 index 000000000..1fc7497f9 --- /dev/null +++ b/scripts/performance/pack_devicefarm.py @@ -0,0 +1,71 @@ +"""Package the Release comparison for an AWS Device Farm Android test host.""" + +import argparse +import json +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +from run import HERE, VARIANTS, describe_apks, write_json + + +DEVICE_FARM = HERE / "devicefarm" + + +def write_archive(stage, destination): + with ZipFile(destination, "x") as archive: + for path in sorted(stage.rglob("*")): + if path.is_file(): + # Stable paths, modes and timestamps keep ZIPs reproducible across build directories. + entry = ZipInfo(path.relative_to(stage).as_posix()) + mode = 0o755 if path.name == "launch" else 0o644 + entry.external_attr = (0o100000 | mode) << 16 + entry.compress_type = ZIP_DEFLATED + with path.open("rb") as source, archive.open(entry, "w") as target: + shutil.copyfileobj(source, target) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for arm in VARIANTS: + parser.add_argument("--" + arm, required=True, nargs=2, type=Path, metavar=("CHECKOUT", "APK")) + parser.add_argument("--study", type=Path, default=DEVICE_FARM / "study.json") + parser.add_argument("--output", type=Path, required=True, help="New test package ZIP") + args = parser.parse_args() + builds = {arm: getattr(args, arm) for arm in VARIANTS} + arms = describe_apks(builds) + if arms["baseline"]["ref"] != arms["candidate"]["ref"]: + parser.error("The A/A calibration requires both APKs at the same Git revision") + plan = json.loads(args.study.read_text()) + hashes = {arm: description["apkSha256"] for arm, description in arms.items()} + if "apkSHA256" in plan and plan["apkSHA256"] != hashes: + parser.error("The APKs differ from the registered study") + plan["apkSHA256"] = hashes + with TemporaryDirectory() as location: + stage = Path(location) + tests = stage / "tests" + tests.mkdir() + shutil.copyfile(DEVICE_FARM / "benchmark.py", tests / "test_performance.py") + requirements = stage / "requirements.txt" + shutil.copyfile(DEVICE_FARM / "requirements.txt", requirements) + write_json(stage / "arms.json", arms) + write_json(stage / "plan.json", plan) + for name in ("run.py", "install.py", "precision.py", "analyze.py"): + shutil.copyfile(HERE / name, stage / name) + for arm, (_, apk) in builds.items(): + shutil.copyfile(apk, stage / (arm + ".apk")) + checkout = HERE.parent.parent + subprocess.run(["bun", "build", "--compile", "--target=bun-linux-x64-baseline", "--no-compile-autoload-dotenv", + "--no-compile-autoload-bunfig", "scripts/performance/launch.ts", "--outfile", stage / "launch"], + cwd=checkout, check=True) + subprocess.run([sys.executable, "-m", "pip", "--disable-pip-version-check", "download", "--no-deps", + "--only-binary=:all:", "--platform", "manylinux2014_x86_64", "--python-version", "3.12", + "--dest", stage / "wheelhouse", "-r", requirements], check=True) + write_archive(stage, args.output) + + +if __name__ == "__main__": + main() diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 3d21cbc22..9069dcf33 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -37,6 +37,23 @@ def write_json(path, value): path.write_text(json.dumps(value, indent=2) + "\n") +def describe_apks(builds): + arms = {} + for variant in VARIANTS: + root, apk = builds[variant] + fixture = root / WORKLOAD + arms[variant] = { + "applicationId": f"com.margelo.reactnitro.example.{variant}", + "ref": output(["git", "-C", root, "rev-parse", "HEAD"]), + "apkSha256": sha256(apk), + "fixtureSha256": sha256(fixture), + } + same_workload = arms["baseline"]["fixtureSha256"] == arms["candidate"]["fixtureSha256"] + if not same_workload: + raise ValueError("The baseline and candidate must embed the same workload source") + return arms + + def main(): parser = argparse.ArgumentParser(description=__doc__) for variant in VARIANTS: @@ -60,39 +77,37 @@ def main(): parser.error(str(error)) serial = os.environ["ANDROID_SERIAL"] lease = os.environ["ADC_LEASE_ID"] - adb = ["adb", "-s", serial] - arms = {} - for variant in VARIANTS: - root, apk = getattr(args, variant) - fixture = root / WORKLOAD - arms[variant] = { - "applicationId": f"com.margelo.reactnitro.example.{variant}", - "ref": output(["git", "-C", root, "rev-parse", "HEAD"]), - "apkSha256": sha256(apk), - "fixtureSha256": sha256(fixture), - "readPasses": args.candidate_read_passes if variant == "candidate" else 128, - } - same_workload = arms["baseline"]["fixtureSha256"] == arms["candidate"]["fixtureSha256"] - if not same_workload: - parser.error("The baseline and candidate must embed the same workload source") - - args.output.mkdir(parents=True, exist_ok=False) + builds = {variant: getattr(args, variant) for variant in VARIANTS} + try: + arms = describe_apks(builds) + except ValueError as error: + parser.error(str(error)) + for variant, arm in arms.items(): + arm["readPasses"] = args.candidate_read_passes if variant == "candidate" else 128 leases = json.loads(output(["adc", "leases"]))["leases"] device = next(item["device_id"] for item in leases if item["id"] == lease) + apks = {variant: apk for variant, (_, apk) in builds.items()} + run_experiment(arms, apks, serial=serial, session=lease, device=device, directory=args.output, first=args.first, + max_pairs=args.pairs, adaptive=not args.fixed, plan=plan, launcher=["bun", HERE / "launch.ts"]) + + +def run_experiment(arms, apks, *, serial, session, device, directory, first, max_pairs, adaptive, plan, launcher): + adb = ["adb", "-s", serial] + directory.mkdir(parents=True, exist_ok=False) props = ("ro.build.fingerprint", "ro.product.cpu.abi", "ro.product.model", "ro.hardware", "ro.build.version.sdk") metadata = { - "started": now(), "lease": lease, "deviceId": device, + "started": now(), "lease": session, "deviceId": device, "properties": {key: output([*adb, "shell", "getprop", key]) for key in props}, "cpusOnline": output([*adb, "shell", "cat", "/sys/devices/system/cpu/online"]), - "pairs": args.pairs, "first": args.first, "positiveControl": args.candidate_read_passes != 128, - "buildType": "release", "adaptive": not args.fixed, + "pairs": max_pairs, "first": first, "positiveControl": arms["candidate"]["readPasses"] != 128, + "buildType": "release", "adaptive": adaptive, "precisionPlan": plan.as_dict() if plan else None, "precisionLooks": [], "arms": arms, } - write_json(args.output / "session.json", metadata) + write_json(directory / "session.json", metadata) for variant in VARIANTS: - _, apk = getattr(args, variant) + apk = apks[variant] install(adb, apk) package = arms[variant]["applicationId"] path = output([*adb, "shell", "pm", "path", package]) @@ -106,18 +121,18 @@ def main(): if cleared != "Success": raise ValueError(f"Could not clear {package} before warmup: {cleared}") - first = VARIANTS if args.first == "baseline" else VARIANTS[::-1] - raw_path = args.output / "raw.jsonl" + first_order = VARIANTS if first == "baseline" else VARIANTS[::-1] + raw_path = directory / "raw.jsonl" with raw_path.open("x") as raw: - for pair in range(args.pairs + 1): + for pair in range(max_pairs + 1): # Pair zero warms both arms. Reverse the order for each subsequent pair. - order = first if pair % 2 else first[::-1] + order = first_order if pair % 2 else first_order[::-1] for position, variant in enumerate(order, start=1): package = arms[variant]["applicationId"] name = f"pair-{pair:02d}-{position}-{variant}" if pair else f"warmup-{variant}" - result_file = args.output / f"{name}.json" + result_file = directory / f"{name}.json" passes = arms[variant]["readPasses"] - command = ["bun", HERE / "launch.ts", serial, package, result_file.resolve(), str(passes)] + command = [*launcher, serial, package, result_file.resolve(), str(passes)] started = now() print(f"{started} {name}", flush=True) try: @@ -129,7 +144,7 @@ def main(): raise ValueError(f"{name} ran a different workload from the planned one") if pair: row = { - "session": lease, "pair": pair, "position": position, "variant": variant, + "session": session, "pair": pair, "position": position, "variant": variant, "started": started, "finished": now(), "metrics": result["metrics"], } raw.write(json.dumps(row, allow_nan=False) + "\n") @@ -137,13 +152,13 @@ def main(): if plan is not None and pair in plan.looks: decision = evaluate_precision(raw_path, plan) metadata["precisionLooks"].append(decision) - write_json(args.output / "session.json", metadata) + write_json(directory / "session.json", metadata) print(f"After {pair} pairs: {decision['reason']}", flush=True) if metadata["adaptive"] and decision["stop"]: break metadata["completedPairs"] = pair metadata["finished"] = now() - write_json(args.output / "session.json", metadata) + write_json(directory / "session.json", metadata) if __name__ == "__main__": From a3e3afe0e145414c5e7fb6ef8e76f417198f9282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 11:08:33 +0100 Subject: [PATCH 5/9] test(performance): verify the release calibration on a physical Galaxy --- scripts/performance/README.md | 13 ++++++++++++- scripts/performance/devicefarm/test-spec.yml | 17 ++++++++--------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 7b3fba6d8..c9cdb0738 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -4,7 +4,7 @@ The workflow builds the example app from the PR base and head. Each APK embeds t ## Running the comparison -Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. The build uses `PERF_MAVEN_USER` and `PERF_MAVEN_TOKEN` with read access to the SDK's GitHub Packages, plus the existing ADC and CI S3 credentials. +Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. Gradle uses `PERF_MAVEN_USER` (GitHub username) and `PERF_MAVEN_TOKEN` (token with package read access) at build time to download `com.callstack:performance-analytics-android:0.1.0` from GitHub Packages. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) The optional `workload` dispatch input selects a repository-relative fixture from the workflow revision for both builds. Locally, pass the same `--workload path/to/workloads.tsx` to both invocations of `prepare.py`. The driver checks the fixture digest on every launch. The default fixture shows the Harness registration and the two timing fields used by the stopping rule. @@ -83,3 +83,14 @@ The default uses eight times as much timed work per launch. Two subsequent adapt | Extra MMKV reads | 192 pairs | 12 min 50 s | +7.45% [+2.90%, +12.22%] | −0.86% [−2.35%, +0.58%] | React alone first reached the precision target at 48 pairs in both adaptive runs, about 3 min 13 s of measured launches. The positive control's MMKV interval supports a slowdown and overlaps the practical +5% threshold. Hardware scheduling, workload and testing day can change the required pair count. Keep classifications advisory when setting up a new workload. These observations describe throughput across many operations. Use a dedicated short fixture to measure a single interaction. + +## Physical Android Release calibration + +On November 30, 2026, one Samsung Galaxy S25 Ultra (Android 15) ran both comparisons with the same APKs, workload and stopping rule as the sustained ADC runs. The times cover measured app launches. Both tests, including installation and warmup, took 2 min 27 s together. The Device Farm run took 5 min 17 s from creation to completion. [AWS Device Farm run](https://us-west-2.console.aws.amazon.com/devicefarm/home?region=us-west-2#/mobile/projects/d2b6a358-e6bb-48fb-9d4a-1a3ccfc727a4/runs/dc479bbc-74e3-4762-96a3-f6bee5c9c04b) + +| Sustained workload | First jointly precise look | Measurement time | MMKV change and interval | React change and interval | +|---|---:|---:|---:|---:| +| Identical code | 32 pairs | 1 min 21 s | +0.16% [−3.76%, +3.89%] | +0.34% [−0.82%, +1.36%] | +| Extra MMKV reads | 20 pairs | 51 s | +9.10% [+7.58%, +13.12%] | +0.36% [−1.80%, +1.71%] | + +On the phone, the positive control's entire MMKV interval cleared the +5% regression threshold. The matched ADC interval crossed that threshold. These observations cover one handset on one day and one run per condition. diff --git a/scripts/performance/devicefarm/test-spec.yml b/scripts/performance/devicefarm/test-spec.yml index e7a70824b..3e63b7830 100644 --- a/scripts/performance/devicefarm/test-spec.yml +++ b/scripts/performance/devicefarm/test-spec.yml @@ -2,16 +2,15 @@ version: 0.1 android_test_host: amazon_linux_2023 phases: - install: - commands: - - devicefarm-cli use python 3.12 - - cd "$DEVICEFARM_TEST_PACKAGE_PATH" - - python3 -m venv /tmp/nitro-performance-venv - - /tmp/nitro-performance-venv/bin/python -m pip install --no-index --find-links=wheelhouse -r requirements.txt - - chmod +x launch test: commands: - - cd "$DEVICEFARM_TEST_PACKAGE_PATH" - - /tmp/nitro-performance-venv/bin/python -m pytest -s --junitxml="$DEVICEFARM_LOG_DIR/performance-junit.xml" tests/test_performance.py + - devicefarm-cli use python 3.12 + - NITRO_BENCH_DIR=$(mktemp -d /tmp/nitro-performance.XXXXXXXX) + - cp -R "$DEVICEFARM_TEST_PACKAGE_PATH/." "$NITRO_BENCH_DIR/package" + - cd "$NITRO_BENCH_DIR/package" + - chmod u+x launch + - python -m pip install --no-index --no-deps --find-links=wheelhouse --target="$NITRO_BENCH_DIR/deps" -r requirements.txt + - export PYTHONPATH="$NITRO_BENCH_DIR/deps${PYTHONPATH:+:$PYTHONPATH}" + - PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -s -p no:cacheprovider --junitxml="$DEVICEFARM_LOG_DIR/performance-junit.xml" tests/test_performance.py artifacts: - $DEVICEFARM_LOG_DIR From 24b5d91b19fec8fda3b1eef113a2d79a210ceb9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 11:10:28 +0100 Subject: [PATCH 6/9] test(performance): measure Android hardware counters in Release workloads --- .github/workflows/android-performance.yml | 27 +++- scripts/performance/README.md | 2 + scripts/performance/launch.ts | 39 +++++- scripts/performance/precision.py | 62 +++++----- scripts/performance/prepare.py | 43 ++++++- scripts/performance/run.py | 9 ++ .../BenchmarkThreadCounters.hpp | 116 ++++++++++++++++++ scripts/performance/thread-counters/README.md | 20 +++ .../thread-counters/analyze_fixed.py | 101 +++++++++++++++ .../thread-counters/instrument.patch | 67 ++++++++++ 10 files changed, 444 insertions(+), 42 deletions(-) create mode 100644 scripts/performance/thread-counters/BenchmarkThreadCounters.hpp create mode 100644 scripts/performance/thread-counters/README.md create mode 100644 scripts/performance/thread-counters/analyze_fixed.py create mode 100644 scripts/performance/thread-counters/instrument.patch diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index bbe6d9cda..78debb4b7 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -12,12 +12,16 @@ on: workload: description: Repository-relative Harness workload to embed in both apps default: scripts/performance/workloads.tsx + thread_counters: + description: Measure hardware counters for the standard fixture at a fixed 64 pairs + type: boolean + default: false pairs: - description: Maximum measured pairs on the same device (even, at least 20) + description: Maximum pairs for adaptive timing (even, at least 20) default: '256' required: true precision: - description: Required precision for both timing effects in percentage points + description: Required precision for adaptive timing in percentage points default: '5' required: true pull_request: @@ -35,6 +39,7 @@ jobs: CXX: clang++ CMAKE_BUILD_PARALLEL_LEVEL: 2 PAIRS: ${{ inputs.pairs || '256' }} + THREAD_COUNTERS: ${{ inputs.thread_counters && 'true' || 'false' }} TARGET_PP: ${{ inputs.precision || '5' }} WORKLOAD: ${{ inputs.workload || 'scripts/performance/workloads.tsx' }} steps: @@ -81,8 +86,12 @@ jobs: PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} run: | (cd experiment && bun install --frozen-lockfile --ignore-scripts) + set -- --workload "experiment/$WORKLOAD" + if [ "$THREAD_COUNTERS" = true ]; then + set -- "$@" --thread-counters + fi for arm in baseline candidate; do - python3 experiment/scripts/performance/prepare.py "$arm" "$arm" --workload "experiment/$WORKLOAD" + python3 experiment/scripts/performance/prepare.py "$arm" "$arm" "$@" (cd "$arm" && bun install && cd apps/example && bun run android --release --build-only --abi arm64-v8a) metadata="$arm/apps/example/.nitro/android/apks/release.json" id=$(jq -er .applicationId "$metadata") @@ -103,12 +112,20 @@ jobs: height: '1600' dpi: '320' command: | - python3 experiment/scripts/performance/run.py --pairs "$PAIRS" --target-pp "$TARGET_PP" \ + set -- --pairs "$PAIRS" --target-pp "$TARGET_PP" + if [ "$THREAD_COUNTERS" = true ]; then + set -- --pairs 64 --fixed + fi + python3 experiment/scripts/performance/run.py "$@" \ --baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results - name: Summarize paired changes run: | - python3 experiment/scripts/performance/analyze.py --session experiment/results/session.json experiment/results/raw.jsonl > experiment/results/report.md + if [ "$THREAD_COUNTERS" = true ]; then + python3 experiment/scripts/performance/thread-counters/analyze_fixed.py --markdown experiment/results > experiment/results/report.md + else + python3 experiment/scripts/performance/analyze.py --session experiment/results/session.json experiment/results/raw.jsonl > experiment/results/report.md + fi cat experiment/results/report.md >> "$GITHUB_STEP_SUMMARY" - name: Save readings and SDK sessions to CI storage diff --git a/scripts/performance/README.md b/scripts/performance/README.md index c9cdb0738..55bce6c67 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -6,6 +6,8 @@ The workflow builds the example app from the PR base and head. Each APK embeds t Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. Gradle uses `PERF_MAVEN_USER` (GitHub username) and `PERF_MAVEN_TOKEN` (token with package read access) at build time to download `com.callstack:performance-analytics-android:0.1.0` from GitHub Packages. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) +The manual `thread_counters` option runs the standard fixture for exactly 64 pairs and reports CPU cycles, retired instructions, thread CPU time and elapsed time for both workloads. The runner checks that each APK contains native libraries for the device ABI before installation. ADC can assign ARM64 or x86_64 for the same phone and API-level request. [Hardware counter setup](thread-counters/README.md) + The optional `workload` dispatch input selects a repository-relative fixture from the workflow revision for both builds. Locally, pass the same `--workload path/to/workloads.tsx` to both invocations of `prepare.py`. The driver checks the fixture digest on every launch. The default fixture shows the Harness registration and the two timing fields used by the stopping rule. For a local run, use expendable baseline and candidate checkouts next to the prototype checkout. Preparation stages the SDK, app entry and benchmark-only Android receiver in each checkout. Set the Maven variables in the build environment and use the same Android toolchain as example CI. diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts index e4304716d..467b06614 100644 --- a/scripts/performance/launch.ts +++ b/scripts/performance/launch.ts @@ -8,9 +8,21 @@ const [serial, applicationId, output, readPasses = 128] = argsSchema.parse(proce const nonce = crypto.randomUUID() const base = z.object({ nonce: z.literal(nonce) }) const beforeSchema = base.extend({ requestedAt: z.number() }) -const timingSchema = base.extend({ +const counterSchema = z.object({ + cycles: z.number().int().positive(), + instructions: z.number().int().positive(), + enabledNs: z.number().int().positive(), + runningNs: z.number().int().positive(), + threadCpuMs: z.number().positive(), + tid: z.number().int().positive(), +}).refine((counter) => counter.runningNs <= counter.enabledNs, 'Invalid PMU scheduling times') +const timingFields = base.extend({ startedAt: z.number(), endedAt: z.number(), mmkvReadMs: z.number().positive(), renderUpdateMs: z.number().positive(), }) +const timingSchema = z.union([ + timingFields.extend({ mmkvCounters: counterSchema, renderCounters: counterSchema }), + timingFields.extend({ mmkvCounters: z.undefined().optional(), renderCounters: z.undefined().optional() }), +]) const errorSchema = z.object({ message: z.string(), stack: z.string() }) const completedSchema = base.extend({ tests: z.array(z.object({ status: z.string(), errors: z.array(errorSchema), path: z.array(z.string()), duration: z.number() })), @@ -69,10 +81,29 @@ function measure(before: Snapshot, after: Snapshot, timings: z.infer 0: + classification = "regression" + elif high_side < 0: + classification = "improvement" + elif low_side == 0 and high_side == 0: + classification = "equivalent" + return { + "changePct": change, "lowerPct": low, "upperPct": high, + "radiusPp": radius, "classification": classification, + } + + def evaluate_samples(samples, plan): count = len(samples) if count not in plan.looks: @@ -163,35 +195,7 @@ def evaluate_samples(samples, plan): comparisons = len(plan.looks) * len(PRIMARY_METRICS) results = {} for name in PRIMARY_METRICS: - if name not in samples[0][1]["baseline"]: - raise ValueError(f"missing primary metric {name}") - relative, changes = metric_changes(samples, name) - if not relative: - raise ValueError(f"relative precision requires strictly positive values for {name}") - blocks = balanced_blocks(changes) - estimate = statistics.median(blocks) - interval = median_interval(blocks, comparisons) - change = 100 * math.expm1(estimate) - low = None - high = None - radius = None - classification = "inconclusive" - if interval is not None: - low = 100 * math.expm1(interval[0]) - high = 100 * math.expm1(interval[1]) - radius = max(change - low, high - change) - low_side = compare_margin(low, plan.equivalence_pp) - high_side = compare_margin(high, plan.equivalence_pp) - if low_side > 0: - classification = "regression" - elif high_side < 0: - classification = "improvement" - elif low_side == 0 and high_side == 0: - classification = "equivalent" - results[name] = { - "changePct": change, "lowerPct": low, "upperPct": high, - "radiusPp": radius, "classification": classification, - } + results[name] = metric_interval(samples, name, comparisons, plan.equivalence_pp) precise = all(metric["radiusPp"] is not None and metric["radiusPp"] <= plan.target_pp for metric in results.values()) diff --git a/scripts/performance/prepare.py b/scripts/performance/prepare.py index 6061dbdd7..61fe0932f 100644 --- a/scripts/performance/prepare.py +++ b/scripts/performance/prepare.py @@ -5,6 +5,7 @@ import json from pathlib import Path import shutil +import subprocess MAVEN_REPOSITORY = """ @@ -42,14 +43,43 @@ def append_once(path, addition): path.write_text(contents + addition) +sources = Path(__file__).resolve().parent +default_workload = sources / "workloads.tsx" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("checkout", type=Path) parser.add_argument("arm", choices=("baseline", "candidate")) -parser.add_argument("--workload", type=Path, default=Path(__file__).with_name("workloads.tsx"), +parser.add_argument("--workload", type=Path, default=default_workload, help="Harness workload to embed in both APKs") +parser.add_argument("--thread-counters", action="store_true", + help="Measure current-thread CPU cycles and instructions in the default Release workload") args = parser.parse_args() -app = args.checkout.resolve() / "apps/example" +checkout = args.checkout.resolve() +app = checkout / "apps/example" +counter_sources = sources / "thread-counters" +cpp = checkout / "packages/react-nitro-runtime/android/src/main/cpp/AndroidRuntime.cpp" +header = cpp.with_name("BenchmarkThreadCounters.hpp") +native_code = cpp.read_text() if cpp.is_file() else "" +has_bindings = header.name in native_code or "react_nitro_benchmark::install(" in native_code +fixture_source = args.workload.read_bytes() +if args.thread_counters: + if fixture_source != default_workload.read_bytes(): + parser.error("--thread-counters requires the standard workloads.tsx with its registered counter boundaries") + if header.exists() and header.read_bytes() != (counter_sources / header.name).read_bytes(): + parser.error("The checkout contains a different counter implementation. Use a fresh disposable checkout.") + cpp_target = cpp.relative_to(checkout).as_posix() + patch = counter_sources / "instrument.patch" + apply_cpp = ["git", "apply", "--include=" + cpp_target] + check = [*apply_cpp, "--check"] + if has_bindings: + check.append("--reverse") + if subprocess.run([*check, patch], cwd=checkout).returncode: + parser.error("The counter bindings do not match this Android runtime. Use a compatible disposable checkout.") +elif has_bindings or header.exists(): + parser.error("The checkout already contains thread counters. Use --thread-counters or a fresh disposable checkout.") +elif b"__nitroStartBenchmarkCounters(" in fixture_source or b"__nitroEndBenchmarkCounters(" in fixture_source: + parser.error("The selected workload uses native counter bindings. Use the standard fixture with --thread-counters.") + package = app / "package.json" manifest = json.loads(package.read_text()) manifest["dependencies"]["@callstack/performance-analytics-react-nitro"] = "0.1.0" @@ -59,12 +89,17 @@ def append_once(path, addition): stage = app / ".nitro/performance" stage.mkdir(parents=True, exist_ok=True) (stage / "arm").write_text(args.arm + "\n") -sources = Path(__file__).resolve().parent benchmark = app / "src/performance" benchmark.mkdir(parents=True, exist_ok=True) shutil.copyfile(sources / "entry.tsx", benchmark / "entry.tsx") workload = benchmark / "workloads.tsx" -shutil.copyfile(args.workload, workload) +workload.write_bytes(fixture_source) +if args.thread_counters: + fixture_target = workload.relative_to(checkout).as_posix() + subprocess.run(["git", "apply", "--include=" + fixture_target, patch], cwd=checkout, check=True) + if not has_bindings: + subprocess.run([*apply_cpp, patch], cwd=checkout, check=True) + shutil.copyfile(counter_sources / header.name, header) digest = hashlib.sha256(workload.read_bytes()).hexdigest() (benchmark / "provenance.ts").write_text(f"export const fixtureSha256 = '{digest}'\n") config_path = app / "app.json" diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 9069dcf33..f47914121 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -7,6 +7,7 @@ from datetime import datetime, timezone from pathlib import Path import subprocess +from zipfile import ZipFile from install import install from precision import DEFAULT_MAX_PAIRS, PrecisionPlan, evaluate_precision @@ -106,6 +107,14 @@ def run_experiment(arms, apks, *, serial, session, device, directory, first, max } write_json(directory / "session.json", metadata) + device_abi = metadata["properties"]["ro.product.cpu.abi"] + for variant, apk in apks.items(): + with ZipFile(apk) as archive: + app_abis = {entry.split("/")[1] for entry in archive.namelist() + if entry.startswith("lib/") and entry.endswith(".so")} + if device_abi not in app_abis: + raise ValueError(f"{variant} provides {sorted(app_abis)}, device {device} has native ABI {device_abi}") + for variant in VARIANTS: apk = apks[variant] install(adb, apk) diff --git a/scripts/performance/thread-counters/BenchmarkThreadCounters.hpp b/scripts/performance/thread-counters/BenchmarkThreadCounters.hpp new file mode 100644 index 000000000..1cdcf9404 --- /dev/null +++ b/scripts/performance/thread-counters/BenchmarkThreadCounters.hpp @@ -0,0 +1,116 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace react_nitro_benchmark { +namespace jsi = facebook::jsi; + +class CounterFile { +public: + CounterFile(uint64_t event, int group) { + perf_event_attr attr{}; + attr.size = sizeof(attr); + attr.type = PERF_TYPE_HARDWARE; + attr.config = event; + attr.disabled = group == -1; + attr.exclude_kernel = 1; + attr.exclude_hv = 1; + attr.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; + _fd = static_cast(syscall(__NR_perf_event_open, &attr, 0, -1, group, PERF_FLAG_FD_CLOEXEC)); + if (_fd < 0) throw std::system_error(errno, std::generic_category(), "perf_event_open"); + } + ~CounterFile() { close(_fd); } + CounterFile(const CounterFile&) = delete; + CounterFile& operator=(const CounterFile&) = delete; + int get() const { return _fd; } +private: + int _fd; +}; + +struct GroupReading { + uint64_t count; + uint64_t enabledNs; + uint64_t runningNs; + uint64_t cycles; + uint64_t instructions; +}; + +inline int64_t threadCpuNs() { + timespec value{}; + if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &value) != 0) { + throw std::system_error(errno, std::generic_category(), "clock_gettime"); + } + return static_cast(value.tv_sec) * 1000000000 + value.tv_nsec; +} + +class CounterWindow { +public: + CounterWindow() + : _thread(gettid()), _leader(PERF_COUNT_HW_CPU_CYCLES, -1), _member(PERF_COUNT_HW_INSTRUCTIONS, _leader.get()) { + _startCpuNs = threadCpuNs(); + if (ioctl(_leader.get(), PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) < 0) { + throw std::system_error(errno, std::generic_category(), "enable counter group"); + } + } + jsi::Object finish(jsi::Runtime& runtime) { + if (gettid() != _thread) throw std::runtime_error("benchmark interval crossed OS threads"); + if (ioctl(_leader.get(), PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) < 0) { + throw std::system_error(errno, std::generic_category(), "disable counter group"); + } + const int64_t cpuNs = threadCpuNs() - _startCpuNs; + GroupReading reading{}; + const auto bytes = read(_leader.get(), &reading, sizeof(reading)); + if (bytes < 0) throw std::system_error(errno, std::generic_category(), "read counter group"); + if (bytes != sizeof(reading) || reading.count != 2 || reading.runningNs == 0 || + reading.runningNs > reading.enabledNs || reading.instructions == 0 || reading.cycles == 0) { + throw std::runtime_error("incomplete PMU group reading"); + } + jsi::Object out(runtime); + out.setProperty(runtime, "cycles", static_cast(reading.cycles)); + out.setProperty(runtime, "instructions", static_cast(reading.instructions)); + out.setProperty(runtime, "enabledNs", static_cast(reading.enabledNs)); + out.setProperty(runtime, "runningNs", static_cast(reading.runningNs)); + out.setProperty(runtime, "threadCpuMs", static_cast(cpuNs) / 1000000.0); + out.setProperty(runtime, "tid", static_cast(_thread)); + return out; + } +private: + pid_t _thread; + CounterFile _leader; + CounterFile _member; + int64_t _startCpuNs; +}; + +inline void install(jsi::Runtime& runtime) { + // Both functions share the window. Overlapping intervals would make attribution ambiguous. + struct State { std::unique_ptr window; }; + auto state = std::make_shared(); + auto startName = jsi::PropNameID::forAscii(runtime, "__nitroStartBenchmarkCounters"); + auto start = jsi::Function::createFromHostFunction(runtime, startName, 0, + [state](jsi::Runtime&, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value { + if (state->window) throw std::runtime_error("overlapping counter windows"); + state->window = std::make_unique(); + return jsi::Value::undefined(); + }); + auto endName = jsi::PropNameID::forAscii(runtime, "__nitroEndBenchmarkCounters"); + auto end = jsi::Function::createFromHostFunction(runtime, endName, 0, + [state](jsi::Runtime& rt, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value { + if (!state->window) throw std::runtime_error("missing counter window"); + auto window = std::move(state->window); + return window->finish(rt); + }); + runtime.global().setProperty(runtime, "__nitroStartBenchmarkCounters", std::move(start)); + runtime.global().setProperty(runtime, "__nitroEndBenchmarkCounters", std::move(end)); +} +} // namespace react_nitro_benchmark diff --git a/scripts/performance/thread-counters/README.md b/scripts/performance/thread-counters/README.md new file mode 100644 index 000000000..39323e7e0 --- /dev/null +++ b/scripts/performance/thread-counters/README.md @@ -0,0 +1,20 @@ +# Current-thread hardware counters + +In GitHub Actions, dispatch **Android performance (ADC)** with the `thread_counters` checkbox enabled. This collects a fixed 64 pairs with the standard MMKV and React fixture on a device with a usable CPU performance monitoring unit. For local builds, stage the same option in both disposable Release checkouts. + +```sh +python3 scripts/performance/prepare.py ../baseline baseline --thread-counters +python3 scripts/performance/prepare.py ../candidate candidate --thread-counters +``` + +Preparation stages two Hermes host functions and brackets each timed section in the embedded Harness fixture. The first opens grouped Linux hardware events for CPU cycles and retired instructions on the calling thread. The second closes the window, verifies the thread identity, and returns both counts, group enabled and running nanoseconds, thread CPU milliseconds and the OS thread ID. Both hardware events count user-space execution on that thread. Kernel and hypervisor execution are excluded. The render interval includes other work on the same thread between the first rerender and the final commit. + +The instrumented app sends `mmkvCounters` and `renderCounters`. The host saves them under `counters.mmkv` and `counters.render` and adds the corresponding cycles, instructions and thread CPU times to `metrics`. Compare `runningNs` with `enabledNs` before interpreting the raw counts. An unsupported event, denied access or unusable reading fails the instrumented measurement. The Android app calls the kernel from its own UID. + +Generate the fixed-horizon report from the directory containing `session.json`, `raw.jsonl` and the individual launch records. + +```sh +python3 scripts/performance/thread-counters/analyze_fixed.py --markdown ../performance-run +``` + +Both arms can be prepared repeatedly in the same mode. For the regular timing fixture after a counter build, use a fresh checkout. The counter fixture and ordinary fixture have distinct digests. diff --git a/scripts/performance/thread-counters/analyze_fixed.py b/scripts/performance/thread-counters/analyze_fixed.py new file mode 100644 index 000000000..c23a51d89 --- /dev/null +++ b/scripts/performance/thread-counters/analyze_fixed.py @@ -0,0 +1,101 @@ +"""Calculate simultaneous intervals for eight thread-counter outcomes at 64 completed pairs.""" + +import argparse +import json +from pathlib import Path +import sys + +performance_dir = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(performance_dir)) +from precision import metric_interval, ordered_pairs, read_sessions + + +PAIRS = 64 +METRICS = ( + "mmkvReadMs", "mmkvThreadCpuMs", "mmkvCycles", "mmkvInstructions", + "renderUpdateMs", "renderThreadCpuMs", "renderCycles", "renderInstructions", +) + + +def verify_counter_windows(folder, pairs): + for number, launches in pairs.items(): + for position, (arm, metrics) in launches.items(): + file = folder / f"pair-{number:02d}-{position}-{arm}.json" + trace = json.loads(file.read_text()) + if metrics != trace["metrics"]: + raise ValueError(f"{file.name}: raw metrics disagree with the launch trace") + for tag in ("mmkv", "render"): + window = trace["counters"][tag] + enabled = window["enabledNs"] + running = window["runningNs"] + if type(enabled) is not int or type(running) is not int or enabled <= 0 or running != enabled: + raise ValueError(f"{file.name}: {tag} needs full PMU coverage, got {running}/{enabled} ns") + for suffix, field in (("Cycles", "cycles"), ("Instructions", "instructions"), ("ThreadCpuMs", "threadCpuMs")): + if metrics[tag + suffix] != window[field]: + raise ValueError(f"{file.name}: {tag} {field} disagrees with the PMU trace") + + +def analyze(folder): + metadata = (folder / "session.json").read_text() + session = json.loads(metadata) + if session.get("adaptive") is not False or session.get("pairs") != PAIRS: + raise ValueError("expected a fixed 64-pair plan") + if not session.get("finished") or session.get("completedPairs") != PAIRS: + raise ValueError("the session did not complete 64 pairs") + raw = folder / "raw.jsonl" + sessions = read_sessions([raw]) + lease = session["lease"] + if set(sessions) != {lease}: + raise ValueError("raw measurements must belong to the recorded lease") + samples = ordered_pairs(sessions[lease], PAIRS) + if samples[0][0] != session["first"]: + raise ValueError("the first measured pair differs from the registered order") + + verify_counter_windows(folder, sessions[lease]) + comparisons = len(METRICS) + metrics = {} + for name in METRICS: + metrics[name] = metric_interval(samples, name, comparisons, 5) + return { + "lease": lease, "pairs": PAIRS, "blocks": PAIRS // 2, + "familywiseConfidence": 0.95, "equivalencePp": 5, "metrics": metrics, + } + + +def markdown(result): + lines = [ + "## Paired Android thread counters", + "", + "| Metric | Candidate change | Simultaneous 95% interval | Decision at ±5% |", + "|---|---:|---:|---|", + ] + for name, metric in result["metrics"].items(): + low = metric["lowerPct"] + high = metric["upperPct"] + change = metric["changePct"] + decision = metric["classification"] + lines.append(f"| {name} | {change:+.2f}% | [{low:+.2f}%, {high:+.2f}%] | {decision} |") + lines.extend([ + "", + "At the fixed 64-pair endpoint, each of 32 AB/BA blocks contributes one mean log ratio. " + "Changes are block medians converted to percent. The exact rank intervals control the " + "5% error budget across eight outcomes on this lease, assuming independent blocks with a common median. " + "All user-mode PMU counts cover the full time the event group was enabled. Positive changes mean larger candidate values.", + ]) + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("folder", type=Path, help="completed run containing the session, raw measurements and per-launch traces") + parser.add_argument("--markdown", action="store_true", help="write a GitHub Markdown table") + args = parser.parse_args() + try: + result = analyze(args.folder) + except (KeyError, TypeError, ValueError, OSError) as error: + parser.exit(1, f"{error}\n") + if args.markdown: + output = markdown(result) + else: + output = json.dumps(result, indent=2, allow_nan=False) + print(output) diff --git a/scripts/performance/thread-counters/instrument.patch b/scripts/performance/thread-counters/instrument.patch new file mode 100644 index 000000000..e0f01f646 --- /dev/null +++ b/scripts/performance/thread-counters/instrument.patch @@ -0,0 +1,67 @@ +--- a/packages/react-nitro-runtime/android/src/main/cpp/AndroidRuntime.cpp ++++ b/packages/react-nitro-runtime/android/src/main/cpp/AndroidRuntime.cpp +@@ -1,4 +1,5 @@ + #include "AndroidRuntime.hpp" ++#include "BenchmarkThreadCounters.hpp" + #include "MappedFileBuffer.hpp" + #include + #include +@@ -24,6 +25,7 @@ + _dispatcher = std::make_shared(*_runtime); + try { + _dispatcher->withJSEntry(*_runtime, [&] { ++ react_nitro_benchmark::install(*_runtime); + layout::installHermesBindings(*_runtime); + install(*_runtime, _dispatcher); + networking::WebSocketRuntime::install(_dispatcher); +--- a/apps/example/src/performance/workloads.tsx ++++ b/apps/example/src/performance/workloads.tsx +@@ -2,6 +2,18 @@ + import { expect, it, render } from 'react-nitro-harness' + import { MMKV } from 'react-nitro-mmkv' + import { Text, View } from 'react-nitro-renderer' ++ ++declare global { ++ function __nitroStartBenchmarkCounters(): void ++ function __nitroEndBenchmarkCounters(): { ++ cycles: number ++ instructions: number ++ enabledNs: number ++ runningNs: number ++ threadCpuMs: number ++ tid: number ++ } ++} + + const rows = Array.from({ length: 48 }, (_, index) => index) + const keys = Array.from({ length: 256 }, (_, index) => `item-${index}`) +@@ -43,6 +55,7 @@ + await post('/before', { nonce: nonce, requestedAt: requestedAt }) + const startedAt = Date.now() + const totalPasses = readPasses * 8 ++ __nitroStartBenchmarkCounters() + const readStart = performance.now() + let checksum = 0 + for (let pass = 0; pass < totalPasses; pass++) { +@@ -53,17 +66,21 @@ + } + } + const mmkvReadMs = performance.now() - readStart ++ const mmkvCounters = __nitroEndBenchmarkCounters() + const expected = totalPasses * keys.length * (keys.length - 1) / 2 + expect(checksum).toBe(expected) + ++ __nitroStartBenchmarkCounters() + const renderStart = performance.now() + for (let revision = 1; revision <= 96; revision++) { + await tree.rerender() + } + const renderUpdateMs = performance.now() - renderStart ++ const renderCounters = __nitroEndBenchmarkCounters() + const endedAt = Date.now() + PerformanceAnalytics.flushNow() + await post('/result', { ++ mmkvCounters: mmkvCounters, renderCounters: renderCounters, + nonce: nonce, startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs, + }) + }, 60_000) From 4174ea49ceec1b9a56e9385e55b3461f1c3164bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 11:18:11 +0100 Subject: [PATCH 7/9] docs(performance): report paired ADC cycle and instruction measurements --- scripts/performance/README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 55bce6c67..f2b4b0fbb 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -96,3 +96,20 @@ On November 30, 2026, one Samsung Galaxy S25 Ultra (Android 15) ran both compari | Extra MMKV reads | 20 pairs | 51 s | +9.10% [+7.58%, +13.12%] | +0.36% [−1.80%, +1.71%] | On the phone, the positive control's entire MMKV interval cleared the +5% regression threshold. The matched ADC interval crossed that threshold. These observations cover one handset on one day and one run per condition. + +## ADC hardware counters in the Release app + +On November 30, 2026, the instrumented fixture ran twice on one native ARM64 Android 15 ADC VM in separate leases. Each comparison ran 64 pairs in alternating order. All 512 measured MMKV and React windows had full hardware-counter coverage. ADC also assigned an x86_64 VM for the same device request. Its native loader failed before the first warmup completed, so that attempt contributed no observations. + +| MMKV metric | Identical code | Candidate doing 10.15625% more reads | +|---|---:|---:| +| Elapsed time | +1.35% [−8.42%, +10.34%] | +8.87% [−2.27%, +23.41%] | +| Thread CPU time | +0.82% [−2.99%, +3.11%] | +10.08% [+5.93%, +16.58%] | +| CPU cycles | +0.25% [−1.39%, +1.28%] | +10.55% [+9.37%, +13.14%] | +| Retired instructions | 0.00% [0.00%, 0.00%] | +10.1561% [+10.1561%, +10.1561%] | + +The intervals account for all eight outcomes at one fixed endpoint per lease. In the A/A trial, all 128 measured launches retired exactly 631,522,940 instructions in the MMKV section. Extra MMKV reads cleared the +5% regression threshold in cycles and thread CPU time. The React workload stayed the same. Its cycle interval was [−4.21%, +3.64%] in A/A and [−3.55%, +1.63%] in the positive control. + +A separate replay checked 20, 24, 32, 48 and 64 pairs, correcting for all eight outcomes and five looks. For both workloads together, instruction counts first reached a five-percentage-point radius after 24 pairs (2 min 14 s in A/A and 2 min 13 s with extra reads). Cycles reached it after 64 pairs (5 min 36 s and 5 min 29 s). Elapsed time and thread CPU time did not reach that joint precision in either series. These times cover measured launches and describe this VM and fixture. + +Instructions quantify executed work. Cycles also reflect stalls and can vary with CPU frequency. Both counters here cover user-space execution on the Hermes thread. Elapsed time to React commit also includes waits and scheduling delays. [Linux performance event definitions](https://man7.org/linux/man-pages/man2/perf_event_open.2.html) From 5ffa5570294e5ea9e7c44cf5948bf379107b496c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 30 Nov 2026 15:28:55 +0100 Subject: [PATCH 8/9] test(performance): use published PerfKit thread benchmarks --- .github/workflows/android-performance.yml | 8 +- scripts/performance/README.md | 4 +- scripts/performance/entry.tsx | 5 +- scripts/performance/launch.ts | 30 +++-- scripts/performance/prepare.py | 43 +------ scripts/performance/run.py | 10 +- .../BenchmarkThreadCounters.hpp | 116 ------------------ scripts/performance/thread-counters/README.md | 20 ++- .../thread-counters/instrument.patch | 67 ---------- scripts/performance/workloads.tsx | 9 +- 10 files changed, 57 insertions(+), 255 deletions(-) delete mode 100644 scripts/performance/thread-counters/BenchmarkThreadCounters.hpp delete mode 100644 scripts/performance/thread-counters/instrument.patch diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index 78debb4b7..4c2a69d25 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -86,12 +86,8 @@ jobs: PERF_MAVEN_TOKEN: ${{ secrets.PERF_MAVEN_TOKEN }} run: | (cd experiment && bun install --frozen-lockfile --ignore-scripts) - set -- --workload "experiment/$WORKLOAD" - if [ "$THREAD_COUNTERS" = true ]; then - set -- "$@" --thread-counters - fi for arm in baseline candidate; do - python3 experiment/scripts/performance/prepare.py "$arm" "$arm" "$@" + python3 experiment/scripts/performance/prepare.py "$arm" "$arm" --workload "experiment/$WORKLOAD" (cd "$arm" && bun install && cd apps/example && bun run android --release --build-only --abi arm64-v8a) metadata="$arm/apps/example/.nitro/android/apks/release.json" id=$(jq -er .applicationId "$metadata") @@ -114,7 +110,7 @@ jobs: command: | set -- --pairs "$PAIRS" --target-pp "$TARGET_PP" if [ "$THREAD_COUNTERS" = true ]; then - set -- --pairs 64 --fixed + set -- --pairs 64 --fixed --thread-counters fi python3 experiment/scripts/performance/run.py "$@" \ --baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results diff --git a/scripts/performance/README.md b/scripts/performance/README.md index f2b4b0fbb..ad62366c9 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -4,7 +4,7 @@ The workflow builds the example app from the PR base and head. Each APK embeds t ## Running the comparison -Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. Gradle uses `PERF_MAVEN_USER` (GitHub username) and `PERF_MAVEN_TOKEN` (token with package read access) at build time to download `com.callstack:performance-analytics-android:0.1.0` from GitHub Packages. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) +Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. Gradle uses `PERF_MAVEN_USER` (GitHub username) and `PERF_MAVEN_TOKEN` (token with package read access) at build time to download `com.callstack:performance-analytics-android:0.2.1` from GitHub Packages. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) The manual `thread_counters` option runs the standard fixture for exactly 64 pairs and reports CPU cycles, retired instructions, thread CPU time and elapsed time for both workloads. The runner checks that each APK contains native libraries for the device ABI before installation. ADC can assign ARM64 or x86_64 for the same phone and API-level request. [Hardware counter setup](thread-counters/README.md) @@ -99,7 +99,7 @@ On the phone, the positive control's entire MMKV interval cleared the +5% regres ## ADC hardware counters in the Release app -On November 30, 2026, the instrumented fixture ran twice on one native ARM64 Android 15 ADC VM in separate leases. Each comparison ran 64 pairs in alternating order. All 512 measured MMKV and React windows had full hardware-counter coverage. ADC also assigned an x86_64 VM for the same device request. Its native loader failed before the first warmup completed, so that attempt contributed no observations. +The original PoC used benchmark-only native bindings for the calibration below. The current harness obtains the same per-thread metrics from PerfKit 0.2.1. On November 30, 2026, the instrumented fixture ran twice on one native ARM64 Android 15 ADC VM in separate leases. Each comparison ran 64 pairs in alternating order. All 512 measured MMKV and React windows had full hardware-counter coverage. ADC also assigned an x86_64 VM for the same device request. Its native loader failed before the first warmup completed, so that attempt contributed no observations. | MMKV metric | Identical code | Candidate doing 10.15625% more reads | |---|---:|---:| diff --git a/scripts/performance/entry.tsx b/scripts/performance/entry.tsx index a6502eb37..bf5184123 100644 --- a/scripts/performance/entry.tsx +++ b/scripts/performance/entry.tsx @@ -13,7 +13,7 @@ import { post, registerWorkloads, resultHost } from './workloads' async function run() { const config = await fetch(`${resultHost}/config`) const text = await config.text() - const [nonce, count] = text.split(' ') + const [nonce, count, mode] = text.split(' ') if (nonce === undefined || count === undefined) throw new Error('Missing benchmark configuration') try { @@ -26,7 +26,8 @@ async function run() { if (!Number.isSafeInteger(readPasses) || readPasses < 1) throw new Error('Invalid MMKV pass count') captureUncaughtErrors() const root = resetCollection() - registerWorkloads(nonce, readPasses) + const register: (nonce: string, passes: number, counters: boolean) => void = registerWorkloads + register(nonce, readPasses, mode === 'counters') finishCollection() const tests: TestResultMessage[] = [] const fileErrors = await execute(root, { diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts index 467b06614..e74f380f5 100644 --- a/scripts/performance/launch.ts +++ b/scripts/performance/launch.ts @@ -2,25 +2,33 @@ import { z } from 'zod' const argsSchema = z.tuple([ z.string(), z.enum(['com.margelo.reactnitro.example.baseline', 'com.margelo.reactnitro.example.candidate']), - z.string(), z.coerce.number().int().positive().optional(), + z.string(), z.coerce.number().int().positive().optional(), z.enum(['timing', 'counters']).optional(), ]) -const [serial, applicationId, output, readPasses = 128] = argsSchema.parse(process.argv.slice(2)) +const [serial, applicationId, output, readPasses = 128, mode = 'timing'] = argsSchema.parse(process.argv.slice(2)) const nonce = crypto.randomUUID() const base = z.object({ nonce: z.literal(nonce) }) const beforeSchema = base.extend({ requestedAt: z.number() }) const counterSchema = z.object({ + name: z.string(), + elapsedMs: z.number().positive(), + countersAvailable: z.literal(true), cycles: z.number().int().positive(), instructions: z.number().int().positive(), - enabledNs: z.number().int().positive(), - runningNs: z.number().int().positive(), + timeEnabledNs: z.number().int().positive(), + timeRunningNs: z.number().int().positive(), threadCpuMs: z.number().positive(), - tid: z.number().int().positive(), -}).refine((counter) => counter.runningNs <= counter.enabledNs, 'Invalid PMU scheduling times') + threadId: z.number().int().positive(), +}).refine((counter) => counter.timeRunningNs <= counter.timeEnabledNs, 'Invalid PMU scheduling times') +// Keep the on-disk representation shared with previously recorded calibration runs. +const recordedWindow = counterSchema.transform((window) => ({ + name: window.name, elapsedMs: window.elapsedMs, tid: window.threadId, threadCpuMs: window.threadCpuMs, + cycles: window.cycles, instructions: window.instructions, enabledNs: window.timeEnabledNs, runningNs: window.timeRunningNs, +})) const timingFields = base.extend({ startedAt: z.number(), endedAt: z.number(), mmkvReadMs: z.number().positive(), renderUpdateMs: z.number().positive(), }) const timingSchema = z.union([ - timingFields.extend({ mmkvCounters: counterSchema, renderCounters: counterSchema }), + timingFields.extend({ mmkvCounters: recordedWindow, renderCounters: recordedWindow }), timingFields.extend({ mmkvCounters: z.undefined().optional(), renderCounters: z.undefined().optional() }), ]) const errorSchema = z.object({ message: z.string(), stack: z.string() }) @@ -91,7 +99,11 @@ function measure(before: Snapshot, after: Snapshot, timings: z.infer -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace react_nitro_benchmark { -namespace jsi = facebook::jsi; - -class CounterFile { -public: - CounterFile(uint64_t event, int group) { - perf_event_attr attr{}; - attr.size = sizeof(attr); - attr.type = PERF_TYPE_HARDWARE; - attr.config = event; - attr.disabled = group == -1; - attr.exclude_kernel = 1; - attr.exclude_hv = 1; - attr.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; - _fd = static_cast(syscall(__NR_perf_event_open, &attr, 0, -1, group, PERF_FLAG_FD_CLOEXEC)); - if (_fd < 0) throw std::system_error(errno, std::generic_category(), "perf_event_open"); - } - ~CounterFile() { close(_fd); } - CounterFile(const CounterFile&) = delete; - CounterFile& operator=(const CounterFile&) = delete; - int get() const { return _fd; } -private: - int _fd; -}; - -struct GroupReading { - uint64_t count; - uint64_t enabledNs; - uint64_t runningNs; - uint64_t cycles; - uint64_t instructions; -}; - -inline int64_t threadCpuNs() { - timespec value{}; - if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &value) != 0) { - throw std::system_error(errno, std::generic_category(), "clock_gettime"); - } - return static_cast(value.tv_sec) * 1000000000 + value.tv_nsec; -} - -class CounterWindow { -public: - CounterWindow() - : _thread(gettid()), _leader(PERF_COUNT_HW_CPU_CYCLES, -1), _member(PERF_COUNT_HW_INSTRUCTIONS, _leader.get()) { - _startCpuNs = threadCpuNs(); - if (ioctl(_leader.get(), PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP) < 0) { - throw std::system_error(errno, std::generic_category(), "enable counter group"); - } - } - jsi::Object finish(jsi::Runtime& runtime) { - if (gettid() != _thread) throw std::runtime_error("benchmark interval crossed OS threads"); - if (ioctl(_leader.get(), PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP) < 0) { - throw std::system_error(errno, std::generic_category(), "disable counter group"); - } - const int64_t cpuNs = threadCpuNs() - _startCpuNs; - GroupReading reading{}; - const auto bytes = read(_leader.get(), &reading, sizeof(reading)); - if (bytes < 0) throw std::system_error(errno, std::generic_category(), "read counter group"); - if (bytes != sizeof(reading) || reading.count != 2 || reading.runningNs == 0 || - reading.runningNs > reading.enabledNs || reading.instructions == 0 || reading.cycles == 0) { - throw std::runtime_error("incomplete PMU group reading"); - } - jsi::Object out(runtime); - out.setProperty(runtime, "cycles", static_cast(reading.cycles)); - out.setProperty(runtime, "instructions", static_cast(reading.instructions)); - out.setProperty(runtime, "enabledNs", static_cast(reading.enabledNs)); - out.setProperty(runtime, "runningNs", static_cast(reading.runningNs)); - out.setProperty(runtime, "threadCpuMs", static_cast(cpuNs) / 1000000.0); - out.setProperty(runtime, "tid", static_cast(_thread)); - return out; - } -private: - pid_t _thread; - CounterFile _leader; - CounterFile _member; - int64_t _startCpuNs; -}; - -inline void install(jsi::Runtime& runtime) { - // Both functions share the window. Overlapping intervals would make attribution ambiguous. - struct State { std::unique_ptr window; }; - auto state = std::make_shared(); - auto startName = jsi::PropNameID::forAscii(runtime, "__nitroStartBenchmarkCounters"); - auto start = jsi::Function::createFromHostFunction(runtime, startName, 0, - [state](jsi::Runtime&, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value { - if (state->window) throw std::runtime_error("overlapping counter windows"); - state->window = std::make_unique(); - return jsi::Value::undefined(); - }); - auto endName = jsi::PropNameID::forAscii(runtime, "__nitroEndBenchmarkCounters"); - auto end = jsi::Function::createFromHostFunction(runtime, endName, 0, - [state](jsi::Runtime& rt, const jsi::Value&, const jsi::Value*, size_t) -> jsi::Value { - if (!state->window) throw std::runtime_error("missing counter window"); - auto window = std::move(state->window); - return window->finish(rt); - }); - runtime.global().setProperty(runtime, "__nitroStartBenchmarkCounters", std::move(start)); - runtime.global().setProperty(runtime, "__nitroEndBenchmarkCounters", std::move(end)); -} -} // namespace react_nitro_benchmark diff --git a/scripts/performance/thread-counters/README.md b/scripts/performance/thread-counters/README.md index 39323e7e0..63a42d017 100644 --- a/scripts/performance/thread-counters/README.md +++ b/scripts/performance/thread-counters/README.md @@ -1,20 +1,18 @@ # Current-thread hardware counters -In GitHub Actions, dispatch **Android performance (ADC)** with the `thread_counters` checkbox enabled. This collects a fixed 64 pairs with the standard MMKV and React fixture on a device with a usable CPU performance monitoring unit. For local builds, stage the same option in both disposable Release checkouts. +Enable `thread_counters` in **Android performance (ADC)** for a fixed 64-pair comparison. The standard Release APKs contain PerfKit 0.2.1. The host requests named MMKV and React windows at launch, so both timing modes use the same signed APKs. -```sh -python3 scripts/performance/prepare.py ../baseline baseline --thread-counters -python3 scripts/performance/prepare.py ../candidate candidate --thread-counters -``` - -Preparation stages two Hermes host functions and brackets each timed section in the embedded Harness fixture. The first opens grouped Linux hardware events for CPU cycles and retired instructions on the calling thread. The second closes the window, verifies the thread identity, and returns both counts, group enabled and running nanoseconds, thread CPU milliseconds and the OS thread ID. Both hardware events count user-space execution on that thread. Kernel and hypervisor execution are excluded. The render interval includes other work on the same thread between the first rerender and the final commit. +The fixture constructs a `ThreadBenchmark` around each workload and calls `end()` on the same thread. On supported Android devices the SDK reports CPU cycles and retired instructions for user-space execution, thread CPU time, elapsed time, OS thread ID and the time the hardware group was enabled and running. React's interval includes other work dispatched to that thread between rerenders. -The instrumented app sends `mmkvCounters` and `renderCounters`. The host saves them under `counters.mmkv` and `counters.render` and adds the corresponding cycles, instructions and thread CPU times to `metrics`. Compare `runningNs` with `enabledNs` before interpreting the raw counts. An unsupported event, denied access or unusable reading fails the instrumented measurement. The Android app calls the kernel from its own UID. - -Generate the fixed-horizon report from the directory containing `session.json`, `raw.jsonl` and the individual launch records. +Stage the APKs with the ordinary Release build instructions, then run the instrumented comparison on the leased device. The analysis requires full hardware-counter coverage in every measured window. ```sh +python3 scripts/performance/run.py --thread-counters --fixed --pairs 64 \ + --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk \ + --output ../performance-run python3 scripts/performance/thread-counters/analyze_fixed.py --markdown ../performance-run ``` -Both arms can be prepared repeatedly in the same mode. For the regular timing fixture after a counter build, use a fresh checkout. The counter fixture and ordinary fixture have distinct digests. +Per-launch records retain the same `counters.mmkv` and `counters.render` fields as the original ADC study. [PerfKit thread benchmarks](https://github.com/callstackincubator/performance-analytics/pull/5) + +With the published 0.2.1 adapter and Android artifact, four positive-control pairs ran on native ARM64 ADC in Release. All 16 measured SDK windows had full hardware-counter coverage. This run checks the integration. The 64-pair calibration in the main README used the earlier prototype. diff --git a/scripts/performance/thread-counters/instrument.patch b/scripts/performance/thread-counters/instrument.patch deleted file mode 100644 index e0f01f646..000000000 --- a/scripts/performance/thread-counters/instrument.patch +++ /dev/null @@ -1,67 +0,0 @@ ---- a/packages/react-nitro-runtime/android/src/main/cpp/AndroidRuntime.cpp -+++ b/packages/react-nitro-runtime/android/src/main/cpp/AndroidRuntime.cpp -@@ -1,4 +1,5 @@ - #include "AndroidRuntime.hpp" -+#include "BenchmarkThreadCounters.hpp" - #include "MappedFileBuffer.hpp" - #include - #include -@@ -24,6 +25,7 @@ - _dispatcher = std::make_shared(*_runtime); - try { - _dispatcher->withJSEntry(*_runtime, [&] { -+ react_nitro_benchmark::install(*_runtime); - layout::installHermesBindings(*_runtime); - install(*_runtime, _dispatcher); - networking::WebSocketRuntime::install(_dispatcher); ---- a/apps/example/src/performance/workloads.tsx -+++ b/apps/example/src/performance/workloads.tsx -@@ -2,6 +2,18 @@ - import { expect, it, render } from 'react-nitro-harness' - import { MMKV } from 'react-nitro-mmkv' - import { Text, View } from 'react-nitro-renderer' -+ -+declare global { -+ function __nitroStartBenchmarkCounters(): void -+ function __nitroEndBenchmarkCounters(): { -+ cycles: number -+ instructions: number -+ enabledNs: number -+ runningNs: number -+ threadCpuMs: number -+ tid: number -+ } -+} - - const rows = Array.from({ length: 48 }, (_, index) => index) - const keys = Array.from({ length: 256 }, (_, index) => `item-${index}`) -@@ -43,6 +55,7 @@ - await post('/before', { nonce: nonce, requestedAt: requestedAt }) - const startedAt = Date.now() - const totalPasses = readPasses * 8 -+ __nitroStartBenchmarkCounters() - const readStart = performance.now() - let checksum = 0 - for (let pass = 0; pass < totalPasses; pass++) { -@@ -53,17 +66,21 @@ - } - } - const mmkvReadMs = performance.now() - readStart -+ const mmkvCounters = __nitroEndBenchmarkCounters() - const expected = totalPasses * keys.length * (keys.length - 1) / 2 - expect(checksum).toBe(expected) - -+ __nitroStartBenchmarkCounters() - const renderStart = performance.now() - for (let revision = 1; revision <= 96; revision++) { - await tree.rerender() - } - const renderUpdateMs = performance.now() - renderStart -+ const renderCounters = __nitroEndBenchmarkCounters() - const endedAt = Date.now() - PerformanceAnalytics.flushNow() - await post('/result', { -+ mmkvCounters: mmkvCounters, renderCounters: renderCounters, - nonce: nonce, startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs, - }) - }, 60_000) diff --git a/scripts/performance/workloads.tsx b/scripts/performance/workloads.tsx index b6f2c6171..8efcbe29a 100644 --- a/scripts/performance/workloads.tsx +++ b/scripts/performance/workloads.tsx @@ -1,4 +1,4 @@ -import { PerformanceAnalytics } from '@callstack/performance-analytics-react-nitro' +import { PerformanceAnalytics, ThreadBenchmark } from '@callstack/performance-analytics-react-nitro' import { expect, it, render } from 'react-nitro-harness' import { MMKV } from 'react-nitro-mmkv' import { Text, View } from 'react-nitro-renderer' @@ -25,7 +25,7 @@ export async function post(route: string, message: object) { if (!response.ok) throw new Error(`Benchmark host rejected ${route}: ${response.status}`) } -export function registerWorkloads(nonce: string, readPasses: number) { +export function registerWorkloads(nonce: string, readPasses: number, collectCounters: boolean) { it('measures MMKV reads and React commits on Android', async () => { const store = new MMKV({ id: 'adc-performance' }) for (const [value, key] of keys.entries()) store.set(key, value) @@ -43,6 +43,7 @@ export function registerWorkloads(nonce: string, readPasses: number) { await post('/before', { nonce: nonce, requestedAt: requestedAt }) const startedAt = Date.now() const totalPasses = readPasses * 8 + const mmkvWindow = collectCounters ? new ThreadBenchmark('mmkv') : undefined const readStart = performance.now() let checksum = 0 for (let pass = 0; pass < totalPasses; pass++) { @@ -53,17 +54,21 @@ export function registerWorkloads(nonce: string, readPasses: number) { } } const mmkvReadMs = performance.now() - readStart + const mmkvCounters = mmkvWindow?.end() const expected = totalPasses * keys.length * (keys.length - 1) / 2 expect(checksum).toBe(expected) + const renderWindow = collectCounters ? new ThreadBenchmark('render') : undefined const renderStart = performance.now() for (let revision = 1; revision <= 96; revision++) { await tree.rerender() } const renderUpdateMs = performance.now() - renderStart + const renderCounters = renderWindow?.end() const endedAt = Date.now() PerformanceAnalytics.flushNow() await post('/result', { + mmkvCounters: mmkvCounters, renderCounters: renderCounters, nonce: nonce, startedAt: startedAt, endedAt: endedAt, mmkvReadMs: mmkvReadMs, renderUpdateMs: renderUpdateMs, }) }, 60_000) From d838585648b8c317d7db4e0f827dc26dcdd0f53a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Thu, 3 Dec 2026 16:33:23 +0100 Subject: [PATCH 9/9] ci(performance): read PerfKit packages with the build job token --- .github/workflows/android-performance.yml | 10 ++++++---- scripts/performance/README.md | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index 4c2a69d25..c3d69773e 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -26,11 +26,13 @@ on: required: true pull_request: -permissions: - contents: read +permissions: {} jobs: compare: + permissions: + contents: read + packages: read if: github.event_name == 'workflow_dispatch' || (vars.ENABLE_ANDROID_PERFORMANCE == 'true' && github.event.pull_request.head.repo.full_name == github.repository) runs-on: [self-hosted, linux, X64, hetzner-cx23] timeout-minutes: 240 @@ -82,8 +84,8 @@ jobs: - name: Build the Release benchmark APK from each revision 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: | (cd experiment && bun install --frozen-lockfile --ignore-scripts) for arm in baseline candidate; do diff --git a/scripts/performance/README.md b/scripts/performance/README.md index ad62366c9..a383de138 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -4,13 +4,13 @@ The workflow builds the example app from the PR base and head. Each APK embeds t ## Running the comparison -Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. Gradle uses `PERF_MAVEN_USER` (GitHub username) and `PERF_MAVEN_TOKEN` (token with package read access) at build time to download `com.callstack:performance-analytics-android:0.2.1` from GitHub Packages. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) +Enable `ENABLE_ANDROID_PERFORMANCE=true` for same-repository PRs. A manual workflow dispatch accepts two Git refs, a maximum pair count and a precision target. The npm SDK depends on `com.callstack:performance-analytics-android:0.2.1`. Gradle downloads it from GitHub Packages using the build job’s automatic `GITHUB_TOKEN` with `packages: read`. ADC uses its own device credential and the CI runner uses its S3 credentials to upload results. [GitHub Packages authentication](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry) The manual `thread_counters` option runs the standard fixture for exactly 64 pairs and reports CPU cycles, retired instructions, thread CPU time and elapsed time for both workloads. The runner checks that each APK contains native libraries for the device ABI before installation. ADC can assign ARM64 or x86_64 for the same phone and API-level request. [Hardware counter setup](thread-counters/README.md) The optional `workload` dispatch input selects a repository-relative fixture from the workflow revision for both builds. Locally, pass the same `--workload path/to/workloads.tsx` to both invocations of `prepare.py`. The driver checks the fixture digest on every launch. The default fixture shows the Harness registration and the two timing fields used by the stopping rule. -For a local run, use expendable baseline and candidate checkouts next to the prototype checkout. Preparation stages the SDK, app entry and benchmark-only Android receiver in each checkout. Set the Maven variables in the build environment and use the same Android toolchain as example CI. +For a local run, use expendable baseline and candidate checkouts next to the prototype checkout. Preparation stages the SDK, app entry and benchmark-only Android receiver in each checkout. Set `PERF_MAVEN_USER` to your GitHub username and `PERF_MAVEN_TOKEN` to a classic personal access token with `read:packages` for the local Gradle build. Use the same Android toolchain as example CI. ```sh for arm in baseline candidate; do