Repository navigation
feat(downloads): remove downloads saved by earlier versions - #370
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: cccf18f9e0
ℹ️ 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".
| for (path, queue) in scopes { | ||
| let directory = root.appendingPathComponent(path, isDirectory: true) | ||
| try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) | ||
| var file = DownloadStoreFile.empty |
There was a problem hiding this comment.
Preserve subscriptions when rebuilding each scope
When an upgraded scope has series monitors, initializing its replacement store from DownloadStoreFile.empty erases every local subscription mirror along with the downloads. runMonitoringAndProgressSync() is client-driven and calls syncSubscriptions() only when file.subscriptions is nonempty, while DownloadAPI has no endpoint that rehydrates the mirrors, so existing server monitors become invisible and unmanageable and stop registering new episodes. Carry the subscriptions forward or explicitly rehydrate and sync them.
Useful? React with 👍 / 👎.
cccf18f to
ec005ea
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ec005eae6e
ℹ️ 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 data = try? Data(contentsOf: store), | ||
| let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], | ||
| let queue = object["progressQueue"] as? [Any] else { return [] } |
There was a problem hiding this comment.
Abort removal when a legacy store cannot be read
When an existing store.json is temporarily unreadable—such as during a protected-data background launch—this guard treats its progress queue as empty. If directory operations still succeed, remove() then moves and deletes the source tree and records the migration as complete, permanently discarding unsent watch progress. Distinguish a missing queue from a failed store read/parse and leave the migration incomplete so a later launch can retry.
Useful? React with 👍 / 👎.
34e0370 to
8c8d7f8
Compare
Downloads saved before the move to /api/v2 hold v1 identifiers, URLs and resume data, and the store loader turned any file it could not decode into an empty registry that the next save wrote over the original. On first launch of this version, DownloadManager cancels every task left in the background download session, then deletes the whole downloads root (stores, media, manifests, artwork, subtitles, resume data and staging) and writes a marker inside the new root so the removal never runs again. Every scope activation waits for this step. When the old storage held at least one download, the app shows one alert: "Downloads from earlier versions were removed. Download them again to watch offline." DownloadStore.load() now renames an undecodable store to store.json.corrupt-<uuid> before returning an empty registry. If the file cannot be read or renamed, saves for that scope are skipped until a later load succeeds. Stack-PR: W1-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The server keeps listing the download rows that earlier versions registered for this device. After the removal, the store knew none of them, so the first reconcile imported every one. Rows the device had reported as completed or downloading mapped to `.registering`, which nothing leaves, and showed a permanent "Preparing download" spinner with only Cancel. Rows in `ready` were queued and downloaded again without any user action. The removal marker now records when the removal ran. Reconcile deletes unknown server rows created before that time instead of importing them, which also frees the device's server quota. A failed delete is retried by the next reconcile, and the deletes stop if the active account changes. Server rows in `downloading` or `completed` now map to `.queued`, because the server still serves their file, so a record rebuilt from one can download instead of getting stuck. Stack-PR: W1-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The one-time removal of earlier versions' downloads had four gaps: - It deleted store.json progressQueue entries the old build never uploaded. The removal now reads each <server>/<profile>/store.json with JSONSerialization (so an undecodable store still gives up its queue), keeps the newest entry per item and writes it into a fresh store for the same scope, where the next online flush uploads it. - It classified server rows as legacy by comparing their createdAt with a device-clock removal date. A lost marker (reinstall, restore to a new device) produced a new date and turned every row this version had registered into "legacy", and clock skew misjudged rows near the cutoff. The fresh stores the removal writes now carry legacyRowsPending instead: the scope's first complete registry read deletes every row the store doesn't know, later reads import. Scopes no earlier version wrote, including every scope after a reinstall, are never flagged. The DELETEs persist in pendingServerDeletes until a read no longer lists the row. - A removal that failed left no date, so reconcile re-imported and re-downloaded the whole old library. The removal now reports whether it completed; when it didn't, reconcile imports no unknown row for the rest of the process and the next launch retries. - A failed marker write skipped deleting the moved-aside tree. Once the carried stores are written, the old trees are deleted even if the marker write fails. Stack-PR: W1-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
ec005ea to
272c273
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 272c273944
ℹ️ 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".
| self.file.pendingServerDeletes?.remove(id) | ||
| if self.file.pendingServerDeletes?.isEmpty == true { self.file.pendingServerDeletes = nil } |
There was a problem hiding this comment.
Retain tombstones until a list confirms deletion
When two lifecycle callers overlap reconcileWithServer, one list request can capture a legacy row before the first caller's DELETE but resume afterward. Removing the ID from pendingServerDeletes as soon as DELETE succeeds means that delayed response no longer filters the row; because legacyRowsPending has already been cleared, the row is imported again and queued for download. Keep the tombstone until a subsequent registry read omits the ID, as the filtering logic at the start of reconciliation expects.
Useful? React with 👍 / 👎.
| let unknownRows = Self.partitionUnknownRows( | ||
| rows.filter { file.records[$0.id] == nil }, | ||
| legacyRowsPending: file.legacyRowsPending == true |
There was a problem hiding this comment.
Block registration until legacy rows are classified
On the first post-upgrade activation, refreshCapability() enables the download UI before this registry read finishes. If a user starts a download and its POST commits server-side while the response is still pending, this concurrent list can see the new row before requestDownload has inserted it locally; the row is therefore classified as legacy here and subsequently deleted. Prevent new registrations until the initial legacy classification completes, or otherwise exclude in-flight registrations from this deletion pass.
Useful? React with 👍 / 👎.
| let removal = await store.removeLegacyStorage() | ||
| legacyDownloadsNoticePending = removal.hadDownloads | ||
| legacyRemovalIncomplete = !removal.completed |
There was a problem hiding this comment.
Stop activation after an incomplete legacy removal
When removeLegacyStorage() reports completed == false because moving, rebuilding, or marking the tree failed, activation still continues and the one-shot task prevents another attempt during this process. If storage later becomes writable, the user can create downloads in the unmarked root, but the next launch sees the marker still missing and removes those newly created downloads as legacy. Keep downloads disabled after an incomplete removal or preserve enough state to distinguish files written afterward.
Useful? React with 👍 / 👎.
Problem
Downloads saved by earlier versions hold v1 identifiers, v1 URLs and v1 resume data. The owner chose to delete them rather than migrate them (decision D1). The server also keeps listing the download rows those versions registered for this device, so a plain local delete would bring them back on the next reconcile. Separately,
DownloadStore.load()returned an empty registry whenever it could not decode the store, and the next save then overwrote the user's offline library.Solution
One-time removal. Every scope activation in
DownloadManagernow waits on a one-shot step. If the markerSiloDownloads/.legacy-downloads-removedis missing, the step:SiloDownloadsroot aside in one rename (stores, media, manifests, artwork, subtitles,resume.binand staging);<server>/<profile>/scope the old tree held, writes the marker, and deletes the moved-aside tree.The marker lives inside the root, so it can only be missing when the root holds nothing this version wrote, and a repeat run never deletes a download made after the upgrade. If a run stops after the rename, the next launch reads the moved-aside tree too, so neither the notice nor the queued progress is lost. The old tree is deleted even when only the marker write fails.
Unsent offline progress is kept. The removal reads each old
store.jsonwithJSONSerialization, so a store that no longer decodes still gives up itsprogressQueue. It keeps the newest entry per item and writes it into the scope's fresh store, where the next online flush uploads it.Notice. When the old storage held at least one download (a download directory, or a store with records), the app shows one alert on iOS and macOS: "Downloads from earlier versions were removed. Download them again to watch offline." The marker records whether the notice is still pending, and dismissing the alert clears it. Empty scopes and stores holding only capability data do not trigger the notice.
Server rows from earlier versions. Each fresh store the removal writes carries
legacyRowsPending. That scope's first complete registry read inreconcileWithServertreats every row the store doesn't know as an earlier version's row: it records the id inpendingServerDeletesand sendsDELETEinstead of importing it. Later reads import unknown rows as before. Scopes the earlier version never wrote, including every scope after a reinstall, are never flagged, and no server timestamp is compared with the device clock. Without this, rows the device had reported ascompletedordownloadingcame back stuck in.registering(a permanent "Preparing download" spinner with only Cancel), andreadyrows downloaded again without any user action. The deletes also free the device's server quota.pendingServerDeletesis persisted before sending. A failedDELETEis retried by the next reconcile, and a row drops out of the set once a complete read no longer lists it. Rows in the set are hidden from reconcile until then. The sends stop if the active scope changes, and reconcile discards a read that finishes after a scope switch.Imported rows can always download.
mapInitialStatusmaps serverdownloadingandcompletedto.queued, likeready, because the server still serves their file (repo.gogates file delivery onready,downloadingandcompleted). A record rebuilt from such a row, for example after a store quarantine, now downloads instead of getting stuck in.registering.Store quarantine.
DownloadStore.load()renames an undecodablestore.jsontostore.json.corrupt-<uuid>before returning an empty registry. If the file exists but cannot be read, or cannot be renamed,save()skips that scope until a later load succeeds, so the original file is never overwritten.DownloadStoretakes an injectable root directory for tests.DownloadFilePaths.scopeDirectory/storeFileURLaccept an optional root.This PR owns no inventory rows. Its only network call is the existing v1
DELETE /api/v1/downloads/{id}(deleteDownloadRow), sent for the old server rows. W3-B moves that call to v2.Validation
LegacyDownloadStorageTests,DownloadGroupingTestsandOfflinePlaybackMappingTests.LegacyDownloadStorageTestscovers:completedanddownloadingmapping to.queued;scripts/ci/check-no-api-v1.shpassed.partitionUnknownRows); no test drivesreconcileWithServeragainst a stubbed server.Risks and follow-ups
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 22 of 50 in the Apple API v2 stack. Base:
apiv2-stack/21-onboarding-tour-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code