Repository navigation
refactor(api): paginate the three pagination: false SahajCloud reads - #277
Conversation
`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
left a comment
There was a problem hiding this comment.
🧐 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_PAGEand 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
`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
Deploying sahajatlas-design with
|
| Latest commit: |
6c2e61c
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://54a8ee72.sahajatlas-design.pages.dev |
| Branch Preview URL: | https://claude-refactor-253-paginate.sahajatlas-design.pages.dev |
Deploying sahajatlas with
|
| Latest commit: |
6c2e61c
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://579a7a7a.sahajatlas.pages.dev |
| Branch Preview URL: | https://claude-refactor-253-paginate.sahajatlas.pages.dev |
|
Review addressed — 2 adopted, 1 rebutted. Pushed 6c2e61c.
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 |
Summary
totalPagesinstead of asking for a whole table.pagination: false, so this repo has to ship first.Change outline
All three reads still hand their callers one whole array —
getGeojsonalone has six direct Reactcall sites, and
loadGeojsoncaches one['geojson']entry thatindexedFeedmemoises per feedreference. What changed is how that array is assembled.
Flow
getEventTitlesis the same shape withwalkSort().getGeojsondiffers in one place, and thatplace is the trap:
Contract — what makes a walk sound, and who owns it
walkSortis the seam, not a comment at each call site: aLIMIT/OFFSETwalk needs a totalorder, and a fourth walked read written with a non-unique sort would silently repeat and drop rows
with every gate green.
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 untouchedPreview
change, so the Ladle playground is unaffected.
Test results
pnpm lint+pnpm typecheck+pnpm test:run(1694 passed)paginate.test.ts, 4 new infetch.test.tspnpm build+pnpm size, within budget on all three graphsManual verification
limit=2000on 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.
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
LIMIT/OFFSETwalk is not immune to the matching set changing between page requests —
walkSortfixes tieordering, not set mutation. Above 2000 rows, an event crossing
schedule.lastDatebetween thepage-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 twoid-sorted reads, but it issequential,
getRegionscannot use it with its display sort, and the ticket chose thetotalPagesshape explicitly. The path needs ~4× growth plus a sub-second race, so I left theshape 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.
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 kindwhose fallback offers retry and report.
2…N fan-out, and this does not make it faster. It bounds its width, because an unwindowed
Promise.allwould put 19 reads on the wire at once from inside a host page, doubled at mountwhere
warmCacheswalks regions and the feed together. That is the storm shape this repoalready caps at 2 in flight for speculative prefetch. One line reverses it if you disagree.
MAX_PAGE_WALKlives beside the loop, not inquery-client.tswith the other pressureknobs. It is read by exactly one function, in the file that holds the loop it bounds; splitting
the two seemed worse than the inconsistency.
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:
refuses a response that reports no page countrefuses a feed whose page count never endstotalPagesread off the parsed valuegetRegionsuite includedsort: 'name'with noidtiebreakergetRegionsrequest-shape specwalkSortwithout its terminal keywalkSortspec and three request-shape specsPromise.allover the whole rangeWhy the sort keys changed.
nameonregionsis a plain required text field with nounique(SahajCloud
src/collections/Regions/Regions.ts), so anOFFSETwalk ordered by it has no totalorder 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'sbuildSearchParamsjoins anarray sort into
sort=name,id, and payload 3.90.2'ssanitizeSortParamssplits a string back oncommas, so the array survives the round trip. The geojson endpoint forwards
sortinto its ownpayload.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
COUNTthatpagination: falseused to skip — which also multiplies the SahajCloud-internalregionsreads that selectingwebPathtriggers.getEventTitlesis per-locale, so thatmultiplier bites hardest there.
getGeojsonstopped re-parsing the merged collection on purpose. Each page's features areparsed 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.
totalPagesis the one wire value validated outside zod. It arrives throughrequestJson<EventFeatureCollection>, an unchecked cast, and is gated byNumber.isIntegerinpaginate.tsrather than by a schema. Deliberate: it is loop control, not data, and the refusalhas to happen before anything is parsed.
Reviews run:
/simplify(four lenses: reuse, simplification, efficiency, altitude),/code-review high, and/security-review— the last becausesrc/config/api/is on this repo'ssecurity trigger paths. Security found nothing, having traced the feed's
webPathsinks tosafePathandisSafeHref, theas Tcast's two readers, and what reaches an error message.Dismissed, with reasons: asserting
limit: CLIENT_PAGE_LIMITinstead of the literal2000inthe fetch specs (the literal is SahajCloud's wire number — if the constant moved, these should go
red, not follow it); folding the two
sdk.findwalks into a sharedfindAllPages(the wrapperwould have to carry the SDK's generic
selecttyping, whichdocs/rules/data-layer.mdcallsload-bearing, to save six lines across two call sites); passing
limitdown through thereadPagecallback (a caller can ignore a parameter as easily as forget a field, and the10-row-default failure it guards against is already loud — 646 regions at 10 a page is 65 pages,
over the cap); threading an
AbortControllerthrough the walk (the window already stops issuingpages after a failure); and a source-walking spec that fails any
sdk.findcall site lacking alimit— the right altitude for the rule and the repo's own precedent (href.test.ts), but ithas to tell collection reads from
findByID, globals and custom endpoints to avoid firing onreads 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_PAGEwas exported with no production reader:its only consumer asserted
MAX_PAGE_WALK <= CLIENT_MAX_PAGEover 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. ThegetGeojsonraw-response ⚠ was thefourth 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.mdandCHANGELOG.mdcarry no entry: sameorigin, same attributes, same CSP. Only the request count to
VITE_SAHAJCLOUD_URLchanges, and atcurrent volume it does not change either.
Closes #253
Generated by Claude Code