test(playlists, recommendation): system-mix builds stop drawing covers no test reads; merge repeated cases (#8297)
release / go (push) Successful in 1m44s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m45s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m40s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped

Timings from one run of the integration lane with -v (39c5b1ed, reverted
here) put the system-mix builds at 1.4-3.8s each, most of the playlists
package's 35s. A build draws a JPEG collage per mix; under -race that is
most of its time, and no build test looked at a cover. The build tests now
pass no data folder, which skips drawing, except SufficientActivity, which
keeps drawing and now checks every mix got a cover: nothing tested that the
build wires covers before.

Merged:
- playlists service: 22 tests become 5 scenario tests (access, bad input,
  partial update, track-list edits, cover-file cleanup), one database
  reset each.
- ARebuildKeepsEachMixsID into DailyNonceDeterminism (both built twice in
  one day); the two You might like builds into one.
- capCandidatesByAlbumAndArtist, Score, Similarity, ContextualMatchScore
  and the session-vector seed rule: one table each.
- LoadCandidates' six contextual-like database tests: the max and seed
  rules are ContextualMatchScore's unit table; the database test keeps what
  only it can see, a like reaching its track and a withdrawn like ignored.

Dropped: Score determinism with a fixed RNG (a pure function), Score's
cold-start case (the same input as the base case), and recencyDecay(nil)
and skipRatio's two cases, which Score's table covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 13:35:36 -05:00
co-authored by Claude Opus 5.5
parent 39c5b1ed66
commit a2dae7ec8c
10 changed files with 471 additions and 1055 deletions
+22 -112
View File
@@ -219,129 +219,39 @@ func helperInsertContextualLike(t *testing.T, f fixture, trackID pgtype.UUID, ve
}
}
func TestLoadCandidates_NoContextualLikes_AllZero(t *testing.T) {
f := newFixture(t, 5)
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current)
if err != nil {
t.Fatalf("load: %v", err)
// LoadCandidates gives each candidate the contextual match of its likes
// (ContextualMatchScore, tested on its own above): a track liked in a session
// like the current one scores about 1, a track whose like was withdrawn
// (soft-deleted) and a track never liked score 0.
func TestLoadCandidates_ContextualLikesReachTheirTracks(t *testing.T) {
f := newFixture(t, 4)
liked, withdrawn := f.tracks[1], f.tracks[2]
session := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
helperInsertContextualLike(t, f, liked.ID, session)
helperInsertContextualLike(t, f, withdrawn.ID, session)
if _, err := f.pool.Exec(context.Background(),
`UPDATE contextual_likes SET deleted_at = now() WHERE track_id = $1`, withdrawn.ID); err != nil {
t.Fatalf("soft-delete: %v", err)
}
for _, c := range got {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("track %s ContextualMatchScore = %v, want 0", c.Track.Title, c.Inputs.ContextualMatchScore)
}
}
}
func TestLoadCandidates_OneMatchingLike_ScoresPositive(t *testing.T) {
f := newFixture(t, 3)
target := f.tracks[1]
likeVec := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
helperInsertContextualLike(t, f, target.ID, likeVec)
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current)
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, session)
if err != nil {
t.Fatalf("load: %v", err)
}
var found bool
for _, c := range got {
if c.Track.ID == target.ID {
score := c.Inputs.ContextualMatchScore
switch {
case c.Track.ID == liked.ID:
found = true
if c.Inputs.ContextualMatchScore < 0.99 {
t.Errorf("target ContextualMatchScore = %v, want ~1.0", c.Inputs.ContextualMatchScore)
}
} else {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("non-target track has ContextualMatchScore = %v", c.Inputs.ContextualMatchScore)
if score < 0.99 {
t.Errorf("liked track scores %v, want ~1.0", score)
}
case score != 0:
t.Errorf("track %s scores %v, want 0", c.Track.Title, score)
}
}
if !found {
t.Error("target track missing from candidate list")
}
}
func TestLoadCandidates_MultipleMatchingLikes_TakesMax(t *testing.T) {
f := newFixture(t, 3)
target := f.tracks[1]
helperInsertContextualLike(t, f, target.ID, SessionVector{
Artists: []string{"a99"}, Tags: map[string]int{"jazz": 1},
})
helperInsertContextualLike(t, f, target.ID, SessionVector{
Artists: []string{"a1"}, Tags: map[string]int{"rock": 1},
})
helperInsertContextualLike(t, f, target.ID, SessionVector{
Artists: []string{"a1"}, Tags: map[string]int{"jazz": 1},
})
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current)
if err != nil {
t.Fatalf("load: %v", err)
}
for _, c := range got {
if c.Track.ID == target.ID && c.Inputs.ContextualMatchScore < 0.99 {
t.Errorf("target = %v, want ~1.0 (max)", c.Inputs.ContextualMatchScore)
}
}
}
func TestLoadCandidates_SoftDeletedLikes_Ignored(t *testing.T) {
f := newFixture(t, 3)
target := f.tracks[1]
likeVec := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
helperInsertContextualLike(t, f, target.ID, likeVec)
if _, err := f.pool.Exec(context.Background(),
`UPDATE contextual_likes SET deleted_at = now() WHERE user_id = $1`, f.user); err != nil {
t.Fatalf("soft-delete: %v", err)
}
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current)
if err != nil {
t.Fatalf("load: %v", err)
}
for _, c := range got {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("soft-deleted track %s ContextualMatchScore = %v", c.Track.Title, c.Inputs.ContextualMatchScore)
}
}
}
func TestLoadCandidates_OnlySeedLikes_ScoresZero(t *testing.T) {
f := newFixture(t, 3)
target := f.tracks[1]
helperInsertContextualLike(t, f, target.ID, SessionVector{
Seed: true, Artists: []string{"a1"}, Tags: map[string]int{"rock": 1},
})
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current)
if err != nil {
t.Fatalf("load: %v", err)
}
for _, c := range got {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("seed-only track %s ContextualMatchScore = %v", c.Track.Title, c.Inputs.ContextualMatchScore)
}
}
}
func TestLoadCandidates_CurrentSeed_ScoresZero(t *testing.T) {
f := newFixture(t, 3)
target := f.tracks[1]
likeVec := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
helperInsertContextualLike(t, f, target.ID, likeVec)
currentSeed := SessionVector{Seed: true}
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, currentSeed)
if err != nil {
t.Fatalf("load: %v", err)
}
for _, c := range got {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("seed-current track %s ContextualMatchScore = %v", c.Track.Title, c.Inputs.ContextualMatchScore)
}
t.Error("the liked track is missing from the candidates")
}
}
+35 -156
View File
@@ -21,66 +21,42 @@ func fixedRNG(v float64) func() float64 {
return func() float64 { return v }
}
func TestScore_BaseCase_NeverPlayed_NoJitter(t *testing.T) {
in := ScoringInputs{}
// Score is base + like boost + recency + context + similarity − skip
// penalty, plus jitter, which a fixed RNG of 0.5 zeroes. With the default
// weights a never-played, unliked track scores 2.0 (base 1.0, recency 1.0,
// since never played counts as long ago), and each case moves one term.
func TestScore(t *testing.T) {
now := time.Now().UTC()
got := Score(in, defaultWeights(), now, fixedRNG(0.5))
// rng=0.5 -> jitter contribution = (0.5*2 - 1) * 0.1 = 0
// expected = 1.0 + 0 (not liked) + 1.0 (never played) - 0 + 0 = 2.0
want := 2.0
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_LikeBoost(t *testing.T) {
notLiked := Score(ScoringInputs{}, defaultWeights(), time.Now(), fixedRNG(0.5))
liked := Score(ScoringInputs{IsGeneralLiked: true}, defaultWeights(), time.Now(), fixedRNG(0.5))
if math.Abs(liked-notLiked-2.0) > 1e-9 {
t.Errorf("delta = %v, want 2.0 (LikeBoost)", liked-notLiked)
}
}
func TestScore_RecencyRamp_15Days(t *testing.T) {
now := time.Now().UTC()
played := now.Add(-15 * 24 * time.Hour)
got := Score(ScoringInputs{LastPlayedAt: &played}, defaultWeights(), now, fixedRNG(0.5))
// recency = 0.5 -> contributes 0.5 * 1.0 = 0.5; expected = 1.0 + 0 + 0.5 - 0 + 0 = 1.5
want := 1.5
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_RecencyRamp_60DaysCapsAt1(t *testing.T) {
now := time.Now().UTC()
played := now.Add(-60 * 24 * time.Hour)
got := Score(ScoringInputs{LastPlayedAt: &played}, defaultWeights(), now, fixedRNG(0.5))
want := 2.0 // base + capped recency (1.0)
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_SkipRatio(t *testing.T) {
// 4 plays, 2 skips -> ratio 0.5 -> -0.5 * SkipPenalty = -0.5
in := ScoringInputs{PlayCount: 4, SkipCount: 2}
got := Score(in, defaultWeights(), time.Now(), fixedRNG(0.5))
// recency = 1.0 (never played by virtue of LastPlayedAt being nil even though PlayCount > 0;
// for this test we rely on the recencyDecay treating nil as max). Adjust: the tests above
// explicitly use nil for LastPlayedAt unless set. So: 1.0 + 1.0 - 0.5 = 1.5.
want := 1.5
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_ColdStartSkip_ZeroPlaysZeroSkips(t *testing.T) {
in := ScoringInputs{PlayCount: 0, SkipCount: 0}
got := Score(in, defaultWeights(), time.Now(), fixedRNG(0.5))
want := 2.0 // base + recency, no skip penalty
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
daysAgo := func(d int) *time.Time { p := now.Add(-time.Duration(d) * 24 * time.Hour); return &p }
withContext := func(w ScoringWeights) ScoringWeights { w.ContextWeight = 2.0; return w }
withSimilarity := func(w ScoringWeights) ScoringWeights { w.SimilarityWeight = 2.0; return w }
for _, tc := range []struct {
name string
in ScoringInputs
weights func(ScoringWeights) ScoringWeights
want float64
}{
{"never played", ScoringInputs{}, nil, 2.0},
{"liked", ScoringInputs{IsGeneralLiked: true}, nil, 4.0},
{"played 15 days ago, recency halved", ScoringInputs{LastPlayedAt: daysAgo(15)}, nil, 1.5},
{"played 60 days ago, recency capped at 1", ScoringInputs{LastPlayedAt: daysAgo(60)}, nil, 2.0},
{"half the plays skipped", ScoringInputs{PlayCount: 4, SkipCount: 2}, nil, 1.5},
{"full context match at weight 2", ScoringInputs{ContextualMatchScore: 1.0}, withContext, 4.0},
{"half context match at weight 2", ScoringInputs{ContextualMatchScore: 0.5}, withContext, 3.0},
{"no context match adds nothing", ScoringInputs{}, withContext, 2.0},
{"full similarity at weight 2", ScoringInputs{SimilarityScore: 1.0}, withSimilarity, 4.0},
{"half similarity at weight 2", ScoringInputs{SimilarityScore: 0.5}, withSimilarity, 3.0},
{"no similarity adds nothing", ScoringInputs{}, withSimilarity, 2.0},
} {
t.Run(tc.name, func(t *testing.T) {
w := defaultWeights()
if tc.weights != nil {
w = tc.weights(w)
}
if got := Score(tc.in, w, now, fixedRNG(0.5)); math.Abs(got-tc.want) > 1e-9 {
t.Errorf("score = %v, want %v", got, tc.want)
}
})
}
}
@@ -98,23 +74,6 @@ func TestScore_JitterBounds(t *testing.T) {
}
}
func TestScore_Determinism(t *testing.T) {
in := ScoringInputs{IsGeneralLiked: true, PlayCount: 10, SkipCount: 3}
w := defaultWeights()
now := time.Now().UTC()
a := Score(in, w, now, fixedRNG(0.7))
b := Score(in, w, now, fixedRNG(0.7))
if a != b {
t.Errorf("non-deterministic with fixed RNG: %v vs %v", a, b)
}
}
func TestRecencyDecay_NilIsOne(t *testing.T) {
if got := recencyDecay(nil, time.Now()); got != 1.0 {
t.Errorf("recencyDecay(nil) = %v, want 1.0", got)
}
}
func TestRecencyDecay_Clamping(t *testing.T) {
now := time.Now().UTC()
cases := []struct {
@@ -136,83 +95,3 @@ func TestRecencyDecay_Clamping(t *testing.T) {
})
}
}
func TestSkipRatio_ZeroPlays_IsZero(t *testing.T) {
if got := skipRatio(0, 0); got != 0.0 {
t.Errorf("skipRatio(0,0) = %v, want 0.0", got)
}
}
func TestSkipRatio_Half(t *testing.T) {
if got := skipRatio(4, 2); got != 0.5 {
t.Errorf("skipRatio(4,2) = %v, want 0.5", got)
}
}
func TestScore_ContextualMatch_PerfectMatchAtWeight2(t *testing.T) {
w := defaultWeights()
w.ContextWeight = 2.0
in := ScoringInputs{ContextualMatchScore: 1.0}
got := Score(in, w, time.Now(), fixedRNG(0.5))
// base 1.0 + recency 1.0 (never played) + contextual 2.0 = 4.0
want := 4.0
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_ContextualMatch_HalfMatchAtWeight2(t *testing.T) {
w := defaultWeights()
w.ContextWeight = 2.0
in := ScoringInputs{ContextualMatchScore: 0.5}
got := Score(in, w, time.Now(), fixedRNG(0.5))
// base 1.0 + recency 1.0 + contextual 1.0 = 3.0
want := 3.0
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_ContextualMatch_ZeroNoEffect(t *testing.T) {
wWithCtx := defaultWeights()
wWithCtx.ContextWeight = 2.0
withCtx := Score(ScoringInputs{ContextualMatchScore: 0}, wWithCtx, time.Now(), fixedRNG(0.5))
withoutCtx := Score(ScoringInputs{}, defaultWeights(), time.Now(), fixedRNG(0.5))
if math.Abs(withCtx-withoutCtx) > 1e-9 {
t.Errorf("score-with-zero-ctx = %v, score-without = %v; should be equal", withCtx, withoutCtx)
}
}
func TestScore_SimilarityScore_PerfectMatchAtWeight2(t *testing.T) {
w := defaultWeights()
w.SimilarityWeight = 2.0
in := ScoringInputs{SimilarityScore: 1.0}
got := Score(in, w, time.Now(), fixedRNG(0.5))
// base 1.0 + recency 1.0 (never played) + similarity 2.0 = 4.0
want := 4.0
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_SimilarityScore_HalfMatchAtWeight2(t *testing.T) {
w := defaultWeights()
w.SimilarityWeight = 2.0
in := ScoringInputs{SimilarityScore: 0.5}
got := Score(in, w, time.Now(), fixedRNG(0.5))
// base 1.0 + recency 1.0 + similarity 1.0 = 3.0
want := 3.0
if math.Abs(got-want) > 1e-9 {
t.Errorf("score = %v, want %v", got, want)
}
}
func TestScore_SimilarityScore_ZeroNoEffect(t *testing.T) {
wWithSim := defaultWeights()
wWithSim.SimilarityWeight = 2.0
withSim := Score(ScoringInputs{SimilarityScore: 0}, wWithSim, time.Now(), fixedRNG(0.5))
withoutSim := Score(ScoringInputs{}, defaultWeights(), time.Now(), fixedRNG(0.5))
if math.Abs(withSim-withoutSim) > 1e-9 {
t.Errorf("score-with-zero-sim = %v, score-without = %v; should be equal", withSim, withoutSim)
}
}
+26 -51
View File
@@ -26,58 +26,33 @@ func uuid(s string) pgtype.UUID {
return u
}
func TestBuildSessionVector_Empty_IsSeed(t *testing.T) {
v := BuildSessionVector(nil)
if !v.Seed {
t.Errorf("Seed = false, want true for empty input")
}
if len(v.Artists) != 0 || len(v.Tags) != 0 || len(v.RecentTrackIDs) != 0 {
t.Errorf("non-empty collections: %+v", v)
}
}
func TestBuildSessionVector_OneTrack_IsSeed(t *testing.T) {
// A session is a seed (too short to describe) until it holds three tracks.
// Artists are deduplicated and genres counted, and each track's id is kept.
func TestBuildSessionVector_SeedUntilThreeTracks(t *testing.T) {
a1 := uuid("11111111-1111-1111-1111-111111111111")
tr := track(a1, "rock")
tr.ID = uuid("22222222-2222-2222-2222-222222222222")
v := BuildSessionVector([]dbq.Track{tr})
if !v.Seed {
t.Errorf("1 track: Seed=false, want true (< 3)")
}
if len(v.Artists) != 1 {
t.Errorf("Artists: %+v", v.Artists)
}
if v.Tags["rock"] != 1 {
t.Errorf("Tags: %+v", v.Tags)
}
if len(v.RecentTrackIDs) != 1 {
t.Errorf("RecentTrackIDs: %+v", v.RecentTrackIDs)
}
}
func TestBuildSessionVector_TwoTracks_IsSeed(t *testing.T) {
a1 := uuid("11111111-1111-1111-1111-111111111111")
v := BuildSessionVector([]dbq.Track{track(a1, "rock"), track(a1, "jazz")})
if !v.Seed {
t.Errorf("2 tracks: Seed=false, want true (< 3)")
}
}
func TestBuildSessionVector_ThreeTracks_NotSeed(t *testing.T) {
a1 := uuid("11111111-1111-1111-1111-111111111111")
v := BuildSessionVector([]dbq.Track{
track(a1, "rock"), track(a1, "rock"), track(a1, "rock"),
})
if v.Seed {
t.Errorf("3 tracks: Seed=true, want false")
}
// All same artist → 1 entry.
if len(v.Artists) != 1 {
t.Errorf("Artists len = %d, want 1 (dedup)", len(v.Artists))
}
// All same genre → count 3.
if v.Tags["rock"] != 3 {
t.Errorf("Tags['rock'] = %d, want 3", v.Tags["rock"])
rock := track(a1, "rock")
rock.ID = uuid("22222222-2222-2222-2222-222222222222")
for _, tc := range []struct {
tracks []dbq.Track
seed bool
rockTags int
}{
{nil, true, 0},
{[]dbq.Track{rock}, true, 1},
{[]dbq.Track{rock, track(a1, "jazz")}, true, 1},
{[]dbq.Track{rock, rock, rock}, false, 3},
} {
v := BuildSessionVector(tc.tracks)
n := len(tc.tracks)
if v.Seed != tc.seed {
t.Errorf("%d tracks: Seed = %v, want %v", n, v.Seed, tc.seed)
}
if n > 0 && len(v.Artists) != 1 {
t.Errorf("%d tracks by one artist: Artists = %v, want one", n, v.Artists)
}
if v.Tags["rock"] != tc.rockTags || len(v.RecentTrackIDs) != n {
t.Errorf("%d tracks: rock = %d, recent ids = %d; want %d and %d", n, v.Tags["rock"], len(v.RecentTrackIDs), tc.rockTags, n)
}
}
}
+64 -143
View File
@@ -7,152 +7,73 @@ import (
func approxEq(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
func TestSimilarity_IdenticalVectors_Returns1(t *testing.T) {
v := SessionVector{
Artists: []string{"a1", "a2"},
Tags: map[string]int{"rock": 2, "indie": 1},
}
got := Similarity(v, v, DefaultSimilarityWeights)
if !approxEq(got, 1.0) {
t.Errorf("Similarity(v,v) = %v, want 1.0", got)
// Similarity is the set overlap (Jaccard) of tags weighted 0.7 plus that of
// artists weighted 0.3. Tag counts collapse to a set, an axis empty on either
// side contributes nothing, empty vectors give 0 rather than NaN, and a seed
// vector (too short a session to say anything) matches nothing.
func TestSimilarity(t *testing.T) {
v := SessionVector{Artists: []string{"a1", "a2"}, Tags: map[string]int{"rock": 2, "indie": 1}}
for _, tc := range []struct {
name string
a, b SessionVector
want float64
}{
{"identical", v, v, 1.0},
{"disjoint",
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}},
SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"jazz": 1}}, 0},
{"tags only shared",
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}},
SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"rock": 5}}, 0.7},
{"artists only shared",
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}},
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"jazz": 1}}, 0.3},
{"partial tag overlap",
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1, "indie": 1}},
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1, "jazz": 1}}, 0.7*(1.0/3.0) + 0.3},
{"counts collapse to a set",
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 2, "indie": 1}},
SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 5, "indie": 3}}, 1.0},
{"each side has a different axis",
SessionVector{Tags: map[string]int{"rock": 1}}, SessionVector{Artists: []string{"a1"}}, 0},
{"both empty", SessionVector{}, SessionVector{}, 0},
{"a seed on the right", v, SessionVector{Seed: true, Artists: v.Artists, Tags: v.Tags}, 0},
{"a seed on the left", SessionVector{Seed: true, Artists: v.Artists, Tags: v.Tags}, v, 0},
} {
t.Run(tc.name, func(t *testing.T) {
got := Similarity(tc.a, tc.b, DefaultSimilarityWeights)
if math.IsNaN(got) || !approxEq(got, tc.want) {
t.Errorf("Similarity = %v, want %v", got, tc.want)
}
})
}
}
func TestSimilarity_FullyDisjoint_Returns0(t *testing.T) {
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
b := SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"jazz": 1}}
got := Similarity(a, b, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("disjoint = %v, want 0.0", got)
}
}
func TestSimilarity_TagsOnlyShared_AppliesTagsWeight(t *testing.T) {
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
b := SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"rock": 5}}
got := Similarity(a, b, DefaultSimilarityWeights)
if !approxEq(got, 0.7) {
t.Errorf("tags-only = %v, want 0.7", got)
}
}
func TestSimilarity_ArtistsOnlyShared_AppliesArtistsWeight(t *testing.T) {
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
b := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"jazz": 1}}
got := Similarity(a, b, DefaultSimilarityWeights)
if !approxEq(got, 0.3) {
t.Errorf("artists-only = %v, want 0.3", got)
}
}
func TestSimilarity_EitherSeed_Returns0(t *testing.T) {
v := SessionVector{Artists: []string{"a"}, Tags: map[string]int{"rock": 1}}
seed := SessionVector{Seed: true, Artists: []string{"a"}, Tags: map[string]int{"rock": 1}}
if got := Similarity(v, seed, DefaultSimilarityWeights); !approxEq(got, 0.0) {
t.Errorf("v vs seed = %v, want 0.0", got)
}
if got := Similarity(seed, v, DefaultSimilarityWeights); !approxEq(got, 0.0) {
t.Errorf("seed vs v = %v, want 0.0", got)
}
}
func TestSimilarity_BothEmpty_Returns0NotNaN(t *testing.T) {
a := SessionVector{}
b := SessionVector{}
got := Similarity(a, b, DefaultSimilarityWeights)
if math.IsNaN(got) || !approxEq(got, 0.0) {
t.Errorf("empty = %v, want 0.0 (not NaN)", got)
}
}
func TestSimilarity_OneAxisEmptyOneSide_AxisContributesZero(t *testing.T) {
a := SessionVector{Tags: map[string]int{"rock": 1}}
b := SessionVector{Artists: []string{"a1"}}
got := Similarity(a, b, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("one-axis-each = %v, want 0.0", got)
}
}
func TestSimilarity_PartialTagsOverlap(t *testing.T) {
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1, "indie": 1}}
b := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1, "jazz": 1}}
got := Similarity(a, b, DefaultSimilarityWeights)
want := 0.7*(1.0/3.0) + 0.3*1.0
if !approxEq(got, want) {
t.Errorf("partial = %v, want %v", got, want)
}
}
func TestSimilarity_BagOfCountsCollapsesToSet(t *testing.T) {
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 2, "indie": 1}}
b := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 5, "indie": 3}}
got := Similarity(a, b, DefaultSimilarityWeights)
if !approxEq(got, 1.0) {
t.Errorf("set-collapse = %v, want 1.0", got)
}
}
func TestContextualMatchScore_NoLikes_Returns0(t *testing.T) {
current := SessionVector{Artists: []string{"a"}, Tags: map[string]int{"rock": 1}}
got := ContextualMatchScore(current, nil, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("no likes = %v, want 0.0", got)
}
got = ContextualMatchScore(current, []SessionVector{}, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("empty likes = %v, want 0.0", got)
}
}
func TestContextualMatchScore_CurrentSeed_Returns0(t *testing.T) {
current := SessionVector{Seed: true}
likes := []SessionVector{
{Artists: []string{"a"}, Tags: map[string]int{"rock": 1}},
}
got := ContextualMatchScore(current, likes, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("current seed = %v, want 0.0", got)
}
}
func TestContextualMatchScore_AllLikesSeed_Returns0(t *testing.T) {
current := SessionVector{Artists: []string{"a"}, Tags: map[string]int{"rock": 1}}
likes := []SessionVector{
{Seed: true, Artists: []string{"a"}, Tags: map[string]int{"rock": 1}},
{Seed: true, Artists: []string{"a"}, Tags: map[string]int{"rock": 1}},
}
got := ContextualMatchScore(current, likes, DefaultSimilarityWeights)
if !approxEq(got, 0.0) {
t.Errorf("all-seed likes = %v, want 0.0", got)
}
}
func TestContextualMatchScore_TakesMax(t *testing.T) {
// Three likes: full match, partial match, mismatch. Expect full match (1.0).
// A track's contextual match is its best similarity to the sessions in which
// it was liked, ignoring likes made in a seed session; a current seed session
// matches nothing.
func TestContextualMatchScore(t *testing.T) {
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
// Three likes covering 1.0 (full match), 0.7 (tags-only match), 0.0 (mismatch).
likes := []SessionVector{
{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}},
{Artists: []string{"a2"}, Tags: map[string]int{"rock": 1}},
{Artists: []string{"a99"}, Tags: map[string]int{"jazz": 1}},
}
got := ContextualMatchScore(current, likes, DefaultSimilarityWeights)
if !approxEq(got, 1.0) {
t.Errorf("takes-max = %v, want 1.0", got)
}
}
func TestContextualMatchScore_FiltersSeedThenMaxes(t *testing.T) {
// One Seed=true match (would be 1.0 if not filtered) + one partial match.
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
likes := []SessionVector{
{Seed: true, Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}},
{Artists: []string{"a2"}, Tags: map[string]int{"rock": 1}},
}
got := ContextualMatchScore(current, likes, DefaultSimilarityWeights)
// Seed=true filtered out → only partial match counts → 0.7
if !approxEq(got, 0.7) {
t.Errorf("filter-then-max = %v, want 0.7", got)
full := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
tagsOnly := SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"rock": 1}}
none := SessionVector{Artists: []string{"a99"}, Tags: map[string]int{"jazz": 1}}
seedFull := SessionVector{Seed: true, Artists: full.Artists, Tags: full.Tags}
for _, tc := range []struct {
name string
current SessionVector
likes []SessionVector
want float64
}{
{"no likes", current, nil, 0},
{"the best like counts", current, []SessionVector{full, tagsOnly, none}, 1.0},
{"likes in seed sessions are ignored", current, []SessionVector{seedFull, seedFull}, 0},
{"seed likes are dropped before the max", current, []SessionVector{seedFull, tagsOnly}, 0.7},
{"a seed session matches nothing", SessionVector{Seed: true}, []SessionVector{full}, 0},
} {
t.Run(tc.name, func(t *testing.T) {
if got := ContextualMatchScore(tc.current, tc.likes, DefaultSimilarityWeights); !approxEq(got, tc.want) {
t.Errorf("ContextualMatchScore = %v, want %v", got, tc.want)
}
})
}
}