Skip to content

feat(downloads): sync download subscriptions through v2 - #374

Merged
Quick104 merged 4 commits into
mainfrom
apiv2-stack/26-download-subscriptions-v2
Sep 23, 2026
Merged

Quick104 merged 4 commits into
mainfrom
apiv2-stack/26-download-subscriptions-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Series monitoring (download subscriptions) now runs on /api/v2: create, edit, stop and sync. Edits and deletes are guarded by the monitor's validator, and sync pages each monitor separately.

Problem

Series monitoring still called four v1 routes (inventory rows 97-100): POST /api/v1/downloads/subscriptions, POST .../subscriptions/sync, PATCH .../subscriptions/{id} and DELETE .../subscriptions/{id}. The v2 contract differs in ways a path swap can't handle:

  • syncDownloadSubscription syncs one monitor per call, one page at a time, with body {subscription_id, etag}. It answers 409 when the monitor changed. v1 synced every monitor in one bodiless call.
  • updateDownloadSubscription and deleteDownloadSubscription require If-Match. A missing header gets 428 and a stale validator gets 412. The app stored no validator: ServerSubscription and DownloadSubscription had no etag.
  • createDownloadSubscription is non_retryable. It returns the bare monitor (no registered count). For a series this device already monitors, it returns that monitor unchanged.
  • Every monitor call requires X-Silo-Device-Id.

Solution

  • Client. New APIv2Client+DownloadSubscriptions.swift and APIv2DownloadSubscriptionModels.swift hold the monitor calls: list, get, create, update, delete and sync. They reuse the download lane's owner-fenced transport (downloadRegistryRequest, now internal with a headers parameter), so every call goes through withOwnerFence and sameCredentialIdentity. HTTPClient still adds X-Silo-Device-Id to every request. Each method asserts its status (200, or 204 for delete). It also checks that the answer describes the requested monitor or series.
  • List. Bounded paging (100 per page, 100 pages). A short, repeated or unusable page throws, so an incomplete read never drops a local monitor.
  • Create. Sent exactly once. After an uncertain outcome the app reads the monitor list instead of sending again. If the create returns an existing monitor with different options, the app applies the requested options with a PATCH. A successful create then syncs that monitor and reconciles the registry. A create first waits for a monitor DELETE already on the wire. If a delete pass that starts during the create removes the monitor the create answered with, the app sends one fresh create: the first create had a definite answer, so this is a new request, not a resend. If the follow-up sync finds the monitor gone, the sheet shows "Silo couldn't confirm the monitoring change…".
  • Update and delete. Both send the stored validator as If-Match. A monitor stored without one is read first. A 412 (or the 409 of a concurrent edit) reads the monitor again and applies the same change once more under the new validator. A second 412 is surfaced. A 428 is logged as a fault and never retried. A delete that gets 404 counts as done.
  • Sync. runMonitoringAndProgressSync runs when the capability allows series monitoring. It first sends pending monitor deletes, then lists the monitors and replaces the local list. Local titles stay, and a stopped monitor stays hidden while its DELETE is pending. A list read describes the server as it was when the read started, so the merge also leaves out monitors whose DELETE landed during the read and keeps monitors a create answered with during the read (SubscriptionWriteLedger, keyed by a write generation). It then pages each active monitor with the validator captured before the first page. A page with no answer (connection lost, 5xx) is sent again up to twice, with the same validator and cursor. A 409 reads the monitor again and restarts from the first page under the new validator, at most twice. A GET 404 during that reload removes the monitor locally. A sync page 404 reads the monitor; a 404 there removes it locally, and a 200 means its series is hidden, so the run logs it and moves on. A 401, 408, 410, 429 or 503, a server that needs an update, or a request that never left the device ends the run for every monitor. Other 4xx answers are logged and the run moves to the next monitor.
  • Store. ServerSubscription decodes the v2 DownloadSubscription, with every required field required. DownloadSubscription gains an optional persisted etag, and DownloadStoreFile gains an optional pendingSubscriptionDeletes (id → validator). Stores without either field still decode.
  • Stopping a monitor. The monitor leaves the local list at once, and its DELETE is recorded before sending. A DELETE without a definite answer is sent again by the next sync. The route is natural_idempotent, and download-registry deletes already use this pattern. A refusal ends the pending delete; the next list read shows the monitor again because the server still has it. If a create answers with a monitor whose DELETE is still pending, the app cancels that pending DELETE. Only a create does this; an edit or sync answer for a stopped monitor is dropped.
  • Monitors from earlier versions. Syncing a monitor an earlier version created would re-register the episodes W1-D removed, so those monitors are set aside by id, not by date. W1-D now also flags each scope it carries over with legacyMonitorsPending. That scope's first complete monitor list records every monitor the store doesn't know in legacyMonitorIds, and later lists hide only those ids. They are never shown or synced, and they stay on the server untouched. A scope no earlier version wrote, including every scope after a reinstall, hides nothing. If this launch's removal did not finish, unknown monitors are hidden for the launch without being recorded.
  • No sync before the first registry read. While a carried scope's first registry read is still pending, or the removal did not finish, monitor syncs register nothing. Otherwise that read would take the new rows for W1-D's legacy rows and delete them.
  • Refresh exclusion. HTTPClient excluded both GET and POST on /api/v2/downloads/subscriptions from 401 refresh-and-retry. It now excludes only the non_retryable POST, so a monitor list read survives an expired access token.
  • Deleted. SiloAPI.createSubscription, syncSubscriptions, updateSubscription and deleteSubscription, plus the v1-only CreateSubscriptionResponse and SubscriptionSyncResponse. DownloadAPI.swift keeps only pullProgressDeltas, which W3-E replaces.

Failure outcomes

Operation (retry safety) Definite success Definite failure Uncertain (sent, no usable answer)
Create (non_retryable) Store the monitor, PATCH differing options, sync it, reconcile Show the error in the monitor sheet; nothing stored Never resent. Read the monitor list: if it has the series, continue as success; otherwise show "Silo couldn't confirm the monitoring change…"
Update (natural_idempotent, If-Match) Store the monitor and its new validator, sync it, reconcile 412/409 twice: "Monitoring for this series changed on the server. Try again." 404: remove locally, "This series is no longer monitored." 428: fault log, error shown, no retry. Other 4xx: error shown Not replayed automatically; the sheet stays open with "Silo couldn't confirm…" so the user can save again (a stale validator then gets 412 → re-read → re-apply)
Delete (natural_idempotent, If-Match) 204 or 404: drop the pending delete. If a create answered with this monitor while the DELETE was on the wire, remove it locally too 412/409: re-read and delete once more. A second 412, 428 and other 4xx: fault or warning log, drop the pending delete; the next list read shows the monitor again. A second 409, and 401/408/410/429/503: keep the pending delete for the next sync Keep the pending delete; the next sync sends it again
Sync page (natural_idempotent) Add registered, follow the cursor 409: re-read the monitor and restart (at most twice). 404 on that re-read: remove locally. Page 404: read the monitor; 404 there removes it locally (a create or edit then shows an error), otherwise log and move on. 401, 408, 410, 429, 503, server-update-required or a request that never left the device: stop the run. Other 4xx: log and move to the next monitor Send the same page again, with the same validator and cursor, up to twice, then log and move to the next monitor
List (read) Replace the local list Log; keep the local list Log; keep the local list

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS and tvOS: DownloadSubscriptionsV2Tests (new), DownloadRegistryV2Tests, DownloadDeliveryV2Tests, LegacyDownloadStorageTests and DownloadGroupingTests.
  • The new tests use StubURLProtocol through APIv2TestStub. They cover:
    • the create body, device and profile headers, one send after a timeout, and refusal of another series' monitor
    • If-Match on PATCH and DELETE, and the PATCH body omitting unset fields
    • 412 → GET → PATCH with the same body, a second 412 surfaced, and a monitor without a validator read before the PATCH
    • 428 never retried on PATCH or DELETE
    • DELETE 404 as done, and 412 → GET → DELETE
    • sync paging under one validator; a page after a lost connection and a 500 sent again with the same body and cursor; a restart after a 409 under the new validator; ending on a deleted or paused monitor; stopping when the request never left; stopping after repeated 409s
    • a sync page 404 removing the monitor only when the monitor read also answers 404
    • list completeness
    • the local merge: titles kept, pending deletes and earlier versions' monitors left out, and earlier versions' monitors taken from the unknown ids of the first list rather than by date
    • a list read issued before a DELETE landed not bringing the monitor back, and one issued before a create answered keeping the new monitor
    • a create answered during its monitor's DELETE: gone when the DELETE lands, kept when it is refused
    • the create-options match, and decoding a monitor stored without a validator
  • The first tvOS run caught a real defect: the sync body was encoded without sorted keys, so a retried page's body was not byte-identical. The encoder now sorts keys.
  • 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: the manual check (subscribe to a series on a live server, then receive a new episode).

Risks and follow-ups

  • Sync now reads the monitor list on every foreground and background refresh when series monitoring is available. Before, it made one call only when the device had local monitors.
  • The races between creates, deletes and list reads are covered by unit tests of SubscriptionWriteLedger and the merge, not by an end-to-end DownloadManager test. The manager is a singleton on SiloAPI.shared, and no test seam exists for it. The same applies to the rule that holds monitor syncs until the first registry read.
  • The 401 refresh-exclusion change (GET list now refreshes) has no dedicated test.
  • Monitors from earlier versions stay on the server, hidden on this device. If the product wants them removed or shown, that is a follow-up.
  • No overlap with the open PRs listed in the plan for this row.

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 26 of 50 in the Apple API v2 stack. Base: apiv2-stack/25-download-assets-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: 4ddf84c1-ca9c-40a1-961f-bcdb90b05d0b

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:44.231597Z be2aba0 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: 6f52e946 (apiv2-stack/26-download-subscriptions-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: Re-monitoring during an in-flight DELETE can report success after the server removed the monitor
  • minor: A list read issued before a DELETE lands brings a stopped monitor back as an untitled ghost
  • minor: The PR body's failure-outcome table misstates which sync and delete failures stop or drop

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

ℹ️ 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 +2048 to +2053
} else if legacyPending == true {
// The first complete list after the removal. A monitor this
// version creates is stored when its create answers, so every
// unknown one is the earlier version's.
storedLegacy.formUnion(unknown)
legacy = storedLegacy

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 Preserve uncertain creates during legacy classification

When an upgraded scope still has legacyMonitorsPending == true and the first create reaches the server but its response is lost, sendCreate recovers by calling this list refresh. Because the newly created monitor was never stored locally, it is included in unknown here, recorded as legacy, and omitted from file.subscriptions; the subsequent series lookup therefore reports monitoringUncertain even though the server created the monitor, and it will not be synced unless the user retries. Exempt the series being recovered from legacy classification or record the recovered monitor before finalizing the legacy set.

Useful? React with 👍 / 👎.

Comment on lines +67 to +69
mutating func listCompleted(startedAt start: Int) {
deleted = deleted.filter { $0.value > start }
created = created.filter { $0.value > start }

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 write generations until every older list read finishes

When two monitor-list refreshes overlap, a newer read can complete first and remove a create/delete generation here even though an older read still needs it. Foreground, background-refresh, and push paths can all invoke onAppActive() without coalescing, so if a write lands after the older read starts, that older stale response can later drop the newly created monitor or restore a deleted one because its ledger protection has already been cleared. Serialize list refreshes, discard out-of-order results, or retain each generation until all reads that predate it have completed.

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

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

ℹ️ 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 +1918 to 1919
upsertSubscription(updated, seriesTitle: existing.seriesTitle)
persist()

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 Protect PATCH results from stale list reads

When a monitor-list request starts before this PATCH completes but returns afterward, refreshSubscriptions can replace the newly stored monitor with the list's older options and ETag because subscriptionWrites tracks only creates and deletes. This can happen when a foreground/background sync or another create-recovery list overlaps an edit; if that caller does not subsequently resync this monitor, the UI and persisted store revert until a later refresh, and the next edit starts with a stale validator. Record successful updates in the write ledger or otherwise prevent older list responses from overwriting them.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/25-download-assets-v2 branch from 0b8330c to dc6f6ed Compare September 23, 2026 13:39
Base automatically changed from apiv2-stack/25-download-assets-v2 to main September 23, 2026 13:39
Quick104 and others added 4 commits September 23, 2026 09:39
Series monitoring still went through /api/v1: one bodiless sync for every
monitor, and PATCH/DELETE without a validator. v2 syncs one monitor per
call and page, guards edits with If-Match, and has no inline registration
count on create, so the v1 calls cannot be switched one for one.

The monitor calls now live in APIv2Client+DownloadSubscriptions.swift and
run under the captured download owner. Create is sent once
(non_retryable); an uncertain create reads the monitor list, and a create
answered with an existing monitor applies the requested options with a
PATCH. PATCH and DELETE send the stored validator as If-Match; a 412 (or
409) reads the monitor again and applies the same change once more, and a
428 is logged as a client bug and never retried. Sync lists this device's
monitors, then pages each active one with {subscription_id, etag}, sends a
page without an answer again with the same validator and cursor, and
starts over under a fresh validator after a 409. Monitors and the local
store keep their etag, and stopped monitors are kept as pending deletes
until the server confirms them. The v1 subscription methods and response
models are deleted.

Stack-PR: W3-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
updateDownloadSubscription and deleteDownloadSubscription each repeated
the same block to pick the If-Match validator: the stored one when set,
otherwise a fresh read of the monitor. Both now call one
monitorValidator helper. Each call keeps its place relative to its
do/catch, so a failed read is handled exactly as before.

Stack-PR: W3-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… and list reads

A create for a series whose monitor DELETE was on the wire could answer
with that monitor, cancel its pending delete locally, and report success
after the DELETE removed it on the server. A monitor list read issued
before a DELETE landed brought the stopped monitor back as an untitled
entry, and one issued before a create answered dropped the new monitor.
A sync page 404 for a deleted monitor was only logged.

A new SubscriptionWriteLedger records which DELETEs landed and which
creates answered, by generation. A list read leaves out monitors whose
DELETE landed and keeps monitors created during the read. A create now
waits for a running delete pass first; if a pass that started during
the create removes the monitor the create answered with, it sends one
fresh create. Only a create revives a stopped monitor; an edit or sync
answer for a stopped monitor is dropped. A sync page 404 reads the
monitor, and a 404 there removes it locally; create surfaces
monitoringUncertain and edit surfaces monitorRemoved.

Stack-PR: W3-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
mergeSubscriptions hid every unknown monitor whose createdAt was before a
device-clock removal date. A reinstall wrote a new date and hid (and
stopped syncing) every monitor this version had created, and clock skew
misjudged monitors near the cutoff.

The removal now flags each carried scope with legacyMonitorsPending. The
scope's first complete monitor list records the monitors the store
doesn't know in legacyMonitorIds; later lists hide only those ids. A
scope no earlier version wrote, including every scope after a reinstall,
hides nothing. While the scope's first registry read is still pending, or
the removal did not finish, monitor syncs register nothing, so that read
can't take their new rows for legacy rows.

Stack-PR: W3-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/26-download-subscriptions-v2 branch from d9eeef8 to be2aba0 Compare September 23, 2026 13:40
@Quick104
Quick104 merged commit 44c1706 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/26-download-subscriptions-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: be2aba0b5a

ℹ️ 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".

priorRecordIds = Set(file.records.keys)
registered = (try? await SiloAPI.shared.syncSubscriptions()) ?? 0
if canMonitorSeries, let owner = await captureScopeOwner() {
registered = await syncSubscriptions(owner: owner)

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 Serialize monitor sync with registry reconciliation

When foreground, background-refresh, or push-triggered onAppActive() calls overlap, this sync can register an episode after another invocation's final registry GET has captured its response. If this invocation then reconciles first and imports the new row, the older response can arrive afterward and reconcileWithServer marks that active local record as failed with removed_on_server; later ready reconciliations do not recover records already in .failed. Coalesce these runs or discard stale registry responses so newly registered episodes cannot be permanently prevented from downloading.

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