Skip to content

fix(playback): bound the load-idle window so proxies stop dropping stream connections - #147

Merged
RXWatcher merged 11 commits into
Silo-Server:mainfrom
RXWatcher:feat/playback-buffers
Jul 30, 2026
Merged

RXWatcher merged 11 commits into
Silo-Server:mainfrom
RXWatcher:feat/playback-buffers

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

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_timeout closes the socket, and the next read finds it dead.

DefaultLoadControl fills to maxBufferMs, then stops reading the socket until the buffer drains below minBufferMs — so max - min is literally how long the TCP connection sits idle. The shipped policy was min 50s / max 120s: a 70-second idle window against a 60-second send_timeout. That is arithmetic, not a race.

It is independently corroborated by a comment in the openresty config:

send_timeout … was 3600s for a while because 60s killed idle-but-alive progressive stream sockets under player backpressure (reconnect hiccup every ~2-3 min)

A 120s buffer fills in about two to three minutes. The observed symptom and the arithmetic agree.

The fix

maxBufferMs is no longer written by hand:

maxBufferMs = minBufferMs + MAX_LOAD_IDLE_MS

enforced by init { require(...) }, so neither the public constructor nor copy() 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, and DefaultLoadControl scales minBufferUs only 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_000 of wall clock.

Memory budget: half the heap

Measured via adb, not assumed:

Device memoryClass before after
Google TV Streamer 384 MB 160 MiB 192 MiB
NVIDIA Shield 192 MB 96 MiB 96 MiB
low-end 96 MB 48 MiB 48 MiB

A 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

  • The byte clamp no longer silently overrides the stated depth. Previously a 60 Mbps stream on a low-RAM device reported 20s while holding ~6s; the budget is now authoritative and the reported depth is the truth.
  • Depth/bytes transposition is a compile error (@JvmInline value class BufferDepthMs / BufferTargetBytes) — the Media3 override can't be reached by tests without Parameters scaffolding, so the mistake is made unrepresentable instead.
  • computeBufferSizing is a pure function; the Media3 override is a thin adapter with no policy arithmetic in it.
  • The dead PlaybackBufferMode enum and its wire parsing are removed — SiloPlayerFactory hardcoded Balanced, so two of the three modes were unreachable.

No transcode special case: the server's TranscodeThrottler already 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.

  • No R8 breakage — the risk this repo flags for minified release builds.
  • Both buffering regimes observed live: high-bitrate content byte-bound at ~172 MiB heap; low-bitrate time-bound at ~62 MiB reaching the full 180s depth.
  • Against a live 60s send_timeout (the 3600s workaround was reverted on 2026-07-28), a direct-play session produced a 70.1-second request that completed with 206, plus ~9 minutes of direct play with no reconnects — where the old build hiccupped every 2-3 minutes. send_timeout applies between successive writes, so a long request completing means no single idle gap approached 60s.

Unit tests: 1,005 passing; both :androidApp:assembleDebug and :androidTvApp:assembleDebug build.

Review round (CodeRabbit + the two follow-ups this body originally listed)

  • The memory budget is now authoritative when it falls below the byte floor. calculateBitrateTargetBufferBytes requires maximumBytes >= 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.
  • The idle-window guard is strict. It asserted stretchedWallClockMs <= ASSUMED_PROXY_SEND_TIMEOUT_MS, so reverting MAX_LOAD_IDLE_MS to the pre-fix 30_000 gave 60_000 <= 60_000 and 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.
  • Doc drift corrected. The spec and plan still said MAX_LOAD_IDLE_MS = 30_000 and 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)

  • An A/B against the pre-fix build on the same title would make the field evidence airtight; the current evidence is a single session plus the config's own account of the old behaviour.

Design and plan are in docs/superpowers/ on this branch.

RXWatcher and others added 8 commits July 30, 2026 09:55
…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.
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]>
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Playback buffer architecture

Layer / File(s) Summary
Architecture contract
docs/superpowers/...
Documents the 15-second idle-window invariant, memory-based depth sizing, and updated validation behavior.
Condition-based playback policy
android-shared/src/androidMain/.../PlaybackBufferPolicy.kt, .../SiloPlayerFactory.kt, android-shared/src/androidUnitTest/.../PlaybackBufferPolicyTest.kt
Replaces playback modes with condition-based construction, computes heap-derived budgets, enforces buffer-window limits, and validates device-profile behavior.
Budgeted load-control sizing
android-shared/src/androidMain/.../SiloLoadControl.kt, android-shared/src/androidUnitTest/.../SiloLoadControlTest.kt
Computes affordable depth and corresponding byte targets, exposes the selected depth, and tests constrained and fallback sizing paths.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main change: constraining the playback load-idle window to avoid proxy disconnects.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

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: 2

🧹 Nitpick comments (1)
docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md (1)

51-53: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Declare the fenced block language.

markdownlint reports 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

📥 Commits

Reviewing files that changed from the base of the PR and between 42815ee and 6000128.

📒 Files selected for processing (7)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicy.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt
  • docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md
  • docs/superpowers/specs/2026-07-30-playback-buffer-architecture-design.md

RXWatcher and others added 2 commits July 30, 2026 10:08
…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]>
@RXWatcher

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6000128 and 4bb5b2a.

📒 Files selected for processing (5)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloLoadControl.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackBufferPolicyTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SiloLoadControlTest.kt
  • docs/superpowers/plans/2026-07-30-playback-buffer-architecture.md
  • docs/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]>
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