diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml
new file mode 100644
index 000000000..c3d69773e
--- /dev/null
+++ b/.github/workflows/android-performance.yml
@@ -0,0 +1,140 @@
+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)
+ 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 pairs for adaptive timing (even, at least 20)
+ default: '256'
+ required: true
+ precision:
+ description: Required precision for adaptive timing in percentage points
+ default: '5'
+ required: true
+ pull_request:
+
+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
+ env:
+ CC: clang
+ 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:
+ - 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 Release benchmark APK from each revision
+ env:
+ 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
+ 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
+
+ - 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: |
+ set -- --pairs "$PAIRS" --target-pp "$TARGET_PP"
+ if [ "$THREAD_COUNTERS" = true ]; then
+ set -- --pairs 64 --fixed --thread-counters
+ fi
+ python3 experiment/scripts/performance/run.py "$@" \
+ --baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results
+
+ - name: Summarize paired changes
+ run: |
+ 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
+ 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/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
new file mode 100644
index 000000000..a383de138
--- /dev/null
+++ b/scripts/performance/README.md
@@ -0,0 +1,115 @@
+# Paired Release benchmarks on ADC
+
+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.
+
+## 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 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 `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
+ 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 --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 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
+```
+
+## 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.
+
+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 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 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.
+
+## 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.
+
+## ADC hardware counters in the Release app
+
+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 |
+|---|---:|---:|
+| 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)
diff --git a/scripts/performance/analyze.py b/scripts/performance/analyze.py
new file mode 100644
index 000000000..6eb66cd3f
--- /dev/null
+++ b/scripts/performance/analyze.py
@@ -0,0 +1,174 @@
+"""Summarize interleaved Android performance measurements as GitHub Markdown."""
+
+import argparse
+import json
+import math
+import statistics
+from pathlib import Path
+
+from precision import (
+ PrecisionPlan, balanced_blocks, evaluate_samples, median_interval,
+ metric_changes, ordered_pairs, read_sessions,
+)
+
+
+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, decision):
+ baseline = [arms["baseline"][name] for _, arms in samples]
+ candidate = [arms["candidate"][name] for _, arms in samples]
+ relative, changes = metric_changes(samples, name)
+ by_order = {"baseline": [], "candidate": []}
+ for (first, _), change in zip(samples, changes):
+ 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 = balanced_blocks(changes)
+ estimate = statistics.median(blocks)
+ bounds = "n/a"
+ 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"])
+ 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, 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 | " + interval_label + " "
+ "| Pair P10 to P90 | AB / BA medians |",
+ "|---|---:|---:|---:|---:|---:|---:|",
+ ])
+ _, first = samples[0]
+ for name in sorted(first["baseline"]):
+ 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 "
+ "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. "
+ "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)
+ 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/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..3e63b7830
--- /dev/null
+++ b/scripts/performance/devicefarm/test-spec.yml
@@ -0,0 +1,16 @@
+version: 0.1
+android_test_host: amazon_linux_2023
+
+phases:
+ test:
+ commands:
+ - 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
diff --git a/scripts/performance/entry.tsx b/scripts/performance/entry.tsx
new file mode 100644
index 000000000..bf5184123
--- /dev/null
+++ b/scripts/performance/entry.tsx
@@ -0,0 +1,68 @@
+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, mode] = 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()
+ const register: (nonce: string, passes: number, counters: boolean) => void = registerWorkloads
+ register(nonce, readPasses, mode === 'counters')
+ 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/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..e74f380f5
--- /dev/null
+++ b/scripts/performance/launch.ts
@@ -0,0 +1,186 @@
+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.enum(['timing', 'counters']).optional(),
+])
+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(),
+ timeEnabledNs: z.number().int().positive(),
+ timeRunningNs: z.number().int().positive(),
+ threadCpuMs: z.number().positive(),
+ 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: recordedWindow, renderCounters: recordedWindow }),
+ 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() })),
+ 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()) })),
+})
+
+async function adb(...command: string[]) {
+ const proc = Bun.spawn(['adb', '-s', serial, ...command], { stdout: 'pipe', stderr: 'inherit' })
+ const stream = new Response(proc.stdout)
+ const contents = await stream.text()
+ const code = await proc.exited
+ if (code !== 0) {
+ const diagnostic = contents.trim().slice(0, 500)
+ throw new Error(`adb ${command.join(' ')} exited with ${code}: ${diagnostic}`)
+ }
+ return contents.trim()
+}
+
+async function snapshotAtOrAfter(timestamp: number) {
+ const receiver = `${applicationId}/com.margelo.reactnitro.example.BenchmarkSnapshot`
+ const deadline = performance.now() + 15_000
+ while (performance.now() < deadline) {
+ 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('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')
+ const mmkv = timings.mmkvCounters
+ const render = timings.renderCounters
+ const metrics = {
+ mmkvReadMs: timings.mmkvReadMs,
+ renderUpdateMs: timings.renderUpdateMs,
+ processCpuMs: processCpuMs,
+ processPssBytes: processPssBytes,
+ }
+ const window = { startedAt: timings.startedAt, endedAt: timings.endedAt, sdkStartedAt: before.cpu.timestamp, sdkEndedAt: after.cpu.timestamp }
+ const readings = { metrics: metrics, window: window, sdk: after.sdk }
+ if (mmkv === undefined || render === undefined) {
+ if (mode === 'counters') throw new Error('The selected fixture did not return PerfKit thread counters')
+ return readings
+ }
+ if (mmkv.name !== 'mmkv' || render.name !== 'render') throw new Error('Unexpected PerfKit window names')
+ return {
+ ...readings,
+ counters: { mmkv: mmkv, render: render },
+ metrics: {
+ ...metrics,
+ mmkvCycles: mmkv.cycles,
+ mmkvInstructions: mmkv.instructions,
+ mmkvThreadCpuMs: mmkv.threadCpuMs,
+ renderCycles: render.cycles,
+ renderInstructions: render.instructions,
+ renderThreadCpuMs: render.threadCpuMs,
+ },
+ }
+}
+
+let before: Snapshot | undefined
+let readings: ReturnType | undefined
+const completion = Promise.withResolvers | Error>()
+const receiver = Bun.serve({
+ 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} ${mode}`)
+ if (request.method !== 'POST') return new Response(null, { status: 405 })
+ if (url.pathname === '/api/v1/sessions') return new Response(null, { status: 201 })
+ 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 })
+ }
+ },
+})
+
+const devicePort = 'tcp:9875'
+const deadline = setTimeout(() => completion.resolve(new Error('Release benchmark timed out')), 120_000)
+try {
+ 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 {
+ clearTimeout(deadline)
+ await receiver.stop()
+ await adb('reverse', '--remove', devicePort)
+}
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/precision.py b/scripts/performance/precision.py
new file mode 100644
index 000000000..c7714dd21
--- /dev/null
+++ b/scripts/performance/precision.py
@@ -0,0 +1,234 @@
+"""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)
+DEFAULT_MAX_PAIRS = 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 = DEFAULT_MAX_PAIRS
+ 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 metric_interval(samples, name, comparisons, equivalence_pp):
+ 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, equivalence_pp)
+ high_side = compare_margin(high, equivalence_pp)
+ if low_side > 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:
+ 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:
+ 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())
+ 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=DEFAULT_MAX_PAIRS)
+ 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
new file mode 100644
index 000000000..f7eb30e48
--- /dev/null
+++ b/scripts/performance/prepare.py
@@ -0,0 +1,96 @@
+"""Stage the benchmark in an expendable checkout of the revision being measured."""
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import shutil
+
+
+SDK_VERSION = "0.2.1"
+
+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"
+}
+
+dependencies {
+ releaseImplementation("com.callstack:performance-analytics-android:SDK_VERSION")
+}
+"""
+
+
+def append_once(path, addition):
+ contents = path.read_text()
+ if addition not in contents:
+ 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=default_workload,
+ help="Harness workload to embed in both APKs")
+args = parser.parse_args()
+
+checkout = args.checkout.resolve()
+app = checkout / "apps/example"
+package = app / "package.json"
+manifest = json.loads(package.read_text())
+manifest["dependencies"]["@callstack/performance-analytics-react-nitro"] = SDK_VERSION
+package.write_text(json.dumps(manifest, indent=2) + "\n")
+append_once(app / "android/settings.gradle.kts", MAVEN_REPOSITORY)
+append_once(app / "android/app/build.gradle.kts", APP_ID.replace("SDK_VERSION", SDK_VERSION))
+stage = app / ".nitro/performance"
+stage.mkdir(parents=True, exist_ok=True)
+(stage / "arm").write_text(args.arm + "\n")
+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
new file mode 100644
index 000000000..3cc5c6b00
--- /dev/null
+++ b/scripts/performance/run.py
@@ -0,0 +1,178 @@
+"""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 zipfile import ZipFile
+
+from install import install
+from precision import DEFAULT_MAX_PAIRS, PrecisionPlan, evaluate_precision
+
+
+HERE = Path(__file__).resolve().parent
+WORKLOAD = Path("apps/example/src/performance/workloads.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 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:
+ parser.add_argument(f"--{variant}", required=True, nargs=2, type=Path, metavar=("CHECKOUT", "APK"))
+ parser.add_argument("--pairs", type=int, default=DEFAULT_MAX_PAIRS, help="Maximum number of measured pairs")
+ parser.add_argument("--target-pp", type=float, default=5.0, help="Precision target in percentage points")
+ parser.add_argument("--thread-counters", action="store_true", help="Open PerfKit thread windows in each workload")
+ 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)
+ 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"]
+ 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"],
+ thread_counters=args.thread_counters)
+
+
+def run_experiment(arms, apks, *, serial, session, device, directory, first, max_pairs, adaptive, plan, launcher, thread_counters=False):
+ 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": 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": max_pairs, "first": first, "positiveControl": arms["candidate"]["readPasses"] != 128,
+ "buildType": "release", "adaptive": adaptive, "threadCounters": thread_counters,
+ "precisionPlan": plan.as_dict() if plan else None, "precisionLooks": [],
+ "arms": arms,
+ }
+ 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)
+ 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_order = VARIANTS if first == "baseline" else VARIANTS[::-1]
+ raw_path = directory / "raw.jsonl"
+ with raw_path.open("x") as raw:
+ for pair in range(max_pairs + 1):
+ # Pair zero warms both arms. Reverse the order for each subsequent pair.
+ 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 = directory / f"{name}.json"
+ passes = arms[variant]["readPasses"]
+ command = [*launcher, serial, package, result_file.resolve(), str(passes)]
+ if thread_counters:
+ command.append("counters")
+ 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 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": session, "pair": pair, "position": position, "variant": variant,
+ "started": started, "finished": now(), "metrics": result["metrics"],
+ }
+ 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(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(directory / "session.json", metadata)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/performance/thread-counters/README.md b/scripts/performance/thread-counters/README.md
new file mode 100644
index 000000000..63a42d017
--- /dev/null
+++ b/scripts/performance/thread-counters/README.md
@@ -0,0 +1,18 @@
+# Current-thread hardware counters
+
+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.
+
+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.
+
+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
+```
+
+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/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/workloads.tsx b/scripts/performance/workloads.tsx
new file mode 100644
index 000000000..8efcbe29a
--- /dev/null
+++ b/scripts/performance/workloads.tsx
@@ -0,0 +1,75 @@
+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'
+
+const rows = Array.from({ length: 48 }, (_, index) => index)
+const keys = Array.from({ length: 256 }, (_, index) => `item-${index}`)
+export const resultHost = 'http://127.0.0.1:9875'
+
+function Rows({ revision }: { revision: number }) {
+ return (
+
+ {rows.map((row) => (
+
+ {`Row ${row}, revision ${revision}`}
+
+ ))}
+
+ )
+}
+
+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, 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)
+ const tree = await render()
+
+ 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 totalPasses = readPasses * 8
+ const mmkvWindow = collectCounters ? new ThreadBenchmark('mmkv') : undefined
+ const readStart = performance.now()
+ let checksum = 0
+ 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}`)
+ checksum += value
+ }
+ }
+ 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)
+}