Repository navigation
feat(downloads): re-read watch state from v2 progress - #375
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:
Note: With downloads present, a foreground more than 10 minutes after the last read still pages through the whole progress history (about 70 requests for a long history), because v2 has no delta or per-item progress read. 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: 7f4f9d5f0a
ℹ️ 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".
| to: file, | ||
| readStartedAt: startedAt | ||
| ) else { return nil } | ||
| lastWatchStateRead = (owner.scope, startedAt, itemIds) |
There was a problem hiding this comment.
Cache only item IDs retained after the read
If a user deletes a download while listAllProgress is awaiting, applyWatchStateRead filters that item's progress out using the current file, but this assignment still records the pre-request itemIds as cached. If the same item is downloaded again within 10 minutes, watchStateReadNeeded treats it as covered and skips the request even though its progress was discarded, leaving resume, watched status, and delete_watched stale until the cache expires. Record the post-merge/current item set or otherwise invalidate coverage for items removed during the read.
Useful? React with 👍 / 👎.
6f52e94 to
d9eeef8
Compare
7f4f9d5 to
64e5328
Compare
d9eeef8 to
be2aba0
Compare
Offline watch state still came from GET /api/v1/progress?since=, which Silo 1.0 retires. v2 has no delta read: GET /api/v2/progress rejects since with 422 and only pages the full set. The same state drives isWatched, offline resume and delete_watched, and delete_watched ran even when the pull had failed. Each monitoring run now reads the profile's whole progress through GET /api/v2/progress under the scope owner: 200 entries per page, at most 100 pages, and any read that ends early, repeats a cursor or item, or overruns the bound throws instead of returning a prefix. A complete read merges by updated_at (the later side wins, completed included) and drops entries the server no longer holds unless this device queued or wrote them during the read. delete_watched runs only after a complete read in the same run, so an interrupted read never removes a file; a finished download no longer triggers it on its own. The persisted progressCursor, the v1 delta models and DownloadAPI.swift are gone. Stack-PR: W3-E Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The test for "an interrupted read deletes nothing" only re-checked a value nothing had touched, so removing the gate that keeps a failed or partial read from deleting downloads left every test passing. The post-read decisions now live in two static functions that the monitoring run calls: applyWatchStateRead returns the merged watch state only for a complete read whose owner is still current, and retentionDeletions returns delete_watched ids only when that read was applied and its owner is still current. Tests start from an episode already marked watched, so a missing gate would delete it, and cover an interrupted read, an owner change, and a complete read. Stack-PR: W3-E Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every monitoring run re-read the profile's whole progress history, even with no downloads on the device, and merged all of it into localProgress. On an admin profile with about 13,600 entries that was 68 sequential GET /api/v2/progress requests (about 12 s) per run, and the store grew with the watch history. The run now skips the read when there is no download record and nothing queued, and the merge keeps only the leaf items of download records and queued uploads, pruning the rest. A complete read is also reused for 10 minutes in the same scope unless a new download or queued upload needs an item it did not cover: v2 has no per-item or delta read, so each read costs one request per 200 history entries. delete_watched still acts only on a complete read applied in the same run. Stack-PR: W3-E Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
64e5328 to
0ae7311
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0ae7311469
ℹ️ 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 page.page.hasMore else { | ||
| guard page.page.nextCursor?.isEmpty ?? true else { throw ProgressReadError.incompleteRead } | ||
| return entries |
There was a problem hiding this comment.
Do not treat a moving cursor scan as a snapshot
When progress changes during a multi-page read—for example, an item on a later page receives a newer updated_at—that item moves ahead of the already-consumed newest-first cursor and can be omitted without repeating an ID or cursor. This path nevertheless returns success, after which refreshWatchState treats the missing item as cleared, persists the loss of its resume/watched state, and caches the read for ten minutes. The contract fixture’s cursor contains only the ordering timestamp and media ID, not a snapshot identifier, so completeness requires server-side snapshot semantics or client-side handling that does not interpret absence destructively.
AGENTS.md reference: AGENTS.md:L13-L15
Useful? React with 👍 / 👎.
Offline watch state now comes from a bounded full read of
GET /api/v2/progress, anddelete_watchedremoves files only after that read completes in the same run.Problem
Offline downloads learned watch state from other devices through
GET /api/v1/progress?since=(row 102), which Silo 1.0 retires. v2 has no delta read:GET /api/v2/progressrejectssincewith 422 and only pages the full set, newest change first. The pulled state feedslocalProgress, which drivesisWatched, offline resume positions and client-sidedelete_watched. The old code also randelete_watchedafter every monitoring run and after every finished download, whether or not the pull had succeeded.Solution
Decision D2: a bounded full paged re-read.
APIv2Client.listAllProgress(auth:)(inAPIv2Client+Progress.swift) reads every page under the captured owner, insidewithOwnerFence, withlimit=200(the server maximum) and at most 100 pages (20,000 entries). The read throwsProgressReadError.incompleteReadif it ends early, lacks page info, repeats a cursor or item, or hits the page bound. It never returns a prefix. Transport and HTTP errors propagate as they do for other v2 reads.DownloadManager.refreshWatchState()replacespullProgressDeltas(). It captures the download scope owner, runs the read, and applies the result only if that scope is still current.mergeProgresskeeps whichever side has the laterupdated_at,completedincluded, so an unwatch on another device reaches this one. The old merge only ever turnedcompletedon.localProgressno longer grows with the watch history.watchStateReadInterval), unless a new download or queued upload needs an item that read did not cover. Before this, a profile with about 13,600 entries cost 68 sequential requests (about 12 s) on every run.delete_watchedgate.runMonitoringAndProgressSyncrunsdelete_watchedonly when this run applied a complete read and its scope is still current. A failed, partial, skipped or reused read deletes nothing. Two static functions hold this gate so tests can drive it:applyWatchStateRead(read outcome and owner check → merged watch state, or nil) andretentionDeletions(read applied and owner still current → ids to delete, otherwise none).delete_watchedon its own, because the progress behind that check could be stale. The next monitoring run that reads the watch state removes an already-watched episode.recordOfflineProgressis unchanged and stays local-first. The offline upload path (flushProgressQueue, W2-S) still runs before the read.SiloAPI.pullProgressDeltas(since:)together withDownloadAPI.swift(its last method), the v1ProgressPullResponse/ProgressPullItemmodels, and the persistedDownloadStoreFile.progressCursor. Store files that still containprogressCursordecode, becauseJSONDecoderignores the extra key. D1 already allows the store format to change without migration.ProgressBootstrapStoreor the bootstrap snapshot operations. Android has no equivalent, because it does not read/progress.iosApp/iosAppgo from 63 to 64.Read outcomes
has_more:false)updated_atfor this device's downloads and queued uploads, drop entries the server no longer holds (except queued or just-written ones), persist, then rundelete_watched.Validation
WatchStateV2Tests,LegacyDownloadStorageTests,ProgressSyncV2Tests,CatalogV2Tests,APIv2ContractTests,DownloadSubscriptionsV2Tests,DownloadRegistryV2Tests,DownloadDeliveryV2Tests,OfflinePlaybackMappingTests) and on tvOS (WatchStateV2Tests,LegacyDownloadStorageTests,ProgressSyncV2Tests,CatalogV2Tests,DownloadSubscriptionsV2Tests).scripts/ci/check-no-api-v1.shpassed.DownloadAPI.swiftno longer exists, so its v1 count is 0.WatchStateV2TestsuseStubURLProtocolthroughAPIv2TestStub. They cover:limit=200, the cursor,X-Profile-Idand nosince; broken or interrupted reads that must throw; the 100-page bound; dispatch refused after an owner change;delete_watchedgate, starting from an episode already marked watched locally so a missing gate would delete it: an interrupted read whose first page says "watched" deletes nothing, a complete read whose owner changed deletes nothing, a complete read that says "watched" deletes the download, and a complete read that no longer lists the item keeps it.runMonitoringAndProgressSync(a private-init singleton). A new direct call that deletes downloads outsideretentionDeletionswould not be caught.LegacyDownloadStorageTestsnow round-tripspendingServerDeletesinstead of the removedprogressCursor.delete_watchedepisode is removed only after an online refresh).Risks and follow-ups
delete_watcheddoes not run. The failure is logged. Cross-repo ask S3 (a server progress delta) would remove the full re-read. It is drafted and not published.updated_at. An item whose progress changes on another device during the read moves ahead of the cursor and is missing from that read. Its local entry is then dropped until the next read. This errs toward keeping files: a dropped entry is not "completed", so it cannot trigger a deletion.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 27 of 50 in the Apple API v2 stack. Base:
apiv2-stack/26-download-subscriptions-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code