Skip to content

feat(player): bound budget-parked origin streams with detach and ranged resume - #100

Merged
Quick104 merged 3 commits into
mainfrom
feat/origin-stream-bounded-park
Jul 24, 2026
Merged

Quick104 merged 3 commits into
mainfrom
feat/origin-stream-bounded-park

Conversation

@Quick104

@Quick104 Quick104 commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Implements #94.

Problem

When the playback source cache hits budget, the origin stream suspends its URLSession task and leaves the HTTP response parked indefinitely. A reverse proxy with nginx's default client-facing send_timeout 60s kills that healthy-but-backpressured response, and the failure only surfaces minutes later when the cache drains onto a dead task.

What this does

  • Bounded park lifecycle: a budget-parked stream stays warm for a grace period (PlaybackOriginStreamPolicy.detachAfterSeconds, default 25s — under any sane proxy timeout), then deliberately cancels into a new detached state at the exact writeCursor. Expected cancellations are tracked by task ID so a deliberate detach never advances unproductiveStreak, enters outage parking, or fires onOriginOutageChanged/onPlaybackSourceInterrupted. Waiters and cached bytes are preserved.
  • Exact-byte resume: returning demand reopens Range: bytes=<cursor>- through the shared reopen seam factored out of retarget(to:order:) (retarget resets routing state; detach-resume preserves reconnect history), with double-open guards and generation-checked scheduled reconnects (fixes a latent stale-reconnect race).
  • True high/low-water hysteresis: shouldPrefetch is now a sticky two-threshold gate (disarm at high water, re-arm at lowWaterBytes), so cache oscillation near the budget can't cause close/reopen storms. The demand-at-cursor override is untouched.
  • Entity validation: the first response's strong ETag is captured (weak validators ignored); reopens at cursor > 0 send If-Range. A 200 at nonzero cursor after a sent validator means the entity changed: new .entityChanged end cause (retry cap 0), no bytes appended, escalated as sourceEntityChanged — and the ViewModel discards the source-cache handoff instead of stashing it so a replaced file's prefix can never leak into recovery. With no ETag, behavior is exactly today's .rangeIgnored path.
  • Delivery gating: resumeCapable (wire delivery original_http) threaded plan → proxy → origin stream; non-resumable deliveries keep the legacy indefinite suspend. direct_stream_resume_v1 server advertisement surfaced in the stats overlay for diagnostics.
  • Injectable clock for the watchdog/park timing so all lifecycle tests run without wall-clock waits.

Coordination

Verification

cd iosApp && xcodegen generate
xcodebuild build  -scheme Silo -destination 'iPhone 17 Pro sim'   ** BUILD SUCCEEDED **
xcodebuild test   -scheme Silo -destination 'iPhone 17 Pro sim'   Executed 735 tests, 0 failures

New coverage (PlaybackOriginStreamResumeTests, NWListener fake origin + fake clock): park→detach at exact cursor; demand reopen with exact Range + If-Range; deliberate detach advances no failure state; hysteresis single-connection under oscillation; entity-change gives up without cache append and escalates; resumeCapable=false parks indefinitely (legacy behavior); weak ETags never sent as If-Range.

Live on-device validation against the dev server (iOS simulator, updated server build): route mounted with resumeCapable=true serverAdvertisesResume=true, direct-play origin stream + chunk fetches healthy, playback clean end to end.

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 self-review pass reported no remaining findings (0.87 confidence); Claude's independent review verified the expected-cancellation bookkeeping across handleCompletion/connectionEnded, the retarget-vs-detach-resume state split, and that the entity-change path discards (not stashes) the cache handoff. Full test suite re-run independently on the simulator by the reviewer.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added direct stream resume support surfaced through protocol V3 planning, execution metadata, and playback UI/network stats.
    • Introduced clock-driven watchdog/resume behavior with explicit detach/resume capability and improved proxy-aware resume signaling.
    • Implemented hysteresis-based cache prefetch re-arming.
  • Bug Fixes
    • Strengthened resume/interleaved request correctness with conditional range validation (ETag/If-Range) and stricter content-range checks.
    • Improved handling of entity-change scenarios to avoid unsafe parking and stale cache reuse.
  • Tests
    • Added coverage for prefetch hysteresis, protocol V3 delivery feature mapping, and deterministic resume/reconnect behaviors (including Range/If-Range semantics).

…ed resume

Implements #94: a budget-parked direct-play origin stream now stays warm
only for a bounded grace (default 25s), then deliberately detaches at the
write cursor instead of suspending indefinitely under reverse-proxy send
timeouts; returning demand reopens an exact-byte Range request through the
shared retarget seam. Deliberate detach never advances the failure streak,
outage state, or interruptions. Adds sticky high/low-water prefetch
hysteresis, strong-ETag capture with If-Range validation on reopen (a full
200 against a sent validator escalates as sourceEntityChanged and discards
the cached prefix instead of stashing it), delivery-gated resume threading
from the V3 plan, an injectable origin-stream clock, and stats overlay
diagnostics. Non-resumable deliveries keep the legacy indefinite park.

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 48f0dd1c-c8dd-4371-8be2-379f115e0cbc

📥 Commits

Reviewing files that changed from the base of the PR and between 2237e12 and fffbae7.

📒 Files selected for processing (2)
  • iosApp/Tests/PlaybackOriginStreamResumeTests.swift
  • iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • iosApp/Tests/PlaybackOriginStreamResumeTests.swift
  • iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift

📝 Walkthrough

Walkthrough

The PR adds direct-stream resume metadata, bounded origin-stream detachment and reopening, strong ETag and range validation, entity-change propagation, cache prefetch hysteresis, playback diagnostics, and focused integration tests.

Changes

Direct stream resume

Layer / File(s) Summary
Protocol V3 resume metadata
iosApp/iosApp/Screens/Player/ProtocolV3/*, iosApp/iosApp/Screens/Player/PlaybackExecutionPlan.swift, iosApp/iosApp/Screens/Player/PlaybackSessionBridge.swift, iosApp/iosApp/Screens/Player/PlayerViewModel.swift
Protocol capabilities and execution plans preserve wire-delivery and server-feature metadata, including direct stream resume.
Origin stream detach and resume
iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
Origin streams use injected clocks, bounded parking, detach/resume reopening, strong ETag If-Range requests, response validation, and .entityChanged termination.
Range fetching and proxy recovery
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift, iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift, iosApp/iosApp/Screens/Player/PlayerViewModel.swift
Chunk fetches validate ranges and entities; proxy resources serialize cache writes, invalidate changed entities, escalate interruptions, and propagate resume settings.
Cache, statistics, and validation
iosApp/iosApp/Screens/Player/PlaybackStats.swift, iosApp/Tests/*
Cache prefetch hysteresis and resume status reporting are added, with deterministic tests covering detach/resume, validators, entity changes, outage causes, and Protocol V3 propagation.

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

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-apple#66 — Overlaps with the origin-stream reconnect, policy, and proxy plumbing extended by this PR.
  • Silo-Server/silo-apple#68 — Overlaps with the source-proxy/cache integration points changed for resume capability and cache behavior.

Sequence Diagram(s)

sequenceDiagram
  participant PlayerViewModel
  participant PlaybackSourceProxy
  participant PlaybackOriginStream
  participant OriginServer
  PlayerViewModel->>PlaybackSourceProxy: configure resume capability
  PlaybackSourceProxy->>PlaybackOriginStream: reopen detached stream
  PlaybackOriginStream->>OriginServer: request range with If-Range
  OriginServer-->>PlaybackOriginStream: return validated or changed response
  PlaybackOriginStream-->>PlaybackSourceProxy: store data or report entityChanged
  PlaybackSourceProxy-->>PlayerViewModel: report interruption and recovery state
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.08% 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 summarizes the main change: bounded parking with detach and ranged resume for origin streams.
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/origin-stream-bounded-park

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: 484f233fa0

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

@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: 2237e12bb5

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

@Quick104
Quick104 merged commit d49d805 into main Jul 24, 2026
1 check passed
@Quick104
Quick104 deleted the feat/origin-stream-bounded-park branch July 24, 2026 15:30
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