Skip to content

feat(downloads): manage downloads through the v2 registry - #372

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/24-downloads-registry-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/24-downloads-registry-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

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_id is now a string.
  • Create answers 202 with a paged {items, skipped, page, batch_id}.
  • Create is non_retryable and needs a revision guard for a managed single item.
  • The status PATCH needs {status, updated_at, revision} plus X-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

  • Client. New APIv2Client+Downloads.swift and APIv2DownloadModels.swift. Every call runs through the shared SiloAPI.apiV2Client under the captured owner (withOwnerFence, pre-dispatch identity check, gate()). HTTPClient already sends this installation's X-Silo-Device-Id on every request, and the server scopes list, create, status and delete to (account, profile, device), so the header is not added a second time.
  • Capability (GET /api/v2/capabilities/downloads). The client decodes the fields it reads, all required. isUsable needs state == available and allowed in addition to enabled and download_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.
  • List (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.
  • Create (POST /api/v2/downloads, 202). Each request is sent once.
    • A single item sends expected_revision: 0, or the local record's expected_download_id and revision.
    • A series or season sends series: true, quality: original and one client-chosen batch_id on every page, and follows page.next_cursor for up to 100 pages. Each page's entries are stored as they arrive.
    • The answer must describe the request: item, file, quality, device and batch.
  • Status (PATCH /api/v2/downloads/{id}). The event {status, updated_at, revision} is stored on DownloadRecord.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 (DELETE /api/v2/downloads/{id}, 204). IDs go into the persisted pendingServerDeletes set (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.
  • Scope fencing. Background delete and status passes capture their scope (server, profile, generation) when they start and stop when it changes. The manager records which scope file was 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.
  • Removed. The v1 methods (downloadCapability, createDownload, listDownloads, patchDownloadStatus, deleteDownloadRow) and the v1-only models (ServerDownloadRow, ServerDownloadsResponse, CreateDownloadRequest, CreateDownloadResponse, DownloadStatusUpdate, the formats alias). DownloadRecord.mediaFileId is a String with no dual decoder (D1). The background 401 retry used the v1 list as a token-refresh probe; it now calls the v2 capability read.
  • Other. APIv2Client.neverConnected (added in W2-S) is now internal so both classifiers share it. The ownership-fence line count in iosApp/iosApp goes from 62 to 63.

Failure outcomes

Call Definite success Definite failure Uncertain (sent, no usable answer)
Create (non_retryable) 202 whose receipt matches: entries stored, pipeline starts 4xx other than 409 (for example 403, 422, 413): error shown once, logged, nothing stored. 401 / 408 / 410 / 429 / 503 / v1-only 404 / never connected: nothing was applied, error shown 5xx other than 503, lost connection, or a 202 that does not describe the request: never re-sent. The registry is read; if it now holds a live entry for the item, the download proceeds, otherwise the user sees "Silo couldn't confirm the download started…". A later tap is safe because expected_revision: 0 gets a 409 when the entry exists
Create 409 (guard mismatch) — Registry read, pending deletes sent and awaited; if the item is now live the download proceeds, otherwise "This download changed on the server. Try again." with the refreshed guard —
Status (domain_identity) 200 with the same entry: event cleared 409: event cleared, registry read. 400 / 403 / 404 / 422: event cleared, logged 5xx, 408 / 429 / 503 / 410, transport, or a mismatched 200: event kept and resent unchanged on the next foreground
Delete (natural_idempotent) 204 or 404: removed from pendingServerDeletes Any other answer: kept pending (the row stays hidden), logged, resent on every complete reconcile and before a create's 409 is settled Same as definite failure: kept and resent
List / capability (reads) 200 complete read applied Error logged; nothing applied; cached capability kept Same

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS and tvOS: DownloadRegistryV2Tests, LegacyDownloadStorageTests, DownloadGroupingTests, ProgressSyncV2Tests and AppleDecodeCapabilitiesTests. Before the sorted-keys fix, testStatusRetrySendsTheSameEvent failed once on tvOS because JSON keys came out in a different order. After it, the tvOS run passed three times in a row.
  • New DownloadRegistryV2Tests (on StubURLProtocol) cover:
    • capability gating on state and allowed, and a missing required field;
    • the paged list with limit=100, the cursor and X-Silo-Device-Id, and the 100-page bound;
    • lists that fail instead of returning a prefix: missing cursor, repeated cursor, duplicate entry, another device's entry, zero revision, failing later page;
    • the single-create body (string media_file_id, expected_revision 0, and the id/revision replacement guard);
    • the 202 create sent exactly once for 409, 422, 403, 429, 410, legacy 404, 500, lost connection, refused connection, mismatched receipt and 201, with the classification for each;
    • series pages repeating batch_id and following the cursor;
    • invalid shapes refused without dispatch, and a profile switch before dispatch sending nothing;
    • a status retry after a lost connection sending a byte-identical body, the event surviving the store coder, and the status resolution for 200, 409, 404, 400, 503, 500, 410 and a mismatched 200;
    • DELETE 204 and 503;
    • a store round-trip of pendingStatusEvent, pendingServerDeletes and a string mediaFileId.
  • scripts/ci/check-no-api-v1.sh passed.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.
  • No manager-level test covers the delete resend or the scope fence. DownloadManager is a singleton bound to the shared SiloAPI, TokenStore, ServerRegistry and its background URLSession, with no seam to stub them. Both were checked by reading the code paths.
  • Not run: manual create, background and relaunch checks on a signed simulator against a live server.

Risks and follow-ups

  • A 500 on create counts as uncertain. The server can return 500 after it has written the entry, and create is 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.
  • Clock skew. The server rejects a status event whose updated_at is in its future (400). A device clock running ahead can have its downloading event refused. The client drops a refused event and logs it; the local download is unaffected, but the server row stays ready.
  • Create flow. Single-item create uses the local record as its guard instead of reading the registry before every tap, which is what Android does. A stale guard costs one 409, one registry read and a "Try again". This is intended but has not been checked against a live server.
  • Series create omits 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 need expected_entries guards with each failed entry's id and revision.
  • Server-side DELETE refusals (for example demo-restricted 403) keep the entry hidden and are retried on every reconcile until the server lists it no longer.
  • Out of scope. Manifest, asset and file URLs, subscriptions and the progress pull still use v1. They belong to W3-C, W3-D and W3-E. OfflineManifest.mediaFileId stays Int until W3-C.
  • Open PR conflict. fix(downloads): retarget store on profile and server switch #181 (download retarget) touches 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

@coderabbitai

coderabbitai Bot commented Sep 23, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 24b79eaf-afbb-496d-916d-d8d35e4ce3dc

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:47:09.920996Z 02365c3 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: ad278528 (apiv2-stack/24-downloads-registry-v2).

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:

  • major: A failed server DELETE is never sent again, and the item can then never be downloaded again
  • minor: Background registry tasks capture their owner late, so they can pair a new scope's auth with the previous scope's store
  • minor: The PR body misstates two behaviors

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 /api/v1 request from the new builds except the retained health probe.

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 (claude-opus-5-5) agents in Claude Code (T3 Code).

@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: 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".

Comment on lines +50 to +52
guard let info = page.page, info.hasMore else {
guard page.page?.nextCursor?.isEmpty ?? true else { throw DownloadRegistryError.incompleteRegistry }
return entries

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 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 👍 / 👎.

Comment on lines +23 to +25
/// Downloads are usable only when the capability is available and this
/// principal may use it.
var isUsable: Bool { state == "available" && allowed && enabled && downloadAllowed }

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 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 👍 / 👎.

Comment on lines +145 to +147
guard let entry = try? HTTPClient.makeJSONDecoder().decode(APIv2DownloadEntry.self, from: response.data),
entry.id == id, entry.isUsable else {
throw DownloadRegistryError.unexpectedReceipt

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 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 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/24-downloads-registry-v2 branch from ad27852 to f9ad77a Compare September 23, 2026 13:19

@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: 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".

Comment on lines +193 to +194
case 401, 408, 410, 429, 503:
return .notApplied

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 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 👍 / 👎.

Comment on lines +730 to +732
applyCreatedEntries(page.items, displayTitle: nil, displaySubtitle: nil, type: nil,
seriesId: seriesId, posterThumbhash: nil)
registered += page.items.count

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 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 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/23-sync-progress-v2 branch from 85e1890 to 32ad13c Compare September 23, 2026 13:38
Quick104 and others added 3 commits September 23, 2026 09:39
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]>
Base automatically changed from apiv2-stack/23-sync-progress-v2 to main September 23, 2026 13:39
@Quick104
Quick104 force-pushed the apiv2-stack/24-downloads-registry-v2 branch from f9ad77a to 02365c3 Compare September 23, 2026 13:39
@Quick104
Quick104 merged commit d2281bc into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/24-downloads-registry-v2 branch September 23, 2026 13:39

@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: 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 {

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 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 👍 / 👎.

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.

1 participant