Repository navigation
SiloPlayer: streaming origin fetch — fix buffering on high-latency connections - #66
Conversation
…nnections Users on fast but high-RTT connections (gigabit fiber, 150ms+ to the server) buffered even on 1080p files while third-party direct-play clients streamed the same files fine. Root cause: the source proxy fetched origin bytes as strictly sequential, fully buffered 2-16 MiB range requests — each chunk pays a fresh TCP slow-start plus one RTT of dead air, capping effective throughput at roughly 14 Mbps at 150 ms RTT regardless of line speed. On LAN the overhead rounds to zero, which is why local testing never reproduced it. Replace the chunked fetcher with long-lived streaming range GETs (the approach AetherEngine adopted after its own chunked reader collapsed on CDNs): - Up to two origin streams (playback + roamer) so the matroska open pattern (head probe <-> cues at tail) and demuxer recycling never churn the warm playback connection; ride-through/spawn/retarget policy routes each demand. - Bytes store into the span cache incrementally as each URLSession delivery arrives — a cache miss now unblocks after ~1 RTT instead of a full-chunk transfer, keeping well clear of the demuxer's 10 s rw_timeout. - Readahead parks the task on TCP backpressure at the cache budget and resumes instantly; the connection is never closed and re-requested. - Reconnect with exponential backoff and progress-aware give-up replaces fail-on-first-error: transient network blips now ride through silently on the forward buffer instead of tearing down and rebuilding the player. Interruption reasons (server outage, network loss, premature EOF, session missing) surface only after retries are exhausted. - Serve loops await cache fills via registered waiters (register-first ordering, re-driven on retarget/finish, failed only for the responsible stream on give-up). - Span cache: adjacent streaming slabs append in place (16 MiB spans) instead of paying the full-copy merge; appends refresh eviction age. - Loopback playback now starts the origin stream at plan time, overlapping connect + slow-start with demuxer spawn. Adversarially reviewed: fixed retarget-stranded waiters, waiter registration racing stream give-up, park/unpark races (suspend under lock + post-park recheck), terminal-stream revival leaking a live URLSession, give-up failing waiters of healthy streams, and generation guards on finish/give-up. 3 platforms build; 511 tests pass (15 new: routing policy, reconnect policy, cache append). Hardware-validated on Apple TV 4K (3rd gen) with a 63 Mbps DV P7 TrueHD title: clean startup, seeks, steady segment cadence, no watchdog escalations. Co-Authored-By: Claude Fable 5 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThis PR replaces chunk-based prefetch with demand-driven origin streaming, adds new stream selection and reconnect policies, rewires cache and response handling around long-lived streams, and updates tests plus loopback prefetch startup. ChangesDemand-driven origin streaming
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant PlaybackSourceProxy
participant PlaybackSourceResource
participant PlaybackOriginStream
participant PlaybackSourceCache
Client->>PlaybackSourceProxy: respondGet(request)
PlaybackSourceProxy->>PlaybackSourceResource: awaitTotalLength / awaitData
PlaybackSourceResource->>PlaybackSourceCache: contains(offset) / read
PlaybackSourceResource->>PlaybackOriginStream: ensureStream / noteDemandHint
PlaybackOriginStream->>PlaybackSourceCache: store bytes
PlaybackOriginStream-->>PlaybackSourceResource: streamDidStore / streamEnded
PlaybackSourceProxy-->>Client: served response
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift`:
- Around line 287-301: `resumeFillingIfNeeded()` in `PlaybackSourceOriginStream`
resumes a parked task without updating `lastDataAt`, so a freshly unparked
stream can still look stalled to the watchdog. When the task is resumed inside
the `parked`/`cancelled` check, also refresh `lastDataAt` at that same point so
the connection’s activity timestamp reflects the unpark event and avoids an
unnecessary reconnect.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: df62baeb-9068-42a8-91d3-7dca75148f90
📒 Files selected for processing (6)
iosApp/Tests/PlaybackOriginStreamPolicyTests.swiftiosApp/Tests/PlaybackSourcePrefetchPolicyTests.swiftiosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swiftiosApp/iosApp/Screens/Player/PlaybackSourcePrefetchPolicy.swiftiosApp/iosApp/Screens/Player/PlaybackSourceProxy.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swift
💤 Files with no reviewable changes (2)
- iosApp/Tests/PlaybackSourcePrefetchPolicyTests.swift
- iosApp/iosApp/Screens/Player/PlaybackSourcePrefetchPolicy.swift
| func resumeFillingIfNeeded() { | ||
| lock.lock() | ||
| let shouldConsider = parked && !cancelled && !finished | ||
| let cursor = writeCursor | ||
| let mark = demandMark | ||
| lock.unlock() | ||
| guard shouldConsider else { return } | ||
| guard callbacks.mayContinueFilling(self, cursor, mark) else { return } | ||
| lock.lock() | ||
| if parked, !cancelled { | ||
| parked = false | ||
| task?.resume() | ||
| } | ||
| lock.unlock() | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the file and inspect the relevant region with line numbers.
git ls-files 'iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift'
wc -l iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
sed -n '1,260p' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
printf '\n---\n'
sed -n '260,360p' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
# Find all uses of lastDataAt and reconnect/stall logic.
printf '\n=== lastDataAt references ===\n'
rg -n 'lastDataAt|reconnectIfStalled|stallSeconds|parked|mayContinueFilling' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swiftRepository: Silo-Server/silo-apple
Length of output: 14668
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the watchdog and data-delivery paths around the cited lines.
sed -n '360,520p' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
printf '\n---\n'
sed -n '520,640p' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift
# Show all assignments to parked/lastDataAt and the watchdog trigger site with context.
printf '\n=== parked / lastDataAt assignments ===\n'
rg -n -C 2 'lastDataAt = Date\(\)|parked = false|parked = true|reconnectIfStalled|resumeFillingIfNeeded|mayContinueFilling' iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swiftRepository: Silo-Server/silo-apple
Length of output: 14095
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Search for watchdog/park semantics in tests or related code.
rg -n -C 2 'stallSeconds|reconnectIfStalled|resumeFillingIfNeeded|lastDataAt|parked|suspend\(\)|resume\(\)' iosApp . --glob '!*.xcworkspace' --glob '!*.xcodeproj' --glob '!*.pbxproj'Repository: Silo-Server/silo-apple
Length of output: 50378
Reset lastDataAt when unparking
resumeFillingIfNeeded() resumes a parked task without refreshing lastDataAt. If the stream stays parked longer than stallSeconds, the next watchdog tick can treat the just-unparked connection as stalled and reconnect it unnecessarily.
Suggested fix
lock.lock()
if parked, !cancelled {
parked = false
+ lastDataAt = Date()
task?.resume()
}
lock.unlock()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func resumeFillingIfNeeded() { | |
| lock.lock() | |
| let shouldConsider = parked && !cancelled && !finished | |
| let cursor = writeCursor | |
| let mark = demandMark | |
| lock.unlock() | |
| guard shouldConsider else { return } | |
| guard callbacks.mayContinueFilling(self, cursor, mark) else { return } | |
| lock.lock() | |
| if parked, !cancelled { | |
| parked = false | |
| task?.resume() | |
| } | |
| lock.unlock() | |
| } | |
| func resumeFillingIfNeeded() { | |
| lock.lock() | |
| let shouldConsider = parked && !cancelled && !finished | |
| let cursor = writeCursor | |
| let mark = demandMark | |
| lock.unlock() | |
| guard shouldConsider else { return } | |
| guard callbacks.mayContinueFilling(self, cursor, mark) else { return } | |
| lock.lock() | |
| if parked, !cancelled { | |
| parked = false | |
| lastDataAt = Date() | |
| task?.resume() | |
| } | |
| lock.unlock() | |
| } |
🤖 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 `@iosApp/iosApp/Screens/Player/PlaybackSourceOriginStream.swift` around lines
287 - 301, `resumeFillingIfNeeded()` in `PlaybackSourceOriginStream` resumes a
parked task without updating `lastDataAt`, so a freshly unparked stream can
still look stalled to the watchdog. When the task is resumed inside the
`parked`/`cancelled` check, also refresh `lastDataAt` at that same point so the
connection’s activity timestamp reflects the unpark event and avoids an
unnecessary reconnect.
…ache reuse Fixes from an adversarial multi-agent review of the streaming rewrite: - Retarget/redrive livelock: with more cache-missing demand regions than stream slots, every re-driven waiter retargeted the connection the previous one had just opened before its first byte arrived. Retarget victims must now have delivered since their last (re)target (or aged past a grace period); ineligible pools return a new `.wait` action and the waiter is re-driven on the first delivery or stream end. - Parked-stream wedge: the readahead budget gate had no demand bypass, so a seek onto a parked stream while the forward run filled the budget parked playback permanently (nothing read -> nothing evicted -> never unparked). shouldPause now never parks a stream whose demand mark is at or ahead of its cursor. - Background give-up escalation: any stream give-up fired onPlaybackSourceInterrupted and tore the player down mid-watch even when playback was riding the forward cache. Interruptions now surface only when the give-up failed a foreground waiter (chunked-path parity). - Cursor-before-store race: handleData published the advanced write cursor before the bytes reached the cache, so a concurrent miss at the frontier classified as behind-cursor and spawned a duplicate playhead connection. Bytes are now stored before the cursor advances. - Cached-run re-download: a stream retargeted just below a back-scrubbed forward cache re-pulled the whole cached region byte-for-byte. Streams now check each 1 MiB of progress and jump (or finish) over cached runs >= 8 MiB via cache.nextPrefetchStart, which the rewrite had orphaned. - Connection churn on retarget/reconnect: each attempt built a fresh ephemeral URLSession and invalidated the old one, destroying the connection pool and paying TCP+TLS+slow-start per seek. One session now lives for the stream's lifetime; attempts are per-task, staleness is keyed on task identifiers. - Unknown-total responses: a total-less first origin response latched and produced 206s with neither Content-Range nor Content-Length. Exact ranges now use the RFC 9110 unknown-total form (bytes s-e/*), head-anchored open ranges downgrade to 200, and mid-file open ranges refuse with 503 instead of emitting an unsizeable 206. - Small ones: past-EOF clamp moved into PlaybackSourceResponseEnd.classify (with a test pinning it), the premature-EOF log no longer reads discoveredTotalLength unlocked, beginOriginRequest now pairs under stateLock so a racing stop() can't strand the stats gauge, and finish/give-up share one terminate() teardown that also cancels a pending reconnect task. 516 tests pass; iOS/tvOS/macOS builds green. Co-Authored-By: Claude Fable 5 <[email protected]>
Review round 2 — verified findings fixed (7e91ca9)An adversarial 8-angle / 16-verifier review pass surfaced 8 confirmed issues; all are fixed in 7e91ca9: Correctness
Performance / robustness Also swept in: past-EOF clamp moved inside Refuted during verification (no change needed): plan-time prefetch offset past EOF (server 416 carries Follow-up candidates (separate PR): consolidate the three Testing: 516 tests pass (5 new: retarget eligibility ×3, budget-bypass parking, past-EOF classify); iOS / tvOS / macOS builds green. 🤖 Generated with Claude Code |
Cluster-by-cluster comparison of AetherEngine's fixed defects against the silo-apple loopback + PlayerCore stack: 18 gaps (1 high, 15 medium, 2 low) where AE enforces an invariant we don't, each with the AE symptom, our concrete exposure scenario, and a fix naming our files/functions. Produced by a 5-phase agent workflow (mine 277 AE fixes → cluster → audit vs our code → adversarial verify); 15 gaps verified, 3 marked unverified. Markdown for review + a self-contained HTML report for sharing. Excludes today's moov-wedge fix (359d20c) and the PR #52/#66/#68 stack as landed. Co-Authored-By: Claude Fable 5 <[email protected]>
Problem
Users on fast but high-latency connections (gigabit fiber, ~150 ms+ RTT to the server) report buffering even on 1080p files, while the same files direct-play fine through the Jellycompat API in third-party clients. LAN testing (including high-bitrate 4K) never reproduces it.
Root cause:
PlaybackSourceProxyfetched origin bytes as strictly sequential, fully-buffered 2–16 MiB range requests. Every chunk pays a fresh TCP slow-start ramp plus one RTT of dead air between requests, and the serve loop cannot forward a single byte until the entire chunk lands. At 150 ms RTT this caps effective throughput around 14 Mbps regardless of line speed — right at the starvation edge for ordinary 1080p remuxes. Third-party clients issue one long-lived GET, pay slow-start once, and ride the congestion window at line rate.Fix
Replace the chunked fetcher with long-lived streaming range GETs (the design AetherEngine adopted after its own chunked reader collapsed on CDNs — "VLC-style single forward-streaming connection"):
rw_timeout).Removed: chunk-size escalation (8/16 MiB for high-bitrate sources — a LAN optimization that made remote misses strictly worse), the single-flight
.utilityprefetch loop, and the dedicated 1-byte total-length probe (total now comes from the first streaming response'sContent-Range).Review hardening
An adversarial review pass on the rewrite surfaced and fixed: retarget stranding waiters of the victim stream, waiter registration racing a stream give-up, two park/unpark races (suspend now under lock + post-park recheck), terminal-stream revival leaking a live URLSession, give-up failing waiters riding healthy streams, and missing generation guards on finish/give-up. Lock hierarchy, continuation exactly-once semantics, 404 session-missing detection, and
PlaybackSourceResponseEnd.classifysemantics verified preserved.Testing
Notes / follow-ups (separate PRs)
streamSpeedratio; auto/offered downshift to server transcode) — the complementary fix for users whose links genuinely can't sustain the file bitrate.BANDWIDTH=18000000while streams can run ~63 Mbps → cosmetic-12318per-segment complaints in AVPlayer's error log.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes
Tests