Skip to content

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

Merged
sydevs-bot merged 5 commits into
mainfrom
claude/refactor-253-paginate-wholesale-reads
Oct 11, 2026
Merged

sydevs-bot merged 5 commits into
mainfrom
claude/refactor-253-paginate-wholesale-reads

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Change outline

All three reads still hand their callers one whole array — getGeojson alone has six direct React
call sites, and loadGeojson caches one ['geojson'] entry that indexedFeed memoises per feed
reference. What changed is how that array is assembled.

Flow

 getRegions()                                       src/config/api/fetch.ts
-  sdk.find regions, pagination: false, sort 'name'
-  RegionNodeSchema.array().parse(docs)
+  readAllPages('regions', readPage)                src/config/api/paginate.ts
+    readPage(1) → rows, totalPages
+    not an integer ≥ 0 → throw atlasError('server')   # no count == silent truncation
+    > MAX_PAGE_WALK    → throw atlasError('server')   # an endless count == an endless fetch
+    pages 2…N, MAX_PAGES_IN_FLIGHT at a time          # bounded range, not hasNextPage
+    concat in page order
+  readPage: sdk.find regions, limit 2000, page, sort walkSort('name')
+    RegionNodeSchema.array().parse(docs)              # a bad row fails inside its own page

getEventTitles is the same shape with walkSort(). getGeojson differs in one place, and that
place is the trap:

 getGeojson()                                       src/config/api/fetch.ts
   readPage: requestJson /events/geojson, limit 2000, page, sort walkSort()
+    totalPages ← the RAW response                     # every schema here strips foreign members
-    GeojsonSchema.parse(data)
+    features   ← GeoFeatureSchema.array().parse(data.features)
   { type: 'FeatureCollection', features }

Contract — what makes a walk sound, and who owns it

walkSort is the seam, not a comment at each call site: a LIMIT/OFFSET walk needs a total
order, and a fourth walked read written with a non-unique sort would silently repeat and drop rows
with every gate green.

 src/config/api/paginate.ts
+  CLIENT_PAGE_LIMIT  = 2000     # SahajCloud's MAX_CLIENT_LIMIT — over it is a 400
+  MAX_PAGE_WALK      = 20       # ~60× today's volume; bounds a paging fault, not growth
+  MAX_PAGES_IN_FLIGHT = 4       # an embed competes with its host for ~6 sockets
+  walkSort(...keys) → [...keys, 'id']

Files

 src/config/api/
 ├── client.ts      # unchanged — auth, locale and live preview still attach here
+├── paginate.ts    # the walk, the sort contract, SahajCloud's page limit
 └── fetch.ts       # the three reads call readAllPages; their return shapes are untouched

Preview

  • Preview pending — Cloudflare has not published a branch alias for this push yet. Not a UI
    change, so the Ladle playground is unaffected.

Test results

  • Lean gate: ✓ pnpm lint + pnpm typecheck + pnpm test:run (1694 passed)
  • Targeted specs: 8 new in paginate.test.ts, 4 new in fetch.test.ts
  • Build: ✓ pnpm build + pnpm size, within budget on all three graphs

Manual verification

  1. 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 exercises the real gate rather than a future one.
  2. The preview renders the full atlas: 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 with no
    error at all.

Notes for reviewer

  • One finding is recorded rather than fixed, and it is yours to overrule. A LIMIT/OFFSET
    walk is not immune to the matching set changing between page requests — walkSort fixes tie
    ordering, not set mutation. Above 2000 rows, an event crossing schedule.lastDate between the
    page-1 and page-2 reads shifts the offset and one event disappears from the feed; a publish in
    the same gap repeats a row, and the region then counts one extra event. Keyset paging
    (where[id][greater_than]) is immune and would suit the two id-sorted reads, but it is
    sequential, getRegions cannot use it with its display sort, and the ticket chose the
    totalPages shape explicitly. The path needs ~4× growth plus a sub-second race, so I left the
    shape alone and noted the limit on the parent goal (The whole atlas loads, and keeps loading as it grows #256), where the next page-size decision
    gets made.
  • Two refusals go past the ticket's criteria, for the same reason: a half-loaded atlas renders
    with no error. A response carrying no page count is refused rather than read as one page, and a
    page count over the cap is refused rather than walked. Both are atlasError('server'), the kind
    whose fallback offers retry and report.
  • The fan-out is windowed, which the ticket did not ask for — it said not to optimise the
    2…N fan-out, and this does not make it faster. It bounds its width, because an unwindowed
    Promise.all would put 19 reads on the wire at once from inside a host page, doubled at mount
    where warmCaches walks regions and the feed together. That is the storm shape this repo
    already caps at 2 in flight for speculative prefetch. One line reverses it if you disagree.
  • MAX_PAGE_WALK lives beside the loop, not in query-client.ts with the other pressure
    knobs. It is read by exactly one function, in the file that holds the loop it bounds; splitting
    the two seemed worse than the inconsistency.
  • The existing mocks carried no pagination members, so every multi-page spec would have gone
    vacuously green against a one-page-only loop. That is why the diff touches specs that look
    unrelated to it.
Detail

Every new assertion was watched red before it was kept, each defect reintroduced at the site
that would actually cause it:

Defect reintroduced What went red
The walk returns page 1 and stops the three multi-page fetcher specs, and the page-order spec
A missing page count treated as one page refuses a response that reports no page count
The page cap removed the cap spec, and refuses a feed whose page count never ends
totalPages read off the parsed value 10 specs, the whole getRegion suite included
sort: 'name' with no id tiebreaker the getRegions request-shape spec
walkSort without its terminal key the walkSort spec and three request-shape specs
One Promise.all over the whole range the fan-out window spec and the stop-after-failure spec

Why the sort keys changed. name on regions is a plain required text field with no unique
(SahajCloud src/collections/Regions/Regions.ts), so an OFFSET walk ordered by it has no total
order and Postgres may place ties differently per page. The other two reads sent no sort at all.

Sort serialization was verified, not assumed. @payloadcms/sdk's buildSearchParams joins an
array sort into sort=name,id, and payload 3.90.2's sanitizeSortParams splits a string back on
commas, so the array survives the round trip. The geojson endpoint forwards sort into its own
payload.find (src/collections/Events/endpoints/geojson.ts), which is why it can carry one.

Request count is unchanged at today's volume. 646 regions and 452 events each fit one page at
2000 (measured in production 2026-10-10), so the fan-out never executes and the window is
zero-width. It is a safety net, not a hot path.

Page size stays at the ceiling. A smaller page only adds requests, and each page costs one
extra COUNT that pagination: false used to skip — which also multiplies the SahajCloud-internal
regions reads that selecting webPath triggers. getEventTitles is per-locale, so that
multiplier bites hardest there.

getGeojson stopped re-parsing the merged collection on purpose. Each page's features are
parsed as they arrive; the container is the schema's only other member and the client supplies it
as a literal, so a merged re-parse would run the app's largest zod pass twice.

totalPages is the one wire value validated outside zod. It arrives through
requestJson<EventFeatureCollection>, an unchecked cast, and is gated by Number.isInteger in
paginate.ts rather than by a schema. Deliberate: it is loop control, not data, and the refusal
has to happen before anything is parsed.

Reviews run: /simplify (four lenses: reuse, simplification, efficiency, altitude),
/code-review high, and /security-review — the last because src/config/api/ is on this repo's
security trigger paths. Security found nothing, having traced the feed's webPath sinks to
safePath and isSafeHref, the as T cast's two readers, and what reaches an error message.

Dismissed, with reasons: asserting limit: CLIENT_PAGE_LIMIT instead of the literal 2000 in
the fetch specs (the literal is SahajCloud's wire number — if the constant moved, these should go
red, not follow it); folding the two sdk.find walks into a shared findAllPages (the wrapper
would have to carry the SDK's generic select typing, which docs/rules/data-layer.md calls
load-bearing, to save six lines across two call sites); passing limit down through the
readPage callback (a caller can ignore a parameter as easily as forget a field, and the
10-row-default failure it guards against is already loud — 646 regions at 10 a page is 65 pages,
over the cap); threading an AbortController through the walk (the window already stops issuing
pages after a failure); and a source-walking spec that fails any sdk.find call site lacking a
limit — the right altitude for the rule and the repo's own precedent (href.test.ts), but it
has to tell collection reads from findByID, globals and custom endpoints to avoid firing on
reads that are correct without one. Filed as #275 rather than built here, because a correct
exemption list is a judgement call that does not belong inside a pagination PR.

The review's two adopted findings. CLIENT_MAX_PAGE was exported with no production reader:
its only consumer asserted MAX_PAGE_WALK <= CLIENT_MAX_PAGE over two literals in the same file,
an assertion docs/testing.md's "a new assertion must have failed once" cannot be satisfied by.
The ceiling is now a line in MAX_PAGE_WALK's docblock. The getGeojson raw-response ⚠ was the
fourth statement of one rule in this diff, so it is one line pointing at
docs/rules/data-layer.md, which carries the mechanism.

No host-observable change, so docs/embedding.md and CHANGELOG.md carry 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 either.

Closes #253


Generated by Claude Code

`getRegions`, `getGeojson` and `getEventTitles` each asked SahajCloud for a
whole table with `pagination: false`. SahajCloud#887 settled that a client gets
no unbounded read, so sydevs/SahajCloud#889 will refuse that shape. This repo
ships first: otherwise the widget breaks on every host site the day it merges.

Each read now walks `totalPages` through one shared helper and concatenates in
page order, so the shape its callers consume is unchanged — `getGeojson` alone
has six direct React call sites. Production fits every one of the three in a
single page today (646 regions, 452 events, measured 2026-10-10), so this is
the same request count as before; the fan-out over pages 2…N is a safety net.

Three things the walk has to get right, each with its own spec:

- The page count comes off the RAW geojson response. `GeojsonSchema` is a plain
  zod object and strips the pagination foreign members, so a loop reading it
  after parsing would fetch exactly one page forever.
- Every read sends a sort whose last key is unique. `name` is not unique, and a
  LIMIT/OFFSET walk over a non-unique key has no total order, so Postgres may
  place ties differently per page and the walk repeats and drops rows.
- The walk is capped, and throws `atlasError('server', …)` past the cap. This
  code runs inside pages nobody here owns, where an endless `totalPages` would
  become an unbounded fetch loop in a stranger's tab. A response carrying no
  page count is refused for the same reason: a half-loaded atlas renders with
  no error at all.

The existing mocks carried no pagination members, so they are updated too —
left alone, every multi-page spec would have gone vacuously green against a
one-page-only loop.

Refs #253

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DBh7Zv7Pcaq7X5QRHWdSsk
Four cleanup lenses over the branch. Three findings changed the code:

- The uniqueness rule that makes a LIMIT/OFFSET walk sound was a comment
  repeated at three call sites. `walkSort` owns it instead, so a fourth walked
  read cannot be written with a non-unique sort and silently repeat and drop
  rows. One spec pins the contract where three pinned it by example.
- The fan-out was one `Promise.all` over the whole range: up to 19 requests in
  the same millisecond, doubled at mount where `warmCaches` walks regions and
  the feed together. It windows now, for the reason this repo already caps
  speculative prefetch at 2 in flight — an embed competes with the host page
  for its own sockets. A failed page also stops the walk instead of leaving
  the rest to download bodies nobody reads.
- `getGeojson` parsed each page through the whole-collection schema and threw
  the container away. It parses the per-feature schema the repo already
  exports, which is the shape the other two walks use.

The rest was comment and fixture weight: the three walks restated the same
facts the helper and `docs/rules/data-layer.md` already carry.

Refs #253

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DBh7Zv7Pcaq7X5QRHWdSsk
…he feed

The enforced client query rules gained a third clause: an explicit `limit` and
`page`, under SahajCloud's ceilings, with a sort whose last key is unique. The
quiet half is worth stating — an absent `limit` is not an unbounded read, it is
ten rows.

`getGeojson`'s entry said to parse the feed through `GeojsonSchema`, which no
longer has a `.parse` call site: a walked read parses each page's features and
builds the one container itself. Left as it was, the next reader either re-adds
the whole-collection parse or trusts a validation that no longer runs.

Refs #253

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01DBh7Zv7Pcaq7X5QRHWdSsk
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 11, 2026
@sydevs-bot

sydevs-bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 16:30Z address-review · attempt 1 · session · done
  • 16:30Z address-review · attempt 1 · session
  • 16:22Z review-pr · attempt 1 · session · done
  • 16:22Z review-pr · attempt 1 · session

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

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

This is the ticket's change at the ticket's size: three reads walk pages, every caller's shape is untouched, and no pagination: false or limit: 0 survives anywhere in src/. Both sides of the contract hold — SahajCloud allows limit: 2000 and page ≤ 10000 exactly, the geojson endpoint forwards sort into its own payload.find and spreads totalPages as a foreign member, and the SDK joins an array sort to sort=name,id, so the tiebreaker really reaches Postgres.

Two of paginate.ts's seven names pay no rent, and both come from going past the ticket: CLIENT_MAX_PAGE has no production reader, and the fan-out window bounds a burst that cannot occur at 60× current volume. Nothing is wrong — the file would read as the ticket's one page loop with about 25 fewer lines.

Findings

  • should-fix — CLIENT_MAX_PAGE and its spec exist only for each other (paginate.ts:12).
  • consider — the fan-out window is machinery for an unreachable burst (paginate.ts:32).
  • consider — the raw-response rule is stated three times (fetch.ts:232).

What was checked

Read whole: paginate.ts, paginate.test.ts, fetch.ts, client.ts, types/geojson.ts, types/payload/response-types.ts, docs/rules/data-layer.md, and the fetch.test.ts diff. Consumer side, in the SahajCloud checkout: Events/endpoints/geojson.ts — toBoolean(undefined) returns undefined, so Payload's default pagination applies and the walk really paginates — plus plugins/usage/{constants,hooks}.ts for both ceilings. Confirmed the SDK's buildSearchParams joins an array sort with commas. Grepped every sdk.find call site in src/: these three are the only collection list reads, so no remaining read silently truncates to Payload's default 10. data-layer.md was the only doc naming the old shape, and this PR updates it.

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


Generated by Claude Code

Comment thread src/config/api/paginate.ts Resolved
Comment thread src/config/api/paginate.ts Resolved
Comment thread src/config/api/fetch.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Oct 11, 2026
`CLIENT_MAX_PAGE` had no production reader. Its only consumer asserted
`MAX_PAGE_WALK <= CLIENT_MAX_PAGE` over two literals in the same file, so the
spec could go red only if someone edited one while reading the other — an
assertion `docs/testing.md` asks to have failed once, and this one cannot.

`MAX_PAGE_WALK = 20` already makes a refused `page` unreachable. The ceiling it
stays under is a fact about the wire, so it moves into that constant's docblock.

Refs #253

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0122oCx3rG9RVVH4GmdoUu4D
The three-line ⚠ was the fourth statement of one rule in this diff:
`docs/rules/data-layer.md` carries the mechanism and the consequence,
`fetch.test.ts` pins it, and `types/geojson.ts` names it on the schema that
strips the member. The code beside it already reads `data.totalPages` off the
unparsed response, so the site needs the rule and a pointer, not the story.

Refs #253

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0122oCx3rG9RVVH4GmdoUu4D
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 6c2e61c
Status: ✅  Deploy successful!
Preview URL: https://579a7a7a.sahajatlas.pages.dev
Branch Preview URL: https://claude-refactor-253-paginate.sahajatlas.pages.dev

View logs

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Review addressed — 2 adopted, 1 rebutted. Pushed 6c2e61c.

  • Adopted (paginate.ts:12) — 08b62da deletes CLIENT_MAX_PAGE and the spec that was its only reader. The 10000 ceiling is a line in MAX_PAGE_WALK's docblock now.
  • Adopted (fetch.ts:232) — 6c2e61c cuts the raw-response ⚠ to one line pointing at docs/rules/data-layer.md, which keeps the mechanism.
  • Rebutted (paginate.ts:32) — the fan-out window stays. It is what makes stops issuing pages once one fails pass, and 19 reads in one millisecond from a host page is the shape createPrefetchIntent already caps at 2.

Lean gate green: lint + typecheck + 1694 unit specs. PR body refreshed — the contract block and the spec count were false after the first commit.

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


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Oct 11, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review October 11, 2026 16:40
@sydevs-bot
sydevs-bot requested a review from Ardnived October 11, 2026 16:40
@sydevs-bot
sydevs-bot enabled auto-merge October 11, 2026 16:40
@sydevs-bot
sydevs-bot added this pull request to the merge queue Oct 11, 2026
Merged via the queue into main with commit a5a66d9 Oct 11, 2026
56 of 59 checks passed
@sydevs-bot
sydevs-bot deleted the claude/refactor-253-paginate-wholesale-reads branch October 11, 2026 19:38
@sydevs-bot sydevs-bot moved this from Revising to Done in SYDevelopers Technical Roadmap Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

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

3 participants