Repository navigation
Description
What should the engine do?
Let a host replace the request headers of a live session, so the next request the source reader makes carries them, without a teardown. And when a credential has lapsed mid-session, say so: a 401/403 that outlasts the reader's ladder should reach the host as sourceRefused with the status, not as vodSourceFailed / "Source read failed".
Motivating use case
A media server that requires a bearer token on every media request, where access tokens live one hour (the server admin can shorten that). The host holds a refresh token and can mint a new access token in the background at any time, with no user interaction. A two-hour film therefore crosses at least one expiry, and nothing about the film, the session or the byte stream changes at that moment except the value of one header.
Reading main at 210728a, the host has two ways to get a new token onto the wire today, and both rebuild the session:
reloadAtCurrentPosition { $0.httpHeaders["Authorization"] = "Bearer \(fresh)" }(A session-preserving reload that can change one LoadOption (reload(withOptions:) or per-setting setters) #460). This is the right primitive for a correction, and docs/api.md uses exactly this example. For a token rotation it is a full teardown at the playhead to change a value that only the next HTTP request reads. In practice it is a visible pause of a few seconds about once an hour on long titles.- A fresh
load(), which costs the same pause and also loses the subtitle carryover and session state that A session-preserving reload that can change one LoadOption (reload(withOptions:) or per-setting setters) #460 exists to keep.
The reason nothing cheaper exists is that the headers are fixed per reader:
AVIOReader.extraHeadersis alet(AVIOReader.swift:44). Every request the reader builds goes throughheaders(for:)(:1177), so the per-request path is already centralised. Only the value is frozen.HLSVideoEngine.sourceHTTPHeadersis alettoo (HLSVideoEngine.swift:44). The producer's fresh-demuxer reopens (:1261, and the live reopen in HLSVideoEngine+LiveReopen.swift:1072) replay the load-time value even after a host correction, unless that correction went through a rebuild.
What happens today when the token lapses mid-session
Again from reading 210728a, for a progressive HTTP source (MKV/MP4) on the software/loopback path:
- The next range request gets a 401.
persistentReceivedResponsenotes only 429/503/509 withOriginRequestBudget(AVIOReader.swift:3673), so the refusal is never stamped as one. - The ended-connection ladder treats it as an unproductive reconnect: backoff 1, 2, 4, 8, 8 … s, up to
reconnectMaxUnproductive = 12(:675, :2698), each attempt sending the same expired header. Phase is.stalled(reconnecting: true)throughout. That is roughly 80 s with nothing a host can read to learn that the cause is the credential. - The give-up returns -1,
handleVODReadErrorExitfinds no metering stamp, and spendsreadErrorReviveGate's two revives on fresh demuxers. Both reopen with the same headers and are refused again. - The session ends with
surfaceVODSourceFailure(code, "Source read failed"), kindvodSourceFailed. The 401 never reachesPlaybackErrorInfo, althoughsourceRefusedexists for exactly this at open time (A refused source (HTTP 403 on every GET) reaches the host as "Invalid data found when processing input" and disables the tail prefetch for the origin #378).
On the revision we ship (7.36.0, c6365cc) the observed behaviour is a stall that holds .stalled(reconnecting: true) for as long as we let it before reloading. So the host works around it: it renews the token before load when less than 30 minutes remain, and if the reader stalls over an expired token, it reloads in place with the new header.
Proposed API
1. Replace the header set for subsequent requests on a live session.
/// Replaces the HTTP headers the session's source requests carry from the next request on, without a
/// rebuild. Also installed into `loadedOptions.httpHeaders`, so every later reopen (an audio switch,
/// a background return, a revive, `reloadAtCurrentPosition()`) replays it too.
@discardableResult
public func updateRequestHeaders(_ headers: [String: String]) -> RequestHeaderUpdateOutcome
public enum RequestHeaderUpdateOutcome: Sendable, Equatable {
/// The session's readers will send these headers on their next request. A reconnect that is
/// already backing off picks them up on its next attempt, so a stall over a lapsed credential
/// heals without a teardown.
case appliedToLiveRequests
/// The session's requests are owned by something that fixes its headers at load (an
/// AVFoundation-hosted remote HLS item, a custom `IOReader`). The headers are installed for the
/// next rebuild. Call `reloadAtCurrentPosition()` if they are needed now.
case installedForNextRebuild
/// There is no session to update.
case noActiveSession
}Implementation sketch (I am preparing a PR along these lines):
- A small lock-protected reference box (
RequestHeaderStore) that the session creates atloadfromoptions.httpHeaders. AVIOReaderreads its headers from the box when it was given one, soheaders(for:), and with it every request path, the held connection and the redirect policy, sees the current value. The box is passed throughDemuxerOpenProfile, soDemuxer.open's signature doesn't change.HLSVideoEnginereadssourceHTTPHeadersfrom the same box, so its reopens use the current value.RedirectHeaderPolicyscoping is unchanged. The credential still stays off a cross-origin redirect target, because the box only supplies the value that the policy then scopes.- Delegates that capture headers for redirect replay keep capturing per request. A request already in flight finishes with the headers it was sent with.
This is deliberately narrower than #460. It changes one field, doesn't touch routing or the session's identity, and costs nothing. A host could call it every few minutes or on a timer derived from the token's exp, and a viewer would never see it.
2. Make a lapsed credential observable and typed.
Any one of these would let a host stop guessing from .stalled(reconnecting: true). I'm listing them in the order I think they're worth it:
- Stamp 401/403 mid-session the way 429 is stamped, and have the revive arm surface
sourceRefusedwithunderlyingCode= status once its budget is spent, rather thanvodSourceFailed. That keeps the existing kind's meaning ("the origin answered with a status instead of media") for the mid-session case. - Give 401 a short ladder of its own. Retrying an identical request with an identical expired credential twelve times can't succeed. Two attempts, then give up, would surface the typed failure in seconds instead of minutes. With (1) in place, a host that renews on the first 401 heals inside those two attempts.
- Optionally, a host-readable event on the first mid-session 401/403 (for example
sourceAuthorizationRefused: AnyPublisher<Int, Never>), so a host can renew immediately instead of waiting for a phase.
I've left part 2 out of the PR because it changes how the revive arm classifies failures, which is your call to shape. I'm happy to follow up with it in whichever form you prefer.
Area
Public API surface
Host app / integration context
A closed-source iOS/tvOS/macOS media client that plays from self-hosted media servers through AetherEngine (pinned by SHA, currently 7.36.0).
Would you be willing to open a PR?
Yes, for part 1; I will link it here.
Activity
superuser404notfound commentedon Oct 15, 2026
Thanks for the thorough write-up, every reference checks out against current
main(b3edb6b):extraHeadersis aprivate let(AVIOReader.swift:44) withheaders(for:)as the single funnel,persistentReceivedResponseonly notes the rate-limit statuses, so a 401 walks the full unproductive ladder with the same header, then spends bothreadErrorReviveGaterevives and ends asvodSourceFailed.Part 1: yes, please open the PR. The scope is right: one field, no routing or identity change,
RedirectHeaderPolicystill scoping whatever the box supplies. Three places in review I'll look at specifically, because they hold or compare a copy today and would otherwise keep sending the old token:warm.requestHeaders == extraHeaders(AVIOReader.swift:2935). It has to compare against the current value, or a warm connection opened with the old token gets adopted (or a valid one gets discarded for the wrong reason).sourceHTTPHeadersonce (HLSVideoEngine.swift:2846).A test that rotates the header mid-session and asserts the next range request, a fresh-demuxer reopen and a scrub-still fetch all carry the new value would cover the lot.
Part 2: I'll take it, after part 1 lands, since it builds on the box. Shape I have in mind, roughly your first two bullets plus one addition:
sourceRefusedwith the status asunderlyingCode, notvodSourceFailed.sourceAuthorizationRefusedevent as well. It's cheap, and a proactiveexptimer doesn't cover a token revoked early by an admin, where the host otherwise only sees.stalled.I'll link the PR here when it's up.
dlev02 commentedon Oct 15, 2026
Part 1 is up as #793. In a loopback test, the 401 stall this issue describes measured 83 s of reconnect ladder before the read failed. With the PR, the same reader heals on its next attempt once the store holds the renewed token.
feat(engine): replace a live session's request headers without a rebu…
superuser404notfound commentedon Oct 15, 2026
Part 1 merged: #793 (4768000), plus 83aefbf so the session's still extractor follows the store too. Not released yet. Part 2 (typed
sourceRefusedfor a mid-session 401/403, the short ladder, the revision-gated revive and thesourceAuthorizationRefusedevent) is next, in the shape described above.Merge branch 'feat/792-credential-refusal': a refused credential is t…
superuser404notfound commentedon Oct 15, 2026
Released in 7.37.0 (
a3db0d7): part 1 (#793 plus the still-extractor follow-up) and part 2 (4f245b88). A mid-session 401/403 now gets its own ladder of about 3 s instead of about 80 s, the first refusal of a header set is published onsourceAuthorizationRefusedwith the status, a renewal throughupdateRequestHeaders(_:)mid-ladder gives the reader a fresh one, and once the reader has given up the loopback session waits up to 10 s for new headers and rebuilds at the playhead if they come. Otherwise the session ends withsourceRefusedand the status asunderlyingCode; the software path reports the same kind. Details under Rotating a credential without a rebuild.fix(engine): the session's still extractor follows rotated request he…
feat(engine): a credential refused mid-session is typed, short, and h…
test: three suites stop asserting on a wall clock or the kernel's mercy
Merge upstream AetherEngine 7.38.1 (fc6b412) into the Silo fork