Documentation comes from this release commit, without inheriting newer content. Commit: 35589c6fda.
Analytics events
Analytics is schema-driven. Event param shapes live in Valibot schemas; typed
track() contracts are derived from them. You never hand-write event constants or call
the Firebase SDK directly from a feature.
- Package:
packages/analytics(@piano/analytics) - Schemas (source of truth):
packages/analytics/src/event-schemas.ts - Derived types:
packages/analytics/src/event-types.ts - App-facing aliases:
packages/analytics/src/schema-types.ts - Provider routing:
packages/analytics/src/event-routing.ts - Wiring metadata (contract tests):
packages/analytics/src/event-contract.ts - PM descriptions (extracted from schema):
packages/analytics/src/event-schema-docs.ts - Shared param fragments:
packages/analytics/src/event-schema-fragments.ts
Schema shape
Each event is a Valibot v.object({ … }) keyed by canonical snake_case name:
Types derive automatically:
App/ad code imports taxonomy types from @piano/analytics (schema-types.ts) —
AnalyticsParam, RewardedAdContext, VideoadsStamp, reviveRewardedContext(), etc. —
all derived from AnalyticsEventMap, not hand-written unions.
Layers
Adding / changing an event
-
Edit
packages/analytics/src/event-schemas.ts. Keep the name snake_case and globally unique. -
Update routing in
event-routing.ts(which providers receive the event). -
Update contract in
event-contract.ts(status,triggerpath once implemented). -
Implement the call site in a feature using the typed API:
Or in a component via the hook:
const a = useAnalytics(); a.track(...). FTUE funnel events usetrackFtueSessionEvent/trackFtueEventfromsrc/core/sdk/ftue-analytics.ts— they stamp the persistedsessioncounter (incremented once per cold start viabindFtueSession()in the root layout). Cold-start boot events (fn_loading_start,fn_loading_end,fn_after_splash_screen) go throughuseTutorialStore((st) => st.trackBootEvent)so the store gates once-per-install firing and skips after onboarding + tutorial complete. Those events andfn_intro_1also carryelapsed_ms(ms since JS entry, stamped byjs-entry-mark);fn_loading_endaddsstatus=ok|degraded(a boot service threw or timed out) |ceiling(the 8 s services ceiling released the app first). It now fires whenever the guarded service chain settles — not only when the hub bootstrap succeeded — so a drop betweenfn_loading_startandfn_loading_endmeans the app was killed/crashed, not that a service failed.fn_loading_startfires when loading starts — after the 1.65 s splash intro (every launch; boot runs only once the intro has played), so itselapsed_msincludes the intro.boot_timing(once per cold start, not install-gated) reports per-service latency (rc_ms,iap_ms,af_ms),js_entry_ms(React Native startup → JS entry = bundle-load time),status,failed_stepandceiling_hit; it goes out at the ceiling if that comes first, so a hung service is named. Boot events are emitted fromsrc/bootstrap/start-app-bootstrap.ts; the UI hook only forwards the lifecycle start action. Deferred first-FTUE gameplay warmups are outsideboot_timingand do not holdfn_loading_end.splash_timing(once per cold start, not install-gated) fires when the splash has gone (the splash store) and says how long it ran:splash_ms(bundle load + JS entry → gone; the native launch before JS is not counted),intro_ms(the JS splash intro,0when it never took over),loading_ms(loading start → the services releasing the splash; absent when they never did),wait_ms(that release → gone: the last gates and the splash minimum, which is the intro's own length) andceiling_hit(the 12 s hard ceiling released it).fn_after_splash_screencarries the samesplash_msfor the FTUE funnel. The app version is on every event via theapp_version/app_builduser properties. Firebase Performance traces (boot_total,boot_<step>) mirror the same timings — see Boot performance.onboarding_perffires when the onboarding screen goes (useOnboardingPerf): the UI thread's frame rate while it was in view — counted from the splash going, since the screen mounts under it (avg_fps,low_fps= worst second,jank_pct= frames over twice the budget,max_fps= 60 or 120 Hz,duration_ms; a Reanimated frame callback,frame-stats), the JS thread's (js_avg_fps),film_ms(screen open → the film's first frame),thumbs_ms/thumbs_ok(the boot prefetch of the tutorial songs' covers, absent while it is still running) andconfig_wait_ms(from the screen being seen to the install's A/B-tested values being locked, at most 3 s;0when an earlier launch had them; absent when the screen went first).gpu_prewarm_done/gpu_prewarm_mswere dropped on 19/11 with the onboarding prewarm.boot_timing.rc_ms/failed_stepstill say how often the fetch is slow or gives up.ab_config_applied(onboarding_script,mon_pkg_variant,ab_lock_version) fires when an install locks its A/B-tested Remote Config on the console's answer (experiment-decision.ts) — once per round of tests, never for an install that fell back to the in-app baseline — and is the activation event of every Firebase experiment on those keys. The user propertyab_source(remote|fallback) says which an install is, on every event after the lock; filter A/B analyses onab_source = remote.onboarding_scriptandmon_pkg_variantreport the locked values.fn_next_song_after_tutorialgoes throughuseTutorialStore.getState().trackNextSongAfterTutorialfromPlayScreen— once per install when the first post-tutorial session starts (tutorial_nextfrom Get orhomefrom the song list). Song engagement events use helpers insrc/core/sdk/song-analytics.ts—trackSongImpression(2s visibility) is meant to begin thesong_session_idfunnel, but nothing calls it yet (see Known tracking issues);trackSongClickstarts the session, or reuses the song's active one.song_ordermust be the 1-based position in the visible on-screen list viasongListOrderFromIndex/songListOrderFromId— never catalogsortOrderfrom the remote sheet. It goes out only onhomeandrecommended_resultplays (songOrderForPlayTypedrops it for every other play type), and only when such a list opened the play: Home'sfilteredTracks(Game Mode and the Learn CTA) and Game Mode's Result recommendations. Learn's result Next song isrecommended_resultwith nosong_order: it is one suggestion, not a list row. Setstatus: "implemented"and atriggerfile path inevent-contract.tsonce it's merged. -
Test:
cd packages/analytics && bun test— contract tests verify trigger files exist and actually calltrack()for implemented events.
Param / trigger descriptions in schema
PM-facing semantics live on the Valibot schema via v.pipe(..., v.description("…")) —
not sent to Firebase. Reuse shared fragments in event-schema-fragments.ts (e.g.
videoadsScreen, videoadsLocation) so revive copy is defined once.
Read descriptions at runtime or for docs export:
Event-level v.description() = when the event fires. Field-level = when to stamp each param.
File wiring stays in event-contract.ts (trigger path).
Videoads context
All videoads_* events share the same param fields (screen, location, reward,
song_id, song_name). Stash context before showRewarded():
- Song unlock:
songUnlockRewardedContext(songId, songName, mode)→screen: "song_unlock";mode: "learn"(the unlock opens the song in Learn) addsreward: "song_learn" - Learn revive:
reviveRewardedContext(songId, songName)→screen: "revive",location/reward: "revive"
The Song List's Learn CTA on a rewarded row shares the Play CTA's unlock, so it shares
its context too — the same songUnlockRewardedContext — bound for Learn, so its reward is
song_learn — and the same unlock_song placement. Its order
is song_click (song_mode: "learn", on the press) → the sheet → videoads_* (on
"Learn this song for free", after the sheet dismisses) → Learn Mode's own session events. No
second song_click: the session guard in trackSongClick has already fired one for that
session, and the Learn CTA reuses it. See features/songs.md.
See src/core/sdk/ad-analytics-track.ts.
App Open (openads_*) — the AdMob App Open format (cold launch and return from the
background, ad-trigger-logic.md §6) reports the eight events of the PO's
sheet (10/11). All are Firebase-only:
Params:
- Every event carries
connection(online/offline, left out until the app has read the network state once;connection.ts). - Every event carries
accumulated_count, plusad_unit_tierandad_unit_idexcept on a notready. The count is the user's lifetime total for that event, kept inuseEventCountStore; it is read from memory at once but saved to MMKV in batches (eventCountStorage: one write per ~1.5 s window on the idle queue, and at once when the app leaves the foreground), so a process that dies inside the window can lose the last few counts. - The five show-side events (
show_ready,show_notready,show,show_failed,click) carrytrigger: how the app came up for the show —cold_start(opened from scratch) orwarm_resume(back from the background). openads_showcarriessession: this launch's number for the player (1 = the first launch), the count the arm's "App Open from session N" rule reads.- The request events carry no
trigger.
Changed on 10/11 (dashboards must switch):
locationbecametriggeron the show-side events:app_open→cold_start,foreground_return→warm_resume.- The request events no longer carry
locationoratt_status. openads_finish(the close) is no longer sent.
openads_show_notready has three sources:
launch_wait_5s: the launch waited 5 s and nothing loaded.show_no_ready: a return found nothing loaded.show_no_ready: the ads engine found no ad at show time.
A gate that stops the App Open sends nothing (premium, FTUE, fewer than 4 finished songs, the
120 s / 60 s gaps, a menu that is covered), as in Guitar. There is no openads_trigger.
The paid event sends ad_impression / ad_impression_ama with ad_format: "app_open" and
ad_unit_name: "Open_All" (Guitar's name), plus AppsFlyer af_ad_revenue. There is no AppsFlyer
custom event. See app-open.ts and
ad-analytics-track.ts.
Full Screen Native (nativeads_*) — the native ad shown full screen right after an
interstitial or a rewarded video, by the install's mon_pkg arm (ad-trigger-logic.md
§7). The PO's funnel (sheet of 2026-11-09), Firebase-only:
Params on every event: connection (online / offline, left out until the app has read the
network state once; connection.ts), accumulated_count,
ad_unit_tier (always all: one unit per slot) and ad_unit_id, which tells the two slots apart
as magicPad does. nativeads_show / nativeads_click also carry trigger (after_fs = after an
interstitial, after_rv = after a rewarded video); until 2026-11-09 that value was sent as
location. Nothing is sent for a slot that is shut (the arm has no FSN, the player is before
fsn_from, has No Ads / VIP, or there is no unit) or for a load parked mid-song.
The paid event sends ad_impression / ad_impression_ama with ad_format: "fullscreen_native"
(magicPad's value) and ad_unit_name FSN_Inter / FSN_RW, plus AppsFlyer af_ad_revenue;
ad_source is the network that filled, which the module reads from the ad's response. See
fsn-controller.ts and
composition-root.ts.
Ad funnel params (fullads_*, videoads_*, bannerads_*)
A funnel event that stands for one AdMob unit names it — ad_unit_tier (high / all) and
ad_unit_id (the full ca-app-pub-…/… id); *_trigger and videoads_backfill carry none, and
so does *_show_notready now — it only fires when neither tier is loaded, so there is never a
unit behind it. An empty show is only that: *_show_failed keeps its own meaning — an ad was in
hand and never reached the player — and always names the unit it had. The engine keeps two tiers warm per format like magicPad's tier cache policy, but since the ads moved onto the SDK's preload pools (admob-integration.md §3) it never requests an ad itself: there is no retry ladder, load timeout or eviction, and a High unit cannot be spammed by anything the app does (AdMob had flagged High's failed requests). *_request marks a pool being created, or refilling after a take; *_request_success a pool reporting an ad; *_request_failed a pool that could not be created or whose preload failed. The SDK does the network requests on its own, so the volume no longer lines up with magicPad's. A failed pool is rebuilt at most once a minute, and that rebuild is a new *_request. In Game Mode, the requests a song
needs go out on its loading screen, which holds the countdown up to 5 s for the interstitial;
from the countdown until the player leaves the song nothing new is requested, so a *_request
never lands mid-song. The banner reports the same
three-event shape, still on the 5 s → 60 s retry ladder: bannerads_request / _request_success /
_request_failed, alongside the existing bannerads_show / _empty / _click. Since 2026-10-05
the app keeps one banner loaded ahead, so a banner request can precede any banner screen: it then
carries no location, and bannerads_show fires when the banner appears in a screen's slot, not
when it loads. No banner request goes out from a Game Mode song's countdown until its last note has
ended.
fullads_request, fullads_request_success and fullads_request_failed also carry
att_status (since 2026-10-07): the iOS App Tracking Transparency status the request went out
under — granted (the IDFA is readable), denied (iOS "restricted" included) or undetermined
(both: no IDFA). Android has no prompt and sends none. It is there to split interstitial no-fill
by whether the networks could see the IDFA; videoads_* and bannerads_* do not carry it. Until
2026-10-19 a status other than granted also meant non-personalised ads only; since then the
request is the same for every status.
fail_reason is the SDK's <code>: <message> or an app-side reason, at most 100 characters.
New app-side values: both_tiers_empty / show_no_ready (an empty interstitial / rewarded
show — magicPad's own wording, never with a unit named, and on *_show_notready only),
reward_not_earned (a rewarded the player closed before earning
it). Retired: sdk_not_loaded no longer reaches any event — the tier is simply not picked, and
the reason stays in the ads log only. retry_count is still not a param (it never was); what
changed is that a retry now shows up as its own *_request event instead of nothing. Details:
admob-integration.md §8.
fullads_trigger and fullads_show carry location (since 2026-11-09) only for an
interstitial at the end of a Learn stage: learn_mode_stage_<n>, the stage just completed
(screen stays others). It is there for the arms that run Learn by stage (learn_fs.mode = stages). No other interstitial sends location, and the schema accepts no other value
(learn-stage-location.ts).
Song sessions across Game Mode and Learn Mode
-
song_mode(game|learn) is stamped on everysong_*event exceptsong_impression,song_preview,song_pauseandsong_pause_action. The shared builders insrc/core/sdk/song-analytics.tsandsong-engagement-run.tsdefault togame, and Learn names its own. The Game Mode result's recommendation column names it too now that it has a Learn/Play toggle: a card tapped on the Learn half opens Learn Mode, sotrackResultRecommendationSongClickstampssong_mode: "learn"on it rather than letting it default togame. -
song_versionrides on every event that carriessong_mode:defaultfor the song's own MIDI, otherwise the name of the version Remote Configsong_versionsassigned (short; see features/catalog.md). Game Mode session events report the chart that loaded (useMagicGameplay'splayedVersionRef), so a version that could not be had and fell back reportsdefault. The Song List, Replay and result recommendation clicks report the version the play will load. Learn Mode, the tutorial's own song (it plays itstutorial_songMIDI) andsong_impressionreportdefault. -
Learn Mode opens after four finished songs (features/songs.md), and the lock adds no events. The locked Learn pill on the Song List sends nothing: no song was chosen, so no
song_click. The first entry is the "Learn Mode unlocked!" popup's Claim, which sends thesong_clickthe Learn pill sends (useLearnEntryClick:song_mode: "learn",song_play_type: "home", nosong_order— no list row opened it) fortwinkle-twinkle-little-star, then Learn Mode's own session events as usual. -
Learn Mode sends through one tracker,
src/features/learn/learn-analytics.ts, made once per visit byuseLearnSessionAnalytics. The screen only says when:- the action phase;
- a key press, saying whether it belongs to the final stage's judged run;
- a stage completed;
- the final (test) stage's run ended;
- out of hearts, a revive offered, a revive;
- a revive about to restart the stage's attempt, with that attempt's counts
(
carryAttemptCounts), and the time the revive's ad took (excludeAdTime); - a stage left (
stageLeft, fromgoToStage); - Retry / Restart / Next song;
- leaving.
The tracker owns the per-session guards. A Retry, Restart or Next song opens a new
song_session_id. The Learn CTA reuses the song's session unless it already has a click or reachedsong_ap(trackSongClickForNewPlay). -
Learn
me_starthas two milestones, and sends once per session on whichever the session reaches first:- stage 1 completed; or
- the 5th press of the final stage's challenge run — the milestone for a session that can never complete stage 1: a Retry, a Replay, or a player returning to a song whose stages they have all passed and resuming on the show.
The count is the final (test) stage's Challenge only. Its Practice counts nothing, the listen step and the "I'm ready!" card take no play input at all, and neither does any earlier stage. Every press the run takes counts, right or wrong: the milestone is that the player is playing the show, not that they are playing it well. Like every other run-state flag the count is per song session — leaving and coming back, or a Retry / Restart / Next song, starts it again from zero, and
me_startstill goes out at most once per session. The threshold isLEARN_CHALLENGE_ME_START_PRESSESinsrc/features/learn/learn-analytics.ts, the one place the rule lives. -
Learn
song_progressadds up every attempt of the stage that a revive (the out-of-hearts card's Keep going) restarted, until the stage completes or the player moves to another stage:error_cntsums their wrong presses.hint_cntis 0 or 1: a revive keeps the attempt's Hint reveal, so the attempt that completes the stage counts that Hint once, however many revives it carried through. -
Learn
song_playtime(onsong_endandsong_result) runs fromsong_apand leaves out the time spent in a revive's ad. -
Learn
song_end/song_resultgo out the moment the final stage's Challenge run ends: when its last note is ruled on — claimed, or its window (±150 ms on the phone's speaker, ±250 ms on headphones) shut with nothing claiming it — not when the backing reaches its cue marker, which on some songs is seconds later. Sosong_playtimestops at the last note, and a press after it is not judged: it adds nothing toerror_cnt(onsong_result, and the stage'ssong_progress) orwrong_rate, and does not count towardsme_start's five presses. A run nothing ever rules on is ended by a backstop, 2.5 s after its last window shuts. A run the player backs out of (back after "I'm ready!", then Keep going!) never ends: it sends neither event, and the run that starts over from "I'm ready!" sends them once, with its own stats only, though itssong_playtimestill runs fromsong_apand so includes the abandoned attempt and the time on the Leave card and the question. -
Learn
song_resultrates need not sum to 1:perfect_rate+miss_rateis 1,early_rateandlate_ratecount timed claims again, andwrong_ratecounts presses. -
song_revive_impressiongoes to subscribers too: the out-of-hearts card offers them Keep going although no ad plays for them. Their heart takes one of the song's 3 refills in any 24 hours, but no ad was watched, so nosong_revivefollows. -
The tutorial song (FTUE, on Game Mode's gameplay) sends
song_aponce its song is ready to play and is watched forsong_quitfrom there, with Game Mode's chart-group progress (useTutorialSongSession). It has no way out of the song, so only a force quit reports one; itssong_endcloses the watch. -
song_quit(src/core/sdk/song-quit.ts) goes out for a session watched fromsong_apthat is left beforesong_end/song_result.- A quit also ends that song session, so the next play of the song opens a new one.
- The watch lives in a persisted store (
open-song-session-store.ts). A session still open at the next launch was left by a force quit, andflushSongQuitFromLastLaunchinuseBootstrapEntrySDKreports it. The flush runs in the bootstrap's mount effect, and the root layout renders no screen until the bootstrap is ready, so it goes out even when the new launch opens onboarding or the tutorial again. progressis"done/total": chart groups in Game Mode and the tutorial song, passed stages in Learn (a five-stage song givesn/5).- A Learn visit that ended at its result, or was left before
song_ap, releases its session when the screen goes.
Known tracking issues (not fixed yet)
song_impressionhelper exists but no call site wires 2s list visibility yet.- Some
plannedevents inevent-contract.tshave no trigger — expected until implemented.
Shop and No Ads popup (PM sheet "Event Shop", 2026-11-10)
Source of truth: the "Event Shop" sheet of the Piano Simulation Roadmap; decisions in
features/shop.md. No Ads events carry pack_type
(noads_1day / noads_7days / noads_lifetime, the same in both price tiers) instead of the
store package; the Song list's IAP songs (screen = home) keep package.
Only the popup the monetization slice opens after the Nth song-end interstitial logs; Labs logs
nothing, and a locked Lifetime bonus song never opens it (Free / Rewarded / VIP sheet rules).
The slice also logs noads_popup_trigger when the popup becomes due.
The price, currency and transaction come from the store: IapProduct.currencyCode,
IapPurchaseResult.transactionId and the RevenueCat error's code / message
(purchaseErrorDetails in core/iap/rc-mappers.pure.ts).
Paywall locations (screen) per trigger
Every paywall trigger sends its own screen on sub_offer_show / sub_offer_click / sub_offer_cancel /
sub_offer_close (clicked after a purchase press) / user_subscription; none falls back to unknown.
The 50%-off modal sends paywall_variant: "discount", the rest default.
Remote Config suggestion per variant (mon_pkg.paywall, all optional; arm defaults apply when a key is absent):
song_start counts after the first note of every gameplay, so a Retry of a normal play counts again.