Skip to content

fix(jellycompat): keep still-playing direct-play sessions in the activity view - #262

Merged
Quick104 merged 6 commits into
mainfrom
fix/issue-244-activity-view-session-drop
Jul 2, 2026
Merged

Quick104 merged 6 commits into
mainfrom
fix/issue-244-activity-view-session-drop

Conversation

@Quick104

@Quick104 Quick104 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

An Infuse client playing via jellycompat Static=true direct play freezes its playback-time indicator in the admin Activity View, then vanishes from the view entirely while still playing (#244, screen recording in the issue). Reproduced with tests that fail on current main (see Verification). Three compounding defects in internal/jellycompat:

  1. Progress reports silently no-op'd. Static=true direct play skips PlaybackInfo, so Infuse reports progress under its own client-generated PlaySessionId. handlePlaybackReport resolved reports strictly by playbackStore.Get(PlaySessionId) and returned 204 on miss — so the position never updated (frozen indicator) and resume progress was never persisted. The stream path already handles exactly this with a route-scoped fallback (fix(jellycompat): reuse the play session for Static direct play instead of leaking one per request #165); the report path never got it.
  2. Nothing kept the session alive. With reports dropped, the upstream session's LastActivityAt never refreshed, and unlike the native stream handler (stream.go), jellycompat never marked an in-flight transport around ServeDirectPlay/ServeRemux. Stale cleanup (45s active grace) reaped the session mid-playback — the card vanishes.
  3. The session never came back. ensureUpstreamPlayback early-returned whenever UpstreamSessionID was set, without checking the session still existed, so once reaped it stayed a dangling id for the rest of playback.

Related but distinct from #205 (ghost sessions lingering); this is an active session vanishing.

Approach

Fix all three legs in the owning package, mirroring existing patterns rather than adding new mechanisms:

  • handlePlaybackReport resolves unknown PlaySessionIds via a recorded client-id alias first (the stream path stores the client's own PlaySessionId when it binds/creates a session), then the same token-scoped item/source route fallback the stream path uses. When a progress report proves the client is still playing but the upstream session was reaped, it is recreated under the same play session.
  • HandleVideoStream wraps direct-play/remux serving in BeginTransport/EndTransport (added to jellycompat's SessionManagerInterface), so long-lived range transfers keep the session alive exactly like native streams.
  • ensureUpstreamPlayback verifies the upstream session still exists before reusing it, closes any transcode still keyed to a reaped id before recreating, and attaches the new session via compare-and-swap — the loser of a concurrent race stops its own session (no orphans against stream limits) and adopts the winner only when play methods match (else 409 Conflict).

Safety propert­ies (driven by the adversarial review): alias lookups require a unique live match and must agree with the report's ItemId/MediaSourceId; a Stopped report that matched only by ambiguous route tears nothing down (stale cleanup owns that path).

The first commit fixes a pre-existing broken test build on main: #258 added ListProgressSince to userstore.UserStore and missed the progressCountingStore fake in jellycompat.

Verification

  • 5 new tests written first and failing on main (report fallback ×2, upstream revive ×2, transport marking), then green after the fix; 10 more cover the hardening (alias determinism, duplicate/contradicted aliases, stop-gating, stale-transcode close, CAS adopt/reject via an interposing fake).
  • GOWORK=off go test ./internal/jellycompat/ ./internal/playback/ ./internal/api/... — all green except two pre-existing environmental failures unrelated to this change (TestBeginWebOperation* process-identity lock checks, which also fail on main, and the documented GPU-probe flakes which pass in isolation).
  • GOWORK=off go build ./... clean; golangci-lint run --new-from-rev=origin/main reports zero non-test findings (test-file goconst/errcheck hits are the known local false positives excluded in CI); make verify-local-paths clean.

Adversarial review

3 Codex adversarial review iterations; final verdict approve, no material findings. Fixed along the way: (1) nondeterministic route/alias binding that could tear down the wrong same-token session → unique-match alias + ItemId/MediaSourceId validation + stop-gating; (2) same-method revive leaking a stale transcode → close before recreate; (3) concurrent attach race orphaning upstream sessions → CAS with rollback and method-checked winner adoption.

Risks & follow-up

  • Behavior change: a Stopped report matched only by ambiguous route no longer tears down immediately — the session now ends via stale cleanup (≤45s active / ≤2m paused). Exact-id and alias-matched stops tear down immediately as before.
  • Remote transcode-node cleanup on revive passes an empty node URL (the reaped session no longer carries it), so a remote ffmpeg from a reaped transcode session is cleaned only by the node's own TTL — same as main's behavior when GetSession misses.
  • No /api/v1 surface changes; jellycompat only. No client (silo-android/silo-apple) follow-up needed.
  • No UI changes (server-side only; the Activity View frontend is untouched).

Closes #244

AI-use disclosure

Implemented by Claude Code (issue-to-pr skill) with human oversight; adversarial review by Codex.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Enhanced support for static/direct-play sessions by recording and using client-generated play-session IDs for more reliable progress/stop mapping.
  • Bug Fixes

    • Improved playback report resolution, including deterministic alias binding and safer fallback behavior when session/item/media-source details don’t initially match.
    • Progress updates now correctly target the resolved session and can revive upstream sessions when appropriate.
    • Reduced stale cleanup during active range streaming by tracking transport liveness.
    • Added clearer concurrency handling by returning 409 Conflict when the playback session changed mid-request.
  • Tests

    • Added regression coverage for playback report liveness and alias/transport scenarios.

Quick104 and others added 4 commits July 2, 2026 00:09
PR #258 added ListProgressSince to the userstore.UserStore interface but
missed the progressCountingStore stub, leaving the jellycompat test build
broken on main. Stub it with the same panic("unused") the sibling methods
use.

Co-Authored-By: Claude Fable 5 <[email protected]>
…vity view

An Infuse Static=true direct play skips PlaybackInfo, so its playback
reports carry a client-generated PlaySessionId. handlePlaybackReport only
resolved reports by exact PlaySessionId, so every report silently no-op'd:
the admin Activity View position froze, nothing refreshed the upstream
session's activity, and stale cleanup reaped the session ~45s in while the
client kept playing. Once reaped, ensureUpstreamPlayback early-returned the
dangling session id forever, so the stream card never came back.

Fix all three legs:
- handlePlaybackReport falls back to the same token-scoped route lookup the
  stream path uses (ItemId, then MediaSourceId) when the PlaySessionId is
  unknown, and revives a reaped upstream session when a progress report
  proves the client is still playing.
- HandleVideoStream marks an in-flight media transport around direct-play
  and remux serving, mirroring the native stream handler, so long-lived
  range transfers keep the session alive without progress reports.
- ensureUpstreamPlayback verifies the upstream session still exists before
  reusing it, recreating it under the same play session when it was reaped.

FindByRoute now compares RouteItemID with UUID normalization so report ids
match regardless of client dash/case formatting.

Closes #244

Co-Authored-By: Claude Fable 5 <[email protected]>
…rsarial review

Address three review findings on the issue #244 fix:

- Deterministic report binding: the stream path now records the client's
  own PlaySessionId (Static=true direct play never learns the server id)
  as an alias on the play session it binds, and playback reports resolve
  by that alias before falling back to the ambiguous item/source route
  scan. A Stopped report that only matched by bare route no longer tears
  the session down (it may not own it when the same item plays twice
  under one token); stale cleanup owns that path.
- Same-method revive closes any transcode still keyed to the reaped
  upstream id before recreating the session, so a second ffmpeg cannot
  start alongside an orphaned one.
- Attaching a new upstream session is now a compare-and-swap on the
  observed upstream id: the loser of a concurrent revive/range-request
  race stops its session and adopts the winner instead of leaving an
  orphan counted against the user's stream limits.

Co-Authored-By: Claude Fable 5 <[email protected]>
…am attach

Second-round adversarial findings on the issue #244 fix:

- A client PlaySessionId alias now only resolves when it identifies
  exactly one live session for the token, and the candidate must agree
  with the report's ItemId/MediaSourceId. A reused or stale client id
  degrades to the route scan (progress still lands on the right item)
  instead of binding an arbitrary session, and an ambiguous Stopped
  report tears nothing down.
- A CAS loser only adopts the concurrent winner when it serves the same
  play method; a concurrent method switch surfaces 409 Conflict instead
  of continuing with mismatched transcode bookkeeping.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: af709009-3fd6-45fa-b9e0-896ec8010c6b

📥 Commits

Reviewing files that changed from the base of the PR and between efd839f and 8d40c81.

📒 Files selected for processing (2)
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/streams.go
 _________________________________________________________________
< I have no memory of this place...but I'll find the bugs anyway. >
 -----------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
📝 Walkthrough

Walkthrough

Adds transport lifecycle tracking, client PlaySessionId alias resolution for static direct-play, concurrency-safe upstream session attachment, playback report revival and teardown changes, and a regression suite covering the updated Jellyfin compat playback liveness flow.

Changes

Playback liveness and alias tracking

Layer / File(s) Summary
Sentinel error and transport interface contract
internal/jellycompat/streams.go, internal/jellycompat/handlers_playback.go, internal/jellycompat/handlers_items.go
Adds errUpstreamReplaced, BeginTransport/EndTransport on SessionManagerInterface, and maps upstream replacement errors to HTTP 409 Conflict.
Playback session alias lookup
internal/jellycompat/playback_sessions.go
Adds ClientPlaySessionID, resolves sessions by client play-session alias, and normalizes route-item matching in FindByRoute.
Static direct-play alias capture and transport marking
internal/jellycompat/streams.go
Reads static PlaySessionId case-insensitively, stores it on new static sessions, and marks direct-play streaming with transport begin/end calls.
Playback report resolution and upstream revival
internal/jellycompat/streams.go
Reworks report lookup with alias fallback and route ambiguity tracking, updates audio selection on the resolved session id, revives stale upstream sessions on missing progress targets, and limits stop teardown for route-only matches.
Test doubles for progress and transport tracking
internal/jellycompat/audio_selection_test.go, internal/jellycompat/content_direct_test.go
Extends the fake session manager with progress and transport call history, and adds a ListProgressSince stub to the direct-content store test double.
Playback report liveness regression suite
internal/jellycompat/playback_report_liveness_test.go
Adds regression tests for fallback resolution, token isolation, upstream revival, alias binding and teardown, CAS race outcomes, and direct-play transport markers.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant PlaybackHandler
  participant PlaybackSessionStore
  participant SessionManagerInterface
  Client->>PlaybackHandler: POST progress or stopped report
  PlaybackHandler->>PlaybackSessionStore: FindByClientPlaySessionID / FindByRoute
  PlaybackSessionStore-->>PlaybackHandler: resolved play session
  PlaybackHandler->>SessionManagerInterface: UpdateProgress(upstreamSessionID)
  alt session missing
    PlaybackHandler->>SessionManagerInterface: reviveUpstreamForReport
    PlaybackHandler->>SessionManagerInterface: UpdateProgress(retry)
  end
Loading
sequenceDiagram
  participant Client
  participant PlaybackHandler
  participant PlaybackSessionStore
  participant SessionManagerInterface
  Client->>PlaybackHandler: GET stream with Static=true and PlaySessionId
  PlaybackHandler->>PlaybackSessionStore: createStaticPlaySession(ClientPlaySessionID)
  PlaybackHandler->>SessionManagerInterface: BeginTransport(sessionID)
  PlaybackHandler->>Client: stream bytes
  PlaybackHandler->>SessionManagerInterface: EndTransport(sessionID)
Loading

Possibly related issues

  • issue 205: Both changes concern Jellyfin-compat playback session state and Activity View visibility while playback is active.

Possibly related PRs

Suggested labels: v1

🚥 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 describes the Jellycompat fix for keeping direct-play sessions active in Activity View.
Linked Issues check ✅ Passed The changes address #244 by fixing direct-play progress matching and transport/session lifecycles so active streams stay visible and progress updates.
Out of Scope Changes check ✅ Passed The PR stays focused on Jellycompat playback-session tracking and related tests, with no obvious unrelated code changes.
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-244-activity-view-session-drop

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 2, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb2e8688d0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// route-scoped lookup the stream path uses (see resolvePlaybackRoute).
// Without either, these reports silently no-op, the admin activity view
// position freezes, and stale cleanup drops the still-active session.
playSession, ok = h.playbackStore.FindByClientPlaySessionID(session.Token, req.PlaySessionID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use canonical play-session ID after alias fallback

When a Static=true client reports under its client-generated PlaySessionId, this alias lookup can resolve the real playSession while req.PlaySessionID remains the client ID. If the same report carries a changed AudioStreamIndex, the later setSelectedAudioStream(req.PlaySessionID, ...) looks up a non-existent store key, silently ignores the update, and the upstream audio track/transcode restart never happens. Use the resolved playSession.ID for subsequent playback-store mutations.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in efd839f — store mutations in the audio-selection branch now use the resolved playSession.ID instead of req.PlaySessionID, with a red-first regression test (TestHandlePlaybackReport_AliasResolvedAudioSelectionApplies).

@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.

Actionable comments posted: 2

🤖 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.

Inline comments:
In `@internal/jellycompat/streams.go`:
- Around line 788-816: The audio-track update path in this handler still uses
the raw request PlaySessionID even when the session was resolved via alias or
route fallback. Update the audio-selection branch to pass the resolved play
session identifier from the looked-up playSession (the same one used by the
alias/route resolution logic) into h.setSelectedAudioStream, and keep the
existing error handling path unchanged. This ensures the audio-track change is
applied for Infuse/Static direct-play sessions where req.PlaySessionID is not
the stored key.
- Around line 1006-1030: The CAS-loser path in the playback session update flow
leaves transcode resources open because it only calls StopSession; update the
conflict handling around h.playbackStore.Update in the same block to also invoke
closeTranscodeSession for session.ID using session.TranscodeNodeURL before
returning. Make sure this happens for any updateErr branch where the local
session loses the race, so the orphaned ffmpeg/node reservation is cleaned up
immediately rather than waiting for stale cleanup.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1279aa99-4a6a-4cd5-a775-72d31d0de204

📥 Commits

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

📒 Files selected for processing (7)
  • internal/jellycompat/audio_selection_test.go
  • internal/jellycompat/content_direct_test.go
  • internal/jellycompat/handlers_items.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/playback_report_liveness_test.go
  • internal/jellycompat/playback_sessions.go
  • internal/jellycompat/streams.go

Comment thread internal/jellycompat/streams.go Resolved
Comment thread internal/jellycompat/streams.go Resolved
Quick104 and others added 2 commits July 2, 2026 10:16
…ssion id

Review follow-up (PR #262): after an alias or route fallback,
req.PlaySessionID is the client's own generated id and not a playback
store key, so the audio-track-change branch in handlePlaybackReport
silently dropped selection updates for Static direct-play sessions.
Use the resolved playSession.ID for the store mutation and logging.

Co-Authored-By: Claude Fable 5 <[email protected]>
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
Quick104 merged commit d6c4dce into main Jul 2, 2026
1 check passed
@Quick104
Quick104 deleted the fix/issue-244-activity-view-session-drop branch July 2, 2026 15:37
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…vity view (Silo-Server#262)

* test(jellycompat): implement ListProgressSince on userstore test fake

PR Silo-Server#258 added ListProgressSince to the userstore.UserStore interface but
missed the progressCountingStore stub, leaving the jellycompat test build
broken on main. Stub it with the same panic("unused") the sibling methods
use.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): keep still-playing direct-play sessions in the activity view

An Infuse Static=true direct play skips PlaybackInfo, so its playback
reports carry a client-generated PlaySessionId. handlePlaybackReport only
resolved reports by exact PlaySessionId, so every report silently no-op'd:
the admin Activity View position froze, nothing refreshed the upstream
session's activity, and stale cleanup reaped the session ~45s in while the
client kept playing. Once reaped, ensureUpstreamPlayback early-returned the
dangling session id forever, so the stream card never came back.

Fix all three legs:
- handlePlaybackReport falls back to the same token-scoped route lookup the
  stream path uses (ItemId, then MediaSourceId) when the PlaySessionId is
  unknown, and revives a reaped upstream session when a progress report
  proves the client is still playing.
- HandleVideoStream marks an in-flight media transport around direct-play
  and remux serving, mirroring the native stream handler, so long-lived
  range transfers keep the session alive without progress reports.
- ensureUpstreamPlayback verifies the upstream session still exists before
  reusing it, recreating it under the same play session when it was reaped.

FindByRoute now compares RouteItemID with UUID normalization so report ids
match regardless of client dash/case formatting.

Closes Silo-Server#244

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): harden report fallback and upstream revive per adversarial review

Address three review findings on the issue Silo-Server#244 fix:

- Deterministic report binding: the stream path now records the client's
  own PlaySessionId (Static=true direct play never learns the server id)
  as an alias on the play session it binds, and playback reports resolve
  by that alias before falling back to the ambiguous item/source route
  scan. A Stopped report that only matched by bare route no longer tears
  the session down (it may not own it when the same item plays twice
  under one token); stale cleanup owns that path.
- Same-method revive closes any transcode still keyed to the reaped
  upstream id before recreating the session, so a second ffmpeg cannot
  start alongside an orphaned one.
- Attaching a new upstream session is now a compare-and-swap on the
  observed upstream id: the loser of a concurrent revive/range-request
  race stops its session and adopts the winner instead of leaving an
  orphan counted against the user's stream limits.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): guard alias ambiguity and method switches in upstream attach

Second-round adversarial findings on the issue Silo-Server#244 fix:

- A client PlaySessionId alias now only resolves when it identifies
  exactly one live session for the token, and the candidate must agree
  with the report's ItemId/MediaSourceId. A reused or stale client id
  degrades to the route scan (progress still lands on the right item)
  instead of binding an arbitrary session, and an ambiguous Stopped
  report tears nothing down.
- A CAS loser only adopts the concurrent winner when it serves the same
  play method; a concurrent method switch surfaces 409 Conflict instead
  of continuing with mismatched transcode bookkeeping.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(jellycompat): key audio-selection updates by the resolved play session id

Review follow-up (PR Silo-Server#262): after an alias or route fallback,
req.PlaySessionID is the client's own generated id and not a playback
store key, so the audio-track-change branch in handlePlaybackReport
silently dropped selection updates for Static direct-play sessions.
Use the resolved playSession.ID for the store mutation and logging.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

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

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Active stream disappears from the Activity View while still playing; playback time frozen

1 participant