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
+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
}