Skip to content

feat(player): resume progressive direct play transparently after mid-stream transport failures - #99

Merged
Quick104 merged 2 commits into
mainfrom
feat/progressive-range-resume
Jul 24, 2026
Merged

Quick104 merged 2 commits into
mainfrom
feat/progressive-range-resume

Conversation

@Quick104

@Quick104 Quick104 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Implements #80.

Problem

A Shield fills Media3's buffer, stops reading, and a proxy with nginx's default send_timeout 60s kills the idle HTTP/2 stream. OkHttp surfaces StreamResetException → ERROR_CODE_IO_UNSPECIFIED, which bypasses even the one-shot transient recovery and lands on a full server replan with a visible hiccup.

What this does

  • In-loader range resume (MediaLoadRetryPolicy): HTTP/2 stream resets, connection shutdowns, and premature EOF become retryable for progressive ORIGINAL_HTTP loads that have made real byte progress — Media3's progressive loader then reopens a ranged DataSpec at the exact byte offset through the existing authed stack. No player error, no setMediaItem+prepare, no replan, no ViewModel involvement.
  • Per-attempt progress tracking: Media3 reports cumulative bytes per load task, so the policy tracks deltas per loadTaskId (cleaned up in onLoadTaskConcluded) — zero-progress reopens fall out of the retryable class and exhaust instead of looping. Existing 90s cumulative retry window and backoff still bound everything.
  • Entity guard (RefreshingHttpDataSource): captures the response ETag per URI, sends If-Range on ranged reopens, and throws a non-retryable EntityChangedException when the entity changed — closing the Media3 silent-skip hole where a 200 answer to a ranged request splices bytes from two file revisions. The single-flight 401 refresh is untouched.
  • Scope discipline: HLS retry behavior unchanged (delivery-gated), ViewModel recovery ladder unchanged, SiloLoadControl audit deferred as the issue allows. Phone and TV share all of this via android-shared. direct_stream_resume_v1 added to advertised client features.
  • Diagnostics: per-retry log (exception, bytesLoaded, resume offset, attempt, delay) and a retry-exhausted marker.

Coordination

Verification

./gradlew :android-shared:testDebugUnitTest    735 tests, 0 failures (rerun fresh)
./gradlew :androidApp:assembleDebug :androidTvApp:assembleDebug   BUILD SUCCESSFUL

New coverage includes a real Media3 integration test (ProgressiveDirectPlayResumeIntegrationTest: ExoPlayer + MockWebServer + the production data-source chain under Robolectric): kills the first 206 mid-body and asserts the next request carries the exact Range and If-Range and playback reaches STATE_ENDED with no player error; plus zero-progress exhaustion, ETag-mismatch abort, and 416 terminal cases — each asserting no third request is issued. Policy unit tests and entity-guard tests cover the remaining matrix.

Field check: debug build installed on a Galaxy S26 Ultra streaming against the updated dev server — clean 200 → 206 ranged request pattern observed server-side, no errors.

AI Disclosure

  • Tool(s): Claude Code (orchestration/spec/review), OpenAI Codex CLI (implementation)
  • Model(s): claude-fable-5, gpt-5.6-sol
  • Involvement: fully AI-generated, human-directed
  • Adversarial review: Codex's two-axis self-review reported no remaining findings after fixes; Claude's independent review confirmed the cumulative-vs-per-attempt bytes distinction (the subtlest correctness point), verified the shared policy can't regress HLS, and validated the ETag guard against Media3's skip-splice behavior. Tests re-run independently by the reviewer.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added support for guarded resumption of interrupted direct playback using ETag validation (If-Range) to ensure the media hasn’t changed.
    • Enabled progressive direct-play recovery after mid-body transport failures.
    • Playback now advertises direct-stream resume support during playback setup.
  • Bug Fixes

    • Improved retry/abort behavior to prevent unsafe retries (e.g., entity changes, invalid/unsatisfiable ranges, and zero-progress scenarios).
  • Tests

    • Expanded unit and Robolectric integration coverage for ranged reopen/ETag handling and progressive resume retry behavior.
  • Chores

    • Updated Gradle test dependencies for mocking and Media3 testing.

…stream transport failures

Implements #80: HTTP/2 stream resets, connection shutdowns, and premature
EOF on ORIGINAL_HTTP progressive loads now retry inside Media3's load-error
policy (gated on real per-attempt byte progress, tracked as deltas of
Media3's cumulative load-task bytes), so the loader reopens a ranged
DataSpec at the exact byte offset with no player error or remount. The
authed data source captures the entity ETag, sends If-Range on ranged
reopens, and aborts with a non-retryable EntityChangedException on
mismatch, preventing Media3's silent 200 skip-splice across file revisions.
Advertises direct_stream_resume_v1. HLS retry behavior and the ViewModel
recovery ladder are unchanged.

Code written by OpenAI Codex CLI (gpt-5.6-sol) from a Claude-authored spec;
reviewed and verified by Claude.

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

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds progressive direct-play resume support through capability negotiation, ETag/If-Range guards, byte-aware Media3 retry handling, player wiring, and unit/integration coverage.

Changes

Progressive direct-play resume

Layer / File(s) Summary
Capability and test wiring
shared/.../PlaybackProtocolV3.kt, gradle/libs.versions.toml, android-shared/build.gradle.kts
Advertises direct_stream_resume_v1 and adds Media3, Robolectric, and MockWebServer test dependencies.
Entity validation for ranged opens
android-shared/.../AuthenticatedDataSourceFactory.kt
Tracks URI and ETag state, applies If-Range on ranged reopen, and throws EntityChangedException for changed entities.
Byte-aware resumable retry policy
android-shared/.../MediaLoadRetryPolicy.kt
Tracks attempt byte progress and classifies eligible transport failures for retry.
Media item resumability wiring
android-shared/.../SiloPlayerFactory.kt, android-shared/src/androidUnitTest/.../SiloPlayerFactoryRetryPolicySourceTest.kt
Connects original HTTP media items to the guarded data source and retry policy.
Entity and playback resume validation
android-shared/src/androidUnitTest/.../*
Tests ETag guards, authentication refresh, retry classification, ranged requests, terminal failures, and successful playback completion.

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

Sequence Diagram(s)

sequenceDiagram
  participant PlaybackClient
  participant SiloPlayerFactory
  participant SiloMediaLoadErrorHandlingPolicy
  participant RefreshingHttpDataSource
  participant MockWebServer
  PlaybackClient->>SiloPlayerFactory: build original HTTP media item
  SiloPlayerFactory->>SiloMediaLoadErrorHandlingPolicy: provide resumable URI predicate
  SiloMediaLoadErrorHandlingPolicy->>RefreshingHttpDataSource: retry after byte-progress transport failure
  RefreshingHttpDataSource->>MockWebServer: send ranged request with Range and If-Range
  MockWebServer-->>RefreshingHttpDataSource: return partial response with ETag
  RefreshingHttpDataSource-->>PlaybackClient: deliver resumed bytes or EntityChangedException
Loading

Possibly related issues

  • Silo-Server/silo-android issue 80 — Covers progressive direct-play recovery, ETag validation, and integration testing.
  • Silo-Server/silo-server issue 443 — Relates to capability negotiation and Range/If-Range streaming behavior.
  • Silo-Server/silo-android issue 3 — Relates to custom Media3 load-retry policy changes.
  • Silo-Server/silo-apple issue 94 — Implements comparable resumable ranged playback behavior on another client platform.

Possibly related PRs

Suggested reviewers: rxwatcher

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.61% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: transparent progressive direct-play resume after mid-stream transport failures.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/progressive-range-resume

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: 760cf359ce

ℹ️ 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".


val mediaLoadErrorHandlingPolicy = SiloMediaLoadErrorHandlingPolicy()
val mediaLoadErrorHandlingPolicy = SiloMediaLoadErrorHandlingPolicy(
isResumableProgressiveDirectPlay = { resumableProgressiveDirectPlay },

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 Tie retry mode to the mounted media item

After an ORIGINAL_HTTP video sets this factory field true, it stays true until SiloPlayerFactory.buildMediaItem is called again; the audiobook screens build plain MediaItems directly (AudiobookPlayerScreen.kt:116-128), and the audiobook VM can mount REMUX/TRANSCODE HLS (AudiobookPlayerViewModel.kt:650-672). In that sequence, HLS load errors are evaluated as resumable direct play, so an early unexpected end of stream with no bytes loaded no longer gets the server-restart retry this policy previously guaranteed. Keep this state per media source/item, or reset it for non-video mounts.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 69799a8. Replaced the factory-wide boolean with URI-scoped classification: buildMediaItem now stores the direct-play stream URI (resumableDirectPlayUri), and both the retry policy and the ETag entity guard match each failing load's own dataSpec.uri against it. Audiobook mounts that bypass buildMediaItem, subtitle sidecars, and HLS loads are no longer classified as resumable direct play. Also restored the unconditional retry for zero-progress "unexpected end of stream" failures, so the pre-existing server-restart resilience applies regardless of the flag state.

val length = open(guardedDataSpec)
val responseEtag = responseHeaders.headerValue("ETag")
val previousEtag = entityEtag
if (previousEtag != null && responseEtag != null && responseEtag != previousEtag) {

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 Reject ambiguous full responses during ranged resume

When a ranged reopen carries If-Range and the entity has changed, the server can answer with a full 200 OK response instead of a 206 range, and some servers/CDNs may omit the new ETag. This check only aborts when a different ETag is present, so a 200/no-ETag response falls through; OkHttpDataSource then manually skips dataSpec.position bytes from the replacement entity, which can resume playback in the wrong file contents. Treat ranged resumes with a prior validator but no confirming range/validator as an entity change or restart from zero.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 69799a8. A ranged reopen with a prior validator now rejects a 200 response unless it carries an ETag matching the stored one — a full-body replacement entity (with or without a new ETag) raises EntityChangedException instead of being byte-skipped into the old buffer. Additionally, If-Range is only sent for strong validators per RFC 7233 (weak W/ ETags are still captured for the equality check), and the guard itself is now scoped to the resumable direct-play URI so HLS/subtitle opens skip it entirely.

…en ranged-resume validation

Address review findings on the progressive range-resume feature:

- Replace the factory-wide resumable boolean with URI-scoped
  classification: the retry policy and entity guard now match each
  failing load's own URI against the direct-play stream URI, so
  audiobook mounts that bypass buildMediaItem, subtitle sidecars, and
  HLS loads keep their existing retry semantics.
- Restore unconditional retry for zero-progress "unexpected end of
  stream" failures (server-restart resilience, including first-attempt
  failures).
- Reject a 200 response on a ranged reopen with a prior validator
  unless it carries a matching ETag; send If-Range only for strong
  validators per RFC 7233.
- Engage the ETag entity guard only for the resumable direct-play URI.
- Keep socket-level causes retryable when wrapped in ParserException;
  the parser veto now only blocks EOF-style premature-end
  classification.
- Clear the active delegate before throwing EntityChangedException.
- Route resume-decision logs through SiloLog (PLAYBACK) so they reach
  diagnostics bundles.

Implementation drafted by OpenAI Codex (gpt-5.6) under review.

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

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

Caution

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

⚠️ Outside diff range comments (1)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicy.kt (1)

207-224: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Avoid depending on OkHttp internal HTTP/2 exceptions
isResumableTransportFailure() still matches okhttp3.internal.http2.StreamResetException and okhttp3.internal.http2.ConnectionShutdownException, which are outside OkHttp’s public API. That makes this retry path brittle across OkHttp upgrades; prefer a public signal or a wrapper you control instead.

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

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicy.kt`
around lines 207 - 224, Update Throwable.isResumableTransportFailure() to remove
direct checks for OkHttp internal StreamResetException and
ConnectionShutdownException. Replace them with a stable public transport-failure
signal or an application-controlled wrapper, while preserving resumable handling
for EOFException and unexpected-end-of-stream ProtocolException and keeping
findResumableTransportFailure() unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicy.kt`:
- Around line 207-224: Update Throwable.isResumableTransportFailure() to remove
direct checks for OkHttp internal StreamResetException and
ConnectionShutdownException. Replace them with a stable public transport-failure
signal or an application-controlled wrapper, while preserving resumable handling
for EOFException and unexpected-end-of-stream ProtocolException and keeping
findResumableTransportFailure() unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 147e5751-01b5-410d-a282-730e47b20392

📥 Commits

Reviewing files that changed from the base of the PR and between 760cf35 and 69799a8.

📒 Files selected for processing (6)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AuthenticatedDataSourceFactory.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicy.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AuthenticatedDataSourceFactoryTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicyTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/ProgressiveDirectPlayResumeIntegrationTest.kt
🚧 Files skipped from review as they are similar to previous changes (3)
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/ProgressiveDirectPlayResumeIntegrationTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/MediaLoadRetryPolicyTest.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AuthenticatedDataSourceFactory.kt

@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: 69799a86f2

ℹ️ 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".

CLIENT_VIDEO_TRANSFORMATIONS_FEATURE,
DEVICE_QUIRKS_V3_FEATURE,
SEEK_REANCHOR_V3_FEATURE,
DIRECT_STREAM_RESUME_V1_FEATURE,

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 Update the serialized feature expectations

Adding DIRECT_STREAM_RESUME_V1_FEATURE to the default V3 client_features list changes every serialized start request, but shared/src/commonTest/kotlin/org/siloserver/silo/network/api/PlaybackApiTest.kt still asserts the exact list ending at seek_reanchor_v1. As a result the shared API test for V3 start negotiation fails until the expected feature list is updated or this new feature is gated out of the default request.

Useful? React with 👍 / 👎.

.withAuthHeaders(snapshot)
val length = open(guardedDataSpec)
val responseEtag = responseHeaders.headerValue("ETag")
if (previousEtag != null && dataSpec.position > 0L) {

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 Require a strong validator before ranged resume

When the first response only supplies a weak ETag, this branch still treats previousEtag != null as enough to validate a nonzero reopen even though withIfRangeHeader refuses to send weak validators. For servers/CDNs that return weak or missing ETags, a later 206 (or a 200 with the same weak tag) is accepted and Media3 can splice bytes from an unvalidated representation after a mid-stream reconnect; only allow the transparent resume path after a strong validator (or another byte-range-safe validator) has been confirmed.

Useful? React with 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant