Skip to main content
A search reads only the one target that the read pointer in the PostgreSQL catalog points to. The query handle reads the catalog on every search, sends only allowed bodies to OpenSearch, and returns the results as candidates. Never return candidates to a client as they are: re-check them against the primary first, as shown under “Results are candidates”.

Creating a query handle

A Sonamu application creates the handle with createSonamuSearchQueries from @sonamu-kit/opensearch/sonamu.
search/client.ts
The factory only validates options; it creates no connection and reads no catalog. Invalid options fail at once with SearchConfigurationError: limits.timeoutMs longer than maxSearchLifetimeMs, a signing key shorter than 32 bytes, or duplicate key IDs. If the handle is created at module load, as in the example, every process that imports that module needs the signing key (Setup). Code that does not use Sonamu passes a reader made by createPostgresCatalogReader from @sonamu-kit/opensearch/postgres to createSearchQueries from the root entry point. That form cannot detect another framework’s transactions, so keeping calls outside transactions is the caller’s job.

No searching inside a transaction

Called inside an active Sonamu transaction (@transactional, puri.transaction(), DB.runWithTransactionScope), search and closeCursor of createSonamuSearchQueries reject with SearchInTransactionError (details.reason ambient-transaction) before any I/O, for two reasons:
  • The catalog lookup takes a second connection from the pool instead of using the surrounding transaction. Searching while a transaction holds a connection can exhaust the pool.
  • The caller might assume the catalog is read in the transaction’s snapshot. It always reads the latest committed pointer.
Finish the database work, then search outside the transaction. In Sonamu test mode, while a test transaction is open DB.getDB("w") returns that transaction, so the catalog lookup fails with SearchConfigurationError (primary-is-transaction). Managed search cannot be used inside Sonamu’s transactional test fixtures.

The search body

The body of search({ body }) is OpenSearch DSL, but only these top-level keys are accepted: A body whose JSON exceeds maxQueryBodyBytes is rejected with SearchQueryInvalid (body-too-large) before it is copied. Any other key (aggs, suggest, pit, post_filter, from, index, and so on) is SearchQueryInvalid (unsupported-body-key). Field paths take the doc. prefix. Responses always include sonamu_meta.revision, and only the doc fields that were requested and that the policy allows.
The contents of query, sort, and highlight are sent unchecked; the package treats them as values built by trusted server code. Never put JSON from the client into them. Accept values such as the search text and build the query on the server.
The caller cannot choose the index: the handle has no index option, and the body’s index and pit keys are rejected. A new search always reads from the catalog’s read pointer, and a continued search only from the target its cursor pinned. A search therefore cannot read a retiring index or another namespace’s index, and retirement can be sure no search still reads the old index once cursor and search lifetimes have passed. If the catalog cannot be read, the search fails with SearchCatalogUnavailable instead of falling back to a cached pointer.

Rendering highlights

Highlight fragments contain user-written text, and OpenSearch does not escape it. Rendering fragments with the default tags (<em>) as HTML opens an XSS hole. Never interpret a fragment as HTML. The safe way is to replace pre_tags and post_tags with characters that never occur in user text, such as the private-use characters U+E000 and U+E001, split the fragment on them on screen, and render both the matches and the rest as text.
The example’s helper builds the highlight clause for the search body and splits a fragment into text segments. The screen creates one text node per segment and never uses innerHTML or dangerouslySetInnerHTML. miomock walkthrough has a screen that works this way.
search/highlight.ts

Results are candidates

search returns { target, hits, total?, timedOut, nextCursor? }. Each candidate holds id, the indexed revision, score, and, if requested, sort, source (allowed doc fields only), and highlight. total is present only when track_total_hits is allowed. Because the index can lag, a candidate is not an authorized record. Before responding, re-check the current record and its permissions on the primary using the candidate IDs. The example searches chat messages like this:
application/chat-message.search.ts
  1. Read the rooms the caller can read now, from the primary.
  2. Search with a filter on those rooms. Even when there are none, send the empty list rather than dropping the filter.
  3. Look the candidate IDs up again against current permissions and state.
  4. Return the current records, not the indexed content, in search order.
This example requests the default highlight tags, so its highlights must be rendered as text, never as HTML; use highlightClause above to get markers that can be split safely. The integration tests check each case this flow guards against:

Cursors and PIT

To page through results, pass paginate, then pass the same body and the cursor on the next page.
  • paginate needs a sort in the body and signing keys. Without them the search fails with SearchQueryInvalid (paginate-requires-sort) or SearchConfigurationError (cursors-not-configured).
  • nextCursor is returned only when the page is full and the cursor has lifetime left.
  • A cursor continues only the same search. It carries a hash of the body without size and search_after, so a different body gives SearchCursorExpired (query-mismatch). A cursor and search_after cannot be combined.
  • paginate: { pit: true } opens a point in time on the target’s physical index to keep results fixed across pages. keep_alive is the shorter of maxPitKeepAliveMs and the cursor’s remaining lifetime, set again on each page. The PIT is extended on each page but never past the cursor’s expiry. When no next cursor is returned, the package closes the PIT; to stop early, close it with closeCursor(cursor).
  • Without a PIT (paginate: {}), a continued page is a plain search_after search. If the index changes between pages, results can shift accordingly, and the only limit on how long the cursor continues is the signed expiry, fixed at issue and checked against database time.

Cursor contents and lifetime

A cursor holds the target ID, the fingerprint, the query hash, the issue time, the expiry, the sort values of the last candidate, the PIT ID, the number read so far, and the read generation. It is base64url JSON and only signed, with HMAC-SHA256, not encrypted, so the client can read it. The sort values are the last candidate’s indexed values, so do not sort on fields the client must not see. The first key in the list signs; every key verifies. To rotate keys, deploy with the new key first and the old one after it, wait until every cursor signed with the old key has expired (maxCursorLifetimeMs), then remove the old key. A cursor signed with a key not in the list is SearchCursorExpired (unknown-key). The expiry is the issue time plus maxCursorLifetimeMs, fixed at issue and never extended. Time is measured on the database clock. A handle’s lifetimes (limits) cannot exceed the maximums the administrative handle recorded in read_heads; if they do, the search fails with SearchConfigurationError (lifetime-exceeds-catalog). A cursor becomes invalid in these cases. All are SearchCursorExpired, and the client must start a new search: While capture is suspended, a continued search is SearchRebuildRequired. A cutover, on the other hand, does not invalidate cursors: a cursor issued before the cutover continues on the old target to the end, and retirement does not delete the old index until that cursor’s lifetime has passed. A PIT request beyond the engine’s point_in_time.max_keep_alive is SearchQueryInvalid (pit-request-rejected).

When search is unavailable

SearchDefinitionMismatch is raised without any request to the engine. It occurs when search processes are deployed before the switch to a new definition, or when a process that knows only the old definition remains. During the transition, list both the old and the new fingerprint in supportedFingerprints. A paused target can still be read; only its indexing has stopped, so results may be stale.

Errors and HTTP responses

Map a search error to an HTTP status by its class and retryable, and render the message again in the request’s locale.
search/errors.ts
sonamu.config.ts
  • An invalid body (SearchQueryInvalid) and an invalidated cursor (SearchCursorExpired) are 400, because the client can fix them. A client that gets a cursor error starts a new search.
  • A search inside a transaction (SearchInTransactionError) is a defect in server code, so 500.
  • Everything else is 503 if retryable, otherwise 500. Only search is unavailable; other APIs are unaffected. One search must finish within the shorter of timeoutMs and maxSearchLifetimeMs; past that it fails with SearchTimeout (search-deadline).
  • error.localize(locale) renders the message in a different language per request. Always branch on the class, code, and details.reason, never on the message.

Next steps

Index administration

Creating targets, rebuilding, cutover, retirement

Operations

Monitoring, tuning, permissions, known limits