Skip to content

fix(jellycompat): sync activity dashboard immediately on compat playback start/stop - #261

Merged
Quick104 merged 3 commits into
mainfrom
fix/issue-205-activity-dashboard-session-state
Jul 2, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/issue-205-activity-dashboard-session-state

Conversation

@Quick104

@Quick104 Quick104 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Issue #205 reports two activity-dashboard accuracy bugs:

  1. Infuse (Jellyfin-compat) sessions linger after stop. Compat playback sessions are mirrored into the in-memory SessionManager, but the shared playback_sessions_sync table the dashboard reads is only reconciled on the 15-second reconciler tick. Native playback handlers trigger an immediate SessionSyncer.SyncNow on start/stop; the jellycompat handler never did. So a stopped Infuse stream stayed in the dashboard until the next tick, and starting a new item during that window showed two "simultaneous" playbacks (one being the ghost of the stopped session) — exactly the reported behavior.
  2. Mobile audiobook sessions never appear. Already fixed on main by [codex] Mirror ABS playback into live sessions #203 (merged 2026-06-26, one day after the issue's code-verification note), which mirrors ABS playback into native sessions with immediate syncs. Not re-fixed here.

Reproduced (1) by code-path analysis: teardownPlaySession (internal/jellycompat/streams.go) stops the in-memory session but nothing flushes playback_sessions_sync, whose rows for a node are replaced only by Reconciler on its 15 s ticker — while the native handlers (internal/api/handlers/playback.go) call syncSessionsNow on every start/stop. Regression tests in streams_test.go fail without the fix.

Approach

Extend the existing native-handler pattern to jellycompat rather than inventing a new mechanism:

  • Add a PlaybackSessionSyncer dependency to the jellycompat PlaybackHandler (wired to the same worker.Reconciler the native handlers use).
  • Flush immediately after teardownPlaySession (both the /Sessions/Playing/Stopped report and DELETE /Videos/ActiveEncodings) and after a new upstream session starts in ensureUpstreamPlayback. Progress reports intentionally do not sync (the periodic tick covers position updates; syncing every ~10 s report per client would add DB churn for no dashboard-accuracy gain).
  • Stop-path syncs run under context.WithoutCancel + a 5 s deadline: clients often drop the connection right after reporting a stop, and a stalled DB must degrade to the periodic tick instead of pinning request goroutines.
  • Hardened Reconciler.SyncNow (pre-existing exposure, made more visible by adding call sites): syncs are now coalesced — one owner reconciles at a time, callers arriving mid-flight return immediately after flagging a follow-up pass, and the owner re-captures a fresh snapshot afterwards. This guarantees snapshots commit in capture order (no resurrected stopped sessions / dropped fresh ones) and that request goroutines never queue behind a slow sync.

Also adds the ListProgressSince method to the progressCountingStore test fake in internal/jellycompat/content_direct_test.go — the downloads-v2 interface change (#258) left the package's tests uncompilable, which blocked verifying this change. The same break exists in internal/access/resolver_test.go; left out of scope (flagged separately).

Verification

  • GOWORK=off go build ./... — clean (with stubbed web/dist).
  • GOWORK=off go test ./internal/jellycompat/ — all pass except TestBeginWebOperationRecoversDeadProcessLock / TestBeginWebOperationRejectsLiveProcessLock, which are pre-existing environment-specific failures (process-lock pid probing, unrelated to this diff; the package didn't even compile on main because of the feat(downloads): offline sync for mobile — downloads v2 #258 fake break).
  • GOWORK=off go test ./internal/worker/ -race — pass, including new TestSyncNowSerializesSnapshotCapture and TestSyncNowCoalescesPendingPass.
  • New regression tests: stop report tears down and syncs immediately (with a canceled request context, proving detachment, and asserting a deadline is present); no sync on unknown-session stops; ActiveEncodings teardown syncs; new upstream start syncs once and reuse doesn't re-sync.
  • golangci-lint (v2, --new-from-rev origin/main): 0 new issues (the one reported typecheck hit is the pre-existing feat(downloads): offline sync for mobile — downloads v2 #258 fake break in internal/access, untouched here).
  • make verify-local-paths — clean.

Adversarial review

Codex adversarial review, 3 iterations, final verdict approve — no material findings:

  • Iter 1 (high): concurrent SyncNow calls could commit stale full-node snapshots out of order → fixed via serialization, then (iter 2, high) queueing on a bare mutex could let a stop-sync expire waiting behind a slow tick → fixed via the coalescing owner/pending design above, with race-enabled regression tests.
  • Iter 1 (medium): context.WithoutCancel sync was unbounded → fixed with a 5 s deadline on request-path syncs.

Risks & follow-up

  • Stop/start requests now do a bounded synchronous DB reconcile (same behavior the native playback endpoints have had); worst case they add ≤5 s latency during DB trouble, after which the periodic tick remains the backstop. Non-owner callers return instantly.
  • No API surface changes; no client (silo-android / silo-apple) follow-up needed — this only affects the admin dashboard's freshness.
  • Pre-existing feat(downloads): offline sync for mobile — downloads v2 #258 test-fake break in internal/access/resolver_test.go still stands (separate task flagged).

Closes #205

AI-use disclosure

Implemented by Claude Code (issue-to-pr skill) with human oversight.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Playback activity now updates immediately when media starts or stops, so session status appears faster and stays more accurate.
    • Session updates are better coordinated during playback, reducing delays in live activity displays.
  • Bug Fixes

    • Fixed cases where playback changes could be missed if a connection ended quickly.
    • Improved handling of concurrent updates so repeated status refreshes are merged instead of conflicting.

Quick104 and others added 3 commits July 2, 2026 00:04
…ack start/stop

Compat (Infuse/Jellyfin) sessions were only reconciled into
playback_sessions_sync on the periodic 15s reconciler tick, so stopped
streams lingered in the admin activity dashboard and overlapped with
newly started ones as ghost sessions. Native playback handlers already
trigger an immediate SessionSyncer.SyncNow on start/stop; wire the same
syncer into the jellycompat playback handler and flush after
teardownPlaySession (Stopped report + ActiveEncodings teardown) and
after a new upstream session starts.

The stop-path sync detaches from request cancellation
(context.WithoutCancel) because clients often drop the connection right
after reporting a stop.

Also adds the ListProgressSince method to the jellycompat test fake so
the package's tests compile again after the downloads-v2 interface
change.

Part of #205

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…sync

Adversarial review follow-ups: SyncNow snapshots could commit out of
order when request-path syncs raced the periodic tick (an older
snapshot committing last would resurrect stopped sessions or drop
fresh ones), and the detached stop-path sync had no deadline, letting
a stalled DB pin request goroutines. Serialize snapshot capture +
reconcile under one lock and cap request-path syncs at 5s so failures
degrade to the periodic tick.

Part of #205

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…a lock

Review iteration 2: a stop-triggered sync queued on a bare mutex could
expire its 5s deadline waiting behind a slow tick and fail before
removing the stopped row. Coalesce instead: one owner reconciles at a
time, callers that arrive mid-flight return immediately after flagging
a follow-up pass, and the owner re-captures a fresh (post-change)
snapshot afterwards. Request goroutines never block behind another
sync, snapshots still commit in capture order, and an expired-context
owner leaves the queued pass for the next tick instead of burning it.

Part of #205

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a PlaybackSessionSyncer interface and wires an optional SessionSyncer dependency through jellycompat's Dependencies, PlaybackHandler, router, and main.go. Compat playback teardown and start paths now trigger immediate admin-session sync via a new syncSessionsNow helper. The worker Reconciler.SyncNow is rewritten to serialize and coalesce concurrent calls.

Changes

Immediate session sync

Layer / File(s) Summary
PlaybackSessionSyncer interface and dependency wiring
internal/jellycompat/handlers_playback.go, internal/jellycompat/server.go, internal/jellycompat/router.go, cmd/silo/main.go
Defines PlaybackSessionSyncer with SyncNow(ctx) error, adds optional SessionSyncer fields to PlaybackHandler and Dependencies, and wires the dependency through the router and main.go.
Immediate sync on teardown and playback start
internal/jellycompat/streams.go, internal/jellycompat/streams_test.go, internal/jellycompat/content_direct_test.go
Adds syncSessionsNow helper and compatSessionSyncTimeout, updates teardownPlaySession to accept context and trigger a detached sync, updates stop/delete call sites, triggers sync on ensureUpstreamPlayback start, and adds tests verifying sync-call counts and context handling.
Reconciler SyncNow serialization and coalescing
internal/worker/reconciler.go, internal/worker/reconciler_test.go
Adds locking/pending state to Reconciler, rewrites SyncNow to prevent overlapping runs and coalesce a follow-up pass via a new syncOnce helper, with concurrency tests validating serialization and coalescing.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant InfuseClient
  participant PlaybackHandler
  participant teardownPlaySession
  participant SessionSyncer
  participant Reconciler

  InfuseClient->>PlaybackHandler: stop report / DELETE ActiveEncodings
  PlaybackHandler->>teardownPlaySession: teardownPlaySession(ctx, session)
  teardownPlaySession->>SessionSyncer: syncSessionsNow(detached ctx, timeout)
  SessionSyncer->>Reconciler: SyncNow(ctx)
  alt sync already running
    Reconciler-->>SessionSyncer: mark pending, return immediately
    Reconciler->>Reconciler: run follow-up syncOnce after current pass
  else no sync in-flight
    Reconciler->>Reconciler: syncOnce(ctx) captures snapshot and reconciles
  end
  Reconciler-->>SessionSyncer: complete or error logged
Loading

Possibly related PRs

  • Silo-Server/silo-server#159: Directly related to the same teardownPlaySession logic in internal/jellycompat/streams.go, which this PR further modifies to accept a context and trigger immediate sync.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: immediate jellycompat dashboard sync on playback start/stop.
Linked Issues check ✅ Passed The changes address the Infuse lingering-session bug by syncing compat start/stop events immediately, matching the issue's expected dashboard behavior.
Out of Scope Changes check ✅ Passed The additional reconciler coalescing and test-fake compatibility updates support the sync fix and do not appear unrelated to the issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/issue-205-activity-dashboard-session-state

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/jellycompat/streams.go (1)

864-930: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Start-path sync is not detached from request cancellation, unlike the stop path.

teardownPlaySession wraps ctx with context.WithoutCancel before syncing (Line 753) specifically because "clients often drop the connection right after reporting a stop." The same client behavior applies to the start path: the manifest/PlaybackInfo request context can be canceled by the client shortly after ensureUpstreamPlayback finishes committing the new session to h.playbackStore (Lines 917-928), but before syncSessionsNow runs at Line 929. Since syncSessionsNow wraps the passed context with context.WithTimeout(ctx, ...), a canceled parent ctx immediately cancels the sync too — the freshly-started session is fully committed locally but the immediate dashboard sync silently fails (logged, not surfaced), reintroducing the exact "ghost/stale session" symptom this PR fixes for the stop path, just on session start instead.

🐛 Proposed fix for consistency with the stop path
-	h.syncSessionsNow(ctx, "compat_start")
+	// Detach from request cancellation for the same reason as the stop path:
+	// the client may disconnect immediately after the session is committed.
+	h.syncSessionsNow(context.WithoutCancel(ctx), "compat_start")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/jellycompat/streams.go` around lines 864 - 930, The start path in
ensureUpstreamPlayback is still tied to the request context, so a client
disconnect can cancel the follow-up sync after the session is already committed
in playbackStore. Detach the sync from cancellation the same way
teardownPlaySession does by using a cancellation-independent context when
calling syncSessionsNow, and keep the change localized to
ensureUpstreamPlayback/syncSessionsNow so the newly started session is always
propagated consistently.
🧹 Nitpick comments (1)
internal/worker/reconciler.go (1)

446-489: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Follow-up coalesced pass reuses the original owner's (possibly short-lived) context.

The for loop always calls r.syncOnce(ctx) using the initial caller's context (Line 485), even for follow-up passes requested by a different, later caller. When the sync "owner" happens to be a compat request-path trigger (syncSessionsNow bounds it to 5s, per internal/jellycompat/streams.go), a follow-up pass requested near the end of that 5s window will be dropped via ctx.Err() != nil (Line 478) and deferred to "the periodic tick at the latest," per the comment. This is a documented, intentional tradeoff, but it means the "immediate" sync guarantee this PR is meant to deliver can silently degrade to periodic-tick latency specifically when the owner is a short-lived compat sync rather than the 15s tick — the exact scenario (rapid stop/start) most likely to trigger coalescing in practice.

Consider giving follow-up passes their own independent bounded context (e.g., a fixed internal timeout) instead of inheriting the owner's, so a short caller-supplied deadline doesn't truncate work requested by unrelated callers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/worker/reconciler.go` around lines 446 - 489, The follow-up
coalesced reconciliation in Reconciler.SyncNow is reusing the original caller’s
context, so later requested passes can be cut short by a short-lived owner
deadline. Update the SyncNow loop to give follow-up syncOnce calls their own
independent bounded internal timeout instead of always passing the initial ctx,
while keeping the syncPending/syncRunning coalescing behavior intact. Use the
Reconciler.SyncNow and syncOnce flow to locate the change, and preserve the
existing “only one reconciliation runs at a time” semantics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/jellycompat/streams.go`:
- Around line 864-930: The start path in ensureUpstreamPlayback is still tied to
the request context, so a client disconnect can cancel the follow-up sync after
the session is already committed in playbackStore. Detach the sync from
cancellation the same way teardownPlaySession does by using a
cancellation-independent context when calling syncSessionsNow, and keep the
change localized to ensureUpstreamPlayback/syncSessionsNow so the newly started
session is always propagated consistently.

---

Nitpick comments:
In `@internal/worker/reconciler.go`:
- Around line 446-489: The follow-up coalesced reconciliation in
Reconciler.SyncNow is reusing the original caller’s context, so later requested
passes can be cut short by a short-lived owner deadline. Update the SyncNow loop
to give follow-up syncOnce calls their own independent bounded internal timeout
instead of always passing the initial ctx, while keeping the
syncPending/syncRunning coalescing behavior intact. Use the Reconciler.SyncNow
and syncOnce flow to locate the change, and preserve the existing “only one
reconciliation runs at a time” semantics.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0e6ba26d-e923-4dbd-9d62-92f7b63913dc

📥 Commits

Reviewing files that changed from the base of the PR and between 46a6e86 and 32d549a.

📒 Files selected for processing (9)
  • cmd/silo/main.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/jellycompat/streams_test.go
  • internal/worker/reconciler.go
  • internal/worker/reconciler_test.go

@Quick104
Quick104 merged commit e5d4e84 into main Jul 2, 2026
2 checks passed
@Quick104
Quick104 deleted the fix/issue-205-activity-dashboard-session-state branch July 2, 2026 14:07
Quick104 added a commit that referenced this pull request Jul 2, 2026
Resolves overlap with #261 (immediate activity-dashboard sync on compat
start/stop): the Stopped-report teardown keeps this branch's
route-ambiguity gate and adopts #261's context-taking
teardownPlaySession; ensureUpstreamPlayback keeps the CAS attach and
fires syncSessionsNow only on a successful attach (the CAS loser adopts
a winner that already synced). Both branches' identical
ListProgressSince test-fake fixes converged.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…ack start/stop (Silo-Server#261)

* fix(jellycompat): sync activity dashboard immediately on compat playback start/stop

Compat (Infuse/Jellyfin) sessions were only reconciled into
playback_sessions_sync on the periodic 15s reconciler tick, so stopped
streams lingered in the admin activity dashboard and overlapped with
newly started ones as ghost sessions. Native playback handlers already
trigger an immediate SessionSyncer.SyncNow on start/stop; wire the same
syncer into the jellycompat playback handler and flush after
teardownPlaySession (Stopped report + ActiveEncodings teardown) and
after a new upstream session starts.

The stop-path sync detaches from request cancellation
(context.WithoutCancel) because clients often drop the connection right
after reporting a stop.

Also adds the ListProgressSince method to the jellycompat test fake so
the package's tests compile again after the downloads-v2 interface
change.

Part of Silo-Server#205

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(worker): serialize SyncNow and bound compat request-path session sync

Adversarial review follow-ups: SyncNow snapshots could commit out of
order when request-path syncs raced the periodic tick (an older
snapshot committing last would resurrect stopped sessions or drop
fresh ones), and the detached stop-path sync had no deadline, letting
a stalled DB pin request goroutines. Serialize snapshot capture +
reconcile under one lock and cap request-path syncs at 5s so failures
degrade to the periodic tick.

Part of Silo-Server#205

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(worker): coalesce immediate session syncs instead of queueing on a lock

Review iteration 2: a stop-triggered sync queued on a bare mutex could
expire its 5s deadline waiting behind a slow tick and fail before
removing the stopped row. Coalesce instead: one owner reconciles at a
time, callers that arrive mid-flight return immediately after flagging
a follow-up pass, and the owner re-captures a fresh (post-change)
snapshot afterwards. Request goroutines never block behind another
sync, snapshots still commit in capture order, and an expired-context
owner leaves the queued pass for the next tick instead of burning it.

Part of Silo-Server#205

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Server activity dashboard misreports stream state (Infuse lingering, mobile audiobooks missing)

1 participant