fix(metrics): web and Android tag plays with one source vocabulary, so a surface reads the same on either (#8075)

The recommendation metrics judge each surface against a baseline of manual
plays. The web tagged only system mixes, so its radio, album, artist and
history plays all sat in the baseline; Android tagged nearly everything, and
its search, Liked-list, library-shuffle and artist-top plays fell to Other.
The surface deltas depended on which client someone listened on.

- The web sends the vocabulary Android uses: radio:<seed>, album:<id>,
  artist:<id>, artist-top:<id>, home:most_played and history, kept in
  web/src/lib/player/playSource.ts.
- The baseline is now named in one place (isManualSource): no source, a
  search pick, or a Liked-list pick.
- library_shuffle gets its own row, the random baseline the mixes exist to
  beat; artist-top counts as an artist play.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 00:08:37 -05:00
co-authored by Claude Opus 5.5
parent 0c9faeca9f
commit 5939248bef
18 changed files with 111 additions and 28 deletions
+22 -4
View File
@@ -66,8 +66,9 @@ type surfaceGroup struct {
type recommendationMetricsResp struct {
WindowDays int `json:"window_days"`
// Baseline is the control group: plays the user picked manually
// (source IS NULL). Surfaces are judged as deltas against it; nil
// when the window holds no manual plays.
// (isManualSource: no source, search or the Liked list). Surfaces are
// judged as deltas against it; nil when the window holds no manual
// plays.
Baseline *surfaceMetric `json:"baseline"`
Groups []surfaceGroup `json:"groups"`
}
@@ -79,6 +80,19 @@ type recFamily struct {
intent string
}
// isManualSource reports whether a play's source marks a manual pick: the
// listener chose the song, with no recommendation between them and it. These
// make the baseline every surface is judged against.
//
// The play-source vocabulary both clients send is: a system mix's variant
// ("for_you", "discover", …), "radio:<seed track>", "album:<id>",
// "artist:<id>", "artist-top:<id>", "home:<section>", "offline:<pool>",
// "history", "library_shuffle", "search", "liked", or none. The web keeps
// it in web/src/lib/player/playSource.ts.
func isManualSource(src string) bool {
return src == "" || src == "search" || src == "liked"
}
// bucketRecSource maps a raw client-stamped source string to its stable
// family. One-off sources (album:<uuid>, radio:<uuid>) collapse into
// their family so the table stays readable at any library size.
@@ -106,8 +120,12 @@ func bucketRecSource(src string) recFamily {
return recFamily{"first_listens", "First listens", intentDiscovery}
case strings.HasPrefix(src, "album:"):
return recFamily{"direct_album", "Album plays", intentDirect}
case strings.HasPrefix(src, "artist:"):
case strings.HasPrefix(src, "artist:") || strings.HasPrefix(src, "artist-top:"):
return recFamily{"direct_artist", "Artist plays", intentDirect}
case src == "library_shuffle":
// Shuffling the whole library: the random baseline the
// recommendations exist to beat, shown beside them.
return recFamily{"library_shuffle", "Library shuffle", intentDirect}
case strings.HasPrefix(src, "offline:"):
return recFamily{"offline", "Offline pools", intentDirect}
case strings.HasPrefix(src, "home:"):
@@ -287,7 +305,7 @@ func bucketMetricsResponse(
families := map[string]*familyAccum{}
picks := map[string]map[string]*familyAccum{}
for _, row := range rows {
if row.Source == nil || *row.Source == "" {
if row.Source == nil || isManualSource(*row.Source) {
baseline.add(row)
continue
}
@@ -279,3 +279,30 @@ func TestRecommendationMetrics_BucketsWithBaseline(t *testing.T) {
t.Errorf("radio family = %+v, want plays=1 (collapsed from radio:<uuid>)", radio)
}
}
// Both clients' sources land on the same surfaces: search and Liked-list
// plays are manual picks in the baseline, library shuffle is its own row,
// and an artist's top songs count as artist plays, not Other.
func TestBucketMetricsResponse_SharedSourceVocabulary(t *testing.T) {
src := func(s string) *string { return &s }
rows := []dbq.RecommendationSourceMetricsForUserRow{
{Source: nil, Plays: 10, Skips: 1, CompletionN: 10, AvgCompletion: 0.9},
{Source: src("search"), Plays: 5, Skips: 1, CompletionN: 5, AvgCompletion: 0.8},
{Source: src("liked"), Plays: 5, Skips: 0, CompletionN: 5, AvgCompletion: 1},
{Source: src("library_shuffle"), Plays: 4, Skips: 2, CompletionN: 4, AvgCompletion: 0.5},
{Source: src("artist-top:abcd"), Plays: 3, Skips: 0, CompletionN: 3, AvgCompletion: 1},
}
resp := bucketMetricsResponse(recMetricsDefaultDays, rows)
if resp.Baseline == nil || resp.Baseline.Plays != 20 {
t.Fatalf("baseline = %+v, want the 20 manual, search and liked plays", resp.Baseline)
}
if s := findSurface(resp, "library_shuffle"); s == nil || s.Plays != 4 {
t.Errorf("library_shuffle = %+v, want its own row of 4", s)
}
if s := findSurface(resp, "direct_artist"); s == nil || s.Plays != 3 {
t.Errorf("direct_artist = %+v, want the 3 top-song plays", s)
}
if s := findSurface(resp, "other"); s != nil {
t.Errorf("other = %+v, want none: every source here has a surface", s)
}
}
+2 -1
View File
@@ -2,6 +2,7 @@
import type { AlbumRef, AlbumDetail } from '#lib/api/types.js';
import { api } from '#lib/api/client.js';
import { enqueueTracks, playQueue } from '#lib/player/store.svelte.js';
import { playSource } from '#lib/player/playSource.js';
import { Play } from 'lucide-svelte';
import AlbumMenu from './AlbumMenu.svelte';
import CardActionCluster from './CardActionCluster.svelte';
@@ -20,7 +21,7 @@
e.preventDefault();
e.stopPropagation();
const detail = await api.get<AlbumDetail>(`/api/albums/${album.id}`);
playQueue(detail.tracks, 0);
playQueue(detail.tracks, 0, { source: playSource.album(album.id) });
}
</script>
+1 -1
View File
@@ -120,7 +120,7 @@ describe('AlbumCard', () => {
expect(api.get).toHaveBeenCalledWith('/api/albums/xyz');
await Promise.resolve();
await Promise.resolve();
expect(playQueue).toHaveBeenCalledWith(tracks, 0);
expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: 'album:xyz' });
});
test('renders the bottom-right kebab menu trigger', () => {
+2 -1
View File
@@ -3,6 +3,7 @@
import type { ArtistRef, TrackRef } from '#lib/api/types.js';
import { api } from '#lib/api/client.js';
import { playQueue, enqueueTracks } from '#lib/player/store.svelte.js';
import { playSource } from '#lib/player/playSource.js';
import { Play } from 'lucide-svelte';
import ArtistMenu from './ArtistMenu.svelte';
import CardActionCluster from './CardActionCluster.svelte';
@@ -18,7 +19,7 @@
e.stopPropagation();
const tracks = await api.get<TrackRef[]>(`/api/artists/${artist.id}/tracks`);
if (tracks.length === 0) return;
playQueue(shuffled(tracks), 0);
playQueue(shuffled(tracks), 0, { source: playSource.artist(artist.id) });
}
async function onAddToQueue(e: MouseEvent) {
@@ -15,17 +15,20 @@
let {
track,
sectionTracks,
index
index,
source
}: {
track: TrackRef;
sectionTracks: TrackRef[];
index: number;
/** Where a play started here began, in the playSource vocabulary. */
source?: string;
} = $props();
const cover = $derived(coverUrl(track.album_id));
function onClick() {
playQueue(sectionTracks, index);
playQueue(sectionTracks, index, { source });
}
function onAddToQueue(e: MouseEvent) {
@@ -41,7 +41,7 @@ describe('CompactTrackCard', () => {
props: { track: tracks[1], sectionTracks: tracks, index: 1 }
});
await fireEvent.click(screen.getByRole('button', { name: /play second/i }));
expect(playQueue).toHaveBeenCalledWith(tracks, 1);
expect(playQueue).toHaveBeenCalledWith(tracks, 1, { source: undefined });
});
test('renders title and artist name', () => {
+2 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import type { HistoryEvent } from '#lib/api/history.js';
import { playQueue } from '#lib/player/store.svelte.js';
import { playSource } from '#lib/player/playSource.js';
import { coverUrl } from '#lib/media/covers.js';
import TrackListRow from './TrackListRow.svelte';
import Cover from './Cover.svelte';
@@ -8,7 +9,7 @@
let { event } = $props<{ event: HistoryEvent }>();
function handleClick() {
playQueue([event.track], 0);
playQueue([event.track], 0, { source: playSource.history });
}
// Format played_at as a human-readable timestamp.
+1 -1
View File
@@ -58,7 +58,7 @@ describe('HistoryRow', () => {
render(HistoryRow, { props: { event: sampleEvent } });
const row = screen.getByRole('button', { name: /play song title/i });
await fireEvent.click(row);
expect(playQueue).toHaveBeenCalledWith([sampleTrack], 0);
expect(playQueue).toHaveBeenCalledWith([sampleTrack], 0, { source: 'history' });
});
it('carries the shared row controls: like, radio, add and the menu', () => {
+4 -1
View File
@@ -15,11 +15,14 @@
tracks,
index,
onPlay,
source,
showAlbum = true
}: {
tracks: TrackRef[];
index: number;
onPlay?: PlayHandler;
/** Where a play started here began, in the playSource vocabulary. */
source?: string;
/** Off on the album page, where the album is the page itself. */
showAlbum?: boolean;
} = $props();
@@ -50,7 +53,7 @@
return;
}
if (onPlay) onPlay(tracks, index);
else playQueue(tracks, index);
else playQueue(tracks, index, { source });
}
function onCheckboxClick(e: MouseEvent) {
+3 -3
View File
@@ -45,19 +45,19 @@ describe('TrackRow', () => {
test('clicking the row calls playQueue(tracks, index)', async () => {
render(TrackRow, { props: { tracks, index: 1 } });
await fireEvent.click(screen.getByRole('button', { name: 'Freddie Freewheeler' }));
expect(playQueue).toHaveBeenCalledWith(tracks, 1);
expect(playQueue).toHaveBeenCalledWith(tracks, 1, { source: undefined });
});
test('Enter on the row activates play', async () => {
render(TrackRow, { props: { tracks, index: 0 } });
await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: 'Enter' });
expect(playQueue).toHaveBeenCalledWith(tracks, 0);
expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: undefined });
});
test('Space on the row activates play', async () => {
render(TrackRow, { props: { tracks, index: 0 } });
await fireEvent.keyDown(screen.getByRole('button', { name: 'So Then' }), { key: ' ' });
expect(playQueue).toHaveBeenCalledWith(tracks, 0);
expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: undefined });
});
test('onPlay prop overrides default playQueue', async () => {
+19
View File
@@ -0,0 +1,19 @@
// The play-source vocabulary: what a play_started's `source` says about where
// a play began. The server's recommendation metrics bucket plays by it
// (internal/api/me_recommendation_metrics.go, bucketRecSource), and the
// Android app sends the same strings, so a surface reads the same whichever
// client the listening happened on. System mixes send their variant name
// ('for_you', 'discover', …) instead.
//
// A play with no source, or from search or the Liked list, is a manual pick:
// the baseline every recommendation surface is judged against.
export const playSource = {
album: (albumId: string) => `album:${albumId}`,
artist: (artistId: string) => `artist:${artistId}`,
artistTop: (artistId: string) => `artist-top:${artistId}`,
radio: (seedTrackId: string) => `radio:${seedTrackId}`,
home: (section: string) => `home:${section}`,
history: 'history',
liked: 'liked',
search: 'search'
} as const;
+10 -5
View File
@@ -1,4 +1,5 @@
import type { TrackRef, RadioResponse } from '#lib/api/types.js';
import { playSource } from './playSource';
import { untrack } from 'svelte';
import { api } from '#lib/api/client.js';
import { user } from '#lib/auth/user.svelte.js';
@@ -83,10 +84,11 @@ let _pendingRestorePosition: number | null = null;
let _radioSeedId = $state<string | null>(null);
let _radioRefreshInFlight = false;
// Which system playlist (if any) this queue was seeded from.
// 'for_you' | 'discover' | null. Read by the events dispatcher so
// play_started carries `source` and the play counts against that
// playlist's rotation. Re-set on every playQueue (a fresh non-system
// Where this queue was seeded from, in the playSource vocabulary: a system
// playlist's variant ('for_you' | 'discover' | …), radio, an album, an
// artist, … or null for a manual pick. Read by the events dispatcher so
// play_started carries `source`: a mix's play counts against that
// playlist's rotation, and every play lands on its surface in the metrics. Re-set on every playQueue (a fresh non-system
// queue clears it).
let _queueSource = $state<string | null>(null);
@@ -480,7 +482,10 @@ export async function playRadio(seedTrackId: string): Promise<void> {
if (tracks.length === 0) return;
// Hand the player a self-heal closure so a fully-stale radio queue
// re-seeds from the same track instead of dead-ending.
playQueue(tracks, 0, { refetch: () => fetchRadioTracks(seedTrackId) });
playQueue(tracks, 0, {
source: playSource.radio(seedTrackId),
refetch: () => fetchRadioTracks(seedTrackId)
});
_radioSeedId = seedTrackId; // Set AFTER playQueue (which clears it)
}
+2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { playSource } from '#lib/player/playSource.js';
import { pageTitle } from '#lib/branding.js';
import { createHomeQuery } from '#lib/api/home.js';
import HorizontalScrollRow from '#lib/components/HorizontalScrollRow.svelte';
@@ -380,6 +381,7 @@
{track}
sectionTracks={data.most_played_tracks}
index={globalIdx}
source={playSource.home('most_played')}
/>
{/snippet}
</HorizontalScrollRow>
+4 -3
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { playSource } from '#lib/player/playSource.js';
import { plural } from '#lib/utils/plural.js';
import PageColumn from '#lib/components/PageColumn.svelte';
import { page } from '$app/state';
@@ -37,7 +38,7 @@
if (isStartingPlay || !data || data.tracks.length === 0) return;
isStartingPlay = true;
try {
playQueue(data.tracks, 0);
playQueue(data.tracks, 0, { source: playSource.album(id) });
} finally {
isStartingPlay = false;
}
@@ -48,7 +49,7 @@
if (isStartingPlay || !data || data.tracks.length === 0) return;
isStartingPlay = true;
try {
playQueue(shuffled(data.tracks), 0);
playQueue(shuffled(data.tracks), 0, { source: playSource.album(id) });
} finally {
isStartingPlay = false;
}
@@ -168,7 +169,7 @@
{:else}
<TrackList>
{#each album.tracks as track, i (track.id)}
<TrackRow tracks={album.tracks} index={i} showAlbum={false} />
<TrackRow tracks={album.tracks} index={i} showAlbum={false} source={playSource.album(id)} />
{/each}
</TrackList>
{/if}
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { playSource } from '#lib/player/playSource.js';
import { plural } from '#lib/utils/plural.js';
import PlayActions from '#lib/components/PlayActions.svelte';
import { shuffled } from '#lib/utils/shuffle.js';
@@ -50,7 +51,7 @@
try {
const tracks = await api.get<TrackRef[]>(`/api/artists/${id}/tracks`);
if (tracks.length === 0) return;
playQueue(order(tracks), 0);
playQueue(order(tracks), 0, { source: playSource.artist(id) });
} finally {
isStartingPlay = false;
}
@@ -134,7 +135,7 @@
<section class="space-y-3">
<HorizontalScrollRow rows={[top]} title="Top tracks" ariaLabel={`Top tracks for ${detail.name}`}>
{#snippet item(track: TrackRef, globalIdx: number)}
<CompactTrackCard {track} sectionTracks={top} index={globalIdx} />
<CompactTrackCard {track} sectionTracks={top} index={globalIdx} source={playSource.artistTop(id)} />
{/snippet}
</HorizontalScrollRow>
</section>
+1 -1
View File
@@ -162,7 +162,7 @@ describe('artist detail page', () => {
(api.get as ReturnType<typeof vi.fn>).mockResolvedValue(tracks);
render(ArtistPage);
await fireEvent.click(screen.getByRole('button', { name: 'Play Alice' }));
await waitFor(() => expect(playQueue).toHaveBeenCalledWith(tracks, 0));
await waitFor(() => expect(playQueue).toHaveBeenCalledWith(tracks, 0, { source: 'artist:abc' }));
});
test('Shuffle queues every track', async () => {
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { playSource } from '#lib/player/playSource.js';
import PageColumn from '#lib/components/PageColumn.svelte';
import { pageTitle } from '#lib/branding.js';
import {
@@ -157,7 +158,7 @@
{:else}
<TrackList>
{#each fTracks as t, i (t.id)}
<TrackRow tracks={fTracks} index={i} />
<TrackRow tracks={fTracks} index={i} source={playSource.liked} />
{/each}
</TrackList>
<ListContinuation