feat(database): shape the library like files, and shrink the catalog
CI / check (push) Successful in 3m7s
CI / e2e (push) Canceled after 1m45s

Plans 013 and 014, the album page that prompted them, and the smaller
fixes they turned up. Changelog, largest first.

## The local library is shaped like files, not like MusicBrainz

`audio_files` carries its own tags and points at `albums` and
`artists`; `file_genres` is the one real many-to-many. `recordings`,
`release_group_recordings`, `artist_credit`, `artist_credit_artist`,
`recording_genres`, `release_groups` and `release_to_rg` are gone from
the local side, and with them a six-way join in every read, a
`MIN(release_group_id)` subquery in eleven queries and a
first-credited-artist subquery in nine. Measured on a real 25,966-file
library, every many-to-many that model expressed was 1:1 in the data.

- Ownership is a file. `GetFilePathsByRecordingMBIDs`,
  `LibraryMBIDIndex.CheckMBIDs`, `collectLibraryEntities` and
  `pruneStaleLocalCrossReferences` all join `audio_files`, so the 812
  orphaned recordings, 216 release groups and 260 artists that library
  carried are now structurally impossible.
- One projection: every track query selects from the `track_metadata`
  view, one row type, one mapper. Nine hand-rolled copies had drifted
  far enough to report different years on different screens.
- `library_id = 0` means every library, so each list query exists once
  instead of scoped and unscoped with a branch at every call site.
- No migration chain. `sql/schemas/` is the one description of the
  shape; `sql/migrations/`, `applyMigrations` and `schema_migrations`
  are squashed away, along with the drift between them that had sqlc
  generating against a stale schema.
- `database.InsertTestTrack` is the one test seeder; twenty test files
  had been assembling the old FK chain each in its own order.

## The catalog stores its ids as bytes

`explore_index`'s three 36-char MBID columns and its entity-type text
are 16 raw bytes and a small integer. The table and its six indexes go
780 MB to 405 MB on a real 2,052,200-row catalog, which is why a fresh
install is ~0.6 GB rather than ~1.0 GB.

- `backend/explore/mbid.go` is the only place the encoding is known;
  everything above it speaks dashed strings.
- `CHECK(length(mbid) = 16)` makes a stringly write fail at the insert
  rather than silently returning no rows, since SQLite does not coerce
  between TEXT and BLOB.
- The importer asks the artifact what encoding it carries and converts
  on the way in, so the artifact already published keeps working and no
  format bump is needed.
- `indexRowColumns`/`scanIndexRow` replace four copies of a 22-column
  list, and `TestStoredEncodingRoundTrips` sweeps every read path.

## An album page that says how much of the album is yours

- One question, asked once: is there a file. `filePaths` is filled by a
  single batched lookup when the tracklist settles, and the badge, the
  Play count, the dimmed rows and every menu item read it — replacing
  four claims of decreasing confidence that could show a green tick on
  an album whose every action did nothing.
- Play, Play 7 of 12, or no play button at all.
- `total_tracks` on `explore_index` (~2 bytes over 400,677 release
  groups) and on `audio_files` from tags that have always carried it:
  a complete MBID-matched album now makes no catalog call at all, where
  it used to spend the most expensive request the app makes.
- A merged cluster shows the running order the most releases agree on,
  and the version list marks the release you own rather than standing a
  synthetic entry in for it.
- `AlbumReleasesFailed`: a slow fetch is no longer reported as a failed
  one by a 12-second timer.
- Rows not in the library are dimmed in place (with `aria-disabled`)
  instead of the owned ones wearing a green tick and a legend.

## Caches and cover art get ceilings

- Only the three tiers of a cover are stored; the full-resolution copy
  nothing rendered was 1,134 MB of a 1.4 GB covers directory.
- One artist portrait is downloaded and the rest are remembered as
  URLs — 4.1 GB of a 5.3 GB cache was candidates no code path reads.
- `browsedArtBudget` and `httpCacheBudget` bound what an age cannot:
  the same install held art for 5,770 artists in a 1,301-artist
  library.
- `OrphanedArtistImagesJob` joined a bare MBID onto a sharded
  directory, so it deleted the rows that were the only record of the
  files it left behind. `explore.ArtistImageDir` is that layout's one
  definition now.

## The autotag queue asks whether there is work

`tagging_items` was a row per album folder, not a queue, and no query
read the `tag_status` column that held the answer. The four queue
queries ask the files, which matters most where it is least visible:
`startPrefetch` was scoring every album in a tagged library against
MusicBrainz.

## Phantom playlist tracks resolve in place

An M3U8 imported before its files leaves phantom rows; they now match
by path and fall back to position, keep their place in the playlist
when resolved, and pair best-first so two phantoms cannot claim the
same file.

## Playing a track plays the list it is in

Double-click, and Play on a single row's menu, queue the list as
displayed with `startIndex` on that row — the album page and the track
list used to queue one track and discard the album around it. A
multi-row selection still plays exactly itself.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AfVYUVExXsx1nSWrXN8mAh
This commit is contained in:
2026-08-16 13:58:15 -04:00
co-authored by Claude Opus 5
parent 1128881e8d
commit e7748f1fd5
208 changed files with 10944 additions and 12104 deletions
+7 -25
View File
@@ -42,35 +42,17 @@ func setupRecordedService(
func seedPlaylistTracks(t *testing.T, db *database.DB, count int) []string {
t.Helper()
_, err := db.ExecContext(
"INSERT OR IGNORE INTO artist_credit (id, text) VALUES (1, 'Test Artist')",
)
if err != nil {
t.Fatalf("insert artist_credit: %v", err)
}
paths := make([]string, count)
for i := range count {
id := i + 1
paths[i] = fmt.Sprintf("/test/pl-track%d.mp3", id)
paths[i] = fmt.Sprintf("/test/pl-track%d.mp3", i+1)
if _, err := db.ExecContext(
"INSERT OR IGNORE INTO recordings (id, name, artist_credit_id) "+
"VALUES (?, ?, 1)",
id, fmt.Sprintf("Track %d", id),
); err != nil {
t.Fatalf("insert recording %d: %v", id, err)
}
if _, err := db.ExecContext(
"INSERT OR IGNORE INTO audio_files (id, file_path, "+
"length_milliseconds, file_type_id, recording_id) "+
"VALUES (?, ?, 180000, 0, ?)",
id, paths[i], id,
); err != nil {
t.Fatalf("insert audio_file %d: %v", id, err)
}
database.InsertTestTrack(t, db, database.TestTrack{
FilePath: paths[i],
Title: fmt.Sprintf("Track %d", i+1),
Artist: "Test Artist",
LengthMs: 180000,
})
}
return paths
+7 -3
View File
@@ -109,12 +109,16 @@ func scoreCandidate(
)
dirScore := scorePathDirs(pp, candidatePath)
// If duration is unknown, redistribute its weight to
// filename.
// If duration is unknown, redistribute its weight to filename.
// Either side can be the one that does not know: an M3U8 written
// without EXTINF lines carries no duration, and neither does a
// library file whose length was never read. Scoring a candidate
// out of 0.9 for the *library's* gap made an otherwise exact
// filename match unable to reach the auto-match threshold.
fnWeight := weightFilename
durWeight := weightDuration
if pp.durationSec == 0 {
if pp.durationSec == 0 || candidateDurationMs == 0 {
fnWeight += durWeight
durWeight = 0
}
+119
View File
@@ -409,3 +409,122 @@ func stringSliceEqual(a, b []string) bool {
return true
}
// TestScoreCandidateUnknownCandidateDuration pins which side may be the
// one that does not know a duration. An M3U8 without EXTINF lines was
// already handled; a *library* file whose length was never read was not,
// so an otherwise exact match was scored out of 0.9 and could not reach
// the auto-match threshold.
func TestScoreCandidateUnknownCandidateDuration(t *testing.T) {
t.Parallel()
pp := newPhantomProfile(
"/old/Music/Artist/01 - Song.mp3",
"Artist - Song",
240,
)
score := scoreCandidate(
pp,
"/new/Music/Artist/01 - Song.mp3",
"Song",
"Artist",
0, // the library never read this file's length
)
if score < autoMatchMinimum {
t.Errorf(
"score = %f, want >= %f for an exact match with no "+
"candidate duration",
score, autoMatchMinimum,
)
}
}
// TestAssignBestFirst covers the rule that one library file cannot
// resolve two phantom tracks, and which phantom gets it when both want
// the same one.
func TestAssignBestFirst(t *testing.T) {
t.Parallel()
offers := []phantomOffer{
// The playlist's first phantom wants this file, but only
// just — and the third one is a better answer for it.
{
phantomPath: "/gone/a.mp3",
candidate: CandidateTrack{
FilePath: "/lib/shared.mp3", Score: 0.86,
},
},
{
phantomPath: "/gone/b.mp3",
candidate: CandidateTrack{
FilePath: "/lib/b.mp3", Score: 0.90,
},
},
{
phantomPath: "/gone/c.mp3",
candidate: CandidateTrack{
FilePath: "/lib/shared.mp3", Score: 0.98,
},
},
}
matches := assignBestFirst(offers)
if len(matches) != 2 {
t.Fatalf("matches = %d, want 2", len(matches))
}
got := make(map[string]string, len(matches))
for _, m := range matches {
got[m.PhantomPath] = m.Candidate.FilePath
}
if got["/gone/c.mp3"] != "/lib/shared.mp3" {
t.Errorf(
"the shared file went to %v, want /gone/c.mp3 to have it",
got,
)
}
if _, claimed := got["/gone/a.mp3"]; claimed {
t.Error("/gone/a.mp3 took a file a better match had claimed")
}
if got["/gone/b.mp3"] != "/lib/b.mp3" {
t.Errorf("/gone/b.mp3 matched %q, want /lib/b.mp3", got["/gone/b.mp3"])
}
}
// TestAssignBestFirstKeepsOnePerPhantom: a phantom with several
// confident candidates takes its best one and no more.
func TestAssignBestFirstKeepsOnePerPhantom(t *testing.T) {
t.Parallel()
matches := assignBestFirst([]phantomOffer{
{
phantomPath: "/gone/a.mp3",
candidate: CandidateTrack{
FilePath: "/lib/one.mp3", Score: 0.90,
},
},
{
phantomPath: "/gone/a.mp3",
candidate: CandidateTrack{
FilePath: "/lib/two.mp3", Score: 0.95,
},
},
})
if len(matches) != 1 {
t.Fatalf("matches = %d, want 1", len(matches))
}
if matches[0].Candidate.FilePath != "/lib/two.mp3" {
t.Errorf(
"matched %q, want the higher-scoring /lib/two.mp3",
matches[0].Candidate.FilePath,
)
}
}
+187
View File
@@ -0,0 +1,187 @@
package playlist
import (
"path/filepath"
"testing"
)
// setupPhantomPlaylist builds a playlist whose M3U8 holds two entries —
// one file the library has and one it does not — with the matching
// playlist_tracks rows: a linked row at position 0 and a phantom at
// position 1. It returns the playlist id, the phantom's absolute path
// and the library path the user would resolve it to.
func setupPhantomPlaylist(
t *testing.T,
) (svc *Service, playlistID int64, phantomAbs, targetAbs string) {
t.Helper()
svc, db, _ := setupRecordedService(t)
paths := seedPlaylistTracks(t, db, 2)
libDir := svc.libraryDir.(stubLibraryDir).dir
// seedPlaylistTracks writes absolute paths outside the library root,
// which is fine: an M3U8 entry may be absolute, and resolveM3UPath
// returns an absolute entry unchanged.
targetAbs = paths[1]
phantomAbs = filepath.Join(libDir, "gone", "missing.mp3")
created, err := svc.CreatePlaylist("Imported")
if err != nil {
t.Fatalf("CreatePlaylist: %v", err)
}
playlistID = created.ID
dir, err := svc.playlistsDir()
if err != nil {
t.Fatalf("playlistsDir: %v", err)
}
if err := writeM3U8(dir, playlistID, "Imported", []m3uEntry{
{RelativePath: paths[0], DisplayTitle: "Track 1", DurationSec: 180},
{
RelativePath: phantomAbs,
DisplayTitle: "Some Artist - Missing",
DurationSec: 200,
},
}); err != nil {
t.Fatalf("writeM3U8: %v", err)
}
if _, err := db.ExecContext(
`INSERT INTO playlist_tracks (playlist_id, audio_file_id, position)
VALUES (?, 1, 0)`,
playlistID,
); err != nil {
t.Fatalf("insert linked track: %v", err)
}
if _, err := db.ExecContext(
`INSERT INTO playlist_tracks
(playlist_id, position, phantom_title, phantom_file_path)
VALUES (?, 1, 'Some Artist - Missing', ?)`,
playlistID, phantomAbs,
); err != nil {
t.Fatalf("insert phantom track: %v", err)
}
return svc, playlistID, phantomAbs, targetAbs
}
// countPlaylistRows reports how many playlist_tracks rows the playlist
// has, and how many of them are still phantoms.
func countPlaylistRows(
t *testing.T, svc *Service, playlistID int64,
) (total, phantoms int) {
t.Helper()
rows, err := svc.db.QueryContext(
`SELECT COUNT(*),
COALESCE(SUM(audio_file_id IS NULL), 0)
FROM playlist_tracks WHERE playlist_id = ?`,
playlistID,
)
if err != nil {
t.Fatalf("count playlist_tracks: %v", err)
}
defer func() { _ = rows.Close() }()
if !rows.Next() {
t.Fatal("count playlist_tracks: no row")
}
if err := rows.Scan(&total, &phantoms); err != nil {
t.Fatalf("scan count: %v", err)
}
return total, phantoms
}
// TestResolvePhantomTracksFillsTheRowItAlreadyHas is the regression for
// a manually resolved phantom appearing twice: the resolution used to
// append a *new* playlist_tracks row and leave the phantom row behind,
// so the playlist held two rows for one M3U8 line — and the resolved
// one sat at the end of the playlist rather than where the track was.
func TestResolvePhantomTracksFillsTheRowItAlreadyHas(t *testing.T) {
t.Parallel()
svc, playlistID, phantomAbs, targetAbs := setupPhantomPlaylist(t)
if err := svc.ResolvePhantomTracks(
playlistID, map[string]string{phantomAbs: targetAbs},
); err != nil {
t.Fatalf("ResolvePhantomTracks: %v", err)
}
total, phantoms := countPlaylistRows(t, svc, playlistID)
if total != 2 {
t.Errorf("playlist_tracks rows = %d, want 2", total)
}
if phantoms != 0 {
t.Errorf("phantom rows left = %d, want 0", phantoms)
}
// The track stays where it was in the playlist.
tracks, err := svc.GetPlaylistTracks(playlistID)
if err != nil {
t.Fatalf("GetPlaylistTracks: %v", err)
}
if len(tracks) != 2 {
t.Fatalf("tracks = %d, want 2", len(tracks))
}
if tracks[1].FilePath != targetAbs {
t.Errorf(
"resolved track at position 1 = %q, want %q",
tracks[1].FilePath, targetAbs,
)
}
if tracks[1].Phantom {
t.Error("resolved track is still marked phantom")
}
}
// TestResolvePhantomTracksRefusesTwoPhantomsForOneFile pins the rule
// FindPhantomMatches already applies on the auto-match path: one library
// file cannot stand in for two phantom tracks, or resolving adds it to
// the playlist twice.
func TestResolvePhantomTracksRefusesTwoPhantomsForOneFile(t *testing.T) {
t.Parallel()
svc, playlistID, phantomAbs, targetAbs := setupPhantomPlaylist(t)
secondPhantom := filepath.Join(
svc.libraryDir.(stubLibraryDir).dir, "gone", "missing-2.mp3",
)
if _, err := svc.db.ExecContext(
`INSERT INTO playlist_tracks
(playlist_id, position, phantom_title, phantom_file_path)
VALUES (?, 2, 'Some Artist - Missing 2', ?)`,
playlistID, secondPhantom,
); err != nil {
t.Fatalf("insert second phantom: %v", err)
}
if err := svc.ResolvePhantomTracks(playlistID, map[string]string{
phantomAbs: targetAbs,
secondPhantom: targetAbs,
}); err != nil {
t.Fatalf("ResolvePhantomTracks: %v", err)
}
total, phantoms := countPlaylistRows(t, svc, playlistID)
if total != 3 {
t.Errorf("playlist_tracks rows = %d, want 3", total)
}
// One of the two phantoms is resolved; the other is left for the
// user to point somewhere else.
if phantoms != 1 {
t.Errorf("phantom rows left = %d, want 1", phantoms)
}
}
+307 -148
View File
@@ -2,6 +2,7 @@
package playlist
import (
"cmp"
"context"
"database/sql"
"errors"
@@ -154,6 +155,8 @@ func NewService(
// SetFavoritesConfig sets the provider used to read and write
// the default-playlist configuration.
//
//wails:ignore // internal wiring, not part of the app's IPC surface.
func (s *Service) SetFavoritesConfig(
provider FavoritesConfigProvider,
) {
@@ -1845,6 +1848,142 @@ type phantomTrackRow struct {
phantomFilePath string
}
// phantomRowSet is a playlist's unresolved rows plus the ones a
// resolution pass has already consumed, so two matches cannot land on
// the same row.
type phantomRowSet struct {
rows []phantomTrackRow
taken map[int64]struct{}
}
// loadPhantomRows reads the playlist's phantom rows — the tracks whose
// file was missing when the M3U8 was imported.
func (s *Service) loadPhantomRows(playlistID int64) *phantomRowSet {
set := &phantomRowSet{taken: map[int64]struct{}{}}
// SAFETY: Hand-crafted SELECT for phantom tracks with position and
// phantom_file_path. Parameterized by playlist ID.
rows, err := s.db.QueryContext(
`SELECT id, position, COALESCE(phantom_file_path, '')
FROM playlist_tracks
WHERE playlist_id = ? AND audio_file_id IS NULL`,
playlistID,
)
if err != nil {
s.logger.Warn(
"could not query phantom tracks",
"playlistId", playlistID,
"err", err,
)
return set
}
defer func() {
if closeErr := rows.Close(); closeErr != nil {
s.logger.Warn(
"could not close phantom track rows",
"err", closeErr,
)
}
}()
for rows.Next() {
var pt phantomTrackRow
if err := rows.Scan(
&pt.id, &pt.position, &pt.phantomFilePath,
); err != nil {
continue
}
set.rows = append(set.rows, pt)
}
return set
}
// takePhantomRow finds the phantom row standing for phantomAbs and
// marks it consumed. It matches on phantom_file_path first and falls
// back to the row sitting at that entry's index in the M3U8, which is
// the same two-step resolvePlaylistPhantoms uses: rows imported before
// migration 7 carry no phantom_file_path at all.
func takePhantomRow(
set *phantomRowSet,
phantomAbs string,
entries []m3uEntry,
libraryRoots []string,
) (int64, bool) {
_, idx := findM3UEntry(entries, phantomAbs, libraryRoots)
return takePhantomRowAt(set, phantomAbs, idx)
}
// takePhantomRowAt is takePhantomRow for a caller that already knows
// the entry's index. A negative index means "no positional fallback":
// positions are non-negative, so it simply never matches.
func takePhantomRowAt(
set *phantomRowSet, phantomAbs string, index int,
) (int64, bool) {
for _, pt := range set.rows {
if _, done := set.taken[pt.id]; done {
continue
}
if pt.phantomFilePath != "" &&
pt.phantomFilePath == phantomAbs {
set.taken[pt.id] = struct{}{}
return pt.id, true
}
}
for _, pt := range set.rows {
if _, done := set.taken[pt.id]; done {
continue
}
if pt.position == int64(index) {
set.taken[pt.id] = struct{}{}
return pt.id, true
}
}
return 0, false
}
// fillPhantomRow points a phantom playlist_tracks row at a real audio
// file and drops the placeholder metadata it was displaying. The row
// keeps its position, which is why resolving a phantom does not move
// the track to the end of the playlist.
func (s *Service) fillPhantomRow(
playlistTrackID, audioFileID int64,
) error {
// SAFETY: Hand-crafted UPDATE to resolve a phantom playlist track.
// Sets audio_file_id and clears all phantom metadata columns.
// Parameterized by ID.
if _, err := s.db.ExecContext(
`UPDATE playlist_tracks SET
audio_file_id = ?,
phantom_title = NULL,
phantom_artist = NULL,
phantom_album = NULL,
phantom_duration_ms = NULL,
phantom_genre = NULL,
phantom_cover_art_path = NULL,
phantom_file_path = NULL
WHERE id = ?`,
audioFileID, playlistTrackID,
); err != nil {
return fmt.Errorf(
"could not resolve phantom track %d: %w",
playlistTrackID, err,
)
}
return nil
}
// resolvePlaylistPhantoms resolves phantom tracks for a single
// playlist by reading its M3U8 file and matching entries against
// the audio_files table. Returns the number of resolved tracks.
@@ -1873,52 +2012,12 @@ func (s *Service) resolvePlaylistPhantoms(
}
// Load phantom tracks for this playlist.
// SAFETY: Hand-crafted SELECT for phantom tracks with
// position and phantom_file_path. No user input.
ptRows, err := s.db.QueryContext(
`SELECT id, position, COALESCE(phantom_file_path, '')
FROM playlist_tracks
WHERE playlist_id = ? AND audio_file_id IS NULL`,
playlistID,
)
if err != nil {
s.logger.Warn(
"could not query phantom tracks",
"playlistId", playlistID,
"err", err,
)
phantoms := s.loadPhantomRows(playlistID)
if len(phantoms.rows) == 0 {
return 0
}
var phantoms []phantomTrackRow
for ptRows.Next() {
var pt phantomTrackRow
if err := ptRows.Scan(
&pt.id, &pt.position, &pt.phantomFilePath,
); err != nil {
continue
}
phantoms = append(phantoms, pt)
}
if err := ptRows.Close(); err != nil {
s.logger.Warn(
"could not close phantom track rows",
"err", err,
)
}
if len(phantoms) == 0 {
return 0
}
// Build a set of already-resolved phantom IDs to avoid
// double-matching.
resolvedIDs := make(map[int64]struct{})
var resolved int
// For each M3U8 entry, resolve its path and try to match
@@ -1933,63 +2032,17 @@ func (s *Service) resolvePlaylistPhantoms(
continue
}
// Find the phantom that corresponds to this entry.
// Priority 1: match by phantom_file_path (exact).
// Priority 2: match by position (M3U8 index).
matchIdx := -1
for j, pt := range phantoms {
if _, done := resolvedIDs[pt.id]; done {
continue
}
if pt.phantomFilePath != "" &&
pt.phantomFilePath == absPath {
matchIdx = j
break
}
}
if matchIdx == -1 {
for j, pt := range phantoms {
if _, done := resolvedIDs[pt.id]; done {
continue
}
if pt.position == int64(i) {
matchIdx = j
break
}
}
}
if matchIdx == -1 {
// Find the phantom that corresponds to this entry:
// phantom_file_path first, then this entry's index.
ptID, found := takePhantomRowAt(phantoms, absPath, i)
if !found {
continue
}
pt := phantoms[matchIdx]
// SAFETY: Hand-crafted UPDATE to resolve a phantom
// playlist track. Sets audio_file_id and clears all
// phantom metadata columns. Parameterized by ID.
if _, err := s.db.ExecContext(
`UPDATE playlist_tracks SET
audio_file_id = ?,
phantom_title = NULL,
phantom_artist = NULL,
phantom_album = NULL,
phantom_duration_ms = NULL,
phantom_genre = NULL,
phantom_cover_art_path = NULL,
phantom_file_path = NULL
WHERE id = ?`,
audioFileID, pt.id,
); err != nil {
if err := s.fillPhantomRow(ptID, audioFileID); err != nil {
s.logger.Warn(
"could not resolve phantom track",
"playlistTrackId", pt.id,
"playlistTrackId", ptID,
"audioFileId", audioFileID,
"err", err,
)
@@ -1997,7 +2050,6 @@ func (s *Service) resolvePlaylistPhantoms(
continue
}
resolvedIDs[pt.id] = struct{}{}
resolved++
}
@@ -2053,52 +2105,110 @@ func (s *Service) FindPhantomMatches(
entryByPath[absPath] = e
}
// Track which candidates have been claimed by auto-match
// so we don't assign the same candidate to two phantoms.
claimed := make(map[string]struct{})
var result PhantomSearchResult
// Every pairing confident enough to apply without asking.
var offers []phantomOffer
for _, phantomPath := range phantomPaths {
entry := entryByPath[phantomPath]
candidates := s.searchCandidates(
phantomPath, entry,
)
matched := false
for _, c := range candidates {
if _, taken := claimed[c.FilePath]; taken {
continue
}
if c.Score >= autoMatchMinimum {
result.AutoMatched = append(
result.AutoMatched,
PhantomMatch{
PhantomPath: phantomPath,
PhantomTitle: entry.DisplayTitle,
Candidate: c,
},
)
claimed[c.FilePath] = struct{}{}
matched = true
for _, c := range s.searchCandidates(phantomPath, entry) {
if c.Score < autoMatchMinimum {
// searchCandidates sorts by score, so nothing
// below this one qualifies either.
break
}
}
if !matched {
result.Unmatched = append(
result.Unmatched, phantomPath,
)
offers = append(offers, phantomOffer{
phantomPath: phantomPath,
phantomTitle: entry.DisplayTitle,
candidate: c,
})
}
}
var result PhantomSearchResult
result.AutoMatched = assignBestFirst(offers)
matched := make(map[string]struct{}, len(result.AutoMatched))
for _, m := range result.AutoMatched {
matched[m.PhantomPath] = struct{}{}
}
// Reported in the order the playlist has them, not the order they
// were matched in.
for _, phantomPath := range phantomPaths {
if _, done := matched[phantomPath]; done {
continue
}
result.Unmatched = append(
result.Unmatched, phantomPath,
)
}
return result, nil
}
// phantomOffer is one candidate a phantom track could be resolved to,
// carrying enough to become a PhantomMatch.
type phantomOffer struct {
phantomPath string
phantomTitle string
candidate CandidateTrack
}
// assignBestFirst pairs phantoms with candidates highest score first,
// at most one candidate per phantom and one phantom per candidate.
//
// A candidate can only stand in for one phantom — two would put that
// file in the playlist twice. Taking the offers in *phantom* order,
// which is what this replaced, let an early phantom claim a candidate
// that was a better answer for a later one, so which of two similar
// tracks got the good match depended on the order they happen to sit in
// the playlist.
func assignBestFirst(offers []phantomOffer) []PhantomMatch {
if len(offers) == 0 {
return nil
}
ordered := make([]phantomOffer, len(offers))
copy(ordered, offers)
slices.SortStableFunc(
ordered,
func(a, b phantomOffer) int {
return cmp.Compare(b.candidate.Score, a.candidate.Score)
},
)
var matches []PhantomMatch
claimedCandidates := make(map[string]struct{}, len(ordered))
matchedPhantoms := make(map[string]struct{}, len(ordered))
for _, o := range ordered {
if _, taken := claimedCandidates[o.candidate.FilePath]; taken {
continue
}
if _, done := matchedPhantoms[o.phantomPath]; done {
continue
}
matches = append(matches, PhantomMatch{
PhantomPath: o.phantomPath,
PhantomTitle: o.phantomTitle,
Candidate: o.candidate,
})
claimedCandidates[o.candidate.FilePath] = struct{}{}
matchedPhantoms[o.phantomPath] = struct{}{}
}
return matches
}
// GetPhantomCandidates returns scored candidate matches for a
// single phantom track.
func (s *Service) GetPhantomCandidates(
@@ -2219,14 +2329,38 @@ func (s *Service) ResolvePhantomTracks(
)
}
// The phantom rows this is about to fill in, so a resolution
// updates the row the user pointed at rather than appending a
// second one beside it.
phantoms := s.loadPhantomRows(playlistID)
// Build M3U path replacements and insert DB rows.
pathReplacements := make(
map[string]string, len(matches),
)
var resolved int
// Two phantoms resolving to one file would put that file in the
// playlist twice, which is what FindPhantomMatches' claimed set
// already refuses to do on the auto-match path.
claimed := make(map[string]struct{}, len(matches))
var (
resolved int
appended int
)
for phantomAbs, resolvedAbs := range matches {
if _, taken := claimed[resolvedAbs]; taken {
s.logger.Warn(
"Two phantom tracks resolved to the same file",
"playlistId", playlistID,
"phantomPath", phantomAbs,
"resolvedPath", resolvedAbs,
)
continue
}
audioFile, lookupErr := s.db.Queries.GetAudioFileByPath(
s.db.Ctx, resolvedAbs,
)
@@ -2241,29 +2375,54 @@ func (s *Service) ResolvePhantomTracks(
continue
}
_, addErr := s.db.Queries.AddPlaylistTrack(
s.db.Ctx,
sqlcgen.AddPlaylistTrackParams{
PlaylistID: playlistID,
AudioFileID: sql.NullInt64{Int64: audioFile.ID, Valid: true},
Position: nextPos + int64(resolved),
},
ptID, found := takePhantomRow(
phantoms, phantomAbs, parsed.Entries, libraryRoots,
)
if addErr != nil {
s.logger.Warn(
"Could not add resolved track",
"playlistId", playlistID,
"path", resolvedAbs,
"err", addErr,
)
continue
switch {
case found:
if updateErr := s.fillPhantomRow(
ptID, audioFile.ID,
); updateErr != nil {
s.logger.Warn(
"Could not resolve phantom row",
"playlistId", playlistID,
"playlistTrackId", ptID,
"path", resolvedAbs,
"err", updateErr,
)
continue
}
default:
// No phantom row for this path — the M3U8 and the
// database disagree, so fall back to appending.
if _, addErr := s.db.Queries.AddPlaylistTrack(
s.db.Ctx,
sqlcgen.AddPlaylistTrackParams{
PlaylistID: playlistID,
AudioFileID: sql.NullInt64{Int64: audioFile.ID, Valid: true},
Position: nextPos + int64(appended),
},
); addErr != nil {
s.logger.Warn(
"Could not add resolved track",
"playlistId", playlistID,
"path", resolvedAbs,
"err", addErr,
)
continue
}
appended++
}
newRel := toRelativePathMultiRoot(
resolvedAbs, libraryRoots,
)
pathReplacements[phantomAbs] = newRel
claimed[resolvedAbs] = struct{}{}
resolved++
}
@@ -2390,11 +2549,11 @@ func (s *Service) searchCandidates(
var combined []database.SearchRow
// 1. Exact basename match via indexed column.
bnRows, err := s.db.Queries.SearchAudioFilesByBasename(
bnRows, err := s.db.Queries.SearchTracksByBasename(
s.db.Ctx,
sqlcgen.SearchAudioFilesByBasenameParams{
sqlcgen.SearchTracksByBasenameParams{
Basename: basename,
Limit: int64(maxCandidates),
Lim: int64(maxCandidates),
},
)
if err != nil {
@@ -2416,7 +2575,7 @@ func (s *Service) searchCandidates(
FilePath: r.FilePath,
LengthMilliseconds: r.LengthMilliseconds,
Title: r.Title,
Artist: r.Artist,
Artist: r.ArtistName,
Album: r.Album,
})
}
+30 -157
View File
@@ -51,116 +51,16 @@ func seedSmartTestTracks(t *testing.T, db *database.DB) {
},
}
// Build unique sets for artist_credit and release_groups.
artistMap := map[string]int64{}
albumMap := map[string]int64{}
var artistID, albumID int64
for _, tr := range tracks {
if _, ok := artistMap[tr.artist]; !ok {
artistID++
artistMap[tr.artist] = artistID
}
if _, ok := albumMap[tr.album]; !ok {
albumID++
albumMap[tr.album] = albumID
}
}
// Insert artist_credit rows.
for text, id := range artistMap {
_, err := db.ExecContext(
"INSERT INTO artist_credit (id, text) VALUES (?, ?)",
id, text,
)
if err != nil {
t.Fatalf("insert artist_credit %q: %v", text, err)
}
}
// Insert release_groups.
for name, id := range albumMap {
_, err := db.ExecContext(
"INSERT INTO release_groups (id, name) VALUES (?, ?)",
id, name,
)
if err != nil {
t.Fatalf("insert release_group %q: %v", name, err)
}
}
// Insert genres.
genreMap := map[string]int64{}
var genreID int64
for _, tr := range tracks {
if _, ok := genreMap[tr.genre]; !ok {
genreID++
genreMap[tr.genre] = genreID
_, err := db.ExecContext(
"INSERT INTO genres (id, name) VALUES (?, ?)",
genreID, tr.genre,
)
if err != nil {
t.Fatalf("insert genre %q: %v", tr.genre, err)
}
}
}
// Insert tracks with full FK chain.
for _, tr := range tracks {
acID := artistMap[tr.artist]
rgID := albumMap[tr.album]
// Insert recording.
_, err := db.ExecContext(
"INSERT INTO recordings (id, name, artist_credit_id, year) "+
"VALUES (?, ?, ?, ?)",
tr.id, tr.title, acID, tr.year,
)
if err != nil {
t.Fatalf("insert recording %d %q: %v", tr.id, tr.title, err)
}
// Insert audio_file.
_, err = db.ExecContext(
"INSERT INTO audio_files (id, file_path, "+
"length_milliseconds, file_type_id, recording_id, "+
"sample_rate, bit_depth, channels, bitrate, file_size) "+
"VALUES (?, ?, ?, 0, ?, 44100, 16, 2, 320000, 5000000)",
tr.id, tr.filePath, tr.lenMs, tr.id,
)
if err != nil {
t.Fatalf("insert audio_file %d: %v", tr.id, err)
}
// Link recording to release_group.
_, err = db.ExecContext(
"INSERT INTO release_group_recordings "+
"(release_group_id, recording_id) VALUES (?, ?)",
rgID, tr.id,
)
if err != nil {
t.Fatalf("insert release_group_recordings %d→%d: %v",
rgID, tr.id, err)
}
// Insert recording_genres link.
gID := genreMap[tr.genre]
_, err = db.ExecContext(
"INSERT INTO recording_genres "+
"(recording_id, genre_id) VALUES (?, ?)",
tr.id, gID,
)
if err != nil {
t.Fatalf("insert recording_genres %d→%d: %v",
tr.id, gID, err)
}
database.InsertTestTrack(t, db, database.TestTrack{
FilePath: tr.filePath,
Title: tr.title,
Artist: tr.artist,
Album: tr.album,
Genres: []string{tr.genre},
Year: tr.year,
LengthMs: tr.lenMs,
})
}
}
@@ -467,27 +367,18 @@ func TestSmartPlaylistEvaluateNonSmartPlaylist(t *testing.T) {
svc := newTestService(t, db)
// Create a regular playlist via direct SQL.
// SAFETY: Test-only insert for regular playlist.
rows, err := db.QueryContext(
`INSERT INTO playlists (name) VALUES (?)
RETURNING id`,
// An INSERT ... RETURNING is a write, so it needs the writer:
// QueryContext routes to the query-only read pool.
var regularID int64
if err := db.QueryRowWriter(
`INSERT INTO playlists (name) VALUES (?) RETURNING id`,
"Regular PL",
)
if err != nil {
).Scan(&regularID); err != nil {
t.Fatalf("insert regular playlist: %v", err)
}
var regularID int64
if rows.Next() {
if err := rows.Scan(&regularID); err != nil {
t.Fatalf("scan regular playlist id: %v", err)
}
}
_ = rows.Close()
// Evaluate should fail — not a smart playlist.
_, err = svc.EvaluateSmartPlaylist(regularID)
_, err := svc.EvaluateSmartPlaylist(regularID)
if err == nil {
t.Fatal("expected error evaluating non-smart playlist, got nil")
}
@@ -512,25 +403,16 @@ func TestSmartPlaylistUpdateNonSmartPlaylist(t *testing.T) {
db := database.NewTestDB(t)
svc := newTestService(t, db)
// Create a regular playlist.
rows, err := db.QueryContext(
`INSERT INTO playlists (name) VALUES (?)
RETURNING id`,
// Create a regular playlist. An INSERT ... RETURNING is a write,
// so it needs the writer: QueryContext routes to the read pool.
var regularID int64
if err := db.QueryRowWriter(
`INSERT INTO playlists (name) VALUES (?) RETURNING id`,
"Regular PL",
)
if err != nil {
).Scan(&regularID); err != nil {
t.Fatalf("insert regular playlist: %v", err)
}
var regularID int64
if rows.Next() {
if err := rows.Scan(&regularID); err != nil {
t.Fatalf("scan regular playlist id: %v", err)
}
}
_ = rows.Close()
rulesJSON := makeRulesJSON(t, smartplaylist.RuleSet{
Rules: []smartplaylist.Rule{
{Field: "title", Operator: "contains", Value: "test"},
@@ -538,7 +420,7 @@ func TestSmartPlaylistUpdateNonSmartPlaylist(t *testing.T) {
})
// Update should fail — not a smart playlist.
err = svc.UpdateSmartPlaylistRules(regularID, rulesJSON)
err := svc.UpdateSmartPlaylistRules(regularID, rulesJSON)
if err == nil {
t.Fatal("expected error updating non-smart playlist, got nil")
}
@@ -765,27 +647,18 @@ func TestSmartPlaylistGetRulesRegularPlaylist(t *testing.T) {
svc := newTestService(t, db)
// Create a regular playlist via direct SQL.
// SAFETY: Test-only insert for regular playlist.
rows, err := db.QueryContext(
`INSERT INTO playlists (name) VALUES (?)
RETURNING id`,
// An INSERT ... RETURNING is a write, so it needs the writer:
// QueryContext routes to the query-only read pool.
var regularID int64
if err := db.QueryRowWriter(
`INSERT INTO playlists (name) VALUES (?) RETURNING id`,
"Regular PL For GetRules",
)
if err != nil {
).Scan(&regularID); err != nil {
t.Fatalf("insert regular playlist: %v", err)
}
var regularID int64
if rows.Next() {
if err := rows.Scan(&regularID); err != nil {
t.Fatalf("scan regular playlist id: %v", err)
}
}
_ = rows.Close()
// GetSmartPlaylistRules should fail — not a smart playlist.
_, err = svc.GetSmartPlaylistRules(regularID)
_, err := svc.GetSmartPlaylistRules(regularID)
if err == nil {
t.Fatal(
"expected error for regular playlist, got nil",