fix(playlists): each daily mix keeps its id across rebuilds (#8081)
The nightly rebuild deleted every system playlist and inserted new rows, so each mix got a new id every day. A Subsonic app caches, pins, downloads and syncs a playlist by id, and saw its mixes deleted and recreated daily: a stored mix answered "not found" and an offline download was orphaned. The rebuild now refills yesterday's row for the same mix in place (keyed by kind, plus the seed artist for "Songs like" and the name for a genre mix), inserts only mixes that are new, and deletes the ones today's build didn't make, along with their collage files. The rollups move updated_at, which is the "changed" time Subsonic apps use to see a mix was refreshed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -73,7 +73,7 @@ func buildDiscoverCandidates(ctx context.Context, q *dbq.Queries, logger *slog.L
|
||||
pools.random[:allocations[3]],
|
||||
)
|
||||
|
||||
// Convert to rankedCandidate (the type insertSystemPlaylist accepts).
|
||||
// Convert to rankedCandidate (the type materializeSystemPlaylist accepts).
|
||||
// Score is unused for Discover — the daily-deterministic md5 ordering
|
||||
// already gave us the ranking.
|
||||
ranked := make([]rankedCandidate, 0, len(out))
|
||||
|
||||
+101
-30
@@ -14,6 +14,8 @@ import (
|
||||
"log/slog"
|
||||
"math"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -859,12 +861,31 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
qtx := dbq.New(tx)
|
||||
|
||||
if err := qtx.DeleteSystemPlaylistsForUser(ctx, userID); err != nil {
|
||||
buildErr = fmt.Errorf("delete old system playlists: %w", err)
|
||||
// Each mix keeps its id from one day's build to the next: the rebuild
|
||||
// refills yesterday's row for the same mix rather than making a new one.
|
||||
// A Subsonic app caches, pins, downloads and syncs a playlist by its id,
|
||||
// and would otherwise see every mix deleted and recreated each day.
|
||||
existing, err := qtx.ListSystemPlaylistsForRebuild(ctx, userID)
|
||||
if err != nil {
|
||||
buildErr = fmt.Errorf("list current system playlists: %w", err)
|
||||
return buildErr
|
||||
}
|
||||
current := make(map[string]pgtype.UUID, len(existing))
|
||||
var stale []pgtype.UUID
|
||||
for _, e := range existing {
|
||||
variant := ""
|
||||
if e.SystemVariant != nil {
|
||||
variant = *e.SystemVariant
|
||||
}
|
||||
key := systemMixKey(variant, e.SeedArtistID, e.Name)
|
||||
if _, dup := current[key]; dup {
|
||||
stale = append(stale, e.ID)
|
||||
continue
|
||||
}
|
||||
current[key] = e.ID
|
||||
}
|
||||
|
||||
// Track the playlist IDs we create so we can generate collage covers
|
||||
// Track the playlist IDs we fill so we can generate collage covers
|
||||
// for each one after the transaction commits. Collage generation
|
||||
// reads the playlist's tracks via a separate query that won't see
|
||||
// uncommitted rows, so the work happens post-commit.
|
||||
@@ -874,14 +895,29 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
||||
if len(bp.Tracks) == 0 {
|
||||
continue
|
||||
}
|
||||
id, err := insertSystemPlaylist(ctx, qtx, userID, bp)
|
||||
key := systemMixKey(bp.Variant, bp.SeedArtistID, bp.Name)
|
||||
existingID := current[key]
|
||||
delete(current, key)
|
||||
id, err := materializeSystemPlaylist(ctx, qtx, userID, bp, existingID)
|
||||
if err != nil {
|
||||
buildErr = fmt.Errorf("insert %s (%s): %w", bp.Variant, bp.Name, err)
|
||||
buildErr = fmt.Errorf("fill %s (%s): %w", bp.Variant, bp.Name, err)
|
||||
return buildErr
|
||||
}
|
||||
createdIDs = append(createdIDs, id)
|
||||
}
|
||||
|
||||
// Mixes today's build didn't make (a seed artist rotated out, a genre
|
||||
// mix no longer earned, a mix with nothing to hold) are removed.
|
||||
for _, id := range current {
|
||||
stale = append(stale, id)
|
||||
}
|
||||
if len(stale) > 0 {
|
||||
if err := qtx.DeletePlaylistsByIDs(ctx, stale); err != nil {
|
||||
buildErr = fmt.Errorf("delete retired system playlists: %w", err)
|
||||
return buildErr
|
||||
}
|
||||
}
|
||||
|
||||
if yml.built {
|
||||
if err := persistYouMightLike(ctx, qtx, userID, yml); err != nil {
|
||||
buildErr = fmt.Errorf("persist you-might-like: %w", err)
|
||||
@@ -908,10 +944,27 @@ func BuildSystemPlaylists(ctx context.Context, pool *pgxpool.Pool, logger *slog.
|
||||
"playlist_id", uuidStringPL(plID), "err", cerr)
|
||||
}
|
||||
}
|
||||
for _, plID := range stale {
|
||||
_ = os.Remove(filepath.Join(dataDir, "playlist_covers", uuidToFilename(plID)+".jpg"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// systemMixKey names a mix across days, so a rebuild can find yesterday's
|
||||
// row for it: the kind, plus the seed artist for a "Songs like" mix (whose
|
||||
// name follows the artist's) and the name for a genre mix (one per genre).
|
||||
// Every other kind is one mix per person.
|
||||
func systemMixKey(variant string, seedArtistID pgtype.UUID, name string) string {
|
||||
switch {
|
||||
case seedArtistID.Valid:
|
||||
return variant + "/" + uuidStringPL(seedArtistID)
|
||||
case variant == "genre_mix":
|
||||
return variant + "/" + name
|
||||
}
|
||||
return variant
|
||||
}
|
||||
|
||||
// pickTopN sorts candidates by score DESC, applies per-album (<=2) /
|
||||
// per-artist (<=3) diversity caps matching Discover's behavior, then
|
||||
// truncates to n. Used by Songs-like-X (and as the fallback inside
|
||||
@@ -1055,32 +1108,50 @@ func systemMixDescription(variant string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// insertSystemPlaylist inserts a kind='system' playlists row plus its
|
||||
// playlist_tracks via AppendPlaylistTrack (which
|
||||
// does the snapshot lookup from tracks/albums/artists). Then recomputes
|
||||
// rollups. Returns the new playlist's ID so the caller can drive
|
||||
// post-commit collage generation.
|
||||
// materializeSystemPlaylist fills a kind='system' playlist with bp's
|
||||
// tracks via AppendPlaylistTrack (which does the snapshot lookup from
|
||||
// tracks/albums/artists), then recomputes rollups. existingID, when valid,
|
||||
// is yesterday's row for the same mix, refilled in place so its id holds;
|
||||
// otherwise a new row is inserted. Returns the playlist's ID so the caller
|
||||
// can drive post-commit collage generation.
|
||||
//
|
||||
// Pass seed_artist_id with Valid=false (zero pgtype.UUID) for the For-You
|
||||
// variant; the CreateSystemPlaylist query persists NULL.
|
||||
//
|
||||
// cover_path is always inserted as NULL — the post-commit collage step
|
||||
// in BuildSystemPlaylists overrides it with a 4-cell composite of the
|
||||
// contributing tracks' album art.
|
||||
func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID,
|
||||
bp builtPlaylist) (pgtype.UUID, error) {
|
||||
variantStr := bp.Variant
|
||||
p, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{
|
||||
UserID: userID,
|
||||
Name: bp.Name,
|
||||
Description: systemMixDescription(bp.Variant),
|
||||
SystemVariant: &variantStr,
|
||||
SeedArtistID: bp.SeedArtistID,
|
||||
CoverPath: nil,
|
||||
ShelfRank: bp.ShelfRank,
|
||||
})
|
||||
if err != nil {
|
||||
return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err)
|
||||
// A new row's cover_path is NULL — the post-commit collage step in
|
||||
// BuildSystemPlaylists draws a 4-cell composite of the contributing
|
||||
// tracks' album art (to the same file, for a refilled row).
|
||||
func materializeSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.UUID,
|
||||
bp builtPlaylist, existingID pgtype.UUID) (pgtype.UUID, error) {
|
||||
var playlistID pgtype.UUID
|
||||
if existingID.Valid {
|
||||
if err := qtx.RefreshSystemPlaylist(ctx, dbq.RefreshSystemPlaylistParams{
|
||||
ID: existingID,
|
||||
Name: bp.Name,
|
||||
Description: systemMixDescription(bp.Variant),
|
||||
ShelfRank: bp.ShelfRank,
|
||||
}); err != nil {
|
||||
return pgtype.UUID{}, fmt.Errorf("refresh playlist row: %w", err)
|
||||
}
|
||||
if err := qtx.ClearPlaylistTracks(ctx, existingID); err != nil {
|
||||
return pgtype.UUID{}, fmt.Errorf("clear playlist tracks: %w", err)
|
||||
}
|
||||
playlistID = existingID
|
||||
} else {
|
||||
variantStr := bp.Variant
|
||||
row, err := qtx.CreateSystemPlaylist(ctx, dbq.CreateSystemPlaylistParams{
|
||||
UserID: userID,
|
||||
Name: bp.Name,
|
||||
Description: systemMixDescription(bp.Variant),
|
||||
SystemVariant: &variantStr,
|
||||
SeedArtistID: bp.SeedArtistID,
|
||||
CoverPath: nil,
|
||||
ShelfRank: bp.ShelfRank,
|
||||
})
|
||||
if err != nil {
|
||||
return pgtype.UUID{}, fmt.Errorf("insert playlist row: %w", err)
|
||||
}
|
||||
playlistID = row.ID
|
||||
}
|
||||
|
||||
tracks, err := oneCopyPerSong(ctx, qtx, bp.Tracks)
|
||||
@@ -1094,7 +1165,7 @@ func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.U
|
||||
pickKind = &k
|
||||
}
|
||||
if _, err := qtx.AppendPlaylistTrack(ctx, dbq.AppendPlaylistTrackParams{
|
||||
PlaylistID: p.ID,
|
||||
PlaylistID: playlistID,
|
||||
TrackID: t.TrackID,
|
||||
PickKind: pickKind,
|
||||
}); err != nil {
|
||||
@@ -1107,10 +1178,10 @@ func insertSystemPlaylist(ctx context.Context, qtx *dbq.Queries, userID pgtype.U
|
||||
}
|
||||
}
|
||||
|
||||
if err := qtx.UpdatePlaylistRollups(ctx, p.ID); err != nil {
|
||||
if err := qtx.UpdatePlaylistRollups(ctx, playlistID); err != nil {
|
||||
return pgtype.UUID{}, fmt.Errorf("update rollups: %w", err)
|
||||
}
|
||||
return p.ID, nil
|
||||
return playlistID, nil
|
||||
}
|
||||
|
||||
// oneCopyPerSong keeps the first of a song's copies on different releases
|
||||
|
||||
@@ -80,7 +80,7 @@ func TestRotateForDay_UntieredPoolIsWholeRotation(t *testing.T) {
|
||||
|
||||
func TestFinishMix_PropagatesPickKind(t *testing.T) {
|
||||
// Tier stamps ride discoverTrack through diversify/truncate into
|
||||
// the rankedCandidates that insertSystemPlaylist persists.
|
||||
// the rankedCandidates that materializeSystemPlaylist persists.
|
||||
pool := []discoverTrack{mixTrack(1, pickKindTier1), mixTrack(2, pickKindTier2)}
|
||||
got := finishMix(pool, false)
|
||||
if len(got) != 2 {
|
||||
|
||||
@@ -228,39 +228,48 @@ func TestBuildSystemPlaylists_QuarantineExcluded(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSystemPlaylists_AtomicReplace(t *testing.T) {
|
||||
// A rebuild refills each mix in place: a Subsonic app caches, pins and
|
||||
// downloads a playlist by id, so the same mix keeps its id from one build to
|
||||
// the next, and no mix is left behind twice.
|
||||
func TestBuildSystemPlaylists_ARebuildKeepsEachMixsID(t *testing.T) {
|
||||
pool := dbtest.Pool(t)
|
||||
logger := discardLogger()
|
||||
u, _ := seedActiveLibrary(t, pool, "atomic", 3, 3)
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
|
||||
// First build.
|
||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil {
|
||||
list := func() map[string]pgtype.UUID {
|
||||
t.Helper()
|
||||
rows, err := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
||||
UserID: u.ID, Column2: "system",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
out := map[string]pgtype.UUID{}
|
||||
for _, r := range rows {
|
||||
if _, dup := out[r.Name]; dup {
|
||||
t.Fatalf("mix %q is held twice after a rebuild", r.Name)
|
||||
}
|
||||
out[r.Name] = r.ID
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
|
||||
t.Fatalf("first build: %v", err)
|
||||
}
|
||||
var ids1 []pgtype.UUID
|
||||
rows1, _ := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
||||
UserID: u.ID, Column2: "system",
|
||||
})
|
||||
for _, r := range rows1 {
|
||||
ids1 = append(ids1, r.ID)
|
||||
first := list()
|
||||
if len(first) == 0 {
|
||||
t.Fatal("no system playlists from the first build")
|
||||
}
|
||||
if len(ids1) == 0 {
|
||||
t.Skip("no system playlists from first build; can't verify replace")
|
||||
}
|
||||
|
||||
// Second build — old rows must be gone, replaced with fresh ones.
|
||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), t.TempDir()); err != nil {
|
||||
if err := playlists.BuildSystemPlaylists(ctx, pool, logger, u.ID, time.Now().UTC(), dir); err != nil {
|
||||
t.Fatalf("second build: %v", err)
|
||||
}
|
||||
rows2, _ := dbq.New(pool).ListPlaylistsByUserAndKind(ctx, dbq.ListPlaylistsByUserAndKindParams{
|
||||
UserID: u.ID, Column2: "system",
|
||||
})
|
||||
for _, r := range rows2 {
|
||||
for _, oldID := range ids1 {
|
||||
if r.ID.Bytes == oldID.Bytes {
|
||||
t.Errorf("playlist id %s persisted across rebuilds — atomic replace failed", uuidString(oldID))
|
||||
}
|
||||
second := list()
|
||||
for name, id := range first {
|
||||
if again, ok := second[name]; ok && again != id {
|
||||
t.Errorf("mix %q got a new id on rebuild: %s then %s", name, uuidString(id), uuidString(again))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user