Skip to content

feat(downloads): re-read watch state from v2 progress - #375

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/27-progress-reread-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/27-progress-reread-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Offline watch state now comes from a bounded full read of GET /api/v2/progress, and delete_watched removes 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/progress rejects since with 422 and only pages the full set, newest change first. The pulled state feeds localProgress, which drives isWatched, offline resume positions and client-side delete_watched. The old code also ran delete_watched after 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:) (in APIv2Client+Progress.swift) reads every page under the captured owner, inside withOwnerFence, with limit=200 (the server maximum) and at most 100 pages (20,000 entries). The read throws ProgressReadError.incompleteRead if 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() replaces pullProgressDeltas(). It captures the download scope owner, runs the read, and applies the result only if that scope is still current.
    • mergeProgress keeps whichever side has the later updated_at, completed included, so an unwatch on another device reaches this one. The old merge only ever turned completed on.
    • An entry missing from a complete read has no progress on the server (cleared or marked unwatched), so it is dropped, unless it is still in the offline upload queue (pending or held) or was written on this device during the read.
    • Only the leaf items of this device's download records and queued uploads are stored. The rest of the profile's history is discarded, so localProgress no longer grows with the watch history.
  • Fewer reads. The run skips the read when the scope has no download record and nothing queued. It also reuses a complete read from the same scope for 10 minutes (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_watched gate. runMonitoringAndProgressSync runs delete_watched only 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) and retentionDeletions (read applied and owner still current → ids to delete, otherwise none).
  • A finished download no longer starts delete_watched on 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.
  • recordOfflineProgress is unchanged and stays local-first. The offline upload path (flushProgressQueue, W2-S) still runs before the read.
  • Deleted: SiloAPI.pullProgressDeltas(since:) together with DownloadAPI.swift (its last method), the v1 ProgressPullResponse/ProgressPullItem models, and the persisted DownloadStoreFile.progressCursor. Store files that still contain progressCursor decode, because JSONDecoder ignores the extra key. D1 already allows the store format to change without migration.
  • This PR does not use ProgressBootstrapStore or the bootstrap snapshot operations. Android has no equivalent, because it does not read /progress.
  • Owner-fence lines in iosApp/iosApp go from 63 to 64.

Read outcomes

Outcome Behavior
Complete read (every page 200, final page has_more:false) Merge by updated_at for this device's downloads and queued uploads, drop entries the server no longer holds (except queued or just-written ones), persist, then run delete_watched.
Definite failure (non-200, problem document, 422, 410 or update required, broken paging, page bound reached) Nothing applied, nothing deleted. Logged. Retried on the next run.
Uncertain (transport failure mid-read, owner or scope changed) Same as a definite failure. The read has no side effects on the server.

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS (WatchStateV2Tests, LegacyDownloadStorageTests, ProgressSyncV2Tests, CatalogV2Tests, APIv2ContractTests, DownloadSubscriptionsV2Tests, DownloadRegistryV2Tests, DownloadDeliveryV2Tests, OfflinePlaybackMappingTests) and on tvOS (WatchStateV2Tests, LegacyDownloadStorageTests, ProgressSyncV2Tests, CatalogV2Tests, DownloadSubscriptionsV2Tests).
  • scripts/ci/check-no-api-v1.sh passed. DownloadAPI.swift no longer exists, so its v1 count is 0.
  • New WatchStateV2Tests use StubURLProtocol through APIv2TestStub. They cover:
    • paging with limit=200, the cursor, X-Profile-Id and no since; broken or interrupted reads that must throw; the 100-page bound; dispatch refused after an owner change;
    • the merge rules, and that only entries of downloads and queued uploads are stored;
    • no read without downloads or queued uploads, and reuse of a recent read until a new item needs it;
    • the delete_watched gate, 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.
  • Temporarily removing either gate check (applying an interrupted read, or ignoring the owner check) made four assertions fail.
  • The tests call the gate functions directly, not runMonitoringAndProgressSync (a private-init singleton). A new direct call that deletes downloads outside retentionDeletions would not be caught.
  • LegacyDownloadStorageTests now round-trips pendingServerDeletes instead of the removed progressCursor.
  • 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: the manual check on a signed simulator (watch an episode on another device, foreground the app, and confirm a monitored delete_watched episode is removed only after an online refresh).

Risks and follow-ups

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

@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: 13e0f03b-661b-4238-829c-4abc4c6e8363

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:46:18.688939Z 0ae7311 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: 7f4f9d5f (apiv2-stack/27-progress-reread-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:

  • minor: The 'interrupted read deletes nothing' test never runs the delete_watched gate
  • whole-stack review: runtime-progress-read

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

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

@Quick104
Quick104 force-pushed the apiv2-stack/26-download-subscriptions-v2 branch from 6f52e94 to d9eeef8 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/27-progress-reread-v2 branch from 7f4f9d5 to 64e5328 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/26-download-subscriptions-v2 branch from d9eeef8 to be2aba0 Compare September 23, 2026 13:40
Base automatically changed from apiv2-stack/26-download-subscriptions-v2 to main September 23, 2026 13:40
Quick104 and others added 3 commits September 23, 2026 09:40
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]>
@Quick104
Quick104 force-pushed the apiv2-stack/27-progress-reread-v2 branch from 64e5328 to 0ae7311 Compare September 23, 2026 13:40
@Quick104
Quick104 merged commit 9872cec into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/27-progress-reread-v2 branch September 23, 2026 13:40

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

Comment on lines +46 to +48
guard page.page.hasMore else {
guard page.page.nextCursor?.isEmpty ?? true else { throw ProgressReadError.incompleteRead }
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 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 👍 / 👎.

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