Skip to content

fix(playback): bound conditional origin chunks - #139

Merged
Quick104 merged 3 commits into
mainfrom
fix/bounded-origin-chunk-responses
Aug 11, 2026
Merged

Quick104 merged 3 commits into
mainfrom
fix/bounded-origin-chunk-responses

Conversation

@Quick104

@Quick104 Quick104 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

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 OK responses after conditional range validation failed. PlaybackOriginChunkFetcher used a completion-handler data task, so it could not inspect the status until Foundation had accumulated the entire response in one Data. The captured responses were hundreds of MiB to multiple GiB, making memory-pressure termination the likely playback failure.

Approach

  • Move discrete chunk reads to a serial URLSessionDataDelegate and validate status, Content-Range, and the strong ETag at response headers.
  • Send If-Match for validator-bound bounded reads so a stale entity receives a bodyless 412, while leaving the sequential stream's standard If-Range behavior unchanged.
  • Reject unexpected nonzero 200 responses before their bodies are delivered.
  • Bound accepted media to the requested/declared interval and 404 diagnostics to 4 KiB, cancelling transport as soon as the bound is reached.
  • Serialize admission, accounting, callbacks, and cancellation so cancel() is a callback-quiescence barrier and begin/end counts remain exact.
  • Strictly validate partial intervals, including short non-EOF and EOF cases, without losing changed-entity precedence.
  • Accept a shorter connection-close-delimited byte-zero 200 only 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).
  • Cancellation-race regression repeated 10 times: 10 passed, 0 failed.
  • Broader SiloTests run before the final focused edge-case additions: 1,255 passed; the same eight unrelated settings/UI tests failed and were reproduced against a clean detached origin/main build.
  • Final signed iOS simulator build, install, and two terminate/launch cycles: passed.
  • Final SiloTV simulator build and SiloMac arm64 build: passed.
  • Final adversarial review: clean; the initial callback-quiescence race, malformed/short 206 handling, 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

  • Tool(s): Codex harness
  • Model(s): gpt-5.6-sol
  • Involvement: fully AI-generated, human-directed
  • Adversarial review: independent agents reproduced the transport behavior, rejected an unsafe server-validator change, found cancellation and partial-range edge cases, and verified their fixes in the final diff. The automated PR review found one additional unknown-length EOF case, which is fixed in the follow-up commit and covered by the 31-test focused suite.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 18 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 83efc55a-f369-478c-afe6-340d634c5293

📥 Commits

Reviewing files that changed from the base of the PR and between eb42284 and fe21f3c.

📒 Files selected for processing (2)
  • iosApp/Tests/PlaybackOriginStreamResumeTests.swift
  • iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift
📝 Walkthrough

Walkthrough

The playback origin chunk fetcher now uses delegate-based streaming, serialized state, If-Match validation, strict range checks, bounded buffering, and cancellation-safe callbacks. Resume tests add origin simulations and coverage for malformed, oversized, stale, missing, delayed, and cancelled responses.

Changes

Origin chunk streaming

Layer / File(s) Summary
Fetcher state and coverage coordination
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift, iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift
The fetcher serializes state changes, publishes in-flight coverage separately, tracks attempts, and synchronously clears work during cancellation.
Request and response validation
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift
Requests use If-Match. Response headers validate status, entity validators, Content-Range, and bounded zero-offset 200 responses before body delivery.
Bounded streaming and lifecycle completion
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift
Delegate callbacks incrementally buffer bounded data, complete valid prefixes, handle diagnostic 404 responses, and suppress callbacks after cancellation.
Origin response simulation and accounting
iosApp/Tests/PlaybackOriginStreamResumeTests.swift
StubOrigin records validators and transmitted bytes and simulates range, entity, delay, malformed-response, error, and EOF cases.
Resume and cancellation test coverage
iosApp/Tests/PlaybackOriginStreamResumeTests.swift
Tests cover exact ranges, validator learning, malformed or oversized responses, status mapping, bounded bodies, request lifecycle counts, and cancellation quiescence.

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
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation and tests address all coding requirements in issue #138, including header validation, bounded bodies, cancellation, and accounting.
Out of Scope Changes check ✅ Passed The code and test changes remain within issue #138; the lock-ordering comment supports the related concurrency fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: bounding conditional origin chunk responses.
✨ 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 fix/bounded-origin-chunk-responses

Comment @coderabbitai help to get the list of available commands.

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift (1)

172-179: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Consider invalidating the session in deinit.

session.invalidateAndCancel() runs only inside cancel(). The session retains ConnectionDelegate until it is invalidated. If any future owner releases the fetcher without calling cancel(), the session and its delegate leak. The observed callers in PlaybackSourceProxy all call cancel(), 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 value

Note the hidden coupling in chunkMalformed206Total.

chunkMalformed206Total emits bytes \(offset)-\(requestedEnd)/\(requestedEnd). This is malformed only because the single caller requests one byte, which makes requestedEnd == 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 value

Add defer cleanup inside the behavior loop.

The loop stops origin and cancels fetcher at the end of each iteration. If try await origin.start() throws, or a future edit adds a try between construction and the cleanup lines, the created origin and fetcher leak for the rest of the run. A defer inside 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 the fetcher declaration.

🤖 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 value

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between b6cfd23 and eb42284.

📒 Files selected for processing (3)
  • iosApp/Tests/PlaybackOriginStreamResumeTests.swift
  • iosApp/iosApp/Screens/Player/PlaybackOriginChunkFetcher.swift
  • iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift

@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: 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".

@Quick104
Quick104 merged commit 43ab6ca into main Aug 11, 2026
1 check passed
@Quick104
Quick104 deleted the fix/bounded-origin-chunk-responses branch August 11, 2026 14:31
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.

[bug] Bound conditional origin chunks before buffering response bodies

1 participant