Files
minstrel/internal/library/duplicate_resolve_test.go
T
bvandeusenandClaude Opus 5.5 677a421675
release / go (push) Successful in 2m28s
release / web (push) Successful in 1m42s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 5m9s
release / android (push) Successful in 5m28s
release / Build signed APK (push) Successful in 5m54s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 34s
release / Verify release artifacts (tag releases only) (push) Skipped
fix(library): the duplicate resolver never removes a file on its own (#8252)
Other programs file music into the library now, and a startup pass
deleted a whole album a download manager had just filed, keeping older
loose copies of the same songs. The resolver assumed Minstrel was the
only program writing the library; it is not.

An automatic pass now changes only Minstrel's database:
- copies of one song, on one album or across releases, are linked as one
  song, so likes, plays and mixes count it once, and any group an admin
  may want to thin stays pending for review (and is announced);
- distinct versions are still dismissed, and rips still held back;
- a one-album wrong slot gets a note naming the song MusicBrainz or
  AcoustID says the recording is, for the admin who settles it.

Removing a copy is an admin's merge or wrong-slot settle, as before. When
an admin merges, a copy in a folder named for its album ("Album (Year)",
or its "CD nn" folder) now outranks a loose copy of the same audio.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:09:11 -05:00

836 lines
32 KiB
Go

package library
import (
"context"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
syncpkg "github.com/Fabled-Sword/minstrel/internal/sync"
)
// resolveFixture is the Mammalz shape: one album, one song twice, both copies on
// disk under an artist/album folder, in one pending exact-tier group.
type resolveFixture struct {
pool *pgxpool.Pool
clean, rip dbq.Track
cleanPath, ripPath string
groupID pgtype.UUID
}
func newResolveFixture(t *testing.T) resolveFixture {
t.Helper()
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
dir := filepath.Join(t.TempDir(), "Plastic Apes", "Mammalz (2017)")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
f := resolveFixture{pool: pool}
f.cleanPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz.mp3")
f.ripPath = filepath.Join(dir, "Plastic Apes - Mammalz - 03 - Neptunez Barz (Official Video).mp3")
for _, p := range []string{f.cleanPath, f.ripPath} {
if err := os.WriteFile(p, []byte("audio"), 0o644); err != nil {
t.Fatal(err)
}
}
var album dbq.Album
var artist dbq.Artist
f.clean, album, artist = seedTrack(t, pool, f.cleanPath)
rip, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Neptunez Barz (Official Video)", AlbumID: album.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: f.ripPath, FileSize: 100, FileFormat: "mp3",
})
if err != nil {
t.Fatal(err)
}
f.rip = rip
exec := func(sql string, args ...any) {
t.Helper()
if _, err := pool.Exec(ctx, sql, args...); err != nil {
t.Fatalf("exec %q: %v", sql, err)
}
}
exec(`UPDATE tracks SET title = 'Neptunez Barz' WHERE id = $1`, f.clean.ID)
if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ('resolve-fixture', 'exact') RETURNING id`,
).Scan(&f.groupID); err != nil {
t.Fatal(err)
}
exec(`INSERT INTO duplicate_group_members (group_id, track_id) VALUES ($1, $2), ($1, $3)`, f.groupID, f.clean.ID, f.rip.ID)
return f
}
func (f resolveFixture) group(t *testing.T) (status string, class *string, note *string, auto bool) {
t.Helper()
if err := f.pool.QueryRow(context.Background(),
`SELECT status, class, resolve_note, resolved_automatically FROM duplicate_groups WHERE id = $1`, f.groupID,
).Scan(&status, &class, &note, &auto); err != nil {
t.Fatal(err)
}
return status, class, note, auto
}
func exists(p string) bool { _, err := os.Stat(p); return err == nil }
// autoMergeAudit reads the resolver's audit row for a group: how many there
// are, and the reason the last one gave for its survivor.
func autoMergeAudit(t *testing.T, pool *pgxpool.Pool, groupID pgtype.UUID) (n int, reason string) {
t.Helper()
if err := pool.QueryRow(context.Background(),
`SELECT count(*), coalesce(max(metadata->>'survivor_reason'), '') FROM audit_log
WHERE action = 'duplicate_merge' AND actor_id IS NULL
AND metadata->>'group_id' = $1 AND (metadata->>'automatic')::boolean`,
syncpkg.FormatUUID(groupID)).Scan(&n, &reason); err != nil {
t.Fatal(err)
}
return n, reason
}
// One album holding a song twice: the pass removes neither file, since
// another program may have filed either. It links the copies as one song and
// leaves the group for an admin to merge.
func TestResolveDuplicates_LinksASameReleaseCopyAndRemovesNothing_Integration(t *testing.T) {
f := newResolveFixture(t)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatalf("resolve: %v", err)
}
if res.Classes[ClassSameRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("result = %+v, want the same-release group linked as one song", res)
}
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("rip exists=%v clean exists=%v; want both files left in place", exists(f.ripPath), exists(f.cleanPath))
}
status, class, note, auto := f.group(t)
if status != "pending" || class == nil || *class != string(ClassSameRelease) || auto || note == nil {
t.Errorf("group = (%s, %v, note %v, auto=%v), want a pending same_release group with a note", status, class, note, auto)
}
if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 {
t.Errorf("automatic merge audit rows = %d, want none", n)
}
}
// With auto-resolve off, the pass classifies and removes nothing.
func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testing.T) {
f := newResolveFixture(t)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, false)
if err != nil {
t.Fatal(err)
}
if res.SongsLinked != 0 || !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("result %+v; want nothing linked or removed", res)
}
status, class, _, _ := f.group(t)
if status != "pending" || class == nil || *class != string(ClassSameRelease) {
t.Errorf("group = (%s, %v), want pending and classified", status, class)
}
}
// crossReleaseRipFixture is a video rip on one release with the clean copy on
// another: the album cut, and the same song's video filed as a single.
type crossReleaseRipFixture struct {
pool *pgxpool.Pool
clean, rip dbq.Track
cleanPath, ripPath string
groupID pgtype.UUID
}
func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
t.Helper()
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
root := t.TempDir()
f := crossReleaseRipFixture{pool: pool}
f.cleanPath = filepath.Join(root, "Plastic Apes", "Ghost Nights (2005)", "06 - Feel Fine Ltd.mp3")
f.ripPath = filepath.Join(root, "Plastic Apes", "Feel Fine Ltd (2005)", "01 - Feel Fine Ltd. (Official Video).mp3")
artist, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Plastic Apes", SortName: "Plastic Apes"})
if err != nil {
t.Fatal(err)
}
track := func(albumTitle, title, path string) dbq.Track {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("audio"), 0o644); err != nil {
t.Fatal(err)
}
album, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: albumTitle, SortTitle: albumTitle, ArtistID: artist.ID})
if err != nil {
t.Fatal(err)
}
tr, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: title, AlbumID: album.ID, ArtistID: artist.ID,
DurationMs: 1000, FilePath: path, FileSize: 100, FileFormat: "mp3",
})
if err != nil {
t.Fatal(err)
}
return tr
}
f.clean = track("Ghost Nights", "Feel Fine Ltd.", f.cleanPath)
f.rip = track("Feel Fine Ltd.", "Feel Fine Ltd. (Official Video)", f.ripPath)
if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ('cross-rip', 'acoustic') RETURNING id`,
).Scan(&f.groupID); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx,
`INSERT INTO duplicate_group_members (group_id, track_id) VALUES ($1, $2), ($1, $3)`,
f.groupID, f.clean.ID, f.rip.ID); err != nil {
t.Fatal(err)
}
return f
}
// A video rip on one release with the clean copy on another: both files stay,
// the copies count as one song, and the group waits for an admin to remove
// the rip.
func TestResolveDuplicates_LinksARipAcrossReleasesAndRemovesNothing_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("result %+v; want the cross-release group linked as one song", res)
}
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("rip exists %v, clean exists %v; want both files left in place", exists(f.ripPath), exists(f.cleanPath))
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending for an admin", status)
}
if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 {
t.Errorf("automatic merge audit rows = %d, want none", n)
}
}
// Copies on two releases that are both clean each belong to their release:
// nothing is removed, and they are linked as one song. A rip an admin
// marked fine counts as clean.
func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.T) {
for name, prepare := range map[string]func(f crossReleaseRipFixture) (string, []any){
"renamed": func(f crossReleaseRipFixture) (string, []any) {
return `UPDATE tracks SET title = 'Feel Fine Ltd.', file_path = $2 WHERE id = $1`,
[]any{f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")}
},
"kept as fine": func(f crossReleaseRipFixture) (string, []any) {
return `UPDATE tracks SET source_verdict = 'fine' WHERE id = $1`, []any{f.rip.ID}
},
} {
t.Run(name, func(t *testing.T) {
f := newCrossReleaseRipFixture(t)
sql, args := prepare(f)
if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("result %+v; want both copies kept", res)
}
if res.SongsLinked != 1 {
t.Errorf("linked %d, want the pair linked as one song", res.SongsLinked)
}
})
}
}
// Identical audio under two titles on two albums, neither a rip: a later
// release retitled the recording ("F.O.E." and "F.O.E. (live)"). Each copy
// belongs to its release, so nothing is removed and they count as one song.
func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
ctx := context.Background()
if _, err := f.pool.Exec(ctx, `UPDATE duplicate_groups SET tier = 'exact' WHERE id = $1`, f.groupID); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(ctx, `UPDATE tracks SET title = 'DARE', file_path = $2 WHERE id = $1`,
f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3")); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 || !exists(f.ripPath) || !exists(f.cleanPath) {
t.Fatalf("result %+v; want the pair linked and kept", res)
}
}
// oneAlbumFixture is one album holding two tracks in one pending group, each
// with a file on disk.
type oneAlbumFixture struct {
pool *pgxpool.Pool
album dbq.Album
a, b dbq.Track
aPath string
bPath string
groupID pgtype.UUID
}
func newOneAlbumFixture(t *testing.T, tier, titleA, titleB string) oneAlbumFixture {
t.Helper()
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
dir := filepath.Join(t.TempDir(), "Savanta", "Void")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
f := oneAlbumFixture{pool: pool, aPath: filepath.Join(dir, "15 - a.m4a"), bPath: filepath.Join(dir, "17 - b.m4a")}
for _, p := range []string{f.aPath, f.bPath} {
if err := os.WriteFile(p, []byte("audio"), 0o644); err != nil {
t.Fatal(err)
}
}
var artist dbq.Artist
f.a, f.album, artist = seedTrack(t, pool, f.aPath)
b, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: titleB, AlbumID: f.album.ID, ArtistID: artist.ID,
DurationMs: 220000, FilePath: f.bPath, FileSize: 100, FileFormat: "m4a",
})
if err != nil {
t.Fatal(err)
}
f.b = b
if _, err := pool.Exec(ctx, `UPDATE tracks SET title = $2, duration_ms = 220000 WHERE id = $1`, f.a.ID, titleA); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx,
`INSERT INTO duplicate_groups (member_key, tier) VALUES ($1, $2) RETURNING id`, t.Name(), tier,
).Scan(&f.groupID); err != nil {
t.Fatal(err)
}
if _, err := pool.Exec(ctx, `INSERT INTO duplicate_group_members (group_id, track_id) VALUES ($1, $2), ($1, $3)`,
f.groupID, f.a.ID, f.b.ID); err != nil {
t.Fatal(err)
}
return f
}
func auditCount(t *testing.T, pool *pgxpool.Pool, action string, groupID pgtype.UUID) int {
t.Helper()
var n int
if err := pool.QueryRow(context.Background(),
`SELECT count(*) FROM audit_log WHERE action = $1 AND metadata->>'group_id' = $2`,
action, syncpkg.FormatUUID(groupID)).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
// Two versions of a song on one album that sound alike are not duplicates:
// the group is dismissed and both files stay.
func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)")
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Dismissed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v; want the group dismissed and both files kept", res)
}
if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "dismissed" || !auto {
t.Errorf("group = (%s, auto=%v), want dismissed by the resolver", status, auto)
}
if n := auditCount(t, f.pool, "duplicate_dismiss", f.groupID); n != 1 {
t.Errorf("dismiss audit rows = %d, want 1", n)
}
}
// seedTrackList holds a release group whose one release lists the songs with
// their lengths, and points the album at it.
func seedTrackList(t *testing.T, pool *pgxpool.Pool, album dbq.Album, songs map[string]int) {
t.Helper()
ctx := context.Background()
rg := "rg-" + syncpkg.FormatUUID(album.ID)
rel := "rel-" + syncpkg.FormatUUID(album.ID)
for _, stmt := range []struct {
sql string
args []any
}{
{`INSERT INTO mb_release_groups (mbid, title) VALUES ($1, 'Void')`, []any{rg}},
{`INSERT INTO mb_releases (mbid, release_group_mbid, title) VALUES ($1, $2, 'Void')`, []any{rel, rg}},
{`UPDATE albums SET release_group_mbid = $2 WHERE id = $1`, []any{album.ID, rg}},
} {
if _, err := pool.Exec(ctx, stmt.sql, stmt.args...); err != nil {
t.Fatalf("exec %q: %v", stmt.sql, err)
}
}
pos := 1
for title, ms := range songs {
if _, err := pool.Exec(ctx,
`INSERT INTO mb_release_tracks (release_mbid, medium_position, position, title, length_ms) VALUES ($1, 1, $2, $3, $4)`,
rel, pos, title, ms); err != nil {
t.Fatal(err)
}
pos++
}
}
// noteOf is a group's resolve note, or "" when it has none.
func noteOf(t *testing.T, pool *pgxpool.Pool, groupID pgtype.UUID) string {
t.Helper()
_, _, note, _ := (resolveFixture{pool: pool, groupID: groupID}).group(t)
if note == nil {
return ""
}
return *note
}
// settleKeeping settles a wrong slot as an admin would, keeping the copy at
// keep.
func settleKeeping(t *testing.T, f oneAlbumFixture, keep pgtype.UUID) WrongSlotResult {
t.Helper()
res, err := SettleWrongSlot(context.Background(), f.pool, nil, f.groupID, keep, pgtype.UUID{})
if err != nil {
t.Fatalf("settle: %v", err)
}
return res
}
// One recording in two slots of an album: MusicBrainz says Void is as long as
// the file and Reach is a minute longer. The pass removes nothing; it names
// Void in the group's note. Settled with that copy, the copy in Reach's slot
// goes, and its track stays, marked missing, until a good copy arrives.
func TestResolveDuplicates_NamesTheSongOfACopyInAnotherSongsSlot_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000})
// The wrong file is Void's recording, so it carries Void's MBID.
if _, err := f.pool.Exec(context.Background(),
`UPDATE tracks SET mbid = 'rec-void', mbid_source = 'tag' WHERE id = ANY($1)`, []pgtype.UUID{f.a.ID, f.b.ID}); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want Void named and both files kept",
res, exists(f.aPath), exists(f.bPath))
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "\u201cVoid\u201d") {
t.Errorf("note %q, want it to name Void", note)
}
settleKeeping(t, f, f.a.ID)
// Folded by that MBID into the copy kept, the slot would never be wanted
// back.
if pairs, err := PairMissingTracks(context.Background(), f.pool, nil); err != nil || pairs.Folded() != 0 {
t.Fatalf("missing-pair pass = %+v, %v; want the emptied slot left alone", pairs, err)
}
if !exists(f.aPath) || exists(f.bPath) {
t.Fatalf("void exists %v, reach exists %v; want only Reach's copy removed", exists(f.aPath), exists(f.bPath))
}
var missing bool
if err := f.pool.QueryRow(context.Background(),
`SELECT missing_since IS NOT NULL FROM tracks WHERE id = $1`, f.b.ID).Scan(&missing); err != nil {
t.Fatalf("Reach's track is gone: %v", err)
}
if !missing {
t.Error("Reach's track is not marked missing, so nothing will fetch it again")
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" {
t.Errorf("group = %s, want settled", status)
}
if n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 {
t.Errorf("wrong-file audit rows = %d, want 1", n)
}
}
// A slot emptied of another song's file folds into a copy of its own song the
// album already holds (Savanta's VOID DLC "Sleeper" beside Void's). A copy under
// the title that is not as long as the song is another song: the slot waits for
// a good copy, and folds into that.
func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *testing.T) {
for _, tc := range []struct {
name string
heldMs int32
foldsFirst int
}{
{"the album holds Reach", 281500, 1},
{"the album holds a file titled Reach that is not", 220000, 0},
} {
t.Run(tc.name, func(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
ctx := context.Background()
q := dbq.New(f.pool)
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000})
held := func(name string, ms int32) {
t.Helper()
if _, err := q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Reach", AlbumID: f.album.ID, ArtistID: f.a.ArtistID,
DurationMs: ms, FilePath: filepath.Join(filepath.Dir(f.aPath), name), FileSize: 100, FileFormat: "m4a",
}); err != nil {
t.Fatal(err)
}
}
held("17 - Reach (other edition).m4a", tc.heldMs)
if res := settleKeeping(t, f, f.a.ID); len(res.Removed) != 1 {
t.Fatalf("settle = %+v; want Reach's slot emptied", res)
}
pairs, err := PairMissingTracks(ctx, f.pool, nil)
if err != nil || pairs.Folded() != tc.foldsFirst {
t.Fatalf("missing-pair pass = %+v, %v; want %d folded", pairs, err, tc.foldsFirst)
}
if tc.foldsFirst == 1 {
return
}
held("17 - Reach (fetched again).m4a", 281200)
if pairs, err := PairMissingTracks(ctx, f.pool, nil); err != nil || pairs.Folded() != 1 {
t.Fatalf("missing-pair pass after the fetch = %+v, %v; want the slot folded into the copy fetched", pairs, err)
}
})
}
}
// One recording filling two slots whose songs are both clearly something else
// (Shnorkelbub's whole album in one file): the note says it is neither song,
// and both files stay until an admin settles it.
func TestResolveDuplicates_SaysWhenNoSlotIsTheRecordings_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 282000, "Reach": 421000})
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want it named and both files kept",
res, exists(f.aPath), exists(f.bPath))
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") {
t.Errorf("note %q, want it to say the recording is neither song", note)
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending for an admin", status)
}
}
// seedTrimmedAlbum is newOneAlbumFixture for one recording cut to both its
// slots' lengths: identical audio, as Tormentor and as Record Shop, each as
// long as its own slot's song, and the track list naming each slot's
// recording.
func seedTrimmedAlbum(t *testing.T) oneAlbumFixture {
t.Helper()
f := newOneAlbumFixture(t, "exact", "Tormentor", "Record Shop")
ctx := context.Background()
seedTrackList(t, f.pool, f.album, map[string]int{"Tormentor": 221000, "Record Shop": 219000})
if _, err := f.pool.Exec(ctx,
`UPDATE mb_release_tracks SET recording_mbid = 'rec-' || lower(replace(title, ' ', '-'))`); err != nil {
t.Fatal(err)
}
return f
}
// AcoustID matched one copy to Tormentor's recording: the note names
// Tormentor, and both files stay.
func TestResolveDuplicates_NamesTheCopyAcoustIDNames_Integration(t *testing.T) {
f := seedTrimmedAlbum(t)
if _, err := f.pool.Exec(context.Background(),
`INSERT INTO track_acoustid_lookups (track_id, state, candidates, recording_mbid) VALUES ($1, 'matched', 1, 'rec-tormentor')`,
f.a.ID); err != nil {
t.Fatal(err)
}
asked := 0
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil },
})
if err != nil {
t.Fatal(err)
}
if asked != 0 {
t.Errorf("AcoustID asked %d times; the copy's own lookup already answered", asked)
}
if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want Tormentor named and both kept",
res, exists(f.aPath), exists(f.bPath))
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "AcoustID says") || !strings.Contains(note, "Tormentor") {
t.Errorf("note %q, want AcoustID's answer naming Tormentor", note)
}
}
// Copies whose own lookups all name Record Shop's recording are that
// recording, though their fingerprints differ a little and one is six seconds
// from Tormentor's length, too near for the lengths to decide. With no
// lookups, copies that far apart are not asked about.
func TestResolveDuplicates_AgreeingLookupsDecideAnAcousticGroup_Integration(t *testing.T) {
setup := func(t *testing.T) oneAlbumFixture {
f := seedTrimmedAlbum(t)
for _, stmt := range []string{
`UPDATE duplicate_groups SET tier = 'acoustic', worst_bit_error_rate = 0.04`,
`UPDATE mb_release_tracks SET length_ms = 226000 WHERE title = 'Tormentor'`,
} {
if _, err := f.pool.Exec(context.Background(), stmt); err != nil {
t.Fatalf("exec %q: %v", stmt, err)
}
}
return f
}
t.Run("agreeing", func(t *testing.T) {
f := setup(t)
if _, err := f.pool.Exec(context.Background(),
`INSERT INTO track_acoustid_lookups (track_id, state, candidates, recording_mbid)
VALUES ($1, 'matched', 1, 'rec-record-shop'), ($2, 'matched', 1, 'rec-record-shop')`,
f.a.ID, f.b.ID); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want Record Shop named and both kept",
res, exists(f.aPath), exists(f.bPath))
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "Record Shop") {
t.Errorf("note %q, want it to name Record Shop", note)
}
})
t.Run("unknown", func(t *testing.T) {
f := setup(t)
asked := 0
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil },
})
if err != nil {
t.Fatal(err)
}
if asked != 0 || res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("asked %d, result %+v; want nothing asked or named for copies that may be two takes", asked, res)
}
})
}
// A pass while a scan is walking the library waits for it: a pass deciding
// from tracks the scan is still rewriting would decide from a library
// half-read. A run stuck past StuckScanThreshold does not hold the resolver
// up. Files being
// read with no run recorded (a scan whose run row hasn't landed yet, a
// watcher batch) hold it up as well.
func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) {
f := seedTrimmedAlbum(t)
ctx := context.Background()
w := NewDuplicateResolveWorker(f.pool, slog.New(slog.NewTextHandler(io.Discard, nil)), nil, ResolveSources{})
if _, err := f.pool.Exec(ctx, `INSERT INTO scan_runs DEFAULT VALUES`); err != nil {
t.Fatal(err)
}
if !w.tickOnce(ctx) {
t.Error("a pass ran under a running scan")
}
if !exists(f.aPath) || !exists(f.bPath) {
t.Error("a copy was removed while the scan was walking the library")
}
if _, err := f.pool.Exec(ctx, `UPDATE scan_runs SET started_at = now() - interval '2 hours'`); err != nil {
t.Fatal(err)
}
if w.tickOnce(ctx) {
t.Error("a scan stuck for two hours held the resolver up")
}
if _, err := f.pool.Exec(ctx, `DELETE FROM scan_runs`); err != nil {
t.Fatal(err)
}
if !filesGate.tryAcquire() {
t.Fatal("the files gate was already held")
}
waited := w.tickOnce(ctx)
filesGate.release()
if !waited {
t.Error("a pass ran while files were being read, with no scan run recorded")
}
if w.tickOnce(ctx) {
t.Error("a pass was put off with nothing reading files")
}
}
// AcoustID knows the recording as no song of the album: the note says so. With
// AcoustID unreachable, nothing is decided. Either way the group waits.
func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testing.T) {
t.Run("no match", func(t *testing.T) {
f := seedTrimmedAlbum(t)
asked := 0
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) {
asked++
return []string{"rec-elsewhere"}, nil
},
})
if err != nil {
t.Fatal(err)
}
if asked != 1 || res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("asked %d, result %+v; want one lookup, the slot named and both files kept", asked, res)
}
if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") {
t.Errorf("note %q, want it to say the recording is neither song", note)
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending", status)
}
})
t.Run("unreachable", func(t *testing.T) {
f := seedTrimmedAlbum(t)
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) { return nil, ErrIdentifyUnavailable },
})
if err != nil {
t.Fatal(err)
}
if res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v; want nothing named while AcoustID cannot answer", res)
}
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending", status)
}
})
}
// An album whose track list the catalogue never read: the resolver asks for
// it, once, and decides with what comes back.
func TestResolveDuplicates_FetchesAMissingTrackList_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
rg := "rg-" + syncpkg.FormatUUID(f.album.ID)
if _, err := f.pool.Exec(context.Background(),
`UPDATE albums SET release_group_mbid = $2 WHERE id = $1`, f.album.ID, rg); err != nil {
t.Fatal(err)
}
calls := 0
fetch := func(_ context.Context, asked string) error {
calls++
if asked != rg {
t.Errorf("asked for %s, want %s", asked, rg)
}
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000})
return nil
}
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: fetch})
if err != nil {
t.Fatal(err)
}
if calls != 1 || res.SlotsNamed != 1 || !exists(f.bPath) {
t.Fatalf("fetches %d, result %+v; want one fetch, the slot named and Reach's copy kept", calls, res)
}
}
// With MusicBrainz track lists switched off, the resolver asks once, gets
// ErrLookupOff, and names nothing it can't decide without the list.
func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
if _, err := f.pool.Exec(context.Background(),
`UPDATE albums SET release_group_mbid = $2 WHERE id = $1`, f.album.ID, "rg-off"); err != nil {
t.Fatal(err)
}
calls := 0
off := func(context.Context, string) error {
calls++
return ErrLookupOff
}
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: off})
if err != nil {
t.Fatal(err)
}
if calls != 1 || res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("fetches %d, result %+v; want one refused fetch and both copies kept", calls, res)
}
}
// Without a track list that decides, nothing is named.
func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000})
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.SlotsNamed != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v; want both copies kept when the lengths cannot tell", res)
}
if status, class, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" ||
class == nil || *class != string(ClassMismatch) {
t.Errorf("group = (%s, %v), want a pending mismatch", status, class)
}
}
// A rip is held back from radio and the mixes; an admin's "fine" sticks
// through later passes; a renamed file is released.
func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
ctx := context.Background()
q := dbq.New(f.pool)
// Without its group the rip is judged by its name alone.
if _, err := f.pool.Exec(ctx, `DELETE FROM duplicate_groups WHERE id = $1`, f.groupID); err != nil {
t.Fatal(err)
}
verdict := func(id pgtype.UUID) *string {
t.Helper()
var v *string
if err := f.pool.QueryRow(ctx, `SELECT source_verdict FROM tracks WHERE id = $1`, id).Scan(&v); err != nil {
t.Fatal(err)
}
return v
}
resolve := func() DuplicateResolveResult {
t.Helper()
res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
return res
}
if res := resolve(); res.HeldBack != 1 {
t.Errorf("held back %d, want the rip", res.HeldBack)
}
if v := verdict(f.rip.ID); v == nil || *v != "suspect" {
t.Errorf("rip verdict %v, want suspect", v)
}
if v := verdict(f.clean.ID); v != nil {
t.Errorf("clean copy verdict %v, want none", *v)
}
if n, err := q.SetTrackSourceVerdict(ctx, dbq.SetTrackSourceVerdictParams{Verdict: "fine", ID: f.rip.ID}); err != nil || n != 1 {
t.Fatalf("set fine: %d, %v", n, err)
}
if res := resolve(); res.HeldBack != 0 {
t.Errorf("held back %d after the operator's fine, want 0", res.HeldBack)
}
if v := verdict(f.rip.ID); v == nil || *v != "fine" {
t.Errorf("rip verdict %v, want fine kept", v)
}
// Held back again, then renamed: the next pass lets it go.
if _, err := q.SetTrackSourceVerdict(ctx, dbq.SetTrackSourceVerdictParams{Verdict: "suspect", ID: f.rip.ID}); err != nil {
t.Fatal(err)
}
if _, err := f.pool.Exec(ctx, `UPDATE tracks SET file_path = $2 WHERE id = $1`,
f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - Feel Fine Ltd.mp3")); err != nil {
t.Fatal(err)
}
if res := resolve(); res.Released != 1 {
t.Errorf("released %d, want the renamed track", res.Released)
}
if v := verdict(f.rip.ID); v != nil {
t.Errorf("renamed track verdict %v, want none", *v)
}
// The clean copy can't be flagged by hand: there is nothing to judge.
if n, err := q.SetTrackSourceVerdict(ctx, dbq.SetTrackSourceVerdictParams{Verdict: "fine", ID: f.clean.ID}); err != nil || n != 0 {
t.Errorf("set on an unflagged track: %d, %v; want 0 rows", n, err)
}
}