Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): carry session ownership across a replace-all data import

Yudhi Armyndharis08a0fe379beb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4257befd4..948297795 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **An API request body with a `Content-Encoding` other than `identity` is now refused with `415`** — the aggregate in-flight body cap counts wire bytes, so a compressed body was admitted on its compressed size and then inflated past the memory it was supposed to bound.
+### Fixed
+
+- **A replace-all data import now carries the session ownership lease across the replace** — the restore re-inserted sessions without it, so the next lease renewal read the blank row as a lost claim and tore down engines that had never stopped.
+
## [0.14.2] - 2026-08-06
### Added
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index 017929c68..e6b1608bf 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -22,7 +22,7 @@ jest.mock('fs', () => {
import { DataSource, QueryFailedError } from 'typeorm';
import { ConflictException } from '@nestjs/common';
-import { InfraDataController } from './infra-data.controller';
+import { InfraDataController, restoreSessionOwnership } from './infra-data.controller';
import { Session, SessionStatus } from '../session/entities/session.entity';
import { Webhook } from '../webhook/entities/webhook.entity';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
@@ -88,6 +88,79 @@ describe('InfraDataController.importData round-trips export-data (no silent mess
}),
);
+ it('keeps the session ownership lease across a replace, and never takes it from the payload', async () => {
+ await seedSession('s1');
+ const claimedAt = new Date('2026-08-06T10:00:00.000Z');
+ const leaseExpiresAt = new Date('2026-08-06T10:05:00.000Z');
+ // A live claim held by THIS node, exactly as SessionOwnershipService would have written it.
+ await ds
+ .getRepository(Session)
+ .update({ id: 's1' }, { nodeId: 'node-a', claimedAt, leaseExpiresAt, nodeUrl: 'http://10.0.0.5:2785' });
+
+ // export-data does SELECT *, so the dump genuinely carries the ownership columns. Rewriting them
+ // to a FOREIGN node proves the restore ignores the payload: taking them from the backup would
+ // install another host's claim with a still-future lease and 409 every start until it lapsed.
+ const dump = await controller.exportData();
+ for (const row of dump.tables.sessions as unknown as Record<string, unknown>[]) {
+ row.nodeId = 'node-from-another-host';
+ row.nodeUrl = 'http://198.51.100.9:2785';
+ row.leaseExpiresAt = new Date('2099-01-01T00:00:00.000Z').toISOString();
+ }
+
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.warnings).toEqual([]);
+ expect(res.imported).toBe(true);
+
+ const restored = await ds.getRepository(Session).findOneByOrFail({ id: 's1' });
+ expect(restored.nodeId).toBe('node-a');
+ expect(restored.nodeUrl).toBe('http://10.0.0.5:2785');
+ expect(new Date(restored.claimedAt as unknown as string).toISOString()).toBe(claimedAt.toISOString());
+ expect(new Date(restored.leaseExpiresAt as unknown as string).toISOString()).toBe(leaseExpiresAt.toISOString());
+ });
+
+ it('rolls the whole import back when ownership cannot be re-applied, instead of reporting success', async () => {
+ await seedSession('s1');
+ await ds.getRepository(Session).update({ id: 's1' }, { nodeId: 'node-a', nodeUrl: 'http://10.0.0.5:2785' });
+ const dump = await controller.exportData();
+
+ // Fail only the ownership UPDATE, leaving every other statement alone. On PostgreSQL a failed
+ // statement aborts the transaction, so a caller that degraded this to a notice and committed
+ // anyway would have the COMMIT execute as a ROLLBACK and still answer imported:true.
+ const realCreate = ds.createQueryRunner.bind(ds);
+ jest.spyOn(ds, 'createQueryRunner').mockImplementation((...args: Parameters<typeof realCreate>) => {
+ const runner = realCreate(...args);
+ const realQuery = runner.query.bind(runner);
+ // Pass EVERY argument through: TypeORM's query builder calls query(sql, params,
+ // useStructuredResult) and silently misreads a raw array when the third is dropped.
+ runner.query = ((...callArgs: Parameters<typeof realQuery>) =>
+ /UPDATE sessions SET "nodeId"/.test(callArgs[0])
+ ? Promise.reject(new Error('ownership write failed'))
+ : realQuery(...callArgs)) as typeof runner.query;
+ return runner;
+ });
+
+ const res = await controller.importData({ tables: dump.tables });
+ jest.restoreAllMocks();
+
+ expect(res.imported).toBe(false);
+ expect(res.warnings.join(' ')).toContain('session ownership');
+ // The rollback must have restored the pre-import row, ownership and all.
+ const stored = await ds.getRepository(Session).findOneByOrFail({ id: 's1' });
+ expect(stored.nodeId).toBe('node-a');
+ });
+
+ it('leaves a session that had no claim unclaimed rather than inventing one', async () => {
+ await seedSession('s1');
+
+ const dump = await controller.exportData();
+ const res = await controller.importData({ tables: dump.tables });
+ expect(res.imported).toBe(true);
+
+ const restored = await ds.getRepository(Session).findOneByOrFail({ id: 's1' });
+ expect(restored.nodeId).toBeNull();
+ expect(restored.leaseExpiresAt).toBeNull();
+ });
+
it('restores messages and message_batches faithfully — not silently to zero', async () => {
await seedSession('s1');
await ds.getRepository(Message).save(
@@ -1184,3 +1257,47 @@ describe('InfraDataController C002 audit trail (light-dependency handlers)', ()
expect(calls[0][1].metadata.counts.sessions).toBe(0);
});
});
+
+describe('restoreSessionOwnership', () => {
+ const claim = { id: 's1', nodeId: 'node-a', claimedAt: 'c', leaseExpiresAt: 'l', nodeUrl: 'u' };
+
+ it('propagates a failure instead of swallowing it, so the caller can roll the import back', async () => {
+ // Swallowing it would be worse than the bug: on PostgreSQL a failed statement aborts the
+ // transaction, so the COMMIT that followed would execute as a ROLLBACK and the endpoint would
+ // report a fully discarded import as a success.
+ await expect(restoreSessionOwnership([claim], () => Promise.reject(new Error('db went away')))).rejects.toThrow(
+ 'db went away',
+ );
+ });
+
+ it('does nothing when there is no ownership to carry', async () => {
+ const calls: unknown[][] = [];
+ const insert = (_sql: string, params: unknown[]): Promise<unknown> => {
+ calls.push(params);
+ return Promise.resolve();
+ };
+
+ await restoreSessionOwnership(null, insert);
+ await restoreSessionOwnership([], insert);
+
+ expect(calls).toEqual([]);
+ });
+
+ it('binds the values it read, never values from the payload', async () => {
+ const bound: unknown[][] = [];
+ const statements: string[] = [];
+ const insert = (sql: string, params: unknown[]): Promise<unknown> => {
+ statements.push(sql);
+ bound.push(params);
+ return Promise.resolve();
+ };
+
+ await restoreSessionOwnership([claim], insert);
+
+ expect(bound).toEqual([['node-a', 'c', 'l', 'u', 's1']]);
+ expect(statements[0]).toContain('UPDATE sessions SET "nodeId"');
+ expect(statements[0]).toContain('"claimedAt"');
+ expect(statements[0]).toContain('"leaseExpiresAt"');
+ expect(statements[0]).toContain('"nodeUrl"');
+ });
+});
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 9ecd8aae2..7a2efcd7f 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -1,7 +1,7 @@
import { Controller, Get, Post, Body, ConflictException, HttpCode, HttpStatus, Optional } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
-import { DataSource } from 'typeorm';
+import { DataSource, QueryRunner } from 'typeorm';
import { InjectDataSource } from '@nestjs/typeorm';
import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
@@ -32,6 +32,56 @@ import type {
} from './migration-tables.types';
import { TABLE_IMPORTERS } from './table-importers';
+/**
+ * The ownership quartet SessionOwnershipService maintains: which process holds a session's engine and
+ * until when. Cluster RUNTIME state — it belongs to the machines currently running, never to a backup.
+ */
+export interface SessionOwnershipRow {
+ id: string;
+ nodeId: string | null;
+ claimedAt: unknown;
+ leaseExpiresAt: unknown;
+ nodeUrl: string | null;
+}
+
+/**
+ * Read the live claims through the caller's queryRunner, so the read sits inside the import's own
+ * transaction. The columns are PROBED rather than SELECTed-and-caught: on PostgreSQL any failed
+ * statement aborts the surrounding transaction (25P02), so catching a missing-column error would
+ * still poison every statement after it — including the DELETE this read precedes. Absent columns
+ * mean a database whose ownership migration was rolled back; there is simply nothing to carry.
+ */
+async function readSessionOwnership(queryRunner: QueryRunner): Promise<SessionOwnershipRow[] | null> {
+ if (!(await queryRunner.hasColumn('sessions', 'nodeId'))) return null;
+ return (await queryRunner.query(
+ 'SELECT id, "nodeId", "claimedAt", "leaseExpiresAt", "nodeUrl" FROM sessions WHERE "nodeId" IS NOT NULL',
+ )) as SessionOwnershipRow[];
+}
+
+/**
+ * Re-apply the claims verbatim for ids present in both the pre-import database and the restored set.
+ * Values are re-bound exactly as they were read (ISO text on SQLite, Date on Postgres) rather than
+ * reconstructed, and go through the caller's `insert` so the `$N`→`?` rewrite applies on SQLite. An
+ * id the backup did not restore simply matches no row.
+ *
+ * Errors are NOT swallowed. On PostgreSQL a failed statement aborts the transaction, and the COMMIT
+ * that followed would silently execute as a ROLLBACK — reporting a fully-discarded import as a
+ * success with per-table counts. The caller routes a failure into `warnings`, which is the existing
+ * all-or-nothing gate.
+ */
+export async function restoreSessionOwnership(
+ preserved: SessionOwnershipRow[] | null,
+ insert: (text: string, params: unknown[]) => Promise<unknown>,
+): Promise<void> {
+ if (!preserved?.length) return;
+ for (const row of preserved) {
+ await insert(
+ 'UPDATE sessions SET "nodeId" = $1, "claimedAt" = $2, "leaseExpiresAt" = $3, "nodeUrl" = $4 WHERE id = $5',
+ [row.nodeId, row.claimedAt, row.leaseExpiresAt, row.nodeUrl, row.id],
+ );
+ }
+}
+
@ApiTags('infrastructure')
@Controller('infra')
// Every route here is deployment-global (data export/import, infra config, service orchestration),
@@ -401,6 +451,22 @@ export class InfraDataController {
await clearTable('integration_delivery_failures');
// status_updates has no FK to sessions; clear it explicitly so the replace is complete.
await clearTable('status_updates');
+ // Session ownership is CLUSTER RUNTIME STATE, not backup payload: which process currently holds
+ // a session's engine, and until when. The replace below deletes it along with everything else,
+ // and the sessions importer does not restore it (deliberately — see below), so without this the
+ // committed rows come back unclaimed and the next lease renewal reads "claim lost" and tears
+ // down engines that never stopped running.
+ //
+ // It must NOT be restored from the payload instead. export-data does `SELECT *`, so real backups
+ // DO carry these columns even though SessionRow does not declare them — restoring them would
+ // install the SOURCE host's nodeId with its still-future lease, and every start would then 409
+ // "running on another node" until that lease lapsed. Strictly worse than the bug.
+ //
+ // Read through the SAME queryRunner (a repository would take a second connection and self-
+ // deadlock on Postgres) and tolerate the columns being absent, so a database whose ownership
+ // migration has been rolled back still imports.
+ const preservedOwnership = await readSessionOwnership(queryRunner);
+
await queryRunner.query('DELETE FROM sessions');
// Restore table by table in TABLE_IMPORTERS order (FK-safe: sessions first). The descriptors
@@ -432,6 +498,18 @@ export class InfraDataController {
}
}
+ // Re-apply the claims read before the DELETE, for ids that exist in both. This runs BEFORE the
+ // all-or-nothing gate below on purpose: a failure here must take the same rollback the gate
+ // already implements. Degrading it to a notice and committing anyway would be worse than the
+ // bug it fixes — on PostgreSQL a failed statement aborts the transaction, so the COMMIT would
+ // execute as a ROLLBACK and the endpoint would report a fully discarded import as a success,
+ // with per-table counts, to an operator restoring after data loss.
+ try {
+ await restoreSessionOwnership(preservedOwnership, insert);
+ } catch (error) {
+ warnings.push(`Failed to restore session ownership: ${error instanceof Error ? error.message : String(error)}`);
+ }
+
// "Replace all data" must be all-or-nothing: the import already DELETEd every row, so if any
// INSERT failed we must roll back (restoring the pre-import data) rather than commit a
// half-wiped DB and report success. A partial restore reported as imported:true was how