Repository navigation
Description
Context
AetherEngine on iPhone. The engine's background lifecycle was (I'm assuming, could be wrong) shaped by tvOS since that's the first platform for Sodalite (where backgrounding mid-playback is rare and the wedge-safety teardown is exactly right), but on iPhone or iPad the single most common flow is: pause → swipe to Home → answer a text or do something real quick → come back 10–30 seconds later. Today that quick switch pays a full pipeline rebuild, which on a slow single-connection debrid source takes 10–30 s to get back to a ready, correctly-positioned session.
What happens today (device logs, 5.0.3, HEVC MP4 over a single-connection debrid CDN, mediocre Wi-Fi)
didEnterBackgroundwhile paused →teardownVideoForBackground()releases the pipeline immediately (correct per the wedge-safety contract).- On return the host calls
reloadAtCurrentPosition(), which re-pays everything:- demuxer reopen: ~3–6 s to first byte on this source (plus a reconnect)
- segment plan scan (145 IRAPs) + cue prewarm seek
- AVPlayer item re-load →
readyToPlaytook 9–30 s across runs
- Positioning is correct (
initial producer anchored at idx=1 (startPosition=13.01s), host loadstartPos=13.01s) — the cost is purely the rebuild latency. For a 15-second app switch, a 30-second resume is a rough exchange rate, and it happens on every switch.
Proposals (roughly in order of impact)
1. Grace period before the paused-in-background teardown (iOS).
Hold the pipeline under a UIBackgroundTask assertion for a short window (~15 s) before running teardownVideoForBackground(); cancel on didBecomeActive. Wedge-safety is preserved: the assertion keeps the app genuinely running for the whole window, and the teardown runs at expiry (or in the assertion's expiration handler) — the pipeline is never alive across an idle suspension. We prototyped this locally against 5.0.3 (schedule in the .teardownVideo case + the pause-while-backgrounded path, cancel in didBecomeActive, re-evaluate backgroundAction at expiry since PiP/lock-screen-play can change mid-window) and quick app switches become seamless — the host reload never runs because playbackBackend never drops to .none. Happy to send the patch as a PR if the direction sounds right.
2. Warm reload across teardown.
When the teardown does happen, retain the cheap session artifacts keyed by loadedURL + options — segment plan, init.mp4, already-produced SegmentCache bytes, demuxer stream metadata — so reloadAtCurrentPosition() can skip the head scans and re-serve cached segments immediately, leaving only the AVPlayer item rebuild. (Same spirit as the #106 cache-backed stills: the bytes were already paid for once.)
3. Defer host seek(to:) while a load is pre-ready.
A host seek forwarded into the not-yet-ready AVPlayer item clamps to 0 against empty seekable ranges and replaces load()'s own pending startPosition seek. We self-inflicted 0:00-restarts this way from a well-meaning host-side restore watchdog: logs show the producer correctly anchored at idx=1/13.01 s, then a host seek during the pre-ready window → AVPlayer fetched seg0 → out-of-range fetch … restarting producer at idx=0 → re-read from the file head. Queuing host seeks until readiness (then applying the latest) would fix this class of bug for every host.
4. A public readiness signal.
There's currently no public way to know the rebuilt session is seekable/ready — currentTime is pinned at exactly 0 until the item is ready, so hosts end up inferring readiness from that, which is a proxy. A @Published ready flag (or exposing the item's seekable range) would let hosts gate corrective actions properly, and makes proposal 3 verifiable from the host side.
Why this matters
On Apple TV you almost never leave the app mid-episode, so the current lifecycle is fine there (and nothing above touches the tvOS unconditional teardown). On iPhone, backgrounding for a few seconds is constant, and right now every one of those costs a cold rebuild. Proposal 1 alone removes the cost for the common case; 2 softens the long-background case; 3+4 are hardening that would have saved us a multi-day debugging chase.
Logs available on request (happy to re-run repros against a branch).
Activity
superuser404notfound commentedon Jul 16, 2026
Thanks for the writeup, the device logs and the proposal set made this straightforward to act on. All four proposals were validated against the code; three are now implemented on
fix/issue127-ios-background-grace(76bf628), one is deferred. In order:1. Grace window before the paused-background teardown: implemented. Exactly the shape you prototyped, engine-side. New host tunable
backgroundTeardownGraceSeconds(default 15 s, 0 restores the immediate teardown). Both teardown triggers (thedidEnterBackgroundpath and pause-while-backgrounded) route through one pure policy,backgroundStep(action:state:supportsGraceWindow:graceSeconds:). The window is held under aUIBackgroundTaskassertion,didBecomeActivecancels it, and at expiry the background action is re-evaluated before tearing down (your note about PiP / lock-screen play changing mid-window is covered). The assertion's expiration handler is a synchronous backstop that runsstopInternalwithout the socket-drain wait, so even an early reclaim never leaves the pipeline alive across an idle suspension. Two deliberate scope points: a PLAYING teardown (background playback disabled) stays immediate, since its audio would keep sounding through the window, and tvOS keeps the unconditional teardown untouched.3. Pre-ready host seeks: implemented. A host seek arriving while the native item is pre-ready is deferred and the latest one replays at readiness, instead of clamping to 0 against empty seekable ranges and replacing
load()'s own pendingstartPositionseek. That is the 0:00-restart class from your logs. One boundary kept as-is: seeks during.loadingare still ignored (that guard protects against a scrub racing a concurrentstop()/load(), where the seconds would refer to the previous session's timeline). The deferral covers the post-load pre-ready window where the restore-watchdog self-infliction happened.4. Public readiness signal: implemented.
@Published public isSessionReadyon the engine: true once the item hits readyToPlay (SW/audio hosts publish readiness at session start), false across every teardown including the background one. This is the signal to gate restore watchdogs and position clamps on, instead of inferring readiness fromcurrentTimebeing pinned at 0. It also makes 3 verifiable from your side.2. Warm reload across teardown: deferred. With the grace window in place the common quick-switch case never tears down at all, so the warm-reload benefit shrinks to long backgrounds. If those still hurt on your debrid source after 1 lands, it deserves its own issue and we will track it there.
The offer to re-run repros against a branch would be great to take up:
fix/issue127-ios-background-graceis pushed. The interesting cases are the ones from your report: pause, background, return inside 15 s (expect no reload at all,playbackBackendnever drops to.none), return after the window (expect the rebuild, but positioned correctly), and a scrub issued immediately after the post-window return (expect no 0:00 restart). Once it checks out on your rig it goes into the next release.Merge fix/issue127-ios-background-grace: iOS background grace window,…
superuser404notfound commentedon Jul 16, 2026
Shipped in 5.1.0 (merged as 0b9ecef). Device verification on an iPhone 17 Pro came back clean on both sides of the window: return inside 15 s resumes instantly on the live pipeline with no reload, and return after the window pays the rebuild but lands correctly positioned, so this went into a release rather than waiting, testing against the release should now be simpler than the branch anyway.
One host-side note from adopting it in Sodalite, in case your app gates the same way: the foreground-return reload must key on the session actually being torn down (
playbackBackend == .none), not onstate != .playing, otherwise the host reloads right over the live pipeline the grace window just preserved. Sounds like your gate already does exactly this.The re-run of your repros (slow debrid source, the watchdog scrub after a post-window return) would still be very welcome as confirmation, especially for the pre-ready seek deferral and
isSessionReady, which shipped exactly for that setup.dlev02 commentedon Jul 16, 2026
Tested 5.1.0 on-device (iPhone 16 Pro, slow single-connection debrid source). The grace window works really well: pause → background → return inside the window resumes immediately on the live pipeline, no loading screen, no reload at all. Exactly the quick-app-switch behavior we were after.
One tuning note: I bumped
backgroundTeardownGraceSecondsto 25 in the host, which in practice is about the ceiling, since beyond that the background-task assertion gets reclaimed and the expiration teardown decides anyway, as expected.Thanks for the fast turnaround on this. If anything comes up with the post-window rebuild path (or long backgrounds make warm reload worth revisiting), I'll open a follow-up. Closing the loop: this resolves the issue for us.
feat(lifecycle): grace window before paused-background teardown, pre-…
fix(seek): stop dropping seeks during load and against pending author…
fix(demux): keep container chapters across every reopen of the same s…
feat(seek): publish a seek-lifecycle event stream and make the fallin…
fix(hls): sequential archives serve an append playlist with real dura…
fix(subtitles): the background teardown hands its selection to the re…
fix(live): let an in-place recovery keep the place it held
fix(live): a rejoin places the item in its playlist, not 150 ms after…
fix(reload): a refusal is said out loud (superuser404notfound#526)
fix(engine): a second background teardown keeps the selection the fir…
refactor(engine): move the app-lifecycle block into AetherEngine+Back…
fix(engine): one background-decision funnel for every entry point (au…