> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Performance monitoring (screens, frames, hangs, songs)

Per-screen and per-song performance, measured **natively** by the backends, with nothing running
or sent while a song plays.

## What measures what

| Need                             | Backend           | How                                                                                                                            |
| -------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| App start                        | Sentry, Firebase  | `enableAppStartTracking` / `_app_start`                                                                                        |
| Slow / frozen / total frames     | Sentry            | `enableNativeFramesTracking`: native (CADisplayLink / FrameMetrics), counted in RAM per **root span**, sent when the span ends |
| App hang (iOS)                   | Sentry            | `enableAppHangTracking` (default on), `appHangTimeoutInterval: 2`                                                              |
| Screen dwell + frames per screen | Sentry            | one root span per focused route (`screen /songs`), from `expo-router:page-focused`                                             |
| Screen traces                    | Firebase          | automatic (`autoScreens`), the app starts none                                                                                 |
| One song                         | Sentry + Firebase | `gameplay_session` / `tutorial_session` root span / custom trace                                                               |

Off on purpose (JS-thread work per tick / per touch): `enableStallTracking`,
`enableUserInteractionTracing`, `enableAutoPerformanceTracing`.

## Layers

`src/core/performance-monitor/`

- **Port** `PerformanceMonitor` (`startScreen`, `startSession`, `capabilities`). A backend that
  already measures a thing natively declares it; the facade does not ask it for that thing.
- **Facade** `PerfFacade` (`perf-facade.ts`): `screenFocused`, `sessionBegin`, `sessionEnd`,
  `pause` / `resume`. Pure logic: sampling decided once per song, kill switch, circuit breaker (a
  monitor that throws once is dropped), `sessionEnd` deferred to the idle queue.
- **Adapters**: `ErrorReportingPerformanceMonitor` (Sentry, through the `ErrorReportingService`
  port, so `@sentry/react-native` stays in its one file), `FirebasePerformanceMonitor` (through
  `PerformanceService`), `NoopPerformanceMonitor`, `FakePerformanceMonitor`.
- **Composition**: `src/bootstrap/performance-monitor-setup.ts` (called from `entrySetup.ts`).
  `EXPO_PUBLIC_PERF_MONITOR=0` turns it off at build time.
- **UI**: `useScreenViewTracking` (route focus, app background) and `usePerfSession` in
  `PlayScreenBody` / `TutorialGameplayScreen` (mount / unmount). Nothing else.

## Not hurting gameplay

1. `sessionBegin` runs at mount (prepare, before the countdown), `sessionEnd` at unmount; no call between.
2. Hot-path code (`src/features/piano/components`, sprite engine, rhythm-engine) may not import the
   monitor or the SDKs — `__tests__/hot-path.test.ts`.
3. Sentry sends at span end; its own `tracesSampleRate` (0.2) samples songs and screens.
4. Known limit: envelopes queued earlier can still be sent by Sentry's native thread during a song.

## Not built yet

- A native frame recorder for backends without native frames (Firebase custom traces carry no
  frame data), MetricKit / Play Vitals, draw-FPS in production.
- Remote Config kill switch / sample rate (today: build-time env + constant).
- Sentry dashboards and alerts (Insights → Mobile; custom gameplay dashboard).

The gameplay hitch tracer (`EXPO_PUBLIC_HITCH_TRACE`) stays a debug tool and is unrelated.

## Non-fatal errors (overview of failures the app survived)

`reportNonFatal(area, error, context?)` in `src/core/utils/crashReporting.ts` records a handled
error to Crashlytics (non-fatal) and Sentry, tagged `area` (+ short `context`). Capped at 3 per
(area, message) and 60 per process, never throws. Not for the gameplay loop.

Areas wired today: `audio-sampler` (piano sampler load), `purchase` (a purchase that threw, not a
cancel), `media-store` (fetch / download), `remote-config` (fetch), `hub-bootstrap`,
`reinstall-restore`, `sfx` (load). Existing `reportCrash(..., HANDLED)` sites (catalog, MIDI,
atlas, lazy route groups) are unchanged. Add a new area at any catch that today only logs.

## Sentry metrics (dashboards / alerts)

`ErrorReportingService.recordDistribution` / `recordCount` → `Sentry.metrics.*` (SDK ≥ 7.8; buffered
and sent periodically by the SDK, never per call). Recorded after the fact only:

| Metric                                                          | When                   | Attributes |
| --------------------------------------------------------------- | ---------------------- | ---------- |
| `gameplay.session_ms`, `tutorial.session_ms` (distribution, ms) | session end            | `outcome`  |
| `gameplay.session`, `tutorial.session` (count)                  | session end            | `outcome`  |
| `app.boot_ms` (distribution, ms)                                | `boot_timing`          | `status`   |
| `non_fatal` (count)                                             | every `reportNonFatal` | `area`     |

Not verified: the SDK's send interval (doc says only "periodically") and whether any metric is
flushed while a song plays — measure on a device. No `beforeSendMetric` kill switch is set; typings
in 8.34.0 do not expose it.

***

<small>Source: [`docs/performance-monitoring.md`](https://github.com/leapgame/leap-sim-piano/blob/f794b594016038c483e2d20b6af56aea0ae1b982/docs/performance-monitoring.md)</small>
