Skip to content

feat(admin): announce playback session starts, pauses, resumes and ends - #3194

Merged
Quick104 merged 8 commits into
mainfrom
feat/playback-lifecycle-events
Oct 28, 2026
Merged

Quick104 merged 8 commits into
mainfrom
feat/playback-lifecycle-events

Conversation

@Quick104

@Quick104 Quick104 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none (the change reaches #1205–#1208 and #1246 C1, which have no recorded results yet)

A monitoring tool watching Silo (the first one is Tracearr) can't tell when a playback session starts, pauses, resumes or ends. The admin sessions channel only says "something changed" (sessions.replaced) and sends the frozen v1 row list, capped at 200 rows. The tool has to diff whole lists to infer transitions, and it misses any session that ends between two reads.

This change announces those transitions as events on the admin sessions channel, with the numbers and history a monitor needs to stay correct across API servers, missed events and server restarts.

Builds on #3191 and #3192, which have merged.

Approach

  • Events. session.started, session.paused, session.resumed and session.stopped on the admin-only sessions channel.
    • Every event carries session_id, seq, at and state.
    • Start, pause and resume events also carry the session's row as GET /api/v2/admin/sessions returns it.
    • A stop carries end_reason and the history entry the end recorded, as stored.
    • sessions.replaced is unchanged. GET /api/v2/admin/sessions/capabilities reports lifecycle_events.
  • Order across servers. A new playback_session_lifecycle row per session holds its announced state. Every transition takes the next number of one global sequence in the statement that makes it, so a session's numbers rise in the order the database accepted its transitions, whichever server publishes them.
    • A native v2 pause or resume commits in the same transaction as the progress sample that caused it. It therefore follows the client's sequence, and a late, older sample changes nothing.
    • Jellyfin, Audiobookshelf and v1 bridge reports carry no sequence, so they follow arrival order and write only on a change.
  • Ends. The end of a session and its admin history row commit in one transaction. The first end sets the reason and lifecycle_seq, and only it is announced. With fix(playback): let only the end that wins a session's row record it #3192 and fix(playback): record admin history for every way a session ends #3191, every way a session ends goes through it.
  • Sessions no server holds. A sweep on every API server, every 15 seconds, ends sessions that no server holds in memory. It uses the durable claims the reaper uses, revalidated inside the claim: a native session's attempt row, idle-only, with node delivery counting as activity; and the Jellyfin play row's expiry claim. It also finishes ends that were interrupted. Every announced native or Jellyfin session thus gets a history row with an end reason within its idle grace while a server runs. Audiobookshelf (beta) sessions are ended after 24 hours.
  • Lists. Native session list rows carry lifecycle_seq. A row's is_paused comes from the same transition, so a row and an event with the same number agree. Ended sessions are left out of the list. A native session whose media a node keeps serving after its API server restarted is now listed from the row recorded at its start. History entries carry lifecycle_seq. The frozen v1 snapshot is unchanged.
  • Same row everywhere. A start event's session is the in-memory session rendered exactly as a sync stores its row (worker.SessionSyncRowJSON, which shares its column list with the sync upsert) and read through the list's own query. A DB test pins that the rendered and synced rows match.
  • Docs. The realtime-api.md section covers the event contract and how a monitor reconciles. admin-api.md covers the new fields; with this change, the first end sets a history row's reason. docs/architecture/playback-lifecycle.md covers the invariants and the guarantee.
  • Surfaces. Additive under /api/v2. Admin-only, so Apple, Android and the web UI need no change. For jellycompat parity: Jellyfin clients don't consume admin session events; Jellyfin plays are announced through their upstream sessions.

Validation

  • Ran on an isolated sandbox built from this branch, with real HTTP and WebSocket calls on the v2 events socket:
    • Native v2 play: started, paused, resumed and stopped, with rising numbers. A progress sample older than the accepted one produced no event.
      • The list row's lifecycle_seq and is_paused matched the resume.
      • The start event carried the session with its client and device.
      • The stop carried end_reason: stopped and the history entry. The history list returned the same lifecycle_seq.
    • Jellyfin play: the same four events, with a repeated pause report producing nothing.
    • A regular account's socket had sessions rejected (forbidden) and received no lifecycle events.
    • A native play left behind by a killed server: with the server killed and restarted and no client coming back, the sweep ended it after 317 s (the 5-minute grace plus one sweep): history expired at 500 s with client and device, and progress afterwards 404.
  • DB contracts, each listed in scripts/ci/db-contracts.txt, cover:
    • the transition rules: start once, unsequenced pause, first end wins, tombstone;
    • progress committing the pause state in sequence order, plus the idle-only expiry;
    • the list's lifecycle projection, including ended and unheld sessions;
    • the rendered start row matching the synced row.
      A unit test covers that events are admin-only, with their ids and stop history.
  • Gate: build, gofmt, vet, make lint-changed (0 issues), make lint-router-recovery, make test-go, every make verify-* target and TestCommittedArtifactMatchesRouter, web lint, format, build and budget pass.
    • make test-web failed one test under load: pgs.test.ts "drops objects past 16 MiB" timed out. It passes alone, and this change touches no web code except the generated API types.
    • make verify-actionlint didn't run: actionlint 1.7.12 isn't installed on the machine used, and no workflow changed.
    • After rebasing onto fix(playback): let only the end that wins a session's row record it #3192's review fixes, the touched packages, the contract checks and lint were rerun and pass.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3194/

No visible change: the web admin still refreshes on sessions.replaced and ignores the new events. The evidence page has the event transcripts, the build and the test results.

Risks

  • A native progress sample now commits in a two-statement transaction instead of one statement. The lifecycle statement is a primary-key lookup that writes only when the pause state changes.
  • Jellyfin and v1 bridge progress reports each add one primary-key lookup on the lifecycle table, which writes only on a change.
  • The sweep runs on every API server every 15 seconds. It reads at most 100 live lifecycle rows that no server synced lately, and deletes tombstones older than 25 hours.
  • In a rolling deploy, servers without this change send no lifecycle events.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code; Codex (gpt-6.1-sol) for read-only design reviews
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated. claude-opus-5-5 wrote the code, tests, migration, docs and this description from a maintainer-approved plan and design.
  • Adversarial review: Codex (gpt-6.1-sol, read-only) reviewed the design twice, at xhigh and then high effort. The first round asked for a rework (14 findings) and the re-check found 4 more. All were accepted. They shaped the transactional pause ordering, the atomic end-plus-history write, the claim-based sweep and the list projection. A review of this diff follows in the PR thread.

🤖 Generated with Claude Code

Note

Add playback session lifecycle tracking with admin start/pause/resume/end events

  • Adds a playback_session_lifecycle table storing per-session state, a global sequence number, and start facts; admin playback history rows gain a nullable lifecycle_seq (migration)
  • Emits lifecycle events on the admin sessions channel: starts are announced by the native, Jellyfin, and Audiobookshelf frontends; pauses and resumes are recorded when accepted progress commits its lifecycle state alongside the attempt update (playback.go, playback_service.go, postgres.go)
  • Adds a periodic background sweep (playback_lifecycle_sweep.go) that finalizes sessions with no server holder, expires idle attempts by cutoff, records history from the first end, and cleans up stopped tombstone rows
  • Admin session lists and history can now include lifecycle data: sessions without a live sync row are reconstructed from lifecycle start facts, and stopped sessions are omitted; API models, OpenAPI contract, web schema, and docs are updated
  • Behavioral Change: ApplyProgress wraps sample acceptance in a transaction and applies pause-state updates to lifecycle rows; LiveSession falls back to lifecycle start facts when no sync row exists; capability responses gain lifecycle_seq and lifecycle_events fields

Macroscope summarized 3439956.

@silo-triage silo-triage Bot added the size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. label Oct 28, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T16:20:21.771671Z 3439956 New commits
🔒 Security Review ✅ Completed 2026-10-28T16:20:59.925984Z 3439956 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-triage silo-triage Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish stacked Base is another open PR; merge in stack order named in the body labels Oct 28, 2026
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 01539c1f-4483-4cfd-8cf4-1f089779d9df
Commits

Reviewing files that changed from the base of the PR and between 1cfdc53 and eaa5437.

Files selected for processing: 1
  • internal/api/handlers/playback_finish_history_test.go
Files skipped from review as they are similar to previous changes: 1
  • internal/api/handlers/playback_finish_history_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Walkthrough

The change adds persistent playback lifecycle tracking for starts, pauses, resumes, and ends. It publishes sequenced admin events, adds lifecycle sequence data to session and history APIs, and processes inactive sessions through a periodic sweep.

Changes: Playback lifecycle tracking

Layer / File(s) Summary
Lifecycle storage and progress sequencing
migrations/sql/*, internal/playback/protocol_store_v3.go, internal/playback/planstore/postgres.go, internal/playback/planstore/progress_lifecycle_db_test.go
A migration adds lifecycle state and history sequence storage. Accepted progress updates can record pause-state transitions and return their sequence and timestamp.
Transition capture and event publication
internal/playback/session.go, internal/api/handlers/playback*.go, internal/api/handlers/playback_lifecycle*.go, internal/audiobooks/abs/native_sessions.go, internal/jellycompat/*, internal/api/router.go, internal/apiv2/admin_playback_lifecycle.go
Playback entry points report starts and pause changes. The handler records transitions and publishes sequenced admin events with session and history data when available.
Inactive-session expiry and finalization
internal/api/handlers/playback_lifecycle_sweep.go, internal/playback/session_activity.go, internal/playback/planstore/postgres.go
A periodic sweep selects inactive sessions and processes native, Jellyfin, and Audiobookshelf expiry and end-recording paths.
Admin session and history read models
internal/api/handlers/admin_playback_history.go, internal/api/handlers/playback_admin_store.go, internal/api/handlers/playback_sessions.go, internal/apiv2/admin_playback*.go, internal/apiv2/admin_sessions.go, internal/apiv2/router.go
Admin session and history reads include lifecycle sequence data. Session reads use lifecycle state and can include eligible native sessions absent from the live sync table.
Contracts, documentation, and supporting validation
contracts/api/v2/*, docs/admin-api.md, docs/architecture/playback-lifecycle.md, docs/realtime-api.md, web/src/api/v2/schema.ts, scripts/ci/db-contracts.txt, internal/api/handlers/*test.go, internal/worker/*test.go, cmd/silo/main.go
API contracts and documentation describe lifecycle capabilities, events, sequence fields, and history behavior. Tests cover transitions, expiry selection, missing media files, and sync-row rendering.

Priority: Normal

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant SessionManager
  participant PlaybackHandler
  participant PlaybackAdminStore
  participant EventsHub
  SessionManager->>PlaybackHandler: Report start or pause change
  PlaybackHandler->>PlaybackAdminStore: Record lifecycle transition
  PlaybackAdminStore-->>PlaybackHandler: Return transition sequence and state
  PlaybackHandler->>EventsHub: Publish sequenced admin session event
Loading

Possibly related PRs

Suggested labels: javascript, impact: playback

Suggested reviewers: rhainland

Merge Risk: Minimal · previous review eaa54

The test now checks that expired-stop history has no file-derived duration when the media file is unavailable. No issue in this change needs resolution before merging.

Security architecture risk: Moderate · up to 1cfdc

Administrative access controls remain in place, and native progress updates have transactional ordering protections. However, automatic expiry can stop an active legacy session and revoke its playback access when server synchronization is delayed and recent media delivery is not visible. Deployment and recovery behavior also retain some uncertainty.

Retained concerns

  • Medium · reliability · inferred: The new cross-server sweep can durably expire an active v1 bridge session using an activity clock that bridge progress does not refresh. Bridge starts create an attempt, so the sweep routes them through ExpireIdleAttempt, but bridge progress updates in-memory activity and changes the lifecycle timestamp only on pause-state transitions. If the holder's synchronization is stale for more than 45 seconds, the attempt and lifecycle clocks exceed their idle grace, and no recent delivery activity protects the session, another server can stop the attempt, deny its stream tokens, and finalize it despite continuing progress reports. Local-holder checks, fresh synchronization, and recent delivery observations protect normal operation; the concern is failure containment when synchronization stalls, not an established cross-user attack.
Security review details

Security Blast Radius

  • inferred — Lifecycle recovery has cross-server authority over eligible sessions in the shared database, including stopping attempts and denying playback tokens. Its failure scope can span sessions belonging to multiple users on a stalled holder, rather than only the request that initiated a transition.

Trust Boundaries and Controls

  • observed — Bridge progress checks both authenticated account and profile ownership before invoking lifecycle reporting. Jellyfin reporting checks the compatibility token on direct lookup and passes that token through fallback lookups before announcing pause state. The new callbacks remain downstream of those existing controls.
  • observed — The existing event boundary admits the sessions channel only for administrative connections and rejects AdminOnly envelopes for non-admin claims. Acting-profile checks can demote an administrator account's connection, and remote-playback credentials do not receive the sessions channel.

Resilience and Maintainability Implications

  • inferred — The bridge expiry concern is a control-plane failure-containment issue: missing synchronization can become a durable terminal decision and token revocation even while the owning server accepts progress. This differs from native progress, whose accepted samples refresh the attempt clock checked by expiry.

Hardening Proposals

  • proposed — Give each frontend an authoritative activity signal that its progress reports refresh, and revalidate that signal together with ownership before committing expiry and denying tokens. This would reduce dependence on synchronization freshness for bridge sessions.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 76.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title names the main change: admin-only announcements of playback session starts, pauses, resumes and ends. The changeset adds the four session.* lifecycle events on the admin sessions channel, so…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The pull request description clearly explains the playback lifecycle events, durable lifecycle state, API changes, sweep behavior, documentation, validation, and risks covered by the changeset.
Full details: Title check

Explanation

The title names the main change: admin-only announcements of playback session starts, pauses, resumes and ends. The changeset adds the four session.* lifecycle events on the admin sessions channel, so the title matches the primary change. It is short and specific, and it uses a conventional feat(admin) prefix.

Full details: Docstring Coverage

Explanation

Docstring coverage is 76.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 21 functions across 27 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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: 75e509fe07

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@coderabbitai coderabbitai Bot added impact: playback Can't play, stalls, or wrong media javascript Pull requests that update javascript code labels Oct 28, 2026
@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch from 75e509f to b702614 Compare October 28, 2026 01:06

@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: 5

Caution

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

⚠️ Outside diff range comments (1)

Minor · Allocate the stop sequence after locking the lifecycle row. · openapi.json:174

contracts/api/v2/openapi.json:174
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Allocate the stop sequence after locking the lifecycle row.

RecordEnd allocates EXCLUDED.seq before it detects the conflict. A concurrent pause can commit a higher sequence before this update runs. The stop event and history row then have a lower sequence, so a monitor can discard the stop and retain the session as live. PostgreSQL documents this allocation order. (postgresql.org)

Call nextval in the conflict-update assignment instead of copying EXCLUDED.seq.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9e22ccd5-f37e-4956-8b25-94d4a3688d05
Commits

Reviewing files that changed from the base of the PR and between e98f2ba and 75e509f.

Files selected for processing: 36
  • cmd/silo/main.go
  • contracts/api/v2/fixtures/get_admin_playback_history_capabilities_ok.json
  • contracts/api/v2/fixtures/index.json
  • contracts/api/v2/fixtures/list_admin_playback_history_ok.json
  • contracts/api/v2/openapi.json
  • docs/admin-api.md
  • docs/architecture/playback-lifecycle.md
  • docs/realtime-api.md
  • internal/api/handlers/admin_playback_history.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_admin_store.go
  • internal/api/handlers/playback_lifecycle.go
  • internal/api/handlers/playback_lifecycle_db_test.go
  • internal/api/handlers/playback_lifecycle_sweep.go
  • internal/api/handlers/playback_lifecycle_test.go
  • internal/api/handlers/playback_service.go
  • internal/api/handlers/playback_sessions.go
  • internal/api/handlers/playback_v3.go
  • internal/api/router.go
  • internal/apiv2/admin_playback_history.go
  • internal/apiv2/admin_playback_lifecycle.go
  • internal/apiv2/admin_sessions.go
  • internal/apiv2/router.go
  • internal/audiobooks/abs/native_sessions.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/streams.go
  • internal/playback/planstore/postgres.go
  • internal/playback/planstore/progress_lifecycle_db_test.go
  • internal/playback/protocol_store_v3.go
  • internal/playback/session.go
  • internal/playback/session_activity.go
  • internal/worker/reconciler.go
  • internal/worker/session_sync_row_db_test.go
  • migrations/sql/20261027235549_add_playback_session_lifecycle.sql
  • scripts/ci/db-contracts.txt
  • web/src/api/v2/schema.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment thread docs/realtime-api.md Resolved
Comment thread docs/realtime-api.md Resolved
Comment thread docs/realtime-api.md Resolved
@Quick104
Quick104 force-pushed the feat/playback-finalization-claims branch from 21ba551 to a8580fe Compare October 28, 2026 01:23
@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch from 36c5047 to 6e8d9d0 Compare October 28, 2026 01:24

@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


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ae35ad0b-f66f-4346-b8a8-128227149c9e
Commits

Reviewing files that changed from the base of the PR and between 75e509f and 36c5047.

Files selected for processing: 10
  • docs/architecture/playback-lifecycle.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_admin_store.go
  • internal/api/handlers/playback_finish_history_test.go
  • internal/api/handlers/playback_lifecycle.go
  • internal/api/handlers/playback_lifecycle_db_test.go
  • internal/api/handlers/playback_lifecycle_sweep.go
  • internal/api/handlers/playback_sessions.go
  • migrations/sql/20261027235549_add_playback_session_lifecycle.sql
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment thread docs/architecture/playback-lifecycle.md Resolved
Comment thread internal/api/handlers/playback.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

The outside-diff point in CodeRabbit's review of 75e509f (allocate the stop's sequence after locking the lifecycle row) was fixed in 556e909: the conflict update now calls nextval itself. TestPlaybackLifecycleOrderAndStartStateDB holds a pause on the row while the end waits and checks the end's number comes out higher; it fails on the old assignment.

@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch from 02e9aa6 to 13c6e52 Compare October 28, 2026 01:33

@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: 13c6e521c7

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1354 to +1356
// An end goes through the session's lifecycle, which announces it;
// a teardown the client can recover from records its stretch only.
if reason != "" && h.recordEnd(ctx, session, *entry) {

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 Finalize announced Jellyfin sessions even without progress

When a Jellyfin session starts at position zero and stops or switches playback method before reporting positive progress, recordStopHistory returns early through compatCopyWithoutProgress, so this lifecycle finalization never runs. The session has already emitted session.started, but its lifecycle remains playing until the sweep eventually emits a stop with end_reason: expired, losing the actual stopped or replaced reason. Keep the existing protection against stale copies writing watch history, but ensure an authoritative end still finalizes an announced lifecycle.

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.

Keeping the guard; documented the trade-off in 9088942. A Jellyfin copy without progress cannot tell whether it is the play's only copy: with several API servers it is often the one that only served media while another server's copy took the reports. If its end recorded history and stopped the lifecycle, the copy with the real progress would later be dropped as ended elsewhere and the play's history lost. Ending through the sweep as expired is late and has the wrong reason, but loses nothing. I tried the change; TestFinishedSessionWithoutPositionRecordsNothing and the stale-copy tests fail on exactly this. The architecture doc now says a Jellyfin play that ends before reporting progress is ended by the sweep.

@Quick104
Quick104 force-pushed the feat/playback-finalization-claims branch from b428c2a to 90c980b Compare October 28, 2026 01:40
@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch 2 times, most recently from 9088942 to e4ee6e9 Compare October 28, 2026 01:58

@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: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ecd48a38-28dd-46f6-b37e-82f6cec1f249
Commits

Reviewing files that changed from the base of the PR and between 36c5047 and 9088942.

Files selected for processing: 8
  • docs/architecture/playback-lifecycle.md
  • docs/realtime-api.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_admin_store.go
  • internal/api/handlers/playback_finish_history_test.go
  • internal/api/handlers/playback_lifecycle.go
  • internal/api/router.go
  • internal/apiv2/admin_playback_lifecycle.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment thread internal/api/router.go Resolved
@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch 6 times, most recently from 49bfd8c to 1cfdc53 Compare October 28, 2026 03:12
Base automatically changed from feat/playback-finalization-claims to main October 28, 2026 15:51
@silo-triage silo-triage Bot added size/XXXL 3000+ added + deleted lines (all files); change volume, not priority. and removed size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. labels Oct 28, 2026
Quick104 and others added 7 commits October 28, 2026 15:51
The admin sessions channel now carries session.started, session.paused,
session.resumed and session.stopped. A lifecycle row per session holds its
announced state and the number of its last transition, from one sequence the
database advances with each transition, so events order correctly across API
servers. Native pauses commit with the accepted progress sample; an end and
its admin history row commit together, and only the first end is announced,
with the history entry as stored. A sweep on every API server ends sessions
no server holds through the same durable claims the reaper uses. The native
session and history lists carry lifecycle_seq, and the sessions
capabilities report lifecycle_events.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An end takes its number under the row lock, so it stays above a pause it
waited for. A start begins at the attempt's accepted pause state. The sweep
selects only sessions it can end now, so active ones never fill its batch,
and revokes tokens only after its claim succeeds. A play whose file left the
catalog is still recorded, and a one-session read filters before rendering.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A lookup that failed for another reason returns the error, so a retry can
record the full row. The docs now say a sweep backlog over 100 sessions
drains over several sweeps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 force-pushed the feat/playback-lifecycle-events branch from f8d8785 to 53434bd Compare October 28, 2026 15:58
@silo-triage silo-triage Bot added size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. and removed size/XXXL 3000+ added + deleted lines (all files); change volume, not priority. labels Oct 28, 2026
@silo-kody

silo-kody Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

A Jellyfin play the expiry claim refuses records that it reported after the
cutoff, so live plays no longer fill every sweep batch. Node delivery is read
once per sweep, and an end recorded from facts takes the attempt's last
accepted position, including a seek back.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌
⚠️ 2 Kody Rule(s) were not evaluated

These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:

  • Preserve optional store capabilities through production wrappers
  • Detach mandatory cleanup from request cancellation and bound its lifetime

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase enhancement New feature or request go Pull requests that update go code impact: playback Can't play, stalls, or wrong media javascript Pull requests that update javascript code priority: P2 Limited scope, workaround exists, or polish size/XXL 1000–2999 added + deleted lines (all files); change volume, not priority. stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant