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

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

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

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

403 lines
13 KiB
Go

package library
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
syncpkg "github.com/Fabled-Sword/minstrel/internal/sync"
)
// Duplicate resolver.
//
// 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:
//
// - 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, 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 (
// 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
// again; a boot scan is short.
scanWaitRetry = time.Minute
)
// DuplicateResolveResult tallies one pass.
type DuplicateResolveResult struct {
Groups int
Classes map[DuplicateClass]int
// SongsLinked counts groups newly linked as one song.
SongsLinked 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
}
// resolveGroup is one pending group and its present copies.
type resolveGroup struct {
id pgtype.UUID
tier string
// worstBER is how far apart the least alike copies' fingerprints are, for
// an acoustic group; nil for an exact one.
worstBER *float32
members []dbq.ListDuplicateGroupsForResolveRow
class DuplicateClass
note string
}
// isRip says whether a copy is a video rip: held back as one, or named like
// one and not kept by an admin. The name is read as well as the verdict
// because a pass reads the groups before it flags new rips.
func isRip(m dbq.ListDuplicateGroupsForResolveRow) bool {
if m.SourceVerdict != nil {
return *m.SourceVerdict == "suspect"
}
return len(SourceMarkersFor(m.FilePath)) > 0
}
// lone returns the index of the group's only copy that is not a rip, or -1
// when there is none or more than one.
func (g *resolveGroup) lone() int {
at := -1
for i, m := range g.members {
if isRip(m) {
continue
}
if at >= 0 {
return -1
}
at = i
}
return at
}
// 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 ClassDistinct:
return false
case ClassCrossRelease:
return g.lone() >= 0
}
return true
}
// TrackListFetcher reads a release group's releases and track lists from
// MusicBrainz into the catalogue (catalogue.Service.RefreshReleaseGroup). It
// returns ErrLookupOff while an admin has switched the lookup off.
type TrackListFetcher func(ctx context.Context, releaseGroupMBID string) error
// ErrLookupOff is a TrackListFetcher's answer while an admin has switched
// MusicBrainz track lists off. The pass then decides from the track lists
// already read, without asking again until the next pass.
var ErrLookupOff = errors.New("an admin has switched this lookup off")
// RecordingIdentifier asks AcoustID which recordings a file may be
// (AcoustIDLookupWorker.IdentifyRecordings).
type RecordingIdentifier func(ctx context.Context, path string) ([]string, error)
// ResolveSources are what a pass may ask beyond the library, a few times per
// pass each. Either may be nil, and the pass decides from what is held.
type ResolveSources struct {
// TrackLists reads the track list of an album whose wrong slot the pass
// must decide and the catalogue has never read (trackListFetchesPerPass).
TrackLists TrackListFetcher
// Identify names the recording cut to several slots' lengths, when no
// copy's own lookup has (identifiesPerPass).
Identify RecordingIdentifier
}
// ResolveDuplicates runs one pass. act is the auto-resolve setting;
// 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, act bool,
) (DuplicateResolveResult, error) {
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, act bool, src ResolveSources,
) (DuplicateResolveResult, error) {
if logger == nil {
logger = slog.Default()
}
q := dbq.New(pool)
res := DuplicateResolveResult{Classes: map[DuplicateClass]int{}}
rows, err := q.ListDuplicateGroupsForResolve(ctx, pgtype.UUID{})
if err != nil {
return res, fmt.Errorf("list duplicate groups: %w", err)
}
groups := foldResolveGroups(rows)
res.Groups = len(groups)
for _, g := range groups {
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
}
if !act {
notifyNewForReview(ctx, groups, nil)
return res, nil
}
if res.HeldBack, err = q.FlagSuspectSourceTracks(ctx, SuspectSourcePattern); err != nil {
return res, fmt.Errorf("hold back video rips: %w", err)
}
if res.Released, err = q.ClearStaleSuspectSourceTracks(ctx, SuspectSourcePattern); err != nil {
return res, fmt.Errorf("release renamed tracks: %w", err)
}
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
}
notifyNewForReview(ctx, groups, settled)
return res, nil
}
// 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 && g.class != ClassSameRelease {
continue
}
if ctx.Err() != nil {
return linked, ctx.Err()
}
ids := make([]pgtype.UUID, len(g.members))
for i, m := range g.members {
ids[i] = m.TrackID
}
moved, err := linkSong(ctx, pool, ids)
if err != nil {
logger.Warn("duplicate resolve: song link failed", "group_id", syncpkg.FormatUUID(g.id), "err", err)
continue
}
if moved {
linked++
}
}
return linked, nil
}
// linkSong links the tracks as one song and, when that changed anything,
// shares their likes across the song and logs each added like for sync.
func linkSong(ctx context.Context, pool *pgxpool.Pool, ids []pgtype.UUID) (bool, error) {
tx, err := pool.Begin(ctx)
if err != nil {
return false, err
}
defer func() { _ = tx.Rollback(ctx) }()
tq := dbq.New(tx)
link, err := tq.LinkTracksAsSong(ctx, ids)
if err != nil {
return false, fmt.Errorf("link: %w", err)
}
if link.Moved == 0 {
return false, nil
}
if _, err := tq.ShareSongLikes(ctx, link.SongKey); err != nil {
return false, fmt.Errorf("share likes: %w", err)
}
return true, tx.Commit(ctx)
}
func foldResolveGroups(rows []dbq.ListDuplicateGroupsForResolveRow) []*resolveGroup {
var groups []*resolveGroup
for _, r := range rows {
if n := len(groups); n == 0 || groups[n-1].id != r.GroupID {
groups = append(groups, &resolveGroup{id: r.GroupID, tier: r.Tier, worstBER: r.WorstBitErrorRate})
}
g := groups[len(groups)-1]
g.members = append(g.members, r)
}
// A group whose other copies went missing has nothing left to resolve.
out := groups[:0]
for _, g := range groups {
if len(g.members) >= 2 {
out = append(out, g)
}
}
return out
}
// classify sets the group's class and the note the report shows beside it.
func (g *resolveGroup) classify() {
cm := make([]ClassifyMember, len(g.members))
for i, m := range g.members {
cm[i] = ClassifyMember{AlbumID: syncpkg.FormatUUID(m.AlbumID), Title: m.Title, ArtistName: m.ArtistName}
}
g.class = ClassifyDuplicateGroup(g.tier, cm)
g.note = resolveNote(g)
}
// resolveNote is what the report says beside a group, when there is something
// 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."
}
return ""
}
func writeResolveVerdicts(ctx context.Context, q *dbq.Queries, groups []*resolveGroup) error {
classes := dbq.SetDuplicateGroupClassesParams{}
for _, g := range groups {
classes.GroupIds = append(classes.GroupIds, g.id)
classes.Classes = append(classes.Classes, string(g.class))
classes.Notes = append(classes.Notes, g.note)
}
if len(classes.GroupIds) == 0 {
return nil
}
if err := q.SetDuplicateGroupClasses(ctx, classes); err != nil {
return fmt.Errorf("write duplicate classes: %w", err)
}
return nil
}
// DuplicateResolveWorker runs a resolver pass every hour.
type DuplicateResolveWorker struct {
pool *pgxpool.Pool
logger *slog.Logger
settings *FingerprintSettingsService
src ResolveSources
tick time.Duration
}
// 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, settings *FingerprintSettingsService, src ResolveSources,
) *DuplicateResolveWorker {
return &DuplicateResolveWorker{
pool: pool, logger: logger, settings: settings, src: src, tick: duplicateResolveTick,
}
}
// Run blocks until ctx is cancelled, running a pass at start and then each
// tick. A pass put off for a running scan is tried again after scanWaitRetry.
func (w *DuplicateResolveWorker) Run(ctx context.Context) {
t := time.NewTicker(w.tick)
defer t.Stop()
soon := time.NewTimer(0)
defer soon.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
case <-soon.C:
}
if w.tickOnce(ctx) {
soon.Reset(scanWaitRetry)
}
}
}
// tickOnce contains one pass so nothing it does can stop the next tick. It
// reports whether the pass was put off for a running scan.
func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool) {
defer func() {
if r := recover(); r != nil {
w.logger.Error("duplicate resolve: tick panicked", "panic", r)
}
}()
q := dbq.New(w.pool)
// A sweep in flight is rewriting the groups; the next tick sees its result.
_, err := q.GetInFlightDuplicateSweep(ctx)
switch {
case err == nil:
return false
case !errors.Is(err, pgx.ErrNoRows):
if ctx.Err() == nil {
w.logger.Warn("duplicate resolve: sweep check failed", "err", err)
}
return false
}
// A pass waits out a whole scan run, whose later stages re-read files
// too. A run past StuckScanThreshold is a dead one.
running, err := scanRunning(ctx, q)
switch {
case err != nil:
if ctx.Err() == nil {
w.logger.Warn("duplicate resolve: scan check failed", "err", err)
}
return false
case running:
return true
}
// A run can begin after the check above, and a watcher batch has no run
// 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.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, "songs_linked", res.SongsLinked, "dismissed", res.Dismissed,
"slots_named", res.SlotsNamed,
"held_back", res.HeldBack, "released", res.Released)
return false
}