Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ the public-API contract.
panel repeated a frame about every 42 s. A probe within 0.005 of 24.000 now snaps to 24; a Matroska track with
DefaultDuration probes as an exact 24/1 or 24000/1001, so 23.976 sources and noisier probes keep 23.976.

- **The detour cache grows to a working set larger than its 8 blocks (AE#909).** An MP4 that stores each
subtitle track in its own region keeps about one block per track live during playback, because every
embedded subtitle track is harvested. With 14 such tracks the LRU evicted each block just before its
next read, so the same blocks were fetched over and over, and against an origin that takes a few
hundred milliseconds per request playback rebuffered every 10 to 30 s. A block the ceiling evicted being
fetched again now raises the ceiling by one, up to 16 blocks (~64 MB); idle release brings it back down,
never below 8. A working set within 8 blocks, and blocks a scrub passes through once, never grow it.

## [7.48.0] - 2026-10-26

### Added
Expand Down
54 changes: 46 additions & 8 deletions Sources/AetherEngine/Demuxer/AVIOReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,10 @@ final class AVIOReader: AVIOProvider, @unchecked Sendable {
// playback fast path never enters this code, so it carries zero overhead.
private static let detourBlockSize = 4 * 1024 * 1024
private static let detourMaxBlocks = 8 // ~32 MB LRU ceiling
/// AE#909: how far the ceiling may grow while the working set outruns it, ~64 MB. A file that stores
/// each subtitle track in its own region keeps about one block per track live during playback, not
/// only during the parse; at 8 every block was evicted before its next read and fetched again.
private static let detourMaxBlocksGrown = 16
/// Audit PERF-108: a detour block nobody has read or filled for this long is a scrub's leftover,
/// not a parse's working set (a parser revisits its region within seconds).
private static let detourBlockIdleSecondsDefault: TimeInterval = 30
Expand Down Expand Up @@ -1040,7 +1044,8 @@ final class AVIOReader: AVIOProvider, @unchecked Sendable {
/// (see serveFromDetour), so eviction never shadows a re-fetchable tail. Pure copy/eviction
/// math lives on the cache and is unit-tested without any network.
private let detourCache = DetourBlockCache(blockSize: AVIOReader.detourBlockSize,
maxBlocks: AVIOReader.detourMaxBlocks)
maxBlocks: AVIOReader.detourMaxBlocks,
grownMaxBlocks: AVIOReader.detourMaxBlocksGrown)
/// When the detour cache was last swept for idle blocks (audit PERF-108). Demux-thread-only.
private var lastDetourIdleSweepNs: UInt64 = 0
/// How long a detour block may sit unread before the sweep releases it. An init parameter for
Expand Down Expand Up @@ -5033,14 +5038,25 @@ final class DetourBlockCache: @unchecked Sendable {
private var lru: [Int64] = []
/// When each resident block was last inserted or served, on `now`'s clock (audit PERF-108).
private var lastHit: [Int64: TimeInterval] = [:]
private let maxBlocks: Int
private let baseMaxBlocks: Int
private let grownMaxBlocks: Int
/// The ceiling in force: `baseMaxBlocks`, raised by one each time a block the ceiling evicted is
/// inserted again, up to `grownMaxBlocks` (AE#909). Idle release brings it back down.
private var maxBlocks: Int
/// Indices the ceiling evicted, oldest first, at most `grownMaxBlocks` of them. Indices only, no data.
/// A block that comes back after more evictions than that belongs to a working set the grown ceiling
/// could not hold either, so it does not count.
private var evictedByCeiling: [Int64] = []
private let now: @Sendable () -> TimeInterval
let blockSize: Int

/// `now` is injectable so the idle test moves a clock instead of waiting one out.
init(blockSize: Int, maxBlocks: Int,
/// `now` is injectable so the idle test moves a clock instead of waiting one out. `grownMaxBlocks`
/// defaults to `maxBlocks`, a fixed ceiling.
init(blockSize: Int, maxBlocks: Int, grownMaxBlocks: Int? = nil,
now: @escaping @Sendable () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }) {
self.blockSize = blockSize
self.baseMaxBlocks = maxBlocks
self.grownMaxBlocks = max(maxBlocks, grownMaxBlocks ?? maxBlocks)
self.maxBlocks = maxBlocks
self.now = now
}
Expand All @@ -5057,23 +5073,35 @@ final class DetourBlockCache: @unchecked Sendable {
return data
}

/// Inserts a (full-size) block, evicting the least-recently-used tail beyond `maxBlocks`.
/// Inserts a (full-size) block, evicting the least-recently-used tail beyond `maxBlocks`. A block the
/// ceiling evicted coming back is the working set outrunning the ceiling (AE#909): every block of a
/// working set one larger than the ceiling is evicted just before its next read, so each read
/// fetches again. That raises the ceiling by one, up to `grownMaxBlocks`.
func insert(_ idx: Int64, _ data: Data) {
lock.lock(); defer { lock.unlock() }
if blocks[idx] == nil { lru.append(idx) }
if blocks[idx] == nil {
if let i = evictedByCeiling.firstIndex(of: idx) {
evictedByCeiling.remove(at: i)
maxBlocks = min(grownMaxBlocks, maxBlocks + 1)
}
lru.append(idx)
}
blocks[idx] = data
lastHit[idx] = now()
while lru.count > maxBlocks {
let evicted = lru.removeFirst()
blocks.removeValue(forKey: evicted)
lastHit[evicted] = nil
evictedByCeiling.append(evicted)
if evictedByCeiling.count > grownMaxBlocks { evictedByCeiling.removeFirst() }
}
}

/// Drops every block nothing has read or filled for `seconds`, and returns how many went. The
/// cache is otherwise only emptied at close, so the blocks of a backward scrub (up to 32 MB)
/// cache is otherwise only emptied at close, so the blocks of a backward scrub (up to the ceiling)
/// outlived the scrub for the whole session (audit PERF-108). Age rather than a clear at the
/// re-anchor, because a parser ping-ponging through a region keeps hitting its blocks.
/// re-anchor, because a parser ping-ponging through a region keeps hitting its blocks. A grown
/// ceiling (AE#909) comes back down to what is still resident, never below `baseMaxBlocks`.
@discardableResult
func evictIdle(olderThan seconds: TimeInterval) -> Int {
lock.lock(); defer { lock.unlock() }
Expand All @@ -5086,6 +5114,8 @@ final class DetourBlockCache: @unchecked Sendable {
blocks.removeValue(forKey: idx)
lastHit[idx] = nil
}
maxBlocks = max(baseMaxBlocks, lru.count)
evictedByCeiling.removeAll()
return idle.count
}

Expand All @@ -5094,6 +5124,8 @@ final class DetourBlockCache: @unchecked Sendable {
blocks.removeAll()
lru.removeAll()
lastHit.removeAll()
maxBlocks = baseMaxBlocks
evictedByCeiling.removeAll()
lock.unlock()
}

Expand All @@ -5102,6 +5134,12 @@ final class DetourBlockCache: @unchecked Sendable {
return blocks.count
}

/// The ceiling currently in force (AE#909).
var currentMaxBlocks: Int {
lock.lock(); defer { lock.unlock() }
return maxBlocks
}

/// Copy up to `maxLen` bytes covering `offset` from the resident block into `dst`, returning the
/// byte count. Returns nil if the covering block is not resident, or if `offset` lands in the
/// uncovered tail of a short block (so the caller re-fetches rather than serving stale bytes).
Expand Down
139 changes: 139 additions & 0 deletions Tests/AetherEngineTests/DetourBlockCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,145 @@ struct DetourBlockCacheTests {
#expect(cache.residentCount == 0)
#expect(cache.block(0) == nil)
}

/// Reads `rounds` passes over `regions` blocks the way the detour path does (serve, else fetch and
/// insert) and returns how many fetches each pass made.
private func fetchesPerPass(_ cache: DetourBlockCache, regions: Int, rounds: Int) -> [Int] {
(0..<rounds).map { _ in
(0..<regions).reduce(0) { fetches, i in
if cache.block(Int64(i)) != nil { return fetches }
cache.insert(Int64(i), patternBlock(base: i * 16))
return fetches + 1
}
}
}

// AE#909: a file that stores each subtitle track in its own region keeps more blocks live than the
// ceiling holds, and LRU then evicts every block just before its next read.
@Test("a working set larger than the ceiling grows it until a pass fetches nothing")
func ceilingGrowsToTheWorkingSet() {
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 8)
let fetches = fetchesPerPass(cache, regions: 5, rounds: 4)
#expect(fetches.first == 5)
#expect(fetches.last == 0, "passes fetched \(fetches)")
#expect(cache.currentMaxBlocks == 5)
}

@Test("a fixed ceiling keeps fetching every block of a working set one larger than it")
func fixedCeilingThrashes() {
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3)
#expect(fetchesPerPass(cache, regions: 4, rounds: 4) == [4, 4, 4, 4])
#expect(cache.currentMaxBlocks == 3)
}

@Test("the ceiling does not grow past grownMaxBlocks")
func growthIsBounded() {
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 5)
_ = fetchesPerPass(cache, regions: 6, rounds: 6)
#expect(cache.currentMaxBlocks == 5)
#expect(cache.residentCount == 5)
}

@Test("a working set the grown ceiling could not hold either does not grow it")
func noGrowthBeyondReach() {
// Nine blocks read in turn miss on every read under any ceiling below nine, so growing to five
// would only hold more memory for the same fetches.
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 5)
#expect(fetchesPerPass(cache, regions: 9, rounds: 4) == [9, 9, 9, 9])
#expect(cache.currentMaxBlocks == 3)
}

@Test("a working set within the ceiling never grows it")
func noGrowthWithinTheCeiling() {
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 8)
#expect(fetchesPerPass(cache, regions: 3, rounds: 4) == [3, 0, 0, 0])
// Blocks passing through once, as a scrub fills them, are evicted but never read again.
for i in 10..<20 { cache.insert(Int64(i), patternBlock(base: i * 16)) }
#expect(cache.currentMaxBlocks == 3)
}

@Test("idle release brings a grown ceiling back to what is still resident, never below the base")
func idleReleaseShrinksTheCeiling() {
let clock = ManualClock()
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 8, now: { clock.now })
_ = fetchesPerPass(cache, regions: 6, rounds: 3)
#expect(cache.currentMaxBlocks == 6)

clock.advance(20)
for i in 0..<4 { _ = cache.block(Int64(i)) }
clock.advance(20)
#expect(cache.evictIdle(olderThan: 30) == 2)
#expect(cache.currentMaxBlocks == 4)

clock.advance(31)
#expect(cache.evictIdle(olderThan: 30) == 4)
#expect(cache.currentMaxBlocks == 3)
}

@Test("clear returns a grown ceiling to the base")
func clearResetsTheCeiling() {
let cache = DetourBlockCache(blockSize: 16, maxBlocks: 3, grownMaxBlocks: 8)
_ = fetchesPerPass(cache, regions: 6, rounds: 3)
cache.clear()
#expect(cache.currentMaxBlocks == 3)
#expect(fetchesPerPass(cache, regions: 4, rounds: 1) == [4])
#expect(cache.currentMaxBlocks == 3, "an index evicted before the clear does not count afterwards")
}
}

/// AE#909, through the reader: a demuxer reading twelve regions behind the streaming window, the way a
/// flat MP4 with one region per subtitle track is read during playback.
@Suite("Detour cache grows to the reader's working set")
struct DetourCacheWorkingSetReaderTests {

private static let chunk = 256 * 1024
private static let block: Int64 = 4 * 1024 * 1024

@Test("a third pass over twelve regions behind the window fetches nothing", .timeLimit(.minutes(2)))
func repeatedPassesStopFetching() throws {
let server = try #require(ThrottledOriginServer(totalSize: 128 * 1024 * 1024, throttleUs: 1000, patternedBody: true))
defer { server.stop() }
// The detour fetch's interactive budget is a wall clock; see Issue782RestartReanchorTests. So is
// idle release: on a loaded runner a pass can outlast its 30 s, and the release would shrink the
// ceiling between passes. What is measured here is growth, not release.
let reader = AVIOReader(url: URL(string: "http://127.0.0.1:\(server.port)/movie.bin")!,
detourIdleSeconds: 3600, detourFetchBudget: 30)
defer { reader.markClosed(); reader.close() }
try reader.open()
reader.markOpenPhaseFinished()

let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: Self.chunk)
defer { buf.deallocate() }
var read = 0
while read < 80 * 1024 * 1024 {
let n = Int(reader.read(into: buf, size: Int32(Self.chunk)))
#expect(n > 0, "forward read failed at \(read)")
if n <= 0 { return }
read += n
}

func blockFetches() -> Int {
server.requestedRanges.filter { range in
guard let end = range.end else { return false }
return end - range.start + 1 == Self.block
}.count
}
var perPass: [Int] = []
for _ in 0..<3 {
let before = blockFetches()
for region in 0..<12 {
let offset = Int64(region) * Self.block + 4321
#expect(reader.seek(offset: offset, whence: Int32(SEEK_SET)) == offset)
let n = Int(reader.read(into: buf, size: Int32(Self.chunk)))
#expect(n > 0)
#expect((0..<n).allSatisfy { buf[$0] == ThrottledOriginServer.patternByte(at: offset + Int64($0)) },
"region \(region) served the wrong bytes")
}
perPass.append(blockFetches() - before)
}
#expect(perPass.first == 12, "the first pass did not fetch each region as a detour block: \(perPass)")
#expect(perPass.last == 0, "passes fetched \(perPass)")
}
}

/// Issue #71: under a sustained 429, parse-driven seekReconnect kept resetting unproductiveReconnects
Expand Down
Loading