Skip to content

Custom IOReader live session retains ~every consumed byte as anonymous memory — physFP grows at the mux rate until jetsam (URL path flat) #445

Closed

Description

@cmcpherson274

Setup. tvOS device (AppleTV14,1 / A15, tvOS 26.6), engine at the 6.21.0 pin (87868c1c), Debug host build. A live MPEG-TS session fed through MediaSource.custom(IOReader): the reader is an adapter over an app-owned, disk-backed spool (one continuous upstream socket; blocking ring reads; logical-offset seek; size unknown; isLive: true; dvrWindowSeconds deliberately unset — the host owns the rewind window and performs jumps as fresh loads, never engine seeks). Route resolves to the loopback/native path.

Finding. The session retains approximately every consumed byte as anonymous memory. phys_footprint grows at the source mux rate (~1.7 MB/s here) for the life of the session, and the process is killed silently at ~11.5 min (no crash report, no main-thread stall — the jetsam shape).

The engine's own memprobe line tells the story. Custom-reader session at t=600/630:

memprobe t=600s rss=360MB vmInt=314MB vmExt=43MB vmCmp=844MB vmIOS=0MB physFP=1158MB mallocBlocks=109568 mallocMB=2472 avioFetchedMB=0 cacheCount=62 cacheMB=105 ...
memprobe t=630s rss=393MB vmInt=347MB vmExt=43MB vmCmp=864MB vmIOS=0MB physFP=1212MB mallocBlocks=110260 mallocMB=2472 avioFetchedMB=0 cacheCount=60 cacheMB=102 ...

Log stops mid-segment at t≈687 with no teardown lines; the process is gone from the process table; no .ips is written. rss alone is misleading — it peaked at 626 MB (t=270) and the OS compressed/reclaimed it down to ~323 — but physFP (what jetsam enforces) ratchets monotonically at the mux rate: ~1.7 MB/s × 687 s ≈ 1.2 GB.

The control. Same box, same channel, same build, URL source (isLive, raw TS over HTTP), 32-minute session:

memprobe t=30s   rss=90MB vmInt=28MB ... physFP=28MB ... avioFetchedMB=61   ...
memprobe t=1922s rss=92MB vmInt=29MB ... physFP=29MB ... avioFetchedMB=3424 ...

3.4 GB fetched through, physFP flat at 28–29 MB.

What the probe's buckets say. On the custom-reader session every itemized bucket is flat while physFP climbs: cacheMB ~102, pumpWinMB 4, pktAlive 3, audioFifo 0 — and avioFetchedMB=0, i.e. the custom path doesn't ride the URL path's fetch-and-release accounting at all. The retained ~1.2 GB is invisible to every bucket the probe itemizes. (mallocMB pins at 2472 early and stays — it reads as a zone high-water rather than live bytes.)

The reader is exonerated by a second consumer. The identical spool + stream adapter feeds libVLC (VLCMedia custom input) through battle-tested 30-minute rewound sessions on the same hardware with flat memory. The retention appears only when the engine is the consumer.

Ask. Where does the custom-source path buffer consumed bytes, and can it ride the same eviction/disk-cache discipline as the URL path? A custom live reader that never EOFs makes "retain everything read" unbounded by construction. Happy to re-run the 30-minute session against a branch — and we will re-measure at 6.52.0 in our upcoming pin-bump pass regardless; if anything in 6.22–6.52 already touched custom-source buffering, a pointer saves a cycle.

Full evidence (collected device log with the memprobe series, the URL-arm control, and the harness scripts) is archived in our repo under qa-artifacts/tevemate/2026-08-27-e3b-wedge/.

Activity

  1. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    Re-measured at 6.53.0 as promised in the report — reproduced, and the series is cleaner than the original.

    Same box (AppleTV14,1, tvOS 26.6), same channel, same custom-IOReader spool shape, engine at 07af2e3f (6.53.0). The memprobe series is a textbook line:

    t=30s   physFP=134MB   rss=199MB   vmCmp=0MB
    t=210s  physFP=455MB   rss=520MB   vmCmp=0MB
    t=330s  physFP=670MB   rss=735MB   vmCmp=0MB
    t=450s  physFP=883MB   rss=948MB   vmCmp=0MB
    t=600s  physFP=1150MB  rss=1216MB  vmCmp=0MB
    

    20 points, perfectly linear at 1.783 MB/s — the source mux rate — with avioFetchedMB=0 (the custom path still bypasses the fetch accounting) and every itemized bucket flat, as before. One difference from the 6.21.0 run: the compressor never engaged this time (vmCmp=0 throughout vs 864 MB then), so the silent kill came correspondingly earlier — the log stops mid-segment at t≈636 (was t≈687), no crash report written, no main-thread stall, process gone from a populated process table. Same jetsam shape, less compressed-memory runway.

    This matches the code reading: IOReader.swift is byte-identical between the pins and no release note in 6.22–6.53 touches custom-source buffering, so nothing was expected to move — but now the issue carries a datapoint at current, and the counter fixes in 6.53.0 make the surrounding telemetry trustworthy (rx/origin both monotonic in the same session's captures).

    Standing offer unchanged: happy to re-run the 30-minute session against any branch. This is the one blocker left on our side for turning the custom-reader arm on.

  2. superuser404notfound commented on Aug 28, 2026

    @superuser404notfound
    Owner

    Reproduced, root-caused and fixed on main (c90ffb16). Thank you for the memprobe series and, above all, for the URL arm next to it: the pair is what made this a one-shot diagnosis instead of a hunt.

    Where the bytes go: nowhere the engine can see, because they are the host's.

    CustomIOReaderBridge copies straight from your read into FFmpeg's 256 KB AVIO buffer and keeps nothing, which is why every itemized bucket on the probe is flat and honest. The retention is one level below that, in an object lifetime rather than in a buffer.

    HLSSegmentProducer runs its pump on a bare Thread, and FFmpeg's read callback reaches your IOReader from inside that loop. A bare thread has no autorelease pool, and the pump never returns for the length of the session, so nothing on it ever drains. Every autoreleased object your reader creates per read (an NSData out of FileHandle, anything Foundation hands back +0) is therefore stranded until the session ends. On a live source that never EOFs, that is one retained byte per byte played, unbounded by construction.

    That also explains the two things that looked contradictory in your report:

    • Why libVLC exonerates the same spool. VLCKit wraps its custom-input callbacks in a pool. Ours did not. The reader is the same; the thread it lands on is not.
    • Why the URL arm is flat at 29 MB. AVIOReader never runs host code on that thread, and the engine's own readers each carry a private pool. FileIOReader.read has had one since Unbounded memory growth when playing a remote Blu-ray ISO over HTTP #243 with the comment "one leaked byte per byte played, measured at 625 MB in-use after 624 MB read", and HTTPDiscIOReader.rangeGet has one too. The lesson was learned twice and both times fixed one reader down, where it could never cover a reader a host wrote. The custom bridge was the one door left without a pool.

    Your own log carries the arithmetic. Between t=600 and t=630, mallocBlocks went 109568 to 110260 (+692) while physFP rose 54 MB. That is 82 KB per new block, i.e. one stranded allocation per read, sized like one read. mallocMB sitting still at 2472 across the same step is what made this hard to see from the outside, and your instinct about that field was right: 2472 MB of live malloc inside a 1158 MB footprint only balances because most of it is in the 844 MB vmCmp bucket, and the counter is too coarse to show a 54 MB step against that background. mallocBlocks is the field that moved, and it moved by exactly the right amount.

    The fix puts the pool at the seam the engine owns rather than asking hosts to know which of our threads their callback lands on: read, seek, the AVSEEK_SIZE probe, the seekability probe and cancel each run inside autoreleasepool. Nothing about the IOReader contract changes, and a reader that already drains its own pays nothing for the second one.

    Measured on a new harness (aetherctl customio --live), a host-owned live spool paced against the wall clock, blocking at the edge instead of ever returning EOF, unknown size, seekable by logical offset, native/loopback route, 5 minutes at a 0.95 MB/s mux rate:

    before   physFP 130 -> 359 MB over 241s = 0.95 MB/s   retention ratio 1.00
    after    physFP  56 ->  55 MB over 241s = 0.00 MB/s   retention ratio 0.00
    

    Ratio 1.00 is your report reproduced exactly: one byte kept per byte played. After the pool the footprint is the session's rather than the stream's, and flat across the run.

    Two notes for your re-measure:

    • Nothing between 6.22 and 6.54 touched this, so a pin bump alone will not move it. The fix is c90ffb16 on main, and it will be in the next release.
    • If your adapter is pure Swift or POSIX and allocates nothing autoreleased per read, this fix does not apply to you and your footprint will be unchanged. In that case say so and I will keep digging, because then the retention is somewhere else and your run is the only one that has seen it. What I can say is that the shape reproduced here matches yours on every axis I could compare: mux-rate slope, flat buckets, avioFetchedMB=0, a flat URL control, and a block census that lands on your +692.

    The harness ships with the fix, because that shape had no harness at all until now, which is the real reason this could sit in the engine unnoticed while three of us stared at the probe.

  3. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    Ran the 30-minute-hold recipe against main (8851d1ae, pool fix verified present in the resolved checkout — CustomIOReaderBridge.swift:62 autoreleasepool { body() }) on the same box, same channel, same spool. The footprint did not move: this is your "then the retention is somewhere else" branch.

    t=150s  physFP=350MB   mallocBlocks=107201
    t=300s  physFP=618MB   mallocBlocks=108946
    t=540s  physFP=1046MB  mallocBlocks=109561
    

    Slope ~1.77 MB/s — the same mux-rate line as 6.21.0 and 6.53.0 — and the same silent kill (process gone from a populated table, no crash report, log stops mid-segment at ~t≈595).

    And the reason the pool cannot cover us is the one you anticipated: our reader allocates nothing autoreleased per read. The hot path, end to end:

    • IOReader.read → a Swift InputStream subclass's read(_:maxLength:) override → a disk-backed ring's read(at:into:maxLength:) → POSIX pread(fd, buffer, …) directly into the buffer your bridge hands us. No FileHandle.readData, no NSData, no Data — the segment FileHandle is created once per SEGMENT rotation (seconds apart) and cached, and only its fileDescriptor is read per call.
    • seek (rare) does touch NSNumber bridging via Stream.property(forKey:); reads do not.

    Two data points that may aim the next dig:

    1. Your block census matched OUR 6.21.0 run (+692 blocks / 54 MB ≈ 82 KB, read-sized, one per read) — but on the fixed build the blocks still strand, so on this stack they are read-sized malloc blocks that no pool ever owned. Whatever allocates them survives autoreleasepool by construction.
    2. vmCmp=0 across all our recent runs — the stranded pages are never even compressed, they sit dirty until jetsam.

    Happy to hand you the complete reader implementation (it is ~70 lines, self-contained) and re-run against any branch or diagnostic build — a per-read block-origin census (malloc stack logging on the pump thread for one minute) is also runnable here on request. Full new-pin series and logs archived in our repo as before.

  4. superuser404notfound commented on Aug 28, 2026

    @superuser404notfound
    Owner

    Your re-measure settles it, and it also says round 1 measured the wrong thing. Thank you for running it against main and for writing out the reader's hot path line by line, because that is what turned this into a correction instead of another hypothesis.

    The harness brought the cause with it. aetherctl customio --live read its spool with FileHandle.readData(ofLength:), which strands one autoreleased Data per read on exactly the thread the fix was about. Ratio 1.00 before the pool and 0.00 after are both real numbers, and both are about the harness. Your adapter preads straight into the buffer the bridge hands it and allocates nothing per read, so the pool has nothing to drain on your stack and could never have moved your line. The fix stays in, because it covers every host reader built on Foundation and that door was genuinely open, but it is not your defect and I should not have shipped a repro whose only arm carried its own retention.

    The control that was missing is an arm that allocates nothing. It is now the default (--foundation-reader keeps the allocating one as a control that proves the pool drains), and it is flat, at e19dffb7:

    541 s at 14 Mbit/s, no DVR   physFP 65 -> 41 MB   retention ratio -0.03
    180 s at 14 Mbit/s, 300 s DVR physFP 79 -> 80 MB   retention ratio  0.00
    

    That is 900 MB of source through a live spool that never EOFs, with the engine holding nothing. Worth stating plainly: this arm would have been flat before the pool fix as well, which is exactly why its absence let a harness result read as a field result.

    One number from those runs may be worth more to you than the ratio. The harness now reports how far behind the live edge the engine ever reaches back:

    LOOKBACK: 1 seeks, deepest reach-back 0.0 MB behind the live edge
    

    Same in both arms, DVR window included. The one seek is the seekability probe at open. The timeshift window lives in the segment cache on disk, not in the source, so the engine never asks a live custom reader for a byte it has already consumed. If your ring keeps history because the engine might come back for it, it is keeping it for a request that does not arrive, and a ring that grows for the session grows at exactly the mux rate you are seeing.

    Your own numbers also disagree with reading 1 in your last comment. Taking the three points as posted:

    interval slope new blocks MB per new block
    6.21.0, t=600 to 630 1.80 MB/s 23.1 /s 80 KB
    main, t=150 to 300 1.79 MB/s 11.6 /s 157 KB
    main, t=300 to 540 1.78 MB/s 2.6 /s 713 KB

    The byte slope is nailed to the mux rate in all three, but the block rate falls by a factor of nine while it does. At 1.78 MB/s with 82 KB reads the session performs about 22 reads a second, so in the last interval fewer than one new block appears per eight reads. Whatever still strands is therefore not one allocation per read any more. It is either a single buffer growing by realloc, which raises size_in_use without ever adding a block, or memory malloc never handed out: vm_allocate pages, a CoreMedia pool, an IOSurface. vmCmp=0 fits the second family better, since ordinary heap growth of that size does engage the compressor.

    So the engine now names the region instead of leaving you with a slope. Three rounds ended on "footprint climbs, every itemized bucket is flat", and that stayed true because the buckets are either totals (vmInt/vmExt/vmCmp) or heap-only (mallocBlocks, the size-class census). None of them can see a region outside malloc. main gains a per-region census: it walks the task's VM map with vm_region_recurse_64 and tallies dirty plus swapped pages per user_tag, reported as growth since the session's first tick:

    vmGrewMB=31 vmRegions=358 vmTagTop=IOSURFACE_ALT:+28MB(66),MALLOC_SMALL:+2MB(27)
    

    It reports growth rather than a total on purpose. Even the anonymous total overshoots phys_footprint (measured here at 100 MB against 56 MB), because IOSurface and video-bitstream mappings look anonymous in that map while the kernel charges them to whoever created them, so an absolute figure would not survive being checked against the line beside it. Summed positive deltas do: hold vmGrewMB against the rise in physFP over the same span, and the remainder is the part no tag explains. It rides the switch you already use, setLargeAllocationCensusEnabled(true), needs no other host change, and the first tick anchors its own baseline so the load burst does not land in the finding.

    Two asks, in the order that would help most:

    1. One run with the census on, same recipe as before. If the growing tag is a CM one, the retention is in CoreMedia's pools and the next dig is what the loopback route hands AVPlayer on tvOS. If it is MALLOC_LARGE, your offer of a malloc stack log becomes exactly the right next step. If it is untagged anonymous memory, that is a third place entirely, and worth knowing before anyone spends an hour on stacks.
    2. The ring, not just the reader. The reader you described is clean and I believe it. What no round has covered is the writer side: how large the ring is, whether it is bounded or grows for the session, whether any of it is mmaped, and how it decides what it may drop. Given the 0.0 MB reach-back above, a ring that keeps everything the engine might still want is holding it for nothing, and that shape would put your slope in your own address space while the reader stays innocent.

    Send the ~70 lines whenever convenient, writer side included, and I will run them here against the same harness. Apologies for the round that fixed a real defect and called it yours.

  5. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    The census run is done, and it does better than name the region — it names the allocation. The whole slope is ONE malloc block, realloc-grown on an exact ×1.25 ladder, whose content is every byte the session has consumed from the custom reader.

    Setup. Same WD7 recipe as every round (app tune on the tvOS device, spool arm through the custom reader, −30 s jump at +25 s, rewound hold to the kill), wrapper built against main@7ea32cf2 — so the pool fix (c90ffb16) and everything since is in — with setLargeAllocationCensusEnabled(true, triggerThresholdMB: 32, triggerPollHz: 8) armed at engine init. One axis note: the memprobe clock restarts at the jump's fresh install, so table t counts from ~30 s after the tune (last tick t=691; the log's final write lands ~12.5 s after it, at tune+734 s). The death is the same silent kill as every prior run: no crash report (.ips count identical before/after), app gone from a populated process table.

    The series (30 s memprobe; vmGrewMB = your summed positive per-tag deltas; REALLOC Δ = the vmTagTop leader every tick from t=60 on; big block = the larger of the two bigExact entries — the other is a static 3.4 MB):

    t (s) physFP MB vmGrewMB REALLOC Δ big block bytes muxBytesMB
    30 136 0 +0 117,981,184 101
    60 190 54 +52 184,385,536 154
    90 244 107 +105 230,506,496 205
    120 297 161 +159 288,178,176 256
    150 351 214 +212 360,251,392 308
    180 405 269 +266 450,330,624 360
    210 458 322 +319 562,921,472 410
    240 512 376 +373 562,921,472 462
    270 565 429 +427 703,660,032 514
    300 619 482 +480 703,660,032 564
    330 672 536 +534 703,660,032 617
    360 726 589 +587 879,591,424 669
    390 779 643 +641 879,591,424 719
    420 833 697 +694 879,591,424 772
    450 886 750 +747 1,099,530,240 822
    481 940 804 +801 1,099,530,240 873
    511 994 857 +855 1,099,530,240 926
    541 1047 911 +908 1,099,530,240 977
    571 1101 965 +962 1,374,486,528 1030
    601 1154 1018 +1015 1,374,486,528 1079
    631 1208 1071 +1069 1,374,486,528 1132
    661 1261 1125 +1122 1,374,486,528 1183
    691 1319 1179 +1176 1,374,486,528 1235

    Reading it:

    • vmGrewMB accounts for the physFP rise at EVERY tick, gap ≤ 4 MB. Nothing grew outside the census's sight.
    • The growth is one tag: REALLOC, +52 → +1176 MB at the mux rate. MALLOC_LARGE holds +1 MB the whole run, MALLOC_SMALL +0, and the only non-malloc entries ever to appear in the top 3 (UNTAGGED once, an unnamed tag89 once) do so at +0 MB. So it is the malloc family after all — the non-heap hypothesis dies here, and vmCmp stayed ≈0 (3 MB at the last tick) anyway.
    • The malloc big-block census pins it to one block (bigBlocks=2 the whole run; the second is a static 3,424,256 B across the memprobe series). Its capacity ladder is exactly geometric: every consecutive ratio in that column lands in 1.2500–1.2502 (and the t=30→60 move is two steps: 1.25² = 1.5625 vs 1.5628 measured). A growth factor that clean is a fingerprint, not a coincidence.
    • The steps land where the CONTENT crosses the previous capacity, and the content tracks bytes consumed from the reader: bracketing each crossing between the last emission at the old capacity and the first at the new one (the trigger-census lines give sub-second brackets on several) puts the block's content at muxBytesMB plus a small, slowly DRIFTING offset — +10.7…+11.5 MiB at the first bracketed crossing, +13.7…+14.8 at the next, +16.0…+18.8 after that, rising past +30 by mid-run. The block is holding ~every byte the session has consumed from the custom reader since load, appended forever, trimmed never.
    • Every gauge you already had stays flat while it grows: cacheMB bounded at 99–107, avioFetchedMB=0, avBufAhead 4–5 s / avBufBehind ≈27–31 s, pktAlive=3, packet/audio FIFOs zero. The 8 Hz trigger census fired until its own 12-emission cap (census trigger cap reached (12); further jumps are not captured — it landed ~4.4 min before the kill, so the final 1049→1312 MB step appears only in the 30 s memprobe grid); the 12 captured census trigger #N jump=+…MB lines carry block tops at each jump instant — archived in the leg log if you want them.

    So the search image on your side is concrete: something on the custom-reader live path appends the session's consumed byte stream into one contiguous buffer with a 1.25× growth policy. The malloc-stack-log offer stands if you want the allocation site proven from our device rather than found by grep — say the word and it runs the same recipe.


    Your ask 2 — the ring and the writer. The short version: the spool is a disk file store, not a memory ring, and nothing in it scales with bytes consumed.

    • Writer: one URLSession data pull (delegate on an owned serial queue) appends each ~64 KB chunk to a fixed-size 64 MB segment FILE (FileHandle.write) in a per-session temp directory; logical offsets are monotonic across segments for the session's life. No mmap anywhere — writes are file appends, reads are pread.
    • Bounds + drop policy: pruned once per segment roll (~1/min), dropping WHOLE oldest segments when either bound is exceeded — a 30-minute PCR-indexed time window, or a 2.5 GB byte backstop. Pruning unlinks the file; an in-flight reader positioned below the new floor keeps reading through its already-open descriptor (unlink semantics), and only future joins clamp to the floor. Session teardown deletes the directory.
    • What stays in memory (per session, independent of bytes consumed): the segment table (one (startOffset, URL) per 64 MB), one write handle, one cached read handle per reader, a PCR→offset index at ~1 entry/second (16 B each, pruned with the ring — ≈29 KB at the full window), and a bounded TS-parse carry (< one chunk). Well under 1 MB total.
    • Why we keep history although the engine never reaches back — your LOOKBACK number agrees with the design rather than indicting it: the history is for the app's own Live Rewind. A rewind is a fresh load — the app maps target-seconds → logical offset through the PCR index and hands the engine a new reader positioned there; the engine sees an ordinary fresh live source and never re-requests consumed bytes. So the ring grows for the viewer's rewind window, on disk, and your 0.0 MB reach-back is exactly what we'd expect.
    • Reader: read = a blocking ring read that preads straight into the buffer your bridge hands us (parks at the growth edge on a 0.25 s condvar quantum); seek accepts SEEK_SET/SEEK_CUR at/above the join anchor (FFmpeg's 0-based axis translated through the offset the install joined at; below-anchor and SEEK_END/AVSEEK_SIZE refuse — a live spool has no known end); allocations per read: none (one NSNumber on the rare seek).

    The source, writer side included, to run against your harness:

    The spool ring, the per-chunk writer path, the read path, and the engine-facing IOReader adapter

    WRITER — SpoolRing.append / rollSegment / prune (disk segment files)

        private func rollSegment() -> Bool {
            try? writeHandle?.close()
            writeHandle = nil   // never leave a CLOSED handle behind — a later write on it raises (review finding)
            let url = dir.appendingPathComponent(String(format: "seg-%06d.ts", segmentIndex))
            segmentIndex += 1
            guard FileManager.default.createFile(atPath: url.path, contents: nil),
                  let h = FileHandle(forWritingAtPath: url.path) else { return false }
            writeHandle = h
            cond.lock()
            writeSegmentStart = storedLength
            segments.append((start: storedLength, url: url))
            cond.unlock()
            return true
        }
    
        /// Writer-queue only. `ok=false` = the write/roll failed (disk full, dir gone) — the caller
        /// fails the pull instead of crashing: the legacy FileHandle.write(_:) RAISED an uncatchable
        /// NSException on error (review finding); write(contentsOf:) throws, and a failed roll leaves
        /// writeHandle nil rather than closed-but-referenced.
        func append(_ data: Data) -> (ok: Bool, rolledSegment: Bool) {
            // The write syscall stays OUTSIDE the lock (readers must never contend with disk I/O just
            // to compare offsets). Writer-queue confinement makes the unlocked handle access safe;
            // length only advances after the bytes are durably in the file.
            guard let handle = writeHandle, (try? handle.write(contentsOf: data)) != nil else {
                return (false, false)
            }
            cond.lock()
            storedLength += Int64(data.count)
            let needRoll = storedLength - writeSegmentStart >= segmentBytes
            cond.broadcast()
            cond.unlock()
            if needRoll { return (rollSegment(), true) }
            return (true, false)
        }
    
        /// Drop whole segments below `keepFrom` (the DVR window's new floor). Never drops the segment
        /// being written. In-flight readers positioned below the new floor keep reading their unlinked
        /// segments' data through their open descriptors; only FUTURE joins clamp to the floor.
        func prune(keepFrom: Int64) {
            var doomed: [URL] = []
            cond.lock()
            while segments.count > 1 {
                let next = segments[1].start
                guard next <= keepFrom else { break }
                doomed.append(segments.removeFirst().url)
                storedFloor = next
            }
            cond.unlock()
            for url in doomed { try? FileManager.default.removeItem(at: url) }
        }

    WRITER — the per-chunk URLSession path + the window bound

        func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
            let outcome = ring.append(data)
            guard outcome.ok else {
                failPull("spool write failed (disk full?)")
                session.invalidateAndCancel()
                return
            }
            index.ingest(data)
            signalWaitersIfReady()   // readiness only ever advances here — the one producer-side signal
            // Prune granularity is a whole 64MB segment (~1/min), so the window check rides the
            // segment ROLL instead of paying index+ring locks on every ~64KB chunk (review finding).
            if outcome.rolledSegment { maintainWindow() }
        }
        /// Prune to the time window (+ byte backstop). Writer-queue, once per segment roll.
        private func maintainWindow() {
            guard let w = index.window else { return }
            var keepFrom: Int64 = 0
            if w.edge - w.floor > Self.windowSecs {
                keepFrom = index.offset(forSecs: w.edge - Self.windowSecs) ?? 0
            }
            if ring.edge - ring.floor > Self.byteBackstop {
                keepFrom = max(keepFrom, ring.edge - Self.byteBackstop)
            }
            if keepFrom > ring.floor {
                ring.prune(keepFrom: keepFrom)
                index.prune(belowOffset: ring.floor)
            }
        }

    READ PATH — SpoolRing.read (pread into the caller's buffer) + the per-reader handle cache

        /// Blocking read at a LOGICAL offset straight into `buffer` (no intermediate Data — this runs
        /// on libVLC's input thread for every demux read). Returns (bytesRead, effectiveOffset):
        /// 0 bytes only at true EOF (writer closed, offset at/after final length); effectiveOffset ≥
        /// offset when the prune floor overtook a paused/slow reader — a data gap the TS demux resyncs
        /// over, same as any mid-GOP join.
        func read(at offset: Int64, into buffer: UnsafeMutablePointer<UInt8>, maxLength: Int,
                  reader: SpoolReader, isCancelled: () -> Bool = { false }) -> (count: Int, effectiveOffset: Int64) {
            cond.lock()
            while offset >= storedLength, !writerClosed, !isCancelled() {
                cond.wait(until: Date().addingTimeInterval(0.25))
            }
            // A cancelled (closed-stream) reader reports EOF without touching the segment table —
            // its backing stream is being torn down (P0 Fix-1b).
            if isCancelled() { cond.unlock(); return (0, offset) }
            let effOffset = max(offset, storedFloor)
            let available = storedLength - effOffset
            guard available > 0,
                  let seg = segments.last(where: { $0.start <= effOffset }) else {
                cond.unlock()
                return (0, effOffset)
            }
            let segEnd = segments.first(where: { $0.start > seg.start })?.start ?? storedLength
            // Open the reader's handle for this segment while STILL under the lock: prune() removes a
            // segment from `segments` under this same lock BEFORE unlinking it, so a segment selected
            // here cannot have been pruned yet, and once the descriptor is open, unlink can't
            // invalidate it. Opening after unlock raced the unlink → nil handle → a false EOF on a
            // live stream (review finding).
            let handle = reader.handle(for: seg.url)
            cond.unlock()
            guard let handle else { return (0, effOffset) }
            let take = min(Int64(maxLength), min(available, segEnd - effOffset))
            let n = pread(handle.fileDescriptor, buffer, Int(take), effOffset - seg.start)
            return (max(0, n), effOffset)
        }
    }
    
    /// A reader's per-segment FileHandle cache (each SpoolInputStream owns one). Keeping the handle
    /// open across reads also keeps PRUNED segments readable mid-flight (unlink semantics).
    final class SpoolReader {
        private var url: URL?
        private var cached: FileHandle?
        func handle(for segmentURL: URL) -> FileHandle? {
            if url == segmentURL, let cached { return cached }
            try? cached?.close()
            url = segmentURL
            cached = FileHandle(forReadingAtPath: segmentURL.path)
            return cached
        }
        deinit { try? cached?.close() }
    }

    READ PATH — SpoolInputStream.read (the stream the adapter wraps)

        override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength len: Int) -> Int {
            guard status == .open else { return 0 }
            let (count, effOffset) = ring.read(at: position, into: buffer, maxLength: len, reader: reader,
                                               isCancelled: { [weak self] in (self?.status ?? .closed) != .open })
            // Re-checked AFTER the blocking ring read, not just at entry (P0 Fix-1b): a close() that
            // landed while this thread was parked at the growth edge must surface as EOF — never
            // advance the position or overwrite .closed with .atEnd. The EOF mark is an atomic
            // .open→.atEnd transition so a close() racing between check and store survives.
            guard status == .open else { return 0 }
            if count == 0 { _ = transition(from: .open, to: .atEnd); return 0 }
            position = effOffset + Int64(count)   // the ring reports where the bytes really came from
            return count
        }
    
        override func property(forKey key: Stream.PropertyKey) -> Any? {
            key == .fileCurrentOffsetKey ? NSNumber(value: position) : nil
        }
    
        override func setProperty(_ property: Any?, forKey key: Stream.PropertyKey) -> Bool {
            guard key == .fileCurrentOffsetKey, let n = property as? NSNumber else { return false }
            position = max(0, n.int64Value)
            _ = transition(from: .atEnd, to: .open)   // atomic: a racing close() must not be revived
            return true
        }

    THE ENGINE-FACING ADAPTER — AetherSpoolReader (IOReader)

        init(stream: InputStream) {
            self.stream = stream
            self.joinOffset = (stream.property(forKey: .fileCurrentOffsetKey) as? NSNumber)?.int64Value ?? 0
        }
    
        func read(_ buffer: UnsafeMutablePointer<UInt8>?, size: Int32) -> Int32 {
            guard let buffer, size > 0 else { return 0 }
            let n = stream.read(buffer, maxLength: Int(size))
            return Int32(max(0, n))   // the spool returns 0 on close/EOF; negatives never (Fix-1b)
        }
    
        func seek(offset: Int64, whence: Int32) -> Int64 {
            let current = (stream.property(forKey: .fileCurrentOffsetKey) as? NSNumber)?.int64Value ?? joinOffset
            let target: Int64
            switch whence {
            case SEEK_SET: target = joinOffset + offset
            case SEEK_CUR: target = current + offset
            default: return -1   // SEEK_END / AVSEEK_SIZE: a live spool has no known end
            }
            guard target >= joinOffset,
                  stream.setProperty(NSNumber(value: target), forKey: .fileCurrentOffsetKey) else { return -1 }
            return target - joinOffset   // FFmpeg's axis, not the spool's
        }
    
        func close() { stream.close() }
        /// Unblock-only (the IOReader contract for reloadable readers — review P2): a parked
        /// ring read re-checks its cancellation and re-parks or returns without the stream
        /// dying. Spool-mode recovery never reloads a retained reader (reinstall forces the
        /// fresh-install path), so this is contract hygiene plus teardown-unhang, never a
        /// reuse path; close() remains the one invalidation.
        func cancel() { (stream as? SpoolInputStream)?.wake() ?? stream.close() }
        func makeIndependentReader() -> IOReader? { nil }   // makeStream() consumes the armed join intent — a non-consuming variant is the follow-up seam
        var discImageProbeEnabled: Bool { false }
    }

    (Context for the excerpts: SpoolRing/SpoolReader/SpoolInputStream live in the app's LiveDVR.swift; AetherSpoolReader is the IOReader the wrapper hands your load(source: .custom(…)). The same ring feeds our libVLC rung through 30-minute holds flat, which is what first pointed the retention at the engine-side path.)


    Edited same day after our adversarial review pass caught three defects in the first posting: (1) the "content ≈ muxBytes + ~55 MB" reconciliation was wrong — impossible at the t=30 tick by this comment's own content-≤-capacity model; the bracketed offsets above (+10.7…+11.5 MiB drifting past +30) are what the log supports, and the headline (one block holding ~every consumed byte) is unchanged and better supported by them; (2) the final-write gap read ≈43 s by double-counting the ~30 s tune→jump axis offset — it is ~12.5 s; (3) the trigger census did not run "through the run" — it hit its 12-emission cap ~4.4 min before the kill (you may want that cap liftable for exactly this shape). The last code fence also over-ran the adapter's closing brace into an unrelated platform stub; trimmed.

  6. superuser404notfound commented on Aug 28, 2026

    @superuser404notfound
    Owner

    6.55.0 carries c90ffb16 (the pool at CustomIOReaderBridge) and e19dffb7 (round 2 of the harness).

    Nothing in it should move your line, and that is the finding rather than a hedge: your reader preads into the buffer the bridge hands it and allocates nothing per read, so the pool has nothing to drain on your stack. The POSIX arm is the harness default now and measures flat across 900 MB, ratio -0.03 over 541 s and 0.00 with a 300 s DVR window, which is the control that was missing in round 1.

    So the open half is unchanged: the region census on your side, since every itemized bucket here is either a total or heap-only and your own block arithmetic points outside malloc.

  7. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    The census run you're asking for landed about an hour before the tag — see #445 (comment) above. Short version: it points INSIDE malloc after all — the entire physFP rise is one REALLOC-tagged block growing on an exact ×1.25 realloc ladder, content tracking bytes-consumed-from-the-reader (trigger-bracketed offsets in the comment). vmGrewMB accounts for the whole rise at every tick; no CM/IOSurface/untagged growth anywhere. The ring/writer answer and the reader+writer source are in the same comment.

  8. superuser404notfound commented on Aug 28, 2026

    @superuser404notfound
    Owner

    Your census landed while I was writing the 6.55.0 note, so that comment crossed it and its last line is wrong: your data does point inside malloc. It carries more than that, though, because the ladder names the allocator family on its own.

    x1.25 is Foundation's growth policy, not libav's. Data grows a large buffer by adding newLength >> 2 (above the 128 KB threshold), rounds the result through malloc_good_size, which is why your sizes are page-aligned, and it grows through realloc, which is why the region carries the REALLOC tag. Every other candidate on this path grows differently and your own column excludes them: av_fast_realloc / av_fast_malloc add a sixteenth plus 32 bytes (1.0625), FFmpeg's AVIO dynamic buffer adds a half (dyn_buf_write: size += size / 2 + 1), Swift's Array and String double, and a CoreMedia pool does not realloc at all. Nine consecutive rungs at 1.2500 to 1.2502 is one family: the block is a Swift Data.

    The one Data shape that grows like that while staying small. A Data consumed from the front with removeFirst only advances the slice's lower bound. The backing store keeps every byte below that bound and reallocs to fit the ever-rising upper bound, so count stays tiny while the allocation holds the entire stream. Twenty lines, no engine, on this Mac:

    --- removeFirst (64 KB chunks in, whole 188 B packets consumed) ---
    appended=  125 MiB carry.count=  92 footprint=  128 MB bigExact=142049280
    appended=  250 MiB carry.count= 184 footprint=  253 MB bigExact=277626880
    appended=  375 MiB carry.count=  88 footprint=  378 MB bigExact=433930240
    appended=  500 MiB carry.count= 180 footprint=  503 MB bigExact=542474240
    appended=  625 MiB carry.count=  84 footprint=  628 MB bigExact=678133760
    appended=  750 MiB carry.count= 176 footprint=  753 MB bigExact=847708160
    appended=  875 MiB carry.count=  80 footprint=  879 MB bigExact=1059717120
    appended= 1250 MiB carry.count= 168 footprint= 1254 MB bigExact=1324728320
    --- the same carry, re-based with subdata ---
    appended= 1250 MiB carry.count= 168 footprint=    2 MB bigExact=
    

    One block (nothing else in the process is over 1 MB), successive ratios 1.2501, content equal to every byte ever appended, logical length under one TS packet for the whole run, and the footprint tracking the stream 1:1. That is your table, produced by one call.

    The probe that settles it in your process, without Instruments:

    print("\(label) count=\(d.count) startIndex=\(d.startIndex) "
          + "mallocSizeAtBase=\(d.withUnsafeBytes { malloc_size($0.baseAddress) })")

    Leaking carry after 78 MB consumed: count=168 startIndex=78643032 mallocSizeAtBase=0 (an interior pointer, so malloc does not recognise the base). Re-based: count=168 startIndex=0 mallocSizeAtBase=192. startIndex is the whole tell and it costs one line per long-lived Data.

    Where to point it first: the piece you described as "a bounded TS-parse carry (< one chunk)". Bounded is a statement about count, and count is exactly what stays small in this defect, which is what makes it invisible from inside the code that owns it. Anything else that appends per chunk and consumes from the front (removeFirst, dropFirst assigned back, a front replaceSubrange) has the same shape. The engine paid for this pattern twice on its own buffers, on AVIOReader's persistent window (70430de) and in ByteFIFO's consume, and both re-base with subdata; neither sits on the custom-source path, which is why the allocation-free harness arm measures flat there across 900 MB.

    One correction to the axis, since it changes what your offset means: muxBytesMB is muxerLifetimeFragmentBytes, the bytes the engine's muxer has WRITTEN to its segment files, not the bytes it consumed from your reader. So the block tracking it means it tracks the stream, and the drifting +10.7 to +30 MiB is the difference between the remuxed output and whatever the block actually holds, not a measured lead over your reader. Worth knowing before that offset is used as evidence for either side. On the engine's own side of that axis there is no long-lived Data to be found: FFmpeg writes into the muxer's fixed 64 KB AVIO buffer, FragmentSplitter hands the moof/mdat bytes straight to write(fd), and the loopback server streams the segment file to the socket. ftyp+moov is the only Data on that path and it is released when moov closes.

    On main now (bfcb4f61, not tagged, collecting):

    • aetherctl customio --live --host-carry removeFirst|subdata: the carry above, put back on the harness's delivery path deliberately, as a positive control. Same fixture, same engine, 260 s at 14 Mbit:
    removeFirst   physFP 174 -> 450 MB over 201s = 1.38 MB/s (mux rate 1.67, ratio 0.82)
                  carry count=48B, slice lower bound 436.9 MB
    subdata       physFP  63 ->  60 MB over 201s = -0.01 MB/s (ratio -0.01)
                  carry count=132B, slice lower bound 0.0 MB
    

    Ratio 0.82 rather than 1.00 is the ladder itself: each realloc frees the old block before the new one is fully dirtied, so the footprint dips a step every time and a slope anchored mid-ladder reads slightly under the mux rate. The per-tick line carries carryCount and carryStart so the tell is visible while the run is going.

    • The census names the family itself now: bigGrowth=1.2501x(Data) next to bigExact, on both the 30 s memprobe line and the trigger line, each with its own previous value so neither reports the ratio the other's interval produced. An unrecognised ratio is printed bare instead of being rounded into the nearest story.

    • Your cap ask: setLargeAllocationCensusEnabled(_:triggerThresholdMB:triggerPollHz:triggerCaptureCap:), 0 = uncapped. A steady mux-rate climb spends one capture per threshold climbed, which is exactly why twelve ran out 4.4 minutes early on your run and the decisive final step only survived in the 30 s grid.

    If the startIndex probe on your ingest carry prints a number that tracks the stream, that is your block and the re-base is the fix. If every long-lived Data over there prints 0, the stack-log offer is the next step and I would take you up on it, because then the ladder says Data while none of yours is riding one.

  9. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    Confirmed at the bytes, same hour: it is ours, and it is exactly the shape you named. The "bounded TS-parse carry" is the one long-lived Data on our writer path, and its hot loop is verbatim your defect:

    carry.append(data)                    // per ~64 KB network chunk
    let consumed = carry.withUnsafeBytes { … }   // whole-packet scan
    …
    carry.removeFirst(consumed)           // ← the slice-lower-bound advance

    The comment two lines above it is the part you'd appreciate: this removeFirst was itself a review fix — the original per-packet carry = Data(carry.dropFirst(188)) was replaced for being O(n²) on the network queue. The slow version re-based every packet and could never leak; the fast one kept count small while the backing store kept the stream. "Bounded is a statement about count" is going in our review checklist word for word.

    It also closes the one exoneration we over-trusted: we'd reasoned "the same spool feeds libVLC through 30-minute holds, so the writer is clean" — but this carry sits on the shared writer path, and the libVLC arm was never memory-measured over a long hold. Your allocation-free-arm logic said engine-clean; ours should have said "writer unmeasured", not "writer clean".

    Fix (the subdata re-base) plus the before/after re-measure on the WD7 recipe are next from our side — bench access permitting, today; the startIndex probe rides the same build as the belt-and-suspenders confirmation. Thank you for the forensic read of the ladder — naming Foundation's growth constant from nine ratios is the kind of thing that saves a week of Instruments.

  10. cmcpherson274 commented on Aug 28, 2026

    @cmcpherson274
    Author

    Fixed, measured, and the numbers agree with your diagnosis to the megabyte.

    The fix: PCRIndex.ingest's trim is now a re-base — carry = carry.subdata(in: (carry.startIndex + consumed)..<carry.endIndex) — once per ~64 KB chunk, so the O(n²) the removeFirst was originally installed to kill stays dead too. (Your startIndex probe becomes structurally moot on this shape — a fresh backing store every chunk — which is its own kind of confirmation.)

    Before/after, same WD7 recipe, same device, same census:

    pre-fix (P-F1, this morning) post-fix (GATE1, tonight)
    physFP at t=30 136 MB (carry already 112.5 MB) 24 MB
    physFP slope +1.78 MB/s, ×1.25 ladder flat — min 24, max 26 MB across 58 ticks
    biggest malloc block 1,374,486,528 B at death the static 3.4 MB
    outcome silent jetsam at tune+734 s ended by us at 38.6 min, still −30 s behind, playing

    ~4 GB of stream through a process that grew 2 MB; crash count unmoved; zero recoveries. The t=30 arithmetic cross-checks your identification exactly: 136 − 112.5 ≈ 24 — the pre-fix baseline WAS the carry.

    So from our side #445 is resolved: your pool fix closed the class for readers that do allocate, your harness's clean arm proved the engine holds nothing, and your ladder forensics found the one buffer that was never the engine's. The census switch (bigGrowth naming, the settable trigger cap) has already paid for itself twice over here — it's staying in our permanent QA kit. Close whenever suits you, and thank you for chasing a leak that turned out to live in someone else's house.

  11. superuser404notfound commented on Aug 29, 2026

    @superuser404notfound
    Owner

    Closing on your numbers. That table is the cleanest possible end to this one: the t=30 arithmetic gives the identification back without any argument (136 minus 112.5 lands on exactly the 24 MB baseline), and 4 GB of stream through a process that moved 2 MB settles the rest.

    The part worth recording is that the removeFirst was itself a performance fix. The O(n²) re-base was correctly identified and correctly replaced, and the replacement was right about count and silent about the backing store. subdata is the version that is right about both. "Bounded is a statement about count" earned its place in your checklist, and it is going into the diagnostic notes here for the same reason.

    Where this stands on my side:

    • The autorelease pool at the custom-IO boundary (c90ffb16) is released in 6.55.0. It never covered your adapter, since a pread straight into our buffer allocates nothing, but it does close the class for hosts whose readers hand back +0 Foundation objects. That class had already cost FileIOReader and HTTPDiscIOReader a fix each, both one altitude too low, which is why it moved to the seam the engine owns.
    • The census work you have been running off main is bfcb4f61, not yet in a tag: bigGrowth=<ratio>x(<family>) on the memprobe and trigger lines, the settable triggerCaptureCap with 0 for unlimited, and the --host-carry removeFirst|subdata positive control in aetherctl customio. It ships with the next release, so a pinned build will carry it rather than a branch checkout.

    If the census stays in your QA kit, keep the ratio table beside it, because the family is the diagnosis: x1.25 is Foundation Data, x1.5 is FFmpeg's dyn_buf, x2 is a Swift array, and +1/16 is av_fast_realloc. Nine rungs at the same ratio is a far stronger fingerprint than any single sample, and it is cheap to log.

    Thank you for the measurement discipline across all three rounds. Two of them landed on my side of the fence and you ran them anyway, including the one that exonerated the engine, and the census that eventually found your buffer only exists because you asked for it.

  12. superuser404notfound commented on Aug 29, 2026

    @superuser404notfound
    Owner

    The census work from round 3 is in 6.56.0, so it is on a tag rather than a branch checkout now: bigGrowth=<ratio>x(<family>) beside bigExact on both the memprobe and the trigger lines, setLargeAllocationCensusEnabled(triggerCaptureCap:) with 0 for uncapped, and aetherctl customio --host-carry removeFirst|subdata as the positive control for the carry shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions