Skip to content

[Task 1/5] [No QA] Add native PGO build and benchmark tooling - #97808

Open
chrispader wants to merge 60 commits into
Expensify:mainfrom
margelo:@chrispader/perf/pgo
Open

chrispader wants to merge 60 commits into
Expensify:mainfrom
margelo:@chrispader/perf/pgo

Conversation

@chrispader

@chrispader chrispader commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Native release builds currently lack a reproducible way to train and validate LLVM optimization profiles. This PR adds opt-in build, collection and benchmark tooling for Android and iOS, while leaving CI workflow activation to a separate PR.

Explanation of Change

The local tooling builds baseline, instrumented and optimized native apps, archives profiles and compares startup and journey measurements. The Android switches cover source-built React Native, Hermes and native utilities; the iOS switches cover the app and source-built CocoaPods targets.

The iOS corrections use compatible Clang, Swift and Hermes IR instrumentation, explicitly forward the Swift frontend flags, and build through Rock with quoted Xcode settings. Profiles carry the current ios-clang-swift-ir-v3 marker so earlier instrumentation formats must be recollected. The App dependency now points to the clean updated native PGO foundation instead of a revision without profiling hooks.

This PR changes no CI workflows. Separate evaluation tooling and report-only CI build on this foundation. The portable iOS corrections were exercised on a physical iPhone in a pinned precursor checkout; this branch has regression coverage but has not had a fresh native rebuild or an actual CI/store-export run. That local smoke run establishes no performance gain.

cc @mountiny @roryabraham

Fixed Issues

$ #98008
PROPOSAL: #98008

The tracking issue contains the proposal. Formal proposal approval remains pending.

MOBILE-EXPENSIFY: https://github.com/Expensify/Mobile-Expensify/pull/14046

Tests

  1. Check out the matching native foundation and follow the documented local PGO flow on physical Android and iOS devices. Build, verify and install an instrumented Release app.
  2. Sign into the approved heavy account and collect a fresh profile from that instrumented artifact. Confirm the iOS profile contains executed Swift and Hermes counters.
  3. Build the optimized app with that profile. Confirm it is uninstrumented, installs successfully and completes a fresh startup. Compare baseline and optimized measurements in both build orders when evaluating performance.
  4. Try a profile with the earlier iOS format marker. Confirm the tooling requests fresh collection instead of consuming it. Check for unexpected JavaScript errors during startup and the journey.
  • Verify that no errors appear in the JS console

Offline tests

  1. Complete profile collection before disconnecting the device. Confirm the installed app still starts with its existing offline behavior.
  2. Interrupt an authenticated training journey by disconnecting the device. Confirm that incomplete evidence is rejected before retrying with a fresh batch.

QA Steps

This PR changes profiling and build infrastructure. QA cannot establish compiler instrumentation or profile consumption through the staging app UI. Native engineers must repeat the documented physical-device checks before enabling the separate CI workflow.

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above

  • I wrote clear testing steps that cover the changes made in this PR

    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms

  • I ran the tests on all platforms & verified they passed on:

    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)

  • I verified any copy / text that was added to the app is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)

  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers

  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)

  • If new assets were added or existing ones were modified, I verified that:

    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.

  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)

  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.

  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.

  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:

    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:

    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.

  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

  • I followed proper code patterns (see Reviewing the code)

    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • I followed the guidelines as stated in the Review Guidelines

  • If a new CSS style is added I verified that:

    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))

Screenshots/Videos

No screenshots or videos are included. This change affects profiling and build tooling and adds no app UI.

@github-actions

github-actions Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
see 96 files with indirect coverage changes

@melvin-bot

melvin-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

@bernhardoj Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot requested review from flaviadefaria and removed request for a team October 12, 2026 18:30
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T18:49:05.973610Z 74f329c Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 74f329c841

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/pgo/android.ts Outdated
Comment thread scripts/pgo/android.ts Outdated
@mountiny

Copy link
Copy Markdown
Contributor

@chrispader what is the order in which the PRs need to be merged?

@chrispader

Copy link
Copy Markdown
Contributor Author

@chrispader what is the order in which the PRs need to be merged?

Posted the order here:

@chrispader chrispader changed the title [HOLD on native PGO foundation] [Task 1/5] [No QA] Add native PGO build and benchmark tooling [Task 1/5] [No QA] Add native PGO build and benchmark tooling Oct 13, 2026
@MelvinBot
MelvinBot requested a review from Julesssss October 13, 2026 15:55
@MelvinBot
MelvinBot requested a review from roryabraham October 13, 2026 15:55
@Julesssss Julesssss removed their assignment Oct 13, 2026
@roryabraham roryabraham removed their assignment Oct 14, 2026
@bernhardoj

Copy link
Copy Markdown
Contributor

@chrispader based on the order, I think this is still on hold?

@chrispader

Copy link
Copy Markdown
Contributor Author

@chrispader based on the order, I think this is still on hold?

@bernhardoj no this should be merged together with https://github.com/Expensify/Mobile-Expensify/pull/14046.

I've updated the merge order in the issue accordingly, to make it easier to understand

+ echo "EXPENSIFY_PGO_PROFILE is required when EXPENSIFY_PGO_MODE=use" >&2
+ exit 1
+ fi
+ pgo_compile_flags="-fprofile-use=${EXPENSIFY_PGO_PROFILE}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it expected that the pgo_linker_flags is not set for "use" mode here?

dispatch_once(&onceToken, ^{
CFNotificationCenterRef notificationCenter = CFNotificationCenterGetDarwinNotifyCenter();
CFNotificationCenterAddObserver(notificationCenter, NULL, HandlePGONotification, PGO_WRITE_NOTIFICATION, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
CFNotificationCenterAddObserver(notificationCenter, NULL, HandlePGONotification, PGO_CLEAR_NOTIFICATION, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notifications are registered even when EXPENSIFY_PGO_GENERATE is disabled.

}
if (result.status !== 0) {
const stderr = result.stderr.trim();
fail(stderr.length > 0 ? stderr : `${command} exited with status ${result.status ?? 'unknown'}.`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If stderr is truthy, we won't know what command fails.

@bernhardoj

Copy link
Copy Markdown
Contributor

@chrispader Can I test iOS without a release signing certificate?

@bernhardoj

Copy link
Copy Markdown
Contributor

I get this error when running scripts/pgo/pgo.ts android build-instrumented.

A problem was found with the configuration of task ':createReleaseApkListingFileRedirect' (type 'ListingFileRedirectTask').
  - In plugin 'com.android.internal.version-check' type 'com.android.build.gradle.internal.tasks.ListingFileRedirectTask' property 'listingFile' specifies file '/Users/bernhardoj/Documents/dev/freelance/Expensify/Mobile-Expensify/Android/build/outputs/apk/release/output-metadata.json' which doesn't exist.

Claude said:

Why the folder is missing: in Mobile-Expensify, the FullStory plugin moves the APK output to build/intermediates/.... The fullstoryRelease task then copies the final APK to build/outputs/apk/release (build.gradle:518-535). The PGO script skips FullStory with -x fullstoryRelease (android.ts:90-91), so nothing creates that folder.

Fix
Also skip that task. It's safe to skip because it only affects Android Studio. In scripts/pgo/android.ts:90-91:

       '-x',
       'fullstoryRelease',
       '-x',
       'createReleaseApkListingFileRedirect',

Comment thread tests/tooling/pgo.test.ts
});

it('reads the bootstrapped release application ID', () => {
// Given

@bernhardoj bernhardoj Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some tests missing Given When Then explanation

@bernhardoj

Copy link
Copy Markdown
Contributor

Startup benchmark results on Android:

Build Runs Average P50 P75 P90 P95 P99 Min Max
Release 20 1893.70 1902.00 1915.50 1952.30 1965.30 1985.06 1798.00 1990.00
PGO optimized 20 1824.05 1807.50 1864.25 1912.50 1930.85 2004.57 1724.00 2023.00
PGO improvement - 3.68% 4.97% 2.68% 2.04% 1.75% -0.98% 4.12% -1.66%

@github-actions

Copy link
Copy Markdown
Contributor

🚧 mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

Copy link
Copy Markdown
Contributor

🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
Built from App PR #97808 Mobile-Expensify PR Expensify/Mobile-Expensify#14046.

Android 🤖 iOS 🍎
❌ FAILED ❌ ❌ FAILED ❌
The QR code can't be generated, because the Android build failed The QR code can't be generated, because the iOS build failed
Web 🕸️
https://97808.pr-testing.expensify.com
Web

👀 View the workflow run that generated this build 👀

@mountiny mountiny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) Full pass over this PR and Mobile-Expensify#14046. The checks that fail closed are good: the iOS format marker, the all-4 Android profile check, no merge of partial journeys, and no automated sign-in. Line comments are inline. These blockers don't map to one line:

  1. No native build has run. This PR comes from a fork, so verifyHybridApp.yml skipped both HybridApp builds. The RN patch, the CMake changes, and RCTBootSplash.mm ship in production builds, so we need an AdHoc build on both platforms before merge.
  2. Merge order. Mobile-Expensify#14046 calls +[RCTBootSplash initializePGOProfileCollection], which only exists after this PR. If it lands first, the iOS HybridApp fails to compile. Order: this PR, then Mobile-Expensify#14046, then the submodule bump.
  3. iOS production gate. +1 to bernhardoj's comment. Mobile-Expensify#14046 calls this on every launch, and any process on the device can post Darwin notifications. Please wrap the observer registration in #if EXPENSIFY_PGO_GENERATE.
  4. Open threads. The proposal on the tracking issue still needs approval. bernhardoj's build failure, iOS signing question, and inline comments have no replies yet.

Comment thread scripts/pgo/android.ts
'-PreactNativeArchitectures=arm64-v8a',
`-PpgoMode=${pgoModes[kind]}`,
'-x',
'fullstoryRelease',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) build-instrumented fails on a clean checkout with createReleaseApkListingFileRedirect (bernhardoj's report). Skipping that task too fixes it:

Suggested change
'fullstoryRelease',
'fullstoryRelease',
'-x',
'createReleaseApkListingFileRedirect',


<receiver
android:name=".PgoProfileReceiver"
android:exported="true">

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) This receiver ships in production with no permission, so any app on the device can send it. One line locks it to adb: the shell user holds DUMP, and normal apps can't get it. Mobile-Expensify#14046 needs the same change.

Suggested change
android:exported="true">
android:exported="true"
android:permission="android.permission.DUMP">

}

System.loadLibrary("ExpensifyNitroUtils");
return writeProfiles(context.getCacheDir().getAbsolutePath());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) The PGO scripts only target HybridApp (org.me.mobiexpensifyg), so this standalone copy never runs. It also writes to getCacheDir(), which adb can't pull from a release build. The Mobile-Expensify copy uses getExternalCacheDir(). Can we drop the android/app changes, or make them match?


+ (void)initWithStoryboard:(NSString * _Nonnull)storyboardName
rootView:(UIView * _Nullable)rootView;
+ (void)initializePGOProfileCollection;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) Nit: this puts about 100 lines of profiling code in the boot splash module. A small ExpensifyPGO.mm would keep it separate and make the #if EXPENSIFY_PGO_GENERATE gate simpler.

OUTPUT_VARIABLE CLANG_RESOURCE_DIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(PGO_RUNTIME "${CLANG_RESOURCE_DIR}/lib/linux/libclang_rt.profile-aarch64-android.a")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) This hardcodes the aarch64 runtime, and so do the two copies in the RN patch. A generate build with the default ABIs will fail to link. Could Gradle reject any pgoMode other than off unless reactNativeArchitectures=arm64-v8a?

Comment thread scripts/pgo/ios.ts
rmSync(directory, {recursive: true, force: true});
}
}
run('/usr/bin/env', [...sourceBuildEnvironment(mode, profilePath), 'bundle', 'exec', 'pod', 'install', '--silent'], iosDirectory);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) This switches Mobile-Expensify's Pods to source builds, and nothing switches them back after the run. Please restore them, or call it out in the README.

Comment thread scripts/pgo/ios.ts
];
}
if (kind === 'optimized') {
const clangProfileFlags = `-fprofile-use=${profilePath} -Wno-error=profile-instr-unprofiled`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) Xcode splits OTHER_CFLAGS on spaces, so a profile path with a space breaks this flag (and the Swift flag below). pgoIOSRock.test.ts only checks Rock's parser, so it doesn't catch this. Please quote the path.

if (device.platform === 'android') {
device.fill('composer', `${token} draft`);
}
device.fill('composer', `${token}. Answered by Codex, instructed by Chris.`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) Every journey run posts this text into a real chat. Please drop the personal and tool names:

Suggested change
device.fill('composer', `${token}. Answered by Codex, instructed by Chris.`);
device.fill('composer', `${token}. Automated PGO journey message.`);

function assertSignedIn(nodes: JourneyNode[]): void {
const signInLabels = new Set(['Sign in', 'Email or phone number', 'Enter your email or phone number', 'Enter your magic code']);
if (nodes.some((node) => ['username', 'validateCode'].includes(node.identifier) || signInLabels.has(normalizeLabel(node.label)))) {
throw new Error('SIGN_IN_REQUIRED: Ask Chris to sign into the approved heavy account, then restart the journey. Automated sign-in is disabled.');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) This error names one person, and so do journeyWorkload.ts:74, journey.ts:44, and the README. Other engineers and CI will run this, so please say "the account owner" instead.

Comment thread scripts/pgo/JOURNEY.md

Start with three repetitions per platform. Use the recorded duration and resulting native counter coverage to adjust the workload; extra repetitions of the same data do not add new paths. Most activity here exercises Hermes, Fabric mounting, layout, text, native input, and scrolling. This trains the compiled native implementation used by JavaScript; it does not compile the application's JavaScript with LLVM. Avoid spending most of the run waiting on network responses or looping over trivial settings screens.

On September 23, 2026, the Android navigation-only run completed in 6 minutes 7 seconds. Two complete instrumented recordings passed in 7 minutes 1 second and 6 minutes 55 seconds, excluding preflight. Each sent two messages and exported four raw profiles; both recordings merged successfully, separately and together. These timings include automation overhead and the final account/preference check; they are not app performance measurements. The first recording's four profiles were also checked individually for nonzero native counters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Vit's agent) Nit: dated run logs go stale quickly. Could these move to the tracking issue?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants