In the first article, I explained how I investigated measurement noise and turned a memory report into a blocking PR check. This companion guide covers our current setup: Macrobenchmark, the build and scenarios, CI emulators, baseline comparisons, verdict rules, cloud-hosted phones, and calibration. References to Parts 1–6 below point to the investigation in the first article.

System components

  • Test: Macrobenchmark with a custom memory sampler running inside it.
  • Build: a dedicated release-based build type that can access the test server.
  • Scenarios: ten user journeys through the most memory-heavy screens.
  • CI emulators: one Android 14 image; a fresh emulator for every scenario.
  • Schedule: diff-selected scenarios on PRs; the full suite on main twice each night.
  • Verdict: warn when growth exceeds max(3σ, 8 MB) relative to the main baseline; block 4 MB above that, never below 12 MB.
  • Cloud phones: two BrowserStack models, run twice a day on main and in response to emulator warnings.

Memory-check architecture: the PR path (blue), nightly main runs (green), and physical phones (orange).

Test and sampler

A scenario is a Macrobenchmark test using measureRepeated with StartupMode.COLD: every pass starts with a cold launch, which Espresso cannot do (see Part 2). Compilation is partial, CompilationMode.Partial(), because it significantly reduces between-session σ (see Part 2). It requires a baseline profile in the perfMetrics APK; our separate Baseline Profile plugin module generates one.

Each scenario consists of four passes. Between passes, the test kills the app process and waits until it has actually terminated. It clears app data (pm clear) only once, before the first pass. On phones and local emulators, the app might remain installed from a previous session, and without the reset the first pass could start already logged in.

The sampler calls dumpsys meminfo <package> through UiAutomation.executeShellCommand, reads TOTAL PSS, and waits one second after each read, so the actual sampling interval is a little over one second. It also samples at every screen marker and immediately after launch. Alongside PSS, it records the per-area breakdown and anon RSS + swap: it gets the PID once per pass with pidof <package> and reads RssAnon and VmSwap from cat /proc/<pid>/status. executeShellCommand launches commands without a shell, so *, |, and redirection do not work. On emulators, these fields help explain growth; they do not determine the verdict.

At the end of each pass, the sampler sends one line per segment through Instrumentation.sendStatus: memseg phase=<screen> iter=<pass> n=<samples> median_pss_kb=… peak_pss_kb=… min_pss_kb=… together with per-area medians. The median is taken across the entire segment or, on screens whose memory never stabilizes, until the end of the fixed wait. The lines appear in am instrument output. A CI script saves that output from every emulator and computes a screen's level as one median across all passes on all emulators—16 numbers on a PR.

A segment begins when its screen appears: the test waits for a recognizable UI element using UiAutomator and adds a marker. The screen must appear within 15 seconds; slow screens can be allowed up to 30 seconds. Then the test waits for memory to stabilize: the difference between the maximum and minimum of the last six samples must be no greater than 4% of their median. The condition is checked every 250 ms. If memory does not stabilize within 60 seconds, the pass fails. Sampling the instant a screen appears measures late class loading rather than the screen itself (see Part 2). The tolerance is relative and the window longer than in Part 2: on screens with live maps, the older rule usually never stabilized, while four samples could close the window before the screen finished loading.

Some screens never stabilize: driver search, a live order feed, and active rides. For them, the test waits a fixed 5–40 seconds, as defined in the scenario.

Build

The perfMetrics build type inherits from release (initWith(release)): the same R8 rules, debuggable = false, and release source sets, where debugging tools are replaced with no-op implementations. On top of that, it adds only what the tests need:

  • profileable in the manifest so the shell can read memory;
  • signing with the same key as the test APK;
  • a configuration receiver—a BroadcastReceiver to which the test sends am broadcast -n <package>/<receiver> with the test-server URL, tokens, and flag values;
  • unencrypted HTTP access to the test server;
  • crash reporting disabled.

For emulators, I build only x86_64; for phones, arm64-v8a and armeabi-v7a. The build type reads its ABI list from our perfMetricsAbis property and puts it in ndk.abiFilters. The test is a separate com.android.test module, in our case :macrobenchmark, with targetProjectPath = ":app". Its benchmark build type uses matchingFallbacks += "debug" so Gradle can find an app variant for compiling the test, and the android block sets experimentalProperties["android.experimental.self-instrumenting"] = true. This flag lets the test launch the app by package name, so the separately built perfMetrics APK is installed on the device. Why not debug? On the order form, perfMetrics used about one-third less memory than a debug build with R8 (see Part 2).

Scenarios and test data

Scenarios cover the screens with the highest P90 PSS on low-end phones in production telemetry, separately for passengers and drivers. We now have ten scenarios: the eight paths from Part 2 and two additional paths through the settings screen, one for each role.

Every scenario on every emulator creates a fresh test user, shared across its four passes; the token is refreshed before each pass. The other party to a ride—order, bid, accepted ride, and ride stages—is created by the test server API, so everything happens on one device (see Part 2).

The server is also part of the test environment. A server-side flag might enable a new screen, causing the test to measure a different app even though the PR code did not change. So the test pins flags that affect scenario paths for the duration of the run using the same configuration receiver, and checks on every pass that they are still effective. If a flag value is not preserved, the pass fails and produces no measurement. But the app evolves, and pinned flag values eventually become outdated. A weekly CI task therefore compares the flags the test server returns for the main build against the pinned list and the previous week's snapshot, and posts a summary to chat. It tells us when the test needs updating.

Weekly summary of pinned flags that differ from the test server and the changes since the previous week.

CI emulator

Configuration recipe:

  • A runner with KVM: /dev/kvm must be readable and writable, or the run stops.
  • Image system-images;android-34;google_apis;x86_64, revision 14: the script checks the installed image revision and aborts if it differs.
  • Device profile pixel_6, 4,096 MB RAM, four CPU cores, 6,144 MB storage partition.
  • GPU: swiftshader_indirect.
  • Flags: -no-window -no-snapshot -no-boot-anim -no-audio -no-metrics.
  • Animations disabled; error dialogs hidden.
  • A fresh AVD (Android Virtual Device) for each scenario: stop the emulator, delete the previous AVD, recreate it from the same image, boot, configure, and install APKs.

We chose Android 14, 4 GB, and four cores because that configuration was the most consistently stable across the full path among the five tested (see Part 3). A fresh AVD is required because scenario position and retries changed the Code row on reused emulators (see Parts 4 and 6). The cost is about 40 seconds per scenario.

Here is the recipe as a script for one emulator per machine. In our setup, each emulator is a separate CI job on its own runner. If several emulators share a machine, give each a separate port (emulator -port 5556) and add -s emulator-5556 to every adb call.

# Build: app uses the perfMetrics build type for x86_64 only; the test uses benchmark ./gradlew :app:assemblePerfMetrics -PperfMetricsAbis=x86_64 :macrobenchmark:assembleBenchmark # Android 14 image with Google APIs. We use revision 14; sdkmanager installs only the latest revision: # For a fresh setup, set IMAGE_REV to the installed revision and cache the image on the runner # so it cannot change. A new revision starts a new main-history series (see "When and what to compare"). IMAGE_REV=14 yes | sdkmanager --licenses sdkmanager "platform-tools" "emulator" "system-images;android-34;google_apis;x86_64" REV=$(sdkmanager --list_installed | grep "system-images;android-34;google_apis;x86_64" \   | awk -F'|' '{gsub(/ /, "", $2); print $2}') [ "$REV" = "$IMAGE_REV" ] || { echo "image revision $REV; expected $IMAGE_REV"; exit 1; } # Fresh AVD before each scenario # Stop the emulator from the previous scenario adb emu kill || true while adb get-state >/dev/null 2>&1; do sleep 1; done avdmanager delete avd -n memory || true avdmanager create avd --force -n memory \   -k "system-images;android-34;google_apis;x86_64" -d pixel_6 emulator -avd memory -memory 4096 -cores 4 -partition-size 6144 \   -gpu swiftshader_indirect \   -no-window -no-snapshot -no-boot-anim -no-audio -no-metrics & # Wait for sys.boot_completed = 1, then configure the device adb wait-for-device until [ "$(adb shell getprop sys.boot_completed | tr -d '\r')" = "1" ]; do sleep 2; done adb shell settings put global window_animation_scale 0 adb shell settings put global transition_animation_scale 0 adb shell settings put global animator_duration_scale 0 adb shell settings put global hide_error_dialogs 1 adb shell input keyevent 82   # unlock the screen # Install with permissions granted adb install -r -g app/build/outputs/apk/perfMetrics/app-perfMetrics.apk adb install -r -g macrobenchmark/build/outputs/apk/benchmark/macrobenchmark-benchmark.apk # Run the scenario adb shell am instrument -w \   -e class 'com.example.macrobenchmark.OrderFormMemoryTest' \   -e androidx.benchmark.suppressErrors EMULATOR,DEBUGGABLE,NOT-PROFILEABLE \   -e androidx.benchmark.dropShaders.enable false \   'com.example.macrobenchmark/androidx.test.runner.AndroidJUnitRunner' 

Macrobenchmark refuses to measure on emulators and with a debuggable test build by default. androidx.benchmark.suppressErrors disables those checks. We do not reset the shader cache between passes. Save am instrument output to a file and parse the sampler's lines with your own script.

On PRs, four measurement emulators run in parallel and yield 16 passes per scenario. A fifth runs each scenario once and captures a screenshot at every screen marker for the timeline view (see Part 3), which uses memory from one measurement emulator. On main, nine emulators run overnight. Four passes are used because the fourth made a noticeable difference (see Part 3). Four emulators mean three replicas plus one spare: if one replica fails completely even after a retry, the remaining three still contribute 12 passes and may block a PR (see Part 4).

If a scenario produces no result on an emulator, that replica gets one retry on a fresh AVD, and the retry result contributes to the screen level normally (see Part 6). I do not retry failures that occur while preparing the test environment. If an emulator produces only some of its passes, it is not retried: those passes count toward the level, but that incomplete level can warn only, not block.

When and what to compare

On PRs, I run diff-selected scenarios. A scenario map associates each scenario with module-path prefixes, and modified files come from the PR API. For every file, rules are checked in order; the first match decides which scenarios that file triggers. The final suite is the union across all files in the PR.

1. Files on the exclusion list, such as translations, trigger nothing.

2. Paths on the "full suite" list—root modules for each role, shared modules such as core/ and app/, shared build files (root *.gradle.kts, gradle/), and the test code itself—trigger every scenario.

3. A scenario module triggers its corresponding scenario.

4. Everything else—code outside the map, tests, documentation, and CI files—triggers nothing. Such changes are measured by the nightly full suite on main.

Each PR is measured automatically once when opened, or when a draft is marked ready for review. New pushes do not automatically launch a new measurement: after a fix, the author posts /run-memory-tests in a PR comment. With no arguments, it runs diff-selected scenarios; all requests the full suite; device requests phones. A workflow watches for new comments (the issue_comment event in GitHub Actions), checks that the author has write access, and launches the measurement. A new command of the same type cancels an older run; a phone command does not affect an emulator run. Fresh results update the existing gate comment.

To make blocking effective, set a status on the PR's head commit through the API and mark it as a required status check. You need the API because a workflow triggered by a comment is not attached to the commit. The status is red only when the gate blocks. It is green for "no verdict" or an empty diff; otherwise, no PR could merge when a new measurement series starts. After a new push, the new commit has no status, and the PR waits for its author to rerun the check.

Why diff-selected scenarios? They covered 53 of 60 PRs while consuming 55% of the full suite's time (see Part 5).

PR comment commands: /run-memory-tests all runs the full suite, while /run-memory-tests device runs phone tests.

On main, the full suite runs twice a night, once in the evening and once in the morning. A merge into main does not trigger a run. The PR baseline is the mean of screen levels from the latest complete overnight pair. It is selected once each morning; if the pair is incomplete, the previous night's pair is used. All PRs opened on the same day are thus compared with the same baseline number. σ comes from the last ten main results within the same measurement series, with a minimum of three.

I do not run main alongside the PR in the same measurement: emulators in one run differ almost as much as emulators across runs (see Part 4), so there is no common noise to subtract, and PR compute time would double.

We store history in a time-series database; any store that supports queries by series key will work. After a main run, a CI script writes one record per result: scenario, screen, metric, value, commit, and series key. The key describes the measurement environment: emulator image and revision, RAM, CPU cores, number of passes, and methodology version. If any of those change, a new series begins. Until the new series has at least three results, PRs receive no verdict.

Verdict rules

Two values are compared on each screen: the screen level and entry cost—how much more memory the screen uses than the previous screen in the same pass. Main-history σ is calculated separately for each value on each screen of each scenario, because screens have different noise levels (see Part 2).

  • Screen-level increase below 8 MB: no action.
  • Screen-level increase greater than max(3σ, 8 MB): a warning in the PR comment, without blocking the merge.
  • Entry-cost increase greater than max(3σ, 4 MB): a warning as well.
  • Screen-level increase at least 4 MB above the warning threshold, with every pass present from every emulator that produced a result: block the PR.
  • Scenario fails on every emulator, either crashing or never reaching the required screen, while main has a baseline for it: block the PR as well.
  • Peaks appear in the report but do not affect the verdict.

On a quiet screen where 3σ is below 8 MB, the rule is straightforward: below 8 MB, no action; from 8 to 12 MB, warn; above 12 MB, block. Both thresholds rise on noisier screens. The 8 MB floor prevents an unusually quiet series from shrinking the threshold to a fraction of a megabyte (see Part 3). Blocking uses a separate, higher threshold and requires complete passes because a false block is more costly than a false warning (see Part 6).

The "passed" verdict is assigned only after comparing everything a scenario is expected to produce: level and entry cost for every screen. Otherwise, the report says "no verdict" and "compared X of Y". If between-emulator σ for a PR exceeds 2 MB and is more than three times main-history σ, the number in the comment table is marked noisy but is still compared normally.

For each scenario, the PR comment includes a table with screen, branch result, main baseline and its σ, entry cost, and peak, plus links to the timeline view and run artifacts. Build the timeline view from day one: it reveals which action preceded a memory jump and whether the test reached the intended screen. For BrowserStack phone runs, the timeline uses frames extracted from test videos.

Verdicts are based on total PSS, not anon RSS + swap as required by Google Play: on emulators, anon RSS + swap is no less noisy than PSS (see Part 5).

Cloud-hosted phones

Phones are necessary because the emulator does not capture GPU memory (see Part 5). We use BrowserStack App Automate with the Espresso v2 endpoint, which accepts a Macrobenchmark test APK as an ordinary instrumentation test. The app reaches the test server through a BrowserStack Local tunnel. The script reads memseg lines from the instrumentation log through the BrowserStack API, falling back to device logs when they are missing. Models: Moto G71 on Android 11 and Galaxy S26 on Android 16.

  • Schedule: twice daily on main, full suite, both models.
  • On PRs: automatically when an emulator reports a warning, for those scenarios only.
  • Session: one per scenario and model; the models run in parallel, with four passes per test.
  • Signals: anon RSS + swap (RssAnon + VmSwap) and Graphics, evaluated separately. PSS is displayed but does not determine the verdict.
  • Threshold: growth greater than max(3σ, 4 MB) above the median of the model's ten most recent scheduled main runs. The floor is lower than for emulators because anon RSS + swap is several times less noisy on phones (see Part 5).
  • If a scheduled run detects growth, the same workflow immediately launches a confirmation run on the same commit, both models, all scenarios. Both runs are evaluated against the baseline snapshot saved at the first threshold crossing (see Part 6).
  • Phone results are posted as a separate comment and do not change the emulator verdict.

How I selected and qualified each model:

1. Initial screening: add 16 MB to Java heap, native heap, and GL textures at the start of the path, with two pairs of control and allocation sessions per area, or 12 sessions per model. For textures, the control session keeps a GL context without textures. A model passes if the allocation shifts its corresponding signal by approximately the expected amount. Without this check, I might trust a Graphics value of zero on a phone that cannot report graphics at all (see Part 5).

2. Noise: measure anon RSS + swap σ in control sessions and the number of OS builds. There is no hard σ cutoff: the final stage determines whether a noisy model, whose threshold exceeds an 8 MB allocation, is acceptable.

3. Intermediate evaluation for the best models: 52–59 sessions with 8 and 16 MB allocations at the start and end of the path, comparing threshold floors of 4 and 8 MB.

4. Fix the rule before the final stage: choose the signal, a history of ten control sessions, and a max(3σ, 4 MB) threshold for each screen.

5. Final stage: 40 sessions per model—ten controls, three graphics controls per position, and four sessions each with an 8 MB allocation in Java, native heap, and textures at the start and end of the path. Control sessions from the intermediate stage form the history. Models without that stage, such as Galaxy S26, require an additional 18 sessions before the final stage.

6. Activation: add the model to the allowlist and collect ten main runs before issuing verdicts.

How long does it take?

Approximate figures:

  • Full suite on a PR: about two hours from launch to results, with four emulators in parallel, each running for about an hour. Diff-selected scenarios take roughly half as long on average.
  • Build: about 20 minutes; the artifact is reused for the same commit.
  • One scenario on an emulator: 5–12 minutes.
  • Nightly main run: about two hours from launch to result with nine emulators.
  • One phone scenario: 12–15 minutes, plus up to an hour waiting for the device.

What do we reliably detect?

I validated the boundaries using calibrated allocations in two passenger scenarios—the order form and settings (see Part 6). I made the app retain known amounts of Java or native memory and compared the changed branch with a run of the same commit without the allocation, using the gate's thresholds. Growth in the table means growth in the measured screen level, not the size of the allocation. The gate evaluated some of the same cases in multiple series, so the result column shows the minimum and maximum numbers detected.

Screen-level increase

Gate action

Calibration result

Below 8 MB

No action

0 of 5 flagged

8–12 MB

Warning

4–6 of 6 warned

12–16 MB

Blocking

7–9 of 9 blocked

16 MB or more

Blocking

39–40 of 40 blocked

Unchanged main

No action

0 alerts in 171 scenario observations

Gate behavior: below 8 MB, no action; from 8 MB, warn; from 12 MB, block. The band shows the share detected, from the minimum to the maximum across calibration series.

Those tight boundaries were possible because main history became so stable: on the passenger order form, the threshold approached the 8 MB floor.

The emulator does not detect GPU memory, so phones handle it. In the final stage, one scenario with an 8 MB allocation, four sessions per cell, produced the following results:

Model

Java and native, 8 MB

Textures, start of path

Textures, end of path

False flags on controls

Moto G71

16 of 16

4 of 4

4 of 4

1 of 10

Galaxy S26

14 of 16

4 of 4

1 of 4

3 of 10, never twice consecutively

I include these numbers alongside the rule because a tool is useful only when it clearly states what it can—and cannot—detect.