Repository navigation
fix(playback): bound the load-idle window so proxies stop dropping stream connections - #147
Conversation
Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
…e connection DefaultLoadControl stops reading the socket once the buffer hits maxBufferMs and does not resume until it drains below minBufferMs, so max - min is literally how long the connection sits idle. The old hardcoded 50s/120s pair left a 70s gap, well past a typical upstream proxy's 60s send_timeout, so long direct-play files got dropped every time the buffer filled. PlaybackBufferPolicy.forConditions() now derives maxBufferMs as minBufferMs + a fixed MAX_LOAD_IDLE_MS (30s), so depth can grow without ever widening the idle window. Depth is pinned to MAX_DEPTH_MS for now; a later task will shrink it per device memory budget without touching the idle-window guarantee. Deletes the unused PlaybackBufferMode enum (QuickStart/Balanced/ SmoothPlayback) and forMode(), which were never wired to any user or server setting.
Add affordableDepthMs, a pure helper beside the existing bitrate-selection and byte-target helpers in SiloLoadControl.kt. It computes the forward buffer depth a device's memory budget can actually fund at the selected bitrate, clamped between minimumDepthMs and the desired depth, so a high-bitrate stream's reduced depth is a number the code chose rather than wherever the byte clamp happens to truncate it. Not yet wired into calculateTargetBufferBytes — that's Task 3.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Task review found the Task 3 test exercised affordableDepthMs and calculateBitrateTargetBufferBytes directly (already covered by Task 2) rather than the calculateTargetBufferBytes wiring it claimed to test, so a wiring bug (wrong value into depthMs, fallback swapped for the budget as maximumBytes, or depth not routed into desiredForwardBufferMs) would still pass. Extract the composition into a pure computeBufferSizing helper beside the other internal helpers, reduce the override to a thin Media3-type adapter over it, and replace the test with cases against computeBufferSizing that pin the wiring itself. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…time depth/bytes guard Scoped re-review injected each wiring bug from the last fix and found "depth not routed into desiredForwardBufferMs" undetected: the 15% overhead margin calculateBitrateTargetBufferBytes applies makes a correct depth and an un-routed 180s depth overshoot the same budget and clamp to the identical byte ceiling, erasing the depth's effect from the only value a test could observe. Same root cause as two product gaps: the fixed 48/96/160 MiB budget tiers can hand a 96 MB-heap device half its heap as a buffer (OOM risk) while capping a 512 MB device's headroom unused, and the 20s floor silently overrides a smaller budget so currentDepthMs() could report 20s on a device the loader could actually only hold 6-7s on. - PlaybackBufferPolicy.memoryBudgetBytes is now 1/4 of the device's own heap (memoryClassMb), bounded to [16, 192] MiB, with a conservative fixed 24 MiB fallback for low-RAM or unknown-heap devices, replacing the fixed 48/96/160 MiB tiers. - affordableDepthMs now lets the budget win over minimumDepthMs when a known bitrate affords less than the floor (the floor remains a lower bound only for the unknown-bitrate branch, where there's no bitrate to derive a number from), and divides by the same 115/100 margin calculateBitrateTargetBufferBytes multiplies back in, so a budget-limited depth lands its byte target at or just under the budget instead of overshooting and clamping. - BufferSizingResult now wraps depth and bytes in BufferDepthMs/ BufferTargetBytes inline value classes so transposing them at the override's two-line handoff is a compile error, not a silent bug no test without Media3 scaffolding could catch. - Tests updated/added throughout: heap-proportional budget cases at both ends, the honest sub-floor depth value, and a computeBufferSizing case asserting the depth itself (not just the clamped byte target) for a budget-limited stream. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…peed-derived idle window, structural invariant
Final fix wave from whole-branch review ("No — with fixes"):
1. memoryBudgetBytes now takes half the heap, not a quarter. Measured via
adb: Shield memoryClass=192MB, Google TV Streamer memoryClass=384MB,
neither low-RAM. The old 25% rule gave both LESS buffer than they
shipped with before this branch existed; half gives Shield 96 MiB and
Streamer 192 MiB (at the cap), both at or above prior fixed values.
2. The low-RAM branch no longer ignores a known small memoryClass: it now
takes the smaller of the flat 24 MiB fallback and the proportional
share, falling back to the flat value only when memoryClassMb is
genuinely unknown (<= 0).
3. MAX_LOAD_IDLE_MS is now derived from the slowest selectable playback
rate (0.5x, shared by audiobooks): 15_000ms media time so the window
still fits the assumed 60s proxy send_timeout once stretched to wall
clock at 0.5x, where DefaultLoadControl does not scale minBufferUs.
4. PlaybackBufferPolicy's init now requires maxBufferMs - minBufferMs ==
MAX_LOAD_IDLE_MS, so the invariant can't be reintroduced by hand via the
public constructor or copy().
5. Removed a vacuous SiloLoadControlTest case that was algebraically true
regardless of what affordableDepthMs returned.
6. computeBufferSizing now coerces maximumBytes to be at least minimumBytes
before calling calculateBitrateTargetBufferBytes, so a future change to
either MIN_MEMORY_BUDGET_BYTES or MIN_TARGET_BUFFER_BYTES can't trigger
an IllegalArgumentException on the playback thread.
Verified: ./gradlew :android-shared:testDebugUnitTest (1,005 tests, 0
failures) and :androidApp:assembleDebug :androidTvApp:assembleDebug both
green.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
📝 WalkthroughWalkthroughPlayback buffering now derives policy settings from device conditions, enforces a bounded load-idle window, and computes memory-budgeted forward-buffer depth and byte targets. Player wiring, unit tests, and architecture documentation are updated accordingly. ChangesPlayback buffer architecture
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related issues
Sequence Diagram(s)sequenceDiagram
participant SiloPlayerFactory
participant PlaybackBufferPolicy
participant SiloLoadControl
participant Media3
SiloPlayerFactory->>PlaybackBufferPolicy: forConditions(device profile)
PlaybackBufferPolicy-->>SiloPlayerFactory: Policy with memory budget
SiloPlayerFactory->>SiloLoadControl: Configure policy
Media3->>SiloLoadControl: calculateTargetBufferBytes(bitrate)
SiloLoadControl->>SiloLoadControl: Compute affordable depth and byte target
SiloLoadControl-->>Media3: Return buffer target bytes
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md (1)
51-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDeclare the fenced block language.
markdownlintreports MD040 for this fence.Proposed fix
-``` +```text maxBufferMs = minBufferMs + MAX_LOAD_IDLE_MS🤖 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 `@docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md` around lines 51 - 53, Declare the fenced code block language for the maxBufferMs example by changing its fence to use text, preserving the example content unchanged.Source: Linters/SAST tools
🤖 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
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt`:
- Around line 181-190: Update the load-control configuration around maximumBytes
and minimumBytes so maximumBytes remains budgetBytes, while minimumBytes is
capped at that same budget before calling calculateBitrateTargetBufferBytes. Add
a regression test covering a budget below 16 MiB and verify the calculated
target never exceeds the app’s memory budget.
In `@docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md`:
- Around line 55-58: Update the documented playback-buffer contract: in
docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md lines
55-58, describe the 15,000 ms window and its 0.5× playback-speed derivation; in
lines 68-72, distinguish the requested 20-second policy floor from
budget-limited actual depth; in
docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md lines 15-16,
replace the 30,000 ms constraint with the 15,000 ms invariant; and in lines
253-255, state that the helper may return below minimumDepthMs when the known
bitrate cannot fit the requested depth.
---
Nitpick comments:
In `@docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md`:
- Around line 51-53: Declare the fenced code block language for the maxBufferMs
example by changing its fence to use text, preserving the example content
unchanged.
🪄 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: d0a15b98-08a7-4023-927f-e571d01ab332
📒 Files selected for processing (7)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.ktdocs/superpowers/plans/2026-07-30-playback-buffer-architecture.mddocs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md
…e byte floor calculateBitrateTargetBufferBytes requires maximumBytes >= minimumBytes. That relation was being restored by raising the ceiling to meet the floor, which inverts the intent: a device whose budget is under the nominal 16 MiB floor would be handed a byte target larger than the heap it was allowed. Restore it by lowering the floor instead, so the budget stays the binding limit on every path including the unknown-bitrate fallback. Unreachable on shipping hardware today — MIN_MEMORY_BUDGET_BYTES and MIN_TARGET_BUFFER_BYTES are both exactly 16 MiB — which is precisely why it needs a regression test rather than a comment. Also corrects doc drift: the spec and plan still described MAX_LOAD_IDLE_MS as 30_000 and the 20s depth floor as a guarantee. The constant became 15_000 (the 30s wall-clock budget divided by the 0.5x audiobook rate), and the floor is deliberately not a guarantee — a known bitrate whose budget funds less than 20s yields the honest smaller number, which is the whole point of making the reduction explicit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The assertion was `stretchedWallClockMs <= ASSUMED_PROXY_SEND_TIMEOUT_MS`. Reverting MAX_LOAD_IDLE_MS to the pre-fix 30_000 yields 60_000 <= 60_000, so the one test whose job is to catch that revert passed through it — a guard that cannot fail is not a guard. Strict is also the correct statement of the property: a socket idle for exactly the timeout is a race, not a fit. Verified by temporarily setting the constant back to 30_000, where the test now fails. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md`:
- Around line 255-260: Update the remaining Step 1 and Step 3 plan examples to
follow affordableDepthMs’s revised contract: known-bitrate results may be below
minimumDepthMs, so remove expectations of 20_000 and any
coerceIn(minimumDepthMs, ...) usage on that path. Preserve minimumDepthMs only
as the floor for unknown-bitrate handling.
In `@docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md`:
- Around line 55-56: Correct the MAX_LOAD_IDLE_MS derivation wording to state
that the 30,000 ms wall-clock budget is multiplied or scaled by the slowest
playback rate of 0.5, yielding 15,000 media milliseconds. Apply this
clarification in
docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md lines
55-56, docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md line
15, and the implementation-snippet explanation at lines 154-156.
🪄 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: b66ed7b9-e71c-4356-a63e-82124fe5025a
📒 Files selected for processing (5)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.ktdocs/superpowers/plans/2026-07-30-playback-buffer-architecture.mddocs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md
…lan snippets Two things CodeRabbit caught on the re-review, both mine. The derivation was written backwards in prose: "a 30s wall-clock budget divided by the slowest playback rate" computes 60_000, not 15_000. The window is in media time and converts TO wall clock by dividing, so deriving the constant multiplies: 30_000 * 0.5 = 15_000. The shipped source comment had it right (30_000 * SLOWEST_PLAYBACK_SPEED); the spec, the plan, and the plan's own code comment did not. The plan also still carried the pre-fix affordableDepthMs: a test asserting `assertEquals(20_000, depth, "should clamp to the floor, not below it")` and an implementation using coerceIn(minimumDepthMs, ...) with no overhead margin. That is exactly the behaviour the review loop removed — anyone re-running the plan would have reimplemented the silent overrun. Both snippets now match the shipped code, including why the known-bitrate path is deliberately not floored. Docs only; no source change. Suite green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The bug
Long direct-play sessions lose their connection every few minutes. The buffer fills, the client stops reading, the proxy's client-facing
send_timeoutcloses the socket, and the next read finds it dead.DefaultLoadControlfills tomaxBufferMs, then stops reading the socket until the buffer drains belowminBufferMs— somax - minis literally how long the TCP connection sits idle. The shipped policy was min 50s / max 120s: a 70-second idle window against a 60-secondsend_timeout. That is arithmetic, not a race.It is independently corroborated by a comment in the openresty config:
A 120s buffer fills in about two to three minutes. The observed symptom and the arithmetic agree.
The fix
maxBufferMsis no longer written by hand:enforced by
init { require(...) }, so neither the public constructor norcopy()can reintroduce a wide window. Depth and idle window become independent: the buffer can hold 180s while the socket is never quiet for more than the window.MAX_LOAD_IDLE_MS = 15_000, not 30_000. The invariant is expressed in media time but a proxy measures wall clock, andDefaultLoadControlscalesminBufferUsonly for speeds above 1.0. Audiobooks offer 0.5x and share this load control, so a 30s media window would become 60s of wall clock — exactly the timeout. 15s is that 30s wall-clock budget scaled down by the slowest selectable rate (30_000 * 0.5); it converts back by dividing,15_000 / 0.5 = 30_000of wall clock.Memory budget: half the heap
Measured via adb, not assumed:
memoryClassA 25% rule was tried first and reduced the budget on every real device — the opposite of the intent. Low-RAM devices take the smaller of 24 MiB and their proportional share, so a small heap is never handed half of itself.
Also fixed
@JvmInline value class BufferDepthMs/BufferTargetBytes) — the Media3 override can't be reached by tests withoutParametersscaffolding, so the mistake is made unrepresentable instead.computeBufferSizingis a pure function; the Media3 override is a thin adapter with no policy arithmetic in it.PlaybackBufferModeenum and its wire parsing are removed —SiloPlayerFactoryhardcodedBalanced, so two of the three modes were unreachable.No transcode special case: the server's
TranscodeThrottleralready bounds transcode-ahead, and a deep target on a realtime-bound encoder is inert rather than harmful.Verification
Release build (R8 + resource shrinking) installed on a Shield and a Google TV Streamer.
send_timeout(the 3600s workaround was reverted on 2026-07-28), a direct-play session produced a 70.1-second request that completed with206, plus ~9 minutes of direct play with no reconnects — where the old build hiccupped every 2-3 minutes.send_timeoutapplies between successive writes, so a long request completing means no single idle gap approached 60s.Unit tests: 1,005 passing; both
:androidApp:assembleDebugand:androidTvApp:assembleDebugbuild.Review round (CodeRabbit + the two follow-ups this body originally listed)
calculateBitrateTargetBufferBytesrequiresmaximumBytes >= minimumBytes; that was being restored by raising the ceiling to meet the floor, so a device budgeted under 16 MiB could be handed a byte target larger than the heap it was allowed. It now lowers the floor instead. Unreachable on shipping hardware — both constants are exactly 16 MiB today — which is why it got a regression test rather than a comment.stretchedWallClockMs <= ASSUMED_PROXY_SEND_TIMEOUT_MS, so revertingMAX_LOAD_IDLE_MSto the pre-fix 30_000 gave60_000 <= 60_000and passed — the one test whose job was to catch that revert could not fail. Verified by setting the constant back to 30_000 and watching it fail.MAX_LOAD_IDLE_MS = 30_000and described the 20s depth floor as a guarantee. The constant became 15_000, and the floor is deliberately not a guarantee: a known bitrate whose budget funds less than 20s yields the honest smaller number, which is the point of making the reduction explicit.Still open (non-blocking)
Design and plan are in
docs/superpowers/on this branch.