createSearchAdmin creates, in the order you use them, and the sonamu search commands that run them from a shell. Procedures for recovering a target and for copied or restored databases are in Recovery runbooks.
The administrative handle
Create the handle withcreateSearchAdmin from @sonamu-kit/opensearch/admin, using administrator credentials: the PostgreSQL admin role, and an OpenSearch user that can create and delete indexes. Do not give these credentials to runtime processes.
search/administration.ts
instanceName from each environmentβs configuration (production, staging, a developer copy). A name fixed in code is the same in every environment and protects nothing; what the name does is described under βEnvironment namesβ in Recovery runbooks.
The handle never closes the client it was given; whoever created the client closes it.
Without
client, the handle runs only operations that send nothing to OpenSearch: those listed in the exported POSTGRES_ONLY_ADMIN_OPERATIONS (inspect, inspectBuild, runBackfillPage, suspendCapture, remark, retryQuarantined, adoptCopiedStore, changeReadLifetimes), and planCreate for a definition without requiredPlugins. Every other operation refuses with SearchAdminPreconditionFailed (search-client-not-configured) before it reads or writes anything. confirmStoreOwnership is not in the list because it writes to OpenSearch to take target fences back; without a client it runs only while no target that may have a remote index (creating, active, paused, retiring) exists. Use a handle without a client for tools that need no OpenSearch credentials, such as monitoring or repairing marks. createChatSearchMonitor above is one.
The worker and every operation that sends remote requests first check the store binding. If this database is not the one the store was recorded in, or instanceName differs from the recorded name, they refuse with SearchStoreMismatch and send nothing. Cutover and rollback (for the target they move to), resumeTarget and retireTarget also check that this database still holds the targetβs fence. If it was lost, they change nothing and refuse with SearchStoreMismatch (target-fence-lost, with targetId, class, localEpoch and remoteEpoch in details). If the fence cannot be read, the error is a retryable SearchUnavailable (fence-unreadable). Marking, initialize() and search are not blocked. What to do on a copy or after an in-place restore is in Recovery runbooks.
Methods that change state take an audit context { operationId, actor, reason } and record start, success and failure in admin_operations. Do not put secrets in it.
search/administration.ts
The admin lease
Only one administrative operation runs on a logical key at a time. An operation acquires the lease when it starts, extends it while it runs, and releases it at the end whether it succeeds or fails. Calling again with the sameoperationId reuses the same lease.
SearchAdminBusy(retryable): another operation holds the lease (lease-held), or a lock or statement did not finish within its time limit. Run the operation again a little later.SearchAdminLeaseLost(retryable): the lease expired or passed to another operation midway, and none of the operationβs later database writes took effect. Run the same operation again; it continues where it stopped.- If an administrative process dies, another operation can take the lease only after
adminLeaseMshas passed.
Time limit of one request = (If this value is below one second, the operation refuses withadminLeaseMsβ 4 ΓstatementTimeoutMs) / 3
SearchConfigurationError (admin-lease-too-short) before it sends or writes anything. With the recommended values it is (5 min β 4 Γ 30 s) / 3 = 1 minute; the clientβs requestTimeoutMs (30 s) is shorter, so that applies.
Running administration from the CLI
@sonamu-kit/opensearch/sonamu ships the administrative operations as sonamu search commands, a plugin for the sonamu CLI. Each command builds an administrative handle from a setup your application provides, runs one or more SearchAdmin operations, and prints the result. Use the commands for operator work from a shell. Call SearchAdmin from code when you need a step the commands do not offer (such as changeReadLifetimes, or planCreate and executeCreate run separately) or your own checks between steps. The lease, refusals and procedures on this page and in Recovery runbooks apply to both. How the CLI loads plugins is described under βCLI pluginsβ in the CLI reference.
Registering the plugin
Add the plugin tocli.plugins in sonamu.config.ts, and build the setup in a separate module:
sonamu.config.ts
search/cli-setup.ts
load runs inside each command, after Sonamu.init. Import the setup module lazily, as above, so that evaluating sonamu.config.ts loads no search module. createSearchCliPlugin checks its options when the config is evaluated (invalid-cli-options); the setup is checked each time a command runs, and a malformed one fails with SearchConfigurationError (invalid-cli-setup, with the offending field in details.path).
The CLI runs the built code: it reads the plugin from
dist/sonamu.config.js, and load imports the built setup module. Run sonamu build after you register the plugin and after every change to the setup or a definition; otherwise init plans from the old definition. Without a build, search is an unknown command (exit code 2), and the error says the plugin commands could not be loaded and why.
Commands
pnpm sonamu search <command> [logicalKey] [options]. Options take a value as --option value; --ids repeats, one ID per flag (--ids 3 --ids 7).
--limit is the page size and defaults to 500. --build defaults to the logical keyβs open build; without one the command refuses with no-open-build. Every command that changes state also takes --operation-id, --actor and --reason for the audit context. By default each operation gets a new operation ID (sonamu-search-<command>-<UUID>), the actor is cli: followed by the operating system user, and the reason is sonamu search <command>.
Approval. A command that changes state runs only after approval. On a terminal the CLI asks before it runs; --confirm skips the question. Without a terminal, or with --non-interactive, it needs --execute --confirm and otherwise exits with code 3 (CONFIRMATION_REQUIRED) before anything runs. init and cutover are the exceptions: without --execute they run as a dry run, which needs no approval and changes nothing. For reconcile, adopt-store and confirm-ownership, the approval stands for the operator confirmation the operation requires (confirmQuiescent, confirmCopy, confirmSoleOwner), so check the precondition in the runbook before you approve.
Logical key. When the setupβs definitions have one logical key, the argument may be omitted. With several, a command that takes it refuses without it (logical-key-required, with the keys in details.keys), and a key without a definition is refused with logical-key-unknown. Both exit with code 2.
Output and failures
A command with one result prints it when it finishes: formatted for people, or as{"ok":true,"command":"search.inspect","data":β¦} with --json. init (when executed), backfill, retire-old, verify, remark, retry-quarantined and drain stream instead: each step is one JSON line such as {"event":"backfill.page","data":β¦}, written as it happens, with or without --json, and no final result line follows. The events are init.plan, init.created, init.build, init.next, backfill.page, cutover.check, cutover.done, retire.none, retire.start, retire.done, verify.page, remark.page, remark.done, retry.page, retry.done, drain.round, drain.<worker event> and drain.stopped.
With --json, a failure is one line on stdout: {"ok":false,"command":β¦,"error":{"code","message","hint","details"},"exitCode":β¦}. Without it, the message and the hint go to stderr. code is the packageβs error code (for example SEARCH_ADMIN_PRECONDITION_FAILED), details.reason is the refusal reason this page lists, and details.retryable says whether running the command again can succeed. Detail keys that look like credentials are dropped. A SearchStoreMismatch carries a hint that names sonamu search adopt-store for a copy or restore and sonamu search confirm-ownership for the same store; both are in Recovery runbooks. When a streaming command fails, the steps already reported have taken effect, and running it again continues where it stopped.
Creating the first target
The first target and a rebuild after a definition change follow the same flow: open a build, fill it from the source, let the worker drain the backlog, and cut over.search/administration.ts
-
Open the build with
beginRebuild({ logicalKey, fingerprint }, audit). With no read target it creates the target and opens a first build (initial); with one it opens a rebuild (rebuild). If an open build with the same fingerprint exists, it writes nothing and returns that build, so running the same call continues a flow that stopped midway. Check:inspect().openBuildshows the build. If the call refuses withremote-create-ambiguous, the createβs outcome is unknown; follow βAn ambiguous createβ in Recovery runbooks. -
Call
runBackfillPage(buildId, { limit })until it returnsdone. Check:inspectBuild(buildId).phaseiscatching_up. If a call fails, call it again; it continues from the recorded page cursor. -
Let the worker drain the new targetβs backlog.
Check:
inspectBuild(buildId).eligibleForCutoveristrue. If not,blockersnames the reasons; see the table under βRebuild and cutoverβ. -
Run
cutover(buildId, audit). Check:inspect().readHead.targetIdnames the new target. If it refuses, nothing changed: fix the cause indetails.blockersand run it again.
beginRebuild runs internally:
search/administration.ts
-
Run
planCreate(logicalKey, { fingerprint }). It creates and records nothing and returns a plan: the new target ID, the physical index and write alias names, the settings and mappings to send,missingPlugins, and warnings (capture-suspended,index-has-live-target,plugins-missing). When the handle holds more than one definition for the key, as during a rebuild,fingerprintpicks one; with a single definition it may be omitted. Check:missingPluginsandwarningsare empty. If not, stop and resolve them; the example throws before creating anything. -
Run
executeCreate(plan, audit). If a plugin is missing, it refuses withplugins-missingand does nothing. Otherwise it records the target intent and the create attempt, creates the index and its write alias in one request (the index_metacarries the store identity), reads the mapping and alias back to verify them, registers the target, and opens the first build. Check: it returns a target handle. Calling it again with the same plan only checks the remote side of the registered target and returns the same handle; it does not create again. If it refuses withremote-create-ambiguous(lost response, 5xx), the target ID stays blocked untilreconcileCreate; see βRemote create stateβ below.
Rebuild and cutover
To rebuild after a definition change, give the administrative handle both the old and the new definition and follow the steps in βCreating the first targetβ:beginRebuild opens a rebuild build. A build moves through created β backfilling β catching_up β serving.
- Backfill: the first call to
runBackfillPage(buildId, { limit })records the scan boundary from the definitionβscaptureScanBoundary. Each later call reads one page fromscanSourceIds, creates ledger rows at revision 1 for IDs that have none, and reserves intents on the new target at the current ledger revision. After the last page the build becomescatching_up. Each call acquires and releases the lease and writes only after comparing the page cursor, so a page is never applied twice and you can stop and continue at any point. - Dual writes: from the moment the new target is registered,
markChangedrecords intents for both the old and the new target. Writes during the backfill, and IDs created after the scan boundary, reach the new target too. - Catching up: the worker drains the new targetβs backlog.
inspectBuild(buildId)shows progress and the cutover blockers without taking locks.
The backlog and quarantine checks count only what the decision needs: the backlog count stops at
maxPendingDocuments + 1 rows, and quarantine is an existence check. Their cost does not grow with the backlog.
cutover(buildId, audit) checks the following in order. If any check fails, it changes nothing and refuses with SearchAdminPreconditionFailed (details.reason is the first blocker, details.blockers lists all of them).
- Remote check: the new targetβs index exists, its
_metanames this target and this store, and the write alias points at it. Nothing missing is recreated. Then the new targetβs fence is checked. - Sample verification: it picks
sampleSizeIDs from the ledger, projects them in one snapshot, and compares revision, deleted flag and hash with the documents in the new index. Documents still pending on the new target pass. Any violation givesverification-failed. - It checks the blockers in the table again in one transaction, and moves the read pointer and the build phase in the same transaction.
eligibleForCutover reflects only the conditions PostgreSQL can check, so the outcome of checks 1 and 2 is known only when cutover runs. A rebuild stays serving after cutover and can be rolled back until the old target is retired.
Rollback
search/administration.ts
rollback(buildId, audit) moves the read pointer of a serving build back to the old target. It refuses unless the old target is still writable and in the same epoch, its definition is in the administrative handle, and the read pointer has not moved elsewhere since the cutover. Check that inspect().readHead.targetId names the old target afterwards. Dual writes continue, so you can cutover again; cutover β rollback β cutover may repeat. Retiring the old target ends the chance to roll back.
The read pointer
The read pointer is one row per logical key in theread_heads table. It holds the target to read now, a generation number, whether a rebuild is required, and the read lifetime maximums. Every new search reads this row, and a cursor stays pinned to the target it was issued on. A search started before a cutover commits finishes on the old target; a search started after the commit reads the new one. Because the pointer lives in PostgreSQL, cutover and rollback happen in one transaction and no OpenSearch alias changes.
Read lifetimes
The read lifetime maximums (maxSearchLifetimeMs, maxCursorLifetimeMs, maxPitKeepAliveMs) and the retirement safety margin are recorded in read_heads when the first target is created. lifetimes given to an administrative handle after that are not used. Read the recorded values with inspect().lifetimes, and change them only with changeReadLifetimes(logicalKey, lifetimes, audit), which takes all four values.
search/administration.ts
- Raising any value, and lowering
maxPitKeepAliveMs, take effect at once. Raise the recorded value before you give a query handle a longer lifetime: a query handle whose lifetime exceeds the recorded value fails its searches withlifetime-exceeds-catalog. - Lowering the search lifetime, the cursor lifetime or the safety margin is refused with
SearchAdminPreconditionFailed(read-lifetime-decrease-unsupported), and nothing changes. The retirement grace is their sum, and cursors issued under a longer value may still be alive. - To shorten the effective cursor lifetime, lower it in the query handleβs settings. A setting below the recorded value is always allowed; the only cost of a high recorded value is how long retirement waits.
Retirement
retireTarget(targetId, audit) deletes a target that nobody reads any more. Deleting the physical index cannot be undone: after retirement the build can no longer be rolled back, and the targetβs names are never created again. Retirement starts only after the read grace period has passed:
Grace =The three values are the ones recorded inmaxCursorLifetimeMs+maxSearchLifetimeMs+retirementSafetyMarginMs
read_heads. The grace counts from the confirmed deselection time, which is recorded after the cutover or rollback commits. If no confirmed time exists yet, retirement records it first and refuses. A target that was never a read target has no grace period. With the recommended values the grace is 10 min + 30 s + 5 min = 15 min 30 s.
search/administration.ts
-
Run
retireTarget(targetId, audit). Check: the call returns andinspect()shows the target asretired. If it refuses withretirement-grace-pending, run it again atdetails.earliestAtMs(the example returns that time). For the other refusals, see the table below. If it fails midway, the same call continues where it stopped.
- It checks the confirmed deselection time, the targetβs fence and the refusals, closes the
servingbuild whose old target this is, and turns off writes for the target. - It checks that the indexβs
_metanames this target and this store. - It removes the write alias. A bulk arriving later is rejected by
require_aliasand cannot create an index. - It waits until
leaseDurationMs + requestTimeoutMs(workerBounds) has passed since the alias was removed and no lease is alive. With the recommended values that is 2 min 30 s. - It checks
_metaand the fence again, then deletes the physical index. The fence document goes with the index. - It deletes the remaining intents and runtime rows in batches and marks the target
retired, deleting its fence row in the same transaction. A long cleanup extends the admin lease between batches.
_meta has no store identity, only the target is checked.
If the store identity in the index
_meta differs from this store, retirement refuses with SearchStoreMismatch (remote-store-mismatch) and touches neither the alias nor the index.
Suspending capture and resuming for a rebuild
Suspending capture trades search availability for a rebuild. Use it when the ledger cannot be trusted, for example after the source database was restored. The procedure, with its example, is βSource database restoreβ in Recovery runbooks.suspendCapture(logicalKey, audit) has these effects:
markChangedreturns"suspended"and leaves no intents. Domain writes keep committing.- The read pointer becomes rebuild-required, so searches get
SearchRebuildRequired. - All existing targets and open builds become the old epoch and are never used again: the worker does not claim them, they cannot be cut over or rolled back, and cursors issued before are invalid for good.
- If capture is already suspended, nothing changes.
resumeCaptureForRebuild(logicalKey, audit) creates a new target in a new epoch and turns capture back on in the commit that registers that target. If capture is not suspended, it refuses without a remote command (capture-not-suspended). Searches return only after you backfill the returned build and cut it over, and that build cannot be rolled back.
The costs: search is unavailable from the suspension until the resume build is cut over, and the whole source has to be filled again. Changes made during the suspension leave no intents, but the backfill reads the current source, so the new target includes them. Retire the old-epoch targets afterwards.
Remote create state
An index creation request can end without a known outcome. The package records the outcome per target as a state and never recreates or deletes anything on its own. The procedure for an unknown outcome is βAn ambiguous createβ in Recovery runbooks.- For an identity in
in_flightorambiguous, registration, re-creation, retirement, and the next creation for the logical key are all refused without a remote command (remote-create-ambiguous,remote-create-unresolved). - Only
reconcileCreate(targetId, { confirmQuiescent: true }, audit)resolves it. Call it only after confirming that the process and requests that were creating this identity can no longer arrive;confirmQuiescentrecords that you confirmed this. Without it the call refuses withquiescence-not-confirmed. - Reconciliation only reads the remote side and creates or deletes nothing. If the index, the write alias and a matching
_metaall exist, the result isverified; otherwise it isabandoned.abandonedchanges only PostgreSQL: the remote index is neither adopted nor deleted, and the operator decides whether to delete a leftover index. - After
verified,executeCreatewith the same plan finishes the registration without a remote command. Afterabandoned, the identity can never be used again; start over with a new plan. - If an index with the same name exists with a different
_meta, the create refuses withremote-index-conflictand neither adopts nor deletes it. If a registered targetβs index or alias has vanished, the error isSearchTargetUnavailableand nothing is recreated. - A creator that lost its lease or attempt token cannot record a late success, and it does not delete anything to compensate.
Inspecting state
inspect(logicalKey, options) reads one logical keyβs PostgreSQL state without locks or a lease. It does not check remote indexes (a targetβs remote is always null).
A targetβs
backlog holds pending (intents not quarantined), quarantined, leased (live leases), delayed (waiting for a retry), intents, oldestPendingAgeMs, and exact and limit, which say whether the counts are exact. The default is bounded mode: each count reads at most 10,000 rows, so frequent reads do no work proportional to the backlog. When exact is false, a count means βat least this manyβ. Change the bound with { countLimit } (1 to 1,000,000). Retired, failed and detached targets have a null backlog.
search/administration.ts
search/administration.ts
fence is the fence this database recorded. inspect reads it from PostgreSQL only, not from the remote side.
The workerβs
target-fence-lost event and status().fenceLostTargets report the same losses. If every binding value is true and a fence is still lost, another database byte-identical to this one (a physical copy, such as one made with pg_basebackup) is writing to the same OpenSearch index, or the index went back in time. The procedure is βA lost target fenceβ in Recovery runbooks.
search/administration.ts
Next steps
Recovery runbooks
Copied databases, quarantine, paused targets, ambiguous creates, source restores
Operations
Monitoring, tuning, permissions, known limits