Repository navigation
feat(downloads): manage downloads through the v2 registry - #372
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Code review summaryReviewed head: Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration. Verified findings, all fixed on this branch:
Deliberate choice: a 500 on the non-retryable download create is treated as uncertain (held, not resent), so a create the server applied is never duplicated. Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no Remaining: no open verified findings. Merge in stack order. Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack. Review by Claude Opus 5.5 ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad278528dd
ℹ️ 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".
| guard let info = page.page, info.hasMore else { | ||
| guard page.page?.nextCursor?.isEmpty ?? true else { throw DownloadRegistryError.incompleteRegistry } | ||
| return entries |
There was a problem hiding this comment.
Require pagination metadata before applying the registry
When /api/v2/downloads returns an incompatible or malformed response with page omitted, the optional model still decodes and this branch treats the accumulated items as the complete registry. reconcileWithServer then interprets every omitted ID as removed and marks active local downloads failed, despite the stated invariant that a prefix must never be applied. Require a terminal page object rather than accepting nil as completion.
Useful? React with 👍 / 👎.
| /// Downloads are usable only when the capability is available and this | ||
| /// principal may use it. | ||
| var isUsable: Bool { state == "available" && allowed && enabled && downloadAllowed } |
There was a problem hiding this comment.
Honor the v2 registry capability flags
When a server reports state: available and allowed: true but advertises bounded_creation: false or ordered_status: false, this still enables Downloads even though the manager unconditionally uses revision-guarded paged creates and ordered status events. Those operation flags are present in the vendored v2 capability contract but are discarded by both download capability models, so partially capable deployments expose actions whose registry writes cannot be supported. Decode the relevant flags and include them in the operation/UI gating.
Useful? React with 👍 / 👎.
| guard let entry = try? HTTPClient.makeJSONDecoder().decode(APIv2DownloadEntry.self, from: response.data), | ||
| entry.id == id, entry.isUsable else { | ||
| throw DownloadRegistryError.unexpectedReceipt |
There was a problem hiding this comment.
Reject status receipts for a different registry revision
If a status PATCH returns 200 with the requested ID but a different revision or device identity, this guard accepts it as success. sendStatusEvents consequently clears the persisted event, even though the response does not acknowledge the event's (device, revision) domain identity and may describe replaced bytes; this can leave the local record and server status permanently out of sync. Validate the receipt's revision and device before settling the event.
Useful? React with 👍 / 👎.
ad27852 to
f9ad77a
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f9ad77a149
ℹ️ 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".
| case 401, 408, 410, 429, 503: | ||
| return .notApplied |
There was a problem hiding this comment.
Retain status events after profile-proof refusals
When a status PATCH receives a transient 403 such as profile_verification_required after a PIN/profile proof expires, this classifier falls through to .rejected; DownloadManager.statusReportResolution then treats the event as settled and permanently clears it. After the user re-verifies the profile, the completed/downloading event is no longer available to retry, leaving the server status stale. Classify this authentication refusal as retryable for status reporting rather than discarding the persisted event.
Useful? React with 👍 / 👎.
| applyCreatedEntries(page.items, displayTitle: nil, displaySubtitle: nil, type: nil, | ||
| seriesId: seriesId, posterThumbhash: nil) | ||
| registered += page.items.count |
There was a problem hiding this comment.
Reject duplicate entries across series pages
When a malformed series/season response repeats an entry ID on a later terminal page, each page passes the per-page receipt check and this loop applies the same record twice, increments registered twice, and reports the batch as successful. That can silently accept an incomplete batch with episodes omitted. Track entry IDs across the entire pagination loop, as listDownloads does, and treat any cross-page duplicate as an unexpected receipt.
Useful? React with 👍 / 👎.
85e1890 to
32ad13c
Compare
Downloads still used the v1 registry: capability, create, list, status
and delete. A v2-only server has none of those routes, and the v1 calls
swallowed their errors, so downloads looked enabled but never started.
Status reports were fire-and-forget without the revision v2 requires,
and a failed DELETE let the next reconcile bring the download back.
The five calls now go through APIv2Client+Downloads.swift under the
captured owner of the download scope. The capability is usable only
when its state is available and it is allowed. The registry is read in
pages of 100, at most 100 pages, and any short or inconsistent read
fails instead of returning a prefix. media_file_id is a string
throughout.
Create sends exactly once. A single item sends expected_revision 0, or
the local entry's id and revision; a series or season sends one
client-chosen batch_id on every page and follows the cursor. A 409 or
an uncertain outcome reads the registry instead of sending again; when
the item is then in the registry the download goes ahead.
Status events store {status, updated_at, revision} on the record, so a
retry sends the same event. A 409 drops the event and reads the
registry; a definite refusal drops it; anything else keeps it for the
next foreground. Deletes are recorded in the store before they are
sent, reconcile never imports a pending delete, and a delete stays
pending until the server answers 204 or 404. Entries left by earlier
versions go through the same delete queue.
Stack-PR: W3-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…heir scope A DELETE that failed (offline, 503, 429) stayed in pendingServerDeletes but was never sent again: reconcile only started a pass when it had legacy ids to add. The entry kept counting against the device quota, and downloading the same item again got a 409 on every try, because settleFailedCreate waited on a delete pass that never started. Every complete reconcile now sends the pending DELETEs, and a create 409 sends them and waits before it settles, so the user's next tap succeeds once the DELETE lands. Background delete and status passes also read their scope only when their Task first ran. A scope switch in between let them send the old scope's ids with the new profile's headers, and persist() then saved the old records into the new profile's store. The passes now capture their scope (server, profile, generation) when they are created. The manager records which scope file was loaded for: persist() saves to that scope, and no registry owner is captured while a switch still waits on its load. Stack-PR: W3-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A status retry must resend the same event. JSONEncoder does not fix the key order, so on tvOS the retried body could list the same keys in a different order, and testStatusRetrySendsTheSameEvent failed intermittently. The status body now encodes with sorted keys. Stack-PR: W3-B Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
f9ad77a to
02365c3
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02365c31f0
ℹ️ 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".
| case let .seriesPage(seriesId, _, batchId, _): | ||
| guard created.batchId == batchId, | ||
| created.items.count + created.skipped.count <= downloadRegistryPageLimit, | ||
| created.items.allSatisfy({ $0.contentId == seriesId && $0.episodeId?.isEmpty == false }) else { |
There was a problem hiding this comment.
Reject duplicate episode IDs in series receipts
When a series page returns two distinct download IDs for the same episode_id, this predicate accepts both because the earlier uniqueness check only compares entry IDs. createSeriesPages then stores and starts both records, while lookup and deletion APIs such as record(forContentId:) operate on only one matching record, leaving a duplicate transfer that consumes storage and cannot be managed reliably. Reject repeated episode IDs within each series receipt.
Useful? React with 👍 / 👎.
Problem
Downloads still used the v1 registry for five calls: capability, create, list, status and delete (inventory rows 89-93). A v2-only server has none of those routes. Every caller swallowed the error: the capability refresh kept the cached value, and status and delete used
try?. So downloads looked enabled and never started.The v1 wire shapes also no longer match:
media_file_idis now a string.{items, skipped, page, batch_id}.non_retryableand needs a revision guard for a managed single item.{status, updated_at, revision}plusX-Silo-Device-Id, and a retry must resend the same values.One more bug predates v2: when a DELETE failed, the next reconcile imported the server row again, and the deleted download came back and re-downloaded.
Solution
APIv2Client+Downloads.swiftandAPIv2DownloadModels.swift. Every call runs through the sharedSiloAPI.apiV2Clientunder the captured owner (withOwnerFence, pre-dispatch identity check,gate()).HTTPClientalready sends this installation'sX-Silo-Device-Idon every request, and the server scopes list, create, status and delete to (account, profile, device), so the header is not added a second time.GET /api/v2/capabilities/downloads). The client decodes the fields it reads, all required.isUsableneedsstate == availableandallowedin addition toenabledanddownload_allowed. A cached capability from before this change reads as unusable until the next refresh. When a refresh fails, the cached value stays and the error is logged at warning level.GET /api/v2/downloads). Pages of 100, at most 100 pages. The read throws if a page promises more without a cursor, repeats a cursor or an entry, holds another device's entry, or holds an entry without an id, file or revision. Reconcile marks absent rows as removed on the server, so it runs only after a complete read.POST /api/v2/downloads, 202). Each request is sent once.expected_revision: 0, or the local record'sexpected_download_idand revision.series: true,quality: originaland one client-chosenbatch_idon every page, and followspage.next_cursorfor up to 100 pages. Each page's entries are stored as they arrive.PATCH /api/v2/downloads/{id}). The event{status, updated_at, revision}is stored onDownloadRecord.pendingStatusEvent, and a retry resends it unchanged, with sorted keys so the body is byte-identical. A 409 drops the event and reads the registry. Replacing an entry's bytes clears its unsent event.DELETE /api/v2/downloads/{id}, 204). IDs go into the persistedpendingServerDeletesset (added in W1-D) before the request is sent. Reconcile never imports a pending ID, and an ID leaves the set on 204, on 404, or when a complete list no longer shows it. Every complete reconcile sends the pending DELETEs again, so a delete made offline or answered 503 goes out on the next reconcile. A create that gets a 409 also sends the pending DELETEs and waits for them, so when the 409 came from this device's own pending delete, the next tap succeeds once that DELETE lands. W1-D's deletes of entries from earlier versions go through the same queue: the first complete read of a scope W1-D carried over still deletes unknown entries instead of importing them.filewas loaded for: saves go to that scope's store, and no registry owner is captured while a scope switch is still waiting on its load. A pass started under one profile can no longer send its requests with the next profile's headers or save the old records into the new profile's store.downloadCapability,createDownload,listDownloads,patchDownloadStatus,deleteDownloadRow) and the v1-only models (ServerDownloadRow,ServerDownloadsResponse,CreateDownloadRequest,CreateDownloadResponse,DownloadStatusUpdate, theformatsalias).DownloadRecord.mediaFileIdis aStringwith no dual decoder (D1). The background 401 retry used the v1 list as a token-refresh probe; it now calls the v2 capability read.APIv2Client.neverConnected(added in W2-S) is now internal so both classifiers share it. The ownership-fence line count iniosApp/iosAppgoes from 62 to 63.Failure outcomes
non_retryable)expected_revision: 0gets a 409 when the entry existsdomain_identity)natural_idempotent)pendingServerDeletesValidation
DownloadRegistryV2Tests,LegacyDownloadStorageTests,DownloadGroupingTests,ProgressSyncV2TestsandAppleDecodeCapabilitiesTests. Before the sorted-keys fix,testStatusRetrySendsTheSameEventfailed once on tvOS because JSON keys came out in a different order. After it, the tvOS run passed three times in a row.DownloadRegistryV2Tests(onStubURLProtocol) cover:stateandallowed, and a missing required field;limit=100, the cursor andX-Silo-Device-Id, and the 100-page bound;media_file_id,expected_revision0, and the id/revision replacement guard);batch_idand following the cursor;pendingStatusEvent,pendingServerDeletesand a stringmediaFileId.scripts/ci/check-no-api-v1.shpassed.DownloadManageris a singleton bound to the sharedSiloAPI,TokenStore,ServerRegistryand its backgroundURLSession, with no seam to stub them. Both were checked by reading the code paths.Risks and follow-ups
non_retryable, so the client reads the registry instead of sending again. This avoids duplicate creates at the cost of a "couldn't confirm" message when the 500 really did nothing.updated_atis in its future (400). A device clock running ahead can have itsdownloadingevent refused. The client drops a refused event and logs it; the local download is unaffected, but the server row staysready.expected_entries. The server treats a missing map as{}(CreateSeriesPage), so existing entries, failed ones included, come back unchanged, as they do for Android. Re-requesting a series does not re-register its failed episodes; doing that would needexpected_entriesguards with each failed entry's id and revision.OfflineManifest.mediaFileIdstaysIntuntil W3-C.DownloadManager.swift. Whichever lands second rebases.AI disclosure
Code and description written by Claude Opus 5.5 (
claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.Part 24 of 50 in the Apple API v2 stack. Base:
apiv2-stack/23-sync-progress-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code