The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
16 changed files with 330 additions and 462 deletions
Showing only changes of commit 677a421675 - Show all commits
+1 -1
View File
@@ -75,7 +75,7 @@ ListenBrainz, email, metadata sources and recommendation tuning are set in the w
## Setup pitfalls
- **The library mount has to be writable by uid 1000.** Minstrel deletes a file when an admin asks it to, and when the duplicate resolver removes a copy. It never moves, renames or retags your files. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
- **The library mount has to be writable by uid 1000.** Minstrel deletes a file only when an admin asks it to, such as merging duplicates. It never moves, renames or retags your files, so a tagger or download manager can keep filing into the same folder. Mount the library `:ro` to forbid writes: those actions then refuse and say why.
- **`MINSTREL_LIBRARY_SCAN_PATHS` names the path inside the container** (`/music`), not the folder on your host.
- **On the internet, put it behind HTTPS.** Plain `http://` is fine on a network you trust. For a public server, bind the port to `127.0.0.1` and put a reverse proxy in front: see [docs/hosting.md](docs/hosting.md).
+1 -1
View File
@@ -369,7 +369,7 @@ func run() error {
// catalogue for the track list of an album whose wrong slot it must
// decide, a few a pass. See internal/library/duplicate_resolve.go.
go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"),
cfg.Storage.DataDir, fpSettings, library.ResolveSources{
fpSettings, library.ResolveSources{
TrackLists: func(ctx context.Context, releaseGroupMBID string) error {
if !lookupSettings.Get().MusicBrainzTrackLists {
return library.ErrLookupOff
+1 -1
View File
@@ -300,7 +300,7 @@ func foldDuplicateGroups(rows []dbq.ListPendingDuplicateGroupMembersRow) []dupli
})
candidates[n] = append(candidates[n], library.SurvivorCandidate{
TrackID: trackID, FileFormat: row.FileFormat, FileSize: row.FileSize, AddedAt: row.AddedAt.Time,
TagFit: library.TagFitScore(row.TrackNumber != nil, row.PositionClash, row.FilePath, row.HasMbid),
TagFit: library.TagFitScore(row.TrackNumber != nil, row.PositionClash, row.FilePath, row.AlbumTitle, row.HasMbid),
})
}
for i := range groups {
+57 -279
View File
@@ -11,41 +11,32 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/audit"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/notifications"
syncpkg "github.com/Fabled-Sword/minstrel/internal/sync"
)
// Duplicate resolver.
//
// The sweep proposes duplicate groups; the resolver decides what each one is
// and settles the ones that are safe to settle without asking. Minstrel is the
// only program writing the library, so no copy is kept because something else
// depends on it. What decides is what the copies are:
// The sweep proposes duplicate groups; the resolver decides what each one is.
// It never removes a file: other programs file music into the library too,
// and a copy one of them filed is not Minstrel's to delete. Removing a copy
// is an admin's merge. What a pass does on its own changes only Minstrel's
// database:
//
// - On one album, a song is held once: the extra copies are merged into the
// best by ProposeSurvivor.
// - Across releases, each copy belongs to its own release (a single and its
// album): nothing is removed, and the copies are linked as one song. An
// album holding the song twice among them still holds it once: its extra
// copies are merged into its best.
// - Except that a video rip is no release's copy. When every copy but one is
// a rip, across releases or under another title, the rips are merged into
// the one that is not.
// - Copies of one song, on one album or across releases (a single and its
// album), are linked as one song: a like on one is a like on all, and
// the Liked list, shuffle and the mixes count the song once. A group an
// admin may want to thin (one album holding the song twice, or video rips
// beside a real copy) also waits for them.
// - A copy named like a video rip is held back from radio and the mixes.
// - Two versions of a song on one album that sound alike are not duplicates:
// the group is dismissed (duplicate_settle.go).
// - One file filling several of an album's track slots: MusicBrainz's track
// lengths say which slot it belongs to, or AcoustID which song it is when
// each copy was cut to its own slot's length, and the copies in the other
// slots are removed, leaving those slots missing (duplicate_settle.go).
// lengths, or AcoustID, say which song the recording is, and the group's
// note tells the admin who settles it (duplicate_settle.go).
// - Anything else waits for an admin.
const (
// resolveMergeCap bounds the merges one pass makes. The first pass after
// deploy meets the whole backlog; a cap spreads it over a few hours, each
// pass short.
resolveMergeCap = 200
// duplicateResolveTick is how often the worker runs a pass.
duplicateResolveTick = time.Hour
// scanWaitRetry is how soon a pass put off for a running scan is tried
@@ -55,15 +46,13 @@ const (
// DuplicateResolveResult tallies one pass.
type DuplicateResolveResult struct {
Groups int
Classes map[DuplicateClass]int
Merged int
MergeFailed int
// SongsLinked counts cross-release groups newly linked as one song.
Groups int
Classes map[DuplicateClass]int
// SongsLinked counts groups newly linked as one song.
SongsLinked int
// Dismissed counts groups of distinct versions dismissed; WrongFiles the
// copies removed from track slots that were not theirs.
Dismissed, WrongFiles int
// Dismissed counts groups of distinct versions dismissed; SlotsNamed the
// one-album mismatches whose recording the pass could name.
Dismissed, SlotsNamed int
// HeldBack counts tracks newly held back from radio and the mixes as video
// rips; Released counts held-back tracks whose name no longer says so.
HeldBack, Released int64
@@ -107,18 +96,17 @@ func (g *resolveGroup) lone() int {
return at
}
// mergePlan says whether the resolver may merge the group on its own, and into
// which copy (an index into members; -1 means ProposeSurvivor decides).
func mergePlan(g *resolveGroup) (ok bool, survivor int) {
// wantsAdmin says whether a group waits for an admin to decide which copies
// to keep: every group but distinct versions, and copies on separate
// releases with no rip among them, which are complete once linked.
func (g *resolveGroup) wantsAdmin() bool {
switch g.class {
case ClassSameRelease:
return true, -1
case ClassDistinct:
return false
case ClassCrossRelease:
if i := g.lone(); i >= 0 {
return true, i
}
return g.lone() >= 0
}
return false, -1
return true
}
// TrackListFetcher reads a release group's releases and track lists from
@@ -150,14 +138,14 @@ type ResolveSources struct {
// with it off, the pass only classifies. It decides from what the library and
// catalogue hold; ResolveDuplicatesWith may also ask MusicBrainz and AcoustID.
func ResolveDuplicates(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, act bool,
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, act bool,
) (DuplicateResolveResult, error) {
return ResolveDuplicatesWith(ctx, pool, logger, dataDir, act, ResolveSources{})
return ResolveDuplicatesWith(ctx, pool, logger, act, ResolveSources{})
}
// ResolveDuplicatesWith is ResolveDuplicates that may ask src.
func ResolveDuplicatesWith(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, act bool, src ResolveSources,
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, act bool, src ResolveSources,
) (DuplicateResolveResult, error) {
if logger == nil {
logger = slog.Default()
@@ -176,6 +164,9 @@ func ResolveDuplicatesWith(
g.classify()
res.Classes[g.class]++
}
if act {
res.SlotsNamed = nameWrongSlots(ctx, pool, logger, groups, src)
}
if err := writeResolveVerdicts(ctx, q, groups); err != nil {
return res, err
}
@@ -192,188 +183,30 @@ func ResolveDuplicatesWith(
return res, fmt.Errorf("release renamed tracks: %w", err)
}
// Merges before links, so a rip merged away is not linked first.
merged := map[pgtype.UUID]bool{}
var mergedNames []string
for _, g := range groups {
if res.Merged >= resolveMergeCap {
break
}
if ctx.Err() != nil {
return res, ctx.Err()
}
ok, survivor := mergePlan(g)
if !ok {
continue
}
if err := autoMerge(ctx, pool, logger, dataDir, g, survivor); err != nil {
res.MergeFailed++
logger.Warn("duplicate resolve: merge failed", "group_id", syncpkg.FormatUUID(g.id), "err", err)
continue
}
merged[g.id] = true
res.Merged++
if len(mergedNames) < notifyItems {
mergedNames = append(mergedNames, notifications.TrackLabel(g.members[0].ArtistName, g.members[0].Title))
}
}
folded, foldedNames := foldAlbumCopies(ctx, pool, logger, dataDir, groups, merged, resolveMergeCap-res.Merged)
res.Merged += folded
mergedNames = append(mergedNames, foldedNames...)
res.Dismissed = dismissDistinct(ctx, pool, logger, groups, merged)
wrong, names := settleWrongSlots(ctx, pool, logger, groups, merged, src)
res.WrongFiles = wrong
mergedNames = append(mergedNames, names...)
linked, err := linkCrossRelease(ctx, pool, logger, groups, merged)
settled := map[pgtype.UUID]bool{}
res.Dismissed = dismissDistinct(ctx, pool, logger, groups, settled)
linked, err := linkSongs(ctx, pool, logger, groups)
res.SongsLinked = linked
if err != nil {
return res, err
}
if settledCopies := res.Merged + res.WrongFiles; settledCopies > 0 {
notifyAdmins(ctx, notifications.KindDuplicatesResolved, notifications.Payload{
Count: int64(settledCopies), Items: mergedNames[:min(len(mergedNames), notifyItems)],
})
}
notifyNewForReview(ctx, groups, merged)
notifyNewForReview(ctx, groups, settled)
return res, nil
}
// foldAlbumCopies merges, in each cross-release group, the extra copies one
// album holds of the song into the best of that album's copies: the one that is
// not a video rip when only one is not, else ProposeSurvivor's choice. Copies
// whose title or file name name different versions (versionWords) are not
// folded, even when they carry one title tag: a song and its clean version are
// both kept. The copies on other releases stay and are linked as one song. At
// most budget copies go. It returns how many went and the songs they were, and
// drops them from their groups.
func foldAlbumCopies(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string,
groups []*resolveGroup, merged map[pgtype.UUID]bool, budget int,
) (int, []string) {
n := 0
var names []string
for _, g := range groups {
if g.class != ClassCrossRelease || merged[g.id] || ctx.Err() != nil || n >= budget {
continue
}
onAlbum := map[string][]int{}
for i, m := range g.members {
k := syncpkg.FormatUUID(m.AlbumID) + "\x00" + MatchTitleKey(m.Title, m.ArtistName) +
"\x00" + versionWords(m.Title, m.FilePath)
onAlbum[k] = append(onAlbum[k], i)
}
gone := map[int]bool{}
for _, copies := range onAlbum {
if len(copies) < 2 {
continue
}
keep, reason := albumCopySurvivor(g, copies)
for _, i := range copies {
if i == keep || n >= budget {
continue
}
if err := foldAlbumCopy(ctx, pool, logger, dataDir, g, i, keep, reason); err != nil {
logger.Warn("duplicate resolve: merging an album's extra copy failed",
"group_id", syncpkg.FormatUUID(g.id), "path", g.members[i].FilePath, "err", err)
continue
}
gone[i] = true
n++
if len(names) < notifyItems {
names = append(names, notifications.TrackLabel(g.members[i].ArtistName, g.members[i].Title))
}
}
}
if len(gone) > 0 {
kept := g.members[:0:0]
for i, m := range g.members {
if !gone[i] {
kept = append(kept, m)
}
}
g.members = kept
}
}
return n, names
}
// albumCopySurvivor picks which of one album's copies (indexes into the
// group's members) to keep, and why.
func albumCopySurvivor(g *resolveGroup, copies []int) (int, string) {
notRip := -1
for _, i := range copies {
if isRip(g.members[i]) {
continue
}
if notRip >= 0 {
notRip = -1
break
}
notRip = i
}
if notRip >= 0 {
return notRip, "the copy that is not a video rip"
}
all := survivorCandidates(g)
cands := make([]SurvivorCandidate, len(copies))
for j, i := range copies {
cands[j] = all[i]
}
id, reason := ProposeSurvivor(cands)
for _, i := range copies {
if all[i].TrackID == id {
return i, reason
}
}
return copies[0], reason
}
// foldAlbumCopy replaces one of an album's copies with the copy kept, history
// and all, and records it as the resolver's merge.
func foldAlbumCopy(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string,
g *resolveGroup, gone, keep int, reason string,
) error {
from, into := g.members[gone], g.members[keep]
moved, err := ReplaceTrack(ctx, pool, logger, dataDir, from.TrackID, into.TrackID)
if err != nil {
return err
}
audit.WriteOrLog(ctx, pool, logger, pgtype.UUID{}, pgtype.UUID{}, audit.ActionDuplicateMerge, map[string]any{
"automatic": true,
"group_id": syncpkg.FormatUUID(g.id),
"tier": g.tier,
"class": string(g.class),
"survivor_track_id": syncpkg.FormatUUID(into.TrackID),
"survivor_path": into.FilePath,
"survivor_reason": reason + "; the album held the song twice",
"removed": []map[string]string{
{"track_id": syncpkg.FormatUUID(from.TrackID), "file_path": from.FilePath},
},
"moved": map[string]any{
"play_events": moved.PlayEvents, "skip_events": moved.SkipEvents,
"likes": moved.Likes, "playlist_entries": moved.PlaylistEntries,
},
})
return nil
}
// linkCrossRelease links each cross-release group's copies as one song: a
// like on one is a like on all, and the Liked list, shuffle and the
// mixes count the song once. A group the pass merged has nothing left to link.
// Linking an already-linked group changes nothing,
// so this runs every pass; likes are shared only when a link is new, since a
// like made after it reaches every copy as it is made.
func linkCrossRelease(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, merged map[pgtype.UUID]bool,
// linkSongs links each group of one song's copies as one song: a like on
// one is a like on all, and the Liked list, shuffle and the mixes count the
// song once. That holds for copies on one album as for copies across
// releases; which copies to keep is the admin's merge. Linking an
// already-linked group changes nothing, so this runs every pass; likes are
// shared only when a link is new, since a like made after it reaches every
// copy as it is made.
func linkSongs(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup,
) (int, error) {
linked := 0
for _, g := range groups {
if g.class != ClassCrossRelease || merged[g.id] {
if g.class != ClassCrossRelease && g.class != ClassSameRelease {
continue
}
if ctx.Err() != nil {
@@ -450,10 +283,13 @@ func (g *resolveGroup) classify() {
// to say.
func resolveNote(g *resolveGroup) string {
switch g.class {
case ClassSameRelease:
return "The album holds this song more than once. The copies count as one song; merge to keep one."
case ClassCrossRelease:
if g.lone() < 0 {
return "Each copy belongs to its own release, so none is removed; they count as one song."
}
return "Every copy but one is named like a video rip. They count as one song; merge to keep the one that is not."
case ClassMismatch:
return "One recording fills several of this album's track slots, and MusicBrainz's track lengths could not say which is its own."
}
@@ -476,68 +312,10 @@ func writeResolveVerdicts(ctx context.Context, q *dbq.Queries, groups []*resolve
return nil
}
// survivorCandidates builds what ProposeSurvivor weighs for a group's copies.
func survivorCandidates(g *resolveGroup) []SurvivorCandidate {
cands := make([]SurvivorCandidate, len(g.members))
for i, m := range g.members {
cands[i] = SurvivorCandidate{
TrackID: syncpkg.FormatUUID(m.TrackID),
FileFormat: m.FileFormat,
FileSize: m.FileSize,
AddedAt: m.AddedAt.Time,
TagFit: TagFitScore(m.TrackNumber != nil, m.PositionClash, m.FilePath, m.HasMbid),
}
}
return cands
}
// autoMerge merges one group into the copy at index survivor, or the copy
// ProposeSurvivor picks when survivor is -1, and records the merge as the
// resolver's.
func autoMerge(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, dataDir string, g *resolveGroup, survivor int,
) error {
survivorKey, reason := ProposeSurvivor(survivorCandidates(g))
if survivor >= 0 {
survivorKey, reason = syncpkg.FormatUUID(g.members[survivor].TrackID), "the copy that is not a video rip"
}
var survivorID pgtype.UUID
if err := survivorID.Scan(survivorKey); err != nil {
return fmt.Errorf("parse survivor id: %w", err)
}
res, err := MergeDuplicateGroup(ctx, pool, logger, dataDir, g.id, survivorID)
if err != nil {
return err
}
if err := dbq.New(pool).MarkDuplicateGroupResolvedAutomatically(ctx, g.id); err != nil {
logger.Warn("duplicate resolve: marking the merge automatic failed", "group_id", syncpkg.FormatUUID(g.id), "err", err)
}
removed := make([]map[string]string, 0, len(res.Removed))
for _, c := range res.Removed {
removed = append(removed, map[string]string{"track_id": syncpkg.FormatUUID(c.TrackID), "file_path": c.FilePath})
}
audit.WriteOrLog(ctx, pool, logger, pgtype.UUID{}, pgtype.UUID{}, audit.ActionDuplicateMerge, map[string]any{
"automatic": true,
"group_id": syncpkg.FormatUUID(g.id),
"tier": res.Tier,
"class": string(g.class),
"survivor_track_id": syncpkg.FormatUUID(res.Survivor.TrackID),
"survivor_path": res.Survivor.FilePath,
"survivor_reason": reason,
"removed": removed,
"moved": map[string]any{
"play_events": res.PlayEvents, "skip_events": res.SkipEvents,
"likes": res.Likes, "playlist_entries": res.PlaylistEntries,
},
})
return nil
}
// DuplicateResolveWorker runs a resolver pass every hour.
type DuplicateResolveWorker struct {
pool *pgxpool.Pool
logger *slog.Logger
dataDir string
settings *FingerprintSettingsService
src ResolveSources
tick time.Duration
@@ -546,10 +324,10 @@ type DuplicateResolveWorker struct {
// NewDuplicateResolveWorker builds a worker with the production cadence. src
// is what a pass may ask beyond the library.
func NewDuplicateResolveWorker(
pool *pgxpool.Pool, logger *slog.Logger, dataDir string, settings *FingerprintSettingsService, src ResolveSources,
pool *pgxpool.Pool, logger *slog.Logger, settings *FingerprintSettingsService, src ResolveSources,
) *DuplicateResolveWorker {
return &DuplicateResolveWorker{
pool: pool, logger: logger, dataDir: dataDir, settings: settings, src: src, tick: duplicateResolveTick,
pool: pool, logger: logger, settings: settings, src: src, tick: duplicateResolveTick,
}
}
@@ -606,19 +384,19 @@ func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool
return true
}
// A run can begin after the check above, and a watcher batch has no run
// at all: filesGate keeps either from reading files while this pass
// removes them.
// at all: filesGate keeps either from rewriting tracks while this pass
// decides from them.
if !filesGate.tryAcquire() {
return true
}
defer filesGate.release()
res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.dataDir, w.settings.Get().AutoResolve, w.src)
res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.settings.Get().AutoResolve, w.src)
if err != nil && ctx.Err() == nil {
w.logger.Warn("duplicate resolve: pass failed", "err", err)
}
w.logger.Info("duplicate resolve complete",
"groups", res.Groups, "merged", res.Merged, "merge_failed", res.MergeFailed,
"songs_linked", res.SongsLinked, "dismissed", res.Dismissed, "wrong_files", res.WrongFiles,
"groups", res.Groups, "songs_linked", res.SongsLinked, "dismissed", res.Dismissed,
"slots_named", res.SlotsNamed,
"held_back", res.HeldBack, "released", res.Released)
return false
}
+137 -94
View File
@@ -6,6 +6,7 @@ import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgtype"
@@ -95,39 +96,39 @@ func autoMergeAudit(t *testing.T, pool *pgxpool.Pool, groupID pgtype.UUID) (n in
return n, reason
}
// One album holding a song twice: the extra copy goes, the copy whose name and
// tags fit the album stays, and the merge is recorded as the resolver's:
// Minstrel is the only program writing the library.
func TestResolveDuplicates_MergesASameReleaseCopy_Integration(t *testing.T) {
// 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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatalf("resolve: %v", err)
}
if res.Merged != 1 || res.Classes[ClassSameRelease] != 1 {
t.Fatalf("result = %+v, want the same-release group merged", res)
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 only the clean copy left", exists(f.ripPath), exists(f.cleanPath))
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, _, auto := f.group(t)
if status != "merged" || class == nil || *class != string(ClassSameRelease) || !auto {
t.Errorf("group = (%s, %v, auto=%v), want merged same_release by the resolver", status, class, auto)
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 != 1 {
t.Errorf("automatic merge audit rows = %d, want 1", n)
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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, false)
if err != nil {
t.Fatal(err)
}
if res.Merged != 0 || !exists(f.ripPath) {
t.Errorf("merged %d", res.Merged)
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) {
@@ -193,22 +194,26 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
return f
}
// A video rip on one release with the clean copy on another: the rip is no
// release's copy, so it goes and the album cut stays.
func TestResolveDuplicates_MergesARipAcrossReleases_Integration(t *testing.T) {
// 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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.Merged != 1 {
t.Fatalf("classes %v, merged %d; want the cross-release group merged", res.Classes, res.Merged)
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 only the clean copy", exists(f.ripPath), exists(f.cleanPath))
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 _, reason := autoMergeAudit(t, f.pool, f.groupID); reason != "the copy that is not a video rip" {
t.Errorf("survivor reason %q, want the rip rule", reason)
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)
}
}
@@ -231,12 +236,12 @@ func TestResolveDuplicates_KeepsCleanCopiesOnTwoReleases_Integration(t *testing.
if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Merged != 0 || !exists(f.ripPath) {
t.Errorf("merged %d; want both copies kept", res.Merged)
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)
@@ -258,12 +263,12 @@ func TestResolveDuplicates_LinksOneRecordingUnderTwoTitles_Integration(t *testin
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)
res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Classes[ClassCrossRelease] != 1 || res.Merged != 0 || res.SongsLinked != 1 {
t.Fatalf("classes %v, merged %d, linked %d; want the pair linked and kept", res.Classes, res.Merged, res.SongsLinked)
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)
}
}
@@ -333,11 +338,11 @@ func auditCount(t *testing.T, pool *pgxpool.Pool, action string, groupID pgtype.
// 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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Dismissed != 1 || res.Merged != 0 || !exists(f.aPath) || !exists(f.bPath) {
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 {
@@ -378,10 +383,32 @@ func seedTrackList(t *testing.T, pool *pgxpool.Pool, album dbq.Album, songs map[
}
}
// 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, so the copy in Reach's slot goes. Its
// track stays, marked missing, until a good copy arrives.
func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testing.T) {
// 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.
@@ -389,18 +416,25 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi
`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)
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 res.WrongFiles != 1 || !exists(f.aPath) || exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want only Reach's copy removed",
res, exists(f.aPath), exists(f.bPath))
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(),
@@ -410,8 +444,8 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi
if !missing {
t.Error("Reach's track is not marked missing, so nothing will fetch it again")
}
if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" || !auto {
t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto)
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)
@@ -446,9 +480,8 @@ func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *tes
}
}
held("17 - Reach (other edition).m4a", tc.heldMs)
res, err := ResolveDuplicates(ctx, f.pool, nil, "", true)
if err != nil || res.WrongFiles != 1 {
t.Fatalf("resolve = %+v, %v; want Reach's slot emptied", res, err)
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 {
@@ -466,23 +499,24 @@ func TestResolveDuplicates_EmptiedSlotFoldsOnlyIntoItsOwnSong_Integration(t *tes
}
// One recording filling two slots whose songs are both clearly something else
// (Shnorkelbub's whole album in one file): both copies go, nothing is kept.
func TestResolveDuplicates_RemovesEveryCopyWhenNoSlotIsTheirs_Integration(t *testing.T) {
// (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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want both copies removed",
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 status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" || !auto {
t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto)
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 n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 {
t.Errorf("wrong-file audit rows = %d, want 1", n)
if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending for an admin", status)
}
}
@@ -502,9 +536,9 @@ func seedTrimmedAlbum(t *testing.T) oneAlbumFixture {
return f
}
// AcoustID matched one copy to Tormentor's recording: that copy stays and
// Record Shop's goes.
func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) {
// 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')`,
@@ -512,7 +546,7 @@ func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) {
t.Fatal(err)
}
asked := 0
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil },
})
if err != nil {
@@ -521,10 +555,13 @@ func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) {
if asked != 0 {
t.Errorf("AcoustID asked %d times; the copy's own lookup already answered", asked)
}
if res.WrongFiles != 1 || !exists(f.aPath) || exists(f.bPath) {
t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want only Record Shop's copy removed",
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
@@ -552,39 +589,43 @@ func TestResolveDuplicates_AgreeingLookupsDecideAnAcousticGroup_Integration(t *t
f.a.ID, f.b.ID); err != nil {
t.Fatal(err)
}
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.WrongFiles != 1 || exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want only Tormentor's copy removed",
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{
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.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("asked %d, result %+v; want nothing asked or removed for copies that may be two takes", asked, res)
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 copy removed
// under the walk is marked present again when the scan reconciles. A run
// stuck past StuckScanThreshold does not hold the resolver up. Files being
// 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{})
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)
}
@@ -617,13 +658,13 @@ func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) {
}
}
// AcoustID knows the recording as no song of the album: every copy goes. With
// AcoustID unreachable, nothing is decided and the group waits.
// 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{
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{
Identify: func(context.Context, string) ([]string, error) {
asked++
return []string{"rec-elsewhere"}, nil
@@ -632,23 +673,26 @@ func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testin
if err != nil {
t.Fatal(err)
}
if asked != 1 || res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) {
t.Fatalf("asked %d, result %+v; want one lookup and both copies removed", asked, res)
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 status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" {
t.Errorf("group = %s, want settled", status)
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{
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.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v; want nothing removed while AcoustID cannot answer", res)
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)
@@ -674,17 +718,17 @@ func TestResolveDuplicates_FetchesAMissingTrackList_Integration(t *testing.T) {
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})
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: fetch})
if err != nil {
t.Fatal(err)
}
if calls != 1 || res.WrongFiles != 1 || exists(f.bPath) {
t.Fatalf("fetches %d, result %+v; want one fetch and Reach's copy removed", calls, res)
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 removes nothing it can't decide without the list.
// 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(),
@@ -696,24 +740,24 @@ func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) {
calls++
return ErrLookupOff
}
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, "", true, ResolveSources{TrackLists: off})
res, err := ResolveDuplicatesWith(context.Background(), f.pool, nil, true, ResolveSources{TrackLists: off})
if err != nil {
t.Fatal(err)
}
if calls != 1 || res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) {
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 removed.
// 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)
res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) {
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" ||
@@ -728,8 +772,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(t)
ctx := context.Background()
q := dbq.New(f.pool)
// Without its group the rip has no clean copy to merge into, so it stays
// on disk and only its verdict changes.
// 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)
}
@@ -743,7 +786,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) {
}
resolve := func() DuplicateResolveResult {
t.Helper()
res, err := ResolveDuplicates(ctx, f.pool, nil, "", true)
res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil {
t.Fatal(err)
}
+35 -38
View File
@@ -78,8 +78,7 @@ type slotCopy struct {
// Several copies may fit when they carry the same title ("Killjoy" twice
// beside "Dreamland"): they are one song held twice, not a wrong slot, so they
// are neither kept nor lost here. Once the wrong slot is emptied, the next
// sweep finds the pair on its own, and the resolver merges it as any song held
// twice on one album.
// sweep finds the pair on its own, as any song held twice on one album.
func wrongSlots(copies []slotCopy, tracks []dbq.MbReleaseTrack) (keep int, losers []int, ok bool) {
keep = -1
keepKey := ""
@@ -164,14 +163,12 @@ func dismissDistinct(
return n
}
// settleWrongSlots removes the copies that sit in another song's slot, for
// every one-album mismatch the track list, or AcoustID with it, decides. It
// returns how many copies went and the songs whose slots were emptied, and
// adds the groups it settled to settled.
func settleWrongSlots(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, settled map[pgtype.UUID]bool,
src ResolveSources,
) (int, []string) {
// nameWrongSlots says, in the note of every one-album mismatch the track list
// or AcoustID decides, which song the recording is, so the admin settling it
// (SettleWrongSlot) need not work it out. It returns how many it named.
func nameWrongSlots(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, src ResolveSources,
) int {
q := dbq.New(pool)
tracksByGroup := map[string][]dbq.MbReleaseTrack{}
fetches, identifies := trackListFetchesPerPass, identifiesPerPass
@@ -181,10 +178,9 @@ func settleWrongSlots(
if src.Identify == nil {
identifies = 0
}
removed := 0
var names []string
named := 0
for _, g := range groups {
if g.class != ClassMismatch || settled[g.id] || ctx.Err() != nil {
if g.class != ClassMismatch || ctx.Err() != nil {
continue
}
rg := g.members[0].ReleaseGroupMbid
@@ -218,13 +214,15 @@ func settleWrongSlots(
for i, m := range g.members {
copies[i] = slotCopy{Title: m.Title, Artist: m.ArtistName, DurationMs: m.DurationMs}
}
keep, losers, ok := wrongSlots(copies, tracks)
source := "MusicBrainz's track lengths say"
keep, _, ok := wrongSlots(copies, tracks)
if !ok {
recordings, known := groupRecordings(ctx, logger, g, src.Identify, &identifies)
if !known {
continue
}
if keep, losers, ok = namedCopies(copies, tracks, recordings); !ok {
source = "AcoustID says"
if keep, _, ok = namedCopies(copies, tracks, recordings); !ok {
logger.Info("duplicate resolve: AcoustID's answer does not place the recording in one slot; left for review",
"group_id", syncpkg.FormatUUID(g.id), "recordings", recordings)
}
@@ -232,19 +230,20 @@ func settleWrongSlots(
if !ok {
continue
}
emptied := emptiedSlots(ctx, q, logger, g, losers, tracks)
n, err := removeWrongSlots(ctx, pool, logger, g, keep, losers, emptied, pgtype.UUID{})
removed += n
if err != nil {
logger.Warn("duplicate resolve: removing wrong-slot copies failed", "group_id", syncpkg.FormatUUID(g.id), "err", err)
continue
}
settled[g.id] = true
for _, i := range losers {
names = append(names, notifications.TrackLabel(g.members[i].ArtistName, g.members[i].Title))
}
g.note = wrongSlotNote(source, g, keep)
named++
}
return removed, names
return named
}
// wrongSlotNote is what a mismatch's note says once the pass knows which song
// the recording is: the copy at keep, or none of them when keep is -1.
func wrongSlotNote(source string, g *resolveGroup, keep int) string {
if keep < 0 {
return source + " this recording is none of these songs. Settle it to empty the slots it fills."
}
return source + " this recording is \u201c" + g.members[keep].Title +
"\u201d. Settle it with that copy to empty the slots that are not its own."
}
// ErrNotWrongSlot means a group is not one recording filling several of an
@@ -261,13 +260,13 @@ type WrongSlotResult struct {
// SettleWrongSlot settles a one-album mismatch the resolver left for the
// admin, with their answer in place of MusicBrainz's lengths and
// AcoustID's. keepID is the copy whose title they say the recording is; an
// invalid id means they cannot say, and every copy goes. Either way it is the
// resolver's own path: the copies removed are marked missing, and their slots
// wait for a good copy. A merge does none of that, and keeps one copy's title
// whether or not it is the audio's.
// invalid id means they cannot say, and every copy goes. Either way the copies
// removed are marked missing, and their slots wait for a good copy. A merge
// does none of that, and keeps one copy's title whether or not it is the
// audio's.
//
// Copies sharing the kept copy's title are one song held twice and stay, as in
// wrongSlots: the next sweep finds the pair and the resolver merges it.
// wrongSlots: the next sweep finds the pair, for an admin to merge.
func SettleWrongSlot(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groupID, keepID, actorID pgtype.UUID,
) (WrongSlotResult, error) {
@@ -548,16 +547,14 @@ func removeWrongSlots(
}
// notifyNewForReview tells admins about groups this pass classified for the
// first time and left for them. A group the resolver settled, linked or will
// link is not news, and would bury the groups that need them.
// first time and left for them. A group that needs no one (distinct versions
// dismissed, or copies on separate releases that count as one song) is not
// news, and would bury the groups that need them.
func notifyNewForReview(ctx context.Context, groups []*resolveGroup, settled map[pgtype.UUID]bool) {
var count int64
var items []string
for _, g := range groups {
if g.members[0].PriorClass != nil || settled[g.id] {
continue
}
if g.class != ClassReview && g.class != ClassMismatch {
if g.members[0].PriorClass != nil || settled[g.id] || !g.wantsAdmin() {
continue
}
count++
+1 -1
View File
@@ -21,7 +21,7 @@ func undecidedSlot(t *testing.T) (oneAlbumFixture, dbq.User) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
ctx := context.Background()
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000})
if res, err := ResolveDuplicates(ctx, f.pool, nil, "", true); err != nil || res.WrongFiles != 0 {
if res, err := ResolveDuplicates(ctx, f.pool, nil, true); err != nil || res.SlotsNamed != 0 {
t.Fatalf("resolve = %+v, %v; want the group left for the operator", res, err)
}
name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name())
+30 -1
View File
@@ -1,6 +1,8 @@
package library
import (
"path/filepath"
"regexp"
"sort"
"strings"
"time"
@@ -23,12 +25,18 @@ type SurvivorCandidate struct {
// - it has a track number that no other track on its album also claims
// - its file name carries no video-rip marker (SourceMarkersFor)
// - it has a MusicBrainz recording id
// - it sits in a folder named for its album (inAlbumFolder), as a tagger or
// download manager files it, rather than loose beside the artist's other
// songs
//
// Two copies of one song differ in these far more often than in anything a
// listener hears: rips of one song can differ by a few bytes, which makes file
// size a poor guide.
func TagFitScore(hasTrackNumber, positionClash bool, filePath string, hasMBID bool) int {
func TagFitScore(hasTrackNumber, positionClash bool, filePath, albumTitle string, hasMBID bool) int {
score := 0
if inAlbumFolder(filePath, albumTitle) {
score++
}
if hasTrackNumber && !positionClash {
score++
}
@@ -41,6 +49,27 @@ func TagFitScore(hasTrackNumber, positionClash bool, filePath string, hasMBID bo
return score
}
// discFolder is a folder holding one medium of an album ("CD 01", "Disc 2").
var discFolder = regexp.MustCompile(`(?i)^(cd|disc|disk)\s*\d+$`)
// folderYear is a release year at the end of an album folder's name.
var folderYear = regexp.MustCompile(`\s*[(\[]\d{4}[)\]]\s*$`)
// inAlbumFolder reports whether a file sits in a folder named for its album,
// "Album (Year)" or that folder's "CD nn" medium folder. Letters and digits
// alone are compared, since a filer drops characters a path cannot hold.
func inAlbumFolder(filePath, albumTitle string) bool {
want := normalizeTitle(albumTitle)
if want == "" {
return false
}
dir := filepath.Dir(filePath)
if discFolder.MatchString(filepath.Base(dir)) {
dir = filepath.Dir(dir)
}
return normalizeTitle(folderYear.ReplaceAllString(filepath.Base(dir), "")) == want
}
// losslessFormats are the scanned extensions that are lossless by definition.
// m4a is left out on purpose: it holds either ALAC or AAC, and the scanner
// records only the extension, so calling it lossless would sometimes prefer an
+26 -6
View File
@@ -148,15 +148,35 @@ func TestTagFitScore(t *testing.T) {
hasMBID bool
want int
}{
{"clean, numbered, identified", true, false, "/music/A/B/A - B - 01 - Song.flac", true, 3},
{"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 2},
{"no track number", false, false, "/music/A/B/Song.flac", true, 2},
{"video rip", true, false, "/music/A/B/A - B - 01 - Song (Official Video).mp3", true, 2},
{"rip with nothing else", false, false, "/music/A/B/Song (Official Video).mp3", false, 0},
{"filed, numbered, identified", true, false, "/music/A/B (2001)/A - B - 01 - Song.flac", true, 4},
{"filed on a medium of the album", true, false, "/music/A/B (2001)/CD 02/A - B - 01 - Song.flac", true, 4},
{"loose in the artist's folder", true, false, "/music/A/A - Song.flac", true, 3},
{"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 3},
{"no track number", false, false, "/music/A/B/Song.flac", true, 3},
{"video rip", true, false, "/music/A/B/A - B - 01 - Song (Official Video).mp3", true, 3},
{"loose rip with nothing else", false, false, "/music/A/Song (Official Video).mp3", false, 0},
}
for _, tc := range cases {
if got := TagFitScore(tc.hasTrackNumber, tc.clash, tc.path, tc.hasMBID); got != tc.want {
if got := TagFitScore(tc.hasTrackNumber, tc.clash, tc.path, "B", tc.hasMBID); got != tc.want {
t.Errorf("%s: TagFitScore = %d, want %d", tc.name, got, tc.want)
}
}
}
// A copy a filer put in its album's folder is proposed over a loose copy of
// the same audio in the artist's folder, though the loose one is larger and
// older: size and age decide only between copies that fit equally.
func TestProposeSurvivor_PrefersTheCopyFiledInItsAlbumFolder(t *testing.T) {
old := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
filed := SurvivorCandidate{
TrackID: "filed", FileFormat: "flac", FileSize: 30_000_000, AddedAt: old.AddDate(5, 0, 0),
TagFit: TagFitScore(true, false, "/music/Tin Orchard/Dusk (2019)/Tin Orchard - Dusk - 01 - Dusk.flac", "Dusk", true),
}
loose := SurvivorCandidate{
TrackID: "loose", FileFormat: "flac", FileSize: 31_000_000, AddedAt: old,
TagFit: TagFitScore(true, false, "/music/Tin Orchard/01 Dusk.flac", "Dusk", true),
}
if id, reason := ProposeSurvivor([]SurvivorCandidate{loose, filed}); id != "filed" || reason != "tags fit the album" {
t.Errorf("ProposeSurvivor = (%q, %q), want the filed copy for its fit", id, reason)
}
}
+8 -9
View File
@@ -6,12 +6,12 @@ import (
"time"
)
// filesGate keeps reading the library's files apart from removing them. A
// full scan holds it for its whole length and the watcher for each batch;
// a duplicate-resolver pass, which removes the copies it merges, runs only
// while no one else holds it. Without it, a file a scan has listed could be
// removed under the scan, and a file read just before its removal would put
// back a track whose file is gone.
// filesGate keeps a library scan and a duplicate-resolver pass from running
// at once. A full scan holds it for its whole length and the watcher for each
// batch; a resolver pass runs only while no one else holds it. The scan
// rewrites tracks from the files it reads, and the pass decides from those
// tracks which copies are one song: run together, the pass would decide from
// a library half-read.
//
// A scan that starts during a resolver pass waits for the pass to finish,
// up to filesWaitLimit. A resolver pass that finds the gate taken is put off
@@ -19,9 +19,8 @@ import (
var filesGate = make(gate, 1)
// filesWaitLimit is how long a scan waits for a resolver pass to let go of
// the files. A pass is capped at resolveMergeCap merges and takes minutes;
// one still holding them after this long is stuck, and the scan gives up
// rather than wait forever.
// the files. A pass takes minutes; one still holding them after this long is
// stuck, and the scan gives up rather than wait forever.
const filesWaitLimit = 30 * time.Minute
// errFilesBusy is a scan giving up on a resolver pass that held the files
+2 -2
View File
@@ -50,8 +50,8 @@ func TestGate_OneHolderAndAWaiterThatCanGiveUp(t *testing.T) {
}
// A scan that starts while a duplicate-resolver pass holds the files reads
// none of them until the pass lets go, so no file it lists is removed under
// it.
// none of them until the pass lets go, so the pass never decides from a
// library half-read.
func TestScanner_WaitsForAPassHoldingTheFiles_Integration(t *testing.T) {
ctx := context.Background()
pool := dbtest.Open(t)
+2 -2
View File
@@ -186,7 +186,7 @@ func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) {
t.Fatal(err)
}
if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil {
if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil {
t.Fatal(err)
}
got := unreadNotices(t, pool, admin)
@@ -198,7 +198,7 @@ func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) {
if _, err := q.MarkAllNotificationsRead(ctx, dbq.MarkAllNotificationsReadParams{UserID: admin.ID}); err != nil {
t.Fatal(err)
}
if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil {
if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil {
t.Fatal(err)
}
if got := unreadNotices(t, pool, admin); len(got) != 0 {
+15 -15
View File
@@ -80,7 +80,7 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) {
q := dbq.New(pool)
f := newSongLinkFixture(t, pool)
res, err := ResolveDuplicates(ctx, pool, nil, "", true)
res, err := ResolveDuplicates(ctx, pool, nil, true)
if err != nil {
t.Fatal(err)
}
@@ -111,7 +111,7 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) {
}
// A second pass changes nothing.
if res, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil || res.SongsLinked != 0 {
if res, err := ResolveDuplicates(ctx, pool, nil, true); err != nil || res.SongsLinked != 0 {
t.Errorf("second pass linked %d (%v), want 0", res.SongsLinked, err)
}
@@ -148,7 +148,7 @@ func TestCrossReleaseLinkNeedsAutoResolve_Integration(t *testing.T) {
ctx := context.Background()
q := dbq.New(pool)
f := newSongLinkFixture(t, pool)
if _, err := ResolveDuplicates(ctx, pool, nil, "", false); err != nil {
if _, err := ResolveDuplicates(ctx, pool, nil, false); err != nil {
t.Fatal(err)
}
keys := songKeys(t, q, f.single.ID, f.albumCut.ID)
@@ -213,10 +213,10 @@ func songKeys(t *testing.T, q *dbq.Queries, ids ...pgtype.UUID) []pgtype.UUID {
}
// A cross-release group whose album holds the song twice (Mammalz: Neptunez
// Barz as a FLAC and a YouTube mp3, beside the single): the album's
// extra copy is merged into its FLAC, the single stays, and the two copies
// left are linked as one song.
func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integration(t *testing.T) {
// Barz as a FLAC and an mp3, beside the single): every file stays, since
// another program may have filed any of them, and all three count as one
// song. Thinning the album's copies is an admin's merge.
func TestResolveDuplicates_KeepsEveryCopyInACrossReleaseGroup_Integration(t *testing.T) {
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
@@ -267,18 +267,18 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio
t.Fatal(err)
}
res, err := ResolveDuplicates(ctx, pool, nil, "", true)
res, err := ResolveDuplicates(ctx, pool, nil, true)
if err != nil {
t.Fatal(err)
}
if res.Merged != 1 || exists(mp3.FilePath) || !exists(flac.FilePath) || !exists(single.FilePath) {
t.Fatalf("result %+v, mp3 %v flac %v single %v; want only the album's mp3 merged away",
res, exists(mp3.FilePath), exists(flac.FilePath), exists(single.FilePath))
}
if _, err := q.GetTrackByID(ctx, mp3.ID); err == nil {
t.Error("the album's extra copy is still a track")
if !exists(mp3.FilePath) || !exists(flac.FilePath) || !exists(single.FilePath) {
t.Fatalf("mp3 %v flac %v single %v; want every file left in place",
exists(mp3.FilePath), exists(flac.FilePath), exists(single.FilePath))
}
if res.SongsLinked != 1 {
t.Errorf("songs linked = %d, want the FLAC and the single linked as one song", res.SongsLinked)
t.Errorf("songs linked = %d, want the group linked as one song", res.SongsLinked)
}
if keys := songKeys(t, q, flac.ID, mp3.ID, single.ID); keys[0] != keys[1] || keys[1] != keys[2] {
t.Errorf("song keys %v, want all three copies one song", keys)
}
}
+3 -2
View File
@@ -21,8 +21,9 @@ const (
KindScanFailed Kind = "scan_failed"
KindTracksMissing Kind = "tracks_missing"
KindDuplicatesFound Kind = "duplicates_found"
// KindDuplicatesResolved: the duplicate resolver merged copies on its
// own. This is how an automatic merge stays visible.
// KindDuplicatesResolved: copies merged without an admin. The resolver no
// longer removes files, so nothing sends it; it stays so notices already
// in an inbox still render.
KindDuplicatesResolved Kind = "duplicates_resolved"
KindPlaybackErrors Kind = "playback_errors"
)
@@ -70,7 +70,7 @@
<SettingRow
label="Resolve duplicates automatically"
for="fp-auto"
hint="Merges clear cases into the best copy. Off, every group waits for you."
hint="Counts copies of one song once and sets aside distinct versions. Files are removed only when you merge. Off, every group waits for you."
>
<input id="fp-auto" type="checkbox" role="switch" aria-checked={f.form.auto_resolve} bind:checked={f.form.auto_resolve} class="h-4 w-4 cursor-pointer accent-accent" />
</SettingRow>
@@ -27,12 +27,12 @@
import ListContinuation from '#lib/components/ListContinuation.svelte';
import TabStrip from '#lib/components/TabStrip.svelte';
// Tracks the duplicate sweep believes hold one recording. The
// resolver settles what is safe on its own: a song held twice on
// one album, and a video rip with a clean copy elsewhere. What is left comes
// in two tabs: groups that need an admin, and the same song on different
// releases, which is kept on purpose. A third tab lists what the resolver
// did.
// Tracks the duplicate sweep believes hold one recording. The resolver
// never removes a file on its own, since other programs file music into the
// library too: it links copies of one song so they count once, and dismisses
// distinct versions. Groups come in two tabs: those that need an admin, and
// the same song on different releases, which is kept on purpose. A third tab
// lists what the resolver settled.
//
// Dismissing a group says "these are not duplicates", and the sweep will not
// propose that set again. On the cross-release tab it reads "Not the same
@@ -43,9 +43,10 @@
// Except for one recording filling several of an album's slots (class
// mismatch), where a merge is the wrong answer: it keeps one copy's
// title whether or not it is the audio's. There an admin says which song the
// recording is, or that they can't tell, and the group settles as the
// resolver would have: copies in other songs' slots are removed, and those
// tracks wait in Needs a file until a good copy is in the library folder.
// recording is (the group's note says when MusicBrainz or AcoustID could
// tell), or that they can't tell: copies in other songs' slots are removed,
// and those tracks wait in Needs a file until a good copy is in the library
// folder.
type Tab = DuplicatesView | 'resolved';
const fromUrl = page.url.searchParams.get('view');