Skip to content

iOS: quick app switches pay a full pipeline rebuild — grace period before paused-background teardown, warm reload, deferred pre-ready seeks, public readiness signal #127

Closed

Description

@dlev02

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)

  1. didEnterBackground while paused → teardownVideoForBackground() releases the pipeline immediately (correct per the wedge-safety contract).
  2. 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 → readyToPlay took 9–30 s across runs
  3. Positioning is correct (initial producer anchored at idx=1 (startPosition=13.01s), host load startPos=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

  1. superuser404notfound commented on Jul 16, 2026

    @superuser404notfound
    Owner

    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 (the didEnterBackground path and pause-while-backgrounded) route through one pure policy, backgroundStep(action:state:supportsGraceWindow:graceSeconds:). The window is held under a UIBackgroundTask assertion, didBecomeActive cancels 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 runs stopInternal without 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 pending startPosition seek. That is the 0:00-restart class from your logs. One boundary kept as-is: seeks during .loading are still ignored (that guard protects against a scrub racing a concurrent stop()/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 isSessionReady on 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 from currentTime being 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-grace is pushed. The interesting cases are the ones from your report: pause, background, return inside 15 s (expect no reload at all, playbackBackend never 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.

  2. superuser404notfound commented on Jul 16, 2026

    @superuser404notfound
    Owner

    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 on state != .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.

  3. dlev02 commented on Jul 16, 2026

    @dlev02
    ContributorAuthor

    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 backgroundTeardownGraceSeconds to 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.

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