Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

perf(database): index messages.mediaPath for the chat-media orphan sweep

Yudhi Armyndharis16f412b926a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c46339f9..6c6bee8ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- The chat-media orphan sweep's `mediaPath IN (...)` lookup is served by a new partial index (`WHERE mediaPath IS NOT NULL`); it was a full messages-table scan per chunk.
- Both bundled Compose files forward every documented runtime knob; `WEBHOOK_SSRF_REDIRECTS`, `PLUGIN_INSTALL_REQUIRE_PIN` and ~75 other `.env` settings were unreachable in the container. A spec now derives the required list from `.env.example`.
- Ingress delivery ids BullMQ refuses at enqueue (numeric, `redrive:<uuid>`, `0:`-led) are hashed to a legal job id, namespaced by plugin/instance; the old refusal read as a Redis failure and silently degraded the delivery to inline dispatch with no retry.
- One precise unique-violation predicate (`23505`, `SQLITE_CONSTRAINT_UNIQUE`/`_PRIMARYKEY`): the old prefix match treated every SQLite constraint failure (FK/NOT NULL/CHECK) as a duplicate, swallowing genuine persistence failures and answering misleading 409s.
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index adc829a3d..589cb6253 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -821,7 +821,8 @@ src/database/migrations/ # data connection (pluggable)
├── 1785700000000-AddMessageMediaArchive.ts
├── 1785800000000-AddSessionOwnership.ts
├── 1785900000000-AddAutomationRules.ts # 14th migration table; FKs sessions ON DELETE CASCADE
-└── 1786000000000-AddSessionNodeUrl.ts
+├── 1786000000000-AddSessionNodeUrl.ts
+└── 1786100000000-AddMessageMediaPathIndex.ts # partial index on messages.mediaPath (orphan sweep)
```
> [!NOTE]
diff --git a/src/database/migrations/1786100000000-AddMessageMediaPathIndex.ts b/src/database/migrations/1786100000000-AddMessageMediaPathIndex.ts
new file mode 100644
index 000000000..0d8ad623c
--- /dev/null
+++ b/src/database/migrations/1786100000000-AddMessageMediaPathIndex.ts
@@ -0,0 +1,35 @@
+import { MigrationInterface, QueryRunner } from 'typeorm';
+
+/**
+ * Partial index on `messages.mediaPath`, backing the chat-media orphan sweep's per-chunk
+ * `WHERE mediaPath IN (...)` lookup (chat-media-archive.service.ts). The column is NULL for every
+ * row while archiving is off (the default) and for every un-archived message, so a full index over
+ * it would mostly index NULLs; the `WHERE mediaPath IS NOT NULL` partial form keeps it to the
+ * archived rows that can ever match, on both SQLite and Postgres.
+ *
+ * Same reasoning as AddMessagesCreatedAtIndex: hand-authored because `synchronize` is off for the
+ * data connection on PostgreSQL (and optional on SQLite). The explicit name matches the entity's
+ * @Index, so the synchronize and migration schema paths converge on one index. Idempotent via
+ * IF NOT EXISTS (supported by both dialects for indexes).
+ */
+export class AddMessageMediaPathIndex1786100000000 implements MigrationInterface {
+ name = 'AddMessageMediaPathIndex1786100000000';
+
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ // The data pool boots with a runtime statement_timeout (default 30s). On an upgrade where this
+ // is the only pending migration, MigrationExecutor wraps it in its OWN transaction, so no
+ // earlier migration's SET LOCAL is in effect and a CREATE INDEX over a large messages table is
+ // cancelled at the timeout, aborting the ledger-advancing transaction and crash-looping the
+ // boot retries. Lift it for this transaction only, exactly like AddMessagesCreatedAtIndex.
+ if (queryRunner.dataSource.options.type === 'postgres') {
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
+ await queryRunner.query(
+ `CREATE INDEX IF NOT EXISTS "IDX_messages_mediaPath" ON "messages" ("mediaPath") WHERE "mediaPath" IS NOT NULL`,
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_messages_mediaPath"`);
+ }
+}
diff --git a/src/database/migrations/__tests__/1786100000000-AddMessageMediaPathIndex.spec.ts b/src/database/migrations/__tests__/1786100000000-AddMessageMediaPathIndex.spec.ts
new file mode 100644
index 000000000..e347e9ebf
--- /dev/null
+++ b/src/database/migrations/__tests__/1786100000000-AddMessageMediaPathIndex.spec.ts
@@ -0,0 +1,62 @@
+import { DataSource } from 'typeorm';
+import { AddMessageMediaPathIndex1786100000000 } from '../1786100000000-AddMessageMediaPathIndex';
+
+describe('AddMessageMediaPathIndex migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });
+ await ds.initialize();
+ // Post-AddMessageMediaArchive shape of the messages table (only the columns this index needs).
+ await ds.query(
+ `CREATE TABLE "messages" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, ` +
+ `"mediaPath" varchar NULL)`,
+ );
+ // Mostly-NULL mediaPath (the archive is opt-in) with a handful of archived rows.
+ const rows: string[] = [];
+ for (let i = 0; i < 200; i++) {
+ rows.push(`('id${i}', 's1', ${i % 20 === 0 ? `'media/${i}.bin'` : 'NULL'})`);
+ }
+ await ds.query(`INSERT INTO "messages" ("id","sessionId","mediaPath") VALUES ${rows.join(',')}`);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const indexNames = async (): Promise<string[]> => {
+ const rows = await ds.query<{ name: string }[]>(`PRAGMA index_list("messages")`);
+ return rows.map(r => r.name).sort();
+ };
+
+ it('creates the partial mediaPath index', async () => {
+ const runner = ds.createQueryRunner();
+ await new AddMessageMediaPathIndex1786100000000().up(runner);
+
+ expect(await indexNames()).toContain('IDX_messages_mediaPath');
+ });
+
+ it('is idempotent (re-running up is a no-op) and down() drops the index', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddMessageMediaPathIndex1786100000000();
+
+ await migration.up(runner);
+ await expect(migration.up(runner)).resolves.toBeUndefined();
+ expect(await indexNames()).toContain('IDX_messages_mediaPath');
+
+ await migration.down(runner);
+ expect(await indexNames()).not.toContain('IDX_messages_mediaPath');
+ });
+
+ it('the orphan sweep mediaPath IN (...) predicate is served by the index, not a table scan', async () => {
+ const runner = ds.createQueryRunner();
+ await new AddMessageMediaPathIndex1786100000000().up(runner);
+
+ const plan = await ds.query<{ detail: string }[]>(
+ `EXPLAIN QUERY PLAN SELECT "mediaPath" FROM "messages" WHERE "mediaPath" IN ('media/0.bin', 'media/20.bin')`,
+ );
+ const detail = plan.map(r => r.detail).join(' ');
+ expect(detail).toContain('IDX_messages_mediaPath');
+ expect(detail).not.toContain('SCAN');
+ });
+});
diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.ts
index a2bee17b4..c1b44550b 100644
--- a/src/modules/message/entities/message.entity.ts
+++ b/src/modules/message/entities/message.entity.ts
@@ -94,6 +94,11 @@ export class Message {
* messages, and for media above the archive cap. Independent of the inline base64 copy in
* `metadata.media`, which is unaffected by archiving.
*/
+ // Partial index for the chat-media orphan sweep's per-chunk `mediaPath IN (...)` lookup. NULL for
+ // every un-archived row (archiving is opt-in), so the WHERE clause keeps the index to rows that
+ // can ever match. The explicit name matches the migration that creates it on synchronize-disabled
+ // deployments, so both schema paths converge on one index.
+ @Index('IDX_messages_mediaPath', { where: 'mediaPath IS NOT NULL' })
@Column({ nullable: true })
mediaPath?: string;