diff --git a/.github/workflows/android-performance.yml b/.github/workflows/android-performance.yml index c3d69773e..110ed172a 100644 --- a/.github/workflows/android-performance.yml +++ b/.github/workflows/android-performance.yml @@ -12,6 +12,10 @@ on: workload: description: Repository-relative Harness workload to embed in both apps default: scripts/performance/workloads.tsx + renderer_suite: + description: Run MMKV, mount, update, text input and scroll with a fixed endpoint + type: boolean + default: false thread_counters: description: Measure hardware counters for the standard fixture at a fixed 64 pairs type: boolean @@ -41,6 +45,7 @@ jobs: CXX: clang++ CMAKE_BUILD_PARALLEL_LEVEL: 2 PAIRS: ${{ inputs.pairs || '256' }} + RENDERER_SUITE: ${{ (github.event_name == 'pull_request' || inputs.renderer_suite) && 'true' || 'false' }} THREAD_COUNTERS: ${{ inputs.thread_counters && 'true' || 'false' }} TARGET_PP: ${{ inputs.precision || '5' }} WORKLOAD: ${{ inputs.workload || 'scripts/performance/workloads.tsx' }} @@ -111,7 +116,9 @@ jobs: dpi: '320' command: | set -- --pairs "$PAIRS" --target-pp "$TARGET_PP" - if [ "$THREAD_COUNTERS" = true ]; then + if [ "$RENDERER_SUITE" = true ]; then + set -- --pairs 64 --fixed --suite + elif [ "$THREAD_COUNTERS" = true ]; then set -- --pairs 64 --fixed --thread-counters fi python3 experiment/scripts/performance/run.py "$@" \ @@ -119,12 +126,16 @@ jobs: - name: Summarize paired changes run: | - if [ "$THREAD_COUNTERS" = true ]; then + outcome=0 + if [ "$RENDERER_SUITE" = true ]; then + python3 experiment/scripts/performance/scenarios/report.py --markdown --require-non-regression experiment/results > experiment/results/report.md || outcome=$? + elif [ "$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" + exit "$outcome" - name: Save readings and SDK sessions to CI storage if: ${{ !cancelled() && hashFiles('experiment/results/session.json') != '' }} diff --git a/.github/workflows/fork-performance.yml b/.github/workflows/fork-performance.yml index 2d20b8eb6..d586c0218 100644 --- a/.github/workflows/fork-performance.yml +++ b/.github/workflows/fork-performance.yml @@ -116,6 +116,8 @@ jobs: printf '%s\n' "$GITHUB_RUN_ATTEMPT" | aws s3 cp - "$AUTH_STORAGE_URI/$ARM.attempt" --only-show-errors compare: + outputs: + verdict: ${{ steps.report.outputs.verdict }} needs: [authorize, build] permissions: contents: read @@ -148,6 +150,7 @@ jobs: - name: Install trusted driver dependencies run: | bun install --frozen-lockfile --ignore-scripts + python3 -I scripts/performance/prepare.py "$PWD" baseline echo "$ANDROID_HOME/platform-tools" >> "$GITHUB_PATH" - uses: margelo/adc@09956980c08fe6790198c721fc0a9da500778407 # v0.5.1 with: @@ -162,14 +165,18 @@ jobs: marker=$(cat /proc/sys/kernel/random/uuid) printf '::stop-commands::%s\n' "$marker" trap 'printf "::%s::\n" "$marker"' EXIT - python3 scripts/performance/run.py --staged-fixture scripts/performance/workloads.tsx \ + python3 scripts/performance/run.py --staged-fixture apps/example/src/performance/workloads.tsx \ --baseline "$BASE_SHA" apks/baseline.apk --candidate "$HEAD_SHA" apks/candidate.apk \ - --pairs 64 --fixed --thread-counters --output results + --pairs 64 --fixed --suite --output results - name: Report the paired changes + id: report run: | printf 'Base %s · candidate %s\n\n' "$BASE_SHA" "$HEAD_SHA" >> "$GITHUB_STEP_SUMMARY" - python3 scripts/performance/thread-counters/analyze_fixed.py --markdown results > results/report.md + outcome=0 + python3 scripts/performance/scenarios/report.py --markdown --require-non-regression results > results/report.md || outcome=$? + echo "verdict=$outcome" >> "$GITHUB_OUTPUT" cat results/report.md >> "$GITHUB_STEP_SUMMARY" + exit "$outcome" - name: Upload benchmark readings to CI storage if: ${{ !cancelled() && steps.apks.outcome == 'success' && hashFiles('results/session.json') != '' }} env: *ci-storage @@ -195,19 +202,27 @@ jobs: HEAD_SHA: ${{ needs.authorize.outputs.head }} PR_NUMBER: ${{ github.event.issue.number }} OUTCOME: ${{ needs.compare.result }} + VERDICT: ${{ needs.compare.outputs.verdict }} run: | - state=failure + state=error description='Build or ADC measurements did not finish successfully' - if [ "$OUTCOME" = success ]; then - pull=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") - if jq -e --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \ - '.state == "open" and .base.sha == $base and .head.sha == $head' <<< "$pull" >/dev/null; then - state=success - description='Measurements complete; see intervals in the run summary' - else - state=error - description='PR revisions changed; review and request a new check' - fi + pull=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") + if jq -e --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \ + '.state == "open" and .base.sha == $base and .head.sha == $head' <<< "$pull" >/dev/null; then + case "$OUTCOME/$VERDICT" in + success/0) + state=success + description='All primary metrics are within their regression limits' + ;; + failure/2) + state=failure + description='A primary metric exceeded its regression limit' + ;; + failure/3) description='Incomplete frame or hardware-counter coverage' ;; + failure/4) description='Needs review. A meaningful regression is still possible' ;; + esac + else + description='PR revisions changed. Review and request a new check' fi gh api --silent "repos/$GITHUB_REPOSITORY/statuses/$HEAD_SHA" -f state="$state" \ -f context='ADC /check' -f description="$description" \ diff --git a/AGENTS.md b/AGENTS.md index ab4711467..46fba06fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,8 @@ - Workarounds for upstream bugs must have an upstream issue report, ideally also a PR fixing the issue. Add a nearby `// TODO:` comment linking the issue and any fix PR, and stating when to remove the workaround after the fix is released. For Swift compiler or Swift/C++ interop bugs, use `swiftlang/swift`. - Weigh recovery complexity against practical benefit. Propagation or a runtime assertion can be acceptable for unexpected failures with no useful recovery, e.g. allocation failures in otherwise valid conversions. Check failure modes and caller behavior first; preserve errors for normal fallible calls instead of forcing success. - Put extra diagnostics for programming mistakes behind `NITRO_DEBUG`, including helpful assertions and early checks. Keep validation and error handling needed for release correctness or normal invalid input. -- Keep new tests, fixtures, and benchmarks outside the repo unless requested otherwise. Do not remove existing tests. +- Add or extend a paired Android Release performance scenario for new runtime features and changes to features without performance coverage. Exercise the public entry point and check the native result outside the measured window. See [contributing performance coverage](README.md#contributing-performance-coverage). +- Keep other new tests, fixtures, and benchmarks outside the repo unless requested otherwise. Do not remove existing tests. - Use the user's Git identity; no AI author or co-author. - Use Humanizer for public prose when available. Keep PR descriptions short and concrete. Never use em dashes. diff --git a/README.md b/README.md index db82c6867..48b691b81 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,18 @@ The Hetzner x64 runners can share builds, logs, and other files through a privat Store short-lived files under `runs////`. Objects under `runs/` expire after one day. Pass the upload URI to downstream jobs as a job output so a retried consumer reads the files from the successful producer. See the [example app workflow](.github/workflows/app.yml). +### Contributing performance coverage + +When adding a runtime feature or changing one that lacks performance coverage, include a Release Harness scenario in the PR. Exercise the same public operation with a fixed amount of work on both revisions. For a new API with no comparable operation on the base revision, calibrate the workload with two builds of the introducing revision to establish a baseline for future PRs. + +A scenario prepares the app state, returns a `run()` function for the measured operation, and checks the native outcome in `verify()`. Keep setup, assertions and cleanup outside the measurement. The mount benchmark commits a fresh tree and checks the text of every native label. The update benchmark prepares its tree before measurement, updates existing rows and verifies that the same native views received the final properties. For interactions that span presented frames, record frame counts and jank for that interaction. [Renderer examples](scripts/performance/scenarios/render.tsx) · [Android benchmark guide](scripts/performance/README.md) + +Register the scenario with the suite and keep its measured window identical for baseline and candidate. If the new metric should inform merge decisions, declare it in the report's primary comparison family before inspecting results. Use an A/A comparison to estimate noise and a known extra workload to check sensitivity. + +Run `python3 scripts/performance/scenarios/report.py --markdown ` on the completed measurements. The default study collects 64 pairs on a single device. All 13 primary intervals share a 5% error budget. The practical regression margins are a 5% increase in elapsed time or CPU work and a 5-percentage-point increase in scroll jank. The scroll rate is 100 times the number of reported scroll frames that exceeded their Android frame deadline divided by the total number of reported frames in the same scroll interaction. For example, an increase from 8% janky frames to 14% is six percentage points. The effect must clear the margin across the whole interval. Device scheduling and the changes between the two checkouts affect precision. Results can remain inconclusive at the selected endpoint. + +The report is advisory locally. PR checks use `--require-non-regression`. They pass when every primary metric's upper bound is at or below its regression margin. A confirmed regression exits 2, incomplete primary coverage exits 3, and an interval that still permits a meaningful regression exits 4 for review. Keep the raw SDK window and frame counts with the report so reviewers can inspect the measurements. [Feature-suite report](scripts/performance/scenarios/report.py) + ## Standalone apps ```sh diff --git a/scripts/performance/BenchmarkInteraction.kt b/scripts/performance/BenchmarkInteraction.kt new file mode 100644 index 000000000..e8ca06d0f --- /dev/null +++ b/scripts/performance/BenchmarkInteraction.kt @@ -0,0 +1,201 @@ +package com.margelo.reactnitro.example + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.SystemClock +import android.util.Base64 +import android.view.Choreographer +import android.view.InputDevice +import android.view.MotionEvent +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inspector.WindowInspector +import android.widget.EditText +import android.widget.ScrollView +import com.callstack.performanceanalytics.CallstackPerformanceAnalytics +import com.callstack.performanceanalytics.ThreadBenchmark +import java.util.UUID +import kotlin.coroutines.Continuation +import kotlin.coroutines.EmptyCoroutineContext +import kotlin.coroutines.resume +import kotlin.coroutines.startCoroutine +import kotlin.coroutines.suspendCoroutine +import org.json.JSONObject + +/** Drives a mounted Nitro view on the Android main looper, one native edit or move per vsync. */ +class BenchmarkInteraction : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val pending = goAsync() + val work = suspend { + val action = intent.getStringExtra("scenario") ?: error("Missing interaction name") + measure(context, action) + } + work.startCoroutine(object : Continuation { + override val context = EmptyCoroutineContext + override fun resumeWith(result: Result) { + try { + val error = result.exceptionOrNull() + val message = if (error == null) result.getOrThrow().toString() else error.toString() + pending.resultCode = if (error == null) 0 else 1 + pending.resultData = Base64.encodeToString(message.toByteArray(Charsets.UTF_8), Base64.NO_WRAP) + } finally { + pending.finish() + } + } + }) + } +} + +private suspend fun measure(context: Context, action: String): JSONObject { + check(Build.VERSION.SDK_INT >= 31) { "Frame deadline benchmarks require Android 12 or newer" } + val root = WindowInspector.getGlobalWindowViews().single { it.hasWindowFocus() } + val deadline = SystemClock.uptimeMillis() + 8_000 + nextFrame(deadline) + val scope = UUID.randomUUID().toString() + val gesture = when (action) { + "text-input" -> textEdits(root) + "scroll" -> scrollDrag(root) + else -> error("Unknown interaction") + } + val window: ThreadBenchmark.Result + CallstackPerformanceAnalytics.markFrameScope(action, "active", "", scope) + try { + nextFrame(deadline) + window = ThreadBenchmark(action).use { benchmark -> + for (frame in 0 until gesture.steps) { + gesture.step(frame) + nextFrame(deadline) + } + benchmark.end() + } + } finally { + CallstackPerformanceAnalytics.markFrameScope(action, "finished", "", scope) + } + gesture.verify() + // A later frame on this same window is a delivery barrier for the SDK's asynchronous listener. + root.postInvalidateOnAnimation() + var frames = scopedFrames(context, scope) + while (frames == null) { + nextFrame(deadline) + frames = scopedFrames(context, scope) + } + return JSONObject().apply { + put("window", window.toJson()) + put("frames", frames) + } +} + +private suspend fun nextFrame(deadline: Long) { + check(SystemClock.uptimeMillis() < deadline) { "Timed out waiting for the interaction or SDK frame delivery" } + suspendCoroutine { continuation -> + Choreographer.getInstance().postFrameCallback { continuation.resume(Unit) } + } +} + +private class Gesture(val steps: Int, val step: (Int) -> Unit, val verify: () -> Unit) + +private fun textEdits(root: View): Gesture { + val editor = root.descendants().filterIsInstance().single() + check(editor.requestFocus()) { "The mounted TextInput could not take focus" } + val connection = editor.onCreateInputConnection(EditorInfo()) ?: error("Missing TextInput input connection") + val input = "sphinxofblackquartzjudgemyvow" + return Gesture(input.length, { index -> + check(connection.commitText(input[index].toString(), 1)) { "Native IME edit failed" } + }, { + connection.closeConnection() + check(editor.text.toString() == input.uppercase(java.util.Locale.ROOT)) { "The native editor did not apply every transformed edit" } + }) +} + +private fun scrollDrag(root: View): Gesture { + val scroll = root.descendants().filterIsInstance().single() + val viewport = scroll.height + check(viewport > 0 && scroll.canScrollVertically(1)) { "The mounted ScrollView has no scrollable content" } + val location = IntArray(2) + scroll.getLocationInWindow(location) + val x = location[0] + scroll.width * 0.5f + val initialY = scroll.scrollY + var downAt = 0L + val moves = 48 + return Gesture(moves + 2, { frame -> + val action = when (frame) { + 0 -> MotionEvent.ACTION_DOWN + moves + 1 -> MotionEvent.ACTION_UP + else -> MotionEvent.ACTION_MOVE + } + val now = SystemClock.uptimeMillis() + if (frame == 0) downAt = now + val fraction = minOf(frame, moves).toFloat() / moves + val y = location[1] + viewport * (0.8f - 0.6f * fraction) + val event = MotionEvent.obtain(downAt, now, action, x, y, 0) + try { + event.source = InputDevice.SOURCE_TOUCHSCREEN + check(root.dispatchTouchEvent(event)) { "The app did not handle the scroll gesture" } + } finally { + event.recycle() + } + }, { + check(scroll.scrollY - initialY > viewport / 4) { "The scroll gesture did not move the native viewport" } + }) +} + +private fun View.descendants(): Sequence = sequence { + yield(this@descendants) + if (this@descendants is ViewGroup) { + for (index in 0 until childCount) yieldAll(getChildAt(index).descendants()) + } +} + +private fun ThreadBenchmark.Result.toJson() = JSONObject().apply { + put("name", name) + put("threadId", threadId) + put("elapsedMs", elapsedMs) + put("threadCpuMs", threadCpuMs) + put("countersAvailable", countersAvailable) + put("instructions", instructions) + put("cycles", cycles) + put("timeEnabledNs", timeEnabledNs) + put("timeRunningNs", timeRunningNs) + put("counterErrno", counterErrno) +} + +private fun scopedFrames(context: Context, scope: String): JSONObject? { + val files = CallstackPerformanceAnalytics.readStoredPayloadFilesForDebug(context) + val session = files.current.singleOrNull() ?: return null + val samples = JSONObject(session.content).getJSONArray("samples") + var ended = false + var total = 0L + var janky = 0L + var dropped = 0L + var time = 0.0 + var overrun = 0.0 + for (index in 0 until samples.length()) { + val sample = samples.getJSONObject(index) + if (sample.getString("type") != "frames") continue + val dimensions = sample.getJSONObject("dimensions") + if (dimensions.optString("transitionId") != scope) continue + val metrics = sample.getJSONObject("metrics") + if (dimensions.getString("phase") == "finished") { + if (metrics.getLong("totalFrameCount") > 0) ended = true + continue + } + check(dimensions.getString("frameTimingSource") == "androidDeadline") + total += metrics.getLong("totalFrameCount") + janky += metrics.getLong("jankFrameCount") + dropped += metrics.getLong("droppedFrameReportCount") + time += metrics.getDouble("totalFrameTimeMs") + overrun += metrics.getDouble("frameDeadlineOverrunMs") + } + if (!ended) return null + check(total > 0) { "The SDK reported no frames within the interaction" } + return JSONObject().apply { + put("totalFrames", total) + put("jankyFrames", janky) + put("droppedReports", dropped) + put("totalFrameTimeMs", time) + put("deadlineOverrunMs", overrun) + } +} diff --git a/scripts/performance/README.md b/scripts/performance/README.md index 4d4b5e528..326896b35 100644 --- a/scripts/performance/README.md +++ b/scripts/performance/README.md @@ -6,9 +6,11 @@ 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. 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) +On an enabled PR the runner measures 64 pairs for the renderer suite. For a manual run select `renderer_suite`. It exercises the standard MMKV workload, a renderer mount, retained updates, native IME text editing and a touch-driven scroll. The interaction driver reads PerfKit's Android frame-deadline counts for the tagged gesture. Its ratio of janky frames to total frames measures missed deadlines. The host records dropped reports and checks counter coverage. A green comparison requires every simultaneous upper bound to rule out a regression above the applicable limit. An unresolved interval is reported as **needs review**. [Benchmark definitions and contribution guide](../../README.md#contributing-performance-coverage) + 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. +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. Custom fixtures that send loopback requests must consume the response body after each acknowledgement so Cronet can reuse the connection. 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. @@ -28,15 +30,24 @@ 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 ``` +Use the same APKs for the fixed renderer comparison that CI runs. + +```sh +adc run --purpose ci --form-factor phone --api-level 35 --width 720 --height 1600 --dpi 320 -- \ + python3 scripts/performance/run.py --fixed --pairs 64 --suite --output ../renderer-run \ + --baseline ../baseline ../baseline.apk --candidate ../candidate ../candidate.apk +python3 scripts/performance/scenarios/report.py --markdown --require-non-regression ../renderer-run +``` + ## Running a fork PR with /check -A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary. The summary gives the path to the raw readings in private CI storage, where run artifacts expire after one day. A successful run means the comparison completed. Read the intervals before merging. +A maintainer with repository write access can comment `/check ` on an open fork PR after reviewing that revision. A bare `/check` uses the commenter's latest approved review if it matches the current head. A push between review and authorization requires a new approval or command. The workflow receives comments after it lands on the default branch. The `ADC /check` status on the reviewed SHA links to the run summary. The summary gives the path to the raw readings in private CI storage, where run artifacts expire after one day. A green status means that all 13 primary intervals rule out a regression beyond the specified limits. The status distinguishes a confirmed regression, incomplete measurements and an inconclusive result that needs review. The private `hetzner-cx23` runners authorize the request, supervise the builds and run the comparison. Builds share one queue across PRs so only one disposable VM is needed at a time. Each build gets a fresh Hetzner CX33 (4 shared vCPUs, 8 GB RAM) in Falkenstein in the `HetznerDefault` project. The supervisor stages the six PerfKit Maven files over SSH, registers the VM with GitHub for one job and calls the worker workflow with a unique label. The worker builds the reviewed commit in a container, validates the APK and applies a fresh signing key. The supervisor verifies which runner finished the job, collects the APK over SSH, uploads it to private CI storage and deletes the VM. An hourly cleanup removes abandoned project VMs older than 3½ hours after checking their repository label, name and ownership. One cold ARM64 candidate build took 15 min 38 s in GitHub Actions and 17 min 17 s from provisioning through cleanup. The resulting APK passed signature verification with debugging disabled. [CX33 Release build](https://github.com/margelo/nitro-ui/actions/runs/46461949749) -Only the persistent supervisors have access to the cloud and runner-management credentials. The worker has read access to the source repository for checkout. The fork's build container receives the source tree, Android toolchain and dependency files. It has public network access for dependencies and submodules. The trusted upstream driver runs the signed apps on ADC. Fork code can misrepresent its timings, so review the implementation before relying on the measurements. +Only the persistent supervisors have access to the cloud and runner-management credentials. The worker has read access to the source repository for checkout. The fork's build container receives the source tree, Android toolchain and dependency files. It has public network access for dependencies and submodules. The trusted upstream driver runs the signed apps on ADC. Fork code can misrepresent its timings, so review the implementation before relying on the measurements. The fork check runs the suite from the upstream default branch. A proposed benchmark in a fork receives maintainer review before it becomes part of that suite. #### Credentials for the supervisors @@ -87,7 +98,7 @@ The default maximum is 256 measured pairs, plus one warmup per arm. The runner e 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. +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. The adaptive two-timing calibration is advisory. The renderer suite uses the fixed-endpoint PR decision described above. Build errors, failed Harness tests and incomplete sessions fail the job. ## ADC Release calibration @@ -102,6 +113,31 @@ The default uses eight times as much timed work per launch. Two subsequent adapt 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. +## Renderer suite calibration on ADC + +On November 30, 2026, two non-debuggable Android 15 ARM64 APKs built from `b4d118ea` ran identical workloads under separate package IDs on one two-vCPU ADC device. The 64 alternating pairs took 13 min 23 s of measurement, or 14 min 7 s including setup and two warmup launches. All 640 measured Harness tests passed. Every one of the 768 thread windows had full hardware-counter coverage. + +The fixed-endpoint check ruled out the specified regression margin for 11 of its 13 primary metrics. Update elapsed time and text input cycles still admitted a slowdown above 5%, so the overall result was **needs review**. + +| Primary metric | Candidate change | Simultaneous 95% interval | +|---|---:|---:| +| Update elapsed time | +2.45% | [−7.46%, +13.78%] | +| Text input cycles | +2.05% | [−0.55%, +6.63%] | +| Mount elapsed time | +0.54% | [−1.89%, +4.97%] | +| Update instructions | +0.00% | [−0.01%, +0.12%] | +| Scroll jank | 0.00 pp | [0.00, 0.00] pp | + +Each arm reported 3,136 scroll frames with no missed deadlines or dropped reports. The jank interval describes the median paired change on this VM during these scripted drags. + +A positive control on a fresh lease of the same host added a 35 ms wait for each native scroll move in the candidate's Android main thread. Both APKs embedded identical benchmark sources and Hermes bytecode. Each arm received its own temporary signing key and ran through the fork workflow's prebuilt-APK entry point. The run collected 24 pairs in 5 min 7 s of measurement, or 6 min 3 s including setup and warmups. + +| Primary metric | Candidate change | Simultaneous 95% interval | +|---|---:|---:| +| Scroll jank | +29.59 pp | [+26.53, +35.71] pp | +| Scroll elapsed time | +10.55% | [+9.96%, +12.13%] | + +The candidate missed 355 of 1,176 scroll frame deadlines. The baseline missed 0 of 1,176. No frame reports were dropped. The check classified both scroll metrics as regressions and exited with status 2. These durations describe one host and the injected delay. + ## 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) diff --git a/scripts/performance/drive.ts b/scripts/performance/drive.ts new file mode 100644 index 000000000..8618444e2 --- /dev/null +++ b/scripts/performance/drive.ts @@ -0,0 +1,46 @@ +import { z } from 'zod' +import type { InteractionAction } from './scenarios/interactionTypes' + +const nonnegative = z.number().nonnegative() +const count = z.number().int().nonnegative() + +const reading = z.object({ + window: z.object({ + name: z.enum(['text-input', 'scroll']), + threadId: count.positive(), + elapsedMs: nonnegative.positive(), + threadCpuMs: nonnegative.positive(), + countersAvailable: z.boolean(), + instructions: count.positive().exactOptional(), + cycles: count.positive().exactOptional(), + timeEnabledNs: count.exactOptional(), + timeRunningNs: count.exactOptional(), + counterErrno: count.exactOptional(), + }), + frames: z.object({ + totalFrames: count.positive(), + jankyFrames: count, + droppedReports: count, + totalFrameTimeMs: nonnegative.positive(), + deadlineOverrunMs: nonnegative, + }), +}) + +export type InteractionResult = z.infer + +type Adb = (...command: string[]) => Promise + +export async function driveInteraction(adb: Adb, applicationId: string, action: InteractionAction): Promise { + const receiver = `${applicationId}/com.margelo.reactnitro.example.BenchmarkInteraction` + const response = await adb('shell', 'am', 'broadcast', '--receiver-foreground', '-n', receiver, '--es', 'scenario', action) + const match = /^Broadcast completed: result=(\d+), data="([A-Za-z0-9+/=]+)"$/m.exec(response) + if (match === null || match[2] === undefined) throw new Error('Android did not return the interaction result') + const raw = Buffer.from(match[2], 'base64') + const message = raw.toString('utf8') + if (match[1] !== '0') throw new Error(`Android ${action} failed: ${message.slice(0, 500)}`) + const json: unknown = JSON.parse(message) + const result = reading.parse(json) + if (result.window.name !== action) throw new Error('The Android interaction name did not match the request') + if (result.frames.jankyFrames > result.frames.totalFrames) throw new Error('Invalid SDK frame counts') + return result +} diff --git a/scripts/performance/entry.tsx b/scripts/performance/entry.tsx index bf5184123..99c53d4c2 100644 --- a/scripts/performance/entry.tsx +++ b/scripts/performance/entry.tsx @@ -7,7 +7,8 @@ import { restoreAllMocks } from '../../../../packages/react-nitro-harness/src/mo 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 { registerSuite } from './scenarios/suite' +import { fixtureSha256, suiteSha256 } from './provenance' import { post, registerWorkloads, resultHost } from './workloads' async function run() { @@ -27,7 +28,8 @@ async function run() { captureUncaughtErrors() const root = resetCollection() const register: (nonce: string, passes: number, counters: boolean) => void = registerWorkloads - register(nonce, readPasses, mode === 'counters') + register(nonce, readPasses, mode === 'counters' || mode === 'suite') + if (mode === 'suite') registerSuite(nonce) finishCollection() const tests: TestResultMessage[] = [] const fileErrors = await execute(root, { @@ -44,7 +46,7 @@ async function run() { takeUncaughtErrors: () => takeUncaughtErrors(serializeError), }) await post('/complete', { - nonce: nonce, fixtureSha256: fixtureSha256, staticFrameworkId: framework.id, readPasses: readPasses, + nonce: nonce, fixtureSha256: fixtureSha256, suiteSha256: suiteSha256, staticFrameworkId: framework.id, readPasses: readPasses, tests: tests, fileErrors: fileErrors, }) } catch (error) { diff --git a/scripts/performance/launch.ts b/scripts/performance/launch.ts index e74f380f5..9582ad4fb 100644 --- a/scripts/performance/launch.ts +++ b/scripts/performance/launch.ts @@ -1,8 +1,9 @@ import { z } from 'zod' +import { driveInteraction } from './drive' 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(), + z.string(), z.coerce.number().int().positive().optional(), z.enum(['timing', 'counters', 'suite']).optional(), ]) const [serial, applicationId, output, readPasses = 128, mode = 'timing'] = argsSchema.parse(process.argv.slice(2)) const nonce = crypto.randomUUID() @@ -36,6 +37,7 @@ 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}$/), + suiteSha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), staticFrameworkId: z.string().regex(/^[a-f0-9]{64}$/), readPasses: z.literal(readPasses), }) @@ -100,7 +102,7 @@ function measure(before: Snapshot, after: Snapshot, timings: z.infer +type NativeInteraction = Awaited> +type ScenarioReading = { window: SdkWindow, frames?: NativeInteraction['frames'] } +const scenarios: Partial> = {} +let nextScenario = 0 + +function beginScenario(name: ScenarioName) { + if (mode !== 'suite' || scenarioNames[nextScenario] !== name || readings === undefined) { + throw new Error(`Unexpected benchmark scenario: ${name}`) + } + nextScenario++ +} + +function suiteMetrics() { + const metrics: Record = {} + for (const name of scenarioNames) { + const sample = scenarios[name] + if (sample === undefined) throw new Error(`Missing benchmark scenario: ${name}`) + const key = name === 'text-input' ? 'textInput' : name + const window = sample.window + if (window.enabledNs !== window.runningNs) throw new Error(`Incomplete hardware counter coverage for ${name}`) + metrics[key + 'ElapsedMs'] = window.elapsedMs + metrics[key + 'ThreadCpuMs'] = window.threadCpuMs + metrics[key + 'Cycles'] = window.cycles + metrics[key + 'Instructions'] = window.instructions + const frames = sample.frames + if (frames !== undefined) { + metrics[key + 'TotalFrames'] = frames.totalFrames + metrics[key + 'JankyFrames'] = frames.jankyFrames + metrics[key + 'DroppedReports'] = frames.droppedReports + metrics[key + 'TotalFrameTimeMs'] = frames.totalFrameTimeMs + metrics[key + 'DeadlineOverrunMs'] = frames.deadlineOverrunMs + metrics[key + 'JankPct'] = 100 * frames.jankyFrames / frames.totalFrames + } + } + return metrics +} + 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, + hostname: '127.0.0.1', port: 0, idleTimeout: 60, maxRequestBodySize: 8 * 1024 * 1024, async fetch(request) { const url = new URL(request.url) if (url.pathname === '/config' && request.method === 'GET') return new Response(`${nonce} ${readPasses} ${mode}`) @@ -144,6 +186,21 @@ const receiver = Bun.serve({ readings = measure(before, after, timings) break } + case '/scenario': { + const record = base.extend({ name: z.enum(['mount', 'update']), window: recordedWindow }).parse(json) + beginScenario(record.name) + if (record.name !== record.window.name) throw new Error('The benchmark window name differs from the scenario') + scenarios[record.name] = { window: record.window } + break + } + case '/drive': { + const request = base.extend({ action: z.enum(['text-input', 'scroll']) }).parse(json) + beginScenario(request.action) + const record = await driveInteraction(adb, applicationId, request.action) + const window = recordedWindow.parse(record.window) + scenarios[request.action] = { window: window, frames: record.frames } + break + } case '/complete': { const report = completedSchema.parse(json) completion.resolve(report) @@ -173,11 +230,19 @@ try { 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) { + const expectedTests = mode === 'suite' ? 5 : 1 + if (report.tests.length !== expectedTests || report.tests.some((test) => test.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 }) + const extended = mode === 'suite' ? suiteMetrics() : {} + const metrics = { ...readings.metrics, ...extended } + if (mode === 'suite' && 'counters' in readings) { + for (const sample of Object.values(readings.counters)) { + if (sample.runningNs !== sample.enabledNs) throw new Error(`Incomplete hardware counter coverage for ${sample.name}`) + } + } + const serialized = JSON.stringify({ ...report, ...readings, metrics: metrics, scenarios: mode === 'suite' ? scenarios : undefined }) await Bun.write(output, serialized) } finally { clearTimeout(deadline) diff --git a/scripts/performance/pack_devicefarm.py b/scripts/performance/pack_devicefarm.py index 1fc7497f9..b92aabd58 100644 --- a/scripts/performance/pack_devicefarm.py +++ b/scripts/performance/pack_devicefarm.py @@ -53,7 +53,7 @@ def main(): 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"): + for name in ("run.py", "suite_sources.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")) diff --git a/scripts/performance/precision.py b/scripts/performance/precision.py index c7714dd21..d809080a2 100644 --- a/scripts/performance/precision.py +++ b/scripts/performance/precision.py @@ -156,23 +156,32 @@ def compare_margin(value, margin): return 0 -def metric_interval(samples, name, comparisons, equivalence_pp): +def metric_interval(samples, name, comparisons, equivalence_pp, *, absolute_pp=False): 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}") + if absolute_pp: + changes = [arms["candidate"][name] - arms["baseline"][name] for _, arms in samples] + else: + relative, changes = metric_changes(samples, name) + if not relative: + raise ValueError(f"relative precision requires strictly positive values for {name}") + + def effect(value): + if absolute_pp: + return value + return 100 * math.expm1(value) + blocks = balanced_blocks(changes) estimate = statistics.median(blocks) interval = median_interval(blocks, comparisons) - change = 100 * math.expm1(estimate) + change = effect(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]) + low = effect(interval[0]) + high = effect(interval[1]) radius = max(change - low, high - change) low_side = compare_margin(low, equivalence_pp) high_side = compare_margin(high, equivalence_pp) diff --git a/scripts/performance/prepare.py b/scripts/performance/prepare.py index 619e500ae..4b29e510d 100644 --- a/scripts/performance/prepare.py +++ b/scripts/performance/prepare.py @@ -5,6 +5,10 @@ import json from pathlib import Path import shutil +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from suite_sources import suite_digest SDK_VERSION = "0.2.1" @@ -80,7 +84,10 @@ def append_once(path, addition): 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") +for source in (sources / "scenarios").glob("*.ts*"): + destination = benchmark / "scenarios" / source.name + destination.parent.mkdir(exist_ok=True) + shutil.copyfile(source, destination) config_path = app / "app.json" config = json.loads(config_path.read_text()) config["entry"] = "src/performance/entry.tsx" @@ -90,6 +97,11 @@ def append_once(path, addition): kotlin = release / "java/com/margelo/reactnitro/example" kotlin.mkdir(parents=True, exist_ok=True) shutil.copyfile(sources / "BenchmarkSnapshot.kt", kotlin / "BenchmarkSnapshot.kt") +shutil.copyfile(sources / "BenchmarkInteraction.kt", kotlin / "BenchmarkInteraction.kt") +suite_sha = suite_digest(workload) +(benchmark / "provenance.ts").write_text( + f"export const fixtureSha256 = '{digest}'\nexport const suiteSha256 = '{suite_sha}'\n" +) xml = release / "res/xml" xml.mkdir(parents=True, exist_ok=True) (xml / "benchmark_network.xml").write_text(""" @@ -100,6 +112,7 @@ def append_once(path, addition): """) (release / "AndroidManifest.xml").write_text(""" + diff --git a/scripts/performance/run.py b/scripts/performance/run.py index 20347fe99..5906d9b95 100644 --- a/scripts/performance/run.py +++ b/scripts/performance/run.py @@ -11,6 +11,7 @@ from zipfile import ZipFile from install import install +from suite_sources import suite_digest from precision import DEFAULT_MAX_PAIRS, PrecisionPlan, evaluate_precision @@ -39,7 +40,7 @@ def write_json(path, value): path.write_text(json.dumps(value, indent=2) + "\n") -def describe_apks(builds, staged_fixture=None): +def describe_apks(builds, staged_fixture=None, *, suite=False): arms = {} for variant in VARIANTS: root, apk = builds[variant] @@ -57,6 +58,10 @@ def describe_apks(builds, staged_fixture=None): "apkSha256": sha256(apk), "fixtureSha256": sha256(fixture), } + if suite: + arms[variant]["suiteSha256"] = suite_digest(fixture) + if suite and arms["baseline"]["suiteSha256"] != arms["candidate"]["suiteSha256"]: + raise ValueError("The baseline and candidate must embed the same benchmark suite") same_workload = arms["baseline"]["fixtureSha256"] == arms["candidate"]["fixtureSha256"] if not same_workload: raise ValueError("The baseline and candidate must embed the same workload source") @@ -70,18 +75,21 @@ def main(): parser.add_argument("--staged-fixture", type=Path, help="Trusted fixture for prebuilt APKs, with a commit SHA per arm") parser.add_argument("--pairs", type=int, default=DEFAULT_MAX_PAIRS, help="Maximum number of measured pairs") parser.add_argument("--target-pp", type=float, default=5.0, help="Precision target in percentage points") + parser.add_argument("--suite", action="store_true", help="Measure mount, updates, text input and scroll at a fixed pair count") 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.suite and not args.fixed: + parser.error("--suite requires --fixed") 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: + if not args.suite and (args.pairs >= 20 or not args.fixed): try: plan = PrecisionPlan(max_pairs=args.pairs, target_pp=args.target_pp) except ValueError as error: @@ -90,7 +98,7 @@ def main(): lease = os.environ["ADC_LEASE_ID"] builds = {variant: getattr(args, variant) for variant in VARIANTS} try: - arms = describe_apks(builds, args.staged_fixture) + arms = describe_apks(builds, args.staged_fixture, suite=args.suite) except ValueError as error: parser.error(str(error)) for variant, arm in arms.items(): @@ -100,10 +108,10 @@ def main(): 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) + thread_counters=args.thread_counters, suite=args.suite) -def run_experiment(arms, apks, *, serial, session, device, directory, first, max_pairs, adaptive, plan, launcher, thread_counters=False): +def run_experiment(arms, apks, *, serial, session, device, directory, first, max_pairs, adaptive, plan, launcher, thread_counters=False, suite=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") @@ -112,7 +120,7 @@ def run_experiment(arms, apks, *, serial, session, device, directory, first, max "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, + "buildType": "release", "adaptive": adaptive, "threadCounters": thread_counters or suite, "suite": suite, "precisionPlan": plan.as_dict() if plan else None, "precisionLooks": [], "arms": arms, } @@ -153,7 +161,9 @@ def run_experiment(arms, apks, *, serial, session, device, directory, first, max result_file = directory / f"{name}.json" passes = arms[variant]["readPasses"] command = [*launcher, serial, package, result_file.resolve(), str(passes)] - if thread_counters: + if suite: + command.append("suite") + elif thread_counters: command.append("counters") started = now() print(f"{started} {name}", flush=True) @@ -164,6 +174,8 @@ def run_experiment(arms, apks, *, serial, session, device, directory, first, max 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 suite and result.get("suiteSha256") != arms[variant]["suiteSha256"]: + raise ValueError(f"{name} ran a different benchmark suite") if pair: row = { "session": session, "pair": pair, "position": position, "variant": variant, diff --git a/scripts/performance/scenarios/interactionTypes.ts b/scripts/performance/scenarios/interactionTypes.ts new file mode 100644 index 000000000..b4962e53c --- /dev/null +++ b/scripts/performance/scenarios/interactionTypes.ts @@ -0,0 +1,2 @@ +export type InteractionAction = 'text-input' | 'scroll' +export type DriveInteraction = (action: InteractionAction) => Promise diff --git a/scripts/performance/scenarios/interactions.tsx b/scripts/performance/scenarios/interactions.tsx new file mode 100644 index 000000000..361a39833 --- /dev/null +++ b/scripts/performance/scenarios/interactions.tsx @@ -0,0 +1,59 @@ +import { useState } from 'react' +import { expect, render } from 'react-nitro-harness' +import { ScrollView, ScrollViewContent, Text, TextInput, View } from 'react-nitro-renderer' +import type { DriveInteraction } from './interactionTypes' + +function EditingScreen(props: { changed: (text: string) => void }) { + const [value, setValue] = useState('') + return ( + + edit.proposedText.toUpperCase()} + onTextChanged={(change) => { + setValue(change.text) + props.changed(change.text) + }} + /> + {value} + + ) +} + +export async function prepareTextInput(drive: DriveInteraction) { + let lastText = '' + let edits = 0 + function changed(text: string) { + lastText = text + edits++ + } + const screen = + await render(screen) + return { + run: () => drive('text-input'), + verify: () => { + const expected = 'SPHINXOFBLACKQUARTZJUDGEMYVOW' + expect(lastText).toBe(expected) + expect(edits).toBe(expected.length) + }, + } +} + +export async function prepareScroll(drive: DriveInteraction) { + const rows = Array.from({ length: 96 }, (_, index) => ( + + {`Scroll row ${index}`} + + )) + const screen = ( + + {rows} + + ) + await render(screen) + return { + run: () => drive('scroll'), + // The native driver verifies the actual view's offset after the drag. + verify: () => {}, + } +} diff --git a/scripts/performance/scenarios/render.tsx b/scripts/performance/scenarios/render.tsx new file mode 100644 index 000000000..85049723e --- /dev/null +++ b/scripts/performance/scenarios/render.tsx @@ -0,0 +1,78 @@ +import { createRef, type RefObject } from 'react' +import { expect, render } from 'react-nitro-harness' +import { Text, View, type ViewDefinitionMap, type ViewRef } from 'react-nitro-renderer' + +export async function prepareMount() { + const tree = await render(null) + const rows = Array.from({ length: 256 }, (_, index) => ({ + title: `Mount row ${index}`, + label: createRef(), + })) + + return { + async run() { + const children = rows.map((row) => ( + + {row.title} + + )) + await tree.rerender({children}) + }, + verify() { + for (const row of rows) { + const label = row.label.current + if (label === null || label.parent === undefined) throw new Error(`Did not mount ${row.title}`) + expect(label.text).toBe(row.title) + } + }, + } +} + +type UpdateRow = { + key: number + view: RefObject +} + +const initialStyle = { opacity: 1, background: 0x104060ff } +const updatedStyle = { opacity: 0.5, background: 0x306080ff } + +function UpdateRows({ rows, revision }: { rows: UpdateRow[]; revision: number }) { + const style = revision % 2 === 0 ? initialStyle : updatedStyle + return ( + + {rows.map((row) => ( + + ))} + + ) +} + +export async function prepareUpdate() { + const rows = Array.from({ length: 64 }, (_, index) => ({ + key: index, + view: createRef(), + })) + const tree = await render() + const mounted = rows.map((row) => { + const view = row.view.current + if (view === null) throw new Error(`Missing initial view for row ${row.key}`) + expect(view.opacity).toBe(initialStyle.opacity) + expect(view.backgroundColor).toBe(initialStyle.background) + return { ref: row.view, original: view } + }) + + return { + async run() { + for (let revision = 1; revision <= 31; revision++) { + await tree.rerender() + } + }, + verify() { + for (const { ref, original } of mounted) { + expect(ref.current).toBe(original) + expect(original.opacity).toBe(updatedStyle.opacity) + expect(original.backgroundColor).toBe(updatedStyle.background) + } + }, + } +} diff --git a/scripts/performance/scenarios/report.py b/scripts/performance/scenarios/report.py new file mode 100644 index 000000000..cc1926822 --- /dev/null +++ b/scripts/performance/scenarios/report.py @@ -0,0 +1,203 @@ +"""Report the fixed-endpoint comparison of Android feature scenarios.""" + +import argparse +import json +import math +from pathlib import Path +from statistics import median +import sys + +performance_dir = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(performance_dir)) +from precision import compare_margin, metric_interval, ordered_pairs, read_sessions + + +SCENARIOS = ("mount", "update", "textInput", "scroll") +TIMINGS = tuple(scenario + "ElapsedMs" for scenario in SCENARIOS) +JANK = "scrollJankPct" +CPU_CASES = ("mmkv", "mount", "update", "textInput") +COUNTERS = tuple(case + suffix for case in CPU_CASES for suffix in ("Cycles", "Instructions")) +PRIMARY = (*TIMINGS, JANK, *COUNTERS) +MARGIN = 5 +FRAME_SUFFIXES = ("TotalFrames", "JankyFrames", "DroppedReports", "TotalFrameTimeMs", "DeadlineOverrunMs") +DIAGNOSTICS = [case + "ThreadCpuMs" for case in ("mmkv", *SCENARIOS)] +DIAGNOSTICS += ["scrollCycles", "scrollInstructions"] +DIAGNOSTICS += [case + suffix for case in ("textInput", "scroll") for suffix in FRAME_SUFFIXES] + + +def scroll_coverage(pairs): + coverage = {"completeLaunches": 0, "emptyLaunches": 0, "droppedReports": 0} + for number, launches in pairs.items(): + for position, (_, metrics) in launches.items(): + total = metrics["scrollTotalFrames"] + janky = metrics["scrollJankyFrames"] + dropped = metrics["scrollDroppedReports"] + if any(value < 0 or int(value) != value for value in (total, janky, dropped)) or janky > total: + raise ValueError(f"invalid scroll frame counts at pair {number}, position {position}") + coverage["droppedReports"] += dropped + if total == 0: + coverage["emptyLaunches"] += 1 + continue + if dropped == 0: + coverage["completeLaunches"] += 1 + if JANK in metrics or dropped == 0: + rate = metrics[JANK] + expected = 100 * janky / total + if not 0 <= rate <= 100 or not math.isclose(rate, expected, rel_tol=1e-9, abs_tol=1e-9): + raise ValueError(f"scroll jank percentage disagrees with frame counts at pair {number}, position {position}") + return coverage + + +def descriptive_metrics(pairs): + result = {} + for name in DIAGNOSTICS: + readings = {"baseline": [], "candidate": []} + for launches in pairs.values(): + for arm, metrics in launches.values(): + if name in metrics: + readings[arm].append(metrics[name]) + if readings["baseline"] or readings["candidate"]: + result[name] = { + arm: {"median": median(values) if values else None, "samples": len(values)} + for arm, values in readings.items() + } + return result + + +def analyze(folder): + metadata = (folder / "session.json").read_text() + session = json.loads(metadata) + count = session["pairs"] + if type(count) is not int or session.get("adaptive") is not False: + raise ValueError("expected a fixed pair count for the feature suite") + if not session.get("finished") or session.get("completedPairs") != count: + raise ValueError("feature suite ended before its fixed endpoint") + + 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") + pairs = sessions[lease] + coverage = scroll_coverage(pairs) + launches = [metrics for pair in pairs.values() for _, metrics in pair.values()] + counter_coverage = {name: sum(name in metrics for metrics in launches) for name in COUNTERS} + unavailable = {} + for name, complete in counter_coverage.items(): + if complete != 2 * count: + unavailable[name] = f"complete PMU coverage on {complete}/{2 * count} launches" + if coverage["completeLaunches"] != 2 * count: + unavailable[JANK] = "incomplete scroll frame coverage" + + # Optional diagnostics and unavailable counters can differ between launches. + # Keep all original pairs for every endpoint with complete evidence. + measured = [name for name in PRIMARY if name not in unavailable] + primary_pairs = {} + for number, pair in pairs.items(): + primary_pairs[number] = {} + for position, (arm, metrics) in pair.items(): + measurements = {name: metrics[name] for name in measured} + primary_pairs[number][position] = (arm, measurements) + samples = ordered_pairs(primary_pairs, count) + if samples[0][0] != session["first"]: + raise ValueError("first measured pair differs from the registered order") + + metrics = {} + for name in PRIMARY: + if name in unavailable: + outcome = { + "classification": "inconclusive", "changePct": None, "lowerPct": None, "upperPct": None, + "radiusPp": None, "reason": unavailable[name], + } + else: + outcome = metric_interval(samples, name, len(PRIMARY), MARGIN, absolute_pp=name == JANK) + outcome["unit"] = "pp" if name == JANK else "%" + metrics[name] = outcome + diagnostics = descriptive_metrics(pairs) + result = { + "lease": lease, "pairs": count, "blocks": count // 2, "familywiseConfidence": 0.95, + "margin": MARGIN, "metrics": metrics, "scrollFrameCoverage": coverage, + "counterLaunches": counter_coverage, "completeCoverage": not unavailable, "diagnostics": diagnostics, + } + result["verdict"] = verdict(result) + return result + + +def verdict(result): + outcomes = result["metrics"].values() + if any(metric["classification"] == "regression" for metric in outcomes): + return "regression" + if not result["completeCoverage"]: + return "incomplete coverage" + for metric in outcomes: + upper = metric["upperPct"] + if upper is None or compare_margin(upper, MARGIN) > 0: + return "needs review" + return "within regression limits" + + +def markdown(result): + lines = [ + "## Paired Android feature benchmarks", "", f"**Result:** {result['verdict']}.", "", + "| Primary metric | Candidate change | Simultaneous 95% interval | Decision |", + "|---|---:|---:|---|", + ] + for name, metric in result["metrics"].items(): + unit = metric["unit"] + estimate = metric["changePct"] + change = f"{estimate:+.2f} {unit}" if estimate is not None else "unavailable" + low = metric["lowerPct"] + high = metric["upperPct"] + interval = f"[{low:+.2f}, {high:+.2f}] {unit}" if low is not None else "unavailable" + decision = metric["classification"] + if "reason" in metric: + decision += " (" + metric["reason"] + ")" + lines.append(f"| {name} | {change} | {interval} | {decision} |") + coverage = result["scrollFrameCoverage"] + launches = 2 * result["pairs"] + lines.extend([ + "", f"At the fixed endpoint of {result['pairs']} pairs, each of {result['blocks']} AB/BA blocks " + "contributes a mean log ratio for durations and hardware counters and a mean candidate-minus-baseline difference for scroll jank. " + "Median rank intervals share the 5% error budget across 13 primary outcomes on this device, " + "assuming independent blocks with a common median effect. Regression requires the entire interval " + "to exceed +5% time or CPU work, or +5 percentage points of janky frames.", + "", "Scroll jank is the percentage of reported frames in the scroll interaction that exceeded their Android frame deadline.", + f"Scroll frame reports covered {coverage['completeLaunches']}/{launches} launches in full. " + f"{coverage['emptyLaunches']} launches had zero frames and the collector dropped {coverage['droppedReports']} reports.", + ]) + if result["diagnostics"]: + lines.extend(["", "### Descriptive readings", "", + "| Metric | Baseline median (samples) | Candidate median (samples) |", "|---|---:|---:|"]) + for name, readings in result["diagnostics"].items(): + cells = [] + for arm in ("baseline", "candidate"): + entry = readings[arm] + value = entry["median"] + cells.append(f"{value:.5g} ({entry['samples']})" if value is not None else "unavailable (0)") + lines.append(f"| {name} | {cells[0]} | {cells[1]} |") + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("folder", type=Path, help="directory containing session.json and raw.jsonl") + parser.add_argument("--markdown", action="store_true", help="write a GitHub Markdown report") + parser.add_argument("--fail-on-regression", action="store_true", help="exit 2 for a primary regression, 3 for incomplete coverage") + parser.add_argument("--require-non-regression", action="store_true", + help="also exit 4 when a primary interval still allows a meaningful regression") + args = parser.parse_args() + try: + result = analyze(args.folder) + except (KeyError, ValueError, OSError) as error: + parser.exit(1, f"{error}\n") + if args.markdown: + print(markdown(result)) + else: + print(json.dumps(result, indent=2, allow_nan=False)) + if args.fail_on_regression or args.require_non_regression: + if result["verdict"] == "regression": + sys.exit(2) + if result["verdict"] == "incomplete coverage": + sys.exit(3) + if args.require_non_regression and result["verdict"] == "needs review": + sys.exit(4) diff --git a/scripts/performance/scenarios/suite.ts b/scripts/performance/scenarios/suite.ts new file mode 100644 index 000000000..278ac37a0 --- /dev/null +++ b/scripts/performance/scenarios/suite.ts @@ -0,0 +1,30 @@ +import { ThreadBenchmark } from '@callstack/performance-analytics-react-nitro' +import { it } from 'react-nitro-harness' +import { post } from '../workloads' +import { prepareScroll, prepareTextInput } from './interactions' +import type { InteractionAction } from './interactionTypes' +import { prepareMount, prepareUpdate } from './render' + +export function registerSuite(nonce: string) { + for (const [name, prepare] of [['mount', prepareMount], ['update', prepareUpdate]] as const) { + it(name, async () => { + const scenario = await prepare() + const window = new ThreadBenchmark(name) + await scenario.run() + const measurement = window.end() + await scenario.verify() + await post('/scenario', { nonce: nonce, name: name, window: measurement }) + }) + } + + async function drive(action: InteractionAction) { + await post('/drive', { nonce: nonce, action: action }) + } + for (const [name, prepare] of [['text-input', prepareTextInput], ['scroll', prepareScroll]] as const) { + it(name, async () => { + const scenario = await prepare(drive) + await scenario.run() + await scenario.verify() + }) + } +} diff --git a/scripts/performance/suite_sources.py b/scripts/performance/suite_sources.py new file mode 100644 index 000000000..6784e73e6 --- /dev/null +++ b/scripts/performance/suite_sources.py @@ -0,0 +1,20 @@ +"""Fingerprint the workload sources used for a suite launch.""" +from hashlib import sha256 +from pathlib import Path + +INTERACTION_RECEIVER = Path("android/app/src/release/java/com/margelo/reactnitro/example/BenchmarkInteraction.kt") + + +def suite_digest(workload): + directory = workload.parent + app = directory.parents[1] + files = sorted((directory / "scenarios").glob("*.ts*")) + files.extend([workload, directory / "entry.tsx", app / INTERACTION_RECEIVER]) + digest = sha256() + for source in files: + digest.update(source.relative_to(app).as_posix().encode()) + digest.update(b"\0") + contents = source.read_bytes() + digest.update(len(contents).to_bytes(8, "big")) + digest.update(contents) + return digest.hexdigest() diff --git a/scripts/performance/workloads.tsx b/scripts/performance/workloads.tsx index 8efcbe29a..b01d5a561 100644 --- a/scripts/performance/workloads.tsx +++ b/scripts/performance/workloads.tsx @@ -22,7 +22,8 @@ function Rows({ revision }: { revision: number }) { 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}`) + const acknowledgement = await response.text() + if (!response.ok) throw new Error(`Benchmark host rejected ${route}: ${response.status} ${acknowledgement}`) } export function registerWorkloads(nonce: string, readPasses: number, collectCounters: boolean) {