feat(subsonic): playlists and daily mixes, the weighted shuffle, and radio
release / go (push) Successful in 2m0s
release / web (push) Successful in 1m23s
release / govulncheck (push) Successful in 20s
release / integration (push) Failing after 4m23s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 2m8s
release / android (push) Canceled after 3m38s

Subsonic apps now get what Minstrel picks, not only what it holds:

- getPlaylists lists the listener's daily mixes first, then their own
  playlists, then other people's public ones; getPlaylist returns the
  playable songs in order, as <entry> elements in XML.
- getRandomSongs answers with the weighted shuffle (likes up, skips down,
  the last hour's plays out), narrowed by genre and release year.
- getSimilarSongs and getSimilarSongs2 answer with Minstrel's radio, seeded
  from a song, or from a random song of an album or artist.

Radio's selection moves out of the /api/radio handler into
recommendation.Picker, built by recsettings.Service.Picker, so the web and
Android apps and the Subsonic apps pick through one piece of code and one
tuning. SongRef loses its XMLName so the field holding it names the element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 14:25:49 -05:00
co-authored by Claude Opus 5.5
parent 66861a2bc4
commit bb2897dfd5
10 changed files with 1106 additions and 120 deletions
+17 -93
View File
@@ -1,14 +1,10 @@
package api
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -26,10 +22,8 @@ type RadioResponse struct {
// handleRadio implements GET /api/radio?seed_track=<uuid>&limit=<int>.
//
// Returns the seed at index 0, followed by up to limit-1 weighted-shuffle
// picks from the user's library, scored by recommendation.Score. The
// scoring formula folds in contextual_match_score using the user's current
// session vector (read from the most recent open play_event).
// Returns the seed at index 0, followed by up to limit-1 picks from
// recommendation.Picker.Radio.
func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
user, ok := requireUser(w, r)
if !ok {
@@ -81,55 +75,15 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
return
}
currentVec := loadCurrentSessionVector(r, q, user.ID, h.logger)
// Condition on the current device: the latest play's device is a
// cheap, request-free proxy for what the user is on right now.
currentVec.DeviceClass = latestDeviceClass(r.Context(), q, user.ID, h.logger)
exclude := parseExcludeParam(r.URL.Query().Get("exclude"))
// Size the pool to the library: a fixed ~170 candidates samples a shrinking
// fraction of a growing collection. Degrades to the base limits if the
// count is unavailable — never fails the request over a sizing hint.
librarySize := h.librarySize.Get(r.Context(), func(ctx context.Context) (int64, error) {
return recommendation.CountLibraryTracks(ctx, q)
})
limits := recommendation.ScaleForLibrary(
recommendation.DefaultCandidateSourceLimits(), librarySize,
)
candidates, err := recommendation.LoadCandidatesFromSimilarity(
r.Context(), q, user.ID, seedID,
h.recCfg.RecentlyPlayedHours, currentVec, exclude, limits,
// A fresh seed per request: radio is a new session each time
// and SHOULD draw differently. The system mixes are the surfaces that
// promise repeatability; this is not one of them.
strconv.FormatInt(time.Now().UnixNano(), 36),
)
// limit-1 because the seed takes the first slot and is prepended below.
picks, err := h.picker().Radio(r.Context(), q, user.ID, seedID, limit-1, exclude)
if err != nil {
h.logger.Warn("api: radio: similarity-pool failed; falling back to whole-library", "err", err)
candidates, err = recommendation.LoadCandidates(
r.Context(), q, user.ID, seedID,
h.recCfg.RecentlyPlayedHours, currentVec,
)
if err != nil {
h.logger.Error("api: radio: load candidates fallback failed", "err", err)
writeErr(w, apierror.InternalMsg("candidate load failed", err))
return
}
h.logger.Error("api: radio: load candidates failed", "err", err)
writeErr(w, apierror.InternalMsg("candidate load failed", err))
return
}
// Scoring weights come from the DB-backed tuning —
// read per request so an admin change takes effect live.
weights := h.recSettings.Weights(recsettings.ScopeRadio)
// Diversity caps, so a whole session cannot come back from one artist.
// Scaled to
// the requested length so a 20-track radio and a 200-track one are capped
// alike; Shuffle relaxes them rather than returning a short radio.
//
// limit-1 because the seed track occupies the first slot and is prepended
// below — the caps govern the tracks that FOLLOW it.
caps := recommendation.RadioDiversityCaps(limit - 1)
picks := recommendation.Shuffle(candidates, weights, time.Now().UTC(), h.rng, limit-1, caps)
out := make([]TrackRef, 0, len(picks)+1)
out = append(out, trackRefFrom(track, album.Title, artist.Name))
for _, p := range picks {
@@ -150,46 +104,16 @@ func (h *handlers) handleRadio(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, RadioResponse{Tracks: out})
}
// loadCurrentSessionVector returns the user's most recent active session
// vector, or a Seed=true sentinel if none exists / the column is NULL /
// the JSON fails to unmarshal. Sentinel short-circuits ContextualMatchScore
// to 0 so the contextual term contributes nothing in cold-start cases.
func loadCurrentSessionVector(r *http.Request, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) recommendation.SessionVector {
raw, err := q.GetCurrentSessionVectorForUser(r.Context(), userID)
if err != nil {
// pgx.ErrNoRows is the common path: no active session yet.
if !errors.Is(err, pgx.ErrNoRows) {
logger.Warn("api: radio: load current session vector", "err", err)
}
return recommendation.SessionVector{Seed: true}
}
if len(raw) == 0 {
return recommendation.SessionVector{Seed: true}
}
var v recommendation.SessionVector
if jerr := json.Unmarshal(raw, &v); jerr != nil {
logger.Warn("api: radio: bad session_vector_at_play json", "err", jerr)
return recommendation.SessionVector{Seed: true}
}
return v
}
// latestDeviceClass returns the device_class of the user's most recent play as
// the "current device" for context conditioning, or "" when unknown
// (no plays yet, or the latest play predates device capture). Best-effort: a
// lookup failure yields a device-agnostic ("") affinity cell.
func latestDeviceClass(ctx context.Context, q *dbq.Queries, userID pgtype.UUID, logger *slog.Logger) string {
dc, err := q.GetLatestPlayDeviceClassForUser(ctx, userID)
if err != nil {
if !errors.Is(err, pgx.ErrNoRows) {
logger.Warn("api: radio: latest device class", "err", err)
}
return ""
}
if dc == nil {
return ""
}
return *dc
// picker is the shared chooser behind radio, with this server's tuning
// (recsettings.Service.Picker).
func (h *handlers) picker() *recommendation.Picker {
return h.recSettings.Picker(recsettings.PickerConfig{
RecentlyPlayedHours: h.recCfg.RecentlyPlayedHours,
MaxLength: h.recCfg.RadioSizeMax,
Rand: h.rng,
LibrarySize: h.librarySize,
Logger: h.logger,
})
}
// parseExcludeParam parses a comma-separated list of UUIDs from the