sonda/internal/taste/service_test.go
tgiachi ca5cbbf088 feat: favourites teach Sonda my taste
A heart adds to what the listening says of an artist: a favourite artist counts
as much as three complete listens, a favourite album 1.5 for its album artist and
a favourite song 1 for each of its main artists, at most 6 for one artist, without
fading with time. An artist hearted but never played is liked, with no listens.
That feeds Discover, the mixes and the smart playlists that use the taste, and
GET /me/taste.

In the mixes of what the listener likes (genre mixes, Your favourites,
Rediscover) a hearted song is wanted 1.5 times as much and a song on a hearted
album 1.25 times. New to you is not changed.
2026-11-16 11:08:20 +01:00

279 lines
9.2 KiB
Go

package taste
import (
"context"
"errors"
"math"
"testing"
"time"
"git.kmalloc.org/squid/sonda/internal/listening"
)
type fakeStore struct {
events []Event
tags map[int64]map[string]float64
names map[int64]string
since time.Time
user int64
tagCalls [][]int64
nameCalls [][]int64
err error
favs map[int64]Favorites
favUser int64
favErr error
}
func (f *fakeStore) ArtistFavorites(_ context.Context, userID int64) (map[int64]Favorites, error) {
f.favUser = userID
return f.favs, f.favErr
}
func (f *fakeStore) ArtistEvents(_ context.Context, userID int64, since time.Time) ([]Event, error) {
f.user, f.since = userID, since
return f.events, f.err
}
func (f *fakeStore) ArtistTags(_ context.Context, ids []int64) (map[int64]map[string]float64, error) {
f.tagCalls = append(f.tagCalls, ids)
return f.tags, f.err
}
func (f *fakeStore) ArtistNames(_ context.Context, ids []int64) (map[int64]string, error) {
f.nameCalls = append(f.nameCalls, ids)
return f.names, f.err
}
func newService(f *fakeStore) *Service {
s := NewService(f, options)
s.now = func() time.Time { return now }
return s
}
func complete(artist int64, n int) []Event {
var out []Event
for i := 0; i < n; i++ {
out = append(out, Event{ArtistID: artist, Type: listening.Complete, At: now})
}
return out
}
func TestTasteRanksTheArtistsILikeAndLeavesOutTheOthers(t *testing.T) {
f := &fakeStore{
events: append(append(complete(1, 5), complete(2, 1)...),
Event{ArtistID: 3, Type: listening.Skip, PlayedMs: 1_000, At: now},
Event{ArtistID: 4, Type: listening.Play, PlayedMs: 2_000, At: now}), // too short: neutral
tags: map[int64]map[string]float64{1: {"rock": 1}, 2: {"pop": 1}},
names: map[int64]string{1: "One", 2: "Two"},
}
p, err := newService(f).Taste(context.Background(), 7, 0)
if err != nil {
t.Fatal(err)
}
if f.user != 7 {
t.Errorf("asked for user %d", f.user)
}
if len(p.Artists) != 2 || p.Artists[0].ID != 1 || p.Artists[1].ID != 2 {
t.Fatalf("artists = %+v, want 1 then 2 only", p.Artists)
}
if p.Artists[0].Name != "One" || p.Artists[0].Listens != 5 || p.Artists[0].Preference <= p.Artists[1].Preference {
t.Errorf("first artist = %+v", p.Artists[0])
}
if len(p.Tags) != 2 || p.Tags[0].Tag != "rock" || p.Tags[0].Weight != 1 {
t.Errorf("tags = %+v, want rock first at 1", p.Tags)
}
// Only the artists that are shown or liked are looked up, never the skipped ones.
for _, ids := range append(f.tagCalls, f.nameCalls...) {
for _, id := range ids {
if id == 3 || id == 4 {
t.Errorf("looked up artist %d, who is not liked", id)
}
}
}
}
func TestTasteLooksOnlyAsFarBackAsItMatters(t *testing.T) {
f := &fakeStore{}
if _, err := newService(f).Taste(context.Background(), 1, 0); err != nil {
t.Fatal(err)
}
if want := now.Add(-10 * options.HalfLife); !f.since.Equal(want) {
t.Errorf("since = %v, want ten half-lives back: %v", f.since, want)
}
}
func TestTasteOfSomeoneWhoHasListenedToNothing(t *testing.T) {
p, err := newService(&fakeStore{}).Taste(context.Background(), 1, 0)
if err != nil {
t.Fatal(err)
}
if p.Artists == nil || p.Tags == nil || len(p.Artists) != 0 || len(p.Tags) != 0 {
t.Errorf("profile = %+v, want empty lists that are not nil", p)
}
}
func TestTasteLimit(t *testing.T) {
var events []Event
names := map[int64]string{}
for id := int64(1); id <= 60; id++ {
events = append(events, complete(id, 1)...)
names[id] = "a"
}
f := &fakeStore{events: events, names: names}
s := newService(f)
p, _ := s.Taste(context.Background(), 1, 0)
if len(p.Artists) != DefaultLimit {
t.Errorf("default limit: %d artists, want %d", len(p.Artists), DefaultLimit)
}
if p, _ = s.Taste(context.Background(), 1, 1000); len(p.Artists) != MaxLimit {
t.Errorf("large limit: %d artists, want %d", len(p.Artists), MaxLimit)
}
if p, _ = s.Taste(context.Background(), 1, 3); len(p.Artists) != 3 {
t.Errorf("limit 3: %d artists", len(p.Artists))
}
if _, err := s.Taste(context.Background(), 1, -1); !errors.Is(err, ErrInvalidQuery) {
t.Errorf("negative limit: err = %v", err)
}
}
func TestTasteTiesAreStable(t *testing.T) {
// Same listens at the same time: the lower id goes first.
same := &fakeStore{
events: []Event{
{ArtistID: 5, Type: listening.Complete, At: now.Add(-time.Hour)},
{ArtistID: 4, Type: listening.Complete, At: now.Add(-time.Hour)},
{ArtistID: 6, Type: listening.Complete, At: now.Add(-time.Hour)},
},
names: map[int64]string{},
}
p, _ := newService(same).Taste(context.Background(), 1, 0)
if len(p.Artists) != 3 || p.Artists[0].ID != 4 || p.Artists[1].ID != 5 || p.Artists[2].ID != 6 {
t.Errorf("order by id = %+v", p.Artists)
}
}
func TestTasteOrdersByTheScoreNotByTheRoundedPreference(t *testing.T) {
var events []Event
for i := 0; i < 500; i++ {
events = append(events, Event{ArtistID: 1, Type: listening.Complete, At: now.Add(-time.Hour)})
}
for i := 0; i < 60; i++ {
events = append(events, Event{ArtistID: 2, Type: listening.Complete, At: now})
}
p, _ := newService(&fakeStore{events: events, names: map[int64]string{}}).Taste(context.Background(), 1, 0)
if len(p.Artists) != 2 || p.Artists[0].ID != 1 {
t.Errorf("order = %+v, want the artist heard 500 times first", p.Artists)
}
}
func TestTasteKeepsTheTagListShort(t *testing.T) {
tags := map[string]float64{}
for i := 0; i < MaxTags+30; i++ {
tags[string(rune('a'+i%26))+string(rune('a'+i/26))] = 1 - float64(i)/1000
}
f := &fakeStore{events: complete(1, 1), tags: map[int64]map[string]float64{1: tags}, names: map[int64]string{1: "One"}}
p, _ := newService(f).Taste(context.Background(), 1, 0)
if len(p.Tags) != MaxTags || p.Tags[0].Weight != 1 {
t.Errorf("%d tags, first %+v; want %d, best first", len(p.Tags), p.Tags[0], MaxTags)
}
}
func TestAZeroHalfLifeDoesNotBreakTheModel(t *testing.T) {
s := NewService(&fakeStore{events: complete(1, 3), names: map[int64]string{1: "One"}}, Options{MinListen: 20 * time.Second})
s.now = func() time.Time { return now }
p, err := s.Taste(context.Background(), 1, 0)
if err != nil || len(p.Artists) != 1 || math.IsNaN(p.Artists[0].Preference) || p.Artists[0].Preference <= 0 {
t.Errorf("profile = %+v err=%v, want a normal preference", p, err)
}
}
func TestTasteBoundsTheArtistsBehindTheTagProfile(t *testing.T) {
var events []Event
for id := int64(1); id <= MaxProfileArtists+50; id++ {
events = append(events, complete(id, 1)...)
}
f := &fakeStore{events: events, names: map[int64]string{}}
if _, err := newService(f).Taste(context.Background(), 1, 0); err != nil {
t.Fatal(err)
}
if len(f.tagCalls) != 1 || len(f.tagCalls[0]) != MaxProfileArtists {
t.Errorf("tags were read in %d calls (%v), want one call for %d artists", len(f.tagCalls), f.tagCalls, MaxProfileArtists)
}
}
func TestTasteReturnsStoreErrors(t *testing.T) {
boom := errors.New("boom")
if _, err := newService(&fakeStore{err: boom}).Taste(context.Background(), 1, 0); !errors.Is(err, boom) {
t.Errorf("err = %v", err)
}
}
func TestLearnGivesEveryPreferenceTheLikedOnesInOrderAndTheWholeTagProfile(t *testing.T) {
tags := map[string]float64{}
for i := 0; i < MaxTags+10; i++ {
tags[string(rune('a'+i%26))+string(rune('a'+i/26))] = 1
}
f := &fakeStore{
events: append(append(complete(1, 5), complete(2, 1)...),
Event{ArtistID: 3, Type: listening.Skip, PlayedMs: 100, At: now}),
tags: map[int64]map[string]float64{1: tags},
}
l, err := newService(f).Learn(context.Background(), 4)
if err != nil {
t.Fatal(err)
}
if f.user != 4 {
t.Errorf("asked for user %d", f.user)
}
if len(l.Prefs) != 3 || l.Prefs[3].Preference >= 0 {
t.Errorf("prefs = %+v, want all three, the skipped one negative", l.Prefs)
}
if len(l.Liked) != 2 || l.Liked[0].ArtistID != 1 || l.Liked[1].ArtistID != 2 {
t.Errorf("liked = %+v, want 1 then 2", l.Liked)
}
if len(l.Tags) != MaxTags+10 {
t.Errorf("%d tags, want the whole profile (%d): only the display is cut", len(l.Tags), MaxTags+10)
}
}
func TestLearnOfSomeoneWhoHasListenedToNothing(t *testing.T) {
l, err := newService(&fakeStore{}).Learn(context.Background(), 1)
if err != nil || l.Prefs == nil || l.Liked == nil || l.Tags == nil || len(l.Prefs)+len(l.Liked)+len(l.Tags) != 0 {
t.Errorf("learned = %+v err=%v, want empty and not nil", l, err)
}
}
func TestLearnCountsTheFavouritesOfTheListener(t *testing.T) {
f := &fakeStore{
events: complete(1, 1),
favs: map[int64]Favorites{2: {Artist: true}, 1: {Tracks: 1}},
tags: map[int64]map[string]float64{1: {"rock": 1}, 2: {"jazz": 1}},
names: map[int64]string{1: "One", 2: "Two"},
}
l, err := newService(f).Learn(context.Background(), 7)
if err != nil {
t.Fatal(err)
}
if f.favUser != 7 {
t.Errorf("favourites of user %d", f.favUser)
}
// Two (a heart: 3) before One (a listen and a heart: 2).
if len(l.Liked) != 2 || l.Liked[0].ArtistID != 2 || l.Liked[1].ArtistID != 1 {
t.Fatalf("liked = %+v", l.Liked)
}
if len(l.Tags) != 2 || l.Tags[0].Tag != "jazz" {
t.Errorf("tags = %+v", l.Tags)
}
p, err := newService(f).Taste(context.Background(), 7, 0)
if err != nil || len(p.Artists) != 2 || p.Artists[0].ID != 2 || p.Artists[0].Listens != 0 {
t.Fatalf("taste = %+v, %v", p, err)
}
}
func TestLearnFailsWhenTheFavouritesCannotBeRead(t *testing.T) {
f := &fakeStore{events: complete(1, 1), favErr: errors.New("boom")}
if _, err := newService(f).Learn(context.Background(), 7); err == nil {
t.Fatal("no error")
}
}