Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(search): retry a SQLite contains build kept off the connection
Yudhi Armyndharis1b05bf4de595
diff --git a/docs/26-global-search.md b/docs/26-global-search.mdindex 0de78f3f2..055508d66 100644--- a/docs/26-global-search.md+++ b/docs/26-global-search.md@@ -313,7 +313,9 @@ answering its health probe (a boot that outlasts the Helm startup probe is restameanwhile are indexed by the triggers. A trigram index holds every three-character window of the body:on a synthetic corpus of 1,000,000 messages it took 289 MB, about 3.1 times the message text, and a9.4 s backfill. Later boots only check it; an index whose document count differs from `messages` (an- interrupted backfill, or rowids renumbered by a table rebuild) is emptied and backfilled again.+ interrupted backfill, or rowids renumbered by a table rebuild) is emptied and backfilled again. A build+ that finds another transaction holding the connection for more than 10 seconds (a data import, for+ one) tries again every 30 seconds instead of failing.- **PostgreSQL** creates the `pg_trgm` and `unaccent` extensions when they are missing and the role may,the IMMUTABLE `openwa_unaccent(text)` wrapper, and the `idx_messages_body_trgm` GIN index on`openwa_unaccent(body)` with `CREATE INDEX CONCURRENTLY`, so writes go on during the build (it cannotdiff --git a/src/modules/search/providers/builtin-fts.provider.contains.spec.ts b/src/modules/search/providers/builtin-fts.provider.contains.spec.tsindex bc75ca6a9..010c104e3 100644--- a/src/modules/search/providers/builtin-fts.provider.contains.spec.ts+++ b/src/modules/search/providers/builtin-fts.provider.contains.spec.ts@@ -5,6 +5,7 @@ import { DataSource } from 'typeorm';import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';import { Session } from '../../../modules/session/entities/session.entity';import { AddMessagesFts1782400000000 } from '../../../database/migrations/1782400000000-AddMessagesFts';+import * as sharedConnection from '../../../common/utils/shared-connection';import { SEARCH_CONTAINS_TERMS_MAX_LENGTH, SEARCH_CONTAINS_WINDOW } from '../search.constants';import { ContainsTermsRefusedError } from '../search-terms';import {@@ -293,6 +294,86 @@ describe('BuiltInFtsProvider trigram index build (sqlite)', () => {expect((await provider.search({ q: 'receipt 2400', match: 'contains' })).total).toBe(0);expect((await provider.search({ q: 'receipt 2401', match: 'contains' })).total).toBe(0);});++ describe('while another transaction holds the shared connection', () => {+ let provider: BuiltInFtsProvider;++ beforeEach(() => {+ // A data import holds it for as long as it runs; the build gives up on it after 20 ms here.+ const wait = sharedConnection.awaitNoOpenTransaction;+ jest.spyOn(sharedConnection, 'awaitNoOpenTransaction').mockImplementation(source => wait(source, 20));+ provider = new BuiltInFtsProvider(ds, containsOn);+ Object.assign(provider, { containsBuildRetryMs: 20 });+ });+ afterEach(() => {+ provider.onModuleDestroy();+ jest.restoreAllMocks();+ });++ const searchOnceBuilt = async (q: string) => {+ for (let i = 0; ; i++) {+ try {+ return await provider.search({ q, match: 'contains' });+ } catch (e) {+ if (i === 200 || !/still being built/.test(String(e))) throw e;+ await new Promise(r => setTimeout(r, 10));+ }+ }+ };++ it('builds the index once the transaction ends instead of failing for good', async () => {+ const importing = ds.createQueryRunner();+ await importing.startTransaction();+ try {+ await provider.buildContainsIndex();+ await expect(provider.search({ q: 'voic', match: 'contains' })).rejects.toThrow(/still being built/);+ } finally {+ await importing.rollbackTransaction();+ await importing.release();+ }++ expect((await searchOnceBuilt('voic')).total).toBe(2);+ });++ it('builds again from empty a backfill the transaction cut short', async () => {+ await insertBulk(2500, i => `Bulk receipt ${i}`);+ const importing = ds.createQueryRunner();+ const query = ds.query.bind(ds);+ let begun = false;+ jest.spyOn(ds, 'query').mockImplementation(async (sql: string, params?: Parameters<DataSource['query']>[1]) => {+ const result: unknown = await query(sql, params);+ // The first batch is in; the import begins before the second.+ if (!begun && /m\."rowid" > \?/.test(sql)) {+ begun = true;+ await importing.startTransaction();+ }+ return result;+ });++ await provider.buildContainsIndex();+ await expect(provider.search({ q: 'receipt', match: 'contains' })).rejects.toThrow(/still being built/);+ await importing.rollbackTransaction();+ await importing.release();++ expect((await searchOnceBuilt('receipt 2499')).total).toBe(1);+ await expect(integrityCheck()).resolves.toBeDefined();+ });++ it('still fails a build for good on any other error', async () => {+ const query = ds.query.bind(ds);+ const ddl = jest+ .spyOn(ds, 'query')+ .mockImplementation((sql: string, params?: Parameters<DataSource['query']>[1]) =>+ /CREATE VIRTUAL TABLE/.test(sql) ? Promise.reject(new Error('disk I/O error')) : query(sql, params),+ );++ await provider.buildContainsIndex();+ await new Promise(r => setTimeout(r, 60));++ await expect(provider.search({ q: 'voic', match: 'contains' })).rejects.toThrow(/building its index failed/);+ expect(ddl.mock.calls.filter(([sql]) => /CREATE VIRTUAL TABLE/.test(sql))).toHaveLength(1);+ });+ });});describe('trigram schema helpers', () => {diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsindex 5d6b9f478..a923823e0 100644--- a/src/modules/search/providers/builtin-fts.provider.ts+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -66,7 +66,7 @@ const TRIGRAM_BACKFILL_BATCH = 1000;export const TRIGRAM_BUILD_LOCK_KEY = 0x7472676d;export const TRIGRAM_BUILD_LOCK = `$1, to_regclass('messages')::oid::int`;-/** How long a replica that found the build lock taken waits before trying it again. */+/** How long a build kept from running (see retryContainsBuild) waits before trying again. */const TRIGRAM_BUILD_RETRY_MS = 30_000;/** Why match=contains answers 501, one message per cause, each naming what to change. */@@ -169,6 +169,9 @@ function postgresCanIndex(term: string): boolean {return POSTGRES_TRIGRAM_SOURCE.test(foldSearchText(term));}+/** A build that could not get the shared SQLite connection free of another transaction: it is tried again later. */+class ConnectionBusyError extends Error {}+/** Shape returned by the dialect-specific SELECT in buildSqlite / buildPostgres. */interface FtsResultRow {id: string;@@ -473,7 +476,9 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit, OnAppli`SELECT max("rowid") AS last FROM "messages"`,);for (let from = 0; from < (last ?? 0); from += TRIGRAM_BACKFILL_BATCH) {- if (!(await awaitNoOpenTransaction(this.dataSource))) throw new Error('Another database transaction stayed open');+ if (!(await awaitNoOpenTransaction(this.dataSource))) {+ throw new ConnectionBusyError('Another database transaction stayed open');+ }await this.dataSource.query(`INSERT INTO "${table}"("rowid", "body")SELECT m."rowid", m."body" FROM "messages" m@@ -499,9 +504,13 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit, OnAppli? await this.buildPostgresTrigramIndex(): await this.buildSqliteTrigramIndex();} catch (e) {- this.containsUnavailable = CONTAINS_UNAVAILABLE.failed;- this.logger.error(`Failed to build the trigram index: ${e instanceof Error ? e.message : String(e)}`);- return;+ if (!(e instanceof ConnectionBusyError)) {+ this.containsUnavailable = CONTAINS_UNAVAILABLE.failed;+ this.logger.error(`Failed to build the trigram index: ${e instanceof Error ? e.message : String(e)}`);+ return;+ }+ this.containsUnavailable = CONTAINS_UNAVAILABLE.building;+ this.logger.warn(`Trigram index build postponed: ${e.message}`);}if (this.containsUnavailable === CONTAINS_UNAVAILABLE.building) this.retryContainsBuild();else if (this.containsUnavailable) this.logger.warn(this.containsUnavailable);@@ -513,6 +522,9 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit, OnAppli* with no valid index, and only a build attempt of this replica's own finds that, so it tries the lock* again until the index is ready or the attempt fails for a cause of its own. A search in the meantime* still finds an index the other replica finished (probePostgresTrigram).+ *+ * On SQLite, another transaction (a data import, for one) held the shared connection longer than the+ * build waits for it. The next attempt starts a backfill it cut short again from empty.*/private retryContainsBuild(): void {if (this.destroyed) return;@@ -532,7 +544,9 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit, OnAppliif (!(await this.sqliteHasFts5())) return CONTAINS_UNAVAILABLE.sqliteTrigram;const rows: Array<{ version: string }> = await this.dataSource.query(`SELECT sqlite_version() AS version`);if (!sqliteSupportsTrigramDiacritics(rows[0]?.version ?? '')) return CONTAINS_UNAVAILABLE.sqliteTrigram;- if (!(await awaitNoOpenTransaction(this.dataSource))) throw new Error('Another database transaction stayed open');+ if (!(await awaitNoOpenTransaction(this.dataSource))) {+ throw new ConnectionBusyError('Another database transaction stayed open');+ }await this.ensureSqliteIndex(TRIGRAM_INDEX);return null;}