Files
silo-server/internal/worker/cleanup.go
T
a4402d4621 fix(playback): stop seek-restart churn and premature paused-session reaping (#279)
* fix(playback): stop seek-restart churn and premature paused-session reaping

Two latent defects (present since the initial migration) explain the
cross-client freezes on resume-after-pause, intro-skip, and manual seek
reported in #243:

1. Dueling transcode restarts. TranscodeSession.Restart had no
   concurrency guard, and SegmentRecoveryDecision told concurrent
   segment requests to restart again while a restart was already in
   flight (the restart window runs with running=false, so requests hit
   the restart-happy transcode_not_running branch before the Restarting
   check). Pipelined HLS segment requests therefore spawned restarts
   that kept killing the ffmpeg the player was waiting on — a 30s stall
   and another restart, surfacing as buffer-then-freeze. Restart is now
   single-flight and the recovery decision waits out an in-flight
   restart (WaitForSegment already polls politely through one).

2. Paused sessions were reaped after 2 minutes, killing the transcode
   with no revival path — every resume request then 404s. Clients that
   stop progress reporting while paused (tvOS; backgrounded web tabs)
   froze on play after a >5 minute pause. Paused grace is now 30
   minutes in both the in-memory session manager and the DB session
   cleaner.

Also unifies post-restart re-arming: the throttler and exit monitor are
re-armed via a restart hook installed at session creation and fired by
Restart itself, so the jellycompat seek path (which previously re-armed
nothing) and the audio-switch path (which re-armed only the throttler)
now behave identically to web segment recovery.

Follow-up (not in this PR): lazily revive a reaped session's transcode
on resume instead of 404ing, so even multi-hour pauses recover.

Fixes #243

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs(playback): scope the restart-hook comment to handler-created sessions

The comment above SetRestartHook claimed the hook covers restarts from
'jellycompat seek', but jellycompat creates its own TranscodeSessions via
playback.StartTranscode in a separate registry and calls Restart directly;
those sessions never get the hook and never had throttler/exit-monitor
wiring to re-arm. Reword the comment (and the matching test comment) to
scope the guarantee to handler-created sessions.

Also fix TestRestartInvokesRestartHook to resolve `true` via PATH instead
of hardcoding /bin/true, which does not exist on macOS.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
2026-07-02 14:06:25 -04:00

212 lines
7.0 KiB
Go

package worker
import (
"context"
"fmt"
"log/slog"
"sync"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Silo-Server/silo-server/internal/cache"
evt "github.com/Silo-Server/silo-server/internal/events"
)
const (
// nodeDeadTimeout is how long a node can go without a heartbeat before
// its sessions are purged.
nodeDeadTimeout = 45 * time.Second
// nodeHeartbeatCleanup is how long before stale heartbeat rows
// themselves are deleted (longer than nodeDeadTimeout to avoid flapping).
nodeHeartbeatCleanup = 5 * time.Minute
// activeSessionGrace is the staleness threshold for active (not paused)
// sessions based on last_sync_at.
activeSessionGrace = 45 * time.Second
// pausedSessionGrace is the staleness threshold for paused sessions.
// Must comfortably cover an intentional pause: reaping kills the
// transcode with no revival path (issue #243). Keep in sync with
// playback.DefaultPausedSessionGrace.
pausedSessionGrace = 30 * time.Minute
// cleanupInterval is how often the cleanup ticker fires.
cleanupInterval = 15 * time.Second
// absStaleOpenSessionGrace closes audiobook playback sessions that stopped
// syncing without an explicit /close (abandoned playback) so they don't
// linger as "open" forever and inflate listening-stats aggregation.
absStaleOpenSessionGrace = 24 * time.Hour
// absSessionPruneInterval throttles the abandoned-session sweep: it's a slow-moving
// concern, so it runs hourly rather than on every 15s cleanup tick.
absSessionPruneInterval = time.Hour
)
// SessionCleaner removes stale playback sessions and dead node records.
type SessionCleaner struct {
pool *pgxpool.Pool
EventBus cache.EventBus
EventsHub *evt.Hub
stop chan struct{}
// lastABSSessionPrune gates the hourly abs_playback_sessions retention
// sweep. Guarded by absPruneMu because CleanStale is also invoked from the
// shutdown path while the ticker goroutine is still running.
absPruneMu sync.Mutex
lastABSSessionPrune time.Time
}
// NewSessionCleaner creates a SessionCleaner. The graceSeconds parameter is
// accepted for backwards compatibility but ignored — grace periods are now
// fixed at 45s (active) and 2m (paused).
func NewSessionCleaner(pool *pgxpool.Pool, graceSeconds int) *SessionCleaner {
return &SessionCleaner{
pool: pool,
stop: make(chan struct{}),
}
}
// Start begins the background cleanup loop, firing every 15 seconds.
func (c *SessionCleaner) Start() {
go func() {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for {
select {
case <-c.stop:
return
case <-ticker.C:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if deleted, err := c.CleanStale(ctx); err != nil {
slog.Error("session cleanup error", "error", err)
} else if deleted > 0 {
slog.Debug("cleaned stale sessions", "count", deleted)
}
cancel()
}
}
}()
}
// Stop signals the cleanup loop to stop.
func (c *SessionCleaner) Stop() {
close(c.stop)
}
// CleanStale performs a full cleanup pass:
// 1. Purge sessions from dead nodes (heartbeat stale > 45s)
// 2. Remove stale heartbeat rows (> 5 minutes)
// 3. Remove stale active sessions (last_sync_at > 45s)
// 4. Remove stale paused sessions (last_sync_at > 2 minutes)
func (c *SessionCleaner) CleanStale(ctx context.Context) (int, error) {
var totalDeleted int64
// 1. Purge sessions belonging to dead nodes.
tag, err := c.pool.Exec(ctx, `
DELETE FROM playback_sessions_sync
WHERE reporting_node IN (
SELECT node_id FROM node_heartbeats
WHERE updated_at < NOW() - make_interval(secs => $1::double precision)
)
`, nodeDeadTimeout.Seconds())
if err != nil {
return 0, fmt.Errorf("purging dead node sessions: %w", err)
}
totalDeleted += tag.RowsAffected()
// 2. Clean up stale heartbeat rows.
if _, err := c.pool.Exec(ctx, `
DELETE FROM node_heartbeats
WHERE updated_at < NOW() - make_interval(secs => $1::double precision)
`, nodeHeartbeatCleanup.Seconds()); err != nil {
return int(totalDeleted), fmt.Errorf("cleaning stale heartbeats: %w", err)
}
// 3. Active sessions: 45s grace on last_sync_at.
tag, err = c.pool.Exec(ctx, `
DELETE FROM playback_sessions_sync
WHERE is_paused = FALSE
AND last_sync_at < NOW() - make_interval(secs => $1::double precision)
`, activeSessionGrace.Seconds())
if err != nil {
return int(totalDeleted), fmt.Errorf("cleaning stale active sessions: %w", err)
}
totalDeleted += tag.RowsAffected()
// 4. Paused sessions: 2 minute grace on last_sync_at.
tag, err = c.pool.Exec(ctx, `
DELETE FROM playback_sessions_sync
WHERE is_paused = TRUE
AND last_sync_at < NOW() - make_interval(secs => $1::double precision)
`, pausedSessionGrace.Seconds())
if err != nil {
return int(totalDeleted), fmt.Errorf("cleaning stale paused sessions: %w", err)
}
totalDeleted += tag.RowsAffected()
// 5. Audiobook session cleanup (hourly): close abandoned open sessions.
// Closed rows are retained because the ABS stats endpoint currently has
// all-time semantics and aggregates directly from abs_playback_sessions.
// Kept off totalDeleted so it doesn't trigger the live-session
// invalidation event. The due-check is mutex-guarded so the shutdown-path
// CleanStale and the ticker can't race or double-run it.
c.absPruneMu.Lock()
pruneStartedAt := time.Now()
previousABSSessionPrune := c.lastABSSessionPrune
abndPruneDue := pruneStartedAt.Sub(c.lastABSSessionPrune) >= absSessionPruneInterval
if abndPruneDue {
c.lastABSSessionPrune = pruneStartedAt
}
c.absPruneMu.Unlock()
if abndPruneDue {
if err := c.closeAbandonedABSSessions(ctx); err != nil {
slog.Warn("abs session cleanup failed", "error", err)
c.absPruneMu.Lock()
if c.lastABSSessionPrune.Equal(pruneStartedAt) {
c.lastABSSessionPrune = previousABSSessionPrune
}
c.absPruneMu.Unlock()
}
}
if totalDeleted > 0 && c.EventsHub != nil {
if err := c.EventsHub.PublishJSON(
ctx,
evt.ChannelSessions,
"sessions.replaced",
nil,
evt.PublishOptions{AdminOnly: true},
); err != nil {
return int(totalDeleted), fmt.Errorf("publishing playback cleanup invalidation: %w", err)
}
} else if c.EventBus != nil && totalDeleted > 0 {
if err := c.EventBus.Publish(ctx, cache.ChannelPlayback, cache.Event{
Type: cache.EventPlaybackSessionsChanged,
Payload: "cleanup",
}); err != nil {
return int(totalDeleted), fmt.Errorf("publishing playback cleanup invalidation: %w", err)
}
}
return int(totalDeleted), nil
}
// closeAbandonedABSSessions closes abandoned audiobook playback sessions (no
// explicit /close, stopped syncing). It intentionally does not delete closed
// sessions: AggregateStats currently uses this table for all-time totals.
func (c *SessionCleaner) closeAbandonedABSSessions(ctx context.Context) error {
if _, err := c.pool.Exec(ctx, `
UPDATE abs_playback_sessions
SET closed_at = now()
WHERE closed_at IS NULL
AND COALESCE(last_sync_at, started_at) < NOW() - make_interval(secs => $1::double precision)
`, absStaleOpenSessionGrace.Seconds()); err != nil {
return fmt.Errorf("closing abandoned abs sessions: %w", err)
}
return nil
}