fix(server): a background job that panics no longer stops the server (#8002)
release / go (push) Successful in 2m6s
release / web (push) Successful in 1m25s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m18s
release / android (push) Successful in 4m19s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 30s
release / Verify release artifacts (tag releases only) (push) Skipped

Background jobs run in their own goroutines, outside the router's panic
recovery, and only five of them recovered. A panic in the scrobble,
similarity, co-play, gc, tags, compactor, notification, backup or
safety-net loop, or in a scan or rebuild started off a request, ended
the process and every stream in it.

internal/periodic now runs each job: a pass at start (or after one
interval, Delayed), then one per interval and on any WakeOn channel,
each pass under recover with the stack logged. Detached one-shot work
(scans, the lazy system-playlist build, bulk cover refetch, leveled
prerender, the backup run, the playlist catch-up) runs under
periodic.Safe. The duplicate resolver keeps its own loop for its
retry-soon timer, and its pass already recovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:38:56 -05:00
co-authored by Claude Opus 5.5
parent 9b36effbaf
commit 125099ede2
21 changed files with 281 additions and 206 deletions
+86
View File
@@ -0,0 +1,86 @@
// Package periodic runs the server's background jobs: a pass now, then one
// per interval until the server shuts down.
//
// Every pass runs under recover. These jobs run in their own goroutines,
// outside the HTTP router's panic recovery, so without it one bad row that
// panics a pass would stop the whole server, streams in progress included.
// A pass that panics is logged and the next one starts on schedule.
package periodic
import (
"context"
"log/slog"
"runtime/debug"
"time"
)
type config struct {
delayed bool
wake []<-chan struct{}
}
// Option changes when a job's passes run.
type Option func(*config)
// Delayed skips the pass at start: the first one runs after one interval.
// For jobs that would otherwise all hit the network or the database in the
// same second as the server comes up.
func Delayed() Option { return func(c *config) { c.delayed = true } }
// WakeOn also runs a pass whenever one of chs receives, such as an admin's
// "run now" or a settings change. A nil channel never wakes the job.
func WakeOn(chs ...<-chan struct{}) Option {
return func(c *config) { c.wake = append(c.wake, chs...) }
}
// Run calls pass now (unless Delayed) and then once every interval, until
// ctx ends. It blocks, so start it with `go`. name labels the job in the log.
func Run(ctx context.Context, logger *slog.Logger, name string, every time.Duration,
pass func(context.Context), opts ...Option,
) {
var c config
for _, o := range opts {
o(&c)
}
// Up to two wake channels, as a select needs them by name. More than
// that is a sign the job wants its own loop.
var wake1, wake2 <-chan struct{}
if len(c.wake) > 0 {
wake1 = c.wake[0]
}
if len(c.wake) > 1 {
wake2 = c.wake[1]
}
if len(c.wake) > 2 {
panic("periodic.Run: at most two wake channels")
}
if !c.delayed {
Safe(ctx, logger, name, pass)
}
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
case <-wake1:
case <-wake2:
}
if ctx.Err() != nil {
return
}
Safe(ctx, logger, name, pass)
}
}
// Safe calls pass once and turns a panic into an error in the log, with the
// stack, so the caller carries on.
func Safe(ctx context.Context, logger *slog.Logger, name string, pass func(context.Context)) {
defer func() {
if r := recover(); r != nil {
logger.Error(name+": pass panicked", "panic", r, "stack", string(debug.Stack()))
}
}()
pass(ctx)
}
+109
View File
@@ -0,0 +1,109 @@
package periodic
import (
"bytes"
"context"
"log/slog"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// syncBuffer lets the job's goroutine log while the test reads.
type syncBuffer struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuffer) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuffer) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(time.Millisecond)
}
}
func TestRun_APanickingPassDoesNotStopTheNext(t *testing.T) {
var logs syncBuffer
logger := slog.New(slog.NewTextHandler(&logs, nil))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var passes atomic.Int32
done := make(chan struct{})
go func() {
Run(ctx, logger, "test job", 5*time.Millisecond, func(context.Context) {
if passes.Add(1) == 1 {
panic("boom")
}
})
close(done)
}()
waitFor(t, "a second pass after the panic", func() bool { return passes.Load() >= 2 })
if !strings.Contains(logs.String(), "test job: pass panicked") {
t.Fatalf("the panic was not logged; log: %s", logs.String())
}
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("Run did not return after cancel")
}
}
func TestRun_FirstPassTiming(t *testing.T) {
logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil))
for _, tc := range []struct {
name string
opts []Option
atStart bool
}{
{"runs at start by default", nil, true},
{"waits an interval when delayed", []Option{Delayed()}, false},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var passes atomic.Int32
go Run(ctx, logger, "test job", time.Hour, func(context.Context) { passes.Add(1) }, tc.opts...)
if tc.atStart {
waitFor(t, "the first pass", func() bool { return passes.Load() == 1 })
return
}
time.Sleep(50 * time.Millisecond)
if n := passes.Load(); n != 0 {
t.Fatalf("a delayed job ran %d passes before its first interval", n)
}
})
}
}
func TestRun_WakeOnRunsAPassBeforeTheInterval(t *testing.T) {
logger := slog.New(slog.NewTextHandler(&bytes.Buffer{}, nil))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
kick := make(chan struct{}, 1)
var passes atomic.Int32
go Run(ctx, logger, "test job", time.Hour, func(context.Context) { passes.Add(1) },
Delayed(), WakeOn(kick, nil))
kick <- struct{}{}
waitFor(t, "a pass on the kick", func() bool { return passes.Load() == 1 })
}