Framework
When two similar list pages run at different speeds, check which execution path each one uses. The hybrid query engine consults the shared index when the query fits and delegates other shapes to the database-backed engine.
HybridQueryEngine is the implementation registered behind the queryEngine DI key at runtime. It answers a query from the shared entity_indexes JSONB index when it can, and delegates to BasicQueryEngine (the join-based plan) when it cannot.
Tip · Read this first
There is no per-module opt-in for the engine. There is no queryIndex metadata option, no hybridQuery: true flag, and no per-entity *_index table – a single shared entity_indexes table backs every indexed entity. What is opt-in is indexing, not routing. See Keeping the index populated.
createRequestContainer() registers a BasicQueryEngine (packages/shared/src/lib/di/container.ts). The query_index module's DI registrar then unconditionally replaces that registration with a HybridQueryEngine that wraps the basic one as its fallback delegate (packages/core/src/modules/query_index/di.ts).
The standard app enables query_index, so every consumer of queryEngine in that configuration gets the hybrid engine. BasicQueryEngine runs directly only when the query_index registration is absent or threw; otherwise it is reachable only as the hybrid engine's fallback.
Both implement the same interface, which has exactly one method (packages/shared/src/lib/query/types.ts):
export interface QueryEngine {
query<T = any>(entity: EntityId, opts?: QueryOptions): Promise<QueryResult<T>>
}
See Query engine for the options and result shape, and JSONB indexing layer for the index schema, document shape, and backfill CLI.
For a given query() call the hybrid engine picks one of three paths.
When opts.forceCustomEntityStorage === true, or the entity id is classified as a custom entity, the query runs against custom_entities_storage instead of a base table. This is a separate reader, not the basic engine.
BasicQueryEngineThere are exactly four conditions, all in packages/core/src/modules/query_index/lib/engine.ts:
| Condition | Profiler reason | Notes |
|---|---|---|
| The base table does not exist | missing_base | |
opts.omitAutomaticTenantOrgScope === true | omit_automatic_tenant_org_scope | The caller owns scoping. BasicQueryEngine still handles cf:* filters/sorts, but search_tokens fulltext, the JSONB index path, and the vector-search branch are bypassed |
| No index rows exist for the entity type | no_index_rows | Only evaluated when the query wants custom fields |
A coverage gap was detected and FORCE_QUERY_INDEX_ON_PARTIAL_INDEXES is off | partial_index | Additionally requires the entity to have at least one active custom-field definition. See Partial coverage |
The last two are gated on the query actually wanting custom-field data – opts.fields containing a cf:/l10n: selector, a cf:/l10n: filter, or an array-form includeCustomFields. A query that asks for no custom fields never falls back for coverage reasons; it still runs the hybrid engine's own SQL. The data query currently left-joins entity_indexes even when no custom fields are requested, while the optimized count path can skip that join.
Everything else. Filters, sorts, paging, tenant/organization scoping, joins, and soft-delete exclusion are applied against the base table plus entity_indexes.
These are handled inside the hybrid engine and are easy to misread as fallback triggers:
ORDER BY, not escalated.entity_indexes.doc ->> '<field>' rather than rejected.opts.joins, opts.customFieldSources) are compiled natively.OM_ENCRYPTED_SORT_MAX_ROWS (unset means uncapped) the result carries meta.encryptedSortRowCapWarning.The supported set is exactly eleven (packages/shared/src/lib/query/types.ts):
eq · ne · gt · gte · lt · lte · in · nin · like · ilike · exists
Warning · Unsupported operators are silently ignored
An operator outside that list does not raise. It is dropped during filter compilation, and the default: branches in both engines are permissive – the predicate is either skipped or compiled to true. The practical effect is that a filter you expected to narrow the result set may not narrow it at all. Validate operator names at the API boundary; do not rely on the engine to reject them.
like/ilike are re-routed to hashed search_tokens lookups when search is active. If the tokenizer yields no hashes for the pattern, the predicate is skipped.
The engine compares baseCount (rows in the base table for the scope) against indexedCount (rows in entity_indexes), reading a snapshot from entity_index_coverage. A gap is any scope where indexedCount is below a non-zero baseCount, where indexedCount exceeds baseCount (stale rows), or where no snapshot exists yet.
On a gap:
query_index.reindex event, unless opts.skipAutoReindex is set or SCHEDULE_AUTO_REINDEX is off. This happens whether or not the query falls back.FORCE_QUERY_INDEX_ON_PARTIAL_INDEXES decides the read:
meta.partialIndexWarning (entity, entityLabel, baseCount, indexedCount, scope), which the CRUD factory forwards as the x-om-partial-index response header so the admin UI can prompt for a reindex via /backend/query-indexes.Warning · Forcing the index trades correctness for latency
With a real coverage gap, FORCE_QUERY_INDEX_ON_PARTIAL_INDEXES=true means unindexed rows silently disappear from filtered lists and counts. Close the gap with a reindex first; only then decide whether to force.
Coverage snapshots are cached in the entity_index_coverage table with a TTL of QUERY_INDEX_COVERAGE_CACHE_MS (5 minutes by default). When a snapshot is stale or missing, OPTIMIZE_INDEX_COVERAGE_STATS decides what happens: off (the default) recomputes inline on the request thread; on schedules an asynchronous refresh and serves the stale snapshot.
QueryResult.total always comes from a real count query – there is no cap, no cache, and no way to skip it.
The hybrid engine takes an optimized path when the query has no cf:/l10n: filters and no cross-entity search source: it rebuilds the count from the base table with base, or-group, and join filters only, skipping the entity_indexes join entirely, then counts distinct base ids. Otherwise it counts distinct b.id over the full query shape.
BasicQueryEngine uses count(distinct <table>.id) when joins, joined aggregates, or custom-field sources could multiply base rows, and count(*) when they cannot.
The query engine never writes index rows. Incremental maintenance runs through the query_index subscribers; bulk rebuilds are written directly by the reindexer behind the CLI and admin UI.
| Event | Effect |
|---|---|
query_index.upsert_one | Rebuild and upsert one row |
query_index.delete_one | Remove the row and its search tokens, adjust coverage |
query_index.reindex | Background (re)build for an entity/tenant/organization scope |
query_index.purge | Drop index rows for a scope |
query_index.coverage.refresh / .warmup | Recompute coverage snapshots |
They are emitted by the DataEngine CRUD side-effect path when a route or command passes indexer: { entityType }, and by automatic <module>.<entity>.created|updated|deleted subscriptions that the query_index DI registrar installs for every entity id appearing in custom_field_defs (falling back to every generated entity id when that table is empty). The created/updated handlers forward only when the entity has an active custom-field definition for the scope; the deleted handler always forwards so stale index rows and search tokens are removed even after definitions change.
To rebuild by hand, use the CLI (mercato query_index rebuild, rebuild-all, reindex, purge; yarn mercato reindex is shorthand for query_index reindex) or the admin UI at /backend/query-indexes. Flags and partitioning are documented in JSONB indexing layer.
OM_PROFILE to emit [qe:profile] nodes. The result field is ok, fallback (with a reason from the table above), custom_entity, or error; SQL timings are labelled query:sql:count and query:sql:data (query:sql:data:phase1 / :phase2 when sorting on an encrypted column).OM_QUERY_INDEX_DEBUG, or LOG_VERBOSITY/LOG_LEVEL at debug or lower) and QUERY_ENGINE_DEBUG_SQL=true. Setting verbosity alone prints nothing from this engine.warn. The missing_base, omit_automatic_tenant_org_scope, and no_index_rows fallbacks are visible only through the profiler or debug logs./backend/query-indexes for a coverage snapshot with indexedCount matching baseCount.omitAutomaticTenantOrgScope off unless the entity's scoping genuinely does not fit organization_id = X AND tenant_id = Y. It forces the basic engine, so you lose the index path and vector search and take the join plan instead.cf:* predicates are JSONB extractions and are only as fast as the expression indexes you add for them.entity_indexes ships no GIN index on doc; the per-entity partial covering indexes that exist today were hand-written for three customers:* entity types and are not generated for other entities.Capture the actual fields, filters, sort order and scope sent by the slow screen. Compare that exact query with the routing conditions below. A smaller query that selects different fields may exercise another engine and give misleading timings.
Previous: Entities and migrations · Next: Hybrid Search Module