fix(library): the duplicate resolver never removes a file on its own (#8252)
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

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>
This commit is contained in:
2026-11-30 21:09:11 -05:00
co-authored by Claude Opus 5.5
parent 63af193b13
commit 677a421675
16 changed files with 330 additions and 462 deletions
+1 -1
View File
@@ -75,7 +75,7 @@ ListenBrainz, email, metadata sources and recommendation tuning are set in the w
## Setup pitfalls ## 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. - **`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). - **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 // catalogue for the track list of an album whose wrong slot it must
// decide, a few a pass. See internal/library/duplicate_resolve.go. // decide, a few a pass. See internal/library/duplicate_resolve.go.
go library.NewDuplicateResolveWorker(pool, logger.With("component", "duplicate_resolve"), 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 { TrackLists: func(ctx context.Context, releaseGroupMBID string) error {
if !lookupSettings.Get().MusicBrainzTrackLists { if !lookupSettings.Get().MusicBrainzTrackLists {
return library.ErrLookupOff return library.ErrLookupOff
+1 -1
View File
@@ -300,7 +300,7 @@ func foldDuplicateGroups(rows []dbq.ListPendingDuplicateGroupMembersRow) []dupli
}) })
candidates[n] = append(candidates[n], library.SurvivorCandidate{ candidates[n] = append(candidates[n], library.SurvivorCandidate{
TrackID: trackID, FileFormat: row.FileFormat, FileSize: row.FileSize, AddedAt: row.AddedAt.Time, 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 { for i := range groups {
+57 -279
View File
@@ -11,41 +11,32 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool" "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/db/dbq"
"github.com/Fabled-Sword/minstrel/internal/notifications"
syncpkg "github.com/Fabled-Sword/minstrel/internal/sync" syncpkg "github.com/Fabled-Sword/minstrel/internal/sync"
) )
// Duplicate resolver. // Duplicate resolver.
// //
// The sweep proposes duplicate groups; the resolver decides what each one is // 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 // It never removes a file: other programs file music into the library too,
// only program writing the library, so no copy is kept because something else // and a copy one of them filed is not Minstrel's to delete. Removing a copy
// depends on it. What decides is what the copies are: // 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 // - Copies of one song, on one album or across releases (a single and its
// best by ProposeSurvivor. // album), are linked as one song: a like on one is a like on all, and
// - Across releases, each copy belongs to its own release (a single and its // the Liked list, shuffle and the mixes count the song once. A group an
// album): nothing is removed, and the copies are linked as one song. An // admin may want to thin (one album holding the song twice, or video rips
// album holding the song twice among them still holds it once: its extra // beside a real copy) also waits for them.
// copies are merged into its best. // - A copy named like a video rip is held back from radio and the mixes.
// - 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.
// - Two versions of a song on one album that sound alike are not duplicates: // - Two versions of a song on one album that sound alike are not duplicates:
// the group is dismissed (duplicate_settle.go). // the group is dismissed (duplicate_settle.go).
// - One file filling several of an album's track slots: MusicBrainz's track // - 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 // lengths, or AcoustID, say which song the recording is, and the group's
// each copy was cut to its own slot's length, and the copies in the other // note tells the admin who settles it (duplicate_settle.go).
// slots are removed, leaving those slots missing (duplicate_settle.go).
// - Anything else waits for an admin. // - Anything else waits for an admin.
const ( 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 is how often the worker runs a pass.
duplicateResolveTick = time.Hour duplicateResolveTick = time.Hour
// scanWaitRetry is how soon a pass put off for a running scan is tried // scanWaitRetry is how soon a pass put off for a running scan is tried
@@ -55,15 +46,13 @@ const (
// DuplicateResolveResult tallies one pass. // DuplicateResolveResult tallies one pass.
type DuplicateResolveResult struct { type DuplicateResolveResult struct {
Groups int Groups int
Classes map[DuplicateClass]int Classes map[DuplicateClass]int
Merged int // SongsLinked counts groups newly linked as one song.
MergeFailed int
// SongsLinked counts cross-release groups newly linked as one song.
SongsLinked int SongsLinked int
// Dismissed counts groups of distinct versions dismissed; WrongFiles the // Dismissed counts groups of distinct versions dismissed; SlotsNamed the
// copies removed from track slots that were not theirs. // one-album mismatches whose recording the pass could name.
Dismissed, WrongFiles int Dismissed, SlotsNamed int
// HeldBack counts tracks newly held back from radio and the mixes as video // 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. // rips; Released counts held-back tracks whose name no longer says so.
HeldBack, Released int64 HeldBack, Released int64
@@ -107,18 +96,17 @@ func (g *resolveGroup) lone() int {
return at return at
} }
// mergePlan says whether the resolver may merge the group on its own, and into // wantsAdmin says whether a group waits for an admin to decide which copies
// which copy (an index into members; -1 means ProposeSurvivor decides). // to keep: every group but distinct versions, and copies on separate
func mergePlan(g *resolveGroup) (ok bool, survivor int) { // releases with no rip among them, which are complete once linked.
func (g *resolveGroup) wantsAdmin() bool {
switch g.class { switch g.class {
case ClassSameRelease: case ClassDistinct:
return true, -1 return false
case ClassCrossRelease: case ClassCrossRelease:
if i := g.lone(); i >= 0 { return g.lone() >= 0
return true, i
}
} }
return false, -1 return true
} }
// TrackListFetcher reads a release group's releases and track lists from // 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 // with it off, the pass only classifies. It decides from what the library and
// catalogue hold; ResolveDuplicatesWith may also ask MusicBrainz and AcoustID. // catalogue hold; ResolveDuplicatesWith may also ask MusicBrainz and AcoustID.
func ResolveDuplicates( 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) { ) (DuplicateResolveResult, error) {
return ResolveDuplicatesWith(ctx, pool, logger, dataDir, act, ResolveSources{}) return ResolveDuplicatesWith(ctx, pool, logger, act, ResolveSources{})
} }
// ResolveDuplicatesWith is ResolveDuplicates that may ask src. // ResolveDuplicatesWith is ResolveDuplicates that may ask src.
func ResolveDuplicatesWith( 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) { ) (DuplicateResolveResult, error) {
if logger == nil { if logger == nil {
logger = slog.Default() logger = slog.Default()
@@ -176,6 +164,9 @@ func ResolveDuplicatesWith(
g.classify() g.classify()
res.Classes[g.class]++ res.Classes[g.class]++
} }
if act {
res.SlotsNamed = nameWrongSlots(ctx, pool, logger, groups, src)
}
if err := writeResolveVerdicts(ctx, q, groups); err != nil { if err := writeResolveVerdicts(ctx, q, groups); err != nil {
return res, err return res, err
} }
@@ -192,188 +183,30 @@ func ResolveDuplicatesWith(
return res, fmt.Errorf("release renamed tracks: %w", err) return res, fmt.Errorf("release renamed tracks: %w", err)
} }
// Merges before links, so a rip merged away is not linked first. settled := map[pgtype.UUID]bool{}
merged := map[pgtype.UUID]bool{} res.Dismissed = dismissDistinct(ctx, pool, logger, groups, settled)
var mergedNames []string linked, err := linkSongs(ctx, pool, logger, groups)
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)
res.SongsLinked = linked res.SongsLinked = linked
if err != nil { if err != nil {
return res, err return res, err
} }
notifyNewForReview(ctx, groups, settled)
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)
return res, nil return res, nil
} }
// foldAlbumCopies merges, in each cross-release group, the extra copies one // linkSongs links each group of one song's copies as one song: a like on
// album holds of the song into the best of that album's copies: the one that is // one is a like on all, and the Liked list, shuffle and the mixes count the
// not a video rip when only one is not, else ProposeSurvivor's choice. Copies // song once. That holds for copies on one album as for copies across
// whose title or file name name different versions (versionWords) are not // releases; which copies to keep is the admin's merge. Linking an
// folded, even when they carry one title tag: a song and its clean version are // already-linked group changes nothing, so this runs every pass; likes are
// both kept. The copies on other releases stay and are linked as one song. At // shared only when a link is new, since a like made after it reaches every
// most budget copies go. It returns how many went and the songs they were, and // copy as it is made.
// drops them from their groups. func linkSongs(
func foldAlbumCopies( ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup,
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,
) (int, error) { ) (int, error) {
linked := 0 linked := 0
for _, g := range groups { for _, g := range groups {
if g.class != ClassCrossRelease || merged[g.id] { if g.class != ClassCrossRelease && g.class != ClassSameRelease {
continue continue
} }
if ctx.Err() != nil { if ctx.Err() != nil {
@@ -450,10 +283,13 @@ func (g *resolveGroup) classify() {
// to say. // to say.
func resolveNote(g *resolveGroup) string { func resolveNote(g *resolveGroup) string {
switch g.class { 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: case ClassCrossRelease:
if g.lone() < 0 { if g.lone() < 0 {
return "Each copy belongs to its own release, so none is removed; they count as one song." 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: 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." 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 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. // DuplicateResolveWorker runs a resolver pass every hour.
type DuplicateResolveWorker struct { type DuplicateResolveWorker struct {
pool *pgxpool.Pool pool *pgxpool.Pool
logger *slog.Logger logger *slog.Logger
dataDir string
settings *FingerprintSettingsService settings *FingerprintSettingsService
src ResolveSources src ResolveSources
tick time.Duration tick time.Duration
@@ -546,10 +324,10 @@ type DuplicateResolveWorker struct {
// NewDuplicateResolveWorker builds a worker with the production cadence. src // NewDuplicateResolveWorker builds a worker with the production cadence. src
// is what a pass may ask beyond the library. // is what a pass may ask beyond the library.
func NewDuplicateResolveWorker( 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 { ) *DuplicateResolveWorker {
return &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 return true
} }
// A run can begin after the check above, and a watcher batch has no run // 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 // at all: filesGate keeps either from rewriting tracks while this pass
// removes them. // decides from them.
if !filesGate.tryAcquire() { if !filesGate.tryAcquire() {
return true return true
} }
defer filesGate.release() 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 { if err != nil && ctx.Err() == nil {
w.logger.Warn("duplicate resolve: pass failed", "err", err) w.logger.Warn("duplicate resolve: pass failed", "err", err)
} }
w.logger.Info("duplicate resolve complete", w.logger.Info("duplicate resolve complete",
"groups", res.Groups, "merged", res.Merged, "merge_failed", res.MergeFailed, "groups", res.Groups, "songs_linked", res.SongsLinked, "dismissed", res.Dismissed,
"songs_linked", res.SongsLinked, "dismissed", res.Dismissed, "wrong_files", res.WrongFiles, "slots_named", res.SlotsNamed,
"held_back", res.HeldBack, "released", res.Released) "held_back", res.HeldBack, "released", res.Released)
return false return false
} }
+137 -94
View File
@@ -6,6 +6,7 @@ import (
"log/slog" "log/slog"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/jackc/pgx/v5/pgtype" "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 return n, reason
} }
// One album holding a song twice: the extra copy goes, the copy whose name and // One album holding a song twice: the pass removes neither file, since
// tags fit the album stays, and the merge is recorded as the resolver's: // another program may have filed either. It links the copies as one song and
// Minstrel is the only program writing the library. // leaves the group for an admin to merge.
func TestResolveDuplicates_MergesASameReleaseCopy_Integration(t *testing.T) { func TestResolveDuplicates_LinksASameReleaseCopyAndRemovesNothing_Integration(t *testing.T) {
f := newResolveFixture(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 { if err != nil {
t.Fatalf("resolve: %v", err) t.Fatalf("resolve: %v", err)
} }
if res.Merged != 1 || res.Classes[ClassSameRelease] != 1 { if res.Classes[ClassSameRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("result = %+v, want the same-release group merged", res) t.Fatalf("result = %+v, want the same-release group linked as one song", res)
} }
if exists(f.ripPath) || !exists(f.cleanPath) { 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)) 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) status, class, note, auto := f.group(t)
if status != "merged" || class == nil || *class != string(ClassSameRelease) || !auto { if status != "pending" || class == nil || *class != string(ClassSameRelease) || auto || note == nil {
t.Errorf("group = (%s, %v, auto=%v), want merged same_release by the resolver", status, class, auto) 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 { if n, _ := autoMergeAudit(t, f.pool, f.groupID); n != 0 {
t.Errorf("automatic merge audit rows = %d, want 1", n) t.Errorf("automatic merge audit rows = %d, want none", n)
} }
} }
// With auto-resolve off, the pass classifies and removes nothing. // With auto-resolve off, the pass classifies and removes nothing.
func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testing.T) { func TestResolveDuplicates_ClassifiesOnlyWithoutPermission_Integration(t *testing.T) {
f := newResolveFixture(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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.Merged != 0 || !exists(f.ripPath) { if res.SongsLinked != 0 || !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("merged %d", res.Merged) t.Errorf("result %+v; want nothing linked or removed", res)
} }
status, class, _, _ := f.group(t) status, class, _, _ := f.group(t)
if status != "pending" || class == nil || *class != string(ClassSameRelease) { if status != "pending" || class == nil || *class != string(ClassSameRelease) {
@@ -193,22 +194,26 @@ func newCrossReleaseRipFixture(t *testing.T) crossReleaseRipFixture {
return f return f
} }
// A video rip on one release with the clean copy on another: the rip is no // A video rip on one release with the clean copy on another: both files stay,
// release's copy, so it goes and the album cut stays. // the copies count as one song, and the group waits for an admin to remove
func TestResolveDuplicates_MergesARipAcrossReleases_Integration(t *testing.T) { // the rip.
func TestResolveDuplicates_LinksARipAcrossReleasesAndRemovesNothing_Integration(t *testing.T) {
f := newCrossReleaseRipFixture(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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.Classes[ClassCrossRelease] != 1 || res.Merged != 1 { if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 {
t.Fatalf("classes %v, merged %d; want the cross-release group merged", res.Classes, res.Merged) t.Fatalf("result %+v; want the cross-release group linked as one song", res)
} }
if exists(f.ripPath) || !exists(f.cleanPath) { 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)) 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" { if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("survivor reason %q, want the rip rule", reason) 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 { if _, err := f.pool.Exec(context.Background(), sql, args...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.Merged != 0 || !exists(f.ripPath) { if !exists(f.ripPath) || !exists(f.cleanPath) {
t.Errorf("merged %d; want both copies kept", res.Merged) t.Errorf("result %+v; want both copies kept", res)
} }
if res.SongsLinked != 1 { if res.SongsLinked != 1 {
t.Errorf("linked %d, want the pair linked as one song", res.SongsLinked) 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 { f.rip.ID, filepath.Join(filepath.Dir(f.ripPath), "01 - DARE.mp3")); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.Classes[ClassCrossRelease] != 1 || res.Merged != 0 || res.SongsLinked != 1 { if res.Classes[ClassCrossRelease] != 1 || res.SongsLinked != 1 || !exists(f.ripPath) || !exists(f.cleanPath) {
t.Fatalf("classes %v, merged %d, linked %d; want the pair linked and kept", res.Classes, res.Merged, res.SongsLinked) 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. // the group is dismissed and both files stay.
func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) { func TestResolveDuplicates_DismissesTwoVersionsOfASong_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Homesick", "Homesick (Instrumental)") 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 { if err != nil {
t.Fatal(err) 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) 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 { 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 // 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 // the file and Reach is a minute longer. The pass removes nothing; it names
// track stays, marked missing, until a good copy arrives. // Void in the group's note. Settled with that copy, the copy in Reach's slot
func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testing.T) { // 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") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000}) 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. // 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 { `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) t.Fatal(err)
} }
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) 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 // Folded by that MBID into the copy kept, the slot would never be wanted
// back. // back.
if pairs, err := PairMissingTracks(context.Background(), f.pool, nil); err != nil || pairs.Folded() != 0 { 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) 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) { if !exists(f.aPath) || exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want only Reach's copy removed", t.Fatalf("void exists %v, reach exists %v; want only Reach's copy removed", exists(f.aPath), exists(f.bPath))
res, exists(f.aPath), exists(f.bPath))
} }
var missing bool var missing bool
if err := f.pool.QueryRow(context.Background(), if err := f.pool.QueryRow(context.Background(),
@@ -410,8 +444,8 @@ func TestResolveDuplicates_RemovesACopyFromAnotherSongsSlot_Integration(t *testi
if !missing { if !missing {
t.Error("Reach's track is not marked missing, so nothing will fetch it again") 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 { if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" {
t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto) t.Errorf("group = %s, want settled", status)
} }
if n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 { if n := auditCount(t, f.pool, "duplicate_wrong_file", f.groupID); n != 1 {
t.Errorf("wrong-file audit rows = %d, want 1", n) 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) held("17 - Reach (other edition).m4a", tc.heldMs)
res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) if res := settleKeeping(t, f, f.a.ID); len(res.Removed) != 1 {
if err != nil || res.WrongFiles != 1 { t.Fatalf("settle = %+v; want Reach's slot emptied", res)
t.Fatalf("resolve = %+v, %v; want Reach's slot emptied", res, err)
} }
pairs, err := PairMissingTracks(ctx, f.pool, nil) pairs, err := PairMissingTracks(ctx, f.pool, nil)
if err != nil || pairs.Folded() != tc.foldsFirst { 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 // 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. // (Shnorkelbub's whole album in one file): the note says it is neither song,
func TestResolveDuplicates_RemovesEveryCopyWhenNoSlotIsTheirs_Integration(t *testing.T) { // and both files stay until an admin settles it.
func TestResolveDuplicates_SaysWhenNoSlotIsTheRecordings_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 282000, "Reach": 421000}) 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) { if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, void exists %v, reach exists %v; want both copies removed", t.Fatalf("result %+v, void exists %v, reach exists %v; want it named and both files kept",
res, exists(f.aPath), exists(f.bPath)) res, exists(f.aPath), exists(f.bPath))
} }
if status, _, _, auto := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "merged" || !auto { if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") {
t.Errorf("group = (%s, auto=%v), want settled by the resolver", status, auto) 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 { if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("wrong-file audit rows = %d, want 1", n) t.Errorf("group = %s, want pending for an admin", status)
} }
} }
@@ -502,9 +536,9 @@ func seedTrimmedAlbum(t *testing.T) oneAlbumFixture {
return f return f
} }
// AcoustID matched one copy to Tormentor's recording: that copy stays and // AcoustID matched one copy to Tormentor's recording: the note names
// Record Shop's goes. // Tormentor, and both files stay.
func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) { func TestResolveDuplicates_NamesTheCopyAcoustIDNames_Integration(t *testing.T) {
f := seedTrimmedAlbum(t) f := seedTrimmedAlbum(t)
if _, err := f.pool.Exec(context.Background(), if _, err := f.pool.Exec(context.Background(),
`INSERT INTO track_acoustid_lookups (track_id, state, candidates, recording_mbid) VALUES ($1, 'matched', 1, 'rec-tormentor')`, `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) t.Fatal(err)
} }
asked := 0 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 }, Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil },
}) })
if err != nil { if err != nil {
@@ -521,10 +555,13 @@ func TestResolveDuplicates_KeepsTheCopyAcoustIDNames_Integration(t *testing.T) {
if asked != 0 { if asked != 0 {
t.Errorf("AcoustID asked %d times; the copy's own lookup already answered", asked) t.Errorf("AcoustID asked %d times; the copy's own lookup already answered", asked)
} }
if res.WrongFiles != 1 || !exists(f.aPath) || exists(f.bPath) { if res.SlotsNamed != 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", t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want Tormentor named and both kept",
res, exists(f.aPath), exists(f.bPath)) 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 // 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 { f.a.ID, f.b.ID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, err := ResolveDuplicates(context.Background(), f.pool, nil, "", true) res, err := ResolveDuplicates(context.Background(), f.pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.WrongFiles != 1 || exists(f.aPath) || !exists(f.bPath) { if res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("result %+v, tormentor exists %v, record shop exists %v; want only Tormentor's copy removed", 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)) 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) { t.Run("unknown", func(t *testing.T) {
f := setup(t) f := setup(t)
asked := 0 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 }, Identify: func(context.Context, string) ([]string, error) { asked++; return nil, nil },
}) })
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if asked != 0 || res.WrongFiles != 0 || !exists(f.aPath) || !exists(f.bPath) { if asked != 0 || res.SlotsNamed != 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) 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 // A pass while a scan is walking the library waits for it: a pass deciding
// under the walk is marked present again when the scan reconciles. A run // from tracks the scan is still rewriting would decide from a library
// stuck past StuckScanThreshold does not hold the resolver up. Files being // 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 // read with no run recorded (a scan whose run row hasn't landed yet, a
// watcher batch) hold it up as well. // watcher batch) hold it up as well.
func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) { func TestDuplicateResolveWorker_WaitsForARunningScan_Integration(t *testing.T) {
f := seedTrimmedAlbum(t) f := seedTrimmedAlbum(t)
ctx := context.Background() 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 { if _, err := f.pool.Exec(ctx, `INSERT INTO scan_runs DEFAULT VALUES`); err != nil {
t.Fatal(err) 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 knows the recording as no song of the album: the note says so. With
// AcoustID unreachable, nothing is decided and the group waits. // AcoustID unreachable, nothing is decided. Either way the group waits.
func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testing.T) { func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testing.T) {
t.Run("no match", func(t *testing.T) { t.Run("no match", func(t *testing.T) {
f := seedTrimmedAlbum(t) f := seedTrimmedAlbum(t)
asked := 0 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) { Identify: func(context.Context, string) ([]string, error) {
asked++ asked++
return []string{"rec-elsewhere"}, nil return []string{"rec-elsewhere"}, nil
@@ -632,23 +673,26 @@ func TestResolveDuplicates_TrimmedCopiesAcoustIDCannotName_Integration(t *testin
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if asked != 1 || res.WrongFiles != 2 || exists(f.aPath) || exists(f.bPath) { if asked != 1 || res.SlotsNamed != 1 || !exists(f.aPath) || !exists(f.bPath) {
t.Fatalf("asked %d, result %+v; want one lookup and both copies removed", asked, res) 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" { if note := noteOf(t, f.pool, f.groupID); !strings.Contains(note, "none of these songs") {
t.Errorf("group = %s, want settled", status) 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) { t.Run("unreachable", func(t *testing.T) {
f := seedTrimmedAlbum(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 }, Identify: func(context.Context, string) ([]string, error) { return nil, ErrIdentifyUnavailable },
}) })
if err != nil { if err != nil {
t.Fatal(err) 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 nothing removed while AcoustID cannot answer", res) 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" { if status, _, _, _ := (resolveFixture{pool: f.pool, groupID: f.groupID}).group(t); status != "pending" {
t.Errorf("group = %s, want pending", status) 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}) seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 281000})
return nil 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if calls != 1 || res.WrongFiles != 1 || exists(f.bPath) { if calls != 1 || res.SlotsNamed != 1 || !exists(f.bPath) {
t.Fatalf("fetches %d, result %+v; want one fetch and Reach's copy removed", calls, res) 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 // 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) { func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
if _, err := f.pool.Exec(context.Background(), if _, err := f.pool.Exec(context.Background(),
@@ -696,24 +740,24 @@ func TestResolveDuplicates_TrackListsSwitchedOff_Integration(t *testing.T) {
calls++ calls++
return ErrLookupOff 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 { if err != nil {
t.Fatal(err) 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) 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) { func TestResolveDuplicates_LeavesAnUndecidedSlotForTheOperator_Integration(t *testing.T) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000}) 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 { if err != nil {
t.Fatal(err) 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) 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" || 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) f := newCrossReleaseRipFixture(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(f.pool) q := dbq.New(f.pool)
// Without its group the rip has no clean copy to merge into, so it stays // Without its group the rip is judged by its name alone.
// on disk and only its verdict changes.
if _, err := f.pool.Exec(ctx, `DELETE FROM duplicate_groups WHERE id = $1`, f.groupID); err != nil { if _, err := f.pool.Exec(ctx, `DELETE FROM duplicate_groups WHERE id = $1`, f.groupID); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -743,7 +786,7 @@ func TestResolveDuplicates_HoldsBackRips_Integration(t *testing.T) {
} }
resolve := func() DuplicateResolveResult { resolve := func() DuplicateResolveResult {
t.Helper() t.Helper()
res, err := ResolveDuplicates(ctx, f.pool, nil, "", true) res, err := ResolveDuplicates(ctx, f.pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) 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 // 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 // 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 // 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 // sweep finds the pair on its own, as any song held twice on one album.
// twice on one album.
func wrongSlots(copies []slotCopy, tracks []dbq.MbReleaseTrack) (keep int, losers []int, ok bool) { func wrongSlots(copies []slotCopy, tracks []dbq.MbReleaseTrack) (keep int, losers []int, ok bool) {
keep = -1 keep = -1
keepKey := "" keepKey := ""
@@ -164,14 +163,12 @@ func dismissDistinct(
return n return n
} }
// settleWrongSlots removes the copies that sit in another song's slot, for // nameWrongSlots says, in the note of every one-album mismatch the track list
// every one-album mismatch the track list, or AcoustID with it, decides. It // or AcoustID decides, which song the recording is, so the admin settling it
// returns how many copies went and the songs whose slots were emptied, and // (SettleWrongSlot) need not work it out. It returns how many it named.
// adds the groups it settled to settled. func nameWrongSlots(
func settleWrongSlots( ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, src ResolveSources,
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groups []*resolveGroup, settled map[pgtype.UUID]bool, ) int {
src ResolveSources,
) (int, []string) {
q := dbq.New(pool) q := dbq.New(pool)
tracksByGroup := map[string][]dbq.MbReleaseTrack{} tracksByGroup := map[string][]dbq.MbReleaseTrack{}
fetches, identifies := trackListFetchesPerPass, identifiesPerPass fetches, identifies := trackListFetchesPerPass, identifiesPerPass
@@ -181,10 +178,9 @@ func settleWrongSlots(
if src.Identify == nil { if src.Identify == nil {
identifies = 0 identifies = 0
} }
removed := 0 named := 0
var names []string
for _, g := range groups { for _, g := range groups {
if g.class != ClassMismatch || settled[g.id] || ctx.Err() != nil { if g.class != ClassMismatch || ctx.Err() != nil {
continue continue
} }
rg := g.members[0].ReleaseGroupMbid rg := g.members[0].ReleaseGroupMbid
@@ -218,13 +214,15 @@ func settleWrongSlots(
for i, m := range g.members { for i, m := range g.members {
copies[i] = slotCopy{Title: m.Title, Artist: m.ArtistName, DurationMs: m.DurationMs} 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 { if !ok {
recordings, known := groupRecordings(ctx, logger, g, src.Identify, &identifies) recordings, known := groupRecordings(ctx, logger, g, src.Identify, &identifies)
if !known { if !known {
continue 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", 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) "group_id", syncpkg.FormatUUID(g.id), "recordings", recordings)
} }
@@ -232,19 +230,20 @@ func settleWrongSlots(
if !ok { if !ok {
continue continue
} }
emptied := emptiedSlots(ctx, q, logger, g, losers, tracks) g.note = wrongSlotNote(source, g, keep)
n, err := removeWrongSlots(ctx, pool, logger, g, keep, losers, emptied, pgtype.UUID{}) named++
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))
}
} }
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 // 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 // SettleWrongSlot settles a one-album mismatch the resolver left for the
// admin, with their answer in place of MusicBrainz's lengths and // 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 // 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 // invalid id means they cannot say, and every copy goes. Either way the copies
// resolver's own path: the copies removed are marked missing, and their slots // removed are marked missing, and their slots wait for a good copy. A merge
// wait for a good copy. A merge does none of that, and keeps one copy's title // does none of that, and keeps one copy's title whether or not it is the
// whether or not it is the audio's. // audio's.
// //
// Copies sharing the kept copy's title are one song held twice and stay, as in // 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( func SettleWrongSlot(
ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groupID, keepID, actorID pgtype.UUID, ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, groupID, keepID, actorID pgtype.UUID,
) (WrongSlotResult, error) { ) (WrongSlotResult, error) {
@@ -548,16 +547,14 @@ func removeWrongSlots(
} }
// notifyNewForReview tells admins about groups this pass classified for the // notifyNewForReview tells admins about groups this pass classified for the
// first time and left for them. A group the resolver settled, linked or will // first time and left for them. A group that needs no one (distinct versions
// link is not news, and would bury the groups that need them. // 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) { func notifyNewForReview(ctx context.Context, groups []*resolveGroup, settled map[pgtype.UUID]bool) {
var count int64 var count int64
var items []string var items []string
for _, g := range groups { for _, g := range groups {
if g.members[0].PriorClass != nil || settled[g.id] { if g.members[0].PriorClass != nil || settled[g.id] || !g.wantsAdmin() {
continue
}
if g.class != ClassReview && g.class != ClassMismatch {
continue continue
} }
count++ count++
+1 -1
View File
@@ -21,7 +21,7 @@ func undecidedSlot(t *testing.T) (oneAlbumFixture, dbq.User) {
f := newOneAlbumFixture(t, "acoustic", "Void", "Reach") f := newOneAlbumFixture(t, "acoustic", "Void", "Reach")
ctx := context.Background() ctx := context.Background()
seedTrackList(t, f.pool, f.album, map[string]int{"Void": 220500, "Reach": 221000}) 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) t.Fatalf("resolve = %+v, %v; want the group left for the operator", res, err)
} }
name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name()) name := strings.NewReplacer("/", "-", " ", "-").Replace(t.Name())
+30 -1
View File
@@ -1,6 +1,8 @@
package library package library
import ( import (
"path/filepath"
"regexp"
"sort" "sort"
"strings" "strings"
"time" "time"
@@ -23,12 +25,18 @@ type SurvivorCandidate struct {
// - it has a track number that no other track on its album also claims // - it has a track number that no other track on its album also claims
// - its file name carries no video-rip marker (SourceMarkersFor) // - its file name carries no video-rip marker (SourceMarkersFor)
// - it has a MusicBrainz recording id // - 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 // 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 // listener hears: rips of one song can differ by a few bytes, which makes file
// size a poor guide. // 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 score := 0
if inAlbumFolder(filePath, albumTitle) {
score++
}
if hasTrackNumber && !positionClash { if hasTrackNumber && !positionClash {
score++ score++
} }
@@ -41,6 +49,27 @@ func TagFitScore(hasTrackNumber, positionClash bool, filePath string, hasMBID bo
return score 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. // 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 // 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 // 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 hasMBID bool
want int want int
}{ }{
{"clean, numbered, identified", true, false, "/music/A/B/A - B - 01 - Song.flac", true, 3}, {"filed, numbered, identified", true, false, "/music/A/B (2001)/A - B - 01 - Song.flac", true, 4},
{"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 2}, {"filed on a medium of the album", true, false, "/music/A/B (2001)/CD 02/A - B - 01 - Song.flac", true, 4},
{"no track number", false, false, "/music/A/B/Song.flac", true, 2}, {"loose in the artist's folder", true, false, "/music/A/A - Song.flac", true, 3},
{"video rip", true, false, "/music/A/B/A - B - 01 - Song (Official Video).mp3", true, 2}, {"position taken by another track", true, true, "/music/A/B/A - B - 01 - Song.flac", true, 3},
{"rip with nothing else", false, false, "/music/A/B/Song (Official Video).mp3", false, 0}, {"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 { 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) 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" "time"
) )
// filesGate keeps reading the library's files apart from removing them. A // filesGate keeps a library scan and a duplicate-resolver pass from running
// full scan holds it for its whole length and the watcher for each batch; // at once. A full scan holds it for its whole length and the watcher for each
// a duplicate-resolver pass, which removes the copies it merges, runs only // batch; a resolver pass runs only while no one else holds it. The scan
// while no one else holds it. Without it, a file a scan has listed could be // rewrites tracks from the files it reads, and the pass decides from those
// removed under the scan, and a file read just before its removal would put // tracks which copies are one song: run together, the pass would decide from
// back a track whose file is gone. // a library half-read.
// //
// A scan that starts during a resolver pass waits for the pass to finish, // 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 // up to filesWaitLimit. A resolver pass that finds the gate taken is put off
@@ -19,9 +19,8 @@ import (
var filesGate = make(gate, 1) var filesGate = make(gate, 1)
// filesWaitLimit is how long a scan waits for a resolver pass to let go of // 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; // the files. A pass takes minutes; one still holding them after this long is
// one still holding them after this long is stuck, and the scan gives up // stuck, and the scan gives up rather than wait forever.
// rather than wait forever.
const filesWaitLimit = 30 * time.Minute const filesWaitLimit = 30 * time.Minute
// errFilesBusy is a scan giving up on a resolver pass that held the files // 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 // 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 // none of them until the pass lets go, so the pass never decides from a
// it. // library half-read.
func TestScanner_WaitsForAPassHoldingTheFiles_Integration(t *testing.T) { func TestScanner_WaitsForAPassHoldingTheFiles_Integration(t *testing.T) {
ctx := context.Background() ctx := context.Background()
pool := dbtest.Open(t) pool := dbtest.Open(t)
+2 -2
View File
@@ -186,7 +186,7 @@ func TestResolveDuplicates_TellsAdminsOnlyOfNewGroupsLeftForThem(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil { if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil {
t.Fatal(err) t.Fatal(err)
} }
got := unreadNotices(t, pool, admin) 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 { if _, err := q.MarkAllNotificationsRead(ctx, dbq.MarkAllNotificationsReadParams{UserID: admin.ID}); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := ResolveDuplicates(ctx, pool, nil, "", true); err != nil { if _, err := ResolveDuplicates(ctx, pool, nil, true); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if got := unreadNotices(t, pool, admin); len(got) != 0 { 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) q := dbq.New(pool)
f := newSongLinkFixture(t, pool) f := newSongLinkFixture(t, pool)
res, err := ResolveDuplicates(ctx, pool, nil, "", true) res, err := ResolveDuplicates(ctx, pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -111,7 +111,7 @@ func TestCrossReleaseCopiesCountAsOneSong_Integration(t *testing.T) {
} }
// A second pass changes nothing. // 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) 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() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
f := newSongLinkFixture(t, 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) t.Fatal(err)
} }
keys := songKeys(t, q, f.single.ID, f.albumCut.ID) 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 // 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 // Barz as a FLAC and an mp3, beside the single): every file stays, since
// extra copy is merged into its FLAC, the single stays, and the two copies // another program may have filed any of them, and all three count as one
// left are linked as one song. // song. Thinning the album's copies is an admin's merge.
func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integration(t *testing.T) { func TestResolveDuplicates_KeepsEveryCopyInACrossReleaseGroup_Integration(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
@@ -267,18 +267,18 @@ func TestResolveDuplicates_FoldsAnAlbumsExtraCopyInACrossReleaseGroup_Integratio
t.Fatal(err) t.Fatal(err)
} }
res, err := ResolveDuplicates(ctx, pool, nil, "", true) res, err := ResolveDuplicates(ctx, pool, nil, true)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if res.Merged != 1 || exists(mp3.FilePath) || !exists(flac.FilePath) || !exists(single.FilePath) { if !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", t.Fatalf("mp3 %v flac %v single %v; want every file left in place",
res, exists(mp3.FilePath), exists(flac.FilePath), exists(single.FilePath)) 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 res.SongsLinked != 1 { 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" KindScanFailed Kind = "scan_failed"
KindTracksMissing Kind = "tracks_missing" KindTracksMissing Kind = "tracks_missing"
KindDuplicatesFound Kind = "duplicates_found" KindDuplicatesFound Kind = "duplicates_found"
// KindDuplicatesResolved: the duplicate resolver merged copies on its // KindDuplicatesResolved: copies merged without an admin. The resolver no
// own. This is how an automatic merge stays visible. // longer removes files, so nothing sends it; it stays so notices already
// in an inbox still render.
KindDuplicatesResolved Kind = "duplicates_resolved" KindDuplicatesResolved Kind = "duplicates_resolved"
KindPlaybackErrors Kind = "playback_errors" KindPlaybackErrors Kind = "playback_errors"
) )
@@ -70,7 +70,7 @@
<SettingRow <SettingRow
label="Resolve duplicates automatically" label="Resolve duplicates automatically"
for="fp-auto" 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" /> <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> </SettingRow>
@@ -27,12 +27,12 @@
import ListContinuation from '#lib/components/ListContinuation.svelte'; import ListContinuation from '#lib/components/ListContinuation.svelte';
import TabStrip from '#lib/components/TabStrip.svelte'; import TabStrip from '#lib/components/TabStrip.svelte';
// Tracks the duplicate sweep believes hold one recording. The // Tracks the duplicate sweep believes hold one recording. The resolver
// resolver settles what is safe on its own: a song held twice on // never removes a file on its own, since other programs file music into the
// one album, and a video rip with a clean copy elsewhere. What is left comes // library too: it links copies of one song so they count once, and dismisses
// in two tabs: groups that need an admin, and the same song on different // distinct versions. Groups come in two tabs: those that need an admin, and
// releases, which is kept on purpose. A third tab lists what the resolver // the same song on different releases, which is kept on purpose. A third tab
// did. // lists what the resolver settled.
// //
// Dismissing a group says "these are not duplicates", and the sweep will not // 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 // 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 // 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 // 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 // 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 // recording is (the group's note says when MusicBrainz or AcoustID could
// resolver would have: copies in other songs' slots are removed, and those // tell), or that they can't tell: copies in other songs' slots are removed,
// tracks wait in Needs a file until a good copy is in the library folder. // and those tracks wait in Needs a file until a good copy is in the library
// folder.
type Tab = DuplicatesView | 'resolved'; type Tab = DuplicatesView | 'resolved';
const fromUrl = page.url.searchParams.get('view'); const fromUrl = page.url.searchParams.get('view');