From 785b15ab5ff7976cc7bf4d64b136db57dda97363 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 25 Nov 2026 22:02:00 -0500 Subject: [PATCH] fix(library): a scan cut off by a restart no longer blocks saving library folders A restart mid-scan left its scan_runs row unfinished, and saving library folders refused ("A library scan is running") until a later scan reaped it, up to 12 hours on. Startup now closes such rows with the reason before the boot scan, as backups already do. Saving folders and the duplicate sweep share one check that treats a run past StuckScanThreshold as dead. Co-Authored-By: Claude Opus 5.5 --- cmd/minstrel/main.go | 4 +- internal/db/dbq/scan_runs.sql.go | 18 +++++++++ internal/db/queries/scan_runs.sql | 9 +++++ internal/library/duplicate_resolve.go | 8 ++-- internal/library/library_paths.go | 10 ++--- internal/library/scanrecover_test.go | 57 +++++++++++++++++++++++++++ internal/library/trigger.go | 27 +++++++++++++ 7 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 internal/library/scanrecover_test.go diff --git a/cmd/minstrel/main.go b/cmd/minstrel/main.go index fe0d11aa..539196b7 100644 --- a/cmd/minstrel/main.go +++ b/cmd/minstrel/main.go @@ -244,7 +244,9 @@ func run() error { // One unified scan chain: library walk → MBID backfill → cover enrich. // Boot-time scan and manual-trigger scans share this path; results land - // in scan_runs for the admin overview. + // in scan_runs for the admin overview. A run the last shutdown cut off is + // closed first, so it doesn't read as a scan still going. + library.RecoverScanRuns(ctx, pool, logger.With("component", "scan_run")) if cfg.Library.ScanOnStartup && len(roots) > 0 { go func() { if _, err := library.RunScan(ctx, pool, scanner, coverEnricher, diff --git a/internal/db/dbq/scan_runs.sql.go b/internal/db/dbq/scan_runs.sql.go index 45727164..340e98b1 100644 --- a/internal/db/dbq/scan_runs.sql.go +++ b/internal/db/dbq/scan_runs.sql.go @@ -11,6 +11,24 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const failUnfinishedScanRuns = `-- name: FailUnfinishedScanRuns :execrows +UPDATE scan_runs + SET finished_at = now(), + error_message = 'The server stopped while the scan was running.' + WHERE finished_at IS NULL +` + +// At startup no scan can be running yet, so a row still unfinished was cut +// off when the server last stopped. Closing it keeps it from reading as a +// scan in progress, which would block saving library folders. +func (q *Queries) FailUnfinishedScanRuns(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, failUnfinishedScanRuns) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const finishScanRun = `-- name: FinishScanRun :exec UPDATE scan_runs SET finished_at = now(), diff --git a/internal/db/queries/scan_runs.sql b/internal/db/queries/scan_runs.sql index 03d1856d..f4cd1502 100644 --- a/internal/db/queries/scan_runs.sql +++ b/internal/db/queries/scan_runs.sql @@ -38,6 +38,15 @@ UPDATE scan_runs SET artist_art_enrich = $2 WHERE id = $1; +-- name: FailUnfinishedScanRuns :execrows +-- At startup no scan can be running yet, so a row still unfinished was cut +-- off when the server last stopped. Closing it keeps it from reading as a +-- scan in progress, which would block saving library folders. +UPDATE scan_runs + SET finished_at = now(), + error_message = 'The server stopped while the scan was running.' + WHERE finished_at IS NULL; + -- name: GetInFlightScanRun :one -- Used by POST /api/admin/scan/run to 409 when a scan is already running. -- "In flight" = finished_at IS NULL. diff --git a/internal/library/duplicate_resolve.go b/internal/library/duplicate_resolve.go index daeae9e6..6b434a37 100644 --- a/internal/library/duplicate_resolve.go +++ b/internal/library/duplicate_resolve.go @@ -598,15 +598,15 @@ func (w *DuplicateResolveWorker) tickOnce(ctx context.Context) (waitForScan bool // A scan in flight has listed the files it will reconcile: a copy removed // now is marked present again when it does. A run past StuckScanThreshold // is a dead one. - run, err := q.GetInFlightScanRun(ctx) + running, err := scanRunning(ctx, q) switch { - case err == nil && time.Since(run.StartedAt.Time) <= StuckScanThreshold: - return true - case err != nil && !errors.Is(err, pgx.ErrNoRows): + case err != nil: if ctx.Err() == nil { w.logger.Warn("duplicate resolve: scan check failed", "err", err) } return false + case running: + return true } res, err := ResolveDuplicatesWith(ctx, w.pool, w.logger, w.dataDir, w.settings.Get().AutoResolve, w.src) if err != nil && ctx.Err() == nil { diff --git a/internal/library/library_paths.go b/internal/library/library_paths.go index 2e0eda22..537f4c7b 100644 --- a/internal/library/library_paths.go +++ b/internal/library/library_paths.go @@ -80,13 +80,13 @@ func (s *Scanner) SetRoots(ctx context.Context, changes []RootChange) (RerootRes q := dbq.New(s.pool) // A scan walking the old folders would put their paths back, or mark the // moved rows missing when it reconciles. - _, err = q.GetInFlightScanRun(ctx) - if err == nil { - return RerootResult{}, badRoots("A library scan is running; save again once it finishes.") - } - if !errors.Is(err, pgx.ErrNoRows) { + running, err := scanRunning(ctx, q) + if err != nil { return RerootResult{}, fmt.Errorf("in-flight scan check: %w", err) } + if running { + return RerootResult{}, badRoots("A library scan is running; save again once it finishes.") + } for _, m := range moves { if err := checkMove(ctx, q, m); err != nil { return RerootResult{}, err diff --git a/internal/library/scanrecover_test.go b/internal/library/scanrecover_test.go new file mode 100644 index 00000000..9ef426e8 --- /dev/null +++ b/internal/library/scanrecover_test.go @@ -0,0 +1,57 @@ +package library + +import ( + "context" + "errors" + "testing" + + "github.com/jackc/pgx/v5/pgtype" +) + +// A scan the last shutdown cut off is closed at startup with the reason, so +// it no longer reads as a scan in progress. +func TestRecoverScanRuns_ClosesARunTheLastShutdownCutOff_Integration(t *testing.T) { + pool := triggerTestPool(t) + ctx := context.Background() + var id pgtype.UUID + if err := pool.QueryRow(ctx, + `INSERT INTO scan_runs (started_at) VALUES (now() - interval '5 minutes') RETURNING id`).Scan(&id); err != nil { + t.Fatal(err) + } + + RecoverScanRuns(ctx, pool, quietLogger()) + + var finished bool + var reason *string + if err := pool.QueryRow(ctx, + `SELECT finished_at IS NOT NULL, error_message FROM scan_runs WHERE id = $1`, id).Scan(&finished, &reason); err != nil { + t.Fatal(err) + } + if !finished || reason == nil || *reason == "" { + t.Errorf("finished %v, reason %v; want the run closed with why", finished, reason) + } +} + +// Saving library folders waits for a scan that is running, but not for an +// unfinished run older than StuckScanThreshold: that one is dead. +func TestSetRoots_OnlyALiveScanHoldsUpSavingFolders_Integration(t *testing.T) { + pool := triggerTestPool(t) + clearSavedRoots(t, pool) + ctx := context.Background() + s := New(pool, quietLogger(), nil, nil) + + if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now() - interval '2 hours')`); err != nil { + t.Fatal(err) + } + if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); err != nil { + t.Errorf("a dead scan blocked saving folders: %v", err) + } + + if _, err := pool.Exec(ctx, `INSERT INTO scan_runs (started_at) VALUES (now())`); err != nil { + t.Fatal(err) + } + var re *RootsError + if _, err := s.SetRoots(ctx, []RootChange{{Path: t.TempDir()}}); !errors.As(err, &re) { + t.Errorf("err %v; want a refusal while a scan is running", err) + } +} diff --git a/internal/library/trigger.go b/internal/library/trigger.go index 52c3e8bd..a2e71e59 100644 --- a/internal/library/trigger.go +++ b/internal/library/trigger.go @@ -20,6 +20,33 @@ import ( // duration so a normally-running scan is never reaped accidentally. const StuckScanThreshold = 1 * time.Hour +// RecoverScanRuns closes the scan runs a stopped server left unfinished. It +// runs once at startup, before the first scan: none can be running yet. +func RecoverScanRuns(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger) { + n, err := dbq.New(pool).FailUnfinishedScanRuns(ctx) + if err != nil { + logger.Warn("scan: recover unfinished runs", "err", err) + return + } + if n > 0 { + logger.Warn("scan: a run was cut off by the last shutdown", "runs", n) + } +} + +// scanRunning reports whether a library scan is running now: an unfinished +// run that started within StuckScanThreshold. An older unfinished run is a +// dead one, and doesn't hold anything up. +func scanRunning(ctx context.Context, q *dbq.Queries) (bool, error) { + run, err := q.GetInFlightScanRun(ctx) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + return time.Since(run.StartedAt.Time) <= StuckScanThreshold, nil +} + // TryStartScan attempts to start a new scan, with built-in handling for // stuck/stale in-flight rows. //