mirror of
https://github.com/navidrome/navidrome.git
synced 2026-08-31 07:30:32 +00:00
* feat(artwork): record the resolution trace so explain works without --live The worker never attached a ChainTrace, so `artwork explain` had to re-walk the priority chain at CLI time. That reconstruction could disagree with what actually happened, and without --live it could not report the external tier at all. The worker now traces every acquisition and stores it. `explain` reads the stored trace by default and reports when it was recorded; --live re-walks and calls the agents. Disc artwork keeps no row, so it always walks live. A chain trace alone would have explained almost nothing about failures: six of the seven ways an item can fail happen after the chain has already picked a winner. The trace now covers those stages too, and has somewhere to live when they fail: the retrying queue row carries the last failure, and the state row keeps it in last_failure once the retry budget is spent and the queue row is deleted. Measured on a copy of a 682MB / 43.6k-item library: +9.7MB (+1.4%). No row crosses the WITHOUT ROWID overflow threshold, so list hydration is unchanged; only full scans of item_artwork, which no request performs, read more pages. * test(artwork): pin the give-up ordering that keeps a failure for unresolved items recordGiveUp updates an existing row, and for a kind with a recheck path that row is only created moments earlier by the absent settle. Recording before the settle would lose the failure for every item that never resolved, with nothing to catch it. * refactor(artwork): tighten the trace code after review Four fixes worth taking: The doc comments on ChainTrace and chainState.trace still said the worker never attaches a trace and resolution stays allocation-free — the exact invariant this branch reverses. explain's report field meant both "the chain shown was walked just now" and "go out for real", and was being passed to loadPluginAgents, which --live documents as the only thing that may open external connections. Renamed to `walked` and restored explainLive as the sole input to that decision. A stored Detail is an error string on the failure paths, with no bound. The measured "no row reaches the WITHOUT ROWID overflow limit" only holds while it is bounded, so cap it at 200 runes. offlineGate was a factory returning a constant closure; make it a plain gateFunc like its sibling passthroughGate. Collapse five copies of the age-a-queue-row loop in the worker tests into one helper. * refactor(artwork): drop the offline explain walk, now that traces are stored `artwork explain` reported the external tier without calling it, so a diagnostic could not add load to a provider already rate-limiting us. Reading the stored trace answers that better: it reports what the agents actually returned, not what would be tried. Nothing could reach the offline gate any more. It was installed only for a walk with --live unset, which now happens for disc artwork alone, and disc rejects the external candidate before any gate call. That made the gate, its sentinel error, the would-try outcome and two of explain's verdicts unreachable. Removes offlineGate, errOfflineSkipped, OutcomeWouldTry, the NewTracingResolver live parameter and the CreateArtworkResolver argument threaded through wire. Verified against a copy of a real library: disc artwork with "external" first in DiscArtPriority and external services enabled still records the skip and issues no agent call. * fix(artwork): make explain's no-network guarantee structural, not incidental Serving falls back disc -> album and track -> disc -> album. The resolver layer explain uses has no such fallback today, so dropping the offline gate did not leak. But the guarantee rested on which chains happen to lack an external tier, and the serving layer already shows the fallback shape someone could mirror. Without --live the tracing resolver is now built with no agents at all, so no chain and no fallback added later can reach a provider. That is stronger than the gate it replaces, which only intercepted the call. The test pins it against exactly that regression: with the guard removed and the serving fallback mirrored into resolveDisc, it fails. * refactor(artwork): trim the trace plumbing EncodeTrace was exported for nobody: only this package writes traces, and cmd reads them. It becomes a ChainTrace method, which also drops the copy Steps made for a caller that only wanted to serialize. explain's report carried queuedSteps and failureSteps, both pure functions of the queue and state rows already in the struct, which let a test set the two out of step with each other. formatExplain derives them, as it already does for every other display value. The trace row format and its tabwriter empty-cell rule lived in two places, and the "nothing was ever recorded" predicate in three. * fix(artwork): clear the queue trace on a fresh re-enqueue Enqueue's conflict clause reset attempts to 0 but left the new trace column, so after a scan or refresh re-enqueued a previously-failed item artwork explain showed "Attempts: 0" next to the prior lifecycle's "Last attempt failed" trace. Clear trace in Enqueue (a fresh lifecycle has no last attempt); EnqueuePreservingBackoff still keeps it. * fix(artwork): treat a processing-stage error as indeterminate in explain A read/hash/decode/store failure records an OutcomeError step and writes an absent row, but explainResult only mapped external errors and unreadable candidates to indeterminate, so the default verdict read "not resolved" — presenting a processing failure as a definitive miss. The worker retries these exactly as it retries an unreadable candidate, so classify any OutcomeError as indeterminate too. * fix(artwork): record a trace step when a chainless resolver faults Playlist and radio resolvers walk no priority chain, so a fault (unreadable upload/sidecar, or an m3u fetch error with no grid) returned localError/extError without recording any trace step. The attempt then encoded [], leaving artwork explain with an empty "Last attempt failed" and "Gave up after". Record a fallback step in the faulted-no-image branch when nothing else did, and carry the source label through resolveLocalFile so the step can name it. * fix(artwork): trace the m3u failure at its source, not via the empty guard A playlist's grid sampling records album-chain steps into the shared trace, so the processor's empty-trace fallback no longer fires when the m3u remote image fetch failed — the error that forced the retry was omitted from explain. Record it where it happens, in resolvePlaylist's external step, as external:m3u. * test(artwork): skip the chainless-fault spec on Windows The spec provokes an open fault with a non-directory parent, but Windows maps that to a not-exist error, so localError is never set and the item resolves absent instead of failed. The sibling failed-on-unreadable-upload spec skips Windows for the same class of reason. * fix(artwork): don't label an absent empty-chain row as pre-tracing explain reported "resolved before traces were recorded" for any stored row with an empty chain, but an empty CoverArtPriority records a real, empty [] chain and resolves absent. A recorded resolution that finds an image always records its winning candidate, so only a row with a hash and no chain predates tracing; split on the hash and report an absent empty chain plainly instead. * fix(db): retimestamp the artwork trace migration after rebase master merged a 2026-08-18 migration, so the original 2026-08-16 timestamp is now older than the newest on the base branch and Goose would silently skip it on an already-upgraded database. Bumped past it; the SQL is unchanged. * fix(artwork): keep the m3u error detail in the trace The m3u trace step recorded OutcomeError with no detail because resolveExternalStep collapsed the gate's error to a bool, so explain showed only "external:m3u error -" and could not tell a timeout from an HTTP error or an open breaker. Return the error (normalizing not-found to nil so it stays a definitive miss, not a failure) and store its message as the step detail; encodeSteps already bounds it. * docs(artwork): note the give-up write relies on serial draining recordGiveUp writes last_failure unconditionally; that is only correct because the drain resolves each item serially, so no concurrent success can store artwork between the write and the queue delete. Record the invariant at the call site.
153 lines
4.5 KiB
Go
153 lines
4.5 KiB
Go
package artwork
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"slices"
|
|
"sync"
|
|
|
|
"github.com/navidrome/navidrome/utils/str"
|
|
)
|
|
|
|
// Outcome is what the priority chain observed for one candidate; the CLI renders and branches on these.
|
|
type Outcome string
|
|
|
|
const (
|
|
OutcomeHit Outcome = "hit"
|
|
OutcomeMiss Outcome = "miss"
|
|
OutcomeUnreadable Outcome = "unreadable"
|
|
OutcomeSkipped Outcome = "skipped"
|
|
OutcomeError Outcome = "error"
|
|
)
|
|
|
|
const (
|
|
// externalCandidate labels the external tier itself, for the cases that never reach an agent.
|
|
externalCandidate = "external"
|
|
// ExternalPrefix qualifies a candidate or a stored source with the agent that produced it.
|
|
ExternalPrefix = externalCandidate + ":"
|
|
)
|
|
|
|
// TraceStep is one candidate the priority chain considered.
|
|
type TraceStep struct {
|
|
Candidate string
|
|
Outcome Outcome
|
|
Detail string
|
|
}
|
|
|
|
// ChainTrace collects the walk of a single resolution: the worker attaches one per queue
|
|
// item so it can be stored, and the CLI attaches one per explain.
|
|
type ChainTrace struct {
|
|
mu sync.Mutex
|
|
steps []TraceStep
|
|
}
|
|
|
|
func (t *ChainTrace) add(step TraceStep) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
t.steps = append(t.steps, step)
|
|
}
|
|
|
|
func (t *ChainTrace) Steps() []TraceStep {
|
|
if t == nil {
|
|
return nil
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
return slices.Clone(t.steps)
|
|
}
|
|
|
|
// maxTraceDetail bounds a stored Detail, which on the failure paths is an error string of
|
|
// unknown length. Past ~1kB a row spills to an overflow page, slowing every scan of the table.
|
|
const maxTraceDetail = 200
|
|
|
|
// storedStep is the persisted shape of a TraceStep. The keys are single letters because a trace
|
|
// is written for every item, and the encoded length is repeated across the whole library.
|
|
type storedStep struct {
|
|
C string `json:"c"`
|
|
O Outcome `json:"o"`
|
|
D string `json:"d,omitempty"`
|
|
}
|
|
|
|
// encode serializes the trace for storage, without the copy Steps would make for a caller
|
|
// that only wants to write it.
|
|
func (t *ChainTrace) encode(sourcePath string) string {
|
|
if t == nil {
|
|
return encodeSteps(nil, sourcePath)
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
return encodeSteps(t.steps, sourcePath)
|
|
}
|
|
|
|
// encodeSteps writes the stored form. A hit's Detail is the winning source's path, which the
|
|
// same row already stores as source_path, so it is dropped and DecodeTrace puts it back.
|
|
func encodeSteps(steps []TraceStep, sourcePath string) string {
|
|
out := make([]storedStep, 0, len(steps))
|
|
for _, s := range steps {
|
|
d := s.Detail
|
|
if s.Outcome == OutcomeHit && d == sourcePath {
|
|
d = ""
|
|
}
|
|
out = append(out, storedStep{C: s.Candidate, O: s.Outcome, D: str.TruncateRunes(d, maxTraceDetail, "...")})
|
|
}
|
|
b, _ := json.Marshal(out) // []storedStep is all strings, so this cannot fail
|
|
return string(b)
|
|
}
|
|
|
|
// DecodeTrace reverses the stored form. A trace that will not parse is reported as no trace at all,
|
|
// since a diagnostic command must not fail on a bad row.
|
|
func DecodeTrace(encoded, sourcePath string) []TraceStep {
|
|
if encoded == "" {
|
|
return nil
|
|
}
|
|
var stored []storedStep
|
|
if err := json.Unmarshal([]byte(encoded), &stored); err != nil {
|
|
return nil
|
|
}
|
|
steps := make([]TraceStep, 0, len(stored))
|
|
for _, s := range stored {
|
|
d := s.D
|
|
if d == "" && s.O == OutcomeHit {
|
|
d = sourcePath
|
|
}
|
|
steps = append(steps, TraceStep{Candidate: s.C, Outcome: s.O, Detail: d})
|
|
}
|
|
return steps
|
|
}
|
|
|
|
type traceCtxKey struct{}
|
|
|
|
func withTrace(ctx context.Context, t *ChainTrace) context.Context {
|
|
return context.WithValue(ctx, traceCtxKey{}, t)
|
|
}
|
|
|
|
func traceFrom(ctx context.Context) *ChainTrace {
|
|
t, _ := ctx.Value(traceCtxKey{}).(*ChainTrace)
|
|
return t
|
|
}
|
|
|
|
// recordAgent files what one external agent answered. The agent loops call this rather than a
|
|
// gate wrapper, because only they hold the context that carries the trace.
|
|
func recordAgent(ctx context.Context, name string, r io.ReadCloser, path string, err error) {
|
|
t := traceFrom(ctx)
|
|
candidate := ExternalPrefix + name
|
|
switch {
|
|
case r != nil:
|
|
t.add(TraceStep{Candidate: candidate, Outcome: OutcomeHit, Detail: path})
|
|
case isTransientExternal(err):
|
|
t.add(TraceStep{Candidate: candidate, Outcome: OutcomeError, Detail: err.Error()})
|
|
default:
|
|
t.add(TraceStep{Candidate: candidate, Outcome: OutcomeMiss})
|
|
}
|
|
}
|
|
|
|
// traceStage records a failure from the stages that run after the priority chain has already
|
|
// picked a winner: most ways an item can fail are here, not in the chain walk.
|
|
func traceStage(ctx context.Context, stage string, err error) {
|
|
traceFrom(ctx).add(TraceStep{Candidate: stage, Outcome: OutcomeError, Detail: err.Error()})
|
|
}
|