Skip to main content
Every write path that changes indexed data calls markChanged in the same transaction as the write. The mark is recorded in PostgreSQL only, as part of that transaction: if it cannot be recorded, the write does not commit either. The worker later projects the marked documents again and indexes them. A mark records which document changed, not what changed, so however often a document is marked, the worker indexes its state at the time it projects.

Calling markChanged

From a Sonamu model

The handle created by createSonamuSynchronization has two methods:
  • markChangedIn(trx, logicalKey, ids) takes the PuriTransactionWrapper that a transaction() callback receives.
  • markChanged(logicalKey, ids) uses the Sonamu "w" transaction that is currently open (inside an @transactional method or puri.transaction()). It never opens a transaction; without an open one it throws SearchInvalidTransaction.
application/chat-message.model.ts
Inside an @transactional method, or a method it calls, use markChanged without a transaction argument; if an outer @transactional is open, its transaction is used. The example below moves messages to another room, which changes their room_id, and marks the moved messages once, sorted.
application/chat-room.model.ts
Code that does not use Sonamu passes a Knex transaction to markChanged(trx, logicalKey, ids) on the handle from createPostgresSynchronization. Either way, statements run only in the transaction passed in; no other connection is used and no transaction is opened. One call does the following:
  1. It checks that the handle is a live transaction. If not, it throws SearchInvalidTransaction without sending any statement.
  2. It checks that the store identity is set, then checks the logical key and the document IDs. A document ID must be a non-empty string with no NUL and no unpaired surrogate, at most 512 UTF-8 bytes, and not the reserved fence document ID __sonamu_fence__. One call takes at most 10,000 IDs by default.
  3. It takes a shared lock on the barrier row of that logical key and checks that the row carries the pinned store identity. Administrative operations such as target registration order themselves against this lock.
  4. It reads the capture mode and the registered write targets. If capture is suspended, it writes nothing and returns "suspended".
  5. It raises each document’s ledger revision by one, records an intent for every registered write target, and returns "recorded".
IDs are deduplicated and processed in UTF-8 byte order. Marking the same document in several calls within one transaction raises its revision once per call, and its intents merge into one.
A logical key enters the catalog when an administrative command records its first target. Before that, markChanged throws SearchNotConfigured; once the target is recorded but not yet registered, it throws SearchNoWriteTarget. Either way the domain transaction does not commit. Deploy code that marks a key only after its first target is registered (Index administration).

Nested transactions and savepoints

  • A nested @transactional method reuses the outer transaction. It is not a separate rollback boundary, so marks made inside commit or roll back with the outer transaction.
  • A manually nested transaction() opens a savepoint. If the savepoint rolls back, the marks made inside it go with it.
  • If the root transaction rolls back, nothing remains in the ledger or in the intents.

Fail-closed behavior

markChanged never lets a domain change commit without its intent. When a package precondition fails, it puts the transaction it received (or the savepoint) into a failed state and then throws a typed error. It does this by running a division by zero, which makes PostgreSQL abort the transaction. Precondition failures: A failed SQL statement has already aborted the transaction, so markChanged translates the error and throws it: When there is no live transaction to fail, the call throws SearchInvalidTransaction without sending any statement: not-a-transaction and completed-transaction from the PostgreSQL handle, and no-active-transaction and not-a-transaction-wrapper from the Sonamu handle.

When the error is swallowed

Do not swallow exceptions from markChanged; let them propagate out of the transaction. If you catch the exception, ignore it, and let the callback return normally, Knex sends COMMIT and finishes without an error, but PostgreSQL rolls back the aborted transaction. The caller believes the write succeeded while nothing was stored. When the call happens inside a savepoint:
  • If the exception propagates out of the savepoint callback, only that savepoint rolls back and the outer transaction stays usable.
  • If the exception is swallowed inside the savepoint, releasing the savepoint fails (SQLSTATE 25P02), and the outer transaction keeps no domain change either.

Ordering across several calls

One call sorts and locks its own IDs, but the order of several calls within one transaction is up to the caller, and two transactions that mark the same documents in different orders can deadlock. To avoid that:
  • Collect the documents a transaction changes and call once per logical key.
  • When marking several logical keys, call them in ascending byte order of the key.
With these rules, overlapping transactions wait for each other and do not deadlock. If they are broken, PostgreSQL ends one side with SQLSTATE 40P01, and the package throws SearchUnavailable with retryable true and details.reason deadlock. Rerun that entire transaction from the start; resending the same statement does not work, because the transaction is already aborted. The helper below reruns a transaction on a serialization failure or a deadlock, after a short random wait so the two sides do not collide again. It decides by structure, never by message: an error the package translated has the code SEARCH_UNAVAILABLE, is retryable, and has details.reason serialization-failure or deadlock; a driver error thrown by an application statement in the same transaction has the SQLSTATE 40001 or 40P01 as its code. Anything else is rethrown. A dropped connection carries the same SEARCH_UNAVAILABLE code (details.reason connection), but whether it committed is unknown, so it is not rerun. run must open the transaction itself: called inside a transaction that is already open, the outer transaction has already failed.
application/transaction-retry.ts
application/chat-message.model.ts

REPEATABLE READ and SERIALIZABLE

A domain write that overlaps an administrator registering a new target ends one of two ways. A READ COMMITTED transaction makes the registration wait if it locked first, and records intents for the new target too if it locked later. A REPEATABLE READ or SERIALIZABLE transaction cannot commit with a snapshot taken before the registration, so it fails with SQLSTATE 40001: a retryable SearchUnavailable with details.reason serialization-failure. Rerunning the whole transaction records intents for both targets. The worker’s housekeeping (leases, acknowledgements, releases) never updates intent rows, so it does not fail REPEATABLE READ domain transactions with 40001.

Deletes and tombstones

Mark deletes too. When the worker runs the projection, the row is gone from the source, so deleted comes back, and the worker indexes a tombstone with a higher revision that carries only sonamu_meta and no body.
application/chat-message.model.ts
The worker never sends a delete request to OpenSearch. The tombstone keeps holding the external version, so an old request sent before the delete and arriving late is rejected by the engine and cannot bring the content back. The ledger row stays too; if a record is created again with the same ID, it is indexed again with a higher revision. Searches exclude tombstones automatically.

Changes the database makes itself

Rows changed by foreign-key ON DELETE CASCADE, SET NULL, SET DEFAULT, ON UPDATE CASCADE, or by triggers are seen by no model method, so nobody marks them. When such a change affects indexed documents, read the affected IDs in the same transaction before changing the parent, then mark them. In the example, deleting a room deletes its messages by CASCADE:
application/chat-message.model.ts
  • SET NULL works the same way. If the projection puts the referencing column into the document, collect the IDs of the referencing rows before deleting the parent and mark them.
  • If the projection reads other tables (for example a room name inside a message document), changes to those tables must also mark every affected document.
  • The foreign-key actions on tables that reference indexed tables, or on tables a projection reads, are listed in pg_constraint under confdeltype and confupdtype. For every action other than NO ACTION or RESTRICT, check that it is covered as above.
Changes made outside the application (SQL run by hand, a restored backup) are not marked. Use the administrative handle to mark the documents again or rebuild the target (Index administration).

When capture is suspended

When an administrator suspends capture, markChanged writes neither ledger rows nor intents and returns "suspended". This result is not an error and does not fail the transaction, so domain writes commit as usual and write paths need no special handling. Changes made during suspension never reach the index, so query handles reject searches with SearchRebuildRequired until a new target is built and cut over. The package never suspends capture on its own because of an error; only an administrative command suspends it.

Error handling

Branch on the error class, code, retryable, and details.reason, never on the message text, which changes with the locale. retryable true means the same call can succeed later without changing code or configuration; on a write path, the same call means rerunning the whole transaction. The errors markChanged throws are listed under Fail-closed behavior above. details holds only stable codes such as sqlstate and reason. Messages and details never contain document bodies, search bodies, or credentials, and messages from the driver or OpenSearch are never passed through. The example below turns search errors into HTTP responses; which status each error class gets is explained in Searching.
search/errors.ts

Localizing messages

An error’s message is rendered in the package locale at the time the error is created. The default is English (en); English and Korean catalogs are built in.
  • setSearchLocale(locale) sets the locale for the whole process. An explicit value always wins. A malformed locale throws SearchConfigurationError.
  • In a Sonamu project, the first operation of a /sonamu handle (markChanged, markChangedIn, a search, the lifecycle’s onStart, a defineSonamuSearch projection) applies Sonamu’s i18n.defaultLocale once. It switches only if a catalog exists for that tag or its base language; otherwise it stays on English and raises no error. If setSearchLocale was already called, nothing changes.
  • registerSearchMessages(locale, messages) registers messages for another language. Registering only some keys is fine; missing keys fall back to the built-in catalog of the same language, then to English. The default locale is applied once per process, so to make that language the default, register it before the first operation.
  • error.localize(locale) renders the message again when the language differs per request. Lookup goes exact tag, then base language, then English; at each step a registered catalog wins over a built-in one.
The example registers Japanese messages once at startup. With Sonamu’s i18n.defaultLocale set to ja, Japanese becomes the default.
search/errors.ts
sonamu.config.ts

Next steps

Indexing worker

How marked documents get indexed

Search definitions

The projection contract and document validation