diff --git a/internal/db/dbq/system_playlists.sql.go b/internal/db/dbq/system_playlists.sql.go index 4d1ee7cc..9b51826d 100644 --- a/internal/db/dbq/system_playlists.sql.go +++ b/internal/db/dbq/system_playlists.sql.go @@ -11,6 +11,15 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const clearPlaylistTracks = `-- name: ClearPlaylistTracks :exec +DELETE FROM playlist_tracks WHERE playlist_id = $1 +` + +func (q *Queries) ClearPlaylistTracks(ctx context.Context, playlistID pgtype.UUID) error { + _, err := q.db.Exec(ctx, clearPlaylistTracks, playlistID) + return err +} + const clearStaleSystemPlaylistInFlight = `-- name: ClearStaleSystemPlaylistInFlight :exec UPDATE system_playlist_runs SET in_flight = false WHERE in_flight = true ` @@ -75,14 +84,14 @@ func (q *Queries) CreateSystemPlaylist(ctx context.Context, arg CreateSystemPlay return i, err } -const deleteSystemPlaylistsForUser = `-- name: DeleteSystemPlaylistsForUser :exec -DELETE FROM playlists WHERE user_id = $1 AND kind = 'system' +const deletePlaylistsByIDs = `-- name: DeletePlaylistsByIDs :exec +DELETE FROM playlists WHERE id = ANY($1::uuid[]) ` -// Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles -// the join rows. -func (q *Queries) DeleteSystemPlaylistsForUser(ctx context.Context, userID pgtype.UUID) error { - _, err := q.db.Exec(ctx, deleteSystemPlaylistsForUser, userID) +// Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id +// handles the join rows. +func (q *Queries) DeletePlaylistsByIDs(ctx context.Context, ids []pgtype.UUID) error { + _, err := q.db.Exec(ctx, deletePlaylistsByIDs, ids) return err } @@ -303,6 +312,46 @@ func (q *Queries) ListPlaylistsByUserAndKind(ctx context.Context, arg ListPlayli return items, nil } +const listSystemPlaylistsForRebuild = `-- name: ListSystemPlaylistsForRebuild :many +SELECT id, name, system_variant, seed_artist_id + FROM playlists + WHERE user_id = $1 AND kind = 'system' +` + +type ListSystemPlaylistsForRebuildRow struct { + ID pgtype.UUID + Name string + SystemVariant *string + SeedArtistID pgtype.UUID +} + +// The user's current mixes, so a rebuild can refill each in place and keep +// its id. +func (q *Queries) ListSystemPlaylistsForRebuild(ctx context.Context, userID pgtype.UUID) ([]ListSystemPlaylistsForRebuildRow, error) { + rows, err := q.db.Query(ctx, listSystemPlaylistsForRebuild, userID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListSystemPlaylistsForRebuildRow + for rows.Next() { + var i ListSystemPlaylistsForRebuildRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.SystemVariant, + &i.SeedArtistID, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const pickSeedArtists = `-- name: PickSeedArtists :many WITH liked AS ( SELECT gla.artist_id FROM general_likes_artists gla WHERE gla.user_id = $1 @@ -528,6 +577,31 @@ func (q *Queries) PickTopPlayedTracksForUser(ctx context.Context, userID pgtype. return items, nil } +const refreshSystemPlaylist = `-- name: RefreshSystemPlaylist :exec +UPDATE playlists + SET name = $2, description = $3, shelf_rank = $4 + WHERE id = $1 +` + +type RefreshSystemPlaylistParams struct { + ID pgtype.UUID + Name string + Description string + ShelfRank int32 +} + +// A rebuild refilling an existing mix: its name, description and shelf +// place may move with the day's build. updated_at moves with the rollups. +func (q *Queries) RefreshSystemPlaylist(ctx context.Context, arg RefreshSystemPlaylistParams) error { + _, err := q.db.Exec(ctx, refreshSystemPlaylist, + arg.ID, + arg.Name, + arg.Description, + arg.ShelfRank, + ) + return err +} + const tryClaimSystemPlaylistRun = `-- name: TryClaimSystemPlaylistRun :one INSERT INTO system_playlist_runs (user_id, in_flight) VALUES ($1, true) diff --git a/internal/db/queries/system_playlists.sql b/internal/db/queries/system_playlists.sql index 2938c17a..15c0030b 100644 --- a/internal/db/queries/system_playlists.sql +++ b/internal/db/queries/system_playlists.sql @@ -214,10 +214,27 @@ SELECT COALESCE( LIMIT 1) )::uuid AS id; --- name: DeleteSystemPlaylistsForUser :exec --- Atomic-replace step. CASCADE on playlist_tracks.playlist_id handles --- the join rows. -DELETE FROM playlists WHERE user_id = $1 AND kind = 'system'; +-- name: ListSystemPlaylistsForRebuild :many +-- The user's current mixes, so a rebuild can refill each in place and keep +-- its id. +SELECT id, name, system_variant, seed_artist_id + FROM playlists + WHERE user_id = $1 AND kind = 'system'; + +-- name: RefreshSystemPlaylist :exec +-- A rebuild refilling an existing mix: its name, description and shelf +-- place may move with the day's build. updated_at moves with the rollups. +UPDATE playlists + SET name = $2, description = sqlc.arg(description), shelf_rank = sqlc.arg(shelf_rank) + WHERE id = $1; + +-- name: ClearPlaylistTracks :exec +DELETE FROM playlist_tracks WHERE playlist_id = $1; + +-- name: DeletePlaylistsByIDs :exec +-- Mixes a rebuild no longer makes. CASCADE on playlist_tracks.playlist_id +-- handles the join rows. +DELETE FROM playlists WHERE id = ANY(sqlc.arg(ids)::uuid[]); -- name: ListPlaylistsByUserAndKind :many -- Used in integration tests; production filter applied in Go diff --git a/internal/playlists/discover.go b/internal/playlists/discover.go index a33cc1bd..875852fe 100644 --- a/internal/playlists/discover.go +++ b/internal/playlists/discover.go @@ -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)) diff --git a/internal/playlists/system.go b/internal/playlists/system.go index 1d2d5fb9..482932c6 100644 --- a/internal/playlists/system.go +++ b/internal/playlists/system.go @@ -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 diff --git a/internal/playlists/system_mixes_test.go b/internal/playlists/system_mixes_test.go index bbb2da08..4f43e416 100644 --- a/internal/playlists/system_mixes_test.go +++ b/internal/playlists/system_mixes_test.go @@ -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 { diff --git a/internal/playlists/system_test.go b/internal/playlists/system_test.go index dab6e747..cdcc1443 100644 --- a/internal/playlists/system_test.go +++ b/internal/playlists/system_test.go @@ -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)) } } }