Skip to content

feat(progress): upload audiobook and offline progress through v2 sync/progress - #371

Merged
Quick104 merged 5 commits into
mainfrom
apiv2-stack/23-sync-progress-v2
Sep 23, 2026
Merged

Quick104 merged 5 commits into
mainfrom
apiv2-stack/23-sync-progress-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

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. syncProgress is x-silo-retry-safety: non_retryable, so an uncertain outcome must never be replayed (plan §9).

Solution

  • Added APIv2Client.syncProgress in APIv2Client+Progress.swift, with wire models in APIv2ProgressSyncModels.swift:
    • It sends POST /api/v2/sync/progress with X-Profile-Id from the captured owner, inside withOwnerFence.
    • Positions go out as integer position_ms/duration_ms. Offline events carry updated_at.
    • Before dispatch it refuses a batch that is empty, has more than 100 items, or repeats a media_item_id. The server would reject such a batch as a whole.
    • It sends exactly once and returns a ProgressSyncOutcome:
      • answered: per-item results matched back to the request by index and media_item_id
      • deferred: the server answered before writing anything (401, 403, 408, 429, 503, the legacy 404, or 410 client_upgrade_required)
      • rejected: any other non-success status
      • notSent: the connection was never established, or the request was refused before dispatch
      • uncertain: the request was sent but no usable answer came back
    • A 200 whose results don't map one-to-one onto the request counts as uncertain.
    • HTTPClient.requestData takes an optional HTTPDispatchRecord that perform marks just before the request goes to the URL session. An owner change refused by the fence's entry check or the dispatch gate is notSent. The same error after the send stays uncertain.
  • Switched the three callers:
    • AudioPlayerViewModel: the periodic sync and the final sync on close.
    • PlaybackSessionBridge.syncProgress: the stale-session recovery write from PlayerViewModel.
    • DownloadManager.flushProgressQueue: the offline queue.
  • The offline queue rules live in the new OfflineProgressQueue:
    • Each batch has at most 100 distinct items. It is marked dispatched and the store is saved before the request goes out. If the app dies mid-flight, the entries come back held, not pending.
    • The results are applied only if the download scope (server, profile, scope generation) is unchanged. If the scope changed, never-sent and deferred entries go back to pending in the old scope's store file, and in memory when that scope's store is loaded again.
    • The flush sends the next batch only after a 200 answer. Any other outcome stops it, so one outage or rejection affects at most one batch.
    • A newer offline event for the same item replaces a held entry. The new entry is a fresh write whose later updated_at wins under the server's last-write-wins merge. It is not a replay.
    • Downloads settings (iOS/macOS) shows an "Offline Progress" section with "Discard held change" while any entry is held.
  • QueuedProgress drops attempts and gains state. Entries stored without state decode as pending, and progress that W1-D carries over from an earlier version starts as pending.
  • SyncProgressItem/SyncProgressRequest keep their names but now use the v2 wire shape.
  • Deleted SiloAPI.syncProgress, SiloAPI.syncProgressBatch(items:), SyncProgressResultsResponse and SyncProgressResult. This removes rows 83 and 101.
  • APIv2Client's http, tokenStore, gate(), requestIdentity and mapErrors are now internal instead of private, so per-domain extension files can use the shared transport, fences and error mapping.

Failure outcomes

Path Outcome Behavior
200 with matching results, item success Definite success Offline entry removed. Audio/video logs nothing
200 with matching results, item failure (for example 404 hidden item) Definite failure Offline entry removed and logged. Not re-sent
401 (refresh failed), 403 (missing or stale profile proof), 408, 429, 503, legacy 404 (server update required), or 410 client_upgrade_required Definite failure, nothing applied (deferred) Offline entries go back to pending and the flush stops. They go out again on the next flush, for example after re-authentication. Audio/video logs and returns false
Any other non-2xx (400, 404 problem, 413, 415, 422, 500, ...) Definite failure (rejected) Batch removed from the queue and logged once. The flush stops. A 500 can follow the server's writes, so it is not replayed. Audio/video logs and returns false
Invalid batch, owner mismatch or owner change before dispatch, update-required gate, or cancellation before dispatch Definite failure (never sent) Nothing sent. Offline entries go back to pending, in the old scope's store if the scope changed
URLError before connecting (notConnectedToInternet, cannotConnectToHost, DNS, TLS trust) Definite failure (never sent) Offline entries go back to pending. The flush stops
Timeout, lost connection, cancellation after send, owner change noticed after the send, 2xx other than 200, or an unmatched 200 body Uncertain Offline entries are held (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 position
App killed after the claim was saved Uncertain Entries come back held on relaunch

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS (ProgressSyncV2Tests, AudiobookProgressTests, APIv2ContractTests, CatalogV2Tests, LegacyDownloadStorageTests, PlaybackProtocolV3Tests, DownloadGroupingTests, DurableCommandStoreTests) and on tvOS (ProgressSyncV2Tests, AudiobookProgressTests, APIv2ContractTests, CatalogV2Tests).
  • scripts/ci/check-no-api-v1.sh passed.
  • The new ProgressSyncV2Tests (on StubURLProtocol via APIv2TestStub) cover:
    • the wire shape (path, X-Profile-Id, integer ms, updated_at, exact keys) and mixed per-item results returned out of order
    • refusal of duplicate, empty and 101-item batches without dispatch
    • permanent rejections versus deferred answers, including an expired session whose refresh fails, with one request each
    • lost connection and timeout as uncertain with one request only, connection refused as not sent, and unmatched 200 bodies as uncertain
    • owner changes before dispatch, inside the client before sending, at the dispatch gate (not sent), and after sending (uncertain)
    • claims of a batch that never left released in the old scope's store
    • the queue's hold, supersede, discard, release and chunking rules, and that the flush sends another batch only after a 200 answer
    • decoding a stored entry that has no state
  • 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 offline watch followed by a reconnect against a real server, and an audiobook play, kill and relaunch.

Risks and follow-ups

  • Making the APIv2Client members internal touches five declaration lines in APIv2Client.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.
  • Audio and video writes capture the current owner when they send, not the owner that started playback. W2-B reworks the audio session (progress_persistence:"client" on start) and can bind the owner there.
  • Held offline entries stay in their own scope's store across sign-out and server or profile switches. They block no other write, so they are not barriers. They clear when the user discards them or plays the item offline again.
  • DownloadStore.save still logs write failures without surfacing them, so a failed claim save isn't detected before dispatch. That behavior is unchanged from before this PR.
  • W3-E replaces pullProgressDeltas (v1 GET /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

@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:20.715270Z 32ad13c 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.

@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: 8bf65cdd-041e-4895-a6db-a3c627f6dac0

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.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: a7225f5f (apiv2-stack/23-sync-progress-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: A transient 503/429/408 permanently deletes queued offline progress, and the flush keeps going and deletes every later batch too
  • whole-stack review: Offline progress batches are deleted on 401/403 even though the server applied nothing
  • whole-stack review: Offline progress that was never sent is held permanently when the scope or owner changes between claim and dispatch

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

Comment on lines +45 to +47
try await http.requestData(method: "POST", path: "/api/v2/sync/progress", body: body,
requestIdentity: identity, expectedAccount: auth.account, expectedAuth: auth,
dispatchRecord: dispatch)

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

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

@Quick104
Quick104 force-pushed the apiv2-stack/22-remove-earlier-downloads branch from cccf18f to ec005ea Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/23-sync-progress-v2 branch from a7225f5 to 85e1890 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: 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".

Comment on lines +103 to +104
case APIv2Error.httpStatus(let status):
return deferredStatuses.contains(status) ? .deferred(error) : .rejected(error)

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

@Quick104
Quick104 force-pushed the apiv2-stack/22-remove-earlier-downloads branch from ec005ea to 272c273 Compare September 23, 2026 13:38
Base automatically changed from apiv2-stack/22-remove-earlier-downloads to main September 23, 2026 13:38
Quick104 and others added 5 commits September 23, 2026 09:38
…/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]>
@Quick104
Quick104 force-pushed the apiv2-stack/23-sync-progress-v2 branch from 85e1890 to 32ad13c Compare September 23, 2026 13:38
@Quick104
Quick104 merged commit f6c1aa1 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/23-sync-progress-v2 branch September 23, 2026 13:39

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

Comment on lines +1625 to +1626
persist()
await saveChain?.value

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

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