package recommendation import ( "context" "encoding/json" "errors" "log/slog" "strconv" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "git.fabledsword.com/bvandeusen/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. 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. return Shuffle(candidates, p.Weights(), time.Now().UTC(), p.Rand, limit, RadioDiversityCaps(limit)), 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. 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 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 }