Skip to content

fix(core): implement pagination for search() and searchCollection() (#1463) - #1578

Merged
ascorbic merged 3 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1463-search-pagination
Jul 9, 2026
Merged

ascorbic merged 3 commits into
emdash-cms:mainfrom
Emdash-Bug-Testing:fix/1463-search-pagination

Conversation

@ColoradoClimbr

Copy link
Copy Markdown
Contributor

What does this PR do?

The search API advertised keyset pagination through its types — SearchOptions.cursor and SearchResponse.nextCursor — but searchWithDb never read the incoming cursor nor populated nextCursor. Results were silently capped at limit with no way to fetch a second page, so any "load more" wired against the documented shape got a button that never appears (and a cursor that's discarded).

This implements real pagination for both search() and searchCollection().

Why offset, not pure keyset: search results are merged from per-collection FTS queries and re-sorted by bm25 score, so there's no single stable keyset column to encode the way getEmDashCollection encodes (orderValue, id). Instead we page the merged, score-sorted set by offset, carried opaquely in the cursor's orderValue — reusing encodeCursor/decodeCursor so the cursor keeps the same base64-JSON shape and InvalidCursorError handling as the rest of the API.

Each collection fetches its top (offset + limit + 1) rows, which is exactly what's needed for the merged window [offset, offset + limit) to rank correctly even when the whole window comes from one collection, plus one row to detect a further page. A nextCursor is issued only when at least one result exists past the page.

  • search() / searchWithDb and searchCollection() both honour cursor and return nextCursor.
  • The /_emdash/api/search endpoint now accepts a cursor query param and returns nextCursor; a malformed cursor surfaces as 400 INVALID_CURSOR via the existing handleError mapping.

Closes #1463

Type of change

  • Bug fix

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation — n/a, no admin UI strings (server-side search API + docs)
  • I have added a changeset
  • New features link to an approved Discussion — n/a, makes an already-advertised API actually work

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 ultracode

Screenshots / test output

New tests/integration/search/pagination.test.ts covers: nextCursor presence past the limit, omission on the final page, a cursor walk over disjoint pages covering every match exactly once, malformed-cursor rejection, and single-collection pagination.

Test Files  8 passed (8)
     Tests  45 passed (45)

…1463)

The search API advertised keyset pagination through its types
(SearchOptions.cursor, SearchResponse.nextCursor) but searchWithDb never
read the incoming cursor nor populated nextCursor, so results were silently
capped at `limit` with no way to fetch a second page — "load more" buttons
wired against the documented shape never appeared.

Results are merged from per-collection FTS queries and re-sorted by score, so
there is no single stable keyset column to encode the way getEmDashCollection
does. Page the merged, score-sorted set by offset instead, carried opaquely in
the cursor's orderValue (reusing encodeCursor/decodeCursor for the same
base64-JSON shape and InvalidCursorError handling). Each collection fetches its
top (offset + limit + 1) rows so the merged window ranks correctly and a
further page is detectable; a nextCursor is issued only when more results
exist past the page. searchCollection() gets the same treatment.

The /_emdash/api/search endpoint now accepts a `cursor` query param and returns
nextCursor; a malformed cursor surfaces as a 400 INVALID_CURSOR via the
existing handleError mapping.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@changeset-bot

changeset-bot Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: b5b49bd

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Minor
@emdash-cms/cloudflare Minor
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Minor
@emdash-cms/auth Minor
@emdash-cms/blocks Minor
@emdash-cms/gutenberg-to-portable-text Minor
@emdash-cms/x402 Minor
create-emdash Minor
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@emdashbot

emdashbot Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Could not push formatting changes to this fork. The contributor may have "Allow edits by maintainers" disabled.

Please run the formatter locally:

pnpm format

@pkg-pr-new

pkg-pr-new Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1578

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1578

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1578

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1578

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1578

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1578

emdash

npm i https://pkg.pr.new/emdash@1578

create-emdash

npm i https://pkg.pr.new/create-emdash@1578

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1578

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1578

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1578

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1578

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1578

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1578

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1578

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1578

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1578

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1578

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1578

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1578

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1578

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1578

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1578

commit: b5b49bd

Convert code-block indentation to tabs to satisfy `oxfmt --check`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jun 24, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is the right change: the search API has been advertising cursor/nextCursor that searchWithDb simply ignored, so any "load more" wired against it was broken. Offset-based pagination is a reasonable fit here because cross-collection results are merged and re-sorted by bm25, so there is no stable per-row keyset to encode.

The implementation is sound for the chosen approach. The per-collection fetch of offset + limit + 1 is sufficient to produce the globally-merged window [offset, offset + limit) (any row beyond that window has a within-collection rank of at least offset + limit, so it cannot appear earlier globally), and allResults.length > offset + limit correctly detects a next page. Tests cover the basic cursor walk, final-page omission, malformed cursor rejection, and the single-collection path.

Three gaps remain:

  1. MCP search tool is now inconsistent. It calls searchWithDb but does not expose a cursor parameter, while other MCP list tools do. Pagination works from the HTTP API and the programmatic search() function, but not from MCP.
  2. decodeSearchOffset doesn't verify the cursor marker. It reads orderValue but ignores the id field, so a numeric orderValue from an unrelated cursor (e.g. a content-list cursor) is accepted as a search offset.
  3. No upper bound on decoded offset. Because the cursor is only base64-JSON — not signed — a client can decode, substitute a huge integer, and re-encode. That makes a single request fetch offset + limit + 1 rows per collection, which is a straightforward deep-pagination DoS amplification.

None of these are merge blockers on their own, but they are real consistency/security holes that should be closed before this ships.


Findings

  • [needs fixing] packages/core/src/mcp/server.ts:1739

    The MCP search tool calls searchWithDb, which now supports cursor, but the tool's input schema does not include a cursor parameter. Other MCP list tools already accept one (e.g. cursor: z.string().min(1).max(2048).optional()). Without it, MCP clients cannot consume the new pagination, leaving the MCP surface inconsistent with the HTTP/programmatic API.

    				limit: z.number().int().min(1).max(50).optional().describe("Max results (default 20)"),
    				cursor: z.string().min(1).max(2048).optional().describe("Pagination cursor from a previous response"),
    

    Then pass cursor: args.cursor to the searchWithDb call below.

  • [needs fixing] packages/core/src/search/query.ts:48

    decodeSearchOffset extracts orderValue but ignores the cursor marker stored in the id slot. A cursor from another API (e.g. a content-list cursor) whose orderValue happens to parse as an integer will be accepted as a search offset, producing the wrong page silently instead of failing fast.

    Validate that id === SEARCH_CURSOR_MARKER before trusting orderValue:

    function decodeSearchOffset(cursor: string): number {
    	const { orderValue, id } = decodeCursor(cursor);
    	if (id !== SEARCH_CURSOR_MARKER) {
    		throw new InvalidCursorError(cursor);
    	}
    	const offset = Number(orderValue);
    	if (!Number.isInteger(offset) || offset < 0) {
    		throw new InvalidCursorError(cursor);
    	}
    	return offset;
    }
    
  • [needs fixing] packages/core/src/search/query.ts:48

    The decoded offset is unbounded. Because the cursor is just base64-encoded JSON, a client can forge one with a very large offset, causing searchWithDb to request offset + limit + 1 rows per collection in a single query — a deep-pagination DoS amplification.

    Add a sane maximum offset and reject anything beyond it as an invalid cursor:

    /** Reasonable ceiling for search pagination offset to bound per-collection fetches. */
    const MAX_SEARCH_OFFSET = 10_000;
    
    function decodeSearchOffset(cursor: string): number {
    	const { orderValue, id } = decodeCursor(cursor);
    	if (id !== SEARCH_CURSOR_MARKER) {
    		throw new InvalidCursorError(cursor);
    	}
    	const offset = Number(orderValue);
    	if (!Number.isInteger(offset) || offset < 0 || offset > MAX_SEARCH_OFFSET) {
    		throw new InvalidCursorError(cursor);
    	}
    	return offset;
    }
    

    (The exact cap can be tuned; the important part is bounding the value before it reaches the LIMIT clause.)

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jun 24, 2026
…, cap offset

Addresses review findings on #1578:
- MCP `search` tool now accepts and passes through a `cursor` argument
  so MCP clients can consume the pagination the API and search()
  already advertise.
- decodeSearchOffset now checks the cursor's marker before trusting
  orderValue, so a numeric orderValue from an unrelated cursor type
  (e.g. content-list) is rejected instead of silently misread.
- Adds a MAX_SEARCH_OFFSET ceiling so a forged cursor can't force an
  unbounded offset + limit + 1 fetch per collection.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 3, 2026

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

@ascorbic
ascorbic merged commit 58f594b into emdash-cms:main Jul 9, 2026
45 checks passed
@emdashbot emdashbot Bot mentioned this pull request Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core area/docs bot:review Trigger an emdashbot code review on this PR cla: signed review/needs-rereview New commits since the last review size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

search() ignores the cursor option and never returns nextCursor — pagination is impossible

2 participants