Files
yellowjacket/backend/database/lyrics_search_test.go
T
yonluandClaude Opus 5 e7748f1fd5
CI / check (push) Successful in 3m7s
CI / e2e (push) Canceled after 1m45s
feat(database): shape the library like files, and shrink the catalog
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
2026-08-16 13:58:15 -04:00

227 lines
5.2 KiB
Go

package database
import (
"testing"
)
// seedLyricsTrack inserts one file with the given lyrics, so lyric
// searches have something realistic to join against. It used to
// insert a four-row FK chain by hand.
func seedLyricsTrack(
t *testing.T,
db *DB,
id int64,
title, artist, album, lyrics string,
lenMs int64,
) int64 {
t.Helper()
fileID := InsertTestTrack(t, db, TestTrack{
FilePath: "/music/track" + itoa(id) + ".mp3",
Title: title,
Artist: artist,
Album: album,
LengthMs: lenMs,
})
if lyrics != "" {
if err := db.SetLyrics(fileID, lyrics, "tag", ""); err != nil {
t.Fatalf("seed lyrics: %v", err)
}
}
return fileID
}
func itoa(v int64) string {
if v == 0 {
return "0"
}
var b []byte
for v > 0 {
b = append([]byte{byte('0' + v%10)}, b...)
v /= 10
}
return string(b)
}
func TestSearchLyrics(t *testing.T) {
t.Parallel()
db := NewTestDB(t)
seedLyricsTrack(
t,
db,
1,
"The Sound of Silence",
"Simon & Garfunkel",
"Sounds of Silence",
"Hello darkness my old friend\nI've come to talk with you again",
180000,
)
seedLyricsTrack(t, db, 2, "Bohemian Rhapsody", "Queen", "A Night at the Opera",
"Is this the real life? Is this just fantasy?", 354000)
seedLyricsTrack(t, db, 3, "Instrumental Track", "Some Artist", "Some Album",
"", 200000) // no lyrics — must never appear in results
if err := db.RebuildLyricsIndex(); err != nil {
t.Fatalf("RebuildLyricsIndex: %v", err)
}
t.Run("phrase match returns the right track with metadata", func(t *testing.T) {
t.Parallel()
hits, err := db.SearchLyrics("hello darkness my old friend", 10)
if err != nil {
t.Fatalf("SearchLyrics: %v", err)
}
if len(hits) != 1 {
t.Fatalf("expected 1 hit, got %d: %+v", len(hits), hits)
}
h := hits[0]
if h.AudioFileID != 1 {
t.Errorf("RecordingID = %d, want 1", h.AudioFileID)
}
if h.Title != "The Sound of Silence" {
t.Errorf("Title = %q, want The Sound of Silence", h.Title)
}
if h.Artist != "Simon & Garfunkel" {
t.Errorf("Artist = %q, want Simon & Garfunkel", h.Artist)
}
if h.Album != "Sounds of Silence" {
t.Errorf("Album = %q, want Sounds of Silence", h.Album)
}
if h.FilePath == "" {
t.Error("FilePath is empty; expected a playable path")
}
})
t.Run("adjacency: scrambled words do not match as a phrase", func(t *testing.T) {
t.Parallel()
hits, err := db.SearchLyrics("friend old darkness", 10)
if err != nil {
t.Fatalf("SearchLyrics: %v", err)
}
if len(hits) != 0 {
t.Errorf("expected 0 phrase hits for scrambled words, got %d", len(hits))
}
})
t.Run("empty query returns nil", func(t *testing.T) {
t.Parallel()
hits, err := db.SearchLyrics(" ", 10)
if err != nil {
t.Fatalf("SearchLyrics: %v", err)
}
if hits != nil {
t.Errorf("expected nil for empty query, got %+v", hits)
}
})
t.Run("no match returns no hits", func(t *testing.T) {
t.Parallel()
hits, err := db.SearchLyrics("this phrase appears in no song", 10)
if err != nil {
t.Fatalf("SearchLyrics: %v", err)
}
if len(hits) != 0 {
t.Errorf("expected 0 hits, got %d", len(hits))
}
})
}
func TestSetRecordingLyricsUpdatesIndex(t *testing.T) {
t.Parallel()
db := NewTestDB(t)
// Track starts with no lyrics.
seedLyricsTrack(t, db, 1, "Yesterday", "The Beatles", "Help!", "", 125000)
if err := db.RebuildLyricsIndex(); err != nil {
t.Fatalf("RebuildLyricsIndex: %v", err)
}
// Nothing indexed yet.
if hits, _ := db.SearchLyrics("yesterday all my troubles", 10); len(hits) != 0 {
t.Fatalf("expected 0 hits before backfill, got %d", len(hits))
}
// Backfill lyrics — should update both the column and the FTS index.
const lyrics = "Yesterday all my troubles seemed so far away"
if err := db.SetLyrics(1, lyrics, "lrclib", ""); err != nil {
t.Fatalf("SetRecordingLyrics: %v", err)
}
stored, err := db.GetLyrics(1)
if err != nil {
t.Fatalf("GetRecordingLyrics: %v", err)
}
if stored != lyrics {
t.Errorf("stored lyrics = %q, want %q", stored, lyrics)
}
hits, err := db.SearchLyrics("all my troubles seemed so far away", 10)
if err != nil {
t.Fatalf("SearchLyrics: %v", err)
}
if len(hits) != 1 || hits[0].AudioFileID != 1 {
t.Fatalf("expected recording 1 after backfill, got %+v", hits)
}
}
func TestRecordingsMissingLyrics(t *testing.T) {
t.Parallel()
db := NewTestDB(t)
seedLyricsTrack(t, db, 1, "Has Lyrics", "Artist A", "Album A", "some words here", 100000)
seedLyricsTrack(t, db, 2, "No Lyrics", "Artist B", "Album B", "", 200000)
missing, err := db.FilesMissingLyrics(50)
if err != nil {
t.Fatalf("RecordingsMissingLyrics: %v", err)
}
if len(missing) != 1 {
t.Fatalf("expected 1 candidate, got %d: %+v", len(missing), missing)
}
c := missing[0]
if c.AudioFileID != 2 || c.Title != "No Lyrics" || c.Artist != "Artist B" {
t.Errorf("unexpected candidate: %+v", c)
}
if c.LengthMilliseconds != 200000 {
t.Errorf("LengthMilliseconds = %d, want 200000", c.LengthMilliseconds)
}
// Single-recording lookup mirrors the batch fields.
one, err := db.FileLyricLookup(2)
if err != nil {
t.Fatalf("RecordingLyricLookup: %v", err)
}
if one == nil || one.Artist != "Artist B" || one.Album != "Album B" {
t.Errorf("unexpected lookup: %+v", one)
}
}