Files
minstrel/internal/recommendation/radio.go
T
bvandeusenandClaude Opus 5.5 e1f270362d
release / go (push) Successful in 2m7s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 4m30s
release / android (push) Successful in 4m39s
release / Build signed APK (push) Successful in 5m10s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 29s
release / Verify release artifacts (tag releases only) (push) Skipped
chore(release): everything that ships points at GitHub and GHCR (#7897)
- Module path: github.com/Fabled-Sword/minstrel, in go.mod, every
  import and the Dockerfile's version ldflags.
- buildinfo.ProjectURL, the contact outside services see in Minstrel's
  User-Agent: https://github.com/Fabled-Sword/minstrel.
- README's compose example pulls ghcr.io/fabled-sword/minstrel:latest.
- docs/security.md sends problem reports to the GitHub issues.
- The demo-library stack builds Minstrel from the checkout, since :dev
  is not published to GHCR.
- hygiene.go's same-site example uses example.com names.

The workbench CI (.gitea/, ci/, export-ignored) still builds and
publishes :dev to the private registry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:28:16 -05:00

160 lines
5.5 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.
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
}