Repository navigation
fix(playback): bound conditional origin chunks - #139
Conversation
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 18 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThe playback origin chunk fetcher now uses delegate-based streaming, serialized state, ChangesOrigin chunk streaming
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant PlaybackOriginChunkFetcher
participant URLSession
participant ConnectionDelegate
participant StubOrigin
PlaybackOriginChunkFetcher->>URLSession: request bounded range with If-Match
URLSession->>StubOrigin: send HTTP request
StubOrigin-->>URLSession: return response headers
URLSession->>ConnectionDelegate: deliver response headers
ConnectionDelegate->>PlaybackOriginChunkFetcher: validate response
StubOrigin-->>URLSession: stream bounded body bytes
URLSession->>ConnectionDelegate: deliver body data
ConnectionDelegate->>PlaybackOriginChunkFetcher: buffer accepted prefix
PlaybackOriginChunkFetcher->>PlaybackOriginChunkFetcher: store bytes and finish callbacks
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
🧹 Nitpick comments (4)
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift (1)
172-179: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueConsider invalidating the session in
deinit.
session.invalidateAndCancel()runs only insidecancel(). The session retainsConnectionDelegateuntil it is invalidated. If any future owner releases the fetcher without callingcancel(), the session and its delegate leak. The observed callers inPlaybackSourceProxyall callcancel(), so this is defensive only.♻️ Proposed guard
init( originURL: URL,deinit { cancel() }🤖 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/PlaybackOriginChunkFetcher.swift` around lines 172 - 179, Add a deinit to PlaybackOriginChunkFetcher that calls cancel(), ensuring its URLSession is invalidated and cancelled when the fetcher is released even if callers omit explicit cancellation.iosApp/Tests/PlaybackOriginStreamResumeTests.swift (3)
570-604: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueNote the hidden coupling in
chunkMalformed206Total.
chunkMalformed206Totalemitsbytes \(offset)-\(requestedEnd)/\(requestedEnd). This is malformed only because the single caller requests one byte, which makesrequestedEnd == offset. If a future test uses this behavior with a multi-byte range, the total becomes larger than the last byte position and the response turns valid. The test then fails for a non-obvious reason.Consider deriving the total from the last byte position so the behavior stays malformed for any requested range.
♻️ Proposed change to keep the malformed total independent of the request size
case .chunkMalformed206Total: - contentRange = "bytes \(offset)-\(requestedEnd)/\(requestedEnd)" + // Total must exceed the last byte position; declare it + // equal so the range stays malformed for any request size. + contentRange = "bytes \(offset)-\(requestedEnd)/\(requestedEnd)" + // requestedEnd is the last byte position, so total == last + // byte position is always invalid.The current values are correct for the existing test. Treat this as a durability note.
🤖 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/Tests/PlaybackOriginStreamResumeTests.swift` around lines 570 - 604, Update the chunkMalformed206Total branch in the response behavior switch so the Content-Range total is derived from the final byte position rather than requestedEnd, ensuring the range remains malformed for both single-byte and multi-byte requests while preserving the existing behavior for other malformed 206 cases.
1626-1660: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd
defercleanup inside the behavior loop.The loop stops
originand cancelsfetcherat the end of each iteration. Iftry await origin.start()throws, or a future edit adds atrybetween construction and the cleanup lines, the createdoriginandfetcherleak for the rest of the run. Adeferinside the loop body keeps cleanup attached to the object lifetime.♻️ Proposed cleanup change
for behavior in behaviors { let origin = try StubOrigin(behavior: behavior) + defer { origin.stop() } try await origin.start() let recorder = ChunkRecorder() let fetcher = PlaybackOriginChunkFetcher(XCTAssertEqual(recorder.requestCounts.ended, 1, "behavior \(behavior)") - fetcher.cancel() - origin.stop() }Add
defer { fetcher.cancel() }directly after thefetcherdeclaration.🤖 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/Tests/PlaybackOriginStreamResumeTests.swift` around lines 1626 - 1660, In the behavior loop, add deferred cleanup immediately after constructing PlaybackOriginChunkFetcher: use defer to cancel fetcher and stop origin so cleanup runs on thrown errors or early exits, then remove the explicit cleanup calls at the loop end.
1481-1482: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe transfer bound is loose and timing-dependent.
XCTAssertLessThan(origin.observedBodyBytesSent(), 64 * 1024 * 1024)only fails if the stub streams the entire 64 MiB response. The stub pushes 64 KiB per send completion and stops only after the peer cancellation makes a send fail. On a fast loopback the stub can transfer far more than the requested 4 MiB and still pass.Assert a bound that is close to the requested interval plus one send chunk. The assertion then detects a regression where the fetcher stops bounding the body.
♻️ Proposed tighter bound
try? await Task.sleep(for: .milliseconds(100)) - XCTAssertLessThan(origin.observedBodyBytesSent(), 64 * 1024 * 1024) + // The fetcher must cancel transport once the requested prefix is + // complete. Allow a few in-flight 64 KiB sends beyond that prefix. + XCTAssertLessThan( + origin.observedBodyBytesSent(), + Int(requestedBytes) + 8 * 64 * 1024 + )Confirm the slack value against observed loopback behavior before you tighten it, so the test does not become flaky in the other direction.
🤖 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/Tests/PlaybackOriginStreamResumeTests.swift` around lines 1481 - 1482, In the playback-origin stream resume test, replace the loose 64 MiB assertion on origin.observedBodyBytesSent() with a bound near the requested 4 MiB interval plus one 64 KiB send chunk. Validate the chosen slack against loopback behavior so the assertion reliably catches unbounded fetching without becoming timing-dependent or flaky.
🤖 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/PlaybackOriginChunkFetcher.swift`:
- Around line 306-331: Update the zero-offset 200 handling in the response path
around acceptResponseLocked so an unknown Content-Length does not impose
state.range.count as a required byte limit. Preserve bounded-prefix behavior
when the length is known, and make handleCompletionLocked accept EOF with a
shorter body as a valid complete entity, matching the existing 206 end-of-entity
behavior.
---
Nitpick comments:
In `@iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift`:
- Around line 172-179: Add a deinit to PlaybackOriginChunkFetcher that calls
cancel(), ensuring its URLSession is invalidated and cancelled when the fetcher
is released even if callers omit explicit cancellation.
In `@iosApp/Tests/PlaybackOriginStreamResumeTests.swift`:
- Around line 570-604: Update the chunkMalformed206Total branch in the response
behavior switch so the Content-Range total is derived from the final byte
position rather than requestedEnd, ensuring the range remains malformed for both
single-byte and multi-byte requests while preserving the existing behavior for
other malformed 206 cases.
- Around line 1626-1660: In the behavior loop, add deferred cleanup immediately
after constructing PlaybackOriginChunkFetcher: use defer to cancel fetcher and
stop origin so cleanup runs on thrown errors or early exits, then remove the
explicit cleanup calls at the loop end.
- Around line 1481-1482: In the playback-origin stream resume test, replace the
loose 64 MiB assertion on origin.observedBodyBytesSent() with a bound near the
requested 4 MiB interval plus one 64 KiB send chunk. Validate the chosen slack
against loopback behavior so the assertion reliably catches unbounded fetching
without becoming timing-dependent or flaky.
🪄 Autofix
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: 588601e9-403f-4f29-8bc4-fe5c905b563d
📒 Files selected for processing (3)
iosApp/Tests/PlaybackOriginStreamResumeTests.swiftiosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swiftiosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eb422845ce
ℹ️ 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".
Problem
Fixes #138.
Companion server contract/diagnostics: Silo-Server/silo-server#594.
An internal TestFlight report showed bounded direct-stream chunk requests receiving full
200 OKresponses after conditional range validation failed.PlaybackOriginChunkFetcherused a completion-handler data task, so it could not inspect the status until Foundation had accumulated the entire response in oneData. The captured responses were hundreds of MiB to multiple GiB, making memory-pressure termination the likely playback failure.Approach
URLSessionDataDelegateand validate status,Content-Range, and the strong ETag at response headers.If-Matchfor validator-bound bounded reads so a stale entity receives a bodyless412, while leaving the sequential stream's standardIf-Rangebehavior unchanged.200responses before their bodies are delivered.cancel()is a callback-quiescence barrier and begin/end counts remain exact.200only at clean EOF and publish the observed entity length, while retaining the requested-byte streaming cap.Testing
xcodegen generate: passed.PlaybackOriginStreamResumeTests: 31 passed, 0 failed on an iPhone 17 Pro simulator (iOS 26.4).SiloTestsrun before the final focused edge-case additions: 1,255 passed; the same eight unrelated settings/UI tests failed and were reproduced against a clean detachedorigin/mainbuild.SiloTVsimulator build andSiloMacarm64 build: passed.206handling, and small full-response edge cases were fixed and covered.The remaining coverage gap is a real-device stream of the reported multi-GiB media. Simulator tests deterministically prove header-time rejection and bounded transport, but cannot prove physical-device jetsam behavior.
AI Disclosure