Skip to content

feat(catalog): page catalog queries with v2 cursors - #382

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/34-catalog-cursor-paging
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/34-catalog-cursor-paging

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Every catalog-shaped list in the Apple clients paged through GET /api/v1/catalog with offset, snapshot/snapshot_at and include_total: library browse and its startup prefetch, the tvOS library grid, search, watch history, person credits, library and user collection grids, and the DEBUG search helper. A 1.0 server answers /api/v1/* with 410 client_upgrade_required. The v1 bracket-key filter groups (groups[0][rules][0][value]) have no v2 form, and the v2 query executor rejects string values for boolean and numeric rules.

Inventory rows 54 (the SiloAPI.catalog(query:) funnel), 63 (history) and 71 (collection items).

Solution

  • SiloAPI.catalog(query:), historyCatalog, personCatalogItems, libraryCollectionItems, userCollectionItems and catalogCollectionItems are deleted. They are replaced by SiloAPI.catalogPage(_:) and SiloAPI.nextCatalogPage(_:), which use the existing APIv2Client.catalogPage and nextCatalogPage and their owner fences.
  • The first page captures the acting owner and the image size. Each screen stores the returned APIv2CatalogContinuation and passes it back for the next page, so every page uses the first page's query, operation and owner. If the profile changes, the next page is refused before any request is sent.
  • When the JSON groups are longer than the 32768-character GET limit, the query goes through POST /api/v2/catalog/query, and the continuation keeps POST. Smaller queries stay on GET /api/v2/catalog.
  • APIv2CatalogQuery gains history, personCredits (sort=-year), collectionItems and search factories, plus a CatalogListPage type (cards and totals, plus the continuation).
  • CatalogQueryBuilder returns an APIv2CatalogQuery, built from the legacy branch's version as a reference. Rule values are typed: JSON booleans for watched, in_progress, favorited, in_watchlist, hdr and dolby_vision, and numbers for decade year between ranges.
  • Callers switched: BrowseViewModel and StartupContentPrefetcher.fetchBrowseFirstPage (the prefetched page 1 now also returns the page-2 continuation), TVLibraryGridViewModel, SearchViewModel (a new search generation stops an older load-more from appending to new results), HistoryViewModel, PersonDetailViewModel, LibraryCollectionDetailView and the DEBUG search in ContentView.
  • A cached page 1 has no cursor. A load-more over a cached page restarts from page 1 and replaces the grid. Opening a collection over a cached first page used to fetch from offset 60 and replace page 1 with page 2; the grid now starts over from page 1. Pull-to-refresh keeps the grid visible while page 1 reloads instead of clearing it first.
  • When the server rejects a cursor because the list changed since page 1 (400 invalid_cursor: a collection edit, a library scan, or a changed access policy), or the server repeats or drops a cursor (invalidCatalogContinuation), SiloAPI.nextCatalogPage reads a fresh page 1 with the same query and owner and marks it startsOver. Every grid replaces its items with that page and pages on from its new cursor, so the dead cursor is never sent again. Without this, the grid kept the rejected cursor, resent it on every scroll and stopped at 60 or 100 items with an "N+ items" label. The restart happens once per load-more; if the fresh page 1 fails, the grid keeps its items and the next scroll tries page 1 again. Other failures keep the cursor for a retry.
  • Cache keys are bumped: browse:v2:…, tvlibrary:v2:… and personal:history:v2. Library collection items move to collection:<id>:catalog:v2, separate from the raw collection-items list that CollectionDetailView still reads over v1. The prefixes used for invalidation (browse:, tvlibrary:, collection:) are unchanged.
  • CatalogResponse drops the v1-only snapshot, source and title fields. It stays Codable because the v1 favorites, watchlist and collection-items reads still decode it.

This PR changes reads only. queryCatalogItems is natural_idempotent and listCatalogItems is a GET, so no failure-outcome table applies.

Paging is bounded. UI grids request one page per user scroll, with no automatic loop. The continuation rejects a missing, empty or repeated cursor (invalidCatalogContinuation). The only looping reader, personalCollectionCards, keeps its 100-page bound.

Validation

  • iOS, tvOS and macOS builds passed, before and after the cursor-restart fix.
  • Focused tests passed on iOS and tvOS: CatalogPagingAPITests, CatalogQueryBuilderTests, CatalogV2Tests, CollectionsV2Tests, BrowseViewModelTests and HomeSectionsAPITests, plus ArtworkURLTests on iOS.
  • The new CatalogPagingAPITests cover:
    • a history first page and its cursor page on GET /api/v2/catalog, with no v1 paging parameters
    • the scope parameters for person credits, user collections, library collections and search
    • oversized filters paging through POST /catalog/query, with the cursor in the body and the first page's query sent again
    • a continuation refused after a profile switch, with no request sent
    • a v1-shaped body that surfaces as decode_failed instead of an empty list
    • a 400 invalid_cursor on page 2 that reads a fresh page 1 marked startsOver and then pages on from the new cursor without resending the rejected one; a repeated cursor that starts over the same way; and another problem (validation_failed) that throws without rereading page 1
  • CatalogQueryBuilderTests is ported to the v2 query. It checks the signed sort, the groups JSON, boolean and numeric rule types, and the switch from GET to POST.
  • scripts/ci/check-no-api-v1.sh passed. SiloAPI.swift and CatalogQueryBuilder.swift have fewer v1 literals, and no /api/v1/catalog literal remains in app sources.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard. Every branch in the stack, this one included, builds on its own.
  • Not run: the plan's Wave 5 manual check (tvOS browse with focus and paging past 100 items, plus an iOS browse).

Risks and follow-ups

  • A cursor restart replaces a grid of several pages with page 1. On tvOS, focus on an item past page 1 should move to the nearest item in the native focus graph; this was not checked on a simulator. The restart is covered by API tests only; the view models that apply it were not run against a stub.
  • Android answers the same invalid_cursor differently: it stops paging and shows "This result expired or changed. Reload from the first page." until the user reloads. Apple restarts from page 1 on its own because its grids show errors only when they are empty.
  • TVLibraryGridViewModel changed here because it calls the funnel. Only its paging state changed; focus, layout and the view are untouched. W5-H still owns the library sections and collections routes.
  • CollectionDetailView (/api/v1/collections/{id}/items), favorites and watchlist still read v1 into CatalogResponse. W5-O and W5-N own them.
  • personalCollectionCards still has no production caller. The user-collection grid pages by cursor like every other grid instead of reading the whole collection up front.
  • History, person and collection pages keep the default exact total on every page. v1 skipped the count after page 1. The continuation fixes the query for its whole chain, so later pages cannot drop the count.
  • Sort fields and the type=video search scope go through v2 unchanged. The server's v2 sort allowlist was not compared field by field against CatalogSortKey.
  • The server's v1 bracket-key parser accepted strings for boolean rules. v2 now receives JSON booleans and numbers, which matches the server's query_builder.go checks at 84ed9e596. This has not been exercised against a live server.

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 34 of 50 in the Apple API v2 stack. Base: apiv2-stack/33-filters-calendar-trailers-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: 944d6fd8-015e-4cd6-ad07-9aa7c6af7db2

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:25:06.485668Z ff7d1da 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: 141bc83d (apiv2-stack/34-catalog-cursor-paging).

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 rejected cursor stops load-more for good, with no error shown and no restart
  • minor: PR body describes the collection-grid bug that was fixed incorrectly

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: ff7d1da5af

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


offset = requestOffset + response.items.count
continuation = page.continuation
total = response.total ?? results.count

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 Avoid presenting estimated search totals as exact

When v2 search returns total_exact: false—for example, the semantic-search response covered by testSearchWindowIsNotGlobalTotalAndInstantDecodes, where total is 10,000 but the result window is only 250—this assigns the estimate to total, and SearchView renders it as an exact “10000 results.” Preserve totalExact (and ideally the result-window limit) or derive a lower-bound label from the loaded results instead of displaying the estimate as an exact count.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/33-filters-calendar-trailers-v2 branch from 58c61e8 to 72a03f9 Compare September 23, 2026 13:42
Base automatically changed from apiv2-stack/33-filters-calendar-trailers-v2 to main September 23, 2026 13:42
Quick104 and others added 3 commits September 23, 2026 09:42
Every catalog-shaped list (library browse, the tvOS library grid, search,
watch history, person credits and collection grids) still paged through
GET /api/v1/catalog with offset, snapshot and include_total. A 1.0 server
answers that route with 410, and v1 bracket-key filter groups have no v2
equivalent.

SiloAPI.catalog(query:) and its history, person and collection wrappers
are replaced by catalogPage(_:) and nextCatalogPage(_:), built on the
existing APIv2Client catalog continuation. The first page captures the
acting owner and image size; each screen keeps the returned continuation
and hands it back for the next page, so every page reuses the first
page's query and owner and a profile switch refuses the next page. Filter
sets whose JSON groups exceed the 32768-character GET limit go through
POST /api/v2/catalog/query, and the continuation keeps that operation.

CatalogQueryBuilder now returns an APIv2CatalogQuery with typed rule
values (JSON booleans for watched/hdr/..., numbers for year ranges), which
the v2 query executor requires. A cached first page carries no cursor, so
a load-more over it restarts from page 1 instead of guessing an offset;
this also fixes the collection grid's pull-to-refresh, which re-fetched
from the old offset and replaced page 1 with page 2. The browse, tvOS
grid and history cache keys move to v2 names and library collection
items get their own key. CatalogResponse drops the v1-only snapshot,
source and title fields.

Stack-PR: W5-I
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Person credits and the tvOS library grid picked the next page with a
startsOver flag and then re-checked the continuation, unlike the other
catalog screens. They now take the same nextPage = reset ? nil :
continuation step the history, collection and search screens use.
Behavior is unchanged.

Stack-PR: W5-I
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
When a collection changes, a library scan runs, or the viewer's access
policy changes between pages, the server answers the next cursor with
400 invalid_cursor. The client also refuses a repeated or dropped cursor
(invalidCatalogContinuation). Every catalog grid kept the dead cursor and
hasMore, hid the error because items were on screen, and resent the same
cursor on every scroll, so the grid stopped at 60 or 100 items.

SiloAPI.nextCatalogPage now treats either error as a restart: it reads a
fresh first page with the continuation's query, operation and owner and
marks it startsOver. History, browse, the tvOS library grid, search,
person credits and the collection grid replace their items with that page
and page on from its new cursor. Other failures still keep the cursor for
a retry.

Stack-PR: W5-I
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/34-catalog-cursor-paging branch from ff7d1da to d449f74 Compare September 23, 2026 13:42
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Quick104
Quick104 merged commit 010d347 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/34-catalog-cursor-paging branch September 23, 2026 13:42
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