Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(search): index messages that predate the full-text index
Yudhi Armyndharisc1929752d29f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 416a5d83a..a609ffa82 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Messages that existed before the full-text index was created are indexed on the next boot instead of being permanently unsearchable, and ordinary edits and deletes on them work again. The boot-time backfill was gated on the index being empty, but `messages_fts` is an FTS5 external-content table whose `count(*)` returns the row count of `messages`, so the condition could never hold and the backfill never ran; until those rows are indexed the sync triggers issue delete commands for documents that were never added and SQLite rejects the whole statement. The guard is now a rowid-level completeness check, so it also repairs a partially populated index rather than only an empty one.- Removing, promoting or demoting group participants on the whatsapp-web.js engine now reports which participants WhatsApp actually acted on. The library resolves each requested id against the group's own member list and silently drops what it cannot find, so a request naming only non-members answered `500` for removal — the empty batch tripped an arity assertion — while promotion and demotion answered `200` claiming success for people WhatsApp never touched. Such a request now answers `403`, and a mixed request reports the untouched entries as `404` instead of confirming them. An installation whose `node_modules` predates this release keeps the previous behaviour for the reporting half; the `500` is closed either way. Refs #1220.- A group participant id that does not name an individual — free text, a group id, a number too short to be one — is now rejected with `400` naming the offending entries, instead of being handed to the engine. On whatsapp-web.js such an id reached the page-side `createWid`, which threw an error the minified bundle reports without a name, so the caller received a `500` that could not be diagnosed from either end. The check covers group creation and adding, removing, promoting and demoting participants, and it sits in the service rather than the request body so the MCP tools are guarded on the same terms as the REST routes. Refs #1220.- Creating a channel on the Baileys engine no longer answers `500` while leaving the channel behind. The library's response parser read `thread.picture.id` eagerly, but its create call sends only a name and description and has no picture parameter, so the picture was absent on every create and the parse threw after WhatsApp had already created the newsletter — and because the operation is non-idempotent, a client retrying the `500` leaked one orphan channel per attempt, invisible through the API since `getSubscribedChannels` is not available on that engine. A new install-time patch reads the response defensively so the call succeeds and returns the new channel's id, which is the only place that id appears.diff --git a/src/modules/search/providers/builtin-fts.provider.backfill.spec.ts b/src/modules/search/providers/builtin-fts.provider.backfill.spec.tsnew file mode 100644index 000000000..545d1fdca--- /dev/null+++ b/src/modules/search/providers/builtin-fts.provider.backfill.spec.ts@@ -0,0 +1,175 @@+import 'reflect-metadata';+import { DataSource } from 'typeorm';+import { Message, MessageDirection } from '../../../modules/message/entities/message.entity';+import { Session } from '../../../modules/session/entities/session.entity';+import { BuiltInFtsProvider } from './builtin-fts.provider';++/**+ * The state no other spec constructs: a database whose `messages` rows predate the FTS schema, with+ * the migration NOT applied.+ *+ * `builtin-fts.provider.spec.ts`, `search-dual-db.spec.ts` and `test/search.e2e-spec.ts` all run+ * `AddMessagesFts…up()` first, so the index is always populated by the migration's own backfill and+ * the provider's backfill branch never executes. That is why this shipped and survived: the branch+ * has no coverage, not weak coverage.+ *+ * `messages_fts` is an FTS5 **external-content** table, so `count(*)` on it scans `messages` and+ * returns that table's row count rather than the number of indexed documents. The document count+ * lives in the `messages_fts_docsize` shadow table. Every assertion here is written against+ * behaviour — what `search()` can find — with `docsize` used only to describe the fixture.+ */+describe('BuiltInFtsProvider — backfilling an index built after the rows', () => {+ let ds: DataSource;++ const row = (body: string, timestamp: number) => ({+ sessionId: 's1',+ chatId: 'c1',+ from: '[email protected]',+ to: '[email protected]',+ body,+ type: 'text',+ direction: MessageDirection.OUTGOING,+ timestamp,+ });++ /** Rows first, no FTS schema at all — the shape an upgrade from before the feature produces. */+ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session, Message],+ synchronize: true,+ });+ await ds.initialize();+ await ds.getRepository(Message).insert([row('alpha legacy', 1), row('bravo legacy', 2)]);+ });+ afterEach(() => ds.destroy());++ /** Rows whose body is NULL — the precondition for the integrity assertion below. */+ const nullBodies = async (): Promise<number> => {+ const r: Array<{ n: number }> = await ds.query(`SELECT count(*) AS n FROM "messages" WHERE "body" IS NULL`);+ return Number(r[0]?.n);+ };++ /**+ * FTS5's index-vs-content check. Two forms exist and they are NOT equivalent: the plain+ * `('integrity-check')` validates only the index's internal structures and answers PASS on an+ * index that holds nothing at all, so it cannot see this defect. The `rank = 1` argument form+ * validates the index AGAINST the content table, which is what makes it discriminating here.+ *+ * VALID ONLY BECAUSE THIS FIXTURE HAS NO NULL BODY, which the caller asserts first. The migration+ * backfills `WHERE body IS NOT NULL` while the AFTER INSERT trigger indexes unconditionally, so on+ * any database holding a NULL-body row this check reports `malformed` forever — including on a+ * healthy, migration-built one. Do not lift it into a general post-condition: it convicts the+ * healthy state, and a fixture that later gains a NULL row would fail here for a reason that has+ * nothing to do with the code under test.+ */+ const indexMatchesContent = async (): Promise<string> => {+ try {+ await ds.query(`INSERT INTO "messages_fts"("messages_fts", "rank") VALUES ('integrity-check', 1)`);+ return 'consistent';+ } catch (e) {+ return e instanceof Error && e.message.includes('malformed') ? 'malformed' : `unexpected: ${String(e)}`;+ }+ };++ const docsize = async (): Promise<number> => {+ const r: Array<{ n: number }> = await ds.query(`SELECT count(*) AS n FROM "messages_fts_docsize"`);+ return Number(r[0]?.n);+ };+ const found = async (q: string): Promise<string[]> =>+ (await new BuiltInFtsProvider(ds).search({ q, limit: 50 })).hits.map(h => h.body ?? '');++ it('indexes rows that predate the FTS table on first boot', async () => {+ await new BuiltInFtsProvider(ds).onModuleInit();++ expect(await docsize()).toBe(2);+ expect(await found('legacy')).toHaveLength(2);+ });++ /**+ * The decisive case, and the reason an emptiness probe is not sufficient: a RESTART, not a fresh+ * boot. The first boot leaves the index empty, then one post-boot write is indexed by the working+ * `AFTER INSERT` trigger — so the second boot meets a PARTIALLY populated index. A probe that asks+ * "is it empty?" is false here and repairs nobody; the installed base is in exactly this state.+ */+ it('repairs a partially populated index on a later boot, not just an empty one', async () => {+ // Construct the state an unrepaired box is actually in, rather than running the old code:+ // the FTS schema and triggers exist, older rows were never indexed, and one later write WAS+ // indexed by the AFTER INSERT trigger. Built by creating the schema and then withdrawing the+ // legacy rows from the index with FTS5's own 'delete' command, so the spec does not restate the+ // provider's DDL and drift from it.+ // Asserted FIRST so it is the failure a future contributor sees: `indexMatchesContent` below is+ // only valid while this fixture holds no NULL body, and a NULL row would otherwise surface as a+ // confusing `malformed` that reads as the fix being broken.+ expect(await nullBodies()).toBe(0);++ await new BuiltInFtsProvider(ds).onModuleInit();+ // The index keys on SQLite's implicit rowid (content_rowid='rowid'), not the entity's uuid id.+ const seeded: Array<{ rowid: number; body: string }> = await ds.query(`SELECT rowid, body FROM "messages"`);+ for (const m of seeded) {+ await ds.query(`INSERT INTO "messages_fts"("messages_fts", "rowid", "body") VALUES ('delete', ?, ?)`, [+ m.rowid,+ m.body,+ ]);+ }+ expect(await docsize()).toBe(0);++ await ds.getRepository(Message).insert([row('charlie fresh', 3)]); // the trigger indexes this one+ expect(await docsize()).toBe(1); // partially populated: the state an emptiness probe cannot see++ await new BuiltInFtsProvider(ds).onModuleInit(); // the build under test++ expect(await docsize()).toBe(3);+ expect(await found('legacy')).toHaveLength(2);+ expect(await found('fresh')).toHaveLength(1);++ // The repair must add ONLY the missing rows. Re-indexing a row the trigger had already indexed+ // leaves a duplicate document that nothing above can see: the shadow table replaces by rowid so+ // `docsize` is unchanged, search returns the right count, and edits and deletes still succeed.+ // This is the one assertion that discriminates — see `indexMatchesContent`, and note the+ // precondition it depends on.+ expect(await indexMatchesContent()).toBe('consistent');+ });++ it('leaves an already complete index alone rather than duplicating it', async () => {+ await new BuiltInFtsProvider(ds).onModuleInit();+ const after = await docsize();+ await new BuiltInFtsProvider(ds).onModuleInit();++ expect(await docsize()).toBe(after);+ expect(await found('legacy')).toHaveLength(2);+ });++ /**+ * Known-negative. The migration backfills `WHERE "body" IS NOT NULL`; the repair must reproduce+ * that contents exactly rather than indexing a NULL body as an empty document, which would make+ * the index disagree with the schema it repairs.+ */+ it('does not index a NULL body, matching what the migration produces', async () => {+ await ds.getRepository(Message).insert([{ ...row('', 4), body: null as unknown as string }]);++ await new BuiltInFtsProvider(ds).onModuleInit();++ expect(await docsize()).toBe(2);+ expect(await found('legacy')).toHaveLength(2);+ });++ /**+ * The write path. On an unrepaired box the `AFTER UPDATE`/`AFTER DELETE` triggers issue FTS5+ * 'delete' commands for documents that were never indexed and the statement is rejected, so the+ * row does not change. This asserts the repair restores ordinary writes — the severe half of the+ * defect, and the half no search assertion can see.+ */+ it('restores ordinary UPDATE and DELETE on rows that predate the index', async () => {+ const repo = ds.getRepository(Message);+ await new BuiltInFtsProvider(ds).onModuleInit();++ const target = await repo.findOneOrFail({ where: { body: 'alpha legacy' } });+ await expect(repo.update({ id: target.id }, { body: 'alpha edited' })).resolves.toBeDefined();+ await expect(repo.delete({ body: 'bravo legacy' })).resolves.toBeDefined();++ expect((await repo.findOneOrFail({ where: { id: target.id } })).body).toBe('alpha edited');+ expect(await found('edited')).toHaveLength(1);+ });+});diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.tsindex 85f1b9dc1..84659fddf 100644--- a/src/modules/search/providers/builtin-fts.provider.ts+++ b/src/modules/search/providers/builtin-fts.provider.ts@@ -156,15 +156,30 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {await this.dataSource.query(`CREATE VIRTUAL TABLE IF NOT EXISTS "messages_fts" USING fts5(body, content='messages', content_rowid='rowid')`,);- // Backfill only when the FTS table is empty but messages has rows — avoids re-copying on every boot- // once the index is populated. `messages_fts` with 'rowid' content exposes its size via this count.- const sizeRow: unknown[] = await this.dataSource.query(- `SELECT (SELECT count(*) FROM "messages_fts") AS fts, (SELECT count(*) FROM "messages" WHERE "body" IS NOT NULL) AS msgs`,+ // Backfill the rows this index does not hold. NOT an emptiness test: `messages_fts` is an FTS5+ // external-content table, so `count(*)` on it scans `messages` and returns THAT table's row+ // count, never the number of indexed documents — a "the index is empty" probe written that way+ // is unsatisfiable, because a zero count means `messages` itself is empty. The indexed documents+ // live in the `messages_fts_docsize` shadow table, so completeness is a rowid-level anti-join.+ //+ // It has to hold on a PARTIALLY populated index, not just an empty one: once a box has booted+ // once without the backfill, its later writes are indexed by the triggers below while its older+ // rows stay missing, and an emptiness test is false there and repairs nothing. Until those rows+ // are indexed the AFTER UPDATE/DELETE triggers issue FTS5 'delete' commands for documents that+ // were never added, and SQLite rejects the whole statement — so ordinary edits and deletes on+ // them fail, not merely searches. Reads `d."rowid"` rather than `d."id"`: same query plan,+ // without depending on the shadow table's column naming.+ const gapRow: unknown[] = await this.dataSource.query(+ `SELECT EXISTS(SELECT 1 FROM "messages" m WHERE m."body" IS NOT NULL+ AND NOT EXISTS (SELECT 1 FROM "messages_fts_docsize" d WHERE d."rowid" = m."rowid")) AS missing`,);- const sr = (sizeRow as Array<{ fts: number; msgs: number }>)[0];- if (Number(sr?.fts) === 0 && Number(sr?.msgs) > 0) {+ if (Number((gapRow as Array<{ missing: number }>)[0]?.missing)) {+ // `body IS NOT NULL` mirrors the migration's own backfill exactly: a repair that indexed a NULL+ // body as an empty document would leave the index disagreeing with the schema it repairs.await this.dataSource.query(- `INSERT INTO "messages_fts"("rowid", "body") SELECT "rowid", "body" FROM "messages" WHERE "body" IS NOT NULL`,+ `INSERT INTO "messages_fts"("rowid", "body")+ SELECT m."rowid", m."body" FROM "messages" m WHERE m."body" IS NOT NULL+ AND NOT EXISTS (SELECT 1 FROM "messages_fts_docsize" d WHERE d."rowid" = m."rowid")`,);}// The three sync triggers are CREATE-OR-REPLACE by name via DROP + CREATE; idempotent on re-run.