Skip to content

Player consolidation + architecture remediation (rounds 1–2b), brand migration, cleanup tail, DRY/KISS/YAGNI round 5, and playback telemetry/runway unification - #172

Closed
Quick104 wants to merge 305 commits into
mainfrom
player/architecture-remediation
Closed

Quick104 wants to merge 305 commits into
mainfrom
player/architecture-remediation

Conversation

@Quick104

@Quick104 Quick104 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Player architecture remediation + streamlining (single PR)

player/architecture-remediation -> main. This branch consolidates the Apple clients onto a single AVPlayer-backed player and rebuilds the playback control plane behind it.

What this program did

The old player was a hybrid of an FFmpeg/VideoToolbox decode core (PlayerCore/CompatibilityPlayer) and an AVPlayer stack. PlayerCore is gone. Every route is now AVPlayer pointed at one of three things: the native asset (native-direct), the on-device loopback (a 127.0.0.1 fMP4-HLS remux written by LoopbackSegmentWriter), or server HLS. Rounds 1-4 were the consolidation and point fixes; rounds 5-6 were two DRY/KISS/YAGNI survey-and-fix sweeps over the tail.

An independent architecture review drove remediation R1 and R2: 14 of its 16 ranked defects fixed with characterization tests, a typed PlaybackFailure channel in place of the string classifiers, AVPlayer injected so the backend is testable, V3 conformance fixtures re-vendored from the server, the silo:// scheme replacing the pre-rename one, and the dormant on-device video-bridge tier plus .passthroughAV1 retired because nothing could route to them.

The brand migration (R2b) moved every persisted, OS-registered, on-disk, and wire continuum literal to silo behind one-time migrations. Pre-rename Keychain and registry entries are copied forward and then kept, so a TestFlight rollback still finds its tokens; the old brand survives only as read-only LegacyBrandKeys.

On the server side, the client advertises client_audio_track_selection_v1 on original_http, routes non-default audio through loopback, and reports progressive as unsupported on device. That was coordinated with silo-server PR #670 (merged).

Stage 2 was the control-plane extraction, shipped as a hard cutover with no runtime flag, one wave at a time, each merged after an independent review pass:

  • Wave 1 built the seams, types, and policies: the PlaybackBackend protocol and its fake, PlaybackReducer and the state types, one RecoveryPolicy with table tests, the TrackSelectionCoordinator extraction, and transport injection into the bridge.
  • Wave 2a pulled the loopback lifecycle (segment store, HTTP server, the producing writer with demand-driven restarts, session directory) into LocalHLSHost as one value.
  • Wave 2b introduced PlaybackEngineSession per load and settled recovery ownership: the in-route ladders now emit RecoveryObservations, RecoveryDriver is the only runtime caller of RecoveryPolicy.decide, and the old recovery handshake is deleted.
  • Wave 3 was the reducer and actor cutover. PlaybackSessionActor holds PlaybackState and is the only caller of the pure PlaybackReducer; every effect is conditional on the LoadID/SessionIdentity it carries; the by-value generation counters are gone.
  • Wave 4 replaced the eight pending* fields with the TrackSelection model, deleted the legacy view-model control core and its ladders, and truth-passed docs/tvos-player/ to the shipped ownership.

Where the code landed

PlaybackSessionActor runs the pure PlaybackReducer; PlayerViewModel is now only the presentation shell and decides no playback policy. PlaybackEngineSession owns the backend adapter, the source proxy, and that load's RecoveryDriver, keyed by LoadID, and dropping it is the teardown. LocalHLSHost owns the loopback lifecycle, and the backend holds exactly one live host. RecoveryPolicy is the single place a recovery decision is made — every rung, the failure ladder, origin-outage ride-through, and the server-outage wait — with RecoveryDriver as its only runtime caller. TrackSelectionCoordinator owns the audio and subtitle half, which leaves AVPlayerBackend as a plain AVFoundation adapter and the only backend.

An in-place replan reuses the live AVPlayerBackend, keeping the audio session and the negotiated tvOS display criteria, so a route or track switch does not renegotiate HDMI. The fallback ladder runs native-direct -> loopback -> server HLS replan, each rung gated by a load-scoped one-shot latch on the recovery context. A mid-stream server restart is ridden out by silent session renewal; an origin outage is covered by the buffered runway under a health-probe backoff.

The as-built player story is in docs/tvos-player/: 01 for the overview, 03 for Dolby Vision, 05 for the route/capability matrix, 09 for the retired video bridge, and 10 for playback continuity.

Late fix: mid-title resume on the loopback route

Resuming a 4K Dolby Vision P7 / DTS title mid-film on the Living Room Apple TV failed every time ("cannot be tone mapped"), then replanned DV -> HDR10 and failed again, while start-from-beginning played fine. Root cause (fb1e1a2): with progressive anchor serving, the ~1.5 s interim flushes can drain every sample of the anchor segment out of the muxer before the plan boundary. The cut's flush then emits nothing, the box sink never sees the mdat that finalizes the closing segment, and the next segment's fragments are appended and stored under the next index — so the segment AVPlayer's resume fetch needs is never produced. performVODFragmentCut now finalizes the already-drained progressive buffer as the closing segment. Verified on device: the anchor segment is stored with the correct tfdt and playback starts on the first DV attempt.

Verification

The iOS SiloTests suite is green at the tip: 1811 executed, 3 skipped, 0 failures. The 3 skips are keychain-migration tests the unsigned simulator host cannot write. The suite carried ~14 "environment" failures earlier in the program; those were root-caused and fixed, so any failure now is a regression.

Silo (iOS), SiloTV (tvOS), and SiloMac (macOS) all build without signing.

Device runs on real Apple TV hardware are recorded under docs/tvos-player/validations/*.yaml: HDR10 loopback with display criteria, Dolby Vision P8.1 passthrough and P7->8.1 conversion with TrueHD->FLAC, seek-heavy reanchor, a frame-exact suspend/resume, and a production origin outage absorbed by the runway.

Docs hygiene

The program's working state — session handoff, cleanup backlog, the architecture review and its slices, the Stage 2 design, inventories, per-wave specs, and the mirrored workflow scripts — lived under docs/cleanup/ and is removed in this branch, per the docs-hygiene policy that keeps ephemeral working artifacts out of the tree. Anything durable was moved into the whitelisted docs/tvos-player/ docs first, and this description carries the narrative the handoff used to.

AI-use disclosure

An AI coding agent (Claude) did most of the work on this branch under the maintainer's direction: it ran the survey, fix, and remediation workflows, wrote and reviewed the code across the waves, and drafted the docs and this description. Each wave went through an independent AI review pass, the characterization-test suite, and on-device validation on real Apple TV hardware before the maintainer accepted it. This follows the disclosure standard in the silo-server docs/ai-contributions.md.

Late fix: signed playback authorization lifetime

AVPlayer freezes asset HTTP headers, so a one-hour account access token could expire underneath an otherwise-valid signed playback URL and stop long titles near the end. The Apple client now treats a non-empty st query token as the playback credential, omits the shorter-lived account bearer for that asset, and truthfully reports auth_header_refresh: false. Unsigned legacy URLs keep the account-header path.

Deployment ordering is required: the coordinated silo-server byte-delivery middleware must validate the signed st token before ordinary account authentication. Deploy that server change before distributing an Apple build from this branch; current servers still require the account bearer before they consider the stream token.

Regression coverage pins signed, unsigned, and local-file URL behavior plus the V3 capability claim. At this head, the full iOS suite executes 1,878 tests with 0 failures and the expected 3 Keychain skips; unsigned iOS, tvOS, and macOS builds all succeed.

AI-use update: Codex implemented and validated this bounded late fix under maintainer direction, and Fable performed an independent adversarial security and compatibility review before publication.

Quick104 and others added 30 commits August 17, 2026 14:00
…) and the brand-key migration decision

Lists the 29 persisted / OS-registered / on-disk / wire 'continuum' literals
that were deliberately kept, grouped by what a migration would need.

Co-Authored-By: Claude Fable 5 <[email protected]>
…vidence

Independent read-only review of the Apple playback pipeline at 36393b4:
executive verdict, ownership map, 16 ranked defects, rewrite options A-D,
target control-plane architecture, staged migration, product decisions,
and the condensed per-slice evidence files it was synthesized from.

Co-Authored-By: Claude Fable 5 <[email protected]>
…source index

Review §3 #11 (slice5-tracks.md, Identity item (1)).

`PlayerTrack.srcId` means different things per track partition: for a
sidecar row it is the server's combined subtitle index
(`subtitle_urls[].index`), but for an FFmpeg-extracted embedded row it is
the FFmpeg stream index. `SubtitleTranslateMenu.translatableSubtitleTracks`
admitted any non-bitmap track with a non-nil `srcId`, and
`SubtitleAIController.translateExisting` sent that `srcId` as the job's
combined `source_index` — so translating an embedded track submitted the
wrong index space (correct only by coincidence). The doc comments in both
files claimed embedded tracks were already excluded; they were not.

The combined-index rule now lives in one place,
`SubtitleAIController.translationSourceIndex(for:)`: sidecar rows pass
`srcId` through, everything else (embedded, AI-live, AVFoundation) is
refused. Converting an embedded FFmpeg stream index would need the
version's subtitle inventory via
`ApplePlaybackV3PlanAdapter.serverCombinedSubtitleIndex(ffmpegStreamIndex:in:)`,
which is not reachable without plumbing a provider through
`PlayerViewModel` (owned by another package) — so embedded tracks are
excluded, matching what the doc comments already claimed.

Behavior changes (iOS, tvOS): an FFmpeg-extracted embedded text track is no
longer offered as an AI-translation source; such files fall back to
transcription (or the AI entry row hides when transcription is
unavailable/quota-less). Sidecar/downloaded tracks are unchanged. macOS
compiles the menu but never presents it, so no user-visible change there.

Tests: 4 new cases in SubtitleAIControllerTests pinning the index-space rule
(sidecar passes its combined index through and stays in the translatable
set; embedded is excluded and refused by the controller guard). No existing
test pinned the defective behavior.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review rows §3 #3 (backend half) and #15, plus the stale comment at
AVPlayerBackend.swift:3632.

#3-backend: generalize the two-rung outage suppression into a
reason-keyed recovery-suspension latch (setRecoverySuspended(_:reason:),
setExternalStallSuppression kept as the origin-outage wrapper). All the
in-route ladders now take no action while any owner holds it: playhead
watchdog tick, item-death evidence, recoverLocalLoopbackStallIfNeeded,
resumeLocalLoopbackPlaybackIfNeeded, startup escalation. The watchdog
keeps observing and logging (`suspended=[...]` in the periodic state
line, replacing the two [CMP-OUTAGE] suppression lines).

#15-B8-1: recovery seeks in performVODStallRecovery and
reloadEstablishedLoopbackItem now run through beginSeekDeadline and mark
isSeekPending, with a new .recovery deadline kind whose responder only
releases the watchdog (the issuing rung owns escalation and its budget).
The startup nudge is deliberately left fire-and-forget.

#15-B8-2: resumeLocalLoopbackPlaybackIfNeeded no longer reissues play()
after AVPlayerItemDidPlayToEndTime.

#15-B8-4: hasReachedItemEnd is cleared when a fresh item is attached in
reloadEstablishedLoopbackItem and reloadLoopbackStartupItem.

#15-B8-3: full loopback session rebuilds are bounded per load by
LoopbackRebuildBudget (2); once spent the backend reports
loopback_rebuild_budget_exhausted so the view-model ladder decides.

#15-B8-5: isPreservingTVDisplayCriteriaForReload is cleared in
teardownMediaPipeline so a session whose writer never reported a first
segment cannot suppress the next load's tvOS display settle wait.

Tests: LoopbackRebuildBudget unit tests in
LoopbackStartupRecoveryPolicyTests.

iOS/tvOS/macOS build; iOS suite 1349 tests / 14 failures = baseline.
…delivery

Review finding #13 (docs/cleanup/player-review/2026-08-17-architecture-review.md
§3 row 13; slices/slice4-v3.md claim C3).

The V3 capability snapshot handed the `original_http` delivery the full flat
decode vocabulary, so a device build claimed h264/hevc in `webm` and `avi`. The
server can only read that as "hand this client the original file", but an
original delivery is executed natively or by the local loopback in copy mode,
and the copy tier refuses both containers (`siloContainerIsNormalizable`) — the
bridge tier that opens them is unreachable on an online plan. The player's only
answer was `needsServerReplanBeforeLoad`: abort the granted plan and ask again.

The delivery now advertises the flat vocabulary filtered to what the planner can
execute — native-direct ∪ silo source ∪ bare audio containers — derived from the
planner's own lists rather than restated literals. The top-level decode
attestation is unchanged: it is a "this stack can open it" claim, and it also
feeds the bootstrap and download surfaces.

Behavior changes
- iOS/tvOS/macOS device builds: `original_http` no longer advertises `webm` or
  `avi`. The server plans a remux/transcode for those sources directly instead
  of granting an original the client then aborts.
- Simulator (all platforms): no change to the advertised set; the simulator
  vocabulary never contained `webm`/`avi`.
- Audiobook snapshot: unchanged (it has always narrowed its own list).

Adds `testOriginalHTTPAdvertisesOnlyContainersThePlannerCanExecute`. Makes
`ApplePlaybackRoutePlanner.nativeDirectContainers` and `siloSourceContainers`
internal so the snapshot and the test can reference them.
…borate near-end EOF

Point fixes from the 2026-08-17 playback architecture review (§3).

#1 (HIGH) loadStream re-applies applyCallbacks/wireSubtitleCallbacks/
setServerChapters on the backend it just acquired. The handlers capture
streamLoadGeneration by value, so the prepareBackend reuse path (every
same-engine V3 replan) kept the closures of the generation the load had
just invalidated and discarded every event from the replacement stream —
isLoading latched, tracks never applied, errors and EOF swallowed.
Restores the pre-e458784 wiring.

#2 (HIGH) shouldTreatPlaybackErrorAsNaturalEnd was the exact negation of
handleEndOfFile's premature check, so a mid-stream failure at >=98.5%
(or <=8 s remaining) marked the title completed and autoplayed Next Up,
pre-empting V3 replan, session renewal and outage recovery. The ratio arm
is gone and the conversion is now corroborated: no source outage and
<=1 s of buffered runway. Uncorroborated failures fall through to the
normal recovery ladder.

#5 (MED, tvOS) PlaybackSessionBridge.stopSession clears its identity only
when the stopped session is still the current one; the tvOS background
suspend stop is registered in PlayerTaskRegistry (new scope-less key)
instead of being an unstructured Task.

#9 (MED, latent) LoopbackSessionSpec.withSource(url:headers:) replaces the
hand-rebuilt spec in prepareSourceProxy, which dropped videoOutputMode,
the source dimensions and the bridged parameter sets.

#14 (MED) applySiloControlCommand ignores seek/audio/subtitle/quality
commands while a load is in flight, matching the realtime path's guard.

#10 skipped: the index space of pendingAudioFfIndex cannot be reconciled
with AVFoundation media-selection ordinals from the code alone (see notes).

Behavior changes: near-end playback errors during a source outage or with
buffered media ahead now enter the recovery ladder instead of the end
screen + autoplay (all platforms); LAN remote track/quality/seek commands
are ignored while loading (all platforms); a superseded stopSession no
longer clears bridge identity or nudges Top Shelf (tvOS).

Co-Authored-By: Claude Fable 5 <[email protected]>
handleSeekDeadline cancelled pending seeks for every kind, so a
`.recovery` seek issued right after replaceCurrentItem (item-death
reload, vod_stall attempt >= 2, AirPlay handoff reload) was discarded
if the fresh item took longer than the 15 s deadline to become ready —
exactly the poisoned-loader / receiver-side-fetch situations those
paths fire in. The item then started at zero, the playhead watchdog
saw an advancing clock and called the route healthy, and the user
silently lost their position.

Clear isSeekPending for every kind as before (that is the watchdog
un-mute), but only cancel the queued seek for the interactive and
initial kinds.

Co-Authored-By: Claude Fable 5 <[email protected]>
…fixes

Remediation package R1-loopback (architecture review 2026-08-17, §3 rows
#4, #6, #7, #8, #16).

#4 Untrusted-keyframe VOD plans refused for remuxed sessions.
LoopbackSegmentPlan's uniform-stride fallback fences segments at fixed
multiples of the target duration. LoopbackSegmentCutter only opens a
segment at a keyframe, so a remuxed (.copy / .passthroughAV1) session
never produces some advertised indices, and the VOD playlist
(0..<segmentCount + ENDLIST) cannot heal the hole. The new
LoopbackSegmentWriter.shouldServeVODPlan gate refuses such a plan before
onSegmentPlanResolved fires — so restarted producers can never receive
one — and the session degrades to the existing plan-less EVENT path.
Bridged sessions keep serving uniform plans (they force encoder
keyframes onto every fence).

#6 moof-before-moov no longer latches initSegmentWritten. When the muxer
emits media with no moov ever captured, init.mp4 does not exist and never
will; publishing a playlist advertised an EXT-X-MAP that 404s forever.
The arm now latches the new LoopbackWriterError.initSegmentMissing into
fatalIOError so the mux loop rethrows and the backend/VM route ladder
takes over.

#7 Open progressive segment memory. LoopbackSegmentStoreStats gains
progressiveBytes so resident memory is no longer understated (the bytes
stay out of memoryBytes because they are not eviction candidates). The
writer gains a hard ceiling (96 MiB, 32 MiB on the constrained tvOS tier)
past which it stops mirroring the open segment into the store; the
segment still cuts at its next keyframe boundary and lands whole.

#8 AVIO buffer leak. teardown() now frees the AVIOContext's *current*
buffer with av_freep before avio_context_free (libavformat may have
replaced the one we allocated), and the wrong comment is gone. The
ioBuffer stored property is demoted to a local in openOutput; the
alloc-failure arm still frees exactly once.

#16 FFmpeg send-EAGAIN drops are counted at all five reachable send
sites (bridge decoder/encoder, writer audio decoder and both audio
encoder paths) via a throttled noteSendEagainDrop, and the false comment
at LoopbackVideoBridge ("retried by the caller's next read") is
corrected. Drain-loop receive-error exits keep returning — a persistent
non-EAGAIN receive code would spin under `continue` — with that reason
recorded in comments.

Behavior changes (iOS, tvOS, macOS alike):
- Loopback sessions on sources with an untrustworthy keyframe index now
  serve a growing EVENT playlist instead of a static VOD playlist.
- A moof-before-moov session fails instead of publishing a broken
  presentation.
- Progressive anchor streaming stops after the ceiling; affected seeks
  wait for the cut, as with progressive serving disabled.
- New progressiveBytes field in LoopbackSegmentStoreStats.
- New diagnostic log lines only for #16.

Tests: LoopbackSegmentPlanTests gains three shouldServeVODPlan cases;
LoopbackSegmentStoreTests gains progressive-byte accounting.
Adds the Stage-0 characterization suite the architecture review
(docs/cleanup/player-review/2026-08-17-architecture-review.md §9, §11;
slices/slice6-tests.md "Migration") identified as writable at this base.
Tests only — no production file is touched, and no behavior changes on
iOS, tvOS or macOS.

Finding: tests-stage0 (zero composed lifecycle tests; 15 contract tests
writable today).

New files, all under iosApp/Tests/:
- PlaybackV3ExecutionPlanMatrixTests: V3 decision -> executable plan per
  delivery (engine, streamRequest, startMode, trace, validation gate),
  built by mutating the vendored decision_response.json fixture.
- ApplePlaybackDecisionTraceSnapshotTests: full decisionTrace arrays for
  13 canonical planner inputs, plus the loopback-session presence rule
  and the needsServerReplanBeforeLoad engine x delivery truth table.
  Device facts are injected so the snapshot is host-independent.
- PlayerErrorClassificationMatrixTests: ~30 messages each through
  protocolV3FailureClassification and stablePlaybackFailureToken, their
  rung-order quirks, and the cases where the two disagree.
- PlaybackSessionBridgeReplanContractTests: replanOperation totality,
  canRetargetDirectSession tolerated-vs-refused field matrix,
  isMaterialOutputRouteChange.
- OfflinePlaybackMappingMatrixTests: multi-audio downloads and
  sidecar-only subtitles through the shared planner.
- PlaybackV3FixtureRoundTripTests: every vendored V3 fixture parses;
  the modelled ones survive decode -> encode -> decode.
- LoopbackSegmentPlanTrustTests: the forceUniformStride override.
- LoopbackSessionSpecCopyHelperTests: reanchored(at:) and
  carryingBridgedVideoParameterSets preserve every other field.

Where current behavior is a listed defect it is marked "PIN:" and left
alone; the near-end EOF classifier is deliberately not pinned here.

Behavior changes: none (iOS, tvOS, macOS).

Co-Authored-By: Claude Fable 5 <[email protected]>
Wire PlayerViewModel.attemptProtocolV3Replan to the backend's reason-keyed
recovery-suspension latch (AVPlayerBackend.setRecoverySuspended, reason
server_replan) for the whole replan round trip, released in the task's
defer on the same backend instance. Closes the VM half of review §3 #3:
the six in-route ladders can no longer reanchor/reload/rebuild while the
view model is negotiating a different route with the server.

Round 1 integration on player/architecture-remediation: Silo, SiloTV,
SiloMac build; iOS suite Executed 1419 tests, 14 failures (0 unexpected)
= documented baseline environment failures.

Co-Authored-By: Claude Fable 5 <[email protected]>
…pback + display criteria pass; DV blocked by server plan)

Two records from the Round-1 build on the Apple TV 4K (3rd gen):
- HDR10 HEVC MKV titles at 24.000 and 29.970 fps take siloPlayerLoopback,
  trusted VOD plans, tvOS display criteria applied (PQ, per-title fps),
  first frame ~4.5 s, no errors/recovery.
- Dolby Vision P5/P8 MKVs never receive a DV plan: production plans
  server_remux_progressive (container_normalization) which AVPlayer cannot
  play (-12939), then HLS strips DV; identical on the pre-Round-1 build;
  shared dev returns adaptation_unavailable for the same request shape.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ecision with correct delivery keys; handed to silo-server
Review §4 item 4 / §9 stage 1: `String` was the only failure channel out of
`AVPlayerBackend` (`onError: (String) -> Void`) and `PlayerViewModel` re-derived
four separate decisions from that string with unanchored substring matches.

- New `PlaybackFailure` enum: one case per failure the backend actually reports
  (item failure, loopback server bind, playlist URL, rebuild-budget exhaustion,
  three startup-ladder rungs, writer failure with a typed kind) plus `.unknown`
  for callers that only ever had text.
- `AVPlayerBackend.onError` and `PlayerCallbacks.onError` are now typed;
  `reportError(_:)` became `reportFailure(_:)` and keeps the same log line.
- `LoopbackWriterError` is triaged by an exhaustive switch at the reporting
  site instead of being re-read out of its own description downstream.
- The four `PlayerViewModel` classifiers (`protocolV3FailureClassification`,
  `stablePlaybackFailureToken`, `isPlaybackSessionMissingMessage`,
  `isPrematureSourceEndMessage`) are retired from the view model; the ladders
  themselves move verbatim onto `PlaybackFailure` and run over
  `legacyMessage`, which reproduces the pre-migration string byte-for-byte.
  Wire classification, replan `message`, diagnostics token and user-visible
  error text are therefore unchanged.
- `AVPlayerBackend.init(player:)` injects the `AVPlayer` (default `AVPlayer()`).

Findings: §4-4, §9-S1-avplayer.
Behavior changes: none intended on iOS, tvOS or macOS.

Tests: PlayerErrorClassifierPinTests and PlayerErrorClassificationMatrixTests
retargeted at `PlaybackFailure`; the matrix file gains the old view-model
implementations as copied-in oracles plus a byte-for-byte `legacyMessage` table,
so every typed case is proven to classify exactly as before.
Finding scheme-silo (review §2.6 URL-scheme row): the app's only custom
URL scheme was `continuum`, brand residue from before the Silo rename.
Android already registers `silo` exclusively.

Register `silo` as a second CFBundleURLSchemes entry on iOS and tvOS,
keep `continuum` registered and accepted for a deprecation window, and
emit `silo://` from every deep-link builder in this repo.

New `SiloDeepLink` (iosApp/iosApp/Shared/) holds the accepted-scheme set
and the preferred scheme; it lives under Shared/ so the Top Shelf
extension target compiles it too.

Behavior changes:
- iOS: `silo://item|play|downloads` now opens the app; download
  notifications carry `silo://downloads`; push display URLs are built as
  `silo://<route>/<id>`. `continuum://` still routes identically.
- tvOS: `silo://` registered; Top Shelf display/play actions emit
  `silo://item/` and `silo://play/`. `continuum://` still routes.
- macOS: none (registers no URL scheme at all; no CFBundleURLTypes).

Tests: new SiloDeepLinkTests pins accept-both/case-insensitive/reject;
ApplePushRegistrationTests updated to pin the new silo:// builder output
plus a continuum:// pass-through case.
Review row #12 / slice4 claim C1: Apple's vendored Protocol V3 fixtures had
drifted from silo-server main, and Apple had no `output_change` replan
operation even though the server has carried one since output_change_v1.

- Re-vendor all nine fixtures byte-for-byte from silo-server
  internal/playback/testdata/protocol_v3 @ 5fdb5d73acc9529837cac90d253e9e3bfc0055bb
  (shasum-verified against the server copies) and rewrite SOURCE with the
  exact commit, path and date. Drift closed: capability/decision
  server_features gain output_change_v1, decision stream.header_refresh
  becomes "none", and the conformance matrix gains the 10th replan scenario
  (category output_change_replan).
- Add PlaybackProtocolV3.outputChangeFeature and
  ReplanOperation.outputChange.
- replanOperation(forClassification:serverFeatures:) returns .outputChange
  for "output_route_changed" only when the active plan's serverFeatures
  advertise output_change_v1, mirroring the seek_reanchor gating. Old
  servers keep the failure_recovery + classification shape.
- replanFailure returns nil for .outputChange (the server rejects a failure
  body on output_change, protocol_v3.go:848-852). The local intent
  emulation (attemptedPlanKeys reset, attemptCount 1, plan_invalidated) is
  unchanged: it keys on the classification, not the operation.

Tests: conformance count 9 -> 10 plus the new category and a vector pin;
gating and replanFailure pins; a decode sweep over every fixture with a
production model; and a pin for the replan fixture's omitted
local_mutations. Two existing pins updated for the re-vendored goldens
(header_refresh mutation value, stale "no output_change yet" comment).

iOS 1424 tests / 14 failures = baseline 1419 + 5 new, same 14 environment
failures. iOS, tvOS and macOS all build.

Co-Authored-By: Claude Fable 5 <[email protected]>
…throughAV1

Finding S3.1-bridge (review §3 row 13, §7 Option B, §9 Stage 3.1, §12;
slice3 §B/§F(i), slice4 C3, slice7 T7/C-2). Product decision P4 = delete.

Dormancy re-verified at this base:
- online: ApplePlaybackV3Capabilities advertises only the two codecs in
  AppleDecodeCapabilities.videoCodecs (h264/hevc) in both the flat list and
  the per-codec decode attestation, and silo-server videoEligibleV3
  (capabilities_v3.go) fails closed on anything else, so no original_http
  plan could ever name a bridge codec;
- offline: DownloadCaps.current() reports the same two codecs
  (DownloadModels.swift:219-227), so no bridgeable artifact can be downloaded.

Deleted: LoopbackVideoBridge.swift; the planner's bridge container/codec
allowlists, 1080p cap, AppleVideoBridgeCapabilities probe and the
dv_not_bridgeable / video_not_bridgeable / video_hdr_bridge_unsupported /
video_bridge_resolution_unsupported blockers; VideoOutputMode
.transcodeHEVC/.transcodeH264/.passthroughAV1; every writer isBridged branch,
the bridge setup/prime/transcode/finish block, the AV1 RFC 6381 codec-string
builder, LoopbackSegmentPlan.forceUniformStride, and the videoTranscodeSetup /
videoBridgeTooSlow errors. -1378 product lines, -815 test lines.

Behavior changes (iOS/tvOS/macOS alike; none reachable on a live plan):
- a non-h264/hevc video codec now blocks the silo route with the single token
  video_not_copyable (was one of four bridge tokens) and falls to server HLS;
- webm/avi/wmv/... containers are no longer normalizable at all;
- the "Video is re-encoded on this device" degradation warning is never emitted.

Scoped SKIPS (recorded, evidence held at this base):
- LoopbackBridgedDriftGovernor and seedVODBridgedAudioPTSIfNeeded /
  noteBridgedAudioDriftIfNeeded are the AUDIO-transcode clock, reached from
  sendConvertedFrameToEncoder under selectedAudioOutputMode != .copy — live for
  TrueHD/DTS -> FLAC, which Option B keeps. Kept, with their tests.
- SoftwareVideoOutputFormatTests covers VideoColorMetadata.sourceBitDepth in
  Shared/, also used by Downloads/LocalMediaProbe.swift. Kept.
- Fixtures v3_vp9_opus.webm / v3_mpeg4_mp3.avi are still used by
  PlaybackMediaFixtureTests' FFmpeg demux attestation. Kept.

Left dormant on purpose (AVPlayerBackend.swift is owned by another package this
round): LoopbackSessionSpec.videoOutputMode (now single-valued),
sourceVideoWidth/Height, bridgedVideoParameterSets,
carryingBridgedVideoParameterSets and the writer's
onBridgedVideoParameterSetsResolved property. Each is commented DORMANT with a
pointer to the backend block that should be removed with them.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ridge tier

R2-typed-failure mapped LoopbackWriterError.videoBridgeTooSlow /
.videoTranscodeSetup into PlaybackFailure.WriterFailureKind; R2-bridge-delete
removed those writer cases. Drop the mapping arms and the now-meaningless
WriterFailureKind.videoBridgeTooSlow (+ its matrix-test row).

Round 2 integration on player/architecture-remediation: Silo, SiloTV,
SiloMac build; iOS suite Executed 1407 tests, 14 failures (0 unexpected)
= documented baseline environment failures.

Co-Authored-By: Claude Fable 5 <[email protected]>
…one-time migrations

Backlog §2.6 rows, all migrated rather than renamed:
- Keychain: service com.continuum.app -> org.siloserver.silo; every account
  prefix com.continuum. -> org.siloserver.silo. (per-server tokens, Top Shelf
  mirrors, server registry v2, device identity, hosted diagnostics ids).
  SharedKeychain migrates on read-miss (copy -> new, delete old only after
  the write confirms; delete() also purges the legacy copy). The legacy
  service is injectable (tests) and defaults to the pre-rename service only
  for the real shared service.
- UserDefaults: continuumServerRegistry.{v1,migrated.v1} ->
  siloServerRegistry.* with one-shot copy+remove.
- OS ids: BGTask org.siloserver.silo.downloads-refresh (plist + code; old
  pending request cancelled), background URLSession
  org.siloserver.silo.downloads (pre-rename session invalidated once).
- URL scheme: continuum removed from both plists and SiloDeepLink; silo only.
  Live Activity / push coordinator / tests updated.
- Disk: silo-source-cache, silo-dv-hls, silo-dv-hls-debug,
  org.siloserver.silo.posters; old dirs/caches deleted once.
- Wire: realtime client names silo-{ios,tvos,macos}.
- Prose reworded; LegacyBrandKeys is the single read-only list of migration
  sources and the only place the old brand remains.

Verification: Silo, SiloTV, SiloMac build; iOS suite Executed 1414 tests,
3 skipped (keychain unwritable in this simulator host), 14 failures =
documented baseline environment set.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t audio to loopback; drop progressive delivery

Root cause of 'Dolby Vision MKVs never get original_http' (bedroom Apple TV
2026-08-17, prod + dev): the profile's audio preference selected a non-default
track and the server's direct branch requires the container default. The
server now accepts a non-default selection when the original_http delivery
advertises client_audio_track_selection_v1 (silo-server bc52478e). Apple:

- ApplePlaybackV3Capabilities: original_http features += client_audio_track_selection_v1.
- ApplePlaybackRoutePlanner: native-direct AVPlayer cannot apply a catalog
  audio index, so a plan selecting a non-default track blocks native-direct
  (audio_selection_requires_loopback) and the loopback — whose writer maps
  exactly the selected track — takes the route; the silo route accepts that
  blocker as a normalization need. Makes the advertisement truthful.
- progressive delivery: supportedOnDevice=false
  (avplayer_requires_seekable_source). The server's progressive remux is a
  live fMP4 pipe without byte-range support; AVPlayer fails it every time
  (-11850/-12939), so the planner now falls straight to HLS remux.
- Tests: ApplePlaybackAudioSelectionRouteTests (5).

Silo, SiloTV, SiloMac build; iOS suite 1419 tests / 14 baseline env
failures / 3 skipped.

Co-Authored-By: Claude Fable 5 <[email protected]>
Quick104 and others added 25 commits August 20, 2026 23:33
…e ones

Finding addressed: source-proxy/12 (source-proxy/206).

`resolveRequest` passed `.exact(start...end)` through verbatim while every
other range kind derived its end from the known total. `respondGet` framed
`Content-Range`/`Content-Length` from that unclamped end while the serve loop
stopped independently at EOF, so `bytes=0-999999` on a 1000-byte source
promised 1,000,000 bytes and sent 1,000, and `bytes=5000-6000` (or `5000-`)
answered 206 with a non-zero `Content-Length` over an empty body.

- `resolveRequest` now clamps an exact range's end to `total - 1` when the
  total is known; unknown totals still pass through verbatim so the RFC 9110
  `/*` unknown-complete-length form keeps carrying them.
- `respondGet` answers `416 Range Not Satisfiable` with
  `Content-Range: bytes */total` and no body when the total is known and the
  first-byte-pos is at or past it. `routeMiss` already refuses offsets past
  the total, so no origin request is made.

The post-hoc clamp in `PlaybackSourceResponseEnd.classify` is kept: a total
discovered after the header was framed still needs it, so it is not dead.

Behavior changes (all platforms, playback source proxy only, AVFoundation is
the only client): over-long exact ranges are now framed and served at the
clamped size; a range starting at or past EOF now gets 416 instead of an
empty 206. In-bounds framing is unchanged.

Tests added to PlaybackSourceProxyThroughputTests:
testExactRangePastEndIsClampedToTheKnownTotal,
testRangeStartingPastEndReturns416, testInBoundsRangeFramingIsUnchanged.
No tests rewritten or removed. Suite 1829/0/3 skips vs control 1826/0/3.

Co-Authored-By: Claude Fable 5 <[email protected]>
…gainst the advertised descriptor

Findings addressed: protocol-v3/7 (idx 9), protocol-v3/recipe (idx 10),
protocol-v3/playercore (idx 11).

- `PlaybackV3AvailableQuality.bitrateKbps` is now `Int?`. The server schema
  requires only `label` + `preserves_source` and the Go field carries
  `omitempty`, so an Original rung copied from a source with an unknown probed
  bitrate omits the key — which rejected the ENTIRE decision response and
  failed playback start. The single consumer
  (`ApplePlaybackQuality.playbackOptions`) already treats 0 as "unknown" and
  now reads `?? 0`.
- `ApplePlaybackV3Capabilities.clientTransformationDescriptors` becomes the one
  descriptor registry: `snapshot()` advertises it (minus the simulator, which
  has no executor) and `ApplePlaybackV3PlanAdapter.validate` rejects any
  client-executed transformation whose recipe version differs from, or whose
  validated claims are not a subset of, the advertised descriptor. Previously a
  future recipe version or a new claim would have executed silently under
  today's behaviour. Rejection uses the existing
  `unsupportedClientTransformation` path; the diagnostic
  `v3_transform_<executor>_<name>_<version>` token builder is untouched.
- Deleted the orphan `apple_playercore` token from the original_http delivery
  feature list (PlayerCore is gone; zero references in silo-server or
  silo-android) and the now-duplicated `clientTransformations` name list in the
  adapter.

Tests: new `iosApp/Tests/PlaybackProtocolV3DecodingTests.swift` (8 cases) edits
a parsed copy of the vendored decision fixture in memory — the fixture on disk
is untouched — to cover an Original rung without `bitrate_kbps`, an audio-only
rung without height or bitrate, a rung with both, a matching recipe descriptor,
a future recipe version, an unadvertised claim, registry/advertisement
agreement, and the retired feature token. Two cases in
PlaybackV3ExecutionPlanMatrixTests pinned `recipe_version: "v1"` and a
`dolby_vision` claim — neither value the server ever sends — and were rewritten
to the advertised descriptor ("1", `profile7_rpu_converted_to_profile81`),
including the decision-trace token they assert.

Behaviour (iOS, tvOS, macOS alike): decisions whose quality rungs omit
bitrate_kbps now play instead of failing to decode; plans carrying an
unadvertised client recipe version or claim are now rejected (stopping the
allocated session) instead of executing; the capability advertisement loses one
dead token. No server or Android change is needed — this is client-side
tolerance plus stricter validation of a contract this client already advertised.

Co-Authored-By: Claude Fable 5 <[email protected]>
Finding engine/5a (P1#5a). Every callback `LocalHLSHost.startWriter`
installed gated on `isTornDown` alone; none could tell which writer was
emitting. `requestProducerRestart` stops the retiring writer by flag and
never joins its mux thread, so that thread kept firing at the host after
its successor was already producing: `onVODProducerAnchored` re-seeded
the store's consumer window at the retired base (synchronously, before
its hop) and overwrote `activeVODWriterBaseIndex`/`HeadIndex`,
`onSegmentPlanResolved` republished a stale plan, and `onFinished(error)`
— whose thrown-error path in the writer carries no `isCancelled` check —
failed the successor's session through the backend's
`.writerFailed`/`.writerPrematureSourceEnd` arms.

One mechanism: a per-producer generation the host owns. `adoptProducer`
(split out of `startWriter`, which now only builds the writer and starts
it) mints the tag, installs every callback around it, and takes the
writer on; each callback drops out unless its tag is still current — on
main for the hopped ones, on the mux thread for the two that never hop
(the anchored store seed and the bitmap cue tap). `teardown()` retires
the tag alongside `isTornDown`, which is what finally gates those two.
The counter is lock-held because the mux thread reads it. No second
latch, no writer changes.

The text subtitle tap stays untagged on purpose: it is source-keyed,
outlives producers by design and dedups the region a restart re-reads.

Tests: LocalHLSHostTests gains
`testRetiredProducerCallbacksAreIgnoredAndTheLiveOnesApply` and
`testRetiredProducerBitmapCuesAreIgnoredOnTheMuxThread`, driving writers
the host adopts but never starts. Both fail on the pre-fix behaviour
(verified by neutralizing the tag check: 7 assertion failures).

Behaviour change (iOS/tvOS/macOS): a retired producer's anchored,
appended, plan-resolved, first-segment-ready, finished, source-download,
generated-media, bridged-audio-anchor, HDR10+ and bitmap-subtitle events
are ignored instead of applied. Nothing else changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
Finding engine/5b (P1#5b). `attachItemObservers` receives KVO off-main
and hops with `DispatchQueue.main.async`, while `detachPerItemObservers`
invalidates on main — invalidation cannot retract blocks already
enqueued, and `NotificationCenter` block observers with a queue are
enqueued too, so `removeObserver` does not cancel one in flight. A
retired item (the one an in-place reload or a fresh load just replaced)
could therefore report terminal failure through `reportItemFailure`,
count a rebuffer and flip buffering on, flip buffering off, change the
duration, emit buffered-ahead, or latch `hasReachedItemEnd` and fire
`onEndOfFile` for its successor.

The anchor is `currentItem` — the same one `attemptInitialPlaybackStart`,
`sampleLoopbackAutoResume` and the stalled / failed-to-play-to-end /
errorLog handlers already use, and every attach site assigns it before
attaching, so `.initial` deliveries still pass. Added inside the main
block (that is where the race is) to `status`,
`isPlaybackBufferEmpty`, `isPlaybackLikelyToKeepUp`, `duration`,
`loadedTimeRanges` and `AVPlayerItemDidPlayToEndTime`. Player-level
observers (rate, timeControlStatus) and `seekableTimeRanges` — whose only
effect is already item-guarded — are unchanged.

Behaviour change (iOS/tvOS/macOS): events from a retired player item are
ignored instead of applied. Nothing else changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
…send errors

Closes loopback-media/4 (CONFIRMED), loopback-media/9 (PARTIALLY CONFIRMED),
loopback-media/14 (CONFIRMED).

A — no false EOF (loopback-media/4). `readProgressiveSegment` returned
`(Data, Bool)` and used `true` for three different situations: the segment is
fully stored, the entry is absent and not awaited, and the offset is past a
buffer a restarted producer replaced. The server treated `true` as clean
completion, and its 45 s deadline finished the same way — on a 200 with no
framing, a close IS a complete body, so AVPlayer could accept a truncated fMP4
instead of refetching.

- Store: `ProgressiveRead { chunk(Data, complete:), waiting, superseded }`
  replaces the Bool. Only a fully stored segment reports `complete: true`.
- Server: `.waiting` keeps pumping; `.superseded` and the overall deadline drop
  the connection without ending the body; `.chunk(_, complete: true)` is the
  only path that ends it.
- The response is now chunk-framed (`Transfer-Encoding: chunked`), because
  ending the body is otherwise unobservable: measured on an iOS 26 simulator, a
  client accepts a truncated unframed body as a successful 200 whether the
  server closes with `cancel()` or `forceCancel()`. With framing, only the
  terminating 0-length chunk says "complete", and the three termination paths
  are distinguishable on the wire.
- `progressiveStreamMaxSeconds` moved from a private static constant to the
  single instance value the responder reads, so a test can shorten it.

B — retention window follows the target (loopback-media/9). `vodHighWaterIndex`
was lifetime-monotonic, so after watching forward to N and seeking back to M
the whole span up to N stayed un-evictable regardless of budget. A target that
moves backwards, or forwards past the producer band, now re-anchors the mark to
itself; ordinary forward playback (inside the band) still keeps the writer's
forward span protected. The "disk failure → unbounded RAM" half of the finding
was refuted upstream — `putSegmentInMemoryWithoutEviction` does prune — and is
left alone.

C — disk send errors (loopback-media/14). `send(_:on:andClose:completion:)`
discarded the `contentProcessed` error and always ran its continuation, so
`sendFileChunks` kept reading and scheduling the rest of a segment into a dead
socket. A failed send now skips the continuation, runs a failure hook (which
closes the file handle) and closes the connection.

Tests: store cases for every progressive result (complete + empty tail, offset
past a stored segment, growing buffer, restarted producer, absent with and
without `waitForStart`); server tests that read the raw wire — the complete
stream ends with the terminating chunk, the superseded and timed-out streams do
not (URLSession cannot pin this, it accepts truncated bodies); retention tests
for a backward seek releasing the stale forward span and for forward playback
keeping the producer's span.

Behaviour (iOS, tvOS, macOS): superseded and timed-out progressive streams
abort mid-body instead of closing as complete; the progressive response carries
chunked framing; the VOD hard window follows the newest target instead of the
furthest point ever reached; a failed response send stops the response instead
of finishing it.

Co-Authored-By: Claude Fable 5 <[email protected]>
`applyAutoSubtitle(.select:)` applies the resolver's pick locally whenever
`replanAutomaticProtocolV3SubtitleSelection` declines — a replan already in
flight, or the live plan already naming that index while `selectedSubtitleId`
is still nil. The resolver scores the raw subtitle list and has no bitmap
filter, so a PGS row that a live V3 plan legitimately keeps selectable could
still reach `AVPlayerBackend.selectSubtitleTrack` and be text-decoded as VTT:
a checked-but-blank track under the server's burn-in.

Guard the local fallback only (the replan path is untouched, so a bitmap pick
still becomes a server burn-in), and name the enforced set of paths in the
two doc comments that previously claimed all of them.

Co-Authored-By: Claude Fable 5 <[email protected]>
… it clobber the newer load

Finding control-plane/1 (P1 #1).

`send`/`ingest` commit the reduced state and then `await run(effects)`, and a
Swift actor is re-entrant at every `await`. `beginLoad` orders three suspending
effects — `.cancelTimer(.sourceOutageRideThrough)` (clearOutageNoticeLatch),
`.publish` (applyPresentation) and `.disposeEngine` (teardownEngine) — before
`.startSession`, and `.load` is accepted from `.preparing`. A second load that
committed and ran while the first batch was parked was then overwritten by it:
the parked batch published its stale surface, and its `.startSession` cancelled
the newer load's fresh-load task and installed its own — whose `.prepared`
answer the reducer refused, leaving the player in `.preparing` behind the
loading overlay with nothing left to finish it.

One mechanism: a monotonic `transitionEpoch` owned by the actor, bumped by
`commit` on every transition that binds the state to a different load or moves
it to a different phase, captured at the commit and checked before every effect
in `run`/`perform`. A stale batch stops where it is and undoes nothing.
`startSession` additionally guards `loadID == state.loadID`, which is what keeps
its `tasks[.freshLoad]?.cancel()` from ever retiring a newer load's task; the
registry key stays a plain enum because the guard, not the key, is the gate.

Also introduces `PlaybackControlPlaneShell`, the seam the lifecycle tests need
to hold a shell call open across a second transition. `PlayerViewModel` is the
one production conformer (retroactive conformance here; that file is untouched)
and every requirement is `async`, which its synchronous `@MainActor` methods
satisfy unchanged. No runtime behaviour rides on the protocol itself.

Co-Authored-By: Claude Fable 5 <[email protected]>
…boundary

Finding control-plane/2 (P2).

Both writes a load boundary owes the session it is leaving were dropped by the
actor. `beginLoad` emits `.reportProgress(outgoingIdentity, …)` and the visible
renewal emits its content-scoped force-overwrite `.syncProgress` from the same
transition that commits `.preparing(identity: nil, newLoadID)` — so
`identityIsCurrent(identity)` (state.identity is nil) and `state.loadID ==
loadID` could only ever refuse them. Nothing else writes the outgoing position
at a load boundary: the heartbeat is cancelled and re-armed only on the new
load's `fileLoaded`. Cost: up to one heartbeat of resume position on every
next-episode, retry, interruption recovery and tvOS resume, and the whole
force-overwrite write on a stale-session renewal.

Both now execute against the identity the effect carries rather than against a
state the reducer has already moved on:
  * `.reportProgress` is compared with the session the *bridge* is holding,
    which is the outgoing one at this point (`.startSession` runs after it and
    mints the next), and which is the final gate anyway.
  * `.syncProgress` loses its `LoadID` payload — a real deletion. It is a
    content-scoped write about the load being left behind and had no identity
    that could match; batch staleness is the transition epoch's job now.

Behaviour: the outgoing progress report and the renewal's force-overwrite write
now actually reach the server (or the offline queue) on all platforms. The
heartbeat is unchanged except that it is skipped, rather than reported under a
superseded identity, in the window between a silent renewal's server round trip
completing and its `.renewed` reduction landing.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ion writes

Findings control-plane/1, control-plane/2.

New `PlaybackSessionActorLifecycleTests` drives the actor through a fake
`PlaybackControlPlaneShell` whose calls the test parks on continuations it
resumes by hand — the shape `PlaybackSessionActorTests` (shell: nil) cannot
reach, because no effect batch can suspend there. Five tests:
  * a load parked in `applyPresentation` while a second load commits and starts
    never reaches `.startSession`, never runs its own `.disposeEngine`, and
    publishes nothing after it resumes;
  * the newer load's fresh-load task survives that and still reaches `.playing`
    — the stuck-`.preparing` outcome is unreachable;
  * a dismiss landing on a parked load starts no session;
  * the outgoing progress report reaches the shell;
  * the visible renewal's force-overwrite write reaches the transport.

Every wait is bounded (2 s) and answers `false` on timeout, so a regression
fails the suite rather than wedging it. Verified by neutering each guard in
turn: with the epoch neutered, tests 1-3 fail; with the old identity/LoadID
guards restored, tests 4-5 fail.

`PlaybackReducerTests` gains the emission-side halves: every load boundary
(reload, next episode, retry, visible renewal) emits its outgoing write before
the `.startSession` that mints the replacement, and every batch that cancels the
fresh-load slot either starts a replacement or leaves `.preparing`. Its
`.syncProgress` expectation drops the deleted `LoadID` payload.

Suite: 1833 tests / 0 failures / 3 keychain skips, against a same-host control
at 16b6696 of 1826 / 0 / 3 — delta +7 is exactly these tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tood

Finding docs-code/18 (stale-comments package): comments across the player
control plane pointed at documents that do not exist in the repo — "design
§", "review §", "Stage 2 §", and wave/stage phase labels — or narrated the
migration that produced the code instead of the rule it enforces.

Each hit was rewritten to state what must hold today, or deleted where it
only narrated history:

- PlaybackFailure: typed-case header now states the ownership rule (this file
  is the only owner of the classification/token ladders) instead of the
  before/after story; `loopbackRebuildBudgetExhausted` names the budget that
  stops a wedge rebuilding forever.
- RecoveryPolicy: dropped the three document references; the auto-resume note
  now names the `!reachedEnd` term it is about.
- PlaybackIdentity: LoadID/SessionIdentity docs state the identity-guard
  invariant; SessionIdentity records that the view model's
  `currentServerSessionId` is a read-only projection, not a second owner.
- LoadRequest, PlaybackState, PlaybackReducer, LocalHLSHost, AVPlayerBackend:
  phase labels replaced with the obligation or ownership rule they described;
  the end-of-file note about `LoadRequest`'s `Equatable` having moved is
  deleted.

One doc comment that had drifted onto the wrong symbol (the "UI projection
for a state" sentence sat above `pendingInterruptionDeadline`) is attached to
`PlaybackReducer.presentation(for:)`, which it describes.

Comments only: with comment lines stripped, all eight files are byte-identical
to 7cf414e. No behaviour change on any platform. Builds: Silo, SiloTV, SiloMac
all succeed. No tests added (package is skip_tests); none rewritten or removed.
Co-Authored-By: Claude Fable 5 <[email protected]>
…alidated

Findings: viewmodel/2 (engine replacement is not transactional),
viewmodel/ordering (command order relied on unstructured-task FIFO),
viewmodel/cleanup (two session-stop owners).

Group A - transactional install. `installEngine` is now prepare-then-commit.
The prepare half builds and validates the replacement (source proxy, rewritten
plan, `ExecutablePlan`) and touches nothing that belongs to the outgoing load;
the outgoing pause, the V3 track re-arm, the transport stop, the handoff-slot
release and the `activeExecutionPlan` write all moved into a commit half that
cannot fail. The source-cache handoff is now offered to the prepare as a value
(`prepareSource(for:handoff:)`) instead of being stashed into the shell slot
before the attempt is known to succeed, so an attempt that never commits leaves
the slot for the next one.

The ownership rule that makes the failure land on the right session is stated
once, in `PlayerViewModel.teardownRetiresInstalledSession`: `engineSession` is
retired by the teardown for the load that installed it, or by the teardown for
`pendingLoadID` when that install never committed. The reducer stamps the
failure with the replan's new `LoadID`, so before this the shell compared it
with the installed session's own id, no-oped, and left a paused AVPlayer and
its loopback graph alive behind the error wall.

`PlaybackSessionActor.loadEngine` no longer cancels the engine-event pump
before the install; `pumpEngineEvents` retires the old pump at the commit,
which is where the outgoing session actually ends.

Group B - serialized ingress. `send`, `requestReplan` and the same-load engine
reload no longer each spawn their own `Task`. All three append to one
`AsyncStream<ControlPlaneCommand>` whose single pump awaits each command before
taking the next, so the re-anchor seek reaches the actor before the reload that
carries it by construction rather than by main-executor enqueue order plus
actor FIFO.

Group C - one teardown owner. `cleanup()` finishes the ingress queue and hands
the drain, the control-plane `shutdown()` and the bridge stop to the single
`cleanupCompletionTask`, in that order, so `waitForCleanupCompletion` covers
all of it and the second stop is a settled no-op rather than the loser of a
race. The synchronous `engineSession?.dispose(reason: "cleanup")` still runs
first. `deinit` closes the queue too, because the pump holds the control plane
rather than the view model.

Group D - migration-artifact comments (`design §`, `base PVM`, `Wave 3`) in
these two files replaced with the invariant they were narrating.

Behaviour changes (iOS, tvOS, macOS alike):
- A replan or reload whose install fails now leaves the outgoing engine playing
  until the reducer's `.fail` lands, and that failure's `.disposeEngine`
  disposes it. Previously it was frozen and then stranded.
- An install superseded before it commits no longer pauses or stops the session
  a newer install may be about to reuse.
- Backgrounding tvOS while an install is in flight now disposes the engine that
  is actually playing instead of leaving it running until the replacement
  commits.
- Command ordering into the control plane is guaranteed rather than assumed.
- `waitForCleanupCompletion` now also waits for the control plane's shutdown
  and for commands queued just before dismissal.

Tests: `PlaybackSessionActorLifecycleTests` gains a failing-install replan
(exactly one teardown, named with the failed attempt's `LoadID`, state
`.failed`) and a direct pin of the teardown ownership rule. The fake shell
gains `nextInstallFailure` and `replanResolves`.

Co-Authored-By: Claude Fable 5 <[email protected]>
… migration history

Group D of the pvm-engine-install package: the `design §` and wave references
in this file narrated how the type came to be rather than what holds now.
Comment-only; no behaviour change.

Co-Authored-By: Claude Fable 5 <[email protected]>
The widened teardown-ownership arm (`pendingLoadID == teardownLoadID`)
could not tell "the install failed" from "the install is still in its
prepare half", because `installEngine` mints `pendingLoadID` up front. On
the `engineOnly` arm that was unsound: `disposeEngineOnly` disposes the
backend but deliberately leaves the session un-`isDisposed` and installed,
so a server-outage escalation landing inside the install window disposed
the very `AVPlayer` the commit was about to adopt through
`relinquishBackend()` — a silent stall on a dead backend rather than a
surfaced error. An `engineOnly` teardown means "keep THIS load's session
alive as its recovery owner", and a session from an older load is never
that, so the arm now applies to terminal teardowns only. The predicate
takes `engineOnly`; no new state.

Also bound the cleanup drain. The single ingress runs each command's
effects to completion, so a dismissal that lands while a `.load` is
waiting on a dead link would otherwise hold `waitForCleanupCompletion` —
the tvOS handoff's gate — for the request timeout. The drain now gets a
2 s grace window, after which the pump is cancelled; `.dismiss` supersedes
whatever was still queued and the bridge stop after it still writes the
final position.

Two disclosures corrected in comments, no behaviour change: events the
retired session had already buffered can still land after a same-`LoadID`
reload commits (finishing that stream in `disposeEngineOnly` is not the
fix — the outage recovery owner emits its `.recoveryAction`s through it),
and the source-cache offer is shared with the still-playing proxy for the
length of the prepare window.

Co-Authored-By: Claude Fable 5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0571cb6c7f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +734 to +736
await shell?.applyEngineEventToPresentation(
event,
reduction: Self.reduction(of: event, from: before, to: state)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard the presentation hop with the originating load

When an event from load A reaches this MainActor hop while the user starts load B, actor reentrancy can change pendingLoadID after the earlier guard but before this callback executes. The callback then applies A's event to B's shell state; for example, a stale .tracks event can replace B's track list and a stale .fileLoaded can apply settings or pending subtitles against B before its engine is ready. Pass the originating loadID through this hop and reject it against the live engine/load on the MainActor before mutating presentation state.

AGENTS.md reference: AGENTS.md:L44-L47

Useful? React with 👍 / 👎.

// multi-page cache would fetch (and re-cache) page two as page one.
if items.isEmpty,
let cached: CatalogResponse = ResponseCache.shared.get(
CacheKey.collectionItems(collectionId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include collection scope in the page cache key

When two regular collections in different libraries share a collectionId, this lookup returns the first library's CatalogResponse because the key omits both libraryId and kind; the navigation model explicitly treats libraryId as part of a collection's semantic identity in UICustomizationPreferences.swift. If the refresh then fails, the catch path suppresses the error because cached items are already present, leaving the grid populated with another library's items; even a successful refresh briefly displays the wrong collection. Key the cached page by library, kind, and collection ID.

Useful? React with 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants