From a1ec8fd10b7947ea68de3fe0cc5b6535b236fa4d Mon Sep 17 00:00:00 2001 From: chrispader Date: Mon, 10 Aug 2026 16:35:25 +0200 Subject: [PATCH 1/7] feat: add native span benchmark tooling --- .env.example | 2 + .gitignore | 1 + contributingGuides/BENCHMARKING.md | 55 +++ package.json | 1 + scripts/benchmarkAppStartup.ts | 440 ++++++++++++++++++++++ src/libs/telemetry/activeSpans.ts | 13 +- src/libs/telemetry/logBenchmarkSpanEnd.ts | 51 +++ tests/unit/ActiveSpansBenchmarkTest.ts | 35 ++ tests/unit/BenchmarkAppStartupTest.ts | 29 ++ tests/unit/BenchmarkSpanLoggerTest.ts | 20 + 10 files changed, 644 insertions(+), 3 deletions(-) create mode 100644 contributingGuides/BENCHMARKING.md create mode 100755 scripts/benchmarkAppStartup.ts create mode 100644 src/libs/telemetry/logBenchmarkSpanEnd.ts create mode 100644 tests/unit/ActiveSpansBenchmarkTest.ts create mode 100644 tests/unit/BenchmarkAppStartupTest.ts create mode 100644 tests/unit/BenchmarkSpanLoggerTest.ts diff --git a/.env.example b/.env.example index 78cc6d5b192c..c66b0e8d6635 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,8 @@ SKIP_ONBOARDING=false USE_WDYR=false USE_REDUX_DEVTOOLS=false CAPTURE_METRICS=false +# Comma-separated Sentry span names to emit as structured release benchmark logs. +EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS= ONYX_METRICS=false USE_THIRD_PARTY_SCRIPTS=false IS_EXPENSIFY_EMPLOYEE=false diff --git a/.gitignore b/.gitignore index e547a16b7ca4..e189c627f0d4 100644 --- a/.gitignore +++ b/.gitignore @@ -107,6 +107,7 @@ storybook-static # E2E test reports tests/e2e/results/ .reassure +.benchmarks/ # Temporary files created by Metro to check the health of the file watcher .metro-health-check* diff --git a/contributingGuides/BENCHMARKING.md b/contributingGuides/BENCHMARKING.md new file mode 100644 index 000000000000..9bf9133f9c90 --- /dev/null +++ b/contributingGuides/BENCHMARKING.md @@ -0,0 +1,55 @@ +# Native app benchmarks + +The native release bundle can emit structured completion events for selected manual Sentry spans. Benchmark logging is disabled unless a developer explicitly configures span names in the git-ignored root `.env` file. + +## Configure benchmark spans + +Add a comma-separated list of exact Sentry span names to `.env` before building the release app: + +```dotenv +EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS=ManualAppStartup,ManualAppStartupNetworkRequest +``` + +Rebuild the release app after changing the list. Enabled spans produce one flat, machine-readable line when they end successfully: + +```text +[EXPENSIFY_BENCHMARK] {"event":"span_end","span":"ManualAppStartup","durationMs":1234,"timestamp":1710000000000} +``` + +The app uses `console.warn` for this opt-in output because production bundles remove `console.log`, `console.info`, and `console.debug`. The Sentry console integration only forwards errors, so benchmark lines do not create Sentry log events or additional network traffic. A dedicated native logging bridge would avoid warning semantics, but would add native code solely for local tooling on both platforms. + +## Run the benchmark + +The benchmark runs one unmeasured warm-up followed by 20 measured cold-process launches by default. It prints each sample and summary statistics, and stores raw samples under the git-ignored `.benchmarks` directory. + +Android: + +```shell +nr benchmark-app-startup -- android ManualAppStartup 20 30 --device emulator-5554 +``` + +iOS physical device: + +```shell +nr benchmark-app-startup -- ios ManualAppStartup 20 30 --device "Developer's iPhone" +``` + +The positional arguments are platform, span name, measured run count, and timeout in seconds. Use `--app-id` for a nonstandard Android application ID or iOS bundle identifier, and `--output` to select another CSV path. + +### True-cold mode + +By default, each run terminates and relaunches the existing app process without clearing persisted state. Pass `--cold` to clear state before every launch. + +On Android, true-cold mode clears package data and resets compiled package state with `cmd package compile --reset`: + +```shell +nr benchmark-app-startup -- android ManualAppStartup --cold --device emulator-5554 +``` + +On iOS, clearing app data requires uninstalling and reinstalling the signed app, so `--app-path` is required: + +```shell +nr benchmark-app-startup -- ios ManualAppStartup --cold --device "Developer's iPhone" --app-path /path/to/Expensify.app +``` + +True-cold runs start with no authenticated account or persisted application state. Cold-process runs are usually more suitable for benchmarking authenticated startup flows. diff --git a/package.json b/package.json index e53ebdec1c36..235b9d1f1787 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "build": "ENV=production bun ./node_modules/.bin/rsbuild build --config config/rsbuild/rsbuild.config.ts && bun ./scripts/combine-web-sourcemaps.ts", "build-staging": "ENV=staging bun ./node_modules/.bin/rsbuild build --config config/rsbuild/rsbuild.config.ts && bun ./scripts/combine-web-sourcemaps.ts", "build-adhoc": "ENV=adhoc bun ./node_modules/.bin/rsbuild build --config config/rsbuild/rsbuild.config.ts && bun ./scripts/combine-web-sourcemaps.ts", + "benchmark-app-startup": "./scripts/benchmarkAppStartup.ts", "createDocsRoutes": "bun .github/scripts/createDocsRoutes.ts", "generateAllowedUrls": "bun .github/scripts/generateAllowedUrls.ts", "detectRedirectCycle": "bun .github/scripts/detectRedirectCycle.ts", diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts new file mode 100755 index 000000000000..c79e8b67af96 --- /dev/null +++ b/scripts/benchmarkAppStartup.ts @@ -0,0 +1,440 @@ +#!/usr/bin/env -S node --experimental-strip-types --disable-warning=MODULE_TYPELESS_PACKAGE_JSON +// cspell:ignore TYPELESS devicectl + +import type {TupleToUnion} from 'type-fest'; + +import CLI from 'expensify-common/CLI'; +import {spawn, spawnSync} from 'node:child_process'; +import {existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {dirname, join, resolve} from 'node:path'; +import process from 'node:process'; + +const PLATFORM_NAMES = ['android', 'ios'] as const; +const DEFAULT_RUNS = 20; +const DEFAULT_TIMEOUT_SECONDS = 30; +const RELAUNCH_DELAY_MS = 500; +const POLL_INTERVAL_MS = 250; +const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; +const MAX_CAPTURED_LOG_LENGTH = 1_000_000; + +type PlatformName = TupleToUnion; +type StartupMode = 'process' | 'cold'; +type BenchmarkLogEvent = { + event: 'span_end'; + span: string; + durationMs: number; + timestamp: number; +}; +type BenchmarkStats = { + runs: number; + average: number; + p50: number; + p75: number; + p90: number; + p95: number; + p99: number; + min: number; + max: number; +}; +type PlatformAdapter = { + name: PlatformName; + prepareStartup: (mode: StartupMode, appPath?: string) => Promise; + launchAndWait: (spanName: string, timeoutSeconds: number) => Promise; +}; + +const scriptPath = process.argv.at(1); +if (!scriptPath) { + throw new Error('Unable to resolve the benchmark script path.'); +} +const rootDirectory = resolve(dirname(resolve(scriptPath)), '..'); + +function fail(message: string): never { + throw new Error(message); +} + +function run(command: string, args: string[]): void { + const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'inherit'}); + if (result.error) { + fail(`Failed to run ${command}: ${result.error.message}`); + } + if (result.status !== 0) { + fail(`${command} exited with status ${result.status ?? 'unknown'}.`); + } +} + +function capture(command: string, args: string[]): string { + const result = spawnSync(command, args, {cwd: rootDirectory, encoding: 'utf8', maxBuffer: 100 * 1024 * 1024}); + if (result.error) { + fail(`Failed to run ${command}: ${result.error.message}`); + } + if (result.status !== 0) { + const stderr = result.stderr.trim(); + fail(stderr || `${command} exited with status ${result.status ?? 'unknown'}.`); + } + return result.stdout; +} + +function runAllowFailure(command: string, args: string[]): boolean { + const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'ignore'}); + return !result.error && result.status === 0; +} + +function sleep(milliseconds: number): Promise { + return new Promise((resolvePromise) => { + setTimeout(resolvePromise, milliseconds); + }); +} + +function parseChoice(value: string, choices: readonly T[], label: string): T { + const choice = choices.find((candidate) => candidate === value); + if (!choice) { + fail(`${label} must be one of: ${choices.join(', ')}. Received: ${value}`); + } + return choice; +} + +function parsePositiveInteger(value: string, label: string): number { + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed <= 0) { + fail(`${label} must be a positive integer. Received: ${value}`); + } + return parsed; +} + +function environmentString(name: string): string | undefined { + const value: unknown = process.env[name]; + return typeof value === 'string' && value.length > 0 ? value : undefined; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseBenchmarkLogEvents(output: string): BenchmarkLogEvent[] { + const events: BenchmarkLogEvent[] = []; + let offset = 0; + + while (offset < output.length) { + const tagIndex = output.indexOf(BENCHMARK_LOG_TAG, offset); + if (tagIndex < 0) { + break; + } + + const jsonStart = output.indexOf('{', tagIndex + BENCHMARK_LOG_TAG.length); + const jsonEnd = jsonStart < 0 ? -1 : output.indexOf('}', jsonStart); + if (jsonStart < 0 || jsonEnd < 0) { + break; + } + + offset = jsonEnd + 1; + try { + const event: unknown = JSON.parse(output.slice(jsonStart, jsonEnd + 1)); + if ( + isRecord(event) && + event.event === 'span_end' && + typeof event.span === 'string' && + typeof event.durationMs === 'number' && + Number.isFinite(event.durationMs) && + typeof event.timestamp === 'number' + ) { + events.push({event: 'span_end', span: event.span, durationMs: event.durationMs, timestamp: event.timestamp}); + } + } catch { + // Ignore unrelated or incomplete console output containing the benchmark tag. + } + } + + return events; +} + +function findBenchmarkDuration(output: string, spanName: string): number | undefined { + return parseBenchmarkLogEvents(output).findLast((event) => event.span === spanName)?.durationMs; +} + +function waitForBenchmarkProcess(command: string, args: string[], spanName: string, timeoutSeconds: number): Promise { + return new Promise((resolvePromise, reject) => { + const processHandle = spawn(command, args, {cwd: rootDirectory}); + let output = ''; + let settled = false; + let timeout: ReturnType; + + const finish = (result: {duration: number} | {error: Error}) => { + if (settled) { + return; + } + + settled = true; + clearTimeout(timeout); + processHandle.kill('SIGINT'); + if ('error' in result) { + reject(result.error); + return; + } + resolvePromise(result.duration); + }; + + const readOutput = (chunk: Buffer) => { + output = `${output}${chunk.toString()}`.slice(-MAX_CAPTURED_LOG_LENGTH); + const duration = findBenchmarkDuration(output, spanName); + if (duration !== undefined) { + finish({duration}); + } + }; + + timeout = setTimeout(() => finish({error: new Error(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${output}`)}), timeoutSeconds * 1000); + processHandle.stdout.on('data', readOutput); + processHandle.stderr.on('data', readOutput); + processHandle.on('error', (error) => finish({error})); + processHandle.on('exit', (code) => { + if (settled) { + return; + } + finish({error: new Error(`App launch exited with code ${code ?? 'unknown'} before ${spanName} completed.\n${output}`)}); + }); + }); +} + +function createAndroidAdapter(deviceIdentifier: string | undefined, appID: string): PlatformAdapter { + const adbArgs = (args: string[]) => (deviceIdentifier ? ['-s', deviceIdentifier, ...args] : args); + const adb = (args: string[]) => run('adb', adbArgs(args)); + const adbCapture = (args: string[]) => capture('adb', adbArgs(args)); + const activity = `${appID}/org.me.mobiexpensifyg.ExpensifyActivityBase`; + + return { + name: 'android', + prepareStartup: async (mode) => { + adb(['shell', 'am', 'force-stop', appID]); + if (mode === 'cold') { + adb(['shell', 'pm', 'clear', appID]); + adb(['shell', 'cmd', 'package', 'compile', '--reset', appID]); + } + adb(['logcat', '-c']); + await sleep(RELAUNCH_DELAY_MS); + }, + launchAndWait: async (spanName, timeoutSeconds) => { + adb(['shell', 'am', 'start', '-W', '-n', activity]); + const deadline = Date.now() + timeoutSeconds * 1000; + let logs = ''; + while (Date.now() < deadline) { + logs = adbCapture(['logcat', '-d', '-v', 'raw']); + const duration = findBenchmarkDuration(logs, spanName); + if (duration !== undefined) { + return duration; + } + await sleep(POLL_INTERVAL_MS); + } + fail(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${logs}`); + }, + }; +} + +function resolveIosDevice(configuredDevice: string | undefined): string { + if (configuredDevice) { + return configuredDevice; + } + + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-devices-')); + const jsonPath = join(temporaryDirectory, 'devices.json'); + try { + run('xcrun', ['devicectl', 'list', 'devices', '--json-output', jsonPath]); + const response: unknown = JSON.parse(readFileSync(jsonPath, 'utf8')); + if (!isRecord(response) || !isRecord(response.result) || !Array.isArray(response.result.devices)) { + fail('CoreDevice returned an unexpected device-list response.'); + } + + const devices = response.result.devices.flatMap((device) => { + if (!isRecord(device) || !isRecord(device.hardwareProperties) || !isRecord(device.deviceProperties)) { + return []; + } + const {hardwareProperties, deviceProperties} = device; + if ( + hardwareProperties.platform !== 'iOS' || + hardwareProperties.reality !== 'physical' || + deviceProperties.bootState !== 'booted' || + typeof hardwareProperties.udid !== 'string' || + typeof deviceProperties.name !== 'string' + ) { + return []; + } + return [{name: deviceProperties.name, udid: hardwareProperties.udid}]; + }); + if (devices.length !== 1) { + fail(`Expected one booted physical iOS device, found ${devices.length}. Use --device to select one.`); + } + const device = devices.at(0); + if (!device) { + fail('Unable to resolve the connected iOS device.'); + } + console.log(`Using iOS device ${device.name} (${device.udid}).`); + return device.udid; + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } +} + +function createIosAdapter(deviceIdentifier: string | undefined, appID: string): PlatformAdapter { + const device = resolveIosDevice(deviceIdentifier ?? environmentString('IOS_DEVICE_ID')); + const terminate = () => runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, appID]); + + return { + name: 'ios', + prepareStartup: async (mode, appPath) => { + terminate(); + if (mode === 'cold') { + if (!appPath) { + fail('iOS true-cold startup requires --app-path so the app can be reinstalled after clearing its data.'); + } + if (!existsSync(appPath)) { + fail(`iOS app not found at ${appPath}.`); + } + runAllowFailure('xcrun', ['devicectl', 'device', 'uninstall', 'app', '--device', device, appID]); + run('xcrun', ['devicectl', 'device', 'install', 'app', '--device', device, appPath]); + } + await sleep(RELAUNCH_DELAY_MS); + }, + launchAndWait: (spanName, timeoutSeconds) => + waitForBenchmarkProcess('xcrun', ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', '--console', appID], spanName, timeoutSeconds), + }; +} + +function percentile(sortedValues: number[], fraction: number): number { + const position = (sortedValues.length - 1) * fraction; + const lowerIndex = Math.floor(position); + const upperIndex = Math.ceil(position); + const remainder = position - lowerIndex; + const lowerValue = sortedValues.at(lowerIndex); + const upperValue = sortedValues.at(upperIndex); + if (lowerValue === undefined || upperValue === undefined) { + fail('Cannot calculate a percentile without benchmark samples.'); + } + return lowerValue + remainder * (upperValue - lowerValue); +} + +function benchmarkStats(samples: number[]): BenchmarkStats { + const sortedValues = samples.toSorted((left, right) => left - right); + const min = sortedValues.at(0); + const max = sortedValues.at(-1); + if (min === undefined || max === undefined) { + fail('No benchmark samples were recorded.'); + } + + return { + runs: samples.length, + average: samples.reduce((sum, value) => sum + value, 0) / samples.length, + p50: percentile(sortedValues, 0.5), + p75: percentile(sortedValues, 0.75), + p90: percentile(sortedValues, 0.9), + p95: percentile(sortedValues, 0.95), + p99: percentile(sortedValues, 0.99), + min, + max, + }; +} + +async function measureStartup(adapter: PlatformAdapter, mode: StartupMode, appPath: string | undefined, spanName: string, timeoutSeconds: number): Promise { + await adapter.prepareStartup(mode, appPath); + return adapter.launchAndWait(spanName, timeoutSeconds); +} + +async function benchmarkStartups( + adapter: PlatformAdapter, + mode: StartupMode, + appPath: string | undefined, + spanName: string, + runs: number, + timeoutSeconds: number, + outputPath: string, +): Promise { + console.log(`Running one unmeasured ${mode === 'cold' ? 'true-cold' : 'cold-process'} warm-up startup.`); + await measureStartup(adapter, mode, appPath, spanName, timeoutSeconds); + + const samples: number[] = []; + for (let runNumber = 1; runNumber <= runs; runNumber += 1) { + const duration = await measureStartup(adapter, mode, appPath, spanName, timeoutSeconds); + samples.push(duration); + console.log(`Run ${runNumber}/${runs}: ${duration}ms`); + } + + mkdirSync(dirname(outputPath), {recursive: true}); + writeFileSync(outputPath, ['run,duration_ms', ...samples.map((duration, index) => `${index + 1},${duration}`), ''].join('\n')); + console.table([Object.fromEntries(Object.entries(benchmarkStats(samples)).map(([key, value]) => [key, value.toFixed(2)]))]); + console.log(`Recorded ${runs} samples in ${outputPath}`); +} + +async function main(): Promise { + /* eslint-disable @typescript-eslint/naming-convention */ + const cli = new CLI({ + positionalArgs: [ + { + name: 'platform', + description: `Native platform to benchmark (${PLATFORM_NAMES.join(', ')})`, + parse: (value): PlatformName => parseChoice(value, PLATFORM_NAMES, 'Platform'), + }, + { + name: 'span', + description: 'Whitelisted Sentry span name to benchmark', + default: 'ManualAppStartup', + }, + { + name: 'runs', + description: 'Number of measured startup runs', + default: DEFAULT_RUNS, + parse: (value) => parsePositiveInteger(value, 'Run count'), + }, + { + name: 'timeout', + description: 'Seconds to wait for the benchmark span', + default: DEFAULT_TIMEOUT_SECONDS, + parse: (value) => parsePositiveInteger(value, 'Timeout'), + }, + ], + namedArgs: { + device: { + description: 'adb serial on Android, or CoreDevice identifier, UDID, serial number, or name on iOS', + required: false, + }, + 'app-id': { + description: 'Application ID or bundle identifier', + required: false, + }, + 'app-path': { + description: 'Path to the signed iOS .app; required with --cold on iOS', + required: false, + }, + output: { + description: 'CSV output path', + required: false, + }, + }, + flags: { + cold: { + description: 'Run true-cold starts by clearing app data; default only terminates and relaunches the process', + }, + }, + }); + /* eslint-enable @typescript-eslint/naming-convention */ + + const platformName = parseChoice(String(cli.positionalArgs.platform), PLATFORM_NAMES, 'Platform'); + const spanName = String(cli.positionalArgs.span); + const runs = Number(cli.positionalArgs.runs); + const timeoutSeconds = Number(cli.positionalArgs.timeout); + const mode: StartupMode = cli.flags.cold ? 'cold' : 'process'; + const defaultAppID = platformName === 'android' ? 'org.me.mobiexpensifyg' : 'com.expensify.expensifylite'; + const appID = cli.namedArgs['app-id'] ?? defaultAppID; + const appPath = cli.namedArgs['app-path'] ?? environmentString('IOS_APP_PATH'); + const safeSpanName = spanName.replaceAll(/[^a-zA-Z0-9_-]/g, '-'); + const outputPath = resolve(cli.namedArgs.output ?? join(rootDirectory, '.benchmarks', `${platformName}-${safeSpanName}-${mode}.csv`)); + const adapter = platformName === 'android' ? createAndroidAdapter(cli.namedArgs.device, appID) : createIosAdapter(cli.namedArgs.device, appID); + + await benchmarkStartups(adapter, mode, appPath, spanName, runs, timeoutSeconds, outputPath); +} + +if (scriptPath.endsWith('benchmarkAppStartup.ts')) { + main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }); +} + +export {benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile}; diff --git a/src/libs/telemetry/activeSpans.ts b/src/libs/telemetry/activeSpans.ts index e0fd5715a6cb..8988e09a5fbd 100644 --- a/src/libs/telemetry/activeSpans.ts +++ b/src/libs/telemetry/activeSpans.ts @@ -6,8 +6,11 @@ import {SPAN_STATUS_OK} from '@sentry/core'; import * as Sentry from '@sentry/react-native'; import {AppState} from 'react-native'; +import logBenchmarkSpanEnd from './logBenchmarkSpanEnd'; + type ActiveSpanEntry = { span: ReturnType; + spanName: string; startTimeForLog: number; }; @@ -33,7 +36,7 @@ function startSpan(spanId: string, options: StartSpanOptions) { startTimeForLog = performance.now(); } - activeSpans.set(spanId, {span, startTimeForLog}); + activeSpans.set(spanId, {span, spanName: options.name, startTimeForLog}); return span; } @@ -44,10 +47,14 @@ function endSpan(spanId: string) { if (!entry) { return; } - const {span, startTimeForLog} = entry; + const {span, spanName, startTimeForLog} = entry; const now = performance.now(); const durationMs = Math.round(now - startTimeForLog); - console.debug(`[Sentry][${spanId}] Ending span (${durationMs}ms)`, {spanId, durationMs, timestamp: now, attributes: Sentry.spanToJSON(span).data}); + const attributes = Sentry.spanToJSON(span).data ?? {}; + console.debug(`[Sentry][${spanId}] Ending span (${durationMs}ms)`, {spanId, durationMs, timestamp: now, attributes}); + if (attributes[CONST.TELEMETRY.ATTRIBUTE_CANCELED] !== true) { + logBenchmarkSpanEnd(spanName, durationMs); + } span.setStatus({code: SPAN_STATUS_OK}); span.setAttribute(CONST.TELEMETRY.ATTRIBUTE_FINISHED_MANUALLY, true); diff --git a/src/libs/telemetry/logBenchmarkSpanEnd.ts b/src/libs/telemetry/logBenchmarkSpanEnd.ts new file mode 100644 index 000000000000..6b6a76f62c31 --- /dev/null +++ b/src/libs/telemetry/logBenchmarkSpanEnd.ts @@ -0,0 +1,51 @@ +const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; +const configuredSpanNames: unknown = process.env.EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS; + +type BenchmarkSpanEnd = { + event: 'span_end'; + span: string; + durationMs: number; + timestamp: number; +}; + +function parseBenchmarkSpanNames(value: unknown): string[] { + if (typeof value !== 'string') { + return []; + } + + return [ + ...new Set( + value + .split(',') + .map((spanName) => spanName.trim()) + .filter(Boolean), + ), + ]; +} + +function createBenchmarkSpanEndLogger(spanNames: string[], writeLog: (message: string) => void): (spanName: string, durationMs: number) => void { + const enabledSpanNames = new Set(spanNames); + + return (spanName, durationMs) => { + if (!enabledSpanNames.has(spanName)) { + return; + } + + const event: BenchmarkSpanEnd = { + event: 'span_end', + span: spanName, + durationMs, + timestamp: Date.now(), + }; + writeLog(`${BENCHMARK_LOG_TAG} ${JSON.stringify(event)}`); + }; +} + +const logBenchmarkSpanEnd = createBenchmarkSpanEndLogger(parseBenchmarkSpanNames(configuredSpanNames), (message) => { + // Production builds strip console.info/debug/log. Warnings are retained and are not forwarded by the app's Sentry console integration. + // eslint-disable-next-line no-console + console.warn(message); +}); + +export {BENCHMARK_LOG_TAG, createBenchmarkSpanEndLogger, parseBenchmarkSpanNames}; +export default logBenchmarkSpanEnd; diff --git a/tests/unit/ActiveSpansBenchmarkTest.ts b/tests/unit/ActiveSpansBenchmarkTest.ts new file mode 100644 index 000000000000..a061bb4e1ab9 --- /dev/null +++ b/tests/unit/ActiveSpansBenchmarkTest.ts @@ -0,0 +1,35 @@ +import {endSpan, startSpan} from '@libs/telemetry/activeSpans'; + +const mockLogBenchmarkSpanEnd = jest.fn(); + +jest.mock('@libs/telemetry/logBenchmarkSpanEnd', () => ({ + __esModule: true, + default: (...args: unknown[]) => { + mockLogBenchmarkSpanEnd(...args); + }, +})); + +jest.mock('@sentry/react-native', () => ({ + startInactiveSpan: () => ({ + setAttribute: jest.fn(), + setStatus: jest.fn(), + end: jest.fn(), + }), + spanToJSON: () => ({data: {}}), +})); + +afterEach(() => { + jest.restoreAllMocks(); + mockLogBenchmarkSpanEnd.mockClear(); +}); + +describe('activeSpans benchmark logging', () => { + it('logs the Sentry span name instead of its unique tracking ID', () => { + jest.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValueOnce(250); + + startSpan('ManualOpenReport_123', {name: 'ManualOpenReport'}); + endSpan('ManualOpenReport_123'); + + expect(mockLogBenchmarkSpanEnd).toHaveBeenCalledWith('ManualOpenReport', 150); + }); +}); diff --git a/tests/unit/BenchmarkAppStartupTest.ts b/tests/unit/BenchmarkAppStartupTest.ts new file mode 100644 index 000000000000..b7fa5ab85827 --- /dev/null +++ b/tests/unit/BenchmarkAppStartupTest.ts @@ -0,0 +1,29 @@ +import {benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; + +describe('benchmarkAppStartup', () => { + it('parses structured benchmark logs among platform output', () => { + const output = [ + 'unrelated log', + `'[EXPENSIFY_BENCHMARK] {"event":"span_end","span":"ManualOpenReport","durationMs":125,"timestamp":1000}'`, + '[EXPENSIFY_BENCHMARK] {"event":"span_end","span":"ManualAppStartup","durationMs":500,"timestamp":2000}', + ].join('\n'); + + expect(parseBenchmarkLogEvents(output)).toHaveLength(2); + expect(findBenchmarkDuration(output, 'ManualAppStartup')).toBe(500); + }); + + it('calculates interpolated percentiles and summary statistics', () => { + expect(percentile([100, 200, 300, 400], 0.75)).toBe(325); + expect(benchmarkStats([300, 100, 200])).toEqual({ + runs: 3, + average: 200, + p50: 200, + p75: 250, + p90: 280, + p95: 290, + p99: 298, + min: 100, + max: 300, + }); + }); +}); diff --git a/tests/unit/BenchmarkSpanLoggerTest.ts b/tests/unit/BenchmarkSpanLoggerTest.ts new file mode 100644 index 000000000000..3e4104dbcaed --- /dev/null +++ b/tests/unit/BenchmarkSpanLoggerTest.ts @@ -0,0 +1,20 @@ +import {BENCHMARK_LOG_TAG, createBenchmarkSpanEndLogger, parseBenchmarkSpanNames} from '@libs/telemetry/logBenchmarkSpanEnd'; + +describe('benchmark span logging', () => { + it('parses and deduplicates configured span names', () => { + expect(parseBenchmarkSpanNames(' ManualAppStartup,ManualOpenReport,ManualAppStartup, ')).toEqual(['ManualAppStartup', 'ManualOpenReport']); + expect(parseBenchmarkSpanNames(undefined)).toEqual([]); + }); + + it('writes a structured event only for enabled spans', () => { + jest.spyOn(Date, 'now').mockReturnValue(1_234); + const writeLog = jest.fn(); + const logSpanEnd = createBenchmarkSpanEndLogger(['ManualAppStartup'], writeLog); + + logSpanEnd('ManualOpenReport', 100); + logSpanEnd('ManualAppStartup', 250); + + expect(writeLog).toHaveBeenCalledTimes(1); + expect(writeLog).toHaveBeenCalledWith(`${BENCHMARK_LOG_TAG} ${JSON.stringify({event: 'span_end', span: 'ManualAppStartup', durationMs: 250, timestamp: 1_234})}`); + }); +}); From 65641f65e94a036b903e422edf76d72cac96666f Mon Sep 17 00:00:00 2001 From: chrispader Date: Mon, 10 Aug 2026 16:57:43 +0200 Subject: [PATCH 2/7] refactor: share native startup benchmark adapters --- contributingGuides/BENCHMARKING.md | 32 ++- package.json | 4 + scripts/benchmarkAppStartup.ts | 357 +++++--------------------- scripts/lib/nativeAppBenchmark.ts | 288 +++++++++++++++++++++ tests/unit/BenchmarkAppStartupTest.ts | 33 ++- 5 files changed, 422 insertions(+), 292 deletions(-) create mode 100644 scripts/lib/nativeAppBenchmark.ts diff --git a/contributingGuides/BENCHMARKING.md b/contributingGuides/BENCHMARKING.md index 9bf9133f9c90..910736acd803 100644 --- a/contributingGuides/BENCHMARKING.md +++ b/contributingGuides/BENCHMARKING.md @@ -1,3 +1,5 @@ + + # Native app benchmarks The native release bundle can emit structured completion events for selected manual Sentry spans. Benchmark logging is disabled unless a developer explicitly configures span names in the git-ignored root `.env` file. @@ -25,16 +27,36 @@ The benchmark runs one unmeasured warm-up followed by 20 measured cold-process l Android: ```shell -nr benchmark-app-startup -- android ManualAppStartup 20 30 --device emulator-5554 +nr benchmark-app-startup -- android 20 30 --span ManualAppStartup --device emulator-5554 ``` iOS physical device: ```shell -nr benchmark-app-startup -- ios ManualAppStartup 20 30 --device "Developer's iPhone" +nr benchmark-app-startup -- ios 20 30 --span ManualAppStartup --device "Developer's iPhone" ``` -The positional arguments are platform, span name, measured run count, and timeout in seconds. Use `--app-id` for a nonstandard Android application ID or iOS bundle identifier, and `--output` to select another CSV path. +The positional arguments are platform, measured run count, and timeout in seconds. Use `--span` to measure any other span included in `EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS`, `--app-id` for a nonstandard Android application ID or iOS bundle identifier, and `--output` to select another CSV path. + +The script also exports `benchmarkAppStartups` and `benchmarkStartups`. Other local tooling, such as the PGO workflow, can install an artifact and invoke the same benchmark implementation. The lower-level Android and iOS process tooling lives in `scripts/lib/nativeAppBenchmark.ts` so callers do not need to duplicate `adb` or `xcrun devicectl` behavior. + +For example, a PGO script can install each artifact and call `benchmarkAppStartups` with its platform, device, bundle identifier, output path, and span name. This keeps artifact building and installation in the PGO workflow while sharing all startup measurement and platform-device behavior. + +```ts +import {benchmarkAppStartups} from '#benchmark-app-startup'; + +await benchmarkAppStartups({ + platform: 'android', + rootDirectory, + deviceIdentifier, + appID: 'org.me.mobiexpensifyg', + mode: 'process', + spanName: 'ManualAppStartup', + runs, + timeoutSeconds, + outputPath, +}); +``` ### True-cold mode @@ -43,13 +65,13 @@ By default, each run terminates and relaunches the existing app process without On Android, true-cold mode clears package data and resets compiled package state with `cmd package compile --reset`: ```shell -nr benchmark-app-startup -- android ManualAppStartup --cold --device emulator-5554 +nr benchmark-app-startup -- android --span ManualAppStartup --cold --device emulator-5554 ``` On iOS, clearing app data requires uninstalling and reinstalling the signed app, so `--app-path` is required: ```shell -nr benchmark-app-startup -- ios ManualAppStartup --cold --device "Developer's iPhone" --app-path /path/to/Expensify.app +nr benchmark-app-startup -- ios --span ManualAppStartup --cold --device "Developer's iPhone" --app-path /path/to/Expensify.app ``` True-cold runs start with no authenticated account or persisted application state. Cold-process runs are usually more suitable for benchmarking authenticated startup flows. diff --git a/package.json b/package.json index 235b9d1f1787..4e14cd155119 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,10 @@ "workspaces": [ "server/victory-chart-renderer" ], + "imports": { + "#benchmark-app-startup": "./scripts/benchmarkAppStartup.ts", + "#native-app-benchmark": "./scripts/lib/nativeAppBenchmark.ts" + }, "scripts": { "i-standalone": "STANDALONE_NEW_DOT=true npm i", "install-standalone": "STANDALONE_NEW_DOT=true npm install", diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts index c79e8b67af96..b1b0702d79ff 100755 --- a/scripts/benchmarkAppStartup.ts +++ b/scripts/benchmarkAppStartup.ts @@ -1,31 +1,19 @@ #!/usr/bin/env -S node --experimental-strip-types --disable-warning=MODULE_TYPELESS_PACKAGE_JSON -// cspell:ignore TYPELESS devicectl - -import type {TupleToUnion} from 'type-fest'; +// cspell:ignore TYPELESS import CLI from 'expensify-common/CLI'; -import {spawn, spawnSync} from 'node:child_process'; -import {existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs'; -import {tmpdir} from 'node:os'; +import {mkdirSync, writeFileSync} from 'node:fs'; import {dirname, join, resolve} from 'node:path'; import process from 'node:process'; -const PLATFORM_NAMES = ['android', 'ios'] as const; +import type {NativeAppBenchmarkAdapter, PlatformName, StartupMode} from '#native-app-benchmark'; + +import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents} from '#native-app-benchmark'; + +const DEFAULT_SPAN_NAME = 'ManualAppStartup'; const DEFAULT_RUNS = 20; const DEFAULT_TIMEOUT_SECONDS = 30; -const RELAUNCH_DELAY_MS = 500; -const POLL_INTERVAL_MS = 250; -const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; -const MAX_CAPTURED_LOG_LENGTH = 1_000_000; -type PlatformName = TupleToUnion; -type StartupMode = 'process' | 'cold'; -type BenchmarkLogEvent = { - event: 'span_end'; - span: string; - durationMs: number; - timestamp: number; -}; type BenchmarkStats = { runs: number; average: number; @@ -37,55 +25,34 @@ type BenchmarkStats = { min: number; max: number; }; -type PlatformAdapter = { - name: PlatformName; - prepareStartup: (mode: StartupMode, appPath?: string) => Promise; - launchAndWait: (spanName: string, timeoutSeconds: number) => Promise; +type BenchmarkStartupsOptions = { + mode: StartupMode; + spanName: string; + runs: number; + timeoutSeconds: number; + outputPath: string; + appPath?: string; +}; +type BenchmarkAppStartupsOptions = BenchmarkStartupsOptions & { + platform: PlatformName; + rootDirectory: string; + appID: string; + deviceIdentifier?: string; +}; +type BenchmarkResult = { + samples: number[]; + stats: BenchmarkStats; + outputPath: string; }; const scriptPath = process.argv.at(1); -if (!scriptPath) { - throw new Error('Unable to resolve the benchmark script path.'); -} -const rootDirectory = resolve(dirname(resolve(scriptPath)), '..'); +const isDirectRun = scriptPath?.endsWith('benchmarkAppStartup.ts') ?? false; +const rootDirectory = scriptPath && isDirectRun ? resolve(dirname(resolve(scriptPath)), '..') : process.cwd(); function fail(message: string): never { throw new Error(message); } -function run(command: string, args: string[]): void { - const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'inherit'}); - if (result.error) { - fail(`Failed to run ${command}: ${result.error.message}`); - } - if (result.status !== 0) { - fail(`${command} exited with status ${result.status ?? 'unknown'}.`); - } -} - -function capture(command: string, args: string[]): string { - const result = spawnSync(command, args, {cwd: rootDirectory, encoding: 'utf8', maxBuffer: 100 * 1024 * 1024}); - if (result.error) { - fail(`Failed to run ${command}: ${result.error.message}`); - } - if (result.status !== 0) { - const stderr = result.stderr.trim(); - fail(stderr || `${command} exited with status ${result.status ?? 'unknown'}.`); - } - return result.stdout; -} - -function runAllowFailure(command: string, args: string[]): boolean { - const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'ignore'}); - return !result.error && result.status === 0; -} - -function sleep(milliseconds: number): Promise { - return new Promise((resolvePromise) => { - setTimeout(resolvePromise, milliseconds); - }); -} - function parseChoice(value: string, choices: readonly T[], label: string): T { const choice = choices.find((candidate) => candidate === value); if (!choice) { @@ -107,197 +74,6 @@ function environmentString(name: string): string | undefined { return typeof value === 'string' && value.length > 0 ? value : undefined; } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function parseBenchmarkLogEvents(output: string): BenchmarkLogEvent[] { - const events: BenchmarkLogEvent[] = []; - let offset = 0; - - while (offset < output.length) { - const tagIndex = output.indexOf(BENCHMARK_LOG_TAG, offset); - if (tagIndex < 0) { - break; - } - - const jsonStart = output.indexOf('{', tagIndex + BENCHMARK_LOG_TAG.length); - const jsonEnd = jsonStart < 0 ? -1 : output.indexOf('}', jsonStart); - if (jsonStart < 0 || jsonEnd < 0) { - break; - } - - offset = jsonEnd + 1; - try { - const event: unknown = JSON.parse(output.slice(jsonStart, jsonEnd + 1)); - if ( - isRecord(event) && - event.event === 'span_end' && - typeof event.span === 'string' && - typeof event.durationMs === 'number' && - Number.isFinite(event.durationMs) && - typeof event.timestamp === 'number' - ) { - events.push({event: 'span_end', span: event.span, durationMs: event.durationMs, timestamp: event.timestamp}); - } - } catch { - // Ignore unrelated or incomplete console output containing the benchmark tag. - } - } - - return events; -} - -function findBenchmarkDuration(output: string, spanName: string): number | undefined { - return parseBenchmarkLogEvents(output).findLast((event) => event.span === spanName)?.durationMs; -} - -function waitForBenchmarkProcess(command: string, args: string[], spanName: string, timeoutSeconds: number): Promise { - return new Promise((resolvePromise, reject) => { - const processHandle = spawn(command, args, {cwd: rootDirectory}); - let output = ''; - let settled = false; - let timeout: ReturnType; - - const finish = (result: {duration: number} | {error: Error}) => { - if (settled) { - return; - } - - settled = true; - clearTimeout(timeout); - processHandle.kill('SIGINT'); - if ('error' in result) { - reject(result.error); - return; - } - resolvePromise(result.duration); - }; - - const readOutput = (chunk: Buffer) => { - output = `${output}${chunk.toString()}`.slice(-MAX_CAPTURED_LOG_LENGTH); - const duration = findBenchmarkDuration(output, spanName); - if (duration !== undefined) { - finish({duration}); - } - }; - - timeout = setTimeout(() => finish({error: new Error(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${output}`)}), timeoutSeconds * 1000); - processHandle.stdout.on('data', readOutput); - processHandle.stderr.on('data', readOutput); - processHandle.on('error', (error) => finish({error})); - processHandle.on('exit', (code) => { - if (settled) { - return; - } - finish({error: new Error(`App launch exited with code ${code ?? 'unknown'} before ${spanName} completed.\n${output}`)}); - }); - }); -} - -function createAndroidAdapter(deviceIdentifier: string | undefined, appID: string): PlatformAdapter { - const adbArgs = (args: string[]) => (deviceIdentifier ? ['-s', deviceIdentifier, ...args] : args); - const adb = (args: string[]) => run('adb', adbArgs(args)); - const adbCapture = (args: string[]) => capture('adb', adbArgs(args)); - const activity = `${appID}/org.me.mobiexpensifyg.ExpensifyActivityBase`; - - return { - name: 'android', - prepareStartup: async (mode) => { - adb(['shell', 'am', 'force-stop', appID]); - if (mode === 'cold') { - adb(['shell', 'pm', 'clear', appID]); - adb(['shell', 'cmd', 'package', 'compile', '--reset', appID]); - } - adb(['logcat', '-c']); - await sleep(RELAUNCH_DELAY_MS); - }, - launchAndWait: async (spanName, timeoutSeconds) => { - adb(['shell', 'am', 'start', '-W', '-n', activity]); - const deadline = Date.now() + timeoutSeconds * 1000; - let logs = ''; - while (Date.now() < deadline) { - logs = adbCapture(['logcat', '-d', '-v', 'raw']); - const duration = findBenchmarkDuration(logs, spanName); - if (duration !== undefined) { - return duration; - } - await sleep(POLL_INTERVAL_MS); - } - fail(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${logs}`); - }, - }; -} - -function resolveIosDevice(configuredDevice: string | undefined): string { - if (configuredDevice) { - return configuredDevice; - } - - const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-devices-')); - const jsonPath = join(temporaryDirectory, 'devices.json'); - try { - run('xcrun', ['devicectl', 'list', 'devices', '--json-output', jsonPath]); - const response: unknown = JSON.parse(readFileSync(jsonPath, 'utf8')); - if (!isRecord(response) || !isRecord(response.result) || !Array.isArray(response.result.devices)) { - fail('CoreDevice returned an unexpected device-list response.'); - } - - const devices = response.result.devices.flatMap((device) => { - if (!isRecord(device) || !isRecord(device.hardwareProperties) || !isRecord(device.deviceProperties)) { - return []; - } - const {hardwareProperties, deviceProperties} = device; - if ( - hardwareProperties.platform !== 'iOS' || - hardwareProperties.reality !== 'physical' || - deviceProperties.bootState !== 'booted' || - typeof hardwareProperties.udid !== 'string' || - typeof deviceProperties.name !== 'string' - ) { - return []; - } - return [{name: deviceProperties.name, udid: hardwareProperties.udid}]; - }); - if (devices.length !== 1) { - fail(`Expected one booted physical iOS device, found ${devices.length}. Use --device to select one.`); - } - const device = devices.at(0); - if (!device) { - fail('Unable to resolve the connected iOS device.'); - } - console.log(`Using iOS device ${device.name} (${device.udid}).`); - return device.udid; - } finally { - rmSync(temporaryDirectory, {recursive: true, force: true}); - } -} - -function createIosAdapter(deviceIdentifier: string | undefined, appID: string): PlatformAdapter { - const device = resolveIosDevice(deviceIdentifier ?? environmentString('IOS_DEVICE_ID')); - const terminate = () => runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, appID]); - - return { - name: 'ios', - prepareStartup: async (mode, appPath) => { - terminate(); - if (mode === 'cold') { - if (!appPath) { - fail('iOS true-cold startup requires --app-path so the app can be reinstalled after clearing its data.'); - } - if (!existsSync(appPath)) { - fail(`iOS app not found at ${appPath}.`); - } - runAllowFailure('xcrun', ['devicectl', 'device', 'uninstall', 'app', '--device', device, appID]); - run('xcrun', ['devicectl', 'device', 'install', 'app', '--device', device, appPath]); - } - await sleep(RELAUNCH_DELAY_MS); - }, - launchAndWait: (spanName, timeoutSeconds) => - waitForBenchmarkProcess('xcrun', ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', '--console', appID], spanName, timeoutSeconds), - }; -} - function percentile(sortedValues: number[], fraction: number): number { const position = (sortedValues.length - 1) * fraction; const lowerIndex = Math.floor(position); @@ -332,34 +108,33 @@ function benchmarkStats(samples: number[]): BenchmarkStats { }; } -async function measureStartup(adapter: PlatformAdapter, mode: StartupMode, appPath: string | undefined, spanName: string, timeoutSeconds: number): Promise { - await adapter.prepareStartup(mode, appPath); - return adapter.launchAndWait(spanName, timeoutSeconds); +async function measureStartup(adapter: NativeAppBenchmarkAdapter, options: Omit): Promise { + await adapter.prepareStartup(options.mode, options.appPath); + return adapter.launchAndWait(options.spanName, options.timeoutSeconds); } -async function benchmarkStartups( - adapter: PlatformAdapter, - mode: StartupMode, - appPath: string | undefined, - spanName: string, - runs: number, - timeoutSeconds: number, - outputPath: string, -): Promise { - console.log(`Running one unmeasured ${mode === 'cold' ? 'true-cold' : 'cold-process'} warm-up startup.`); - await measureStartup(adapter, mode, appPath, spanName, timeoutSeconds); +async function benchmarkStartups(adapter: NativeAppBenchmarkAdapter, options: BenchmarkStartupsOptions): Promise { + console.log(`Running one unmeasured ${options.mode === 'cold' ? 'true-cold' : 'cold-process'} warm-up startup for ${options.spanName}.`); + await measureStartup(adapter, options); const samples: number[] = []; - for (let runNumber = 1; runNumber <= runs; runNumber += 1) { - const duration = await measureStartup(adapter, mode, appPath, spanName, timeoutSeconds); + for (let runNumber = 1; runNumber <= options.runs; runNumber += 1) { + const duration = await measureStartup(adapter, options); samples.push(duration); - console.log(`Run ${runNumber}/${runs}: ${duration}ms`); + console.log(`Run ${runNumber}/${options.runs}: ${duration}ms`); } - mkdirSync(dirname(outputPath), {recursive: true}); - writeFileSync(outputPath, ['run,duration_ms', ...samples.map((duration, index) => `${index + 1},${duration}`), ''].join('\n')); - console.table([Object.fromEntries(Object.entries(benchmarkStats(samples)).map(([key, value]) => [key, value.toFixed(2)]))]); - console.log(`Recorded ${runs} samples in ${outputPath}`); + const stats = benchmarkStats(samples); + mkdirSync(dirname(options.outputPath), {recursive: true}); + writeFileSync(options.outputPath, ['run,duration_ms', ...samples.map((duration, index) => `${index + 1},${duration}`), ''].join('\n')); + console.table([Object.fromEntries(Object.entries(stats).map(([key, value]) => [key, value.toFixed(2)]))]); + console.log(`Recorded ${options.runs} samples in ${options.outputPath}`); + return {samples, stats, outputPath: options.outputPath}; +} + +async function benchmarkAppStartups(options: BenchmarkAppStartupsOptions): Promise { + const adapter = createNativeAppBenchmarkAdapter(options); + return benchmarkStartups(adapter, options); } async function main(): Promise { @@ -371,11 +146,6 @@ async function main(): Promise { description: `Native platform to benchmark (${PLATFORM_NAMES.join(', ')})`, parse: (value): PlatformName => parseChoice(value, PLATFORM_NAMES, 'Platform'), }, - { - name: 'span', - description: 'Whitelisted Sentry span name to benchmark', - default: 'ManualAppStartup', - }, { name: 'runs', description: 'Number of measured startup runs', @@ -390,6 +160,10 @@ async function main(): Promise { }, ], namedArgs: { + span: { + description: 'Whitelisted Sentry span name to measure', + default: DEFAULT_SPAN_NAME, + }, device: { description: 'adb serial on Android, or CoreDevice identifier, UDID, serial number, or name on iOS', required: false, @@ -415,26 +189,37 @@ async function main(): Promise { }); /* eslint-enable @typescript-eslint/naming-convention */ - const platformName = parseChoice(String(cli.positionalArgs.platform), PLATFORM_NAMES, 'Platform'); - const spanName = String(cli.positionalArgs.span); + const platform = parseChoice(String(cli.positionalArgs.platform), PLATFORM_NAMES, 'Platform'); + const spanName = cli.namedArgs.span ?? DEFAULT_SPAN_NAME; const runs = Number(cli.positionalArgs.runs); const timeoutSeconds = Number(cli.positionalArgs.timeout); const mode: StartupMode = cli.flags.cold ? 'cold' : 'process'; - const defaultAppID = platformName === 'android' ? 'org.me.mobiexpensifyg' : 'com.expensify.expensifylite'; + const defaultAppID = platform === 'android' ? 'org.me.mobiexpensifyg' : 'com.expensify.expensifylite'; const appID = cli.namedArgs['app-id'] ?? defaultAppID; const appPath = cli.namedArgs['app-path'] ?? environmentString('IOS_APP_PATH'); const safeSpanName = spanName.replaceAll(/[^a-zA-Z0-9_-]/g, '-'); - const outputPath = resolve(cli.namedArgs.output ?? join(rootDirectory, '.benchmarks', `${platformName}-${safeSpanName}-${mode}.csv`)); - const adapter = platformName === 'android' ? createAndroidAdapter(cli.namedArgs.device, appID) : createIosAdapter(cli.namedArgs.device, appID); - - await benchmarkStartups(adapter, mode, appPath, spanName, runs, timeoutSeconds, outputPath); + const outputPath = resolve(cli.namedArgs.output ?? join(rootDirectory, '.benchmarks', `${platform}-${safeSpanName}-${mode}.csv`)); + + await benchmarkAppStartups({ + platform, + rootDirectory, + deviceIdentifier: cli.namedArgs.device, + appID, + appPath, + mode, + spanName, + runs, + timeoutSeconds, + outputPath, + }); } -if (scriptPath.endsWith('benchmarkAppStartup.ts')) { +if (isDirectRun) { main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; }); } -export {benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile}; +export {benchmarkAppStartups, benchmarkStartups, benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile}; +export type {BenchmarkAppStartupsOptions, BenchmarkResult, BenchmarkStartupsOptions, BenchmarkStats}; diff --git a/scripts/lib/nativeAppBenchmark.ts b/scripts/lib/nativeAppBenchmark.ts new file mode 100644 index 000000000000..8a81e804c582 --- /dev/null +++ b/scripts/lib/nativeAppBenchmark.ts @@ -0,0 +1,288 @@ +// cspell:ignore devicectl + +import type {TupleToUnion} from 'type-fest'; + +import {spawn, spawnSync} from 'node:child_process'; +import {existsSync, mkdtempSync, readFileSync, rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; +import process from 'node:process'; + +const PLATFORM_NAMES = ['android', 'ios'] as const; +const RELAUNCH_DELAY_MS = 500; +const POLL_INTERVAL_MS = 250; +const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; +const MAX_CAPTURED_LOG_LENGTH = 1_000_000; + +type PlatformName = TupleToUnion; +type StartupMode = 'process' | 'cold'; +type BenchmarkLogEvent = { + event: 'span_end'; + span: string; + durationMs: number; + timestamp: number; +}; +type NativeAppBenchmarkAdapter = { + name: PlatformName; + prepareStartup: (mode: StartupMode, appPath?: string) => Promise; + launchAndWait: (spanName: string, timeoutSeconds: number) => Promise; +}; +type NativeAppBenchmarkAdapterOptions = { + platform: PlatformName; + rootDirectory: string; + appID: string; + deviceIdentifier?: string; +}; + +function fail(message: string): never { + throw new Error(message); +} + +function createCommandHelpers(rootDirectory: string) { + const run = (command: string, args: string[]): void => { + const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'inherit'}); + if (result.error) { + fail(`Failed to run ${command}: ${result.error.message}`); + } + if (result.status !== 0) { + fail(`${command} exited with status ${result.status ?? 'unknown'}.`); + } + }; + + const capture = (command: string, args: string[]): string => { + const result = spawnSync(command, args, {cwd: rootDirectory, encoding: 'utf8', maxBuffer: 100 * 1024 * 1024}); + if (result.error) { + fail(`Failed to run ${command}: ${result.error.message}`); + } + if (result.status !== 0) { + const stderr = result.stderr.trim(); + fail(stderr || `${command} exited with status ${result.status ?? 'unknown'}.`); + } + return result.stdout; + }; + + const runAllowFailure = (command: string, args: string[]): boolean => { + const result = spawnSync(command, args, {cwd: rootDirectory, stdio: 'ignore'}); + return !result.error && result.status === 0; + }; + + return {capture, run, runAllowFailure}; +} + +function sleep(milliseconds: number): Promise { + return new Promise((resolvePromise) => { + setTimeout(resolvePromise, milliseconds); + }); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function parseBenchmarkLogEvents(output: string): BenchmarkLogEvent[] { + const events: BenchmarkLogEvent[] = []; + let offset = 0; + + while (offset < output.length) { + const tagIndex = output.indexOf(BENCHMARK_LOG_TAG, offset); + if (tagIndex < 0) { + break; + } + + const jsonStart = output.indexOf('{', tagIndex + BENCHMARK_LOG_TAG.length); + const jsonEnd = jsonStart < 0 ? -1 : output.indexOf('}', jsonStart); + if (jsonStart < 0 || jsonEnd < 0) { + break; + } + + offset = jsonEnd + 1; + try { + const event: unknown = JSON.parse(output.slice(jsonStart, jsonEnd + 1)); + if ( + isRecord(event) && + event.event === 'span_end' && + typeof event.span === 'string' && + typeof event.durationMs === 'number' && + Number.isFinite(event.durationMs) && + typeof event.timestamp === 'number' + ) { + events.push({event: 'span_end', span: event.span, durationMs: event.durationMs, timestamp: event.timestamp}); + } + } catch { + // Ignore unrelated or incomplete console output containing the benchmark tag. + } + } + + return events; +} + +function findBenchmarkDuration(output: string, spanName: string): number | undefined { + return parseBenchmarkLogEvents(output).findLast((event) => event.span === spanName)?.durationMs; +} + +function waitForBenchmarkProcess(rootDirectory: string, command: string, args: string[], spanName: string, timeoutSeconds: number): Promise { + return new Promise((resolvePromise, reject) => { + const processHandle = spawn(command, args, {cwd: rootDirectory}); + let output = ''; + let settled = false; + let timeout: ReturnType; + + const finish = (result: {duration: number} | {error: Error}) => { + if (settled) { + return; + } + + settled = true; + clearTimeout(timeout); + processHandle.kill('SIGINT'); + if ('error' in result) { + reject(result.error); + return; + } + resolvePromise(result.duration); + }; + + const readOutput = (chunk: Buffer) => { + output = `${output}${chunk.toString()}`.slice(-MAX_CAPTURED_LOG_LENGTH); + const duration = findBenchmarkDuration(output, spanName); + if (duration !== undefined) { + finish({duration}); + } + }; + + timeout = setTimeout(() => finish({error: new Error(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${output}`)}), timeoutSeconds * 1000); + processHandle.stdout.on('data', readOutput); + processHandle.stderr.on('data', readOutput); + processHandle.on('error', (error) => finish({error})); + processHandle.on('exit', (code) => { + if (settled) { + return; + } + finish({error: new Error(`App launch exited with code ${code ?? 'unknown'} before ${spanName} completed.\n${output}`)}); + }); + }); +} + +function createAndroidAdapter({rootDirectory, deviceIdentifier, appID}: Omit): NativeAppBenchmarkAdapter { + const {capture, run} = createCommandHelpers(rootDirectory); + const adbArgs = (args: string[]) => (deviceIdentifier ? ['-s', deviceIdentifier, ...args] : args); + const adb = (args: string[]) => run('adb', adbArgs(args)); + const adbCapture = (args: string[]) => capture('adb', adbArgs(args)); + const activity = `${appID}/org.me.mobiexpensifyg.ExpensifyActivityBase`; + + return { + name: 'android', + prepareStartup: async (mode) => { + adb(['shell', 'am', 'force-stop', appID]); + if (mode === 'cold') { + adb(['shell', 'pm', 'clear', appID]); + adb(['shell', 'cmd', 'package', 'compile', '--reset', appID]); + } + adb(['logcat', '-c']); + await sleep(RELAUNCH_DELAY_MS); + }, + launchAndWait: async (spanName, timeoutSeconds) => { + adb(['shell', 'am', 'start', '-W', '-n', activity]); + const deadline = Date.now() + timeoutSeconds * 1000; + let logs = ''; + while (Date.now() < deadline) { + logs = adbCapture(['logcat', '-d', '-v', 'raw']); + const duration = findBenchmarkDuration(logs, spanName); + if (duration !== undefined) { + return duration; + } + await sleep(POLL_INTERVAL_MS); + } + fail(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${logs}`); + }, + }; +} + +function resolveIosDevice(rootDirectory: string, configuredDevice: string | undefined): string { + if (configuredDevice) { + return configuredDevice; + } + + const {run} = createCommandHelpers(rootDirectory); + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-devices-')); + const jsonPath = join(temporaryDirectory, 'devices.json'); + try { + run('xcrun', ['devicectl', 'list', 'devices', '--json-output', jsonPath]); + const response: unknown = JSON.parse(readFileSync(jsonPath, 'utf8')); + if (!isRecord(response) || !isRecord(response.result) || !Array.isArray(response.result.devices)) { + fail('CoreDevice returned an unexpected device-list response.'); + } + + const devices = response.result.devices.flatMap((device) => { + if (!isRecord(device) || !isRecord(device.hardwareProperties) || !isRecord(device.deviceProperties)) { + return []; + } + const {hardwareProperties, deviceProperties} = device; + if ( + hardwareProperties.platform !== 'iOS' || + hardwareProperties.reality !== 'physical' || + deviceProperties.bootState !== 'booted' || + typeof hardwareProperties.udid !== 'string' || + typeof deviceProperties.name !== 'string' + ) { + return []; + } + return [{name: deviceProperties.name, udid: hardwareProperties.udid}]; + }); + if (devices.length !== 1) { + fail(`Expected one booted physical iOS device, found ${devices.length}. Use --device to select one.`); + } + const device = devices.at(0); + if (!device) { + fail('Unable to resolve the connected iOS device.'); + } + console.log(`Using iOS device ${device.name} (${device.udid}).`); + return device.udid; + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } +} + +function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit): NativeAppBenchmarkAdapter { + const {run, runAllowFailure} = createCommandHelpers(rootDirectory); + const iosDeviceID: unknown = process.env.IOS_DEVICE_ID; + const environmentDeviceIdentifier = typeof iosDeviceID === 'string' ? iosDeviceID : undefined; + const device = resolveIosDevice(rootDirectory, deviceIdentifier ?? environmentDeviceIdentifier); + const terminate = () => runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, appID]); + + return { + name: 'ios', + prepareStartup: async (mode, appPath) => { + terminate(); + if (mode === 'cold') { + if (!appPath) { + fail('iOS true-cold startup requires --app-path so the app can be reinstalled after clearing its data.'); + } + if (!existsSync(appPath)) { + fail(`iOS app not found at ${appPath}.`); + } + runAllowFailure('xcrun', ['devicectl', 'device', 'uninstall', 'app', '--device', device, appID]); + run('xcrun', ['devicectl', 'device', 'install', 'app', '--device', device, appPath]); + } + await sleep(RELAUNCH_DELAY_MS); + }, + launchAndWait: (spanName, timeoutSeconds) => + waitForBenchmarkProcess( + rootDirectory, + 'xcrun', + ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', '--console', appID], + spanName, + timeoutSeconds, + ), + }; +} + +function createNativeAppBenchmarkAdapter(options: NativeAppBenchmarkAdapterOptions): NativeAppBenchmarkAdapter { + if (options.platform === 'android') { + return createAndroidAdapter(options); + } + return createIosAdapter(options); +} + +export {BENCHMARK_LOG_TAG, PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents}; +export type {BenchmarkLogEvent, NativeAppBenchmarkAdapter, NativeAppBenchmarkAdapterOptions, PlatformName, StartupMode}; diff --git a/tests/unit/BenchmarkAppStartupTest.ts b/tests/unit/BenchmarkAppStartupTest.ts index b7fa5ab85827..08070af10528 100644 --- a/tests/unit/BenchmarkAppStartupTest.ts +++ b/tests/unit/BenchmarkAppStartupTest.ts @@ -1,4 +1,8 @@ -import {benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; +import {benchmarkStartups, benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; + +import {mkdtempSync, readFileSync, rmSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join} from 'node:path'; describe('benchmarkAppStartup', () => { it('parses structured benchmark logs among platform output', () => { @@ -26,4 +30,31 @@ describe('benchmarkAppStartup', () => { max: 300, }); }); + + it('measures the configured span through a reusable adapter', async () => { + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-test-')); + const outputPath = join(temporaryDirectory, 'samples.csv'); + const prepareStartup = jest.fn(async () => undefined); + const launchAndWait = jest.fn(async () => 123); + + try { + const result = await benchmarkStartups( + {name: 'android', prepareStartup, launchAndWait}, + { + mode: 'process', + spanName: 'ManualAppStartupNetworkRequest', + runs: 1, + timeoutSeconds: 30, + outputPath, + }, + ); + + expect(launchAndWait).toHaveBeenNthCalledWith(1, 'ManualAppStartupNetworkRequest', 30); + expect(launchAndWait).toHaveBeenNthCalledWith(2, 'ManualAppStartupNetworkRequest', 30); + expect(result.samples).toEqual([123]); + expect(readFileSync(outputPath, 'utf8')).toBe('run,duration_ms\n1,123\n'); + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } + }); }); From 826b6a59e03f8696e6f5ac12f649f9669990e1be Mon Sep 17 00:00:00 2001 From: chrispader Date: Mon, 10 Aug 2026 17:17:08 +0200 Subject: [PATCH 3/7] feat: log startup benchmark configuration --- scripts/benchmarkAppStartup.ts | 15 +++++++++++++++ scripts/lib/nativeAppBenchmark.ts | 14 ++++++++++++-- tests/unit/BenchmarkAppStartupTest.ts | 18 +++++++++++++++++- 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts index b1b0702d79ff..3723e9d176a2 100755 --- a/scripts/benchmarkAppStartup.ts +++ b/scripts/benchmarkAppStartup.ts @@ -114,6 +114,21 @@ async function measureStartup(adapter: NativeAppBenchmarkAdapter, options: Omit< } async function benchmarkStartups(adapter: NativeAppBenchmarkAdapter, options: BenchmarkStartupsOptions): Promise { + console.log('=== Native app startup benchmark ==='); + console.table([ + { + platform: adapter.name, + device: adapter.deviceIdentifier, + appID: adapter.appID, + span: options.spanName, + mode: options.mode, + measuredRuns: options.runs, + warmUpRuns: 1, + timeoutSeconds: options.timeoutSeconds, + appPath: options.appPath ?? 'installed app', + outputPath: options.outputPath, + }, + ]); console.log(`Running one unmeasured ${options.mode === 'cold' ? 'true-cold' : 'cold-process'} warm-up startup for ${options.spanName}.`); await measureStartup(adapter, options); diff --git a/scripts/lib/nativeAppBenchmark.ts b/scripts/lib/nativeAppBenchmark.ts index 8a81e804c582..7f1f2bd7fa47 100644 --- a/scripts/lib/nativeAppBenchmark.ts +++ b/scripts/lib/nativeAppBenchmark.ts @@ -1,4 +1,4 @@ -// cspell:ignore devicectl +// cspell:ignore devicectl serialno import type {TupleToUnion} from 'type-fest'; @@ -24,6 +24,8 @@ type BenchmarkLogEvent = { }; type NativeAppBenchmarkAdapter = { name: PlatformName; + appID: string; + deviceIdentifier: string; prepareStartup: (mode: StartupMode, appPath?: string) => Promise; launchAndWait: (spanName: string, timeoutSeconds: number) => Promise; }; @@ -165,13 +167,19 @@ function waitForBenchmarkProcess(rootDirectory: string, command: string, args: s function createAndroidAdapter({rootDirectory, deviceIdentifier, appID}: Omit): NativeAppBenchmarkAdapter { const {capture, run} = createCommandHelpers(rootDirectory); - const adbArgs = (args: string[]) => (deviceIdentifier ? ['-s', deviceIdentifier, ...args] : args); + const selectedDeviceIdentifier = deviceIdentifier ?? capture('adb', ['get-serialno']).trim(); + if (!selectedDeviceIdentifier || selectedDeviceIdentifier === 'unknown') { + fail('Unable to resolve the Android device serial. Use --device to select one.'); + } + const adbArgs = (args: string[]) => ['-s', selectedDeviceIdentifier, ...args]; const adb = (args: string[]) => run('adb', adbArgs(args)); const adbCapture = (args: string[]) => capture('adb', adbArgs(args)); const activity = `${appID}/org.me.mobiexpensifyg.ExpensifyActivityBase`; return { name: 'android', + appID, + deviceIdentifier: selectedDeviceIdentifier, prepareStartup: async (mode) => { adb(['shell', 'am', 'force-stop', appID]); if (mode === 'cold') { @@ -252,6 +260,8 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit { terminate(); if (mode === 'cold') { diff --git a/tests/unit/BenchmarkAppStartupTest.ts b/tests/unit/BenchmarkAppStartupTest.ts index 08070af10528..4c3c6b5e183c 100644 --- a/tests/unit/BenchmarkAppStartupTest.ts +++ b/tests/unit/BenchmarkAppStartupTest.ts @@ -36,10 +36,11 @@ describe('benchmarkAppStartup', () => { const outputPath = join(temporaryDirectory, 'samples.csv'); const prepareStartup = jest.fn(async () => undefined); const launchAndWait = jest.fn(async () => 123); + const consoleTable = jest.spyOn(console, 'table').mockImplementation(() => undefined); try { const result = await benchmarkStartups( - {name: 'android', prepareStartup, launchAndWait}, + {name: 'android', appID: 'org.me.mobiexpensifyg', deviceIdentifier: 'emulator-5554', prepareStartup, launchAndWait}, { mode: 'process', spanName: 'ManualAppStartupNetworkRequest', @@ -53,7 +54,22 @@ describe('benchmarkAppStartup', () => { expect(launchAndWait).toHaveBeenNthCalledWith(2, 'ManualAppStartupNetworkRequest', 30); expect(result.samples).toEqual([123]); expect(readFileSync(outputPath, 'utf8')).toBe('run,duration_ms\n1,123\n'); + expect(consoleTable).toHaveBeenNthCalledWith(1, [ + { + platform: 'android', + device: 'emulator-5554', + appID: 'org.me.mobiexpensifyg', + span: 'ManualAppStartupNetworkRequest', + mode: 'process', + measuredRuns: 1, + warmUpRuns: 1, + timeoutSeconds: 30, + appPath: 'installed app', + outputPath, + }, + ]); } finally { + consoleTable.mockRestore(); rmSync(temporaryDirectory, {recursive: true, force: true}); } }); From 8842ce29107fa032fad4fc92292342866454b574 Mon Sep 17 00:00:00 2001 From: chrispader Date: Mon, 10 Aug 2026 17:41:19 +0200 Subject: [PATCH 4/7] refactor: run startup benchmark with bun --- contributingGuides/BENCHMARKING.md | 4 ++-- package.json | 4 ---- scripts/benchmarkAppStartup.ts | 7 +++---- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/contributingGuides/BENCHMARKING.md b/contributingGuides/BENCHMARKING.md index 910736acd803..2dfdc652d55a 100644 --- a/contributingGuides/BENCHMARKING.md +++ b/contributingGuides/BENCHMARKING.md @@ -38,12 +38,12 @@ nr benchmark-app-startup -- ios 20 30 --span ManualAppStartup --device "Develope The positional arguments are platform, measured run count, and timeout in seconds. Use `--span` to measure any other span included in `EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS`, `--app-id` for a nonstandard Android application ID or iOS bundle identifier, and `--output` to select another CSV path. -The script also exports `benchmarkAppStartups` and `benchmarkStartups`. Other local tooling, such as the PGO workflow, can install an artifact and invoke the same benchmark implementation. The lower-level Android and iOS process tooling lives in `scripts/lib/nativeAppBenchmark.ts` so callers do not need to duplicate `adb` or `xcrun devicectl` behavior. +The script runs with Bun and also exports `benchmarkAppStartups` and `benchmarkStartups`. Other local tooling, such as the PGO workflow, can install an artifact and invoke the same benchmark implementation. The lower-level Android and iOS process tooling lives in `scripts/lib/nativeAppBenchmark.ts` so callers do not need to duplicate `adb` or `xcrun devicectl` behavior. For example, a PGO script can install each artifact and call `benchmarkAppStartups` with its platform, device, bundle identifier, output path, and span name. This keeps artifact building and installation in the PGO workflow while sharing all startup measurement and platform-device behavior. ```ts -import {benchmarkAppStartups} from '#benchmark-app-startup'; +import {benchmarkAppStartups} from '../benchmarkAppStartup'; await benchmarkAppStartups({ platform: 'android', diff --git a/package.json b/package.json index 4e14cd155119..235b9d1f1787 100644 --- a/package.json +++ b/package.json @@ -9,10 +9,6 @@ "workspaces": [ "server/victory-chart-renderer" ], - "imports": { - "#benchmark-app-startup": "./scripts/benchmarkAppStartup.ts", - "#native-app-benchmark": "./scripts/lib/nativeAppBenchmark.ts" - }, "scripts": { "i-standalone": "STANDALONE_NEW_DOT=true npm i", "install-standalone": "STANDALONE_NEW_DOT=true npm install", diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts index 3723e9d176a2..8c6ea9d3deda 100755 --- a/scripts/benchmarkAppStartup.ts +++ b/scripts/benchmarkAppStartup.ts @@ -1,14 +1,13 @@ -#!/usr/bin/env -S node --experimental-strip-types --disable-warning=MODULE_TYPELESS_PACKAGE_JSON -// cspell:ignore TYPELESS +#!/usr/bin/env bun import CLI from 'expensify-common/CLI'; import {mkdirSync, writeFileSync} from 'node:fs'; import {dirname, join, resolve} from 'node:path'; import process from 'node:process'; -import type {NativeAppBenchmarkAdapter, PlatformName, StartupMode} from '#native-app-benchmark'; +import type {NativeAppBenchmarkAdapter, PlatformName, StartupMode} from './lib/nativeAppBenchmark'; -import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents} from '#native-app-benchmark'; +import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents} from './lib/nativeAppBenchmark'; const DEFAULT_SPAN_NAME = 'ManualAppStartup'; const DEFAULT_RUNS = 20; From 14cf81206901137461ac5949dcd4d638ab9ccccb Mon Sep 17 00:00:00 2001 From: chrispader Date: Mon, 10 Aug 2026 18:54:29 +0200 Subject: [PATCH 5/7] fix: collect iOS benchmark spans from app container --- scripts/benchmarkAppStartup.ts | 4 +- scripts/lib/nativeAppBenchmark.ts | 101 +++++++++--------- src/libs/telemetry/logBenchmarkSpanEnd.ts | 12 +-- .../telemetry/writeBenchmarkLog/index.ios.ts | 20 ++++ src/libs/telemetry/writeBenchmarkLog/index.ts | 7 ++ tests/unit/BenchmarkAppStartupTest.ts | 6 +- tests/unit/BenchmarkSpanLoggerIOSTest.ts | 27 +++++ tests/unit/BenchmarkSpanLoggerTest.ts | 2 +- 8 files changed, 116 insertions(+), 63 deletions(-) create mode 100644 src/libs/telemetry/writeBenchmarkLog/index.ios.ts create mode 100644 src/libs/telemetry/writeBenchmarkLog/index.ts create mode 100644 tests/unit/BenchmarkSpanLoggerIOSTest.ts diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts index 8c6ea9d3deda..dfda4fa01c2a 100755 --- a/scripts/benchmarkAppStartup.ts +++ b/scripts/benchmarkAppStartup.ts @@ -7,7 +7,7 @@ import process from 'node:process'; import type {NativeAppBenchmarkAdapter, PlatformName, StartupMode} from './lib/nativeAppBenchmark'; -import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents} from './lib/nativeAppBenchmark'; +import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents} from './lib/nativeAppBenchmark'; const DEFAULT_SPAN_NAME = 'ManualAppStartup'; const DEFAULT_RUNS = 20; @@ -235,5 +235,5 @@ if (isDirectRun) { }); } -export {benchmarkAppStartups, benchmarkStartups, benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile}; +export {benchmarkAppStartups, benchmarkStartups, benchmarkStats, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents, percentile}; export type {BenchmarkAppStartupsOptions, BenchmarkResult, BenchmarkStartupsOptions, BenchmarkStats}; diff --git a/scripts/lib/nativeAppBenchmark.ts b/scripts/lib/nativeAppBenchmark.ts index 7f1f2bd7fa47..6efdaa35a963 100644 --- a/scripts/lib/nativeAppBenchmark.ts +++ b/scripts/lib/nativeAppBenchmark.ts @@ -2,7 +2,7 @@ import type {TupleToUnion} from 'type-fest'; -import {spawn, spawnSync} from 'node:child_process'; +import {spawnSync} from 'node:child_process'; import {existsSync, mkdtempSync, readFileSync, rmSync} from 'node:fs'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; @@ -12,7 +12,7 @@ const PLATFORM_NAMES = ['android', 'ios'] as const; const RELAUNCH_DELAY_MS = 500; const POLL_INTERVAL_MS = 250; const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; -const MAX_CAPTURED_LOG_LENGTH = 1_000_000; +const IOS_BENCHMARK_DIRECTORY = 'Library/Caches/ExpensifyBenchmark'; type PlatformName = TupleToUnion; type StartupMode = 'process' | 'cold'; @@ -122,47 +122,8 @@ function findBenchmarkDuration(output: string, spanName: string): number | undef return parseBenchmarkLogEvents(output).findLast((event) => event.span === spanName)?.durationMs; } -function waitForBenchmarkProcess(rootDirectory: string, command: string, args: string[], spanName: string, timeoutSeconds: number): Promise { - return new Promise((resolvePromise, reject) => { - const processHandle = spawn(command, args, {cwd: rootDirectory}); - let output = ''; - let settled = false; - let timeout: ReturnType; - - const finish = (result: {duration: number} | {error: Error}) => { - if (settled) { - return; - } - - settled = true; - clearTimeout(timeout); - processHandle.kill('SIGINT'); - if ('error' in result) { - reject(result.error); - return; - } - resolvePromise(result.duration); - }; - - const readOutput = (chunk: Buffer) => { - output = `${output}${chunk.toString()}`.slice(-MAX_CAPTURED_LOG_LENGTH); - const duration = findBenchmarkDuration(output, spanName); - if (duration !== undefined) { - finish({duration}); - } - }; - - timeout = setTimeout(() => finish({error: new Error(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${output}`)}), timeoutSeconds * 1000); - processHandle.stdout.on('data', readOutput); - processHandle.stderr.on('data', readOutput); - processHandle.on('error', (error) => finish({error})); - processHandle.on('exit', (code) => { - if (settled) { - return; - } - finish({error: new Error(`App launch exited with code ${code ?? 'unknown'} before ${spanName} completed.\n${output}`)}); - }); - }); +function iosBenchmarkMarkerPath(spanName: string): string { + return `${IOS_BENCHMARK_DIRECTORY}/${encodeURIComponent(spanName)}.log`; } function createAndroidAdapter({rootDirectory, deviceIdentifier, appID}: Omit): NativeAppBenchmarkAdapter { @@ -257,6 +218,32 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, appID]); + const readBenchmarkMarker = (spanName: string): string | undefined => { + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-marker-')); + const localPath = join(temporaryDirectory, 'benchmark.log'); + try { + const copied = runAllowFailure('xcrun', [ + 'devicectl', + 'device', + 'copy', + 'from', + '--device', + device, + '--source', + iosBenchmarkMarkerPath(spanName), + '--destination', + localPath, + '--domain-type', + 'appDataContainer', + '--domain-identifier', + appID, + '--quiet', + ]); + return copied && existsSync(localPath) ? readFileSync(localPath, 'utf8') : undefined; + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } + }; return { name: 'ios', @@ -276,14 +263,24 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit - waitForBenchmarkProcess( - rootDirectory, - 'xcrun', - ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', '--console', appID], - spanName, - timeoutSeconds, - ), + launchAndWait: async (spanName, timeoutSeconds) => { + const previousMarker = readBenchmarkMarker(spanName); + run('xcrun', ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', appID]); + + const deadline = Date.now() + timeoutSeconds * 1000; + let marker: string | undefined; + while (Date.now() < deadline) { + marker = readBenchmarkMarker(spanName); + if (marker !== undefined && marker !== previousMarker) { + const duration = findBenchmarkDuration(marker, spanName); + if (duration !== undefined) { + return duration; + } + } + await sleep(POLL_INTERVAL_MS); + } + fail(`Timed out after ${timeoutSeconds}s waiting for benchmark span ${spanName}.\n${marker ?? 'No iOS benchmark marker was found.'}`); + }, }; } @@ -294,5 +291,5 @@ function createNativeAppBenchmarkAdapter(options: NativeAppBenchmarkAdapterOptio return createIosAdapter(options); } -export {BENCHMARK_LOG_TAG, PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, parseBenchmarkLogEvents}; +export {BENCHMARK_LOG_TAG, PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents}; export type {BenchmarkLogEvent, NativeAppBenchmarkAdapter, NativeAppBenchmarkAdapterOptions, PlatformName, StartupMode}; diff --git a/src/libs/telemetry/logBenchmarkSpanEnd.ts b/src/libs/telemetry/logBenchmarkSpanEnd.ts index 6b6a76f62c31..be1eab0d2002 100644 --- a/src/libs/telemetry/logBenchmarkSpanEnd.ts +++ b/src/libs/telemetry/logBenchmarkSpanEnd.ts @@ -1,3 +1,5 @@ +import writeBenchmarkLog from './writeBenchmarkLog'; + const BENCHMARK_LOG_TAG = '[EXPENSIFY_BENCHMARK]'; const configuredSpanNames: unknown = process.env.EXPO_PUBLIC_BENCHMARK_SENTRY_SPANS; @@ -23,7 +25,7 @@ function parseBenchmarkSpanNames(value: unknown): string[] { ]; } -function createBenchmarkSpanEndLogger(spanNames: string[], writeLog: (message: string) => void): (spanName: string, durationMs: number) => void { +function createBenchmarkSpanEndLogger(spanNames: string[], writeLog: (message: string, spanName: string) => void): (spanName: string, durationMs: number) => void { const enabledSpanNames = new Set(spanNames); return (spanName, durationMs) => { @@ -37,15 +39,11 @@ function createBenchmarkSpanEndLogger(spanNames: string[], writeLog: (message: s durationMs, timestamp: Date.now(), }; - writeLog(`${BENCHMARK_LOG_TAG} ${JSON.stringify(event)}`); + writeLog(`${BENCHMARK_LOG_TAG} ${JSON.stringify(event)}`, spanName); }; } -const logBenchmarkSpanEnd = createBenchmarkSpanEndLogger(parseBenchmarkSpanNames(configuredSpanNames), (message) => { - // Production builds strip console.info/debug/log. Warnings are retained and are not forwarded by the app's Sentry console integration. - // eslint-disable-next-line no-console - console.warn(message); -}); +const logBenchmarkSpanEnd = createBenchmarkSpanEndLogger(parseBenchmarkSpanNames(configuredSpanNames), writeBenchmarkLog); export {BENCHMARK_LOG_TAG, createBenchmarkSpanEndLogger, parseBenchmarkSpanNames}; export default logBenchmarkSpanEnd; diff --git a/src/libs/telemetry/writeBenchmarkLog/index.ios.ts b/src/libs/telemetry/writeBenchmarkLog/index.ios.ts new file mode 100644 index 000000000000..e926da1e5e1f --- /dev/null +++ b/src/libs/telemetry/writeBenchmarkLog/index.ios.ts @@ -0,0 +1,20 @@ +import RNFS from 'react-native-fs'; + +const BENCHMARK_DIRECTORY_NAME = 'ExpensifyBenchmark'; + +function writeBenchmarkLog(message: string, spanName: string): void { + // Keep the warning for developers inspecting unified device logs manually. + // eslint-disable-next-line no-console + console.warn(message); + + const directoryPath = `${RNFS.CachesDirectoryPath}/${BENCHMARK_DIRECTORY_NAME}`; + const markerPath = `${directoryPath}/${encodeURIComponent(spanName)}.log`; + RNFS.mkdir(directoryPath) + .then(() => RNFS.writeFile(markerPath, message, 'utf8')) + .catch((error: unknown) => { + // eslint-disable-next-line no-console + console.warn(`Failed to persist benchmark span ${spanName}.`, error); + }); +} + +export default writeBenchmarkLog; diff --git a/src/libs/telemetry/writeBenchmarkLog/index.ts b/src/libs/telemetry/writeBenchmarkLog/index.ts new file mode 100644 index 000000000000..e743155d0257 --- /dev/null +++ b/src/libs/telemetry/writeBenchmarkLog/index.ts @@ -0,0 +1,7 @@ +function writeBenchmarkLog(message: string): void { + // Production builds strip console.info/debug/log. Warnings are retained and are not forwarded by the app's Sentry console integration. + // eslint-disable-next-line no-console + console.warn(message); +} + +export default writeBenchmarkLog; diff --git a/tests/unit/BenchmarkAppStartupTest.ts b/tests/unit/BenchmarkAppStartupTest.ts index 4c3c6b5e183c..65c875f06875 100644 --- a/tests/unit/BenchmarkAppStartupTest.ts +++ b/tests/unit/BenchmarkAppStartupTest.ts @@ -1,4 +1,4 @@ -import {benchmarkStartups, benchmarkStats, findBenchmarkDuration, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; +import {benchmarkStartups, benchmarkStats, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; import {mkdtempSync, readFileSync, rmSync} from 'node:fs'; import {tmpdir} from 'node:os'; @@ -16,6 +16,10 @@ describe('benchmarkAppStartup', () => { expect(findBenchmarkDuration(output, 'ManualAppStartup')).toBe(500); }); + it('creates an app-container-safe marker path for an iOS span', () => { + expect(iosBenchmarkMarkerPath('Manual/App Startup')).toBe('Library/Caches/ExpensifyBenchmark/Manual%2FApp%20Startup.log'); + }); + it('calculates interpolated percentiles and summary statistics', () => { expect(percentile([100, 200, 300, 400], 0.75)).toBe(325); expect(benchmarkStats([300, 100, 200])).toEqual({ diff --git a/tests/unit/BenchmarkSpanLoggerIOSTest.ts b/tests/unit/BenchmarkSpanLoggerIOSTest.ts new file mode 100644 index 000000000000..07f8df58d6db --- /dev/null +++ b/tests/unit/BenchmarkSpanLoggerIOSTest.ts @@ -0,0 +1,27 @@ +import writeBenchmarkLog from '@libs/telemetry/writeBenchmarkLog/index.ios'; + +const mockMkdir = jest.fn(() => Promise.resolve()); +const mockWriteFile = jest.fn(() => Promise.resolve()); + +jest.mock('react-native-fs', () => ({ + CachesDirectoryPath: '/Library/Caches', + mkdir: (...args: [string]) => mockMkdir(...args), + writeFile: (...args: [string, string, string]) => mockWriteFile(...args), +})); + +describe('iOS benchmark span logging', () => { + it('persists the tagged event to a span-specific app-container marker', async () => { + const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + + try { + writeBenchmarkLog('[EXPENSIFY_BENCHMARK] {"durationMs":250}', 'Manual/App Startup'); + await Promise.resolve(); + await Promise.resolve(); + + expect(mockMkdir).toHaveBeenCalledWith('/Library/Caches/ExpensifyBenchmark'); + expect(mockWriteFile).toHaveBeenCalledWith('/Library/Caches/ExpensifyBenchmark/Manual%2FApp%20Startup.log', '[EXPENSIFY_BENCHMARK] {"durationMs":250}', 'utf8'); + } finally { + consoleWarn.mockRestore(); + } + }); +}); diff --git a/tests/unit/BenchmarkSpanLoggerTest.ts b/tests/unit/BenchmarkSpanLoggerTest.ts index 3e4104dbcaed..0130562a63e2 100644 --- a/tests/unit/BenchmarkSpanLoggerTest.ts +++ b/tests/unit/BenchmarkSpanLoggerTest.ts @@ -15,6 +15,6 @@ describe('benchmark span logging', () => { logSpanEnd('ManualAppStartup', 250); expect(writeLog).toHaveBeenCalledTimes(1); - expect(writeLog).toHaveBeenCalledWith(`${BENCHMARK_LOG_TAG} ${JSON.stringify({event: 'span_end', span: 'ManualAppStartup', durationMs: 250, timestamp: 1_234})}`); + expect(writeLog).toHaveBeenCalledWith(`${BENCHMARK_LOG_TAG} ${JSON.stringify({event: 'span_end', span: 'ManualAppStartup', durationMs: 250, timestamp: 1_234})}`, 'ManualAppStartup'); }); }); From 07519a2bfebeefc15dc2b2c0a6981f1549923b02 Mon Sep 17 00:00:00 2001 From: chrispader Date: Tue, 11 Aug 2026 11:54:02 +0200 Subject: [PATCH 6/7] fix: stabilize iOS startup benchmarks --- scripts/benchmarkAppStartup.ts | 24 ++++- scripts/lib/nativeAppBenchmark.ts | 105 +++++++++++++++++++++- src/libs/telemetry/activeSpans.ts | 4 +- src/libs/telemetry/logBenchmarkSpanEnd.ts | 9 +- tests/unit/ActiveSpansBenchmarkTest.ts | 45 ++++++++-- tests/unit/BenchmarkAppStartupTest.ts | 36 +++++++- tests/unit/BenchmarkSpanLoggerIOSTest.ts | 4 +- 7 files changed, 210 insertions(+), 17 deletions(-) diff --git a/scripts/benchmarkAppStartup.ts b/scripts/benchmarkAppStartup.ts index dfda4fa01c2a..09f29004d97b 100755 --- a/scripts/benchmarkAppStartup.ts +++ b/scripts/benchmarkAppStartup.ts @@ -7,7 +7,16 @@ import process from 'node:process'; import type {NativeAppBenchmarkAdapter, PlatformName, StartupMode} from './lib/nativeAppBenchmark'; -import {PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents} from './lib/nativeAppBenchmark'; +import { + PLATFORM_NAMES, + createNativeAppBenchmarkAdapter, + findBenchmarkDuration, + iosBenchmarkMarkerPath, + parseIosInstalledAppURL, + parseBenchmarkLogEvents, + parseIosLaunchProcessIdentifier, + parseIosRunningAppProcessIdentifier, +} from './lib/nativeAppBenchmark'; const DEFAULT_SPAN_NAME = 'ManualAppStartup'; const DEFAULT_RUNS = 20; @@ -235,5 +244,16 @@ if (isDirectRun) { }); } -export {benchmarkAppStartups, benchmarkStartups, benchmarkStats, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents, percentile}; +export { + benchmarkAppStartups, + benchmarkStartups, + benchmarkStats, + findBenchmarkDuration, + iosBenchmarkMarkerPath, + parseIosInstalledAppURL, + parseBenchmarkLogEvents, + parseIosLaunchProcessIdentifier, + parseIosRunningAppProcessIdentifier, + percentile, +}; export type {BenchmarkAppStartupsOptions, BenchmarkResult, BenchmarkStartupsOptions, BenchmarkStats}; diff --git a/scripts/lib/nativeAppBenchmark.ts b/scripts/lib/nativeAppBenchmark.ts index 6efdaa35a963..924bedcde0ab 100644 --- a/scripts/lib/nativeAppBenchmark.ts +++ b/scripts/lib/nativeAppBenchmark.ts @@ -126,6 +126,48 @@ function iosBenchmarkMarkerPath(spanName: string): string { return `${IOS_BENCHMARK_DIRECTORY}/${encodeURIComponent(spanName)}.log`; } +function parseIosLaunchProcessIdentifier(response: unknown): number { + if (!isRecord(response) || !isRecord(response.result) || !isRecord(response.result.process)) { + fail('CoreDevice returned an unexpected app-launch response.'); + } + const {processIdentifier} = response.result.process; + if (typeof processIdentifier !== 'number' || !Number.isInteger(processIdentifier) || processIdentifier <= 0) { + fail('CoreDevice did not return a valid app process identifier.'); + } + return processIdentifier; +} + +function parseIosInstalledAppURL(response: unknown, appID: string): string { + if (!isRecord(response) || !isRecord(response.result) || !Array.isArray(response.result.apps)) { + fail('CoreDevice returned an unexpected installed-app response.'); + } + const apps: unknown[] = response.result.apps; + const app: unknown = apps.find((candidate) => isRecord(candidate) && candidate.bundleIdentifier === appID); + if (!isRecord(app) || typeof app.url !== 'string') { + fail(`Unable to find installed iOS app ${appID}.`); + } + return app.url.endsWith('/') ? app.url : `${app.url}/`; +} + +function parseIosRunningAppProcessIdentifier(response: unknown, appURL: string): number | undefined { + if (!isRecord(response) || !isRecord(response.result) || !Array.isArray(response.result.runningProcesses)) { + fail('CoreDevice returned an unexpected process-list response.'); + } + const runningProcesses: unknown[] = response.result.runningProcesses; + const runningProcess: unknown = runningProcesses.find((candidate) => { + if (!isRecord(candidate) || typeof candidate.executable !== 'string') { + return false; + } + const relativeExecutablePath = candidate.executable.slice(appURL.length); + return candidate.executable.startsWith(appURL) && relativeExecutablePath.length > 0 && !relativeExecutablePath.includes('/'); + }); + if (!isRecord(runningProcess)) { + return undefined; + } + const {processIdentifier} = runningProcess; + return typeof processIdentifier === 'number' && Number.isInteger(processIdentifier) && processIdentifier > 0 ? processIdentifier : undefined; +} + function createAndroidAdapter({rootDirectory, deviceIdentifier, appID}: Omit): NativeAppBenchmarkAdapter { const {capture, run} = createCommandHelpers(rootDirectory); const selectedDeviceIdentifier = deviceIdentifier ?? capture('adb', ['get-serialno']).trim(); @@ -217,7 +259,53 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, appID]); + let runningProcessIdentifier: number | undefined; + const terminate = () => { + if (runningProcessIdentifier === undefined) { + return; + } + runAllowFailure('xcrun', ['devicectl', 'device', 'process', 'terminate', '--device', device, '--pid', String(runningProcessIdentifier)]); + runningProcessIdentifier = undefined; + }; + const launch = (): void => { + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-launch-')); + const jsonPath = join(temporaryDirectory, 'launch.json'); + try { + run('xcrun', ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', '--json-output', jsonPath, '--quiet', appID]); + const response: unknown = JSON.parse(readFileSync(jsonPath, 'utf8')); + runningProcessIdentifier = parseIosLaunchProcessIdentifier(response); + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } + }; + const resolveRunningProcessIdentifier = (): number | undefined => { + const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-process-')); + const appsJSONPath = join(temporaryDirectory, 'apps.json'); + const processesJSONPath = join(temporaryDirectory, 'processes.json'); + try { + run('xcrun', ['devicectl', 'device', 'info', 'apps', '--device', device, '--bundle-id', appID, '--json-output', appsJSONPath, '--quiet']); + const appsResponse: unknown = JSON.parse(readFileSync(appsJSONPath, 'utf8')); + const appURL = parseIosInstalledAppURL(appsResponse, appID); + const escapedAppURL = appURL.replaceAll('\\', '\\\\').replaceAll("'", "\\'"); + run('xcrun', [ + 'devicectl', + 'device', + 'info', + 'processes', + '--device', + device, + '--filter', + `executable.absoluteString BEGINSWITH '${escapedAppURL}'`, + '--json-output', + processesJSONPath, + '--quiet', + ]); + const processesResponse: unknown = JSON.parse(readFileSync(processesJSONPath, 'utf8')); + return parseIosRunningAppProcessIdentifier(processesResponse, appURL); + } finally { + rmSync(temporaryDirectory, {recursive: true, force: true}); + } + }; const readBenchmarkMarker = (spanName: string): string | undefined => { const temporaryDirectory = mkdtempSync(join(tmpdir(), 'expensify-benchmark-ios-marker-')); const localPath = join(temporaryDirectory, 'benchmark.log'); @@ -250,6 +338,7 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit { + runningProcessIdentifier ??= resolveRunningProcessIdentifier(); terminate(); if (mode === 'cold') { if (!appPath) { @@ -265,7 +354,7 @@ function createIosAdapter({rootDirectory, deviceIdentifier, appID}: Omit { const previousMarker = readBenchmarkMarker(spanName); - run('xcrun', ['devicectl', 'device', 'process', 'launch', '--device', device, '--terminate-existing', appID]); + launch(); const deadline = Date.now() + timeoutSeconds * 1000; let marker: string | undefined; @@ -291,5 +380,15 @@ function createNativeAppBenchmarkAdapter(options: NativeAppBenchmarkAdapterOptio return createIosAdapter(options); } -export {BENCHMARK_LOG_TAG, PLATFORM_NAMES, createNativeAppBenchmarkAdapter, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents}; +export { + BENCHMARK_LOG_TAG, + PLATFORM_NAMES, + createNativeAppBenchmarkAdapter, + findBenchmarkDuration, + iosBenchmarkMarkerPath, + parseIosInstalledAppURL, + parseBenchmarkLogEvents, + parseIosLaunchProcessIdentifier, + parseIosRunningAppProcessIdentifier, +}; export type {BenchmarkLogEvent, NativeAppBenchmarkAdapter, NativeAppBenchmarkAdapterOptions, PlatformName, StartupMode}; diff --git a/src/libs/telemetry/activeSpans.ts b/src/libs/telemetry/activeSpans.ts index 8988e09a5fbd..b662d6451afa 100644 --- a/src/libs/telemetry/activeSpans.ts +++ b/src/libs/telemetry/activeSpans.ts @@ -6,7 +6,7 @@ import {SPAN_STATUS_OK} from '@sentry/core'; import * as Sentry from '@sentry/react-native'; import {AppState} from 'react-native'; -import logBenchmarkSpanEnd from './logBenchmarkSpanEnd'; +import logBenchmarkSpanEnd, {isBenchmarkSpanEnabled} from './logBenchmarkSpanEnd'; type ActiveSpanEntry = { span: ReturnType; @@ -17,7 +17,7 @@ type ActiveSpanEntry = { const activeSpans = new Map(); function startSpan(spanId: string, options: StartSpanOptions) { - if ((AppState.currentState ?? CONST.APP_STATE.ACTIVE) !== CONST.APP_STATE.ACTIVE) { + if ((AppState.currentState ?? CONST.APP_STATE.ACTIVE) !== CONST.APP_STATE.ACTIVE && !isBenchmarkSpanEnabled(options.name)) { return; } // End any existing span for this name diff --git a/src/libs/telemetry/logBenchmarkSpanEnd.ts b/src/libs/telemetry/logBenchmarkSpanEnd.ts index be1eab0d2002..3de04d9e184c 100644 --- a/src/libs/telemetry/logBenchmarkSpanEnd.ts +++ b/src/libs/telemetry/logBenchmarkSpanEnd.ts @@ -43,7 +43,12 @@ function createBenchmarkSpanEndLogger(spanNames: string[], writeLog: (message: s }; } -const logBenchmarkSpanEnd = createBenchmarkSpanEndLogger(parseBenchmarkSpanNames(configuredSpanNames), writeBenchmarkLog); +const enabledBenchmarkSpanNames = new Set(parseBenchmarkSpanNames(configuredSpanNames)); +const logBenchmarkSpanEnd = createBenchmarkSpanEndLogger([...enabledBenchmarkSpanNames], writeBenchmarkLog); -export {BENCHMARK_LOG_TAG, createBenchmarkSpanEndLogger, parseBenchmarkSpanNames}; +function isBenchmarkSpanEnabled(spanName: string): boolean { + return enabledBenchmarkSpanNames.has(spanName); +} + +export {BENCHMARK_LOG_TAG, createBenchmarkSpanEndLogger, isBenchmarkSpanEnabled, parseBenchmarkSpanNames}; export default logBenchmarkSpanEnd; diff --git a/tests/unit/ActiveSpansBenchmarkTest.ts b/tests/unit/ActiveSpansBenchmarkTest.ts index a061bb4e1ab9..02c633652f50 100644 --- a/tests/unit/ActiveSpansBenchmarkTest.ts +++ b/tests/unit/ActiveSpansBenchmarkTest.ts @@ -1,26 +1,42 @@ import {endSpan, startSpan} from '@libs/telemetry/activeSpans'; +import CONST from '@src/CONST'; + +import {AppState} from 'react-native'; + const mockLogBenchmarkSpanEnd = jest.fn(); +const mockIsBenchmarkSpanEnabled = jest.fn(() => false); +const mockStartInactiveSpan = jest.fn< + { + setAttribute: jest.Mock; + setStatus: jest.Mock; + end: jest.Mock; + }, + [unknown] +>(() => ({ + setAttribute: jest.fn(), + setStatus: jest.fn(), + end: jest.fn(), +})); jest.mock('@libs/telemetry/logBenchmarkSpanEnd', () => ({ __esModule: true, default: (...args: unknown[]) => { mockLogBenchmarkSpanEnd(...args); }, + isBenchmarkSpanEnabled: (spanName: string) => mockIsBenchmarkSpanEnabled(spanName), })); jest.mock('@sentry/react-native', () => ({ - startInactiveSpan: () => ({ - setAttribute: jest.fn(), - setStatus: jest.fn(), - end: jest.fn(), - }), + startInactiveSpan: (options: unknown) => mockStartInactiveSpan(options), spanToJSON: () => ({data: {}}), })); afterEach(() => { jest.restoreAllMocks(); mockLogBenchmarkSpanEnd.mockClear(); + mockIsBenchmarkSpanEnabled.mockReset().mockReturnValue(false); + mockStartInactiveSpan.mockClear(); }); describe('activeSpans benchmark logging', () => { @@ -32,4 +48,23 @@ describe('activeSpans benchmark logging', () => { expect(mockLogBenchmarkSpanEnd).toHaveBeenCalledWith('ManualOpenReport', 150); }); + + it('starts an enabled benchmark span while iOS is still transitioning to active', () => { + jest.spyOn(AppState, 'currentState', 'get').mockReturnValue(CONST.APP_STATE.INACTIVE); + mockIsBenchmarkSpanEnabled.mockReturnValue(true); + + startSpan('ManualAppStartup', {name: 'ManualAppStartup'}); + endSpan('ManualAppStartup'); + + expect(mockStartInactiveSpan).toHaveBeenCalledWith({name: 'ManualAppStartup'}); + expect(mockLogBenchmarkSpanEnd).toHaveBeenCalledWith('ManualAppStartup', expect.any(Number)); + }); + + it('still skips a regular span while the app is inactive', () => { + jest.spyOn(AppState, 'currentState', 'get').mockReturnValue(CONST.APP_STATE.INACTIVE); + + startSpan('ManualOpenReport', {name: 'ManualOpenReport'}); + + expect(mockStartInactiveSpan).not.toHaveBeenCalled(); + }); }); diff --git a/tests/unit/BenchmarkAppStartupTest.ts b/tests/unit/BenchmarkAppStartupTest.ts index 65c875f06875..fbdbcc0a6bf8 100644 --- a/tests/unit/BenchmarkAppStartupTest.ts +++ b/tests/unit/BenchmarkAppStartupTest.ts @@ -1,4 +1,14 @@ -import {benchmarkStartups, benchmarkStats, findBenchmarkDuration, iosBenchmarkMarkerPath, parseBenchmarkLogEvents, percentile} from '@scripts/benchmarkAppStartup'; +import { + benchmarkStartups, + benchmarkStats, + findBenchmarkDuration, + iosBenchmarkMarkerPath, + parseIosInstalledAppURL, + parseBenchmarkLogEvents, + parseIosLaunchProcessIdentifier, + parseIosRunningAppProcessIdentifier, + percentile, +} from '@scripts/benchmarkAppStartup'; import {mkdtempSync, readFileSync, rmSync} from 'node:fs'; import {tmpdir} from 'node:os'; @@ -20,6 +30,30 @@ describe('benchmarkAppStartup', () => { expect(iosBenchmarkMarkerPath('Manual/App Startup')).toBe('Library/Caches/ExpensifyBenchmark/Manual%2FApp%20Startup.log'); }); + it('reads the launched iOS process identifier from CoreDevice output', () => { + expect(parseIosLaunchProcessIdentifier({result: {process: {processIdentifier: 1234}}})).toBe(1234); + expect(() => parseIosLaunchProcessIdentifier({result: {process: {}}})).toThrow('CoreDevice did not return a valid app process identifier.'); + }); + + it('finds an already-running iOS app process from CoreDevice output', () => { + const appID = 'com.example.app'; + const appURL = parseIosInstalledAppURL({result: {apps: [{bundleIdentifier: appID, url: 'file:///containers/Example.app'}]}}, appID); + const processIdentifier = parseIosRunningAppProcessIdentifier( + { + result: { + runningProcesses: [ + {executable: `${appURL}PlugIns/Notification.appex/Notification`, processIdentifier: 123}, + {executable: `${appURL}Example`, processIdentifier: 456}, + ], + }, + }, + appURL, + ); + + expect(appURL).toBe('file:///containers/Example.app/'); + expect(processIdentifier).toBe(456); + }); + it('calculates interpolated percentiles and summary statistics', () => { expect(percentile([100, 200, 300, 400], 0.75)).toBe(325); expect(benchmarkStats([300, 100, 200])).toEqual({ diff --git a/tests/unit/BenchmarkSpanLoggerIOSTest.ts b/tests/unit/BenchmarkSpanLoggerIOSTest.ts index 07f8df58d6db..8e6f2b8d141c 100644 --- a/tests/unit/BenchmarkSpanLoggerIOSTest.ts +++ b/tests/unit/BenchmarkSpanLoggerIOSTest.ts @@ -1,7 +1,7 @@ import writeBenchmarkLog from '@libs/telemetry/writeBenchmarkLog/index.ios'; -const mockMkdir = jest.fn(() => Promise.resolve()); -const mockWriteFile = jest.fn(() => Promise.resolve()); +const mockMkdir = jest.fn, [string]>(() => Promise.resolve()); +const mockWriteFile = jest.fn, [string, string, string]>(() => Promise.resolve()); jest.mock('react-native-fs', () => ({ CachesDirectoryPath: '/Library/Caches', From 5256224d1138c3bdea9e778bc20f41dd92902e66 Mon Sep 17 00:00:00 2001 From: chrispader Date: Tue, 11 Aug 2026 12:15:01 +0200 Subject: [PATCH 7/7] fix: use consistent clock for span durations --- src/libs/telemetry/activeSpans.ts | 26 ++++++++++++++++---------- tests/unit/ActiveSpansBenchmarkTest.ts | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/libs/telemetry/activeSpans.ts b/src/libs/telemetry/activeSpans.ts index b662d6451afa..f5cde473bd38 100644 --- a/src/libs/telemetry/activeSpans.ts +++ b/src/libs/telemetry/activeSpans.ts @@ -2,7 +2,7 @@ import CONST from '@src/CONST'; import type {Span, SpanAttributeValue, StartSpanOptions} from '@sentry/core'; -import {SPAN_STATUS_OK} from '@sentry/core'; +import {SPAN_STATUS_OK, spanTimeInputToSeconds} from '@sentry/core'; import * as Sentry from '@sentry/react-native'; import {AppState} from 'react-native'; @@ -16,6 +16,17 @@ type ActiveSpanEntry = { const activeSpans = new Map(); +function getPerformanceStartTimeForLog(startTime: StartSpanOptions['startTime']): number { + const performanceTimestamp = performance.now(); + if (startTime === undefined) { + return performanceTimestamp; + } + + // Sentry start times are Unix timestamps, while performance.now() is relative to the process start. Translate the timestamp once so elapsed time stays monotonic. + const epochStartTime = spanTimeInputToSeconds(startTime) * 1000; + return performanceTimestamp - (Date.now() - epochStartTime); +} + function startSpan(spanId: string, options: StartSpanOptions) { if ((AppState.currentState ?? CONST.APP_STATE.ACTIVE) !== CONST.APP_STATE.ACTIVE && !isBenchmarkSpanEnabled(options.name)) { return; @@ -29,12 +40,7 @@ function startSpan(spanId: string, options: StartSpanOptions) { }); const span = Sentry.startInactiveSpan(options); - let startTimeForLog: number; - if (typeof options.startTime === 'number') { - startTimeForLog = options.startTime; - } else { - startTimeForLog = performance.now(); - } + const startTimeForLog = getPerformanceStartTimeForLog(options.startTime); activeSpans.set(spanId, {span, spanName: options.name, startTimeForLog}); @@ -48,10 +54,10 @@ function endSpan(spanId: string) { return; } const {span, spanName, startTimeForLog} = entry; - const now = performance.now(); - const durationMs = Math.round(now - startTimeForLog); + const performanceTimestamp = performance.now(); + const durationMs = Math.round(performanceTimestamp - startTimeForLog); const attributes = Sentry.spanToJSON(span).data ?? {}; - console.debug(`[Sentry][${spanId}] Ending span (${durationMs}ms)`, {spanId, durationMs, timestamp: now, attributes}); + console.debug(`[Sentry][${spanId}] Ending span (${durationMs}ms)`, {spanId, durationMs, timestamp: Date.now(), attributes}); if (attributes[CONST.TELEMETRY.ATTRIBUTE_CANCELED] !== true) { logBenchmarkSpanEnd(spanName, durationMs); } diff --git a/tests/unit/ActiveSpansBenchmarkTest.ts b/tests/unit/ActiveSpansBenchmarkTest.ts index 02c633652f50..725d36cf7b62 100644 --- a/tests/unit/ActiveSpansBenchmarkTest.ts +++ b/tests/unit/ActiveSpansBenchmarkTest.ts @@ -40,6 +40,22 @@ afterEach(() => { }); describe('activeSpans benchmark logging', () => { + it('calculates an epoch-based span duration with the monotonic clock', () => { + const dateNow = jest.spyOn(Date, 'now').mockReturnValue(1_786_362_201_500); + const performanceNow = jest.spyOn(performance, 'now').mockReturnValue(10_000); + + startSpan(CONST.TELEMETRY.SPAN_APP_STARTUP, { + name: CONST.TELEMETRY.SPAN_APP_STARTUP, + startTime: 1_786_362_201_000, + }); + + dateNow.mockReturnValue(1_786_362_201_750); + performanceNow.mockReturnValue(10_250); + endSpan(CONST.TELEMETRY.SPAN_APP_STARTUP); + + expect(mockLogBenchmarkSpanEnd).toHaveBeenCalledWith(CONST.TELEMETRY.SPAN_APP_STARTUP, 750); + }); + it('logs the Sentry span name instead of its unique tracking ID', () => { jest.spyOn(performance, 'now').mockReturnValueOnce(100).mockReturnValueOnce(250);