Skip to content

refactor(api): paginate the three pagination: false SahajCloud reads #253

Closed

Description

@sydevs-bot

Summary

src/config/api/fetch.ts makes three reads that ask SahajCloud for a whole table at once. The
owner answered SahajCloud#887's open question on
2026-10-06 — option (b), a client gets no unbounded read — so these three have to paginate
before that refusal can land. This repo ships first. The widget breaks on every host site the
day SahajCloud#889 merges otherwise.

Call site Read What it feeds
src/config/api/fetch.ts:173-182 (getRegions) regions, depth: 0, sort: 'name', REGIONS_SELECT the full region tree
src/config/api/fetch.ts:212-216 (getGeojson) GET /events/geojson, depth: 1, FEED_SELECT, REGION_POPULATE the full map feed
src/config/api/fetch.ts:243-246 (getEventTitles) events, depth: 0, select: { title: true } the id→title map, per locale

Each read returns one docs array its caller consumes whole, so the shape callers see must not
change: fetch page by page and concatenate, rather than pushing pagination up into indexedFeed
(fetch.ts:320), the geojson parse, or the title Map. loadRegions (:196),
loadGeojson (:226) and loadEventTitles (:276) keep their cache contracts untouched, so
warmCaches (:842) and regionsQuery (src/config/api/index.ts:109) need no change.

Goal context

Part of #256 — the atlas keeps loading in
full as it grows. This piece teaches the widget's three wholesale reads to read in pages, which is
the precondition for the system behind the atlas refusing to serve a whole table.

Interfaces

  • Consumes SahajCloud's MAX_CLIENT_LIMIT (2000) and MAX_CLIENT_PAGE (10000), both on main
    since SahajCloud PR #890.
  • Provides SahajCloud#889 its precondition:
    no read from this widget sends pagination: false or limit: 0. It is not sufficient on its own
    — see Downstream impact.

Approach

The page size is 2000, and the bound is now live

MAX_CLIENT_LIMIT = 2000 (src/plugins/usage/constants.ts:44) and MAX_CLIENT_PAGE = 10_000
(:51) are both on SahajCloud main: sydevs/SahajCloud#890 merged 2026-10-10 17:25Z
(d1b0322), and SahajCloud deploys from main. An earlier revision of this ticket said they did
not exist yet. Treat the gate as enforcing in production now.

assertWithinBound (src/plugins/usage/hooks.ts:329), called at :259-260:

  • A numeric limit or page must be a whole number in 0 … max, or the read is refused 400.
    2000 is allowed, exactly at the cap (tests/int/client-query-validation.int.spec.ts:222, the
    "a limit at the cap" row); page is allowed to 10000 (:231).
  • A non-numeric value passes through untouched, so the bound cannot be satisfied by accident.
  • 0 passes both bounds — it is payload's "no limit" sentinel. So this gate does not yet refuse
    an unbounded read; that refusal is feat(api): refuse an unbounded client read, once the Atlas widget paginates SahajCloud#889.
  • An absent limit is not an unbounded read either: Payload defaults it to 10. So every read
    must send its limit explicitly, or it silently truncates to 10 rows.
  • The two bounds run ahead of the asTrustedReq (hooks.ts:266) and live-preview (:271)
    bypasses, so no request shape escapes them.

The volume: every read fits in one page today

Measured in production with a full-read client key, limit=1, reading totalDocs (Ardnived,
2026-10-10). The parent goal's own production measurement on 2026-10-08 agrees: 452 classes, 646
places.

Read totalDocs Pages at 2000
regions 646 1
events 452 1
GET /events/geojson 452 1

What follows, and what the implementation should be sized for:

  • The walk is one request per read today — the same request count as now. The fan-out over
    pages 2 … totalPages is a safety net that does not execute at this volume, not a hot path. Do
    not optimize it.
  • 2000 is the page size, decided on The whole atlas loads, and keeps loading as it grows #256 and capped there by MAX_CLIENT_LIMIT. A smaller page
    only adds requests. Headroom before a second page: about 3× for regions, about 4× for events.
  • The extra COUNT per page that pagination adds is one extra query per read at this volume.
    The unbounded reads take about 0.45s each today, so it is not measurable.
  • getEventTitles's per-locale multiplier is likewise one request per locale, as now. The page cap
    still matters most there, because it is the read a session repeats.
  • A narrower widget key sees at most these counts, never more.

Phase 1 — a shared page loop

Add one helper beside the fetchers (src/config/api/fetch.ts, or src/config/api/paginate.ts
re-exported from it). The repo has no page loop today — grep -rn 'hasNextPage' src/ hits only
generated types — so this is new code, not a pattern to copy.

  • Read page 1 with an explicit limit, then use that response's totalPages to fetch pages
    2 … totalPages. That makes the bound a number read from the server rather than a while
    condition, and answers the sequential-vs-concurrent question in one shape: fan the remaining
    pages out with Promise.all and concatenate in page order. Same request count as a sequential
    walk, one round trip of latency instead of N.
  • Cap the page count and throw atlasError('server', …) (src/lib/report.ts:76) past it. A
    while (hasNextPage) with no cap turns a server-side bug into an infinite fetch inside someone
    else's page. 'server' is the kind that offers a retry and a report button
    (src/components/molecules/Fallbacks/Fallbacks.tsx:191-201). The cap can be small — one page
    covers production today — and must never let the loop request a page above 10000 regardless.
  • Parse each page through its zod schema and concatenate the parsed arrays, rather than
    concatenating raw rows and parsing once. A bad row then fails inside the page that carried it.

Phase 2 — the three call sites

getRegions (:172) — drop pagination: false, send limit and page. sdk.find already
returns PaginatedDocs, so const { docs, totalPages } = … type-checks with no cast
(@payloadcms/sdk, dist/collections/find.d.ts).

⚠ sort: 'name' is not a stable page key. name is a plain type: 'text', required: true
field with no unique on it (SahajCloud src/collections/Regions/Regions.ts:272). A LIMIT/
OFFSET walk over a non-unique sort key has no total order, so Postgres may order ties differently
per page and the walk silently repeats and drops rows. Append a unique tiebreaker:
sort: ['name', 'id'] — Sort = Array<string> | string ([email protected],
dist/types/index.d.ts:114), and the SDK passes it through. The other two reads send no sort
at all and need an explicit one for the same reason.

getGeojson (:208) — the endpoint already paginates, so no SahajCloud work is needed and
nothing here belongs on sydevs/SahajCloud#889. src/collections/Events/endpoints/geojson.ts:92-104
forwards limit, page and pagination straight into payload.find and spreads Payload's
pagination metadata into the FeatureCollection as foreign members. This repo already holds the
typed contract for it
: EventFeatureCollection at src/types/payload/response-types.ts:39-51
carries totalPages, hasNextPage and nextPage. Type the raw response with it, the way
mutate.ts:1 imports from that file.

⚠ GeojsonSchema strips those members, so read them before you parse.
src/types/geojson.ts:22-25 is a plain z.object on zod ^3.25.76, which drops unknown keys —
the file's own comment says so at src/types/geojson.ts:8. A loop that reads hasNextPage off the
parsed value gets undefined on every page, forever, and fetches exactly one page. Read the loop
state off the requestJson<EventFeatureCollection> result, and parse only the merged features
through GeojsonSchema at the end.

getEventTitles (:242) — same as getRegions. It is per-locale, so a page loop here
multiplies by the number of locales a session visits.

Acceptance criteria

  • None of the three reads sends pagination: false or limit: 0.
  • Each sends an explicit limit at or under 2000, and an explicit page at or under 10000.
  • Each read follows totalPages to the end and returns every row.
  • Each read sends a sort whose last key is unique (id), so no row is repeated or skipped at a
    page boundary.
  • Every page walk is bounded and throws atlasError('server', …) past its cap rather than
    looping forever.
  • The region tree, the map feed and the title map are identical to today's for a dataset that
    fits in one page — which is every one of them at current volume.
  • A dataset spanning more than one page produces the same result as one unbounded read.
  • getGeojson reads its pagination state from the raw response, not from GeojsonSchema's
    output.

Verification checklist

  • pnpm test:run passes, with a single-page and a multi-page case per fetcher. Mock at the
    @payloadcms/sdk boundary, as src/config/api/fetch.test.ts:23-33 does.
  • ⚠ Update the existing mocks, or the multi-page cases are vacuous. fetch.test.ts:301
    (mockBackend) and the getGeojson spec at :172 both resolve responses carrying no
    pagination members, so hasNextPage and totalPages read undefined, one page is fetched,
    and every existing spec stays green against a one-page-only loop. Give the mocks real
    totalPages / hasNextPage values.
  • ⚠ fetch.test.ts:199 asserts options.args.pagination === false. That assertion has to
    flip, not be deleted — it is the one spec that pins what the feed request sends.
  • Each new assertion has failed once. Make the multi-page case red by returning page 1 only,
    watch it fail, restore. A multi-page case written against the current single-request code is
    the easy one to get vacuously green (docs/testing.md, "A regression spec is not finished
    until it has FAILED").
  • A spec covers the page cap: a mock that always reports another page must throw, not hang.
  • pnpm lint && pnpm typecheck pass.
  • Against a published client key, limit=2000 on each of the three reads returns 200.
    fix(api): unbounded client limit and page reach SQL and return 500 SahajCloud#890's bound is live, so this now exercises the real gate rather than a
    future one.
  • The widget renders the full atlas against a preview: all 25 countries with a class, all 452
    markers, every event title, and Brazil's 81. A partial atlas is this change's failure mode
    and it renders without an error.

Downstream impact

  • SahajCloud PR #890 (phase 1) has merged
    (2026-10-10). It bounds an explicit limit/page and leaves pagination: false working, so
    the widget is unaffected today and this ticket's page size is already enforced server-side.
  • SahajCloud#889 is blocked on this merging
    and deploying
    — it carries the Blocked by line pointing here — but this ticket does not
    unblock it on its own.
    feat(api): refuse an unbounded client read, once the Atlas widget paginates SahajCloud#889's own "The internal reads" section records three
    SahajCloud reads that fetch a whole regions table on the client's own req, fired by
    selecting webPath or webUrl. Both of this repo's selects do: FEED_SELECT at
    fetch.ts:119, REGIONS_SELECT at :138-139. Those reads are SahajCloud's to fix inside
    feat(api): refuse an unbounded client read, once the Atlas widget paginates SahajCloud#889, and nothing here can clear them. At one page per read this change adds no
    internal reads versus today; a multi-page walk would multiply them, which is a second reason to
    keep the page size at the cap. feat(api): refuse an unbounded client read, once the Atlas widget paginates SahajCloud#889's own criterion
    "GET /api/events/geojson answers a paginated client request" is already satisfied by the
    endpoint as written.
  • ⚠ getGeojson has six direct React call sites, not just loadGeojson — Map.tsx:254,
    SearchFilters.tsx:177, use-country-site.ts:42, FilterView.tsx:49, CountriesView.tsx:53
    and views/shared.tsx:424 each pass it as a queryFn. They all consume the Geojson shape, so
    "the shape callers see must not change" is the criterion that protects all six. getRegions has
    one (config/api/index.ts:111); getEventTitles is reached only through eventTitlesQuery.
  • No host-observable change, so docs/embedding.md and CHANGELOG.md need no entry: same origin,
    same attributes, same CSP. Only the request count to VITE_SAHAJCLOUD_URL changes, and at
    current volume it does not change at all.

Notes

pagination: false also skips Payload's COUNT query ("avoid querying for document counts",
@payloadcms/sdk FindOptions.pagination). Paginating adds one COUNT per page per read, and
under option (b) there is no way to opt out of it. At the measured volume that is one extra query
per read, which the timings above make negligible. Not a reason to change the design.

GET /events/geojson was confirmed to paginate already — see Phase 2. It needs no SahajCloud
change, which also answers the second open question on sydevs/SahajCloud#889.

🤖 Written by the sydevs autonomous loop — see what this is

Activity

  1. added theissue type on Oct 6, 2026
  2. added
    proposal
    on Oct 6, 2026
  3. added
    bot:working
    and removed on Oct 6, 2026
  4. sydevs-bot commented on Oct 6, 2026

    @sydevs-bot
    ContributorAuthor

    🤖 no session running

    recent dispatches
    • 15:41Z implement · attempt 1 · session · done
    • 15:41Z implement · attempt 1 · session
    • 19:12Z revise · attempt 1 · session · done
    • 19:12Z revise · attempt 1 · session
    • 20:46Z revise · attempt 1 · session · done

    Written by the sydevs dispatcher. Sessions never edit this comment.

  5. sydevs-bot commented on Oct 6, 2026

    @sydevs-bot
    ContributorAuthor

    Revised from the code. Five substantive changes.

    MAX_CLIENT_LIMIT is not on SahajCloud main. It lands with PR #890, at 2000. The filing cited it as current.

    MAX_CLIENT_PAGE = 10_000 bounds page too. The filing missed that ceiling.

    GET /events/geojson already paginates. It forwards limit/page and returns the metadata, which this repo already types (src/types/payload/response-types.ts:39). No SahajCloud work needed.

    GeojsonSchema strips those members (src/types/geojson.ts:22, zod 3). A loop reading hasNextPage after parsing fetches one page forever.

    sort: 'name' is not a stable page key. name is not unique, so an OFFSET walk can repeat and drop rows. Use ['name', 'id'].

    The existing mocks carry no pagination fields, so a multi-page spec goes vacuously green. The checklist names each one.

    Row counts stay open. This clone has no client key, and an unauthenticated read returns 403.

    Effort Moderate, Priority High — #889 is blocked on this. Title unchanged.

    @sydevs-bot implement starts the work.

    🤖 Written by the sydevs autonomous loop — see what this is


    Generated by Claude Code

  6. added and removed
    bot:working
    on Oct 6, 2026
  7. Ardnived commented on Oct 10, 2026

    @Ardnived
    Contributor

    Open question answered: production row counts (measured 2026-10-10 against cloud.sydevelopers.com with a full-read client key, limit=1, reading totalDocs):

    Read totalDocs
    regions 646
    events 452
    GET /events/geojson 452
    • Each read fits in one page at 2000. Today the walk is page 1 only, one request per read, the same count as now. The fan-out over pages 2 … totalPages is a safety net, not a hot path.
    • 2000 is the right page size. It is #890's cap, so a larger page is not available, and a smaller one only adds requests. Headroom before a second page: about 3× for regions, about 4× for events.
    • The unbounded reads today take about 0.45 s each, so the extra COUNT per page that pagination adds is negligible at this size.
    • A narrower widget key sees at most these counts, never more.

    The design stands as written. The Notes section's COUNT cost and the per-locale multiplier on getEventTitles are both one extra query at most, at current volume.

  8. Ardnived commented on Oct 10, 2026

    @Ardnived
    Contributor

    @sydevs-bot Revise based on my last comment

  9. added
    bot:working
    and removed
    proposal
    on Oct 10, 2026
  10. sydevs-bot commented on Oct 10, 2026

    @sydevs-bot
    ContributorAuthor

    Row counts folded in. The open-questions section is gone — nothing is outstanding now.

    Every read fits one page at 2000. 646 regions, 452 events. So the walk is one request per read, the same count as today. The fan-out over pages 2…N is a safety net, not a hot path.

    sydevs/SahajCloud#890 has merged (2026-10-10 17:25Z). MAX_CLIENT_LIMIT and MAX_CLIENT_PAGE sit on main at src/plugins/usage/constants.ts:44,51. The body said they did not exist yet. The bound is live, so the checklist now verifies limit=2000 against the real gate.

    This ticket does not unblock sydevs/SahajCloud#889 on its own. Three SahajCloud reads fetch a whole regions table on the client's own req, fired by the webPath/webUrl our selects ask for (fetch.ts:119,138-139). Those are theirs to fix.

    Added ## Goal context and ## Interfaces, both missing for a roadmap child. Corrected two stale spec line references. Priority stays High. Title and type unchanged.

    @sydevs-bot implement starts the work.

    🤖 Written by the sydevs autonomous loop — see what this is


    Generated by Claude Code

  11. added and removed
    bot:working
    on Oct 10, 2026
  12. Ardnived commented on Oct 11, 2026

    @Ardnived
    Contributor

    @sydevs-bot implement

  13. added
    bot:working
    and removed
    bot:working
    on Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    High

    Hold Until

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions