Repository navigation
feat(downloads): sync download subscriptions through v2 - #374
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:
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: 6f52e9465a
ℹ️ 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".
| } else if legacyPending == true { | ||
| // The first complete list after the removal. A monitor this | ||
| // version creates is stored when its create answers, so every | ||
| // unknown one is the earlier version's. | ||
| storedLegacy.formUnion(unknown) | ||
| legacy = storedLegacy |
There was a problem hiding this comment.
Preserve uncertain creates during legacy classification
When an upgraded scope still has legacyMonitorsPending == true and the first create reaches the server but its response is lost, sendCreate recovers by calling this list refresh. Because the newly created monitor was never stored locally, it is included in unknown here, recorded as legacy, and omitted from file.subscriptions; the subsequent series lookup therefore reports monitoringUncertain even though the server created the monitor, and it will not be synced unless the user retries. Exempt the series being recovered from legacy classification or record the recovered monitor before finalizing the legacy set.
Useful? React with 👍 / 👎.
| mutating func listCompleted(startedAt start: Int) { | ||
| deleted = deleted.filter { $0.value > start } | ||
| created = created.filter { $0.value > start } |
There was a problem hiding this comment.
Retain write generations until every older list read finishes
When two monitor-list refreshes overlap, a newer read can complete first and remove a create/delete generation here even though an older read still needs it. Foreground, background-refresh, and push paths can all invoke onAppActive() without coalescing, so if a write lands after the older read starts, that older stale response can later drop the newly created monitor or restore a deleted one because its ledger protection has already been cleared. Serialize list refreshes, discard out-of-order results, or retain each generation until all reads that predate it have completed.
Useful? React with 👍 / 👎.
6f52e94 to
d9eeef8
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d9eeef88bb
ℹ️ 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".
| upsertSubscription(updated, seriesTitle: existing.seriesTitle) | ||
| persist() |
There was a problem hiding this comment.
Protect PATCH results from stale list reads
When a monitor-list request starts before this PATCH completes but returns afterward, refreshSubscriptions can replace the newly stored monitor with the list's older options and ETag because subscriptionWrites tracks only creates and deletes. This can happen when a foreground/background sync or another create-recovery list overlaps an edit; if that caller does not subsequently resync this monitor, the UI and persisted store revert until a later refresh, and the next edit starts with a stale validator. Record successful updates in the write ledger or otherwise prevent older list responses from overwriting them.
Useful? React with 👍 / 👎.
0b8330c to
dc6f6ed
Compare
Series monitoring still went through /api/v1: one bodiless sync for every
monitor, and PATCH/DELETE without a validator. v2 syncs one monitor per
call and page, guards edits with If-Match, and has no inline registration
count on create, so the v1 calls cannot be switched one for one.
The monitor calls now live in APIv2Client+DownloadSubscriptions.swift and
run under the captured download owner. Create is sent once
(non_retryable); an uncertain create reads the monitor list, and a create
answered with an existing monitor applies the requested options with a
PATCH. PATCH and DELETE send the stored validator as If-Match; a 412 (or
409) reads the monitor again and applies the same change once more, and a
428 is logged as a client bug and never retried. Sync lists this device's
monitors, then pages each active one with {subscription_id, etag}, sends a
page without an answer again with the same validator and cursor, and
starts over under a fresh validator after a 409. Monitors and the local
store keep their etag, and stopped monitors are kept as pending deletes
until the server confirms them. The v1 subscription methods and response
models are deleted.
Stack-PR: W3-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
updateDownloadSubscription and deleteDownloadSubscription each repeated the same block to pick the If-Match validator: the stored one when set, otherwise a fresh read of the monitor. Both now call one monitorValidator helper. Each call keeps its place relative to its do/catch, so a failed read is handled exactly as before. Stack-PR: W3-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… and list reads A create for a series whose monitor DELETE was on the wire could answer with that monitor, cancel its pending delete locally, and report success after the DELETE removed it on the server. A monitor list read issued before a DELETE landed brought the stopped monitor back as an untitled entry, and one issued before a create answered dropped the new monitor. A sync page 404 for a deleted monitor was only logged. A new SubscriptionWriteLedger records which DELETEs landed and which creates answered, by generation. A list read leaves out monitors whose DELETE landed and keeps monitors created during the read. A create now waits for a running delete pass first; if a pass that started during the create removes the monitor the create answered with, it sends one fresh create. Only a create revives a stopped monitor; an edit or sync answer for a stopped monitor is dropped. A sync page 404 reads the monitor, and a 404 there removes it locally; create surfaces monitoringUncertain and edit surfaces monitorRemoved. Stack-PR: W3-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
mergeSubscriptions hid every unknown monitor whose createdAt was before a device-clock removal date. A reinstall wrote a new date and hid (and stopped syncing) every monitor this version had created, and clock skew misjudged monitors near the cutoff. The removal now flags each carried scope with legacyMonitorsPending. The scope's first complete monitor list records the monitors the store doesn't know in legacyMonitorIds; later lists hide only those ids. A scope no earlier version wrote, including every scope after a reinstall, hides nothing. While the scope's first registry read is still pending, or the removal did not finish, monitor syncs register nothing, so that read can't take their new rows for legacy rows. Stack-PR: W3-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
d9eeef8 to
be2aba0
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: be2aba0b5a
ℹ️ 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".
| priorRecordIds = Set(file.records.keys) | ||
| registered = (try? await SiloAPI.shared.syncSubscriptions()) ?? 0 | ||
| if canMonitorSeries, let owner = await captureScopeOwner() { | ||
| registered = await syncSubscriptions(owner: owner) |
There was a problem hiding this comment.
Serialize monitor sync with registry reconciliation
When foreground, background-refresh, or push-triggered onAppActive() calls overlap, this sync can register an episode after another invocation's final registry GET has captured its response. If this invocation then reconciles first and imports the new row, the older response can arrive afterward and reconcileWithServer marks that active local record as failed with removed_on_server; later ready reconciliations do not recover records already in .failed. Coalesce these runs or discard stale registry responses so newly registered episodes cannot be permanently prevented from downloading.
Useful? React with 👍 / 👎.
Series monitoring (download subscriptions) now runs on
/api/v2: create, edit, stop and sync. Edits and deletes are guarded by the monitor's validator, and sync pages each monitor separately.Problem
Series monitoring still called four v1 routes (inventory rows 97-100):
POST /api/v1/downloads/subscriptions,POST .../subscriptions/sync,PATCH .../subscriptions/{id}andDELETE .../subscriptions/{id}. The v2 contract differs in ways a path swap can't handle:syncDownloadSubscriptionsyncs one monitor per call, one page at a time, with body{subscription_id, etag}. It answers 409 when the monitor changed. v1 synced every monitor in one bodiless call.updateDownloadSubscriptionanddeleteDownloadSubscriptionrequireIf-Match. A missing header gets 428 and a stale validator gets 412. The app stored no validator:ServerSubscriptionandDownloadSubscriptionhad noetag.createDownloadSubscriptionisnon_retryable. It returns the bare monitor (noregisteredcount). For a series this device already monitors, it returns that monitor unchanged.X-Silo-Device-Id.Solution
APIv2Client+DownloadSubscriptions.swiftandAPIv2DownloadSubscriptionModels.swifthold the monitor calls: list, get, create, update, delete and sync. They reuse the download lane's owner-fenced transport (downloadRegistryRequest, now internal with aheadersparameter), so every call goes throughwithOwnerFenceandsameCredentialIdentity.HTTPClientstill addsX-Silo-Device-Idto every request. Each method asserts its status (200, or 204 for delete). It also checks that the answer describes the requested monitor or series.If-Match. A monitor stored without one is read first. A 412 (or the 409 of a concurrent edit) reads the monitor again and applies the same change once more under the new validator. A second 412 is surfaced. A 428 is logged as a fault and never retried. A delete that gets 404 counts as done.runMonitoringAndProgressSyncruns when the capability allows series monitoring. It first sends pending monitor deletes, then lists the monitors and replaces the local list. Local titles stay, and a stopped monitor stays hidden while its DELETE is pending. A list read describes the server as it was when the read started, so the merge also leaves out monitors whose DELETE landed during the read and keeps monitors a create answered with during the read (SubscriptionWriteLedger, keyed by a write generation). It then pages each active monitor with the validator captured before the first page. A page with no answer (connection lost, 5xx) is sent again up to twice, with the same validator and cursor. A 409 reads the monitor again and restarts from the first page under the new validator, at most twice. A GET 404 during that reload removes the monitor locally. A sync page 404 reads the monitor; a 404 there removes it locally, and a 200 means its series is hidden, so the run logs it and moves on. A 401, 408, 410, 429 or 503, a server that needs an update, or a request that never left the device ends the run for every monitor. Other 4xx answers are logged and the run moves to the next monitor.ServerSubscriptiondecodes the v2DownloadSubscription, with every required field required.DownloadSubscriptiongains an optional persistedetag, andDownloadStoreFilegains an optionalpendingSubscriptionDeletes(id → validator). Stores without either field still decode.natural_idempotent, and download-registry deletes already use this pattern. A refusal ends the pending delete; the next list read shows the monitor again because the server still has it. If a create answers with a monitor whose DELETE is still pending, the app cancels that pending DELETE. Only a create does this; an edit or sync answer for a stopped monitor is dropped.legacyMonitorsPending. That scope's first complete monitor list records every monitor the store doesn't know inlegacyMonitorIds, and later lists hide only those ids. They are never shown or synced, and they stay on the server untouched. A scope no earlier version wrote, including every scope after a reinstall, hides nothing. If this launch's removal did not finish, unknown monitors are hidden for the launch without being recorded.HTTPClientexcluded both GET and POST on/api/v2/downloads/subscriptionsfrom 401 refresh-and-retry. It now excludes only thenon_retryablePOST, so a monitor list read survives an expired access token.SiloAPI.createSubscription,syncSubscriptions,updateSubscriptionanddeleteSubscription, plus the v1-onlyCreateSubscriptionResponseandSubscriptionSyncResponse.DownloadAPI.swiftkeeps onlypullProgressDeltas, which W3-E replaces.Failure outcomes
non_retryable)natural_idempotent, If-Match)natural_idempotent, If-Match)natural_idempotent)registered, follow the cursorValidation
DownloadSubscriptionsV2Tests(new),DownloadRegistryV2Tests,DownloadDeliveryV2Tests,LegacyDownloadStorageTestsandDownloadGroupingTests.StubURLProtocolthroughAPIv2TestStub. They cover:If-Matchon PATCH and DELETE, and the PATCH body omitting unset fieldsscripts/ci/check-no-api-v1.shpassed.Risks and follow-ups
SubscriptionWriteLedgerand the merge, not by an end-to-endDownloadManagertest. The manager is a singleton onSiloAPI.shared, and no test seam exists for it. The same applies to the rule that holds monitor syncs until the first registry read.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 26 of 50 in the Apple API v2 stack. Base:
apiv2-stack/25-download-assets-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code