Files
minstrel/internal/recommendation/candidates_test.go
T
bvandeusenandClaude Opus 5.5 a2dae7ec8c
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
test(playlists, recommendation): system-mix builds stop drawing covers no test reads; merge repeated cases (#8297)
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>
2026-12-02 13:35:36 -05:00

258 lines
8.8 KiB
Go

package recommendation
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
)
type fixture struct {
pool *pgxpool.Pool
q *dbq.Queries
user pgtype.UUID
tracks []dbq.Track // tracks[0] is the canonical seed
}
func newFixture(t *testing.T, n int) fixture {
t.Helper()
pool := dbtest.Pool(t)
q := dbq.New(pool)
u, err := q.CreateUser(context.Background(), dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "tester", PasswordHash: "x", ApiTokenHash: "x", IsAdmin: false,
})
if err != nil {
t.Fatalf("user: %v", err)
}
a, _ := q.UpsertArtist(context.Background(), dbq.UpsertArtistParams{Name: "A", SortName: "A"})
al, _ := q.UpsertAlbum(context.Background(), dbq.UpsertAlbumParams{Title: "B", SortTitle: "B", ArtistID: a.ID})
tracks := make([]dbq.Track, 0, n)
for i := 0; i < n; i++ {
tr, err := q.UpsertTrack(context.Background(), dbq.UpsertTrackParams{
Title: string(rune('A' + i)),
AlbumID: al.ID,
ArtistID: a.ID,
FilePath: "/tmp/track-" + string(rune('A'+i)) + ".flac",
DurationMs: 120_000,
})
if err != nil {
t.Fatalf("track[%d]: %v", i, err)
}
tracks = append(tracks, tr)
}
return fixture{pool: pool, q: q, user: u.ID, tracks: tracks}
}
func TestLoadCandidates_ExcludesSeed(t *testing.T) {
f := newFixture(t, 5)
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, SessionVector{Seed: true})
if err != nil {
t.Fatalf("LoadCandidates: %v", err)
}
if len(got) != 4 {
t.Fatalf("len = %d, want 4 (5 minus seed)", len(got))
}
for _, c := range got {
if c.Track.ID == f.tracks[0].ID {
t.Errorf("seed appeared in candidate set")
}
}
}
func TestLoadCandidates_ExcludesRecentlyPlayed(t *testing.T) {
f := newFixture(t, 3)
// Seed = tracks[0]. Other tracks are tracks[1], tracks[2].
// Insert a play_session and a play_event for tracks[1] 30 minutes ago.
now := time.Now().UTC()
thirtyMinAgo := now.Add(-30 * time.Minute)
sess, _ := f.q.InsertPlaySession(context.Background(), dbq.InsertPlaySessionParams{
UserID: f.user,
StartedAt: pgtype.Timestamptz{Time: thirtyMinAgo, Valid: true},
ClientID: nil,
})
_, _ = f.q.InsertPlayEvent(context.Background(), dbq.InsertPlayEventParams{
UserID: f.user,
TrackID: f.tracks[1].ID,
SessionID: sess.ID,
StartedAt: pgtype.Timestamptz{Time: thirtyMinAgo, Valid: true},
ClientID: nil,
})
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, SessionVector{Seed: true})
if err != nil {
t.Fatalf("LoadCandidates: %v", err)
}
// Expect tracks[2] only (seed excluded, tracks[1] excluded by recently-played).
if len(got) != 1 {
t.Fatalf("len = %d, want 1; got=%v", len(got), trackTitles(got))
}
if got[0].Track.ID != f.tracks[2].ID {
t.Errorf("expected tracks[2], got %v", got[0].Track.Title)
}
}
func TestLoadCandidates_StatJoin(t *testing.T) {
f := newFixture(t, 2)
// Seed = tracks[0]. Like tracks[1]; play it twice (one skip, one full play) 2 hours ago.
if _, err := f.q.LikeTrack(context.Background(), dbq.LikeTrackParams{UserID: f.user, TrackID: f.tracks[1].ID}); err != nil {
t.Fatalf("like: %v", err)
}
twoH := time.Now().UTC().Add(-2 * time.Hour)
sess, _ := f.q.InsertPlaySession(context.Background(), dbq.InsertPlaySessionParams{
UserID: f.user, StartedAt: pgtype.Timestamptz{Time: twoH, Valid: true},
})
// First play: completed (was_skipped=false).
pe1, _ := f.q.InsertPlayEvent(context.Background(), dbq.InsertPlayEventParams{
UserID: f.user, TrackID: f.tracks[1].ID, SessionID: sess.ID,
StartedAt: pgtype.Timestamptz{Time: twoH, Valid: true},
})
dur := int32(120_000)
ratio := 1.0
_, _ = f.q.UpdatePlayEventEnded(context.Background(), dbq.UpdatePlayEventEndedParams{
ID: pe1.ID, EndedAt: pgtype.Timestamptz{Time: twoH.Add(2 * time.Minute), Valid: true},
DurationPlayedMs: &dur, CompletionRatio: &ratio, WasSkipped: false,
})
// Second play: skipped (was_skipped=true).
pe2, _ := f.q.InsertPlayEvent(context.Background(), dbq.InsertPlayEventParams{
UserID: f.user, TrackID: f.tracks[1].ID, SessionID: sess.ID,
StartedAt: pgtype.Timestamptz{Time: twoH.Add(5 * time.Minute), Valid: true},
})
dur2 := int32(5_000)
ratio2 := 0.04
_, _ = f.q.UpdatePlayEventEnded(context.Background(), dbq.UpdatePlayEventEndedParams{
ID: pe2.ID, EndedAt: pgtype.Timestamptz{Time: twoH.Add(5*time.Minute + 5*time.Second), Valid: true},
DurationPlayedMs: &dur2, CompletionRatio: &ratio2, WasSkipped: true,
})
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, SessionVector{Seed: true})
if err != nil {
t.Fatalf("LoadCandidates: %v", err)
}
if len(got) != 1 {
t.Fatalf("len = %d, want 1", len(got))
}
c := got[0]
if !c.Inputs.IsGeneralLiked {
t.Errorf("IsGeneralLiked = false, want true")
}
if c.Inputs.PlayCount != 2 {
t.Errorf("PlayCount = %d, want 2", c.Inputs.PlayCount)
}
if c.Inputs.SkipCount != 1 {
t.Errorf("SkipCount = %d, want 1", c.Inputs.SkipCount)
}
if c.Inputs.LastPlayedAt == nil {
t.Errorf("LastPlayedAt = nil, want non-nil")
}
}
func TestLoadCandidates_NeverPlayedHasNilLastPlayed(t *testing.T) {
f := newFixture(t, 2)
got, err := LoadCandidates(context.Background(), f.q, f.user, f.tracks[0].ID, 1, SessionVector{Seed: true})
if err != nil {
t.Fatalf("LoadCandidates: %v", err)
}
if len(got) != 1 {
t.Fatalf("len = %d, want 1", len(got))
}
if got[0].Inputs.LastPlayedAt != nil {
t.Errorf("never-played track has non-nil LastPlayedAt: %v", got[0].Inputs.LastPlayedAt)
}
if got[0].Inputs.PlayCount != 0 || got[0].Inputs.SkipCount != 0 {
t.Errorf("never-played track has non-zero counts: %+v", got[0].Inputs)
}
}
func TestLoadCandidates_CrossUserIsolation(t *testing.T) {
f := newFixture(t, 2)
bob, _ := f.q.CreateUser(context.Background(), dbq.CreateUserParams{
Username: dbtest.TestUserPrefix + "bob", PasswordHash: "x", ApiTokenHash: "y", IsAdmin: false,
})
// Alice likes tracks[1]; Bob shouldn't see it.
_, _ = f.q.LikeTrack(context.Background(), dbq.LikeTrackParams{UserID: f.user, TrackID: f.tracks[1].ID})
got, err := LoadCandidates(context.Background(), f.q, bob.ID, f.tracks[0].ID, 1, SessionVector{Seed: true})
if err != nil {
t.Fatalf("LoadCandidates: %v", err)
}
for _, c := range got {
if c.Track.ID == f.tracks[1].ID && c.Inputs.IsGeneralLiked {
t.Errorf("bob sees alice's like on track %v", c.Track.Title)
}
}
}
func trackTitles(cs []Candidate) []string {
out := make([]string, 0, len(cs))
for _, c := range cs {
out = append(out, c.Track.Title)
}
return out
}
// helperInsertContextualLike likes the track and inserts a contextual_like
// row with the given session_vector marshaled to JSON, as a like while
// playing does. Bypasses playevents.CaptureContextualLikeIfPlaying because we
// want full control over the stored vector for these unit tests. (Only a
// still-liked song's context counts, so the like has to be there too.)
func helperInsertContextualLike(t *testing.T, f fixture, trackID pgtype.UUID, vec SessionVector) {
t.Helper()
raw, err := json.Marshal(vec)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if _, err := f.pool.Exec(context.Background(),
`INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
f.user, trackID); err != nil {
t.Fatalf("like: %v", err)
}
if _, err := f.pool.Exec(context.Background(),
`INSERT INTO contextual_likes (user_id, track_id, session_vector) VALUES ($1, $2, $3)`,
f.user, trackID, raw); err != nil {
t.Fatalf("insert: %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)
}
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 {
score := c.Inputs.ContextualMatchScore
switch {
case c.Track.ID == liked.ID:
found = true
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("the liked track is missing from the candidates")
}
}