Files
minstrel/internal/recommendation/radio.go
T
bvandeusenandClaude Opus 5.5 27e3725e54
release / web (push) Successful in 1m17s
release / go (push) Failing after 1m42s
release / govulncheck (push) Successful in 17s
release / integration (push) Failing after 3m57s
release / android (push) Successful in 4m23s
release / Build signed APK (push) Successful in 4m50s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Verify release artifacts (tag releases only) (push) Skipped
fix(recommendation): radio and shuffle keep one artist's songs apart (#8216)
Radio returned its picks in score order, and a seed's own artist matches
it best, so a DROELOE radio opened with four DROELOE songs in a row. The
artist cap bounded how many songs an artist got, not where they played.

SpreadArtists reorders picks so an artist doesn't play again within
three songs where another choice exists. Each slot takes the best
remaining pick outside that gap; when none is, the artist heard longest
ago goes next, so two artists alternate. Which songs are picked doesn't
change. Radio counts the seed's artist as just played; the library
shuffle spreads from a blank start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:48:04 -05:00

169 lines
6.0 KiB
Go

package recommendation
import (
"context"
"encoding/json"
"errors"
"log/slog"
"strconv"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
)
// Picker chooses what plays next: a radio after a seed track, or a weighted
// shuffle of the whole library. Minstrel's own API and the Subsonic API both
// pick through it, so an app on either one gets the same choices.
type Picker struct {
// Weights returns the scoring weights to use, read on every pick so a
// change in the admin tuning applies at once.
Weights func() ScoringWeights
// Rand is the jitter source for scoring.
Rand func() float64
// RecentlyPlayedHours keeps a track played this recently out of a pick.
RecentlyPlayedHours int
// LibrarySize sizes radio's candidate pool to the library. Nil counts on
// every pick instead of caching (LibrarySize.Get explains).
LibrarySize *LibrarySize
// MaxLength is the most tracks one pick returns; 0 leaves it unbounded.
MaxLength int
Logger *slog.Logger
}
// bound clamps a requested length to MaxLength.
func (p *Picker) bound(limit int) int {
if p.MaxLength > 0 && limit > p.MaxLength {
return p.MaxLength
}
return limit
}
func (p *Picker) logger() *slog.Logger {
if p.Logger != nil {
return p.Logger
}
return slog.Default()
}
// 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. 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 {
return nil, nil
}
current := p.currentContext(ctx, q, userID)
// Size the pool to the library: a fixed ~170 candidates samples a
// shrinking fraction of a growing collection.
librarySize := p.LibrarySize.Get(ctx, func(ctx context.Context) (int64, error) {
return CountLibraryTracks(ctx, q)
})
limits := ScaleForLibrary(DefaultCandidateSourceLimits(), librarySize)
candidates, err := LoadCandidatesFromSimilarity(ctx, q, userID, seedID,
p.RecentlyPlayedHours, current, exclude, limits,
// A fresh order seed per pick: each radio is a new session and
// should draw differently. The system mixes are the surfaces that
// promise repeatability; radio is not one of them.
strconv.FormatInt(time.Now().UnixNano(), 36),
)
if err != nil {
p.logger().Warn("radio: similarity pool failed; falling back to the whole library", "err", err)
candidates, err = LoadCandidates(ctx, q, userID, seedID, p.RecentlyPlayedHours, current)
if err != nil {
return nil, err
}
}
// Diversity caps scaled to the length asked for, so a 20-track radio
// and a 200-track one are capped alike.
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
// leaves out its seed with `id <> seed`, and a NULL seed would leave out
// every row, so a shuffle with no seed passes this instead.
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, 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 {
return nil, nil
}
candidates, err := LoadCandidates(ctx, q, userID, noSeed, p.RecentlyPlayedHours, p.currentContext(ctx, q, userID))
if err != nil {
return nil, err
}
if keep != nil {
kept := candidates[:0]
for _, c := range candidates {
if keep(c.Track) {
kept = append(kept, c)
}
}
candidates = kept
}
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
// vector of their latest open play, conditioned on the device of their latest
// play. With no session it is the Seed sentinel, which scores the contextual
// term as nothing.
func (p *Picker) currentContext(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) SessionVector {
v := p.currentSessionVector(ctx, q, userID)
v.DeviceClass = p.latestDeviceClass(ctx, q, userID)
return v
}
func (p *Picker) currentSessionVector(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) SessionVector {
raw, err := q.GetCurrentSessionVectorForUser(ctx, userID)
if err != nil {
// No rows is the common case: no session yet.
if !errors.Is(err, pgx.ErrNoRows) {
p.logger().Warn("radio: load current session vector", "err", err)
}
return SessionVector{Seed: true}
}
if len(raw) == 0 {
return SessionVector{Seed: true}
}
var v SessionVector
if err := json.Unmarshal(raw, &v); err != nil {
p.logger().Warn("radio: bad session_vector_at_play json", "err", err)
return SessionVector{Seed: true}
}
return v
}
// latestDeviceClass is the device of the user's latest play, or "" when
// unknown. A failed lookup yields the device-agnostic affinity.
func (p *Picker) latestDeviceClass(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) string {
dc, err := q.GetLatestPlayDeviceClassForUser(ctx, userID)
if err != nil {
if !errors.Is(err, pgx.ErrNoRows) {
p.logger().Warn("radio: latest device class", "err", err)
}
return ""
}
if dc == nil {
return ""
}
return *dc
}