You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(playback): measure watch time on every stop and name the history end position - #4552
Related issue: N/A
Validation tasks: reaches #1206 C2 (how a stopped session's history is recorded; no intended change to cleanup)
Other clients: N/A (no client-visible change outside the web admin, which this updates; Apple, Android and Roku do not read admin playback history)
A developer integrating a third-party monitor reported two problems with admin playback history. A 16-second play came back with measured: false and null watch-time fields. And watched_seconds reads like watch time but holds the position the play ended at.
The unmeasured play was ended by an administrator stop that the player confirmed. That path removes the live session first, then records the play from the playback attempt row, which never had the session's measurement. The same loss happens when a stop lands after a server restart or on an API server that does not hold the session, when an abort or expiry finishes an earlier stop, and when a Jellyfin stop reaches such a server.
This keeps every play measured through those paths and renames the history field to say what it holds.
Approach
Measurement. A session's watch-time measurement is saved with its lifecycle row (playback_session_lifecycle.watch, new migration) when the session starts, on each 15-second live-session sync, and once more at graceful shutdown. It lives there, not on the live-session sync row, because the sync row is deleted when its server shuts down.
A session rebuilt after a restart restores the saved measurement, through the native or the Jellyfin transcode manager.
A stop recorded without the live session continues from it, then counts the stop's own final position.
An end that removed the live session itself (confirmed administrator stop, abort, expiry) hands that session's measurement straight to the history write.
A saved measurement is never replaced by an older one.
The first sample is now taken when the start commits its plan, not at admission, so time spent preparing a transcode is not judged as viewing. The existing guard against implausible credit is unchanged and applies to a restored measurement too.
Field name. History entries, including the one inside the session.stopped event, carry end_position_seconds and no longer carry watched_seconds. There is no alias: /api/v2 is pre-1.0, and no first-party client reads the field (checked on the main branches of silo-apple, silo-android and silo-roku). The account watch summary keeps its own watched_seconds, which is watch time, and its description now says so. The database column keeps its name, so history writes from servers not yet upgraded still land during a rolling upgrade.
The two changes share a pull request because they touch the same history entry and the same tests.
jellycompat: no Jellyfin-protocol response changes; a Jellyfin stop that reaches a server without the session is now measured. The user manual does not describe these fields.
Validation
Go tests for the playback, worker, apiv2 and handlers packages pass on the rebased branch. cmd/silo could not be tested locally after the rebase because the embedded web build was absent. New tests cover a saved measurement continuing on another server, a confirmed administrator stop, and a detached stop measured through its final position; the two handler tests fail with the fix removed.
Changed-line lint, web typecheck and the full web suite passed before the rebase. OpenAPI, fixtures and web types regenerate with no diff after it.
On an isolated single-node sandbox, with history read by a monitor-scoped key: plays of 5 s and 16 s, a play with a pause, a play resumed mid-film, a play ended by a confirmed administrator stop, a Jellyfin play, and plays stopped after a graceful restart all come back measured. Restart plays read 32.5 s and 31.8 s for about 32 s of wall time.
Known shortfall: a confirmed administrator stop carries no position, so that play reads 10 s for 16.7 s of wall time. The seconds since the last progress report are not counted.
Not run: two API servers. The restart and confirmed-stop runs go through the code a second server would use. There is no test for the rule that an older saved measurement never replaces a newer one.
Breaking for API consumers: watched_seconds leaves admin playback history entries and the session.stopped event. Read end_position_seconds for the end position and played_seconds for watch time.
Migration: one nullable jsonb column on playback_session_lifecycle.
Load: one batched UPDATE per server per 15-second sync, skipped for sessions whose measurement did not change.
An ungraceful server death loses at most the last 15 seconds of measurement.
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 how I checked a change nobody sees.
AI Disclosure
Harness: Claude Code in T3 Code
Tool(s): Claude Code, Codex CLI (review round), GitHub CLI
Model(s): claude-opus-5-5 (implementation, sandbox testing, and the Jellyfin rebuild fix from review), claude-fable-5-2 (triage, review of the full diff, rebase, this description)
Involvement: Fully AI-generated, human verified
Adversarial review: a maintainer review with Claude Code (claude-opus-5-5) and a cross-provider round with Codex (gpt-6.2-sol); its one fix is on this branch, and the lower-severity cases are listed in the review
Persist playback watch time across stops and rename history watched_seconds to end_position_seconds
Watch-time measurement now starts at plan commit in SessionManager.MarkPlanCommitted, is serialized with its sampling state via WatchTime JSON methods, and is persisted to the playback_session_lifecycle table's new nullable JSONB watch column (migration).
The reconciler saves watch measurements after session reconciliation and at shutdown; TranscodeManager.reconstructSession restores a saved measurement for rebuilt sessions, so measurement survives cross-server session reconstruction.
All stop paths (realtime, sweep, abort, expiry, detached fallback) carry the saved measurement into the recorded admin stop history, so every stop records the measured watch time.
The playback-history field watched_seconds is renamed to end_position_seconds end-to-end: API structs, OpenAPI schema, web types, and docs. The database column watched_seconds is unchanged; only the field name differs from the stored end position.
Behavioral Change: listAdminPlaybackHistory now requires end_position_seconds instead of watched_seconds — a breaking API change recorded in breaking-approvals.json. Any out-of-tree consumer reading watched_seconds from the v2 playback-history response must switch to end_position_seconds.
… copy
An admin stop the player confirms removes the live session before its
history is written from the attempt row, so a play Tracearr stopped after
16 seconds was recorded with no measurement. A stop after a restart, or on a
replica without the session, lost it the same way.
The measurement is now saved on the session's lifecycle row at start and on
each live-session sync (and once more at graceful shutdown). A session
rebuilt from a stream token, and a stop recorded from the attempt row or a
Jellyfin detached finish, carry on from it; an end that removed the live copy
passes that copy's measurement along. The stop's own final sample is then
measured too. The first sample is taken when the start commits its plan, not
at admission, so transport preparation is not judged as viewing.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
watched_seconds on a playback history entry, and on the history embedded in
session.stopped, was where the play ended, which monitors read as watch
time. It is now end_position_seconds, with no alias; played_seconds is the
watch time. The account watch summary's watched_seconds is watch time and
keeps its name, with a description that says so. The database column keeps
its name, so history writes from servers mid-upgrade still land.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Playback sessions now persist and restore measured watch time across reconciliation, shutdown, and session reconstruction. Playback history uses end_position_seconds for the final media position, distinct from measured watch time, across API contracts and web views.
Watch-time state can be serialized and stored in lifecycle rows. Session synchronization and shutdown save measurements, while reconstructed sessions and stop finalization restore or carry them forward.
Separate end position from watch time internal/api/handlers/admin_playback_history.go, internal/api/handlers/playback_admin_store.go, internal/api/handlers/playback.go, internal/apiv2/admin_playback_history.go, internal/apiv2/admin_account_insights.go, contracts/api/v2/openapi.json, contracts/api/v2/fixtures/list_admin_playback_history_ok.json, docs/admin-api.md, docs/admin-users-api.md, internal/api/handlers/playback_finish_history_test.go, internal/api/handlers/playback_lifecycle_db_test.go, internal/api/handlers/playback_lifecycle_test.go, internal/api/handlers/playback_service_test.go, internal/apiv2/admin_playback_history_test.go
Playback history exposes the final media position as end_position_seconds; measured watch time remains a separate value. API descriptions and tests reflect the distinction.
Update web history data and displays web/src/api/types.ts, web/src/api/v2/adminPlaybackHistory.ts, web/src/api/v2/adminUserActivity.ts, web/src/api/v2/schema.ts, web/src/pages/AdminPlaybackHistory.tsx, web/src/pages/admin-users/detail/activity/WatchHistoryCard.tsx, web/src/pages/admin-users/detail/overview/RecentlyWatchedCard.tsx, web/src/api/v2/adminUserActivity.test.ts
Web API types and validation use end_position_seconds. History and user activity views use that value for playback position and fallback progress calculations.
This change saves watch time with each playback session and reports the play's ending position under a new field name. In rare cases, such as a database read failure during session rebuild, a stale replica stop, or a slow shutdown, the recorded watch time can come out lower than it should. These cases only affect watch-time accuracy. The risk of merging is low, and the three edge cases are worth following up.
Security architecture risk: Minimal · up to 2885b
The inspected changes preserve session ownership and administrator-only history access. The reporting-field rename requires consumers to update, but no introduced change materially weakening security, cleanup, or ownership guarantees was established.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
observed — The history endpoint remains a cross-account administrator view. Viewer-initiated stops still require the attempt's account and profile to match the caller before mutation; adding measurement restoration does not change those identity fields.
Trust Boundaries and Controls
observed — Client-supplied final positions remain subject to finite, nonnegative-value validation and the stop store's sequence comparison. Reconstruction checks recipe/session identity and rejects a nonzero caller that differs from the recipe owner before restoring watch state. The restored document supplies measurement, not session ownership.
Resilience and Maintainability Implications
inferred — A failed checkpoint or interruption can leave recovery with older or absent measurement, but checkpoint freshness does not extend lifecycle activity or reopen a stopped row. The inspected failure consequence is reduced reporting precision rather than a new route around stop ownership or cleanup.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the two changes in the PR: watch time is now measured on every stop (the detached, confirmed-admin, abort, and expiry paths that previously lost the measurement), and the history field…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Description check
The description states the problem (unmeasured plays after administrator stops, restarts, and Jellyfin stops, plus the misleading watched_seconds name), the approach (lifecycle-row watch persistence, …
Full details: Title check
Explanation
The title names the two changes in the PR: watch time is now measured on every stop (the detached, confirmed-admin, abort, and expiry paths that previously lost the measurement), and the history field is renamed to end_position_seconds. Both match the changeset and the objectives. The title is a single sentence and is specific, though it is long and combines two concerns.
Full details: Description check
Explanation
The description states the problem (unmeasured plays after administrator stops, restarts, and Jellyfin stops, plus the misleading watched_seconds name), the approach (lifecycle-row watch persistence, restore on stop paths, rename to end_position_seconds), the risks (breaking API change, migration, load), and validation evidence. It matches the changeset in cmd/silo, the migration, the handlers, the playback package, the worker reconciler, the API schema, docs, and the web client.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
The reason will be displayed to describe this comment to others. Learn more.
Include accepted progress newer than the saved watch measurement
When a stop reaches a replica without the live session and omits a new final sample, accepted.Sequence equals record.LastSequence, so this condition skips the latest accepted position even if the saved watch measurement predates it. Watch state is saved only on session syncs, while ordinary progress does not trigger a sync, so a short play stopped before the next sync can be recorded as measured with zero watched seconds despite having accepted progress. The stopped lifecycle row then rejects further watch saves. Compare against what the restored measurement actually includes rather than requiring a sample newly introduced by this stop.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in a9a70d0. A stop recorded without the live session now observes the latest accepted sample whenever the measurement was restored from the last save, not only when the stop itself brought a newer sequence. A measurement handed over by the session copy that the same end removed is left as it is, since that copy saw every sample. The credit still goes through the existing plausibility guard. No new test covers this exact ordering; the existing detached-stop tests pass.
Expired sessions and history-write retries remain unmeasured even when a saved measurement exists because endLifecycleWith reads LiveSession without populating Watch. Restore the saved watch in the sweep finalization path before recording history.
Prompt for LLM
File internal/api/handlers/playback.go, lines 1658-1661:
Lifecycle sweep ignores persisted watch measurements
Lifecycle sweep finalization bypasses this restoration: `endLifecycleWith` reads `LiveSession`, which does not populate `Watch`, and writes history directly, so expired sessions and retries of failed history writes remain unmeasured even when a saved measurement exists. Restore the saved watch in the sweep finalization path before recording history.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 2a83454: the sweep now restores the measurement saved on the lifecycle row before it records history. The Audiobookshelf path is left alone, because it credits its own reported listening and restoring there would count it twice.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for addressing this. Restoring the lifecycle measurement before the sweep writes history addresses the reported gap, and leaving the Audiobookshelf path unchanged avoids double-counting its reported listening.
I haven’t independently verified commit 2a83454db.
The reason will be displayed to describe this comment to others. Learn more.
Detached stops discard unsynced accepted progress
A stop on another replica can lose all playback since the last sync, including an entire short play. Apply accepted when it is newer than the restored watch measurement, rather than only when accepted.Sequence exceeds record.LastSequence.
Prompt for LLM
File internal/api/handlers/playback_service.go, lines 659-661:
Detached stops discard unsynced accepted progress
A stop without a new final sample skips the last accepted progress sample even when the saved watch predates it, so a stop on another replica loses all playback since the last sync, including an entire short play. Apply the accepted sample when it is newer than the restored watch measurement, rather than only when its sequence exceeds the attempt row's sequence.
The reason will be displayed to describe this comment to others. Learn more.
Fixed in a9a70d0: a stop recorded without the live session observes the latest accepted sample whenever the measurement was restored from the last save. A measurement handed over by the session copy the same end removed is left as it is.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the update. The described fix addresses the reported gap: detached stops apply the latest accepted sample to a restored measurement, while stops with a measurement handed over by the removed session leave it unchanged.
I haven’t independently verified commit a9a70d07c or its tests.
The reason will be displayed to describe this comment to others. Learn more.
Compatibility playback never receives the initial watch sample
A short Jellyfin play whose only position update is the stop can record zero played seconds because its watch starts at the end position. Initialize the first Watch sample when the compatibility stream is ready; check AnnounceStart and MarkPlanCommitted.
Prompt for LLM
File internal/playback/session.go, lines 1207-1208:
Compatibility playback never receives the initial watch sample
Jellyfin sessions start through `AnnounceStart` and never call `MarkPlanCommitted`, so a short play whose only position update is the stop initializes its watch at the end position and records zero played seconds. Initialize the first watch sample for compatibility sessions when their stream is ready as well.
The reason will be displayed to describe this comment to others. Learn more.
Not changing this here. A Jellyfin client's first sample comes from its own start report (POST /Sessions/Playing), which goes through the same report handler as progress; this pull request did not move or remove that. A client that sends only a Stopped report would be measured from that single sample, which is the behaviour before this change too. The sandbox Jellyfin play in the evidence read 30.5 s for 30.6 s of wall time. I read the handler routing for this and did not run a start-report-less client.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the clarification. I withdraw the suggestion: a normal Jellyfin start report provides the initial sample, so skipping MarkPlanCommitted alone does not establish a regression.
The stop-only case remains untested and, as described, is pre-existing behavior rather than a change introduced by this PR. The sandbox result supports the normal start-report path, though it does not validate that edge case.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Do not register a rebuilt session without its saved watch time after a read error.
When SessionWatch fails, savedWatch returns an unmeasured result (internal/api/handlers/playback.go:1679-1683). The rebuild then registers the session with an empty Watch (internal/playback/transcode_manager.go:905-909). The first progress sample starts a new measurement whose Until is the current time. saveWatch (internal/worker/reconciler.go:359-364) writes that measurement over the stored row because the stored until is not later. A stored prefix, such as 120 seconds, can therefore be replaced by a shorter new measurement, such as 10 seconds. No retry or merge restores the prefix before that save.
A rebuilt session must not replace a saved measurement that it failed to read. The required behavior is that the stored watch time survives a failed read during reconstruction. Choosing how to meet that requirement is left to the change.
The reason will be displayed to describe this comment to others. Learn more.
Not fixing this here. It needs the saved-measurement read to fail during a rebuild, and the result is an under-count for that one play, never an over-count. Guarding the write alone would not help: the rebuilt copy would keep measuring a shorter stretch and record it at stop, so a real fix has to merge the two measurements, and that is more than this change should carry. The read failure is logged.
A stop that reaches a server without the live session restores the
measurement the session last saved. Progress does not trigger a save, so
a stop that carries no newer sample could record a play as measured with
none of the progress accepted since. The stop now observes the latest
accepted sample whenever the measurement was restored, not only when the
stop brought a newer one.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Detached progress is measured at stop time instead of sample time
Revises an earlier Kody suggestion on internal/api/handlers/playback_service.go:659 (2026-11-19 03:10 UTC).
Using time.Now() credits time after the accepted sample as playback, so a seek can be recorded as played seconds. Preserve the sample's observation time and pass it to observeEndSample.
Prompt for LLM
File internal/api/handlers/playback_service.go, lines 660-666:
**Revises an earlier Kody suggestion** on `internal/api/handlers/playback_service.go:659` (2026-11-19 03:10 UTC).
Detached progress is measured at stop time instead of sample time
Applying an old accepted progress sample at `time.Now()` treats the time between that sample and stop finalization as playback time, so a seek that occurred shortly after the saved measurement can be incorrectly recorded as played seconds. Preserve the accepted sample's actual observation time and use it when applying the sample to the restored watch.
The reason will be displayed to describe this comment to others. Learn more.
Not changing this. The attempt row stores the accepted sample's sequence, position and pause state, not when it arrived, so there is no sample time to pass. Observing at stop time widens the interval the advance is judged against by at most the gap between the last save and the stop, about one 15-second sync. The plausibility limit is deliberately loose for that reason: the cost of a wrong guess is a few seconds credited to a short skip.
The reason will be displayed to describe this comment to others. Learn more.
Understood. I’ll withdraw the suggestion: the accepted sample’s observation time is not stored, and you’ve accepted the risk that using the stop time may credit a short skip as playback.
One qualification: the roughly 15-second bound depends on the measurement having been saved by a recent successful sync. If syncs are delayed or fail, the gap could be longer.
The sweep ends a play from its shared row, which carries no measurement,
so an expired play or a retried history write was recorded unmeasured.
It now restores the measurement saved on the lifecycle row.
Also record the approval for removing watched_seconds from admin
playback history before the contract lock.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
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 settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 5 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
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
Retain distributed firing claims through their own validity windows
…wn save
A stop that carries the measurement of the copy it removed now takes the
saved measurement instead when that one is newer, as the periodic save
already refuses to replace a newer measurement with an older one. The
final save at shutdown gets its own deadline, so a slow drain cannot
leave it with an expired context.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
The reason will be displayed to describe this comment to others. Learn more.
Watch saving can exhaust the deadline for node cleanup
The save can consume the remaining shutdownCtx deadline, leaving this node's heartbeat and live-session rows behind even if CleanupSelf could otherwise succeed. Give cleanup its own bounded context so SaveWatch cannot prevent it.
Prompt for LLM
File cmd/silo/main.go, lines 4485-4486:
Watch saving can exhaust the deadline for node cleanup
The independent save can consume the remaining `shutdownCtx` deadline before `CleanupSelf` runs, leaving this node's heartbeat and live-session rows behind even when cleanup would otherwise have succeeded. Give cleanup its own bounded context as well so the watch save cannot prevent the existing shutdown cleanup.
The reason will be displayed to describe this comment to others. Learn more.
Leaving the cleanup as it is. The save now runs on its own 5-second context, so it cannot spend more than 5 seconds of wall time before the heartbeat cleanup, and it is one batched UPDATE. The cleanup steps sharing the 30-second shutdown deadline is how they worked before this change; giving each its own deadline would be a separate change to the shutdown sequence.
The reason will be displayed to describe this comment to others. Learn more.
Understood. We can leave the cleanup sequence as it is. The save has its own five-second timeout, although those five seconds can still reduce the time remaining on the shared shutdown deadline for cleanup.
I’ll withdraw the suggestion to give cleanup a separate context; that would be a broader change to shutdown behavior.
The reason will be displayed to describe this comment to others. Learn more.
🤖 Claude Code in T3 Code (claude-opus-5-5), with a cross-provider round from Codex (gpt-6.2-sol)
One gap is worth fixing before merge. Jellyfin playback rebuilt after a restart still starts with no measurement, and I'm fixing that in a commit on this branch. The other findings are small, bounded under-counts or over-counts in rare multi-replica orderings. They sit within the loose guard this PR already accepts, so I'm not changing them here. They're listed below for the record.
Lower-severity findings, not fixed:
FFmpeg crash, then reconstruction. The crash teardown writes the live measurement to history, and the rebuilt copy then restores the older periodic save. If the viewer seeks after recovery, the stretch between the last save and the crash is judged a seek. History keeps the larger of the two totals instead of adding a separate later stretch, so up to one sync interval (about 15 s) is lost. On the base, the rebuilt copy starts a new stretch, and history adds it.
Takeover after a stop's replica dies (finishStop). When an expiry or abort on the replica holding the copy finishes a stop that another replica accepted, accepted.Sequence == record.LastSequence. The copy never saw that final sample, so it isn't observed. History has the final position, but watch time misses the time since the copy's last report.
Detached Audiobookshelf close.handleFinishedSession now observes the close position against the restored measurement. A seek since the last save that fits the 2× rate guard counts as listening, unlike the live path, which credits only the reported listening total.
Progress accepted on a replica without the copy. It updates the attempt row but not the measurement. At a detached stop, the saved sample is compared with the final one across the whole gap, so a stall followed by a seek can be credited as viewing.
Seek replan rollback, and pause on a stale replica. A sync can save a replan's provisional sample before the replan commits. A pause sets pausedAt without advancing Until, so a stale copy with the same Until can overwrite it. Both need narrow interleavings.
None of these was reproduced on a cluster. They come from source traces.
Jellyfin playback uses its own transcode manager, which rebuilt sessions
without the measurement saved on the lifecycle row. After a restart the
rebuilt copy started from zero and its next sync replaced the saved
prefix. Give that manager the same lifecycle-row reader the native
handler uses.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review summary for head 2a08913. I reviewed e25f0a9, then added one fix.
Fit: 9/10 · Readiness: 8/10 — conditional (assuming CI is green)
Addressed
Jellyfin sessions rebuilt after a restart now restore the saved measurement, like native ones (2a08913).
Left for the maintainers
The lower-severity multi-replica cases in the review above: FFmpeg crash then reconstruction, takeover after a stop's replica dies, detached Audiobookshelf close, progress accepted without the copy, replan rollback, and a stale pause. Each one moves watch time by about one sync interval or less, and none was reproduced. I recommend leaving them out of this PR.
Readiness is 8, not 9, for two reasons. Two-server and restart behavior is shown by source trace and single-node sandbox runs only, and the Jellyfin rebuild fix has no test or live run.
Tests. I disabled the restore and the hand-off, and the two new handler tests (TestStopPlaybackV2WithoutLiveSessionStillStopsTheRow and the confirmed-stop case of TestRealtimeConfirmedStopNotifiesProvidersOnce) then failed. So they detect the fix. The playback, worker, apiv2, jellycompat, and handlers suites pass apart from three upload tests that fail on this host for an unrelated temp-dir permission. Changed-line lint is clean.
Fit. Admin history should record measured watch time on every way a play ends, and a field named watched_seconds that holds a position misleads integrators. Renaming it before /api/v2 locks follows docs/architecture/api-contract.md, and the breaking approval is recorded.
Validated features.#1206 C1 and C2 are not run yet, so no passed case is affected. Validation tasks: reaches #1206 C2 is still correct.
User manual. Unaffected. The manual doesn't describe these history fields.
Other clients. Apple, Android and Roku don't read admin playback history, so N/A as the PR says. jellycompat responses don't change.
Against main as the base, the listAdminPlaybackHistory rename is no
longer a change in this branch, and the contract gate fails on an
approval that matches nothing.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Quick104
added a commit
to darthShadow/silo-server
that referenced
this pull request
Nov 19, 2026
The approval for Silo-Server#4552's listAdminPlaybackHistory change came in with main.
Against the merge base it matches no change in this branch, and the contract
check refuses an approval that matches nothing.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…4497)
* feat(web): direct play reads a file over parallel range connections
One HTTP connection to a long, lossy link moves a fraction of what the
link can carry, so web direct play stalled where the link had room. The
web player now reads the file as several closed ranges at once, through
a Mediabunny source that keeps its read orchestrator, cache and prefetch
profile and changes only how the bytes arrive. mediabunny is pinned to
an exact version because the source relies on UrlSource internals.
The first bytes of each read come from the plan's own URL while the
extra connections warm up, and a range that finds the stripe URL busy
falls back to the plan's URL. The first 5xx answer or transport failure
(fetch, body read, early end) on the stripe URL does the same for the
rest of that range and every later range, with no retry spent on the
stripe URL. The player stripes on, in order:
- stream.parallel_range_url, when the plan carries it;
- the page's own origin, when the page came over HTTP/1.1;
- a proxy node's absolute URL, as issued.
The stream reference in parallel_range_url (st) authorizes each range on
its own, so the player sends no account token to the media origin. It
adds its access token only to a parallel_range_url that has no st, and
never to a proxy node.
Server side:
- New admin setting server.web_media_url: an https origin that serves
the same API over HTTP/1.1 only. Empty is off, and a change applies
without restart.
- The client feature parallel_range_origin_v1 is the client's promise to
read the file from stream.parallel_range_url when the plan has one,
and from stream.url otherwise. Only then, and only for an attempt that
a login session started, does an API-served original_http plan carry
stream.parallel_range_url. An attempt with no login session, such as
one an API key started, keeps stream.url, where st plus the account
token still rebuild an evicted session. stream.url stays valid in
either case, so the client may also read the warm head, overflow
ranges, or a natively played file from it.
- GET, HEAD and OPTIONS on /api/v2/stream/{session_id} answer with
Access-Control-Allow-Origin: *, allow the Range header and expose
Content-Range, with no credentials. GET and HEAD carry them on every
answer, authorization refusals included, so the page can read the
refusal. The preflight is answered before authentication, and
authorization stays in the URL's token and st. No other route gains
CORS.
- nodesessions.Tracker.HoldLingering keeps a direct-play session counted
for sessionTTL after its last range request ends, so the gap between
ranges no longer ends the session.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): keep a striped read going through stripe refusals and dropped bodies
Review fixes for the parallel range reader:
- Any answer from the stripe URL that is not a readable 206 moves the
read to the plan's URL, as a 5xx already did. A 4xx from the media
origin no longer fails a read the plan's URL can serve.
- A response that delivered bytes restarts the retry count, and a body
from the plan's URL that ends early after sending bytes is asked for
again with no retry, as the stock source does.
- A HEAD on a proxy node's direct-play route takes no session hold, so a
probe does not count against the node's capacity for a minute.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(config): refuse a media origin whose port a browser cannot parse
url.Parse accepts any digits as a port, so server.web_media_url could
store https://host:65536. The web player parses that origin before it
plays anything, and the parse error stopped playback of the plan's own
URL too.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(config): refuse a media origin with a port and no hostname
url.Parse puts ":443" in Host for https://:443, so the setting stored
an origin a browser cannot parse.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(web): fall back on an unusable stripe Content-Range and reset retries after a short body
A stripe answer whose Content-Range does not name the range and the
file's size now moves the read to the plan's URL, like a missing one. A
short body from the plan's URL that delivered bytes restarts the retry
count, as a body error after bytes already did. The test file's byte
pattern no longer repeats every 64 KiB, so a duplicated or misplaced
chunk fails the comparison.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(playback): leave parallel_range_url out for header-authenticated media
A client that sends header_authenticated_media_v1 gets a stream URL with no
st, and the media origin's preflight allows only Range. The plan no longer
names a media origin for such a client, so it reads stream.url.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): fall back when a stripe answer names other bytes or another file
A stripe 206 whose Content-Range disagrees with the request or the file's
size now moves the read to the plan's URL, as any other bad stripe answer
does. The plan's URL keeps failing the read on a mismatch.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): move a read off a stripe that goes silent
A stripe request that sends no byte for 8 s is aborted alone and the read
continues at the plan's URL from the same position, instead of waiting for
the page's 20 s stall timeout. A worker abort still ends the range.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* docs(playback): say what a parallel_range_url without st needs
When the URL carries no st, the client sends its account access token, as the
protocol document already says.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* docs(playback): let a replan request negotiate parallel_range_origin_v1
The start request's client_features and a replan request's both decide
whether the plan carries parallel_range_url, as for
progressive_range_refusal_v1.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(apiv2): list OPTIONS in Allow on a 405 for the playback media path
The router answers OPTIONS there before routing, so a 405 for another method
now names it with GET and HEAD.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): keep playing when the media origin does not parse
A stored media origin that new URL() rejects, such as https://a<b.example,
no longer throws during route resolution. The player skips it and applies
its other rules, so stream.url still plays.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(config): refuse a media origin whose hostname a browser rejects
A host such as a<b.example passes url.Parse, but the browser's URL parser
refuses it, and the web player parses this origin before it plays anything.
The setting now refuses the forbidden domain code points of the WHATWG host
parser, with IP literals and valid hostnames unchanged.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): stripe range reads only when the plan names a media origin
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): measure engine throughput over the time responses were receiving
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): treat a body error after the last byte as the end of the response
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): play a plan URL that ignores Range through the stock sequential source
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): cancel a rejected plan-URL body before its slot frees
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* test(web): make the missing-size Content-Range row change only the size
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): move a read to the plan's URL when a stripe body runs past its range
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(activitylog): write one stream row per play and keep failed ranges visible
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(proxy): count a direct-play session only while a request holds it
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* docs(playback): state when parallel_range_url is absent and how the meter counts a striped read
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* refactor(activitylog): check the stream path prefixes inline
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(web): start a seek's first read while both read workers are busy
A seek that found both read workers running waited for their read-ahead
before its first range request left, and a read of one whole cluster
was enough to hold it.
At a page seek the source records the reads Mediabunny still waits for
and cuts each queued read to the bytes those reads need. When a new read
then finds every worker running, each older run is cut to the bytes its
reads wait for and its other ranges are cancelled. The older run that
owes the fewest bytes is retired, its unmet bytes go back on the queue,
and the new read takes its place. Runs for the latest seek take free
slots first.
Each range now has its own abort signal, so a cancelled range frees its
slot and never counts as a stripe failure.
The source relies on more Mediabunny private members for this; the
header comment lists them. The tests cover both workers busy, a queued
read from before the seek, a read after the seek that lands on an old
run, and the bytes every old read still receives.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* refactor(web): split the parallel range source tests and Mediabunny internals
The size ratchet failed the parallel range source and its test file,
which crossed 800 lines. Nothing about behavior changes; text moves.
The types that describe Mediabunny's private members, and the list of
internals the source relies on, now live in mediabunnyInternals.ts,
with the note that an upgrade re-runs both test files. The shared fake
server and read helpers move to parallelRangeSource.test-support.ts, and
the seek tests get their own file, parallelRangeSource.seek.test.ts.
Each test file registers its own afterEach that frees the sources it
made.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* docs(web): correct the seek comments in the parallel range source
The header said an older run is one that serves only reads from before
the latest seek. The code retires a run that started before the latest
seek and has no read made after it pending, so the comment now states
that rule.
The comment also gave a delay figure without the rate it was measured
at, and it did not name a cost of the rule: a run that serves the new
playback between its reads counts as older, so a later read can retire
it and its read-ahead is fetched again. Both are now stated.
In the Mediabunny internals list, nextAge is the orchestrator's one
counter for workers, cache entries and queued reads, and a requeued
read takes its age from it.
Comments only; no behavior changes.
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
* fix(activitylog): keep a row for a stream sent again from its origin, none for a preflight
A GET on a stream path answered 200 for a range past byte 0 is a progressive
remux started again, so it keeps its activity row. An answered OPTIONS on a
stream path is the media origin's CORS preflight and writes none. The
preflight answer carries Access-Control-Max-Age: 600, so a browser that
preflights Range does not repeat it every 5 seconds.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(web): retire a worker for a seek near the end of the file, and bound the meter's spans
A seek's first read can ask for the same hole as a read queued before the
seek: Mediabunny aligns the start to 64 KiB and caps the end at the file's
size. The source now tells a new read from a queue restart by whether
read() is running, and the worker that takes a retired worker's place takes
the queued reads it covers, so their bytes are not fetched twice.
The striped source counts every range into one metered run, kept as merged
stretches of receiving time and not one span per response. Stock reads keep
a run each, so the meter's gate on short requests applies to them as before,
and the page reports each request under its own key again.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(web): count a restarted pre-seek read as older from its start
A read queued before a seek starts on a new worker once an old one stops.
That run took the current seek count as its start, so it counted as serving
the new playback: the seek's next read could not retire it and waited for it.
A run that starts with only reads recorded at a seek now counts as older.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* chore(apiv2): drop the approval for a breaking change already on main
The approval for #4552's listAdminPlaybackHistory change came in with main.
Against the merge base it matches no change in this branch, and the contract
check refuses an approval that matches nothing.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* feat(proxy): keep a direct-play session counted between range requests
A striping player reads one file through many short range requests. A node
counted the session only while a request was open, so it dropped out of the
node's capacity count and the admin's session list in each gap.
The last request of a direct play to end now lingers for the session TTL when
it delivered media. A HEAD, a refusal or an unsatisfiable range delivered
none: it adds no linger, and ends none that an earlier request started. The
lingering record expires with the count instead of being refreshed past it.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* feat(playback): name the stripe URL for node-served and same-origin plays
stream.parallel_range_url was set only for a plan the API serves, on the
admin's media origin. With the default routing a proxy node serves direct
play, so a deployment with proxy nodes never striped.
The server now names one of three for an original_http plan whose attempt
negotiated parallel_range_origin_v1: the proxy node's own direct-play URL,
the same stream on the media origin, or the plan's own stream relative to the
API root. The media origin is named only for a client on the default access
path. The URL always authorizes itself: the contract no longer has a client
add its account token to a URL without st, which would have sent a login
token to a node. The field's format is uri-reference.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* feat(web): stripe on a proxy node's URL and on the page's own origin
The engine uses the stripe URL the server names exactly as given and adds no
token to it. A reference to the plan's own stream is striped only when the
page loaded over HTTP/1.1, where the browser opens several connections. A
proxy node's URL is striped as issued.
When the stripe URL is the plan's own URL there is one URL, so no range is a
stripe range: every range uses it, up to 4 at once, and a transport failure is
retried there like any read's.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* feat(web): stop striping when the striped URL answers over HTTP/2 or HTTP/3
HTTP/2 and HTTP/3 put every request to an origin on one connection, so
parallel ranges there add requests and no connections. A proxy node or a
media origin behind such a front is common enough: the development
deployment's nodes answer over HTTP/2.
After a completed range the reader asks the browser which protocol the
striped URL answered over, and hands the source to the stock reader when it
was HTTP/2 or HTTP/3. The API's and the node's stream answers carry
Timing-Allow-Origin so a cross-origin answer can say. A browser that does not
say leaves the reader striping.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(web): hand no worker at its target to the stock reader
The range that tells the source its URL answers over HTTP/2 can be the one
that takes its worker to its target. Handing that worker on made the stock
reader ask for the bytes after the file's end, which a server refuses with
416.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* refactor(web): move two range-request helpers out of the parallel range source
The source crossed the 800-line limit. The inactivity signal and the
protocol lookup use nothing of the source, so they move to rangeRequest.ts.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(proxy): remember a delivery on the session, and end a linger when another transport holds it
A range that delivered media could end while a probe for the same session
was still open; the probe ending last then dropped the session. Delivery is
now recorded on the session, so the last release lingers whichever request it
belongs to. A plain hold for the session, as a remux after a replan takes,
ends a running linger: when that remux ended, the direct play's record came
back.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(web): give the stock reader its own read-ahead after a hand-off
After the reader handed a source to the stock reader, new reads still got the
32 MiB read-ahead target meant for parallel ranges, and nothing retired a
stock worker, so a seek could wait behind tens of MiB on one connection. The
stock reader now keeps Mediabunny's read-ahead, and a worker handed over keeps
only the bytes its reads still wait for.
The protocol check also no longer stops at the first HTTP/1.1 answer: a front
can answer later requests over HTTP/3.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(proxy): bound a session's last writes and keep a removed session removed
The last release of a hold wrote to Redis on the caller's context, without a
bound of its own. It now runs detached from the request and within the
tracker's cleanup timeout.
A lingering release writes its record outside the lock, so a Remove or
Cleanup that landed first was undone by it for the session TTL: the record is
deleted again when the tracker no longer knows the session. After a refresh
write, a lingering record goes back to the time its linger has left, not only
when the bytes differ.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(proxy): end a session whose last release is a direct-play range that outlived a remux
A replan to remux on the same node can start while a direct-play range is
still open. When the remux ended first, that range's release was the last and
made the finished remux linger for the session TTL. A session a plain hold
joined ends at its last release.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
* fix(proxy): let the latest hold decide a session's transport, and serialize the linger cleanup
A direct-play range that started while a remux request was still open
inherited the remux's mark and ended the session at its release, so the play
left the count until its next range. The latest hold now decides: a lingering
hold after a plain one makes the session a direct play again, and a plain hold
after a lingering one ends its linger.
The cleanup after a lingering write checked the tracker and deleted outside
the lock, so a registration between the two lost its record. Both run under
the lock. The repair after a refresh no longer rides on refresh's context.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
---------
Signed-off-by: Anagh Kumar Baranwal <[email protected]>
Co-authored-by: Quick104 <[email protected]>
Co-authored-by: Claude Fable 5.2 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bugSomething isn't workinggoPull requests that update go codepriority: P2Limited scope, workaround exists, or polishsize/XL500–999 added + deleted lines (all files); change volume, not priority.
1 participant
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: N/A
Validation tasks: reaches #1206 C2 (how a stopped session's history is recorded; no intended change to cleanup)
Other clients: N/A (no client-visible change outside the web admin, which this updates; Apple, Android and Roku do not read admin playback history)
A developer integrating a third-party monitor reported two problems with admin playback history. A 16-second play came back with
measured: falseand null watch-time fields. Andwatched_secondsreads like watch time but holds the position the play ended at.The unmeasured play was ended by an administrator stop that the player confirmed. That path removes the live session first, then records the play from the playback attempt row, which never had the session's measurement. The same loss happens when a stop lands after a server restart or on an API server that does not hold the session, when an abort or expiry finishes an earlier stop, and when a Jellyfin stop reaches such a server.
This keeps every play measured through those paths and renames the history field to say what it holds.
Approach
Measurement. A session's watch-time measurement is saved with its lifecycle row (
playback_session_lifecycle.watch, new migration) when the session starts, on each 15-second live-session sync, and once more at graceful shutdown. It lives there, not on the live-session sync row, because the sync row is deleted when its server shuts down.The first sample is now taken when the start commits its plan, not at admission, so time spent preparing a transcode is not judged as viewing. The existing guard against implausible credit is unchanged and applies to a restored measurement too.
Field name. History entries, including the one inside the
session.stoppedevent, carryend_position_secondsand no longer carrywatched_seconds. There is no alias:/api/v2is pre-1.0, and no first-party client reads the field (checked on the main branches of silo-apple, silo-android and silo-roku). The account watch summary keeps its ownwatched_seconds, which is watch time, and its description now says so. The database column keeps its name, so history writes from servers not yet upgraded still land during a rolling upgrade.The two changes share a pull request because they touch the same history entry and the same tests.
jellycompat: no Jellyfin-protocol response changes; a Jellyfin stop that reaches a server without the session is now measured. The user manual does not describe these fields.
Validation
cmd/silocould not be tested locally after the rebase because the embedded web build was absent. New tests cover a saved measurement continuing on another server, a confirmed administrator stop, and a detached stop measured through its final position; the two handler tests fail with the fix removed.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-4552/
Risks
watched_secondsleaves admin playback history entries and thesession.stoppedevent. Readend_position_secondsfor the end position andplayed_secondsfor watch time.jsonbcolumn onplayback_session_lifecycle.UPDATEper server per 15-second sync, skipped for sessions whose measurement did not change.Checklist
AI Disclosure
🤖 Generated with Claude Code
Note
Persist playback watch time across stops and rename history
watched_secondstoend_position_secondsSessionManager.MarkPlanCommitted, is serialized with its sampling state viaWatchTimeJSON methods, and is persisted to theplayback_session_lifecycletable's new nullable JSONBwatchcolumn (migration).TranscodeManager.reconstructSessionrestores a saved measurement for rebuilt sessions, so measurement survives cross-server session reconstruction.watched_secondsis renamed toend_position_secondsend-to-end: API structs, OpenAPI schema, web types, and docs. The database columnwatched_secondsis unchanged; only the field name differs from the stored end position.listAdminPlaybackHistorynow requiresend_position_secondsinstead ofwatched_seconds— a breaking API change recorded in breaking-approvals.json. Any out-of-tree consumer readingwatched_secondsfrom the v2 playback-history response must switch toend_position_seconds.Macroscope summarized 2a08913.