Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): suspend ownership loss detection for the duration of an import
Yudhi Armyndharisdfd3250af2ad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 948297795..c0baf1735 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### 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.+- **A replace-all data import no longer disturbs the engines it left running** — the restore dropped each session's ownership lease and, on SQLite, the heartbeat could read the half-applied transaction, so a renewal concluded the claim was lost and tore down engines that had never stopped.## [0.14.2] - 2026-08-06diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex e6b1608bf..e0b665765 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -118,6 +118,51 @@ describe('InfraDataController.importData round-trips export-data (no silent messexpect(new Date(restored.leaseExpiresAt as unknown as string).toISOString()).toBe(leaseExpiresAt.toISOString());});+ it('holds the ownership loss-detection token for the whole transaction, and releases it', async () => {+ await seedSession('s1');+ const dump = await controller.exportData();++ const events: string[] = [];+ let held = 0;+ const ownership = {+ suspendLossDetection: () => {+ held++;+ events.push('suspend');+ return () => {+ held--;+ events.push('release');+ };+ },+ heldByOtherNodes: () => Promise.resolve([]),+ };+ // Observe from inside the transaction: the token must already be held by the time rows move.+ 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);+ runner.query = ((...callArgs: Parameters<typeof realQuery>) => {+ if (/DELETE FROM sessions/.test(callArgs[0])) events.push(`delete(held=${held})`);+ return realQuery(...callArgs);+ }) as typeof runner.query;+ return runner;+ });++ const withOwnership = new InfraDataController(+ cfg as never,+ ds,+ undefined,+ undefined,+ undefined,+ ownership as never,+ );+ const res = await withOwnership.importData({ tables: dump.tables });+ jest.restoreAllMocks();++ expect(res.imported).toBe(true);+ expect(events).toEqual(['suspend', 'delete(held=1)', 'release']);+ expect(held).toBe(0);+ });+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' });diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex 7a2efcd7f..2df65f85e 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -402,6 +402,13 @@ export class InfraDataController {failedOrphanEngines,};+ // Silence the ownership heartbeat's loss detection for the whole transaction. On SQLite every+ // query runner shares ONE connection, so a heartbeat tick can execute INSIDE this transaction —+ // after the DELETE below, before the re-inserts commit — and see no session rows at all. It+ // would read that as "a peer took everything" and tear down every engine on this node, even on+ // the paths where this import then rolls back and every row comes straight back.+ const resumeLossDetection = this.ownership?.suspendLossDetection();+const queryRunner = this.dataDataSource.createQueryRunner();await queryRunner.connect();await queryRunner.startTransaction();@@ -571,6 +578,8 @@ export class InfraDataController {throw error;} finally {await queryRunner.release();+ // After release(), so the heartbeat cannot observe the transaction's connection state.+ resumeLossDetection?.();}}}diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.tsindex 233a2ffd3..278346a93 100644--- a/src/modules/session/session-ownership.service.spec.ts+++ b/src/modules/session/session-ownership.service.spec.ts@@ -247,6 +247,120 @@ describe('SessionOwnershipService', () => {* perfectly healthy — a slow query is enough — after which a peer may legitimately claim the* session; an engine left running here would be the second one on that WhatsApp account.*/+ describe('suspending loss detection', () => {+ /**+ * On SQLite every query runner shares ONE connection, so a heartbeat tick can execute INSIDE a+ * replace-all import's open transaction and see zero session rows — the DELETE has run and the+ * re-inserts have not committed. Concluding loss from that tears down engines that never stopped,+ * and does so even when the import later rolls back and the rows come straight back.+ */+ it('does not conclude loss while an import holds the token', async () => {+ const session = await seed();+ const nodeA = service('node-a', 60_000);+ await nodeA.claim(session.id);+ const lost: string[][] = [];+ nodeA.onLeaseLoss(ids => {+ lost.push(ids);+ });++ const release = nodeA.suspendLossDetection();+ await sessions.delete({ id: session.id }); // what the import's DELETE looks like from here+ await nodeA.renew();++ expect(lost).toEqual([]);+ expect(nodeA.ownedIds()).toContain(session.id);+ release();+ });++ it('concludes loss again once the token is released', async () => {+ const session = await seed();+ const nodeA = service('node-a', 60_000);+ await nodeA.claim(session.id);+ const lost: string[][] = [];+ nodeA.onLeaseLoss(ids => {+ lost.push(ids);+ });++ nodeA.suspendLossDetection()();+ await sessions.delete({ id: session.id });+ await nodeA.renew();++ expect(lost).toEqual([[session.id]]);+ });++ it('stays suspended until the LAST overlapping holder releases', async () => {+ const session = await seed();+ const nodeA = service('node-a', 60_000);+ await nodeA.claim(session.id);+ const lost: string[][] = [];+ nodeA.onLeaseLoss(ids => {+ lost.push(ids);+ });++ const first = nodeA.suspendLossDetection();+ const second = nodeA.suspendLossDetection();+ first();+ await sessions.delete({ id: session.id });+ await nodeA.renew();+ expect(lost).toEqual([]);++ second();+ await nodeA.renew();+ expect(lost).toEqual([[session.id]]);+ });++ it('releasing the same token twice does not resume early', async () => {+ const session = await seed();+ const nodeA = service('node-a', 60_000);+ await nodeA.claim(session.id);+ const lost: string[][] = [];+ nodeA.onLeaseLoss(ids => {+ lost.push(ids);+ });++ const outer = nodeA.suspendLossDetection();+ const inner = nodeA.suspendLossDetection();+ inner();+ inner(); // a double release must not cancel the outer holder++ await sessions.delete({ id: session.id });+ await nodeA.renew();++ expect(lost).toEqual([]);+ outer();+ });++ /**+ * The re-check must happen AFTER renew()'s awaits, not only at entry: a tick that was already in+ * flight when the import began is exactly the one that observes the emptied table.+ */+ it('neutralises a tick that was already running when the suspension began', async () => {+ const session = await seed();+ const nodeA = service('node-a', 60_000);+ await nodeA.claim(session.id);+ const lost: string[][] = [];+ nodeA.onLeaseLoss(ids => {+ lost.push(ids);+ });++ // Suspend from inside the query renew() awaits, i.e. after it has already started.+ const realFind = sessions.find.bind(sessions);+ let release: (() => void) | undefined;+ jest.spyOn(sessions, 'find').mockImplementation(async (...args: Parameters<typeof realFind>) => {+ release = nodeA.suspendLossDetection();+ await sessions.delete({ id: session.id });+ return realFind(...args);+ });++ await nodeA.renew();+ jest.restoreAllMocks();++ expect(lost).toEqual([]);+ expect(nodeA.ownedIds()).toContain(session.id);+ release?.();+ });+ });+describe('losing a claim', () => {it('reports the sessions a peer has taken, and stops counting them as its own', async () => {const mine = await seed();diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex 95ebf93e9..f9509804e 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -43,6 +43,12 @@ export class SessionOwnershipService {private readonly owned = new Set<string>();/** Notified when a renewal proves this process no longer holds sessions it thought it did. */private onLeaseLost?: (sessionIds: string[]) => Promise<void> | void;++ /**+ * How many callers are currently telling renew() that an empty/blank result is NOT evidence of+ * loss. A counter rather than a flag so overlapping spans cannot resume each other early.+ */+ private lossDetectionSuspended = 0;/** Answers "does anything still run for this id here?" — consulted by renew(). See setEngineLiveness. */private engineLiveness?: (sessionId: string) => boolean;@@ -192,6 +198,28 @@ export class SessionOwnershipService {this.onLeaseLost = handler;}+ /**+ * Tell renew() that "this node no longer holds the row" is currently uninformative, and get back+ * the release. Held by a replace-all data import across its whole transaction.+ *+ * Why it is needed: on SQLite every TypeORM query runner shares ONE connection, so a heartbeat+ * tick can execute INSIDE the import's open transaction, after its DELETE and before its+ * re-inserts commit, and see no rows at all. Concluding loss there tears down engines that never+ * stopped — and does so even when the import later rolls back and every row comes straight back.+ *+ * Returns a release rather than exposing a resume(), so the count cannot be unbalanced by a caller+ * that forgets which spans it opened; releasing the same token twice is a no-op.+ */+ suspendLossDetection(): () => void {+ this.lossDetectionSuspended++;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.lossDetectionSuspended--;+ };+ }+/*** Register the probe renew() consults before extending a lease. Wired by SessionService to the* engine lifecycle (engine registered, start in flight, or reconnect pending). Optional like the@@ -243,6 +271,11 @@ export class SessionOwnershipService {return;}+ // Re-checked HERE, after the queries above rather than only at entry: the tick this protects+ // against is precisely one that was already in flight when the import took the token, so an+ // entry-only check would let it through. Renewing was harmless; concluding loss is not.+ if (this.lossDetectionSuspended > 0) return;+const lost = held.filter(id => !kept.has(id));if (lost.length === 0) return;for (const id of lost) this.owned.delete(id);