Skip to content

SiloPlayer: seek cache — disk spill on by default with NAND wear guard - #68

Merged
Quick104 merged 4 commits into
mainfrom
feature/seek-cache-disk-spill
Jul 5, 2026
Merged

Quick104 merged 4 commits into
mainfrom
feature/seek-cache-disk-spill

Conversation

@Quick104

@Quick104 Quick104 commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

What

Makes the playback source cache spill to temporary disk storage by default (previously dormant behind SILO_ENABLE_SOURCE_DISK_SPILL), so large forward/backward seeks are served from local storage instead of refetching from origin. Follows the AetherEngine pattern (small RAM window, disk-backed retention, mmap reads).

  • Dynamic disk budget min(2 GiB, free/4, floor 512 MiB) via new PlaybackDiskBudget, shared with the loopback segment store so both spill tiers size against one policy (existing AVPlayerBackend.vodRetentionBudget delegates to it).
  • Real disk eviction, farthest-from-playhead first — a seek-back target is the last thing dropped. Previously disk spans were never deleted: once the fixed 512 MiB budget filled, spill silently stopped for the session.
  • NAND wear guard: per-session write budget of 2× the retention budget (1× on constrained Apple TVs), halved when the budget holds under ~10 min of content. Once spent, spilling and evict-to-make-room churn stop. Worst case for a 70 GB remux drops from ~70 GB of flash writes per watch to ~2–4 GiB.
  • mmap reads (.alwaysMapped, .uncached) for disk hits in both spill tiers, so a large cache pages through the kernel instead of the heap.
  • User setting "Seek Cache" (default ON) in Playback Settings → Streaming on iOS/tvOS/macOS, server-persisted as player.seek_cache_enabled. Governs the source cache only — the segment store's spill stays on (load-bearing for the DV loopback route). Env vars remain as dev overrides in both directions.
  • Orphan sweep at startup: a force-killed process never runs deinit cleanup and strands its spill directories (observed on-device); a once-per-process sweep clears leftovers from both tiers, fixing the same pre-existing hole for continuum-dv-hls generations.
  • diskBudgetBytes/diskBytesWritten surfaced in cache stats and the playback stats overlay ("Source disk written").

Why

PR #66's streaming fetch fills the RAM window fast (6×+ realtime), but the window is only 256/128 MiB — far seeks past it always went back to origin. Disk retention buys instant seek-back within ~2 GiB of recently streamed content. The wear guard exists because unbounded spill would write each stream to flash once per watch, which matters on small-NAND Apple TVs.

Validation

  • iOS, tvOS, macOS builds green; 526 tests pass including 5 new PlaybackSourceCacheDiskSpillTests (disk round-trip integrity, playhead-aware eviction, write-budget enforcement, spill-off parity with old behavior, budget-clamp parity with the segment store).
  • Hardware-validated on the living-room Apple TV 4K (3rd gen) with a 4K DV Profile 7 remux: post-seek segment serves 0.2–0.9 ms from local storage, far seeks ~1.3–3 s (producer-restart path, unchanged), footprint 488–535 MiB against the ~487 MiB pre-change baseline, zero decode errors / +0.3 ms audio drift over the session.

Reviewer notes

  • The write-budget exhaustion path logs one [CMP-SOURCE-CACHE] spill write-budget exhausted line per session; not yet observed on hardware (session ended before budget spent).
  • mmap'd files deleted by eviction while a reader holds the mapping are safe (POSIX keeps mappings valid after unlink; ledger mutation is under the cache lock).
  • Known pre-existing issue surfaced during validation, tracked separately: resume-after-force-kill can wedge on "buffering" (repros without this change).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a Seek Cache toggle to playback settings on iPhone/iPad and tvOS to control local seek support.
    • Keep Seek Cache behavior consistent across devices and server-applied settings.
  • Improvements

    • Enhanced disk-spill budgeting/eviction and added “source disk written” telemetry in playback stats.
    • Improved disk-backed read behavior to reduce memory impact.
    • Expanded streaming help text to document Seek Cache clearing.
  • Bug Fixes

    • Better retention behavior during seeking and automatic cleanup of orphaned spill data.
  • Tests

    • Added coverage for disk-spill, eviction, budget clamping, and seeking scenarios.

Quick104 and others added 2 commits July 5, 2026 15:35
Far forward/backward seeks now hit local temporary storage instead of
refetching from origin. The source cache's dormant spill path becomes
default behavior, hardened per the AetherEngine pattern:

- Dynamic disk budget min(2 GiB, free/4, floor 512 MiB) shared with the
  loopback segment store via new PlaybackDiskBudget helper
- Disk-span eviction farthest-from-playhead first (a seek-back target is
  the last thing dropped); previously spill silently stopped forever
  once the fixed 512 MiB budget filled
- NAND wear guard: per-session write budget of 2x the retention budget
  (1x on constrained Apple TVs), halved when the budget holds under
  10 minutes of content — a 70 GB remux now costs at most a few GiB of
  flash writes instead of the full stream, and the evict-to-make-room
  churn stops with it
- Disk reads mmap with [.alwaysMapped, .uncached] in both spill tiers
  so a large cache pages through the kernel instead of the heap
- User setting "Seek Cache" (player.seek_cache_enabled, default ON) in
  Playback Settings on iOS/tvOS/macOS; env vars remain as dev overrides
- diskBudget/diskBytesWritten surfaced in stats + playback stats rows

iOS/tvOS/macOS builds green; 526 tests incl. 5 new spill tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
A force-killed process never runs the caches' deinit cleanup, stranding
its spill directories (up to the full retention budget each) — observed
on-device when the app was swiped away mid-playback. One-shot
per-process sweep in PlaybackDiskBudget clears leftovers from both
spill tiers before the first cache of the new process creates its own
directory. Also fixes the same pre-existing hole for the segment
store's continuum-dv-hls generations.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4ab0edb5-fd01-437a-8882-5c541eef3aaa

📥 Commits

Reviewing files that changed from the base of the PR and between 67189b6 and ad1b8a0.

📒 Files selected for processing (2)
  • iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift
  • iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift
  • iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift

📝 Walkthrough

Walkthrough

Adds shared disk-budget policy and refactors playback cache spill, eviction, and stats handling. Introduces a persisted Seek Cache setting wired through iOS and tvOS settings, then covers the behavior with new disk-spill tests.

Changes

Disk spill budgeting and Seek Cache setting

Layer / File(s) Summary
PlaybackDiskBudget shared policy and consumers
iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift, AVPlayerRoute/AVPlayerBackend.swift, AVPlayerRoute/LoopbackSegmentStore.swift
PlaybackDiskBudget centralizes free-space and retention-budget calculations, sweeps orphaned spill directories, and is used by AVPlayerBackend and LoopbackSegmentStore; spilled segments are read with mapped/uncached options.
PlaybackSourceCache disk write budget and eviction rewrite
iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift, PlaybackStats.swift
Cache initialization, spill control, per-session write budgeting, farthest-from-playhead eviction, mapped/uncached disk reads, and disk budget/write stats are added and surfaced through playback stats.
Seek Cache setting wired through PlayerSettings, ViewModels and UI
iosApp/iosApp/Screens/Player/PlayerSettings.swift, PlayerViewModel.swift, Settings/SettingsViewModel.swift, Settings/PlaybackSettingsView.swift, tvOS/Screens/Settings/TV*.swift
Adds persisted seekCacheEnabled, threads it into cache creation, and exposes Seek Cache toggles and copy on iOS and tvOS settings screens.
Disk spill and retention budget test suite
iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift
New tests cover disk spill reads, disabled spill, playhead-based eviction, write-budget churn limits, and retention-budget parity.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main change: seek cache disk spill enabled by default with a NAND wear guard.
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.
✨ 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 feature/seek-cache-disk-spill

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

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

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

lastReadEnd is a monotonic high-water mark (forward-buffer accounting),
so after a backward seek it stays pinned ahead of the bytes being
served and disk eviction protected the wrong neighborhood — the
seek-back target could be evicted while stale forward spans survived.
Track the most recent read position separately and anchor eviction
there. Regression test included.

Review finding by Codex on PR #68.

Co-Authored-By: Claude Fable 5 <[email protected]>

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

🧹 Nitpick comments (3)
iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift (2)

18-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Unused fill() helper — every test inlines the same loop instead.

fill() is defined but never called; testEvictedSpanIsServedFromDisk, testDiskSpillDisabledWritesNothing, testDiskEvictionPrefersSpansFarthestFromPlayhead, and testWriteBudgetStopsSpillAndChurn each hand-roll the identical span-storing loop instead of reusing it.

♻️ Example: reuse fill() in testEvictedSpanIsServedFromDisk
     func testEvictedSpanIsServedFromDisk() {
         let cache = makeCache()
         // Distinct non-adjacent spans so the append fast path can't merge
         // them; overflow the 4 KiB memory budget to force eviction + spill.
-        for i in 0..<8 {
-            cache.store(
-                start: Int64(i * spanBytes * 2),
-                data: Data(repeating: UInt8(i + 1), count: spanBytes),
-                totalLength: nil
-            )
-        }
+        fill(cache, spans: 8, spacing: spanBytes * 2)
(Would need `fill`'s signature extended with an optional `spacing` parameter, defaulting to `spanBytes`, to cover the non-adjacent-span cases.)
🤖 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/PlaybackSourceCacheDiskSpillTests.swift` around lines 18 - 26,
The PlaybackSourceCacheDiskSpillTests helper fill(_ cache:spans:startingAt:) is
currently unused because several tests duplicate the same span-storing loop;
update the tests to call fill() instead of inlining the loop. Extend fill() with
an optional spacing parameter (defaulting to spanBytes) so it can cover both
adjacent and non-adjacent span cases, and reuse it in
testEvictedSpanIsServedFromDisk, testDiskSpillDisabledWritesNothing,
testDiskEvictionPrefersSpansFarthestFromPlayhead, and
testWriteBudgetStopsSpillAndChurn.

1-131: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

No cleanup of on-disk spill artifacts across test runs.

Several tests force real disk spill (testEvictedSpanIsServedFromDisk, testDiskEvictionPrefersSpansFarthestFromPlayhead, testWriteBudgetStopsSpillAndChurn), which per the upstream contract writes files to a diskDirectory. There's no tearDown() removing these directories, which could leave orphaned temp files if the cache's per-session cleanup doesn't already handle it deterministically in a test/CI environment.

🤖 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/PlaybackSourceCacheDiskSpillTests.swift` around lines 1 - 131,
The disk-spill tests create real on-disk cache artifacts, but
`PlaybackSourceCacheDiskSpillTests` does not clean them up between runs. Add
test teardown cleanup for the cache’s disk directory so
`testEvictedSpanIsServedFromDisk`,
`testDiskEvictionPrefersSpansFarthestFromPlayhead`, and
`testWriteBudgetStopsSpillAndChurn` cannot leave orphaned files behind. Use the
existing `PlaybackSourceCache`/`diskDirectory` setup in this test class to
locate and remove spill artifacts deterministically after each test.
iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift (1)

37-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Move the orphan sweep off the startup path. sweepOrphanedSpillDirectories does synchronous enumeration and deletion on first access of PlaybackSourceCache/LoopbackSegmentStore, so a leftover spill tree can add a noticeable stall before playback starts. Dispatch this cleanup to a background queue so it reclaims space without blocking session startup.

🤖 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/PlaybackDiskBudget.swift` around lines 37 - 52,
The synchronous cleanup in sweepOrphanedSpillDirectories is running on the
startup path and can block playback initialization. Move the directory
enumeration and deletion work off the first-access path for
PlaybackSourceCache/LoopbackSegmentStore by dispatching it to a background queue
or async task, keeping the static initializer lightweight while still reclaiming
spill space in the background.
🤖 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.

Nitpick comments:
In `@iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift`:
- Around line 37-52: The synchronous cleanup in sweepOrphanedSpillDirectories is
running on the startup path and can block playback initialization. Move the
directory enumeration and deletion work off the first-access path for
PlaybackSourceCache/LoopbackSegmentStore by dispatching it to a background queue
or async task, keeping the static initializer lightweight while still reclaiming
spill space in the background.

In `@iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift`:
- Around line 18-26: The PlaybackSourceCacheDiskSpillTests helper fill(_
cache:spans:startingAt:) is currently unused because several tests duplicate the
same span-storing loop; update the tests to call fill() instead of inlining the
loop. Extend fill() with an optional spacing parameter (defaulting to spanBytes)
so it can cover both adjacent and non-adjacent span cases, and reuse it in
testEvictedSpanIsServedFromDisk, testDiskSpillDisabledWritesNothing,
testDiskEvictionPrefersSpansFarthestFromPlayhead, and
testWriteBudgetStopsSpillAndChurn.
- Around line 1-131: The disk-spill tests create real on-disk cache artifacts,
but `PlaybackSourceCacheDiskSpillTests` does not clean them up between runs. Add
test teardown cleanup for the cache’s disk directory so
`testEvictedSpanIsServedFromDisk`,
`testDiskEvictionPrefersSpansFarthestFromPlayhead`, and
`testWriteBudgetStopsSpillAndChurn` cannot leave orphaned files behind. Use the
existing `PlaybackSourceCache`/`diskDirectory` setup in this test class to
locate and remove spill artifacts deterministically after each test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e99dd28e-37ff-43ea-b3e8-2393e49b38bb

📥 Commits

Reviewing files that changed from the base of the PR and between 9f5d666 and 0f66658.

📒 Files selected for processing (12)
  • iosApp/Tests/PlaybackSourceCacheDiskSpillTests.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swift
  • iosApp/iosApp/Screens/Player/AVPlayerRoute/LoopbackSegmentStore.swift
  • iosApp/iosApp/Screens/Player/PlaybackDiskBudget.swift
  • iosApp/iosApp/Screens/Player/PlaybackSourceProxy.swift
  • iosApp/iosApp/Screens/Player/PlaybackStats.swift
  • iosApp/iosApp/Screens/Player/PlayerSettings.swift
  • iosApp/iosApp/Screens/Player/PlayerViewModel.swift
  • iosApp/iosApp/Screens/Settings/PlaybackSettingsView.swift
  • iosApp/iosApp/Screens/Settings/SettingsViewModel.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVPlaybackSettingsView.swift
  • iosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift

Review nitpicks from PR #68: the orphan sweep now enumerates
synchronously (still before any live directory exists) but deletes on a
utility queue so a multi-GiB leftover tree never stalls session
startup; the spill tests reuse the fill() helper instead of six
hand-rolled loops.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the CodeRabbit nitpicks in ad1b8a0:

  • Async sweep: orphan directories are still enumerated synchronously on first access (before any live directory exists, so the captured set can only contain a dead predecessor's leftovers), but the deletions now run on a .utility queue — a multi-GiB leftover tree no longer stalls session startup.
  • fill() helper: extended with a spacing default and reused across all six spill tests; the hand-rolled loops are gone.
  • Test teardown: skipped — PlaybackSourceCache.deinit already removes its spill directory deterministically when each test's local cache is released (Swift refcounting), and the new startup sweep covers any abnormal-exit stragglers.

🤖 Addressed by Claude Code

@Quick104
Quick104 merged commit c991166 into main Jul 5, 2026
1 check passed
@Quick104
Quick104 deleted the feature/seek-cache-disk-spill branch July 5, 2026 20:10
Quick104 added a commit that referenced this pull request Jul 7, 2026
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]>
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