diff --git a/internal/recommendation/radio.go b/internal/recommendation/radio.go index dcee9975..9f1d2a5d 100644 --- a/internal/recommendation/radio.go +++ b/internal/recommendation/radio.go @@ -51,7 +51,8 @@ func (p *Picker) logger() *slog.Logger { // Radio returns up to limit tracks to play after seedID, the seed itself not // among them. Candidates come from tracks similar to the seed, and fall back // to the whole library if that pool cannot be loaded. exclude keeps tracks -// already queued out. +// already queued out. The picks are spread (SpreadArtists) so the seed's own +// artist, whose songs match it best, doesn't open the radio back to back. func (p *Picker) Radio(ctx context.Context, q *dbq.Queries, userID, seedID pgtype.UUID, limit int, exclude []pgtype.UUID) ([]Candidate, error) { limit = p.bound(limit) if limit <= 0 { @@ -80,7 +81,14 @@ func (p *Picker) Radio(ctx context.Context, q *dbq.Queries, userID, seedID pgtyp } // Diversity caps scaled to the length asked for, so a 20-track radio // and a 200-track one are capped alike. - return Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)), nil + picks := Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)) + // The seed plays first, so its artist counts as just played. An unknown + // seed only loses that: the picks are still spread among themselves. + var seedArtist pgtype.UUID + if seed, err := q.GetTrackByID(ctx, seedID); err == nil { + seedArtist = seed.ArtistID + } + return SpreadArtists(picks, seedArtist), nil } // noSeed is a track id no track has. The whole-library candidate query @@ -90,7 +98,8 @@ var noSeed = pgtype.UUID{Valid: true} // Shuffle returns up to limit tracks from the whole library, chosen by the // same scoring as radio (what the user likes, skips and has heard lately) -// rather than at random. keep, when not nil, narrows the library first. +// rather than at random, and spread so one artist doesn't play back to back. +// keep, when not nil, narrows the library first. func (p *Picker) Shuffle(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, limit int, keep func(dbq.Track) bool) ([]Candidate, error) { limit = p.bound(limit) if limit <= 0 { @@ -109,7 +118,7 @@ func (p *Picker) Shuffle(ctx context.Context, q *dbq.Queries, userID pgtype.UUID } candidates = kept } - return Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)), nil + return SpreadArtists(Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit))), nil } // currentContext is what the user is listening in right now: the session diff --git a/internal/recommendation/spread.go b/internal/recommendation/spread.go new file mode 100644 index 00000000..1bc3378e --- /dev/null +++ b/internal/recommendation/spread.go @@ -0,0 +1,64 @@ +package recommendation + +import "github.com/jackc/pgx/v5/pgtype" + +// artistGap is how many other songs SpreadArtists puts between two songs by +// one artist when the picks allow it. Radio's best matches are usually the +// seed artist's own songs, and played in score order they would open the +// radio back to back; three songs between them keeps the artist present +// without the radio sounding like an album. +const artistGap = 3 + +// SpreadArtists reorders picks so that, where another choice exists, an +// artist doesn't play again within artistGap songs. It changes only the +// order, never which songs are picked. +// +// Each slot takes the best-scoring remaining pick whose artist is outside the +// gap, so the strongest picks stay near the front. When every remaining pick +// is by a recently played artist, the slot takes the one whose artist was +// played longest ago, so a pool of two artists alternates rather than +// clumping. A pick with no known artist is never held back. +// +// lastPlayed lists the artists heard just before these picks, oldest first: +// a radio's seed song plays first, so its artist counts as just played. +func SpreadArtists(picks []Candidate, lastPlayed ...pgtype.UUID) []Candidate { + if len(picks) < 2 { + return picks + } + remaining := append([]Candidate(nil), picks...) + out := make([]Candidate, 0, len(picks)) + // lastAt is the position each artist last played at, counting the + // lastPlayed songs as positions before 0. + lastAt := make(map[[16]byte]int, len(picks)) + for i, a := range lastPlayed { + if a.Valid { + lastAt[a.Bytes] = i - len(lastPlayed) + } + } + for len(remaining) > 0 { + pos := len(out) + choice := -1 + oldest, oldestAt := -1, 0 + for i, c := range remaining { + a := c.Track.ArtistID + at, played := lastAt[a.Bytes] + if !a.Valid || !played || pos-at > artistGap { + choice = i + break + } + if oldest < 0 || at < oldestAt { + oldest, oldestAt = i, at + } + } + if choice < 0 { + choice = oldest + } + c := remaining[choice] + remaining = append(remaining[:choice], remaining[choice+1:]...) + if c.Track.ArtistID.Valid { + lastAt[c.Track.ArtistID.Bytes] = pos + } + out = append(out, c) + } + return out +} diff --git a/internal/recommendation/spread_test.go b/internal/recommendation/spread_test.go new file mode 100644 index 00000000..b945b2ee --- /dev/null +++ b/internal/recommendation/spread_test.go @@ -0,0 +1,101 @@ +package recommendation + +import ( + "fmt" + "slices" + "testing" + + "github.com/jackc/pgx/v5/pgtype" +) + +// tooClose lists each pick whose artist already played within artistGap songs +// before it, counting lastPlayed as the songs heard just before the picks. +func tooClose(picks []Candidate, lastPlayed ...pgtype.UUID) []string { + var heard []pgtype.UUID + heard = append(heard, lastPlayed...) + var out []string + for _, c := range picks { + a := c.Track.ArtistID + from := max(0, len(heard)-artistGap) + if a.Valid && slices.Contains(heard[from:], a) { + out = append(out, c.Track.Title) + } + heard = append(heard, a) + } + return out +} + +func artistOf(t *testing.T, artist string) pgtype.UUID { + t.Helper() + var id pgtype.UUID + if err := id.Scan("00000000-0000-0000-0001-" + artist); err != nil { + t.Fatal(err) + } + return id +} + +// A radio seeded from one artist: that artist's songs match best, so in score +// order they come first, back to back, right after the seed. Spread, the seed's +// artist waits artistGap songs and then never plays twice within the gap, and +// the radio holds exactly the same songs. +func TestSpreadArtists_TheSeedArtistDoesNotOpenTheRadioBackToBack(t *testing.T) { + const seed = "00000000000d" + var picks []Candidate + for i := 0; i < 4; i++ { + picks = append(picks, candBy(t, fmt.Sprintf("d%011d", i), seed, "000000000001", ScoringInputs{})) + } + // Twelve others: room for the seed artist's four songs each artistGap + // apart after the seed, as a 50-song radio capped at 6 per artist has. + for i := 0; i < 12; i++ { + picks = append(picks, candBy(t, fmt.Sprintf("o%011d", i), fmt.Sprintf("%012d", 100+i), fmt.Sprintf("%012d", 100+i), ScoringInputs{})) + } + seedArtist := artistOf(t, seed) + + // The check below has to be able to fail: score order itself breaks it. + if len(tooClose(picks, seedArtist)) == 0 { + t.Fatal("score order already keeps the seed artist apart, so this fixture proves nothing") + } + + spread := SpreadArtists(picks, seedArtist) + if bad := tooClose(spread, seedArtist); len(bad) > 0 { + t.Errorf("%v play within %d songs of the same artist: %v", bad, artistGap, titles(spread)) + } + if got, want := titles(spread)[0], "o00000000000"; got != want { + t.Errorf("first pick %s, want %s: the best pick by another artist", got, want) + } + if !sameSongs(spread, picks) { + t.Errorf("spreading changed which songs were picked: %v from %v", titles(spread), titles(picks)) + } +} + +// Two artists can't keep artistGap apart, so they alternate rather than +// clumping. +func TestSpreadArtists_TwoArtistsAlternate(t *testing.T) { + var picks []Candidate + for i := 0; i < 3; i++ { + picks = append(picks, candBy(t, fmt.Sprintf("a%011d", i), "00000000000a", "000000000001", ScoringInputs{})) + } + for i := 0; i < 3; i++ { + picks = append(picks, candBy(t, fmt.Sprintf("b%011d", i), "00000000000b", "000000000002", ScoringInputs{})) + } + got := titles(SpreadArtists(picks)) + want := []string{"a00000000000", "b00000000000", "a00000000001", "b00000000001", "a00000000002", "b00000000002"} + if !slices.Equal(got, want) { + t.Errorf("got %v, want %v", got, want) + } +} + +// Picks with no known artist are never held back, so their order stands. +func TestSpreadArtists_UnknownArtistsKeepTheirOrder(t *testing.T) { + picks := []Candidate{cand("000000000001", ScoringInputs{}), cand("000000000002", ScoringInputs{}), cand("000000000003", ScoringInputs{})} + if got := titles(SpreadArtists(picks)); !slices.Equal(got, titles(picks)) { + t.Errorf("got %v, want the order unchanged", got) + } +} + +func sameSongs(a, b []Candidate) bool { + x, y := titles(a), titles(b) + slices.Sort(x) + slices.Sort(y) + return slices.Equal(x, y) +}