Repository navigation
feat(progress): upload audiobook and offline progress through v2 sync/progress - #371
Conversation
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. |
|
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 |
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: a7225f5f17
ℹ️ 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".
| try await http.requestData(method: "POST", path: "/api/v2/sync/progress", body: body, | ||
| requestIdentity: identity, expectedAccount: auth.account, expectedAuth: auth, | ||
| dispatchRecord: dispatch) |
There was a problem hiding this comment.
Exclude progress sync from automatic 401 retries
When the access token has expired but refresh succeeds, this generic requestData path consults HTTPClient.shouldAttemptRefresh, which retries 401 responses unless the path is explicitly excluded; /api/v2/sync/progress was not added to that exclusion list. The POST can therefore be dispatched twice even though this endpoint is marked non_retryable, so a server that consumed the first attempt before returning 401 can receive a replay and the queue's single-dispatch outcome guarantees no longer hold.
Useful? React with 👍 / 👎.
| /// active download scope. Each batch is claimed durably before it is | ||
| /// sent, so a batch whose answer never arrives, even across a crash, is | ||
| /// held instead of sent again (see `OfflineProgressQueue`). | ||
| func flushProgressQueue() async { |
There was a problem hiding this comment.
Coalesce concurrent offline progress flushes
When two lifecycle paths call onAppActive concurrently, this @MainActor method can re-enter while the first flush awaits a save or network response. The second invocation sees the first batch as dispatched, claims the next 100 entries, and sends it in parallel; if the server returns a rejection such as 500, both batches are removed, defeating the stated guarantee that one server fault can discard at most one batch. Use a single in-flight drain task so later callers await the existing flush.
Useful? React with 👍 / 👎.
cccf18f to
ec005ea
Compare
a7225f5 to
85e1890
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 85e1890785
ℹ️ 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".
| case APIv2Error.httpStatus(let status): | ||
| return deferredStatuses.contains(status) ? .deferred(error) : .rejected(error) |
There was a problem hiding this comment.
Defer legacy-envelope 410 responses
When the server returns the documented v1-shaped upgrade tombstone (410 with {"error":"client_upgrade_required",...}), mapErrors cannot decode it as APIv2Problem and produces .httpStatus(410). Because 410 is absent from deferredStatuses, this branch classifies the response as rejected, and OfflineProgressQueue.resolve permanently removes the offline batch instead of preserving it until the app is upgraded. Use the existing UpdateRequirement.isClientUpgradeRequired(statusCode:body:) classification before discarding the response body, or otherwise preserve this envelope as deferred.
Useful? React with 👍 / 👎.
ec005ea to
272c273
Compare
…/progress Audiobook resume, the video stale-session recovery write and the offline download queue all posted to POST /api/v1/sync/progress with seconds as doubles. A v2-only server has no such route, so audiobook resume and offline watch progress never reached it. The offline queue also retried a batch whose outcome it never saw, which syncProgress's non_retryable contract forbids. All three callers now go through one APIv2Client.syncProgress in APIv2Client+Progress.swift. It sends integer milliseconds, refuses empty, oversized (more than 100) or duplicate-item batches before dispatch, sends exactly once, and reports one of three outcomes: answered with per-item results matched back by index, rejected (non-success status), not sent (the connection never opened), or uncertain (sent, no usable answer). The offline queue claims each batch durably before sending it. Answered and rejected entries leave the queue; not-sent entries go back to pending; uncertain entries are held and never sent again. A newer offline event for the same item replaces a held entry, and Downloads settings offers "Discard held change". SyncProgressItem and SyncProgressRequest keep their names with the v2 wire shape; the v1 method, batch client and result models are deleted. Stack-PR: W2-S Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The offline flush deleted a batch on every non-success answer, then sent the next batch straight away. A reconnect that met a 503, 429 or 408, or a v1-only server's legacy 404, therefore discarded the whole queue, batch by batch, although the server had applied none of it. The same v1-only server kept the entries when the recorded probe verdict refused the call first. syncProgress now reports those answers, and 410 client_upgrade_required, as a separate deferred outcome. The queue returns deferred entries to pending, like a batch that was never sent, so the next flush sends them. Other whole-batch rejections (400, 403, 404 problem, 422, 500, ...) still delete the batch; a 500 can follow the server's writes, so it is not replayed. The flush now sends another batch only after a 200 answer, so one outage or rejection affects at most one batch. Stack-PR: W2-S Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…2 entries The legacy removal now keeps offline progress the earlier build queued. This branch replaces QueuedProgress.attempts with a dispatch state, so harvested entries are built as pending (a main-era entry was never claimed for a v2 upload), and an entry that already carries a state keeps it. Stack-PR: W2-S Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
progressSyncFailure sent every status outside 408/429/503 to .rejected, so a flush that met an expired session (refresh failed) or a PIN-locked profile without a valid proof deleted up to 100 queued entries. Those answers come before any write and the batch succeeds after re-authentication, so 401 and 403 now defer: the entries go back to pending and the flush after re-auth sends them. Stack-PR: W2-S Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…e sending When a profile switch, sign-out or server switch landed between claiming a batch and sending it, the fence's entry check or HTTPClient's dispatch gate refused the request with the same error a discarded answer gets. The flush then returned on the scope change without resolving, so the entries stayed dispatched in the old scope's store and were held for good although nothing reached the server. HTTPClient.requestData takes an optional HTTPDispatchRecord that perform marks just before the send (moved down from the diagnostics lane). syncProgress passes one and maps an owner-change error with an unmarked record to .notSent; after sending it stays .uncertain. A flush whose scope changed returns never-sent or deferred claims to pending: in the old scope's store file, ordered after queued saves, and in memory when that scope's store is installed again. Stack-PR: W2-S Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
85e1890 to
32ad13c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 32ad13caa4
ℹ️ 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".
| persist() | ||
| await saveChain?.value |
There was a problem hiding this comment.
Verify the progress claim was persisted before dispatch
When the claim save fails—for example because storage is full or protected—DownloadStore.save logs and swallows the error, so awaiting saveChain.value still proceeds to dispatch. If the server applies the request and the app is then terminated before a later save succeeds, the on-disk entries remain pending and are replayed on relaunch, violating this endpoint's non_retryable guarantee. Make the claim save report success and do not send unless the dispatched state is durably stored.
Useful? React with 👍 / 👎.
Problem
Audiobook resume, the video player's stale-session recovery write, and the offline download progress queue all posted to
POST /api/v1/sync/progress, sending positions as seconds in doubles. A v2-only server has no such route. As a result, audiobook positions (the audiobook's only durable resume point, D5) and offline watch progress never reached it.The offline queue had a second problem: when a batch failed at the transport, it sent the same batch again on the next reconnect, even when the server might already have applied it.
syncProgressisx-silo-retry-safety: non_retryable, so an uncertain outcome must never be replayed (plan §9).Solution
APIv2Client.syncProgressinAPIv2Client+Progress.swift, with wire models inAPIv2ProgressSyncModels.swift:POST /api/v2/sync/progresswithX-Profile-Idfrom the captured owner, insidewithOwnerFence.position_ms/duration_ms. Offline events carryupdated_at.media_item_id. The server would reject such a batch as a whole.ProgressSyncOutcome:answered: per-item results matched back to the request byindexandmedia_item_iddeferred: the server answered before writing anything (401, 403, 408, 429, 503, the legacy 404, or 410client_upgrade_required)rejected: any other non-success statusnotSent: the connection was never established, or the request was refused before dispatchuncertain: the request was sent but no usable answer came backHTTPClient.requestDatatakes an optionalHTTPDispatchRecordthatperformmarks just before the request goes to the URL session. An owner change refused by the fence's entry check or the dispatch gate isnotSent. The same error after the send staysuncertain.AudioPlayerViewModel: the periodic sync and the final sync on close.PlaybackSessionBridge.syncProgress: the stale-session recovery write fromPlayerViewModel.DownloadManager.flushProgressQueue: the offline queue.OfflineProgressQueue:dispatchedand the store is saved before the request goes out. If the app dies mid-flight, the entries come back held, not pending.updated_atwins under the server's last-write-wins merge. It is not a replay.QueuedProgressdropsattemptsand gainsstate. Entries stored withoutstatedecode as pending, and progress that W1-D carries over from an earlier version starts as pending.SyncProgressItem/SyncProgressRequestkeep their names but now use the v2 wire shape.SiloAPI.syncProgress,SiloAPI.syncProgressBatch(items:),SyncProgressResultsResponseandSyncProgressResult. This removes rows 83 and 101.APIv2Client'shttp,tokenStore,gate(),requestIdentityandmapErrorsare now internal instead of private, so per-domain extension files can use the shared transport, fences and error mapping.Failure outcomes
successfailure(for example 404 hidden item)client_upgrade_requireddeferred)rejected)notConnectedToInternet,cannotConnectToHost, DNS, TLS trust)dispatched), never re-sent, and the flush stops. The user can discard them, and a newer event for the item replaces them. Audio/video logs, doesn't retry, and the next periodic sync sends a new current positionValidation
ProgressSyncV2Tests,AudiobookProgressTests,APIv2ContractTests,CatalogV2Tests,LegacyDownloadStorageTests,PlaybackProtocolV3Tests,DownloadGroupingTests,DurableCommandStoreTests) and on tvOS (ProgressSyncV2Tests,AudiobookProgressTests,APIv2ContractTests,CatalogV2Tests).scripts/ci/check-no-api-v1.shpassed.ProgressSyncV2Tests(onStubURLProtocolviaAPIv2TestStub) cover:X-Profile-Id, integer ms,updated_at, exact keys) and mixed per-item results returned out of orderstateRisks and follow-ups
APIv2Clientmembers internal touches five declaration lines inAPIv2Client.swift. Another lane that makes the same change will conflict on those lines when the stack is rebased. Keep either side; the result is the same.progress_persistence:"client"on start) and can bind the owner there.DownloadStore.savestill logs write failures without surfacing them, so a failed claim save isn't detected before dispatch. That behavior is unchanged from before this PR.pullProgressDeltas(v1GET /api/v1/progress?since=), which is still live.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 23 of 50 in the Apple API v2 stack. Base:
apiv2-stack/22-remove-earlier-downloads. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code