Skip to content

Persistent reader window grows without bound when the origin delivers moderately above media rate (URLSession suspend is advisory) #220

Closed

Description

@rrgomes

Playing a PGS-subtitled title on the software decode path allocates without bound on 5.20.7 until tvOS kills the app. 5.20.4 plays the same file with the same subtitle track cleanly.

Environment

  • AetherEngine 5.20.7 (4ec14be) — fails. 5.20.4 (1abe7fa) — clean.
  • Apple TV 4K 3rd gen (AppleTV14,1), tvOS 26.5.
  • Source: local MKV over HTTP. H.264 1080p interlaced (hardware deinterlace engaged, yadif_videotoolbox), DTS audio, one hdmv_pgs_subtitle track, 46.5 min. dispatch: codec=27 → software, so this is the software path, not loopback-HLS (srvConns=0, cacheCount=0, avioFetchedMB=0 throughout).
  • Subtitles enabled on the PGS track for the whole session.

Symptom

Memory is flat for twenty minutes, then goes vertical inside a single 30 s memprobe window:

t=1322s  rss=442MB  vmInt=300MB  vmCmp=7MB    physFP=299MB   mallocMB=537
t=1352s  rss=155MB  vmInt=141MB  vmCmp=978MB  physFP=1112MB  mallocMB=3642
t=1382s  rss=99MB   vmInt=89MB   vmCmp=236MB  physFP=316MB   mallocMB=4088
         -> process killed

Playback stutters and pauses shortly before the kill; our reader logs slow reads after the spike begins, so the stalling reads like a consequence of memory pressure rather than a source problem.

Two runs, and the second is the more interesting one

  • Cold start from 0: killed at ~22.5 minutes.
  • Relaunch and resume into the middle of the same file: rss 318MB at t=30s, 336MB at t=60s, 756MB / mallocMB=1622 at t=90s, killed roughly two minutes in.

Resuming into the middle fails an order of magnitude faster than playing from the start, which is what makes me suspect the seek-landing reconstruction path specifically rather than steady-state cue delivery.

subCues stays bounded the whole time (43 → 87 across the long run), so this is not cue count. The growth is in malloc and compressed memory, which is where I would expect decoded PGS bitmap surfaces to live.

Where I think it is (not proven)

I have not bisected 5.20.5 and 5.20.6 individually — only 5.20.4 good, 5.20.7 bad. Reading the range, #204 in 5.20.6 is the only change that touches this path: shouldFinalizeReconstruction lost its hasSuccessorAhead argument, so a reconstruction pass now finalizes whenever it is active with a candidate rather than only when nothing is stored ahead in the lead window. If a pass can stay active with a candidate across successive drain ticks, that would finalize repeatedly, and finalization inserts reconstruction cues.

That is a guess from the diff, not a diagnosis — you will know immediately whether the pass is supposed to be able to stay active.

Status on our side

We pinned back to 5.20.4 and re-ran the same title with the same track for 27 minutes: clean, memory flat. Nothing in 5.20.5 or 5.20.7 affects us (live-only, and a prefetch ceiling we do not opt into), so we are not blocked and can sit on 5.20.4 as long as needed.

Happy to run a candidate build against the repro, or capture anything else useful — the repro is reliable and cheap on our side.

Activity

  1. superuser404notfound commented on Jul 26, 2026

    @superuser404notfound
    Owner

    Thank you for this. The two-run comparison, the memprobe deltas, and the explicit note that subCues stays bounded while malloc runs away are exactly what makes this actionable without logs.

    On the #204 suspicion: it cannot loop

    Ruling that out first, since it is cheap to verify and it changes where to look.

    shouldFinalizeReconstruction losing hasSuccessorAhead cannot make a pass finalize repeatedly. finalizeReconstruction clears the pass state before it emits anything:

    mutating func finalizeReconstruction(playhead: Double) -> [SubtitleCue] {
        guard reconstructing else { return [] }
        reconstructing = false
        ...
    }

    and reconstructing is set back to true at exactly one place in the engine: the .resetAndDecode branch of the drain tick, which only fires on a fresh selection or a playhead jump past the 2.5 s threshold. So the gate is single-shot per reset in both 5.20.4 and 5.20.7. What the #204 change altered is whether a pass that never saw a renderable successor publishes its landing line or stays dark, not how many times it can run.

    The reconstruction candidate is also a single same-start group, replaced rather than appended, and finalized cues go through the same-start same-geometry replacing insert. Neither accumulates. That matches your subCues observation rather than contradicting it.

    The likelier variable, and it is not in your bisect range

    5.20.7 is the last release before the SoftwarePlaybackHost autorelease fix. #205 landed in 5.20.8:

    Each of the four dispatch-block loops (demux, reader, feeder, pumpAudio) now drains its autorelease pool on every iteration instead of only at session end [...] Each loop ran inside a single GCD work item that never returned for the lifetime of the session, so the thread's autorelease pool was never drained and per-iteration temporaries accrued unbounded while every pool the engine tracks itself (packet ring, segment cache, audio FIFO) stayed flat.

    That is the same shape you measured: growth in malloc and compressed memory, engine-tracked pools flat, jetsam kill on a long software-path session. On an Apple TV 4K (3rd gen) the pre-fix footprint climbed 174 MB to 451 MB over ten minutes and holds flat at ~163 MB over thirteen minutes after.

    It also accounts for the terminal shape specifically. The back-pressure park polls isReadyForMoreMediaData at up to 200 Hz, so the moment the renderer stops draining, the per-iteration temporary rate multiplies and the leak goes vertical. That is a feedback loop, which is why the last 30 s look nothing like the first twenty minutes and why the stalling reads show up on the way down rather than on the way up.

    The catch: 5.20.4 predates that fix too, so your good/bad pair does not separate this variable. Both builds carry the leak; only the rate at which each session reaches the ceiling differs.

    What would settle it

    1. A run on 5.23.3. It carries the Long running SoftwarePlaybackHost live sessions result in host app being terminated due to memory pressure #205 fix plus everything since. If the repro survives it, the autorelease path is out and the subtitle drain is back on the table with a much smaller search space.
    2. If it still reproduces, the mallocMB / malloc-block series from the 5.20.4 baseline run would help. "Flat" in rss or physFP is consistent with a leak that the compressor is still absorbing, so the malloc counter is the one that separates a genuinely clean baseline from a slower approach to the same ceiling.

    Taking the offer of a candidate build up if 5.23.3 does not resolve it. The next step there would be a counter on drain resets and forward-prefetch restarts: a reset re-decodes a 75 s PGS window and opens a fresh side demuxer, so if playhead jitter is driving resets at tick rate, that is a second amplifier worth measuring rather than guessing at.

  2. rrgomes commented on Jul 26, 2026

    @rrgomes
    ContributorAuthor

    5.23.3 does not fix it, and a subtitles-off control isolates it to the PGS path

    Ran your suggested 5.23.3 (pinned at f16e1cd) on the same Apple TV 4K 3rd gen, tvOS 26.5, same source: a 46-minute 1080i H.264 episode, interlaced so it takes dispatch: codec=27 → software, DTS-HD MA 5.1, one hdmv_pgs_subtitle track. Resume into the middle, PGS track selected. It died in 2.5 minutes.

    t=30s    rss=338MB  physFP=180MB  vmCmp=0MB   mallocBlocks=611171  mallocMB=431  subCues=18
    t=60s    rss=354MB  physFP=193MB  vmCmp=0MB   mallocBlocks=600059  mallocMB=449  subCues=27
    t=90s    rss=333MB  physFP=169MB  vmCmp=0MB   mallocBlocks=598000  mallocMB=430  subCues=37
    t=120s   rss=334MB  physFP=169MB  vmCmp=0MB   mallocBlocks=598025  mallocMB=437  subCues=47
    t=150s   rss=508MB  physFP=420MB  vmCmp=29MB  mallocBlocks=597127  mallocMB=876  subCues=56   <- last line
    

    So the autorelease path is out, as you framed it. There is also a signal in these numbers that argues against it independently of the version test: mallocBlocks falls (598,025 → 597,127) while mallocMB doubles (437 → 876). Bytes explode while the block count does not. Undrained per-iteration temporaries would show the opposite — many small blocks. This is a small number of very large allocations.

    The control. Identical run — same build, same file, same software dispatch, same start position — with the subtitle track deselected server-side:

    t=30s    rss=288MB  physFP=138MB  vmCmp=0MB  mallocBlocks=592789  mallocMB=344  subCues=0
    t=150s   rss=290MB  physFP=140MB  vmCmp=0MB  mallocBlocks=578304  mallocMB=351  subCues=0
    t=300s   rss=291MB  physFP=140MB  vmCmp=0MB  mallocBlocks=577960  mallocMB=347  subCues=0
    

    Flat for twice as long as the PGS run lasted, at lower absolute memory than that run ever reached.

    Two observations from the failing run, offered as leads rather than conclusions:

    1. subCues climbs strictly monotonically, ~10 per 30 s, from the first sample. On the clean 5.20.4 baseline it oscillated (40–76, rising and falling), so on this run nothing is being released. The count stays small, but each cue on this path holds a decoded bitmap, and the magnitude of the jump is in the right range for a few dozen full-width decoded surfaces.
    2. Every cue is inserted open-ended: cueStart=1393.800s cueEnd=4296361.095s. The difference is exactly 2^32-1 ms, the same shape as PGS cues arriving after a reader stall flash through the overlay one by one — each inserts with an open-ended endTime (start + 2^32 ms) and only its successor's trim removes it #100. Combined with #151 forward prefetch started: streams=[2] startAt=1396.36s lead=60.0s, a 60-second window of PGS cues is resident and none of it can expire by time.

    The step rather than a ramp is what makes me think the decode happens in bulk rather than per cue, which would line up with the reset/re-decode amplifier you named — but I can't distinguish that from the host side.

    Baseline malloc series you asked for, the clean 27-minute 5.20.4 run on the same source and track: mallocMB oscillates 498–580 across t=30s→1684s with no trend, mallocBlocks 1,432,543 → 1,442,866 (+0.7%), physFP 274–307 MB, vmCmp pinned at 8 MB. Genuinely flat, not a slower approach to the same ceiling.

    One caveat on what these logs can and cannot show: applySubtitleEvent logging is capped at 20 per load(), and we reach #20 about 40 s in, so the absence of later cue lines carries no information — only the memprobe series does. (We misread exactly that once before, in #196.)

    Happy to take a candidate build, and to run any counter you want on drain resets or forward-prefetch restarts.

  3. superuser404notfound commented on Jul 26, 2026

    @superuser404notfound
    Owner

    The subtitles-off control is the most valuable thing in this thread so far. It isolates the growth to the PGS path at equal video work, equal dispatch, equal start position, and it runs twice as long at lower absolute memory than the failing run ever reached. Combined with the 5.23.3 result, the autorelease path is closed and the baseline malloc series settles the "flat is real" question. Nothing further is needed on that axis.

    Two of the three leads offered are worth taking off the table before more measurement goes into them, because both are expected behaviour rather than signal, and chasing them would cost a run each.

    The monotonic subCues is a run-length artifact

    Cue retention prunes against sourceTime - 300 s:

    let cutoff = sourceTime - subtitleCueRetentionSeconds   // 300
    guard cutoff > 0 else { return }
    cues.removeAll { $0.endTime < cutoff }

    The failing run died at 150 s, so the cutoff was never reachable and nothing was eligible for eviction at any sample. The 5.20.4 baseline ran 27 minutes, which is why it oscillated. Strictly-monotonic-over-150 s and oscillating-over-27-minutes are the same behaviour observed through two different window lengths, not a regression between the builds.

    The open-ended cueEnd is the PGS representation, not #100

    A PGS composition has no intrinsic end. FFmpeg reports end_display_time = UINT32_MAX, the decoder stamps that placeholder window, and the SUCCESSOR composition's trim closes it. The 2^32-1 ms difference is what a correctly inserted PGS cue looks like at insert time, on every build. #100 is the gate that copes with that representation during catch-up, so the shape is a consequence of the design rather than evidence of the defect.

    The related worry, that a resident 60 s window of cues holds decoded bitmaps that cannot expire, does not carry the magnitude either. Bitmap rects are re-cropped to their non-zero-alpha bounding box before the CGImage is built, specifically because some Blu-ray-to-MKV conversions emit full-frame ODS bitmaps with cropping params that pgssubdec discards. A dialogue line is a few hundred KB, so the 56 cues resident at the last sample cannot account for 439 MB.

    Where the block-count observation actually points

    mallocBlocks falling while mallocMB doubles is the strongest measurement in the report. Every subtitle-side structure is byte-bounded already: the packet store caps at 32 MB per stream and 96 MB in aggregate, the cue array is small and holds cropped bitmaps. One thing on that path is not bounded by bytes at all, only by how many of it exist at once: the #151 forward-prefetch side demuxer.

    Each one carries its own AVIO reader, and each reader carries a 16 MB sliding window, up to 32 MB of 4 MB detour blocks, and a 4 MB current plus 4 MB prefetch chunk. That is roughly 56 MB of large, few-block allocations per live instance, which is the allocation shape measured.

    The arithmetic lines up with both runs. The steady-state difference between the PGS run and the control is about 87 MB at t=30 s and holds flat through t=120 s, consistent with exactly one side demuxer alive. The terminal jump of 439 MB is consistent with roughly five more.

    The restart path does not serialize:

    func cancelSubtitleForwardPrefetcher() {
        subtitleForwardPrefetchTask?.cancel()
        subtitleForwardPrefetchTask = nil
        subtitleForwardPrefetchDemuxer?.markClosed()
        subtitleForwardPrefetchDemuxer = nil
    }

    markClosed() releases the socket and unblocks a parked read. It deliberately does not free the AVIO buffers; only close() does, and that runs in the outgoing task's defer whenever that task actually returns. The replacement demuxer opens immediately, without waiting for the outgoing one to unwind. Nothing caps how many can be mid-teardown at once.

    The restart trigger is a playhead jump beyond 2.5 s observed by the 500 ms drain tick. That is the feedback loop this shape needs: a rebuffer moves the playhead enough to re-anchor, the replacement immediately runs a cue-index prewarm seek to duration * 0.5 plus a positioning seek over the same link, which competes with the starved playback read, which produces the next jump. It also explains why resume into the middle dies faster than a cold start, and why a step rather than a ramp shows up at the end while the first two minutes look level.

    The check that costs nothing

    This is decidable from logs already captured, with no candidate build. Count the

    #151 forward prefetch started: streams=[...] startAt=...
    

    lines in the failing run, and pair them against #151 forward prefetch exited. Those emit once per prefetch session and are not subject to the applySubtitleEvent 20-per-load cap, so unlike the cue lines, their absence is informative.

    One started line and one matching exited refutes the hypothesis outright and the search moves elsewhere. Several started lines clustered into the final 30 s, or any run of started lines without matching exited lines, confirms overlap and gives the count directly.

    If it confirms, the fix is on the engine side and is not a tuning change: the restart has to await the outgoing session's teardown and free through close() rather than leaving buffers resident behind a markClosed(), plus a guard so tick-rate re-anchoring cannot open a second demuxer while the first is still unwinding. The offer of a candidate build is taken up either way, but the log count decides which build is worth the time.

  4. rrgomes commented on Jul 26, 2026

    @rrgomes
    ContributorAuthor

    The prefetch count refutes the overlap hypothesis

    Counted across every run on this source today. In both kills there is exactly one live prefetch session, and no cluster in the final 30 s.

    Failing run on 5.23.3 (resume into the middle, died at 2.5 min):

    16:06:03  #151 started: streams=[2] startAt=0.00s lead=60.0s
    16:06:03  #151 exited (cancelled=true) harvested=5
    16:06:03  #151 started: streams=[2] startAt=1396.36s lead=60.0s     <- live at death
    

    Cold-start kill on 5.20.7 (died at 22.5 min): identical shape — one cancelled start at t≈0, one live session for the rest of the run. The clean 5.20.4 baseline (27 min) also ran with exactly one live prefetch session throughout, so the count does not separate clean from failing either.

    There is also a direct counter-example. A 5.20.7 run restarted the prefetcher five times in 34 seconds, with exactly the decreasing re-anchor targets the hypothesis predicts:

    01:18:02  started startAt=0.00s     -> exited harvested=5
    01:18:02  started startAt=1485.32s  -> exited harvested=41
    01:18:15  started startAt=1479.72s  -> exited harvested=44
    01:18:34  started startAt=1477.71s  -> exited harvested=16
    01:18:36  started startAt=1468.98s  -> exited harvested=284 (01:40:50)
    

    That run did not die. It played for 22 more minutes and exited cleanly. So the clustered-restart shape happens without a kill, and the kills happen without the clustered-restart shape.

    Taking both corrections: the monotonic subCues as a 300 s-retention run-length artifact, and the open-ended cueEnd as the PGS representation rather than #100 evidence. Both retract cleanly — the 150 s run never reached the cutoff, and I read a per-build difference into a window-length difference.

    That leaves the block-count measurement without a candidate: bytes doubling while block count falls, on the PGS path, with the subtitle-side structures byte-bounded and the side demuxer now excluded by count. Happy to take the candidate build, and to run any instrumented counter you want — a per-allocation-site byte tally on that path would be more use than anything further I can infer from these logs.

  5. superuser404notfound commented on Jul 26, 2026

    @superuser404notfound
    Owner

    Thank you for running that count. It settles the question, and the counter-example is the more valuable half: a run that restarts the prefetcher five times in 34 seconds, with exactly the descending re-anchor targets the hypothesis predicts, and then plays for 22 more minutes and exits cleanly. Clustered restarts without a kill, and kills without clustered restarts. The overlap idea is withdrawn.

    Rather than send another round of questions, I went looking locally.

    What the local runs say

    Harness: a Blu-ray remux served from a real Jellyfin origin over LAN, software path, one PGS track selected, and the memprobe extended with a live census of malloc blocks at or above 1 MB (count, summed size, and the exact sizes of the largest few).

    Ten minutes with the PGS track against ten minutes with subtitles off, same source, same dispatch, same start position:

    large blocks mallocMB over 600 s summed size of large blocks
    subtitles off constant 4 42 → 60, no trend 25-39 MB, no trend
    PGS selected constant 8 56 → 122 36-73 MB, no trend

    The block count is the useful part. Selecting a PGS track takes the large-block count from 4 to 8 and holds it there: one extra reader buffer plus three extra 4 MB detour blocks. That is the forward prefetcher's side demuxer, and it is a fixed structural cost of roughly 32 MB rather than something that accumulates.

    That is worth separating out of your numbers, because it accounts for the shape of the ~87 MB steady-state difference you measured at t=30 s between the PGS run and the control: a constant offset that appears when the second demuxer opens and then holds flat is expected on this path. The terminal 439 MB is the part that still needs an explanation.

    A third run drove 89 seeks over 15 minutes to push the drain through resetAndDecode repeatedly, which is the churn a rebuffering source produces on its own. The large-block count settles at 13 and moves by at most one after that, their summed size oscillates between 49 and 95 MB with no trend, and all 89 prefetch sessions started and exited paired.

    So the kill does not reproduce here. Being explicit about what that is worth: the remux I have is progressive HEVC, so the software path had to be forced with a test flag rather than reached through interlaced content, which leaves the deinterlacer out of the picture entirely, and this is macOS rather than tvOS. Both are real gaps against your setup.

    A correction to something I told you

    I described the monotonic subCues as purely a run-length artifact. That is right for your 150 s run, but it was too broad as a general statement. The prune is:

    cues.removeAll { $0.endTime < cutoff }

    A PGS image cue carries endTime = start + (2^32-1) ms until a successor composition trims it, so an untrimmed one cannot satisfy that predicate at any playhead. Time-based retention on this path only ever evicts cues that a successor already closed. At 56 cues that is nowhere near your magnitude, so it is not the defect, but the mechanism is real and I waved it away too broadly.

    Two refinements to the search space

    mallocMB is malloc_zone_statistics().size_in_use, so it counts live allocated bytes rather than address space. Your +439 MB sits against only +251 MB of footprint growth, which means roughly 190 MB was allocated and never written. Together with the falling block count, that is precisely the case the comment above that counter names: a flat count with a rising size is a single large buffer growing, and a largely unwritten one at that.

    On the bisect: of the three functional commits between 5.20.4 and 5.20.7, two cannot execute in your session. The byte-bounded prefetch change touches the opt-in forward buffer and the segment cache, and the third is live loopback only. With cacheCount=0, srvConns=0 and no loopback, neither path runs. That leaves the PGS clear-successor change as the only reachable difference inside your own good/bad pair. I ruled it out mechanically earlier, and that argument still holds for the specific question of whether a pass can finalize repeatedly, but by elimination it is the only delta left in that range and should not stay dismissed.

    The build

    Taking up the offer. The triage build carries the census wired into the existing 30 s memprobe line, adding bigBlocks, bigMB, bigTop and bigExact: how many live blocks of at least 1 MB exist, their total, and the exact sizes of the largest few. If the growth really is one buffer being reallocated larger, the exact size will name it outright instead of leaving it to be inferred from the totals.

    The same run shape as before would be ideal: the resume into the middle that dies in about two and a half minutes, plus the subtitles-off control alongside it.

  6. rrgomes commented on Jul 26, 2026

    @rrgomes
    ContributorAuthor

    Happy to run it — but I don't think the build actually shipped. There's no branch, tag, release or PR I can find carrying the census, and no ref in the comment. If you push it as a tag or branch I'll pin to it and run the pair the same evening.

    Two things from our side while that's in flight.

    The deinterlacer is not an incidental gap in your harness — it may be the gap. You forced the software path with a test flag on a progressive remux. We arrive there by a different route: forcesSoftwareForUndecodableFormat returns true because VideoToolbox can't hardware-decode this interlaced H.264, so every killing run has a live deinterlace graph:

    [Deinterlace] engaged [hardware]: 64x64 pixFmt=0
      (format=nv12,hwupload,yadif_videotoolbox=mode=send_field:parity=auto:deint=interlaced) outTB=1/60
    

    That is an hwupload into a VideoToolbox pool plus a Metal yadif at field rate, none of which exists in your runs. Being straight about how far that gets us: the subtitles-off control ran the same graph and stayed flat for 300 s, so the deinterlacer alone is not the cause. But it means the failing configuration is PGS and a hardware deinterlace graph, and you have only ever tested PGS without one.

    Could the triage build expose the software-path force flag? If it does, we can run PGS on progressive content forced to software, on tvOS. That isolates the deinterlacer from the PGS path on our hardware in a single run. Right now we can't produce that control at all — anything progressive we own is hardware-decodable and routes native.

    Noted on bigBlocks/bigMB/bigTop/bigExact, on the ~87 MB steady-state offset being the second demuxer's fixed structural cost rather than a leak, and on the untrimmed-endTime retention mechanism being real but too small to matter here. We're on 5.23.7 now.

  7. superuser404notfound commented on Jul 26, 2026

    @superuser404notfound
    Owner

    The ref was missing from that comment, which is on me. Both branches are public:

    • Engine: diag/issue-220-malloc-census at 8189b0db03f812184194bd2cae5dc7bdfd715584, sitting directly on 5.23.7.
    • Host: diag/issue-220-census-build at 7303c306bb80243d76ba690d216f58394e0adbcd, which already pins the engine commit above.

    One thing that would otherwise cost a whole run: pinning the engine alone produces nothing. The census is opt-in, and the host has to arm it with

    AetherEngine.setLargeAllocationCensusEnabled(true)

    before playback starts. The host branch does that in the composition root, so building that branch needs no edit.

    On the deinterlacer

    Good push, and it sent me back to the logs instead of my own summary of them. The premise turns out not to hold: that combination has been tested.

    Two harnesses ran and I conflated them in the write-up. The Blu-ray remux is progressive, so it only reached software through the test flag and had no deinterlace graph, which is the case I described. But the runs before it used a synthetic 1080i H.264 source that reaches software the same way yours does, and those carried a live full-size graph:

    [Deinterlace] engaged [hardware]: 1920x1080 pixFmt=0
      (format=nv12,hwupload,yadif_videotoolbox=mode=send_field:parity=auto:deint=interlaced) outTB=1/2000
    

    Same graph as yours, at frame size, with a PGS track selected, and the objects in that source are full-frame 1920x1080 ODS so the full-plane decode branch is exercised as well. Over 300 s mallocMB went from 377 down to 49. A second run over the same source with 36 seeks pushed memory up but oscillating, with no trend. So PGS alongside a live hardware yadif graph does not by itself produce the growth, at least on macOS over that duration.

    What that does not settle: those runs are five minutes against your 22.5 minute cold start, they are macOS rather than tvOS, and the PGS is synthetic. The platform gap stays wide open in particular, since yadif_videotoolbox and the VideoToolbox pool behind hwupload are not the same implementation on tvOS.

    One detail worth having, because it changes what your own logs prove. The line quoted above:

    [Deinterlace] engaged [hardware]: 64x64 pixFmt=0 (...) outTB=1/60
    

    is the warm-up probe rather than the session's graph. It appears in every run here, including the progressive ones that never deinterlace anything. The real graph logs separately at the frame size with its own output timebase, so that is the line to grep for when confirming the graph is live. Your content is interlaced and certainly has one, but the 64x64 line on its own would not show it.

    The control you asked for

    Worth having, and it is in the host branch now. setForceSoftwarePathForTesting was already public on the engine, so the diag build only had to make it reachable:

    // AetherEngine.setForceSoftwarePathForTesting(true)

    sits commented directly under the census opt-in in SodaliteApp.init. Uncomment it and every source routes through the software host, so progressive hardware-decodable content produces exactly the control described: PGS on the software path with no deinterlace graph, on your hardware. Interlaced sources reach software on their own and do not need it.

    It is a comment rather than a toggle on purpose. tvOS has no convenient way to flip a UserDefaults key from outside the app, and one uncommented line in a source build is harder to get wrong than a hidden switch.

    The pair from before is still the most valuable single run though: the resume into the middle that dies in about two and a half minutes, plus the subtitles-off control, both with the census armed.

  8. rrgomes commented on Jul 26, 2026

    @rrgomes
    ContributorAuthor

    Both runs are clean, and reading the logs for them I found something that undercuts this issue's premise. Reporting it against ourselves.

    The census runs

    Apple TV 4K (3rd gen), tvOS 26.5, engine at 8189b0db with the census armed, resume into the middle, played through to end of media — 23 minutes. bigBlocks pinned at 24 for the whole run, bigMB 82-127 with no trend, and the largest block oscillating between 11 MB and 25.6 MB rather than climbing.

    A second, identical Apple TV 4K running plain 5.23.7 with no census, same source, same start position: flat through 5 minutes. Its subCues series is identical sample-for-sample to the 5.23.3 kill run (18/27/37/47/56), so the two sessions match right up to the point where one of them died. The census is not masking anything.

    The failure is explosive, not gradual

    Every kill we have is flat and then jumps inside a single 30 s sample:

    run last healthy sample next sample
    5.20.7, cold start t=1322 mallocMB=537 mallocBlocks=1122892 t=1352 mallocMB=3642 physFP=1112MB mallocBlocks=884778
    5.20.7, restart t=60 mallocMB=424 t=90 mallocMB=1622 physFP=737MB
    5.23.3, resume into middle t=120 mallocMB=437 t=150 mallocMB=876 physFP=420MB

    +3.1 GB, +1.2 GB and +439 MB, each inside one sampling interval, after 22 minutes, 60 seconds and 120 seconds of dead-flat behaviour respectively. The block count falls hard at the same moment — 238,000 fewer blocks across the +3.1 GB step.

    And 5.20.7 both kills and runs clean

    All four of those sessions are the same host build, pinning AetherEngine 4ec14be3 = 5.20.7. In the same hour that build killed twice and then played 22.5 minutes flat at mallocMB around 432 with no incident.

    I don't think "5.20.4 clean, 5.20.7 kills" survives that. Our 5.20.4 baseline was a single 27-minute run, and one clean run on a build that kills intermittently proves nothing — so the bisect that leaves the PGS clear-successor change as the only reachable delta rests on a discriminator we don't actually have. It also makes your inability to reproduce much less surprising than it looked, and it means our two clean runs tonight are not evidence of a fix either.

    What that implies for the census

    The event completes inside one 30 s window, so a 30 s sampler can never name the allocation — by the following tick the process is dying or already gone. Catching it would need either a much shorter interval while a PGS track is active, or a trigger: capture the top blocks when size_in_use jumps past some threshold since the previous check, tested at a few Hz. Happy to build and run whatever shape you prefer.

    Two smaller things

    Our runs show only the 64x64 warm-up probe and never a frame-size Deinterlace line, on 1080i content that is certainly being deinterlaced — so either that line is conditional or something is not engaging.

    And I withdraw my earlier claim to have shown the graph was live in the killing runs. That was the warm-up probe, exactly as you said.

  9. superuser404notfound commented on Jul 27, 2026

    @superuser404notfound
    Owner

    Reporting a result against your own premise is the most useful thing anyone has done on this thread. Taking all three points.

    The bisect is gone, and it should be

    Four sessions on the same host build pinning 4ec14be3, two kills and a 22.5 minute clean run inside the same hour, is decisive. A build that fails intermittently cannot be cleared by a single 27 minute run, so the 5.20.4 baseline never was a discriminator, and the elimination argument I built on top of it collapses with it. The PGS clear-successor change is no longer "the only reachable delta", because there is no established regression range for it to be the delta of.

    That is worth more than it costs. It removes a constraint that was quietly steering the search, and it means the defect may predate 5.20.4 entirely rather than having been introduced in that window. It also explains the reproduction failure far better than any of the platform gaps I listed: if the same build kills twice and then runs clean, a handful of clean runs on a different platform were never going to say much.

    And you are right that tonight's two clean runs are not evidence of a fix. Nothing has been fixed.

    The explosive shape is the finding

    That table is the most informative thing in the issue so far. Flat, then +439 MB, +1.2 GB or +3.1 GB inside one sampling interval, after two minutes, sixty seconds and twenty-two minutes of level behaviour.

    The block count matters as much as the bytes. Across the +3.1 GB step the count falls by roughly 238,000, so those bytes did not arrive as many allocations. They arrived as very few, while a large number of small blocks were being freed at the same moment, which is what a process does when it is shedding caches under pressure. Gross allocation is therefore larger than the +3.1 GB net.

    Very few blocks carrying gigabytes is a size computation producing an absurd value, not a buffer that grew. That is a different search from the one this issue started with, and it is one the census can finish in a single line, because the exact size of the block is the evidence.

    New build: the census fires on the jump, not on a clock

    Your read is right and the 30 s cadence is abandoned rather than shortened.

    • Engine: diag/issue-220-malloc-census at 629efbffe5e7135abe5eaef43c080dbe5317fa8f
    • Host: diag/issue-220-census-build at 1593aced7cdb6f6161ccce31dbe301d8df6e2c4e

    malloc_zone_statistics is a counter read with no enumeration, so it is polled at 8 Hz, and the expensive zone walk runs only once the counter has actually moved. Each capture emits the jump size, the current and peak size_in_use, the block count, and the full census including bigExact.

    Two design points that decide whether it works at all:

    It runs on its own queue, never the main actor. The existing memprobe is @MainActor, and if the main actor is blocked during the event then raising its rate would not have helped. This watcher is unaffected by that.

    The trigger is monotone: a capture requires size_in_use to clear its running high-water by the threshold, rather than comparing against the previous poll. That is not theoretical tidiness. The first version compared consecutive polls, and against a local PGS session it fired over and over at a completely flat 373 to 374 MB, because the allocator swings about 12 MB between two levels at 8 Hz without going anywhere. It would have spent its entire capture budget on churn in the first thirty seconds and had nothing left for your event. The monotone rule produces eight captures on strictly rising levels and then goes quiet when the session plateaus.

    Defaults are 64 MB above high-water and 8 Hz, tunable through setLargeAllocationCensusEnabled(_:triggerThresholdMB:triggerPollHz:). Given your smallest step is +439 MB there is a lot of headroom; if your session climbs gently enough to spend captures on the climb, raise the threshold rather than lower it. The captures are capped at twelve so a sustained explosion cannot turn the log into a slideshow of zone walks while the device is already dying.

    The running high-water is recorded on every poll rather than only on captures, and shows up as peakMB on the memprobe line, so a step that no sample caught still leaves a trace.

    On the Deinterlace line

    Checked the code rather than guessing. The frame-size line is unconditional at the point the filter graph configures, and it uses the same log category as the warm-up line you do see, so category filtering or gating cannot explain the difference. Its absence means the graph never configured at frame size.

    Which raises a question worth answering on your side before it gets folded into this issue: does the picture actually look deinterlaced in those sessions? If it is visibly combed, that is a separate defect and deserves its own issue. If it looks correct, then something other than that filter is handling it and the log line is not the signal I assumed it was.

    No need to withdraw anything on the warm-up probe. It reads as an engaged line and it names an engine and a filter chain, so reading it as the live graph was reasonable. That the same line appears on progressive content that never deinterlaces anything is a logging problem, not a reading error.

  10. rrgomes commented on Jul 27, 2026

    @rrgomes
    ContributorAuthor

    Taking the new build — I'll pin 629efbff and arm it tonight. Before that, two things landed on our side that change the search, and one of them answers your deinterlacer question outright.

    The kill is wire-fed

    Our Plex server logs per-connection lifetime byte totals at connection close, which gives server-side ground truth per reader. For the 5.23.3 kill both long-lived connections closed at process death:

    range: bytes=5600572296-    680,296,448 bytes / 170.65s =  3.8 MB/s   ← pump reader
    range: bytes=5592281175-  1,806,974,976 bytes / 170.17s = 10.1 MB/s   ← subtitle prefetcher's side reader
    

    Media rate for the file is 10,884,979,438 B / 2792.2 s = 3.90 MB/s. The pump was exactly paced, healthy to the very end — video and audio decode were never in trouble. The prefetcher consumed 1.7 GB in 170 s, 2.6× media rate, and its final file position (7.40 GB = 68.0% of the file ≈ source 1899 s) puts it at playhead + 333 s, against a 60 s lead allowance, still streaming when the process died.

    The clean census run over the same source and start offset has both connections at media rate: prefetcher 5.29 GB / 1320 s = 4.0 MB/s, pump 5.28 GB / 1381 s = 3.8 MB/s, both reading to EOF as the playhead reached end of media. A properly parked prefetcher measures at media rate. The kill run's did not.

    The excess, roughly 0.8–1.1 GB concentrated in the final stretch, matches the client-side malloc explosion in both magnitude and timing.

    This also explains the PGS-only conditionality for free, which no allocator-side story did: the prefetcher only exists while a subtitle track is selected. The subtitles-off control doesn't have a second reader at all.

    The park had constant opportunities and never took one

    The park in SubtitleForwardPrefetcher.run is edge-triggered on subtitle packets only — discarded A/V packets continue before the guard. So we checked whether it was simply starved of triggers. ffprobe of the PGS stream across the whole overshoot region shows packets every 1 to 5 seconds, no gaps. The loop passed dozens of parkable packets between 1626 s and 1899 s without parking once. Broken, not idle.

    The park-break candidate we'd put first, purely from reading the code:

    tb = demuxer.stream(at: streamIdx)?.pointee.time_base ?? AVRational(num: 0, den: 1)

    That result — including the 0/1 fallback — is cached in timeBaseCache for the session. The guard is guard rawTS != Int64.min, tb.num > 0, tb.den > 0 else { continue }. So one failed stream(at:) lookup permanently disarms the park, and every subsequent subtitle packet skips the check. That is exactly "reads straight past dozens of parkable packets," it is a race so it's intermittent, and it needs no allocator pathology at all. Worth auditing the markClosed/close interleavings that take the same accessLock.

    Second candidate, weaker but resolved by the same instrumentation: the release condition pktSeconds <= playheadSnapshot + lead reads playhead() off the synchronizer timebase guarded only by isFinite && >= 0, so a transiently large clock value releases the park.

    A correction on the block count

    The falling block count is real but it is only kill 1, and it is the purge rather than the mechanism. Kills 2 and 3 were caught earlier in the event and their block counts are flat — +457 and −898 — against +1.2 GB and +439 MB. Kill 1's −238,000 arrives alongside vmInt going 300 → 141 → 89 across its tail, which is the app shedding caches under pressure.

    So "very few blocks carrying the bytes" holds, but it comes from kills 2 and 3, not from the fall. Two other things from the full lines, which our earlier excerpts had dropped:

    Kill 1 has a fourth sample. At t=1382 the process was still alive and mallocMB had grown another 446 MB (3642 → 4088) while physFP fell 1112 → 316. Early in each event 40–50% of the new bytes are dirty (+505 MB of +1198, +250 MB of +439); late, almost none. That is capacity outrunning content — the signature of a large-block realloc chain where the copy is vm_copy and only the appended tail dirties pages.

    And vmIOS is 0 with vmExt flat throughout: the explosion is malloc heap only. Pixel buffer and IOSurface pools are out.

    What the census can now settle in one line

    The clean runs turned out to be worth as much as a kill would have been, because they let us attribute the census output. In a healthy software-path session with PGS selected, everything above 1 MB is ingest-path buffering: 4194304 appears 10–11 times and is exactly detourBlockSize at 8 per reader across two readers, and the 8 MB and 16 MB class blocks migrate in antiphase (16MBx1,8MBx2 → 16MBx2,8MBx1 → 8MBx2), which is the two AVIOReader sliding windows breathing between winLowWater and winHighWater.

    That makes the retention locus a single read on the next kill:

    • A window Data under consumer starvation predicts one or two blocks at hundreds of MB to GB with bigBlocks still around 24. The prefetch task runs at .utility while the delegate does not, and your own #174 comment notes the window can overshoot high water by the transport's in-flight amount.
    • CFNetwork-internal accumulation, if the suspend stops being called while the socket keeps reading, predicts thousands of 256 KB–1 MB blocks and a block count up by thousands — mildly disfavoured by the flat counts above.
    • libavformat-internal predicts mixed medium blocks. Long shot; nothing in n8.1 queues unboundedly under AVDISCARD_ALL.

    Instrumentation that would settle it without waiting for luck

    Four fields in the periodic line, alongside your jump trigger:

    • prefetchLead = side-demuxer position minus playhead. This is the live tell — it is visible on the wire minutes before the process dies, and it is the difference between "the prefetcher reads fast" (normal, that is how it builds its lead) and "the lead never settles" (the actual defect).
    • the reader's window.count and persistentTaskSuspended
    • a log line on any timeBaseCache fallback capture
    • framesEnqueued — the software path has no periodic frame gauge at all, which is why three kills were silent

    One kill with those settles the whole thing including the sub-variant.

    Your deinterlacer question, answered from the file

    Not visibly combed, and the graph is right not to configure. We checked the content rather than the screen:

    ffprobe stream:  field_order=tt            (container and SPS declare TFF interlaced)
    ffprobe frames:  interlaced_frame=0        every sampled frame, I/P and B
    

    MediaInfo agrees with the container — MBAFF / InterleavedFields / TFF, and the SEI carries pic_struct=3 — while every decoded frame comes out with equal field POCs and unflagged. The source is PsF: progressive pictures in interlaced carriage. European Blu-ray does this systematically because BD has no 1080p25, so 25 fps content ships as 1080i25. Both tools are right at different layers.

    So SoftwareVideoDecoder never flags a frame, the graph never builds, the frame-size line never emits, and the picture is correct. Nothing to file.

    It does have a consequence for the routing rule, which I'll raise separately rather than fold in here. The #107 field_order rule prices its false positive in its own comment — "a false positive only costs an unnecessary SW decode" — and #220 has repriced that: it now also buys exposure to this. The policy already has a probe hierarchy where a concrete frames-analyzed PROGRESSIVE result wins; extending that to catch equal-POC unflagged frames would route this class native, visually identically, since AVPlayer decodes MBAFF fine and PsF needs no deinterlacing. Not a substitute for the leak fix — genuinely interlaced content with PGS stays exposed either way.

    Four defects found on the way through, worth filing regardless

    1. SoftwareVideoDecoder.decode returns on avcodec_send_packet < 0 without draining — guard sendRet >= 0 else { return } precedes the receive loop. One EAGAIN, which is legal under frame threading whenever the internal output queue fills, wedges video permanently until a seek flushes. Audio keeps playing.
    2. The timebase-cache poisoning above.
    3. The park being edge-triggered on subtitle packets only — subtitle-sparse stretches are read through at full speed by design. Bounded when healthy, but it couples badly with 2.
    4. The prefetcher can die silently and is never restarted. We have a session where it exited cancelled=false harvested=22 mid-playback with nothing bringing it back until a seek; subtitles quietly starve beyond the pump's own park.

    Base rate

    Four runs on the previous census build, all clean: three of five minutes and one of twenty-four to end of media. The long one passed t=1352, the exact sample at which the first kill exploded, with mallocMB 433 → 410 and bigBlocks pinned at 24. Our earlier "kills in about two minutes" framing came from the resume shape only; the cold start had run flat for twenty-two minutes first, so five-minute runs were sampling one shape three times. Everything from here is a long run.

  11. superuser404notfound commented on Jul 27, 2026

    @superuser404notfound
    Owner

    Per-connection byte totals is the measurement this issue was missing. A pump exactly at media rate next to a prefetcher at 2.6x, on the same session, is a discriminator no client-side counter of mine was going to produce, and it also explains the PGS-only conditionality mechanically rather than by correlation: the second reader only exists while a subtitle track is selected. Taking all of it.

    New build

    • Engine: diag/issue-220-malloc-census at dc73c54bde558dc8692d57fffc0e2ae4b8144906
    • Host: diag/issue-220-census-build at 093c0ef2e486fc6795198f81674fb7cd5f5e720b

    It carries the jump-triggered census unchanged plus the four fields, and both fixes below. The census still needs setLargeAllocationCensusEnabled(true), which the host branch already sets; the new fields do not, they are in the periodic line unconditionally.

    prefetch=park prefetchLead=60.2s prefetchHarvested=31 prefetchTbFallback=0
    pumpWinMB=6 pumpAheadMB=5 pumpSusp=0 prefWinMB=2 prefAheadMB=2 prefSusp=0 swFrames=753
    

    That is a healthy local run for reference: the park holding exactly at the allowance, both windows breathing well under the 16 MB high water.

    • prefetchLead is packet PTS minus playhead, sampled at the last routed subtitle packet. prefetch= is off, read, park or dead; dead means the loop exited mid-session, which is its own finding.
    • prefWinMB / prefAheadMB / prefSusp per reader, plus the pump's own as the control. ahead far above the 16 MB high water with Susp=0 is backpressure that never engaged, which is a different defect from a transport overshoot past a suspend that did. That is the discriminator the window hypothesis needs.
    • swFrames closes the gap you named: the software path had no periodic frame gauge, which is why three kills were silent.

    Both defects fixed

    Software decoder drain (c437171). Confirmed exactly as reported. EAGAIN now drains the receive loop and resends the same packet, a real error drops it and logs once, and the drain runs either way since a dropped packet does not invalidate frames the decoder already holds.

    Time-base cache (8335dd9). Confirmed, and worse than the park consequence alone: the cached 0/1 also reached SubtitlePacketStore.harvest, where the rate is num/den, so every harvested cue would land at second 0. Only usable values are cached now, a failed lookup costs one packet and retries on the next.

    One caveat on that as a candidate for your runs, reported against my own fix: if the cache had been poisoned, the subtitles harvested by the prefetcher would all have collapsed to second 0 and been visibly broken, not merely unparked. If your kill runs had working subtitles up to the moment they died, that path was not taken. prefetchTbFallback answers it directly on the next run, and it is a real defect either way.

    The park being edge-triggered on subtitle packets is now #230, the silent exit with no restart is #231, both credited.

    Where I think this still has a gap

    The wire evidence establishes the lead. It does not yet establish the bytes. The prefetch demuxer runs with AVDISCARD_ALL on everything except the subtitle streams, so the excess it pulls passes through the reader window and is discarded rather than retained. Reading 333 s ahead is a defect on its own, but between it and +3.1 GB of live malloc in one 30 s window there is still a step neither of us has named.

    Your own ranking is the right one and the census can now settle it in a line: a window Data under consumer starvation predicts one or two blocks at hundreds of MB with bigBlocks still near 24, and the new prefAheadMB / prefSusp pair says in the same line whether the suspend was ever armed. If that pair comes back at 16 MB and Susp=1 while bigExact still shows a multi-hundred-MB block, the window is exonerated and the retention is somewhere neither hypothesis reaches yet.

    On the PsF finding: please do open that separately. The analysis is right, the picture is correct, the graph is right not to configure, and the #107 field-order rule genuinely is repriced by this issue. Extending the probe hierarchy to catch equal-POC unflagged frames is worth doing on its own merits, and I agree it is not a substitute for whatever is eating the heap.

    Everything from here is a long run, agreed. Thanks for the base rate too; four clean runs including one past t=1352 is exactly the context that keeps the next clean result from being over-read.

  12. 43 remaining items

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