Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions .github/workflows/android-performance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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' }}
Expand Down Expand Up @@ -111,20 +116,26 @@ 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 "$@" \
--baseline baseline baseline.apk --candidate candidate candidate.apk --output experiment/results

- 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') != '' }}
Expand Down
43 changes: 29 additions & 14 deletions .github/workflows/fork-performance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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" \
Expand Down
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ The Hetzner x64 runners can share builds, logs, and other files through a privat

Store short-lived files under `runs/<run-id>/<run-attempt>/<artifact-name>/`. 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 <session-directory>` 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
Expand Down
201 changes: 201 additions & 0 deletions scripts/performance/BenchmarkInteraction.kt
Original file line number Diff line number Diff line change
@@ -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<JSONObject> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<JSONObject>) {
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<Unit> { 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<EditText>().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<ScrollView>().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<View> = 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)
}
}
Loading