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
+1 -8
View File
@@ -303,14 +303,7 @@ jobs:
PKGS=$(sh ci/db-test-packages.sh) PKGS=$(sh ci/db-test-packages.sh)
echo "database test packages: $(echo "$PKGS" | wc -l)" echo "database test packages: $(echo "$PKGS" | wc -l)"
go test -race -run '^$' $PKGS go test -race -run '^$' $PKGS
# TEMPORARY (#8297): one run with per-test durations, slowest first. go test -p 1 -race -timeout 20m $PKGS
rc=0
go test -p 1 -race -timeout 20m -v $PKGS > /tmp/gotest.log 2>&1 || rc=$?
grep -E '^(ok|FAIL|panic)|--- FAIL' /tmp/gotest.log || true
echo "::group::slowest database tests"
grep -E '^--- (PASS|FAIL)' /tmp/gotest.log | sed -E 's/^--- [A-Z]+: (\S+) \(([0-9.]+)s\)/\2 \1/' | sort -rn | head -150
echo "::endgroup::"
exit $rc
web: web:
runs-on: go-ci runs-on: go-ci
+29 -49
View File
@@ -38,57 +38,37 @@ func makeCand(trackN, albumN, artistN int, similarity float64) recommendation.Ca
} }
} }
func TestCapCandidatesByAlbumAndArtist_AlbumCap(t *testing.T) { // A mix keeps at most discoverMaxTracksPerAlbum (2) tracks from one album and
// discoverMaxTracksPerAlbum = 2: third track on album 10 must be dropped. // discoverMaxTracksPerArtist (3) by one artist, dropping the later ones and
in := []recommendation.Candidate{ // keeping the order of the rest.
makeCand(1, 10, 100, 1.0), func TestCapCandidatesByAlbumAndArtist(t *testing.T) {
makeCand(2, 10, 101, 0.9), for _, tc := range []struct {
makeCand(3, 10, 102, 0.8), // 3rd from album 10 → drop name string
makeCand(4, 11, 103, 0.7), in []recommendation.Candidate
want []byte // track numbers kept, in order
}{
{"a third track from one album", []recommendation.Candidate{
makeCand(1, 10, 100, 1.0), makeCand(2, 10, 101, 0.9), makeCand(3, 10, 102, 0.8), makeCand(4, 11, 103, 0.7),
}, []byte{1, 2, 4}},
{"a fourth track by one artist", []recommendation.Candidate{
makeCand(1, 10, 100, 1.0), makeCand(2, 11, 100, 0.9), makeCand(3, 12, 100, 0.8),
makeCand(4, 13, 100, 0.7), makeCand(5, 14, 101, 0.6),
}, []byte{1, 2, 3, 5}},
{"nothing over a cap keeps its order", []recommendation.Candidate{
makeCand(3, 10, 100, 0.5), makeCand(1, 11, 101, 0.9), makeCand(2, 12, 102, 0.7),
}, []byte{3, 1, 2}},
{"empty", nil, nil},
} {
t.Run(tc.name, func(t *testing.T) {
got := capCandidatesByAlbumAndArtist(tc.in)
ids := make([]byte, len(got))
for i, c := range got {
ids[i] = c.Track.ID.Bytes[15]
} }
got := capCandidatesByAlbumAndArtist(in) if string(ids) != string(tc.want) {
if len(got) != 3 { t.Errorf("kept %v, want %v", ids, tc.want)
t.Errorf("len = %d, want 3 (album 10 capped at 2)", len(got))
} }
} })
func TestCapCandidatesByAlbumAndArtist_ArtistCap(t *testing.T) {
// discoverMaxTracksPerArtist = 3: fourth track by artist 100 must be dropped.
in := []recommendation.Candidate{
makeCand(1, 10, 100, 1.0),
makeCand(2, 11, 100, 0.9),
makeCand(3, 12, 100, 0.8),
makeCand(4, 13, 100, 0.7), // 4th by artist 100 → drop
makeCand(5, 14, 101, 0.6),
}
got := capCandidatesByAlbumAndArtist(in)
if len(got) != 4 {
t.Errorf("len = %d, want 4 (artist 100 capped at 3)", len(got))
}
}
func TestCapCandidatesByAlbumAndArtist_PreservesOrder(t *testing.T) {
// All distinct albums and artists: all kept, original order preserved.
in := []recommendation.Candidate{
makeCand(3, 10, 100, 0.5),
makeCand(1, 11, 101, 0.9),
makeCand(2, 12, 102, 0.7),
}
got := capCandidatesByAlbumAndArtist(in)
if len(got) != 3 {
t.Fatalf("len = %d, want 3", len(got))
}
for i, want := range []byte{3, 1, 2} {
if got[i].Track.ID.Bytes[15] != want {
t.Errorf("got[%d].ID = %d, want %d", i, got[i].Track.ID.Bytes[15], want)
}
}
}
func TestCapCandidatesByAlbumAndArtist_Empty(t *testing.T) {
got := capCandidatesByAlbumAndArtist(nil)
if len(got) != 0 {
t.Errorf("len = %d, want 0", len(got))
} }
} }
+1 -1
View File
@@ -191,7 +191,7 @@ func TestBuildSystemPlaylists_GenreMixes(t *testing.T) {
seedPlayEvent(t, pool, u.ID, tr.ID, now.Add(-time.Duration(i+1)*time.Hour), false) seedPlayEvent(t, pool, u.ID, tr.ID, now.Add(-time.Duration(i+1)*time.Hour), false)
} }
if err := playlists.BuildSystemPlaylists(ctx, pool, discardLogger(), u.ID, now, t.TempDir()); err != nil { if err := playlists.BuildSystemPlaylists(ctx, pool, discardLogger(), u.ID, now, ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
+221 -433
View File
@@ -13,467 +13,255 @@ import (
"github.com/Fabled-Sword/minstrel/internal/playlists" "github.com/Fabled-Sword/minstrel/internal/playlists"
) )
func TestCreate_HappyPath(t *testing.T) { // A playlist is its owner's to change. Anyone may see a public one, only the
pool := dbtest.Pool(t) // owner a private one, and an unknown id is not found rather than forbidden.
user := seedUser(t, pool, "alice") // The REST API and the Subsonic endpoints both rely on these answers.
dir := t.TempDir() func TestService_WhoMaySeeAndChangeAPlaylist(t *testing.T) {
ctx := context.Background()
svc := playlists.NewService(pool, nil, dir)
row, err := svc.Create(context.Background(), user.ID, "Saturday morning", "Mellow", false)
if err != nil {
t.Fatalf("Create: %v", err)
}
if row.Name != "Saturday morning" {
t.Errorf("name = %q, want Saturday morning", row.Name)
}
if row.IsPublic {
t.Error("IsPublic = true, want false (default)")
}
if row.OwnerUsername != "test-alice" {
t.Errorf("OwnerUsername = %q, want test-alice", row.OwnerUsername)
}
if row.TrackCount != 0 || row.DurationSec != 0 {
t.Errorf("rollups should start at 0; got count=%d duration=%d", row.TrackCount, row.DurationSec)
}
}
func TestCreate_EmptyNameRejected(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
_, err := svc.Create(context.Background(), user.ID, "", "", false)
if !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("err = %v, want ErrInvalidInput", err)
}
}
func TestGet_NotFound(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
_, err := svc.Get(context.Background(), user.ID, randomUUID())
if !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
}
func TestGet_Forbidden_PrivatePlaylistFromOtherUser(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Private", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
if _, err := svc.Get(context.Background(), bob.ID, pl.ID); !errors.Is(err, playlists.ErrForbidden) {
t.Errorf("err = %v, want ErrForbidden", err)
}
}
func TestGet_Public_VisibleToOtherUser(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Public mix", "", true)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
got, err := svc.Get(context.Background(), bob.ID, pl.ID)
if err != nil {
t.Fatalf("Get: %v", err)
}
if got.Name != "Public mix" {
t.Errorf("name = %q", got.Name)
}
if !got.IsPublic {
t.Error("IsPublic = false, want true")
}
if len(got.Tracks) != 0 {
t.Errorf("Tracks len = %d, want 0 for an empty playlist", len(got.Tracks))
}
}
func TestGet_Owner_SeesOwnPrivate(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Mine", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
got, err := svc.Get(context.Background(), alice.ID, pl.ID)
if err != nil {
t.Fatalf("Get: %v", err)
}
if got.Name != "Mine" {
t.Errorf("name = %q", got.Name)
}
}
func TestList_OwnAndPublic(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
svc := playlists.NewService(pool, nil, t.TempDir())
if _, err := svc.Create(context.Background(), alice.ID, "Alice private", "", false); err != nil {
t.Fatalf("seed: %v", err)
}
if _, err := svc.Create(context.Background(), alice.ID, "Alice public", "", true); err != nil {
t.Fatalf("seed: %v", err)
}
if _, err := svc.Create(context.Background(), bob.ID, "Bob private", "", false); err != nil {
t.Fatalf("seed: %v", err)
}
if _, err := svc.Create(context.Background(), bob.ID, "Bob public", "", true); err != nil {
t.Fatalf("seed: %v", err)
}
rows, err := svc.List(context.Background(), alice.ID)
if err != nil {
t.Fatalf("List: %v", err)
}
if len(rows) != 3 {
t.Errorf("alice's list = %d rows, want 3 (her 2 + bob's public)", len(rows))
}
for _, r := range rows {
if r.Name == "Bob private" {
t.Errorf("alice's list leaked bob's private playlist")
}
}
}
func TestUpdate_OwnerOnly(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Mine", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
rename := "Renamed"
if _, err := svc.Update(context.Background(), bob.ID, pl.ID, playlists.UpdateInput{Name: &rename}); !errors.Is(err, playlists.ErrForbidden) {
t.Errorf("err = %v, want ErrForbidden", err)
}
updated, err := svc.Update(context.Background(), alice.ID, pl.ID, playlists.UpdateInput{Name: &rename})
if err != nil {
t.Fatalf("owner Update: %v", err)
}
if updated.Name != "Renamed" {
t.Errorf("name = %q, want Renamed", updated.Name)
}
}
func TestUpdate_PartialFieldsLeaveOthersAlone(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Original", "Long description", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
// Touch only IsPublic — name and description must survive.
pub := true
updated, err := svc.Update(context.Background(), alice.ID, pl.ID, playlists.UpdateInput{IsPublic: &pub})
if err != nil {
t.Fatalf("Update: %v", err)
}
if updated.Name != "Original" {
t.Errorf("name = %q, want unchanged Original", updated.Name)
}
if updated.Description != "Long description" {
t.Errorf("description = %q, want unchanged", updated.Description)
}
if !updated.IsPublic {
t.Error("IsPublic = false, want true after toggle")
}
}
func TestUpdate_EmptyNameRejected(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Original", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
empty := ""
if _, err := svc.Update(context.Background(), alice.ID, pl.ID, playlists.UpdateInput{Name: &empty}); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("err = %v, want ErrInvalidInput", err)
}
}
func TestUpdate_NotFound(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
rename := "Renamed"
if _, err := svc.Update(context.Background(), alice.ID, randomUUID(), playlists.UpdateInput{Name: &rename}); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
}
func TestDelete_OwnerOnly(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(context.Background(), alice.ID, "Mine", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
if err := svc.Delete(context.Background(), bob.ID, pl.ID); !errors.Is(err, playlists.ErrForbidden) {
t.Errorf("non-owner err = %v, want ErrForbidden", err)
}
if err := svc.Delete(context.Background(), alice.ID, pl.ID); err != nil {
t.Fatalf("owner Delete: %v", err)
}
// Idempotency: a second delete reports NotFound rather than silently succeeding.
if err := svc.Delete(context.Background(), alice.ID, pl.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("repeat Delete err = %v, want ErrNotFound", err)
}
}
func TestDelete_NotFound(t *testing.T) {
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
if err := svc.Delete(context.Background(), alice.ID, randomUUID()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
}
func TestDelete_RemovesCoverFile(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
dir := t.TempDir()
svc := playlists.NewService(pool, nil, dir)
pl, err := svc.Create(context.Background(), user.ID, "Will be deleted", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
// Simulate the collage generator having stashed a file at the
// path stored on the row. The Delete path should clean it up.
coverDir := filepath.Join(dir, "playlist_covers")
if err := os.MkdirAll(coverDir, 0o755); err != nil {
t.Fatalf("mkdir cover dir: %v", err)
}
relPath := filepath.Join("playlist_covers", uuidString(pl.ID)+".jpg")
full := filepath.Join(dir, relPath)
if err := os.WriteFile(full, []byte("jpeg-bytes"), 0o644); err != nil {
t.Fatalf("seed cover file: %v", err)
}
if _, err := pool.Exec(context.Background(),
`UPDATE playlists SET cover_path = $1 WHERE id = $2`, relPath, pl.ID); err != nil {
t.Fatalf("set cover_path: %v", err)
}
if err := svc.Delete(context.Background(), user.ID, pl.ID); err != nil {
t.Fatalf("Delete: %v", err)
}
if _, statErr := os.Stat(full); !errors.Is(statErr, os.ErrNotExist) {
t.Errorf("cover file still on disk after delete: stat err=%v", statErr)
}
}
func TestDelete_MissingCoverFileTolerated(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
dir := t.TempDir()
svc := playlists.NewService(pool, nil, dir)
pl, err := svc.Create(context.Background(), user.ID, "No cover on disk", "", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
// Set cover_path to a file that doesn't exist — Delete must not
// error on a missing cached file; it's just cleanup.
relPath := filepath.Join("playlist_covers", uuidString(pl.ID)+".jpg")
if _, err := pool.Exec(context.Background(),
`UPDATE playlists SET cover_path = $1 WHERE id = $2`, relPath, pl.ID); err != nil {
t.Fatalf("set cover_path: %v", err)
}
if err := svc.Delete(context.Background(), user.ID, pl.ID); err != nil {
t.Fatalf("Delete with missing cover file: %v", err)
}
}
func TestAppendTracks_Snapshot(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
track := seedTrack(t, pool, "Prismatic", "Fields of Ontario")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false)
if err := svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{track.ID}); err != nil {
t.Fatalf("AppendTracks: %v", err)
}
got, _ := svc.Get(context.Background(), user.ID, pl.ID)
if len(got.Tracks) != 1 {
t.Fatalf("Tracks length = %d, want 1", len(got.Tracks))
}
if got.Tracks[0].Title != "Prismatic" {
t.Errorf("Title snapshot = %q, want Prismatic", got.Tracks[0].Title)
}
if got.Tracks[0].ArtistName != "Fields of Ontario" {
t.Errorf("ArtistName snapshot = %q, want Fields of Ontario", got.Tracks[0].ArtistName)
}
if got.TrackCount != 1 {
t.Errorf("rollup TrackCount = %d, want 1", got.TrackCount)
}
}
func TestAppendTracks_OwnerOnly(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice") alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob") bob := seedUser(t, pool, "bob")
track := seedTrack(t, pool, "T", "A") track := seedTrack(t, pool, "T", "A")
svc := playlists.NewService(pool, nil, t.TempDir()) svc := playlists.NewService(pool, nil, t.TempDir())
create := func(owner pgtype.UUID, name string, public bool) *playlists.PlaylistRow {
t.Helper()
row, err := svc.Create(ctx, owner, name, "", public)
if err != nil {
t.Fatalf("Create %q: %v", name, err)
}
return row
}
pl, _ := svc.Create(context.Background(), alice.ID, "Mine", "", true) private := create(alice.ID, "Alice private", false)
err := svc.AppendTracks(context.Background(), bob.ID, pl.ID, []pgtype.UUID{track.ID}) public := create(alice.ID, "Alice public", true)
if !errors.Is(err, playlists.ErrForbidden) { create(bob.ID, "Bob private", false)
t.Errorf("err = %v, want ErrForbidden", err) create(bob.ID, "Bob public", true)
if private.OwnerUsername != "test-alice" || private.TrackCount != 0 || private.DurationSec != 0 {
t.Errorf("created row = %+v, want owner test-alice and empty rollups", private)
}
rename := "Renamed"
for _, tc := range []struct {
name string
do func() error
want error
}{
{"the owner sees her private playlist", func() error { _, err := svc.Get(ctx, alice.ID, private.ID); return err }, nil},
{"another user can't see it", func() error { _, err := svc.Get(ctx, bob.ID, private.ID); return err }, playlists.ErrForbidden},
{"another user sees a public one", func() error { _, err := svc.Get(ctx, bob.ID, public.ID); return err }, nil},
{"an unknown id is not found", func() error { _, err := svc.Get(ctx, alice.ID, randomUUID()); return err }, playlists.ErrNotFound},
{"another user can't rename it", func() error {
_, err := svc.Update(ctx, bob.ID, public.ID, playlists.UpdateInput{Name: &rename})
return err
}, playlists.ErrForbidden},
{"renaming an unknown id", func() error {
_, err := svc.Update(ctx, alice.ID, randomUUID(), playlists.UpdateInput{Name: &rename})
return err
}, playlists.ErrNotFound},
{"another user can't add to a public one", func() error {
return svc.AppendTracks(ctx, bob.ID, public.ID, []pgtype.UUID{track.ID})
}, playlists.ErrForbidden},
{"another user can't delete it", func() error { return svc.Delete(ctx, bob.ID, public.ID) }, playlists.ErrForbidden},
{"deleting an unknown id", func() error { return svc.Delete(ctx, alice.ID, randomUUID()) }, playlists.ErrNotFound},
} {
if err := tc.do(); !errors.Is(err, tc.want) {
t.Errorf("%s: err = %v, want %v", tc.name, err, tc.want)
} }
} }
func TestAppendTracks_NonExistentTrack(t *testing.T) { rows, err := svc.List(ctx, alice.ID)
if err != nil {
t.Fatalf("List: %v", err)
}
names := map[string]bool{}
for _, r := range rows {
names[r.Name] = true
}
if len(rows) != 3 || !names["Alice private"] || !names["Alice public"] || !names["Bob public"] {
t.Errorf("alice's list = %v, want her two and bob's public one", names)
}
if updated, err := svc.Update(ctx, alice.ID, private.ID, playlists.UpdateInput{Name: &rename}); err != nil || updated.Name != "Renamed" {
t.Errorf("owner rename = %+v, %v; want Renamed", updated, err)
}
if err := svc.Delete(ctx, alice.ID, private.ID); err != nil {
t.Fatalf("owner Delete: %v", err)
}
// A second delete reports NotFound rather than silently succeeding.
if err := svc.Delete(ctx, alice.ID, private.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("repeat Delete err = %v, want ErrNotFound", err)
}
}
// Bad input is refused as ErrInvalidInput, which the API answers with 400:
// an empty name on create or rename, and a reorder that isn't a permutation
// of the playlist's positions. A track that doesn't exist is its own error.
func TestService_RefusesBadInput(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice") alice := seedUser(t, pool, "alice")
t1 := seedTrack(t, pool, "T1", "A")
t2 := seedTrack(t, pool, "T2", "A")
svc := playlists.NewService(pool, nil, t.TempDir()) svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false) if _, err := svc.Create(ctx, alice.ID, "", "", false); !errors.Is(err, playlists.ErrInvalidInput) {
err := svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{randomUUID()}) t.Errorf("Create with no name: err = %v, want ErrInvalidInput", err)
if !errors.Is(err, playlists.ErrTrackNotFound) { }
t.Errorf("err = %v, want ErrTrackNotFound", err) pl, err := svc.Create(ctx, alice.ID, "Two", "", false)
if err != nil {
t.Fatal(err)
}
empty := ""
if _, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{Name: &empty}); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("rename to nothing: err = %v, want ErrInvalidInput", err)
}
if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{randomUUID()}); !errors.Is(err, playlists.ErrTrackNotFound) {
t.Errorf("append an unknown track: err = %v, want ErrTrackNotFound", err)
}
if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID}); err != nil {
t.Fatal(err)
}
for _, order := range [][]int32{{0, 1, 2}, {0, 0}, {1}} {
if err := svc.Reorder(ctx, alice.ID, pl.ID, order); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("Reorder %v of two tracks: err = %v, want ErrInvalidInput", order, err)
}
} }
} }
func TestRemoveTrack_RenumbersPositions(t *testing.T) { // An update changes only the fields it carries.
func TestService_UpdateLeavesFieldsItDoesNotCarry(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice") alice := seedUser(t, pool, "alice")
t1 := seedTrack(t, pool, "Track 1", "Artist")
t2 := seedTrack(t, pool, "Track 2", "Artist")
t3 := seedTrack(t, pool, "Track 3", "Artist")
svc := playlists.NewService(pool, nil, t.TempDir()) svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false) pl, err := svc.Create(ctx, alice.ID, "Original", "Long description", false)
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID, t3.ID}) if err != nil {
t.Fatalf("seed Create: %v", err)
}
pub := true
updated, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{IsPublic: &pub})
if err != nil {
t.Fatalf("Update: %v", err)
}
if updated.Name != "Original" || updated.Description != "Long description" || !updated.IsPublic {
t.Errorf("after toggling public: %+v; want name and description unchanged", updated)
}
}
// Remove the middle one (position 1). // A playlist's entries keep a snapshot of each track's title and artist, so an
if err := svc.RemoveTrack(context.Background(), user.ID, pl.ID, 1, pgtype.UUID{}); err != nil { // entry survives its track being deleted, shown by name with no track id.
// Removing an entry renumbers the rest, and a reorder applies a permutation.
func TestService_TrackListEdits(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
a := seedTrack(t, pool, "Prismatic", "Fields of Ontario")
b := seedTrack(t, pool, "B", "Artist")
c := seedTrack(t, pool, "C", "Artist")
d := seedTrack(t, pool, "D", "Artist")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(ctx, user.ID, "Test", "", false)
if err != nil {
t.Fatal(err)
}
titles := func() []string {
t.Helper()
got, err := svc.Get(ctx, user.ID, pl.ID)
if err != nil {
t.Fatal(err)
}
out := make([]string, len(got.Tracks))
for i, pt := range got.Tracks {
if int(pt.Position) != i {
t.Errorf("entry %d has position %d", i, pt.Position)
}
out[i] = pt.Title
}
return out
}
expect := func(step string, want ...string) {
t.Helper()
if got := titles(); !equal(got, want) {
t.Errorf("after %s: %q, want %q", step, got, want)
}
}
if err := svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID, c.ID, d.ID}); err != nil {
t.Fatalf("AppendTracks: %v", err)
}
got, _ := svc.Get(ctx, user.ID, pl.ID)
if got.TrackCount != 4 || got.Tracks[0].ArtistName != "Fields of Ontario" {
t.Errorf("after append: count %d, first artist %q; want 4 and the snapshot artist", got.TrackCount, got.Tracks[0].ArtistName)
}
if err := svc.RemoveTrack(ctx, user.ID, pl.ID, 1, pgtype.UUID{}); err != nil {
t.Fatalf("RemoveTrack: %v", err) t.Fatalf("RemoveTrack: %v", err)
} }
expect("removing position 1", "Prismatic", "C", "D")
got, _ := svc.Get(context.Background(), user.ID, pl.ID) if err := svc.Reorder(ctx, user.ID, pl.ID, []int32{2, 1, 0}); err != nil {
if len(got.Tracks) != 2 {
t.Fatalf("Tracks length = %d, want 2", len(got.Tracks))
}
if got.Tracks[0].Title != "Track 1" {
t.Errorf("position 0 = %q, want Track 1", got.Tracks[0].Title)
}
if got.Tracks[1].Title != "Track 3" {
t.Errorf("position 1 = %q, want Track 3 (renumbered from 2)", got.Tracks[1].Title)
}
}
func TestReorder_Permutation(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
t1 := seedTrack(t, pool, "A", "Artist")
t2 := seedTrack(t, pool, "B", "Artist")
t3 := seedTrack(t, pool, "C", "Artist")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false)
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID, t3.ID})
// Reverse order: send [2, 1, 0].
if err := svc.Reorder(context.Background(), user.ID, pl.ID, []int32{2, 1, 0}); err != nil {
t.Fatalf("Reorder: %v", err) t.Fatalf("Reorder: %v", err)
} }
expect("reversing", "D", "C", "Prismatic")
got, _ := svc.Get(context.Background(), user.ID, pl.ID) if _, err := pool.Exec(ctx, `DELETE FROM tracks WHERE id = $1`, a.ID); err != nil {
wantOrder := []string{"C", "B", "A"}
for i, pt := range got.Tracks {
if pt.Title != wantOrder[i] {
t.Errorf("position %d = %q, want %q", i, pt.Title, wantOrder[i])
}
}
}
func TestReorder_RejectsNonPermutation(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
tk := seedTrack(t, pool, "T", "A")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false)
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{tk.ID})
// 2 positions for a 1-track playlist — invalid.
err := svc.Reorder(context.Background(), user.ID, pl.ID, []int32{0, 1})
if !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("err = %v, want ErrInvalidInput (length mismatch)", err)
}
pl2, _ := svc.Create(context.Background(), user.ID, "Two", "", false)
t2 := seedTrack(t, pool, "T2", "A")
_ = svc.AppendTracks(context.Background(), user.ID, pl2.ID, []pgtype.UUID{tk.ID, t2.ID})
err = svc.Reorder(context.Background(), user.ID, pl2.ID, []int32{0, 0})
if !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("err = %v, want ErrInvalidInput (duplicate)", err)
}
}
func TestSnapshotPersistsAfterUpstreamTrackDelete(t *testing.T) {
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
tk := seedTrack(t, pool, "Doomed track", "Artist")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, _ := svc.Create(context.Background(), user.ID, "Test", "", false)
_ = svc.AppendTracks(context.Background(), user.ID, pl.ID, []pgtype.UUID{tk.ID})
// Delete the track row directly (simulating a re-import / file removal).
if _, err := pool.Exec(context.Background(), `DELETE FROM tracks WHERE id = $1`, tk.ID); err != nil {
t.Fatalf("delete track: %v", err) t.Fatalf("delete track: %v", err)
} }
got, _ = svc.Get(ctx, user.ID, pl.ID)
if len(got.Tracks) != 3 || got.Tracks[2].Title != "Prismatic" || got.Tracks[2].TrackID != nil {
t.Errorf("after the track's deletion: %+v; want the entry kept by name, with no track id", got.Tracks)
}
}
got, _ := svc.Get(context.Background(), user.ID, pl.ID) // Deleting a playlist removes its cached cover from disk, and a cover file
if len(got.Tracks) != 1 { // already gone is no obstacle.
t.Fatalf("Tracks length = %d, want 1 (soft-mark not silent-cascade)", len(got.Tracks)) func TestService_DeleteRemovesTheCoverFile(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
dir := t.TempDir()
svc := playlists.NewService(pool, nil, dir)
if err := os.MkdirAll(filepath.Join(dir, "playlist_covers"), 0o755); err != nil {
t.Fatal(err)
} }
row := got.Tracks[0] withCover := func(name string, onDisk bool) (*playlists.PlaylistRow, string) {
if row.TrackID != nil { t.Helper()
t.Error("TrackID should be nil after upstream delete") pl, err := svc.Create(ctx, user.ID, name, "", false)
if err != nil {
t.Fatal(err)
} }
if row.Title != "Doomed track" { rel := filepath.Join("playlist_covers", uuidString(pl.ID)+".jpg")
t.Errorf("Snapshot Title = %q, want Doomed track", row.Title) if onDisk {
if err := os.WriteFile(filepath.Join(dir, rel), []byte("jpeg-bytes"), 0o644); err != nil {
t.Fatal(err)
} }
} }
if _, err := pool.Exec(ctx, `UPDATE playlists SET cover_path = $1 WHERE id = $2`, rel, pl.ID); err != nil {
t.Fatal(err)
}
return pl, filepath.Join(dir, rel)
}
pl, full := withCover("With a cover", true)
if err := svc.Delete(ctx, user.ID, pl.ID); err != nil {
t.Fatalf("Delete: %v", err)
}
if _, err := os.Stat(full); !errors.Is(err, os.ErrNotExist) {
t.Errorf("cover file still on disk after delete: %v", err)
}
gone, _ := withCover("Cover already gone", false)
if err := svc.Delete(ctx, user.ID, gone.ID); err != nil {
t.Errorf("Delete with its cover file already gone: %v", err)
}
}
func equal(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
+59 -69
View File
@@ -126,6 +126,12 @@ func TestBuildSystemPlaylists_SufficientActivity(t *testing.T) {
if r.TrackCount == 0 { if r.TrackCount == 0 {
t.Errorf("row %s: empty track_count", uuidString(r.ID)) t.Errorf("row %s: empty track_count", uuidString(r.ID))
} }
// The one build test that draws covers: every mix gets one. The
// others pass no data folder, which skips drawing, since a JPEG per
// mix is most of a build's time under -race.
if r.CoverPath == nil {
t.Errorf("row %s: no collage cover", uuidString(r.ID))
}
// For-You / Discover / the discovery mixes are sized to ~100 // For-You / Discover / the discovery mixes are sized to ~100
// songs_like_artist stays at systemMixLength (25). // songs_like_artist stays at systemMixLength (25).
if r.TrackCount > 100 { if r.TrackCount > 100 {
@@ -163,7 +169,7 @@ func TestBuildSystemPlaylists_StaleActivity_SongsLikeSurvives(t *testing.T) {
} }
} }
if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil { if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
@@ -201,7 +207,7 @@ func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) {
quarantined := tracks[0] quarantined := tracks[0]
seedQuarantine(t, pool, u.ID, quarantined.ID) seedQuarantine(t, pool, u.ID, quarantined.ID)
if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil { if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
@@ -228,65 +234,6 @@ func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) {
} }
} }
// A rebuild refills each mix in place: a Subsonic app caches, pins and
// downloads a playlist by id, so the same mix keeps its id from one build to
// the next, and no mix is left behind twice.
func TestBuildSystemPlaylists_ARebuildKeepsEachMixsID(t *testing.T) {
pool := dbtest.Pool(t)
logger := discardLogger()
u, _ := seedActiveLibrary(t, pool, "atomic", 3, 3)
ctx := context.Background()
dir := t.TempDir()
// A mix is named by its name AND its seed artist: the fixtures make one
// artist row per track, all named alike, so two Songs like mixes can
// share a name (see snapshotSystemTracks).
list := func() map[string]pgtype.UUID {
t.Helper()
rows, err := pool.Query(ctx, `
SELECT p.name || ' [' || COALESCE(p.seed_artist_id::text, '-') || ']', p.id
FROM playlists p
WHERE p.user_id = $1 AND p.kind = 'system'`, u.ID)
if err != nil {
t.Fatalf("list: %v", err)
}
defer rows.Close()
out := map[string]pgtype.UUID{}
for rows.Next() {
var mix string
var id pgtype.UUID
if err := rows.Scan(&mix, &id); err != nil {
t.Fatalf("scan: %v", err)
}
if _, dup := out[mix]; dup {
t.Fatalf("mix %q is held twice", mix)
}
out[mix] = id
}
if err := rows.Err(); err != nil {
t.Fatalf("rows: %v", err)
}
return out
}
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
t.Fatalf("first build: %v", err)
}
first := list()
if len(first) == 0 {
t.Fatal("no system playlists from the first build")
}
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
t.Fatalf("second build: %v", err)
}
second := list()
for name, id := range first {
if again, ok := second[name]; ok && again != id {
t.Errorf("mix %q got a new id on rebuild: %s then %s", name, uuidString(id), uuidString(again))
}
}
}
func TestBuildSystemPlaylists_Concurrency(t *testing.T) { func TestBuildSystemPlaylists_Concurrency(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
logger := discardLogger() logger := discardLogger()
@@ -296,9 +243,8 @@ func TestBuildSystemPlaylists_Concurrency(t *testing.T) {
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(2) wg.Add(2)
dataDir := t.TempDir() go func() { defer wg.Done(); _ = playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, "") }()
go func() { defer wg.Done(); _ = playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, dataDir) }() go func() { defer wg.Done(); _ = playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, "") }()
go func() { defer wg.Done(); _ = playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, dataDir) }()
wg.Wait() wg.Wait()
// Exactly one run must have completed; in_flight must be false either way. // Exactly one run must have completed; in_flight must be false either way.
@@ -390,7 +336,7 @@ func TestBuildSystemPlaylists_SongsLikeIncludesItsSeedArtist(t *testing.T) {
ctx := context.Background() ctx := context.Background()
now := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC) now := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC)
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, t.TempDir()); err != nil { if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, now, ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
@@ -445,6 +391,9 @@ func TestBuildSystemPlaylists_SongsLikeIncludesItsSeedArtist(t *testing.T) {
} }
} }
// A same-day rebuild picks the same tracks, and refills each mix in place: a
// Subsonic app caches, pins and downloads a playlist by id, so the same mix
// keeps its id from one build to the next, and no mix is held twice.
func TestBuildSystemPlaylists_DailyNonceDeterminism(t *testing.T) { func TestBuildSystemPlaylists_DailyNonceDeterminism(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
logger := discardLogger() logger := discardLogger()
@@ -452,22 +401,63 @@ func TestBuildSystemPlaylists_DailyNonceDeterminism(t *testing.T) {
ctx := context.Background() ctx := context.Background()
day1 := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC) day1 := time.Date(2026, 5, 4, 12, 0, 0, 0, time.UTC)
dataDir := t.TempDir() if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, day1, ""); err != nil {
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, day1, dataDir); err != nil {
t.Fatalf("build day1 first: %v", err) t.Fatalf("build day1 first: %v", err)
} }
snap1 := snapshotSystemTracks(t, pool, u.ID) snap1 := snapshotSystemTracks(t, pool, u.ID)
ids1 := systemMixIDs(t, pool, u.ID)
if len(ids1) == 0 {
t.Fatal("no system playlists from the first build")
}
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, day1, dataDir); err != nil { if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, day1, ""); err != nil {
t.Fatalf("build day1 second: %v", err) t.Fatalf("build day1 second: %v", err)
} }
snap2 := snapshotSystemTracks(t, pool, u.ID) snap2 := snapshotSystemTracks(t, pool, u.ID)
ids2 := systemMixIDs(t, pool, u.ID)
for mix, id := range ids1 {
if again, ok := ids2[mix]; ok && again != id {
t.Errorf("mix %q got a new id on rebuild: %s then %s", mix, uuidString(id), uuidString(again))
}
}
if !equalSnapshots(snap1, snap2) { if !equalSnapshots(snap1, snap2) {
t.Errorf("same-day rebuild produced different track lists: %s", describeSnapshotDiff(snap1, snap2)) t.Errorf("same-day rebuild produced different track lists: %s", describeSnapshotDiff(snap1, snap2))
} }
} }
// systemMixIDs maps each of the user's system mixes to its playlist id. A mix
// is named by its name AND its seed artist: the fixtures make one artist row
// per track, all named alike, so two Songs like mixes can share a name (see
// snapshotSystemTracks). A mix held twice fails the test.
func systemMixIDs(t *testing.T, pool *pgxpool.Pool, userID pgtype.UUID) map[string]pgtype.UUID {
t.Helper()
rows, err := pool.Query(context.Background(), `
SELECT p.name || ' [' || COALESCE(p.seed_artist_id::text, '-') || ']', p.id
FROM playlists p
WHERE p.user_id = $1 AND p.kind = 'system'`, userID)
if err != nil {
t.Fatalf("list: %v", err)
}
defer rows.Close()
out := map[string]pgtype.UUID{}
for rows.Next() {
var mix string
var id pgtype.UUID
if err := rows.Scan(&mix, &id); err != nil {
t.Fatalf("scan: %v", err)
}
if _, dup := out[mix]; dup {
t.Fatalf("mix %q is held twice", mix)
}
out[mix] = id
}
if err := rows.Err(); err != nil {
t.Fatalf("rows: %v", err)
}
return out
}
// snapshotSystemTracks returns a per-mix → []track_id mapping for the // snapshotSystemTracks returns a per-mix → []track_id mapping for the
// user's system playlists, in playlist_tracks position order. // user's system playlists, in playlist_tracks position order.
// //
@@ -604,7 +594,7 @@ func TestBuildSystemPlaylists_DiscoverColdStart(t *testing.T) {
t.Fatalf("clear plays: %v", err) t.Fatalf("clear plays: %v", err)
} }
if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil { if err := playlists.BuildSystemPlaylists(context.Background(), pool, logger, u.ID, time.Now().UTC(), ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
+18 -38
View File
@@ -39,7 +39,7 @@ func TestYouMightLike_ColdStartGate(t *testing.T) {
u, _ := seedActiveLibrary(t, pool, "ymlcold", 3, 3) u, _ := seedActiveLibrary(t, pool, "ymlcold", 3, 3)
if err := playlists.BuildSystemPlaylists( if err := playlists.BuildSystemPlaylists(
context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir(), context.Background(), pool, logger, u.ID, time.Now().UTC(), "",
); err != nil { ); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
@@ -51,50 +51,30 @@ func TestYouMightLike_ColdStartGate(t *testing.T) {
} }
} }
// TestYouMightLike_SufficientActivityPopulates: a rich profile (8 artists // A rich profile (8 artists × 4 tracks = 32 distinct tracks, clearing both
// × 4 tracks = 32 distinct tracks, clearing both gate bars) populates the // gate bars) populates the You-might-like tables in the daily build, and a
// You-might-like tables in the daily build. // second build replaces those rows rather than adding to them, so the counts
func TestYouMightLike_SufficientActivityPopulates(t *testing.T) { // stay within the persisted depth.
func TestYouMightLike_PopulatesAndAReplaceKeepsTheDepth(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
logger := discardLogger() logger := discardLogger()
u, _ := seedActiveLibrary(t, pool, "ymlrich", 8, 4) u, _ := seedActiveLibrary(t, pool, "ymlrich", 8, 4)
ctx := context.Background()
if err := playlists.BuildSystemPlaylists( build := func() {
context.Background(), pool, logger, u.ID, time.Now().UTC(), t.TempDir(), t.Helper()
); err != nil { if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), ""); err != nil {
t.Fatalf("build: %v", err) t.Fatalf("build: %v", err)
} }
}
build()
albums, artists := countYouMightLike(t, pool, u.ID) albums, artists := countYouMightLike(t, pool, u.ID)
if albums == 0 { if albums == 0 || artists == 0 {
t.Error("rich user should have you-might-like album rows; got 0") t.Fatalf("rich user has %d album and %d artist rows; want some of each", albums, artists)
} }
if artists == 0 { build()
t.Error("rich user should have you-might-like artist rows; got 0") albums, artists = countYouMightLike(t, pool, u.ID)
} if albums > 12 || artists > 12 {
} t.Errorf("after two builds: %d albums, %d artists; want <= 12 each (atomic replace)", albums, artists)
// TestYouMightLike_AtomicReplace: a second build replaces rather than
// appends, so counts stay bounded by the persisted depth.
func TestYouMightLike_AtomicReplace(t *testing.T) {
pool := dbtest.Pool(t)
logger := discardLogger()
u, _ := seedActiveLibrary(t, pool, "ymlreplace", 8, 4)
ctx := context.Background()
for i := 0; i < 2; i++ {
if err := playlists.BuildSystemPlaylists(
ctx, pool, logger, u.ID, time.Now().UTC(), t.TempDir(),
); err != nil {
t.Fatalf("build %d: %v", i, err)
}
}
albums, artists := countYouMightLike(t, pool, u.ID)
if albums > 12 {
t.Errorf("albums = %d after two builds, want <= 12 (atomic replace)", albums)
}
if artists > 12 {
t.Errorf("artists = %d after two builds, want <= 12 (atomic replace)", artists)
} }
} }
+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) { // LoadCandidates gives each candidate the contextual match of its likes
f := newFixture(t, 5) // (ContextualMatchScore, tested on its own above): a track liked in a session
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}} // like the current one scores about 1, a track whose like was withdrawn
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, current) // (soft-deleted) and a track never liked score 0.
if err != nil { func TestLoadCandidates_ContextualLikesReachTheirTracks(t *testing.T) {
t.Fatalf("load: %v", err) f := newFixture(t, 4)
} liked, withdrawn := f.tracks[1], f.tracks[2]
for _, c := range got { session := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
if c.Inputs.ContextualMatchScore != 0 { helperInsertContextualLike(t, f, liked.ID, session)
t.Errorf("track %s ContextualMatchScore = %v, want 0", c.Track.Title, c.Inputs.ContextualMatchScore) 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)
} }
func TestLoadCandidates_OneMatchingLike_ScoresPositive(t *testing.T) { got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, session)
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)
if err != nil { if err != nil {
t.Fatalf("load: %v", err) t.Fatalf("load: %v", err)
} }
var found bool var found bool
for _, c := range got { for _, c := range got {
if c.Track.ID == target.ID { score := c.Inputs.ContextualMatchScore
switch {
case c.Track.ID == liked.ID:
found = true found = true
if c.Inputs.ContextualMatchScore < 0.99 { if score < 0.99 {
t.Errorf("target ContextualMatchScore = %v, want ~1.0", c.Inputs.ContextualMatchScore) t.Errorf("liked track scores %v, want ~1.0", score)
}
} else {
if c.Inputs.ContextualMatchScore != 0 {
t.Errorf("non-target track has ContextualMatchScore = %v", c.Inputs.ContextualMatchScore)
} }
case score != 0:
t.Errorf("track %s scores %v, want 0", c.Track.Title, score)
} }
} }
if !found { if !found {
t.Error("target track missing from candidate list") t.Error("the liked track is missing from the candidates")
}
}
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)
}
} }
} }
+33 -154
View File
@@ -21,66 +21,42 @@ func fixedRNG(v float64) func() float64 {
return func() float64 { return v } return func() float64 { return v }
} }
func TestScore_BaseCase_NeverPlayed_NoJitter(t *testing.T) { // Score is base + like boost + recency + context + similarity − skip
in := ScoringInputs{} // 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() now := time.Now().UTC()
got := Score(in, defaultWeights(), now, fixedRNG(0.5)) daysAgo := func(d int) *time.Time { p := now.Add(-time.Duration(d) * 24 * time.Hour); return &p }
// rng=0.5 -> jitter contribution = (0.5*2 - 1) * 0.1 = 0 withContext := func(w ScoringWeights) ScoringWeights { w.ContextWeight = 2.0; return w }
// expected = 1.0 + 0 (not liked) + 1.0 (never played) - 0 + 0 = 2.0 withSimilarity := func(w ScoringWeights) ScoringWeights { w.SimilarityWeight = 2.0; return w }
want := 2.0 for _, tc := range []struct {
if math.Abs(got-want) > 1e-9 { name string
t.Errorf("score = %v, want %v", got, want) 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)
} }
})
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)
} }
} }
@@ -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) { func TestRecencyDecay_Clamping(t *testing.T) {
now := time.Now().UTC() now := time.Now().UTC()
cases := []struct { 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)
}
}
+23 -48
View File
@@ -26,58 +26,33 @@ func uuid(s string) pgtype.UUID {
return u return u
} }
func TestBuildSessionVector_Empty_IsSeed(t *testing.T) { // A session is a seed (too short to describe) until it holds three tracks.
v := BuildSessionVector(nil) // Artists are deduplicated and genres counted, and each track's id is kept.
if !v.Seed { func TestBuildSessionVector_SeedUntilThreeTracks(t *testing.T) {
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) {
a1 := uuid("11111111-1111-1111-1111-111111111111") a1 := uuid("11111111-1111-1111-1111-111111111111")
tr := track(a1, "rock") rock := track(a1, "rock")
tr.ID = uuid("22222222-2222-2222-2222-222222222222") rock.ID = uuid("22222222-2222-2222-2222-222222222222")
v := BuildSessionVector([]dbq.Track{tr}) for _, tc := range []struct {
if !v.Seed { tracks []dbq.Track
t.Errorf("1 track: Seed=false, want true (< 3)") 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 len(v.Artists) != 1 { if n > 0 && len(v.Artists) != 1 {
t.Errorf("Artists: %+v", v.Artists) t.Errorf("%d tracks by one artist: Artists = %v, want one", n, v.Artists)
} }
if v.Tags["rock"] != 1 { if v.Tags["rock"] != tc.rockTags || len(v.RecentTrackIDs) != n {
t.Errorf("Tags: %+v", v.Tags) t.Errorf("%d tracks: rock = %d, recent ids = %d; want %d and %d", n, v.Tags["rock"], len(v.RecentTrackIDs), tc.rockTags, n)
} }
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"])
} }
} }
+62 -141
View File
@@ -7,152 +7,73 @@ import (
func approxEq(a, b float64) bool { return math.Abs(a-b) < 1e-9 } func approxEq(a, b float64) bool { return math.Abs(a-b) < 1e-9 }
func TestSimilarity_IdenticalVectors_Returns1(t *testing.T) { // Similarity is the set overlap (Jaccard) of tags weighted 0.7 plus that of
v := SessionVector{ // artists weighted 0.3. Tag counts collapse to a set, an axis empty on either
Artists: []string{"a1", "a2"}, // side contributes nothing, empty vectors give 0 rather than NaN, and a seed
Tags: map[string]int{"rock": 2, "indie": 1}, // 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)
} }
got := Similarity(v, v, DefaultSimilarityWeights) })
if !approxEq(got, 1.0) {
t.Errorf("Similarity(v,v) = %v, want 1.0", got)
} }
} }
func TestSimilarity_FullyDisjoint_Returns0(t *testing.T) { // A track's contextual match is its best similarity to the sessions in which
a := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}} // it was liked, ignoring likes made in a seed session; a current seed session
b := SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"jazz": 1}} // matches nothing.
got := Similarity(a, b, DefaultSimilarityWeights) func TestContextualMatchScore(t *testing.T) {
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).
current := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}} 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). full := SessionVector{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}
likes := []SessionVector{ tagsOnly := SessionVector{Artists: []string{"a2"}, Tags: map[string]int{"rock": 1}}
{Artists: []string{"a1"}, Tags: map[string]int{"rock": 1}}, none := SessionVector{Artists: []string{"a99"}, Tags: map[string]int{"jazz": 1}}
{Artists: []string{"a2"}, Tags: map[string]int{"rock": 1}}, seedFull := SessionVector{Seed: true, Artists: full.Artists, Tags: full.Tags}
{Artists: []string{"a99"}, Tags: map[string]int{"jazz": 1}}, 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)
} }
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)
} }
} }