Skip to content

feat(downloads): remove downloads saved by earlier versions - #370

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/22-remove-earlier-downloads
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/22-remove-earlier-downloads

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

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 DownloadManager now waits on a one-shot step. If the marker SiloDownloads/.legacy-downloads-removed is missing, the step:

    1. cancels every task in the background download session, including tasks an earlier version started;
    2. moves the whole SiloDownloads root aside in one rename (stores, media, manifests, artwork, subtitles, resume.bin and staging);
    3. recreates the root, writes a fresh store for each <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.json with JSONSerialization, so a store that no longer decodes still gives up its progressQueue. 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 in reconcileWithServer treats every row the store doesn't know as an earlier version's row: it records the id in pendingServerDeletes and sends DELETE instead 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 as completed or downloading came back stuck in .registering (a permanent "Preparing download" spinner with only Cancel), and ready rows downloaded again without any user action. The deletes also free the device's server quota.

    • pendingServerDeletes is persisted before sending. A failed DELETE is 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.
    • If this launch's removal did not complete, reconcile imports no unknown row for the rest of the process. The next launch retries the removal.
  • Imported rows can always download. mapInitialStatus maps server downloading and completed to .queued, like ready, because the server still serves their file (repo.go gates file delivery on ready, downloading and completed). 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 undecodable store.json to store.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.

  • DownloadStore takes an injectable root directory for tests. DownloadFilePaths.scopeDirectory/storeFileURL accept 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

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS and tvOS: LegacyDownloadStorageTests, DownloadGroupingTests and OfflinePlaybackMappingTests.
  • LegacyDownloadStorageTests covers:
    • the removal deleting the store, media, resume data and staging, writing the marker, and running only once (a store saved afterwards survives a later launch);
    • no notice for a root with only empty scopes or capability-only stores, for a fresh install, or for queued progress without downloads;
    • queued progress surviving the removal, including from a store that no longer decodes;
    • a failed marker write still freeing the old tree and reporting the removal as incomplete;
    • an interrupted run finishing the delete and keeping the notice;
    • an acknowledged notice staying dismissed after relaunch;
    • the first read of a carried scope dropping every unknown row, and later reads importing them;
    • server completed and downloading mapping to .queued;
    • an undecodable store renamed aside with its bytes intact, and a store that cannot be renamed never overwritten.
  • 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.
  • Not run: a manual upgrade over a device with completed and paused downloads. The alert, the background-task cancellation and the server-row deletes have not been checked on a device or simulator. The row split is tested as a pure function (partitionUnknownRows); no test drives reconcileWithServer against a stubbed server.

Risks and follow-ups

  • The first read of a carried scope deletes every unknown row. A row registered for this device between the removal and that read (for example by a series monitor) is deleted rather than imported. The next subscription sync registers it again.
  • Download monitors from earlier versions stay active. Series monitors live on the server and this PR doesn't touch them. After their old rows are deleted, the next subscription sync registers the covered episodes again, and they download on their own. Whether to remove old monitors is a product decision for W3-D.
  • An incomplete removal. If the removal fails (the rename and the in-place delete both fail, or a fresh store or the marker can't be written), the error is logged and the app continues without importing unknown server rows. The next launch retries, and that retry would also delete downloads made in the failed session. This needs a filesystem that refuses writes inside the app container.
  • A store that exists but can't be read (for example before first unlock) keeps saves off for that scope for the rest of the process, so changes made in that session are not persisted.
  • Open PR fix(downloads): retarget store on profile and server switch #181 (download retarget) touches DownloadManager.swift. Whichever lands second rebases.
  • After this PR, W3-B and W3-C can change the store and manifest formats without a migration. A build that has this PR but predates those changes will quarantine its store on upgrade instead of losing it.

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

@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: 89a07d8d-ef61-4280-b10d-fd328292259f

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:43:29.383082Z 272c273 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: cccf18f9 (apiv2-stack/22-remove-earlier-downloads).

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:

  • blocking: After the removal, the first reconcile brings back every old server download: finished ones as stuck "Preparing" rows and unfinished ones as automatic re-downloads
  • whole-stack review: The D1 wipe deletes offline watch progress the old build never uploaded
  • whole-stack review: When the marker is lost, the app hides and stops syncing monitors, and deletes server rows, that this version created
  • whole-stack review: A failed removal leaves no removal date, so reconcile re-imports and re-downloads every legacy row
  • whole-stack review: Legacy classification compares server createdAt with the device clock

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

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

@Quick104
Quick104 force-pushed the apiv2-stack/22-remove-earlier-downloads branch from cccf18f to ec005ea 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: 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".

Comment on lines +179 to +181
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 [] }

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

@Quick104
Quick104 force-pushed the apiv2-stack/21-onboarding-tour-v2 branch from 34e0370 to 8c8d7f8 Compare September 23, 2026 13:38
Quick104 and others added 3 commits September 23, 2026 09:38
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]>
Base automatically changed from apiv2-stack/21-onboarding-tour-v2 to main September 23, 2026 13:38
@Quick104
Quick104 force-pushed the apiv2-stack/22-remove-earlier-downloads branch from ec005ea to 272c273 Compare September 23, 2026 13:38
@Quick104
Quick104 merged commit 3b43e64 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/22-remove-earlier-downloads branch September 23, 2026 13:38

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

Comment on lines +1379 to +1380
self.file.pendingServerDeletes?.remove(id)
if self.file.pendingServerDeletes?.isEmpty == true { self.file.pendingServerDeletes = nil }

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

Comment on lines +1318 to +1320
let unknownRows = Self.partitionUnknownRows(
rows.filter { file.records[$0.id] == nil },
legacyRowsPending: file.legacyRowsPending == true

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

Comment on lines +477 to +479
let removal = await store.removeLegacyStorage()
legacyDownloadsNoticePending = removal.hadDownloads
legacyRemovalIncomplete = !removal.completed

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

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