Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(takeover): contain and narrow the lapsed-status correction
Yudhi Armyndharis719d3ed81243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 039dae648..9fb66ebb1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,7 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The Sessions page reports a dead live-event feed and re-reads the list once the feed recovers.- A Baileys media download aborted at `MEDIA_DOWNLOAD_MAX_BYTES` reports the bytes received as `sizeBytes`, and a timed-out one its declared size, instead of the cap.- The webhook docs state that at the default limits media above about 768 KiB reaches webhooks as the omitted marker, and how to raise both limits ([#1569](https://github.com/rmyndharis/OpenWA/issues/1569)). Thanks @Magnarks for the report.-- The takeover sweep marks sessions left `ready` or `initializing` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`.+- The takeover sweep marks sessions left `ready`, `initializing`, `authenticating` or `action_required` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`; `qr_ready` sessions keep their status.- Branch Docker images (`:main`, sha tags) rebuild the production apt layer, so they cannot serve stale OS packages from the build cache.- The Docker image upgrades the Debian packages inherited from the digest-pinned `node:22-slim` base at build time, so security fixes published after the base snapshot reach them; this clears CVE-2026-86145 and CVE-2026-89161 in `libpcre2-8-0`.- The Message Tester's bulk-recipients file picker refuses files over 2 MB before reading them.diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex bd6083c7d..35327b244 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -35,10 +35,17 @@> ones are left alone, and a cleanly stopped session releases its claim so it is never> "lapsed". Adopting a session fails its stuck in-flight batches (no auto-resume — the dead> node's already-sent messages are unknowable). Adopting is gated by the same-> `AUTO_START_SESSIONS` flag as boot auto-start; the sweep itself is not, because it also has a job-> that starts nothing: a row a vanished node left in a running status is marked disconnected once its-> lease has been silent for two TTLs. Nothing else revisits such a row, since the boot reset skips a-> foreign claim that is still live.+> `AUTO_START_SESSIONS` flag as boot auto-start; the sweep itself is not, and runs on every node,+> because it also has a job that starts nothing: a row a vanished node left `ready`, `initializing`,+> `authenticating` or `action_required` is marked disconnected once its lease expired more than two+> TTLs ago, which is three TTLs after the holder's last renewal plus up to one sweep interval. A+> `qr_ready` row keeps its status, so the correction never makes a mid-pairing session adoptable.+> Nothing else revisits such a row, since the boot reset skips a foreign claim that is still live.+>+> Known limitation: a holder that is alive but cannot reach the database for more than three lease+> TTLs minus one heartbeat (160s at defaults) is marked disconnected by a peer too, and does not write its status back when it reconnects. Its+> renewal still finds its own claim, so it detects no loss, and a steadily connected engine emits no+> new status. The row reads `disconnected` until that engine's status next changes.>> **Request routing now exists, opt-in via `NODE_URL`.** When every node sets its own> reachable URL (e.g. `NODE_URL=http://10.0.0.5:2785`), a session-scoped request landing on@@ -57,6 +64,11 @@> node whose clock runs more than one lease TTL (default 60s) ahead sees healthy peers as lapsed and> will take their sessions over. Run NTP (or any time sync) on every node — the default on ordinary> server images — and treat a skew larger than `SESSION_LEASE_TTL_MS` as a misconfiguration.+> The status correction reads the same timestamps: a node whose clock runs more than three TTLs minus+> one heartbeat ahead (160s at defaults) marks a healthy peer's sessions disconnected, even with+> `AUTO_START_SESSIONS` off, and nothing writes them back. On PostgreSQL the lease columns hold a+> local wall time with no zone, so every node must also run in the same time zone (`TZ`): a node east+> of a peer reads that peer's leases as expired by the offset between them.>> **A forwarded request is throttled on both nodes.** The receiving node counts it before> forwarding, and the owner counts it again on arrival; with `REDIS_ENABLED=true` both counts landdiff --git a/docs/31-session-lifecycle-design.md b/docs/31-session-lifecycle-design.mdindex 48d5686ca..88e8b9a65 100644--- a/docs/31-session-lifecycle-design.md+++ b/docs/31-session-lifecycle-design.md@@ -77,9 +77,12 @@ stop/delete lands during start() — no resurrection to READY').**Interleaving:** node A holds session X's lease; node B adopts it after A's lease lapses; astale in-flight write from A would clobber B's status.**Defense:** on lease loss, `stopOrphanEngines` destroys local engines; the session row is the-owning node's alone (`session.service.ts` boot path).+owning node's alone (`session.service.ts` boot path). The one exception is the takeover sweep's+`markLapsedDisconnected`, which marks a row disconnected only under the predicate it read (same+`nodeId`, same status, lease expired more than two TTLs ago), so a row B has claimed matches nothing.**Pinned by:** `src/modules/takeover/session-takeover.service.spec.ts` +-`session-ownership.service.spec.ts` + `session-ownership-status-fence.spec.ts`.+`session-ownership.service.spec.ts` + `session-ownership-status-fence.spec.ts` + the real-database+predicate spec for `markLapsedDisconnected` in `src/modules/session/session.service.spec.ts`.### INV-7 — FAILED sessions are deliberately NOT adopted by takeoverdiff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 6fcd66966..df4b328ee 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -461,8 +461,9 @@ export default () => ({return Number.isFinite(n) && n > 0 ? n : 20_000;})(),// Takeover sweep cadence (default 30s): how often a node looks for sessions whose holder's- // lease has lapsed — a crashed peer, or this node's own previous identity after a container- // recreate — and starts them here. Gated by the AUTO_START_SESSIONS feature flag.+ // lease has lapsed (a crashed peer, or this node's own previous identity after a container+ // recreate) and starts them here. Adopting follows the AUTO_START_SESSIONS feature flag; the+ // sweep itself runs on every node and also marks a vanished node's leftover rows disconnected.takeoverSweepMs: (() => {const n = parseInt(process.env.SESSION_TAKEOVER_SWEEP_MS ?? '', 10);return Number.isFinite(n) && n > 0 ? n : 30_000;diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex c4d218c0c..f727800b3 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -1175,8 +1175,16 @@ export class SessionEngineLifecycle {return this.broadcaster.updateStatus(id, status);}- /** Public delegate: the fan-out half only, for a caller that wrote the row under its own predicate. */+ /**+ * Public delegate: the fan-out half only, for a caller that wrote the row under its own predicate.+ *+ * Always fans out. The caller's write affecting a row already proves a real transition, and the+ * de-dup map cannot judge one: it only records what THIS process announced, so on a node that never+ * hosted the engine it still holds the status of an earlier correction, not the READY a peer+ * announced since.+ */announceStatus(id: string, status: SessionStatus): void {+ this.broadcaster.clear(id);this.broadcaster.announce(id, status);}}diff --git a/src/modules/session/session-status-broadcaster.ts b/src/modules/session/session-status-broadcaster.tsindex 48f836314..971ce7c53 100644--- a/src/modules/session/session-status-broadcaster.ts+++ b/src/modules/session/session-status-broadcaster.ts@@ -18,7 +18,8 @@ import { type createLogger } from '../../common/services/logger.service';export class SessionStatusBroadcaster {// Last session.status value broadcast per session. Some engines signal one transition via BOTH// onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards both the WS emit- // and the webhook POST against firing the same status twice. Cleared on delete().+ // and the webhook POST against firing the same status twice. Cleared on delete(), and before a+ // lapsed-row correction is announced (see SessionEngineLifecycle.announceStatus).readonly lastDispatchedStatus = new Map<string, SessionStatus>();private readonly sessionRepository: Repository<Session>;@@ -67,7 +68,10 @@ export class SessionStatusBroadcaster {}}- /** Drop the de-dup entry for a session — called from delete()'s committed-delete cleanup. */+ /**+ * Drop the de-dup entry for a session — called from delete()'s committed-delete cleanup, and+ * before a lapsed-status correction announces, since that write is a transition this process never saw.+ */clear(id: string): void {this.lastDispatchedStatus.delete(id);}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 929d0569a..529dab61d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2527,6 +2527,116 @@ describe('SessionService', () => {expect(marked).toEqual([]);expect(repository.update).not.toHaveBeenCalled();});++ // The takeover sweep adopts every corrected status anyway, so a correction never changes what it+ // adopts. QR_READY is the exception: the sweep never adopts a mid-pairing session but does adopt a+ // DISCONNECTED one with a phone, so rewriting it would launch an engine that only renders a QR.+ it('corrects every running status the takeover sweep adopts, and leaves QR_READY alone', async () => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ const rows = [+ SessionStatus.READY,+ SessionStatus.INITIALIZING,+ SessionStatus.AUTHENTICATING,+ SessionStatus.ACTION_REQUIRED,+ SessionStatus.QR_READY,+ ].map(status => stranded({ id: status, status, phone: '628123' }));++ const marked = await service.markLapsedDisconnected(rows, GONE_BEFORE);++ expect(marked).toEqual([+ SessionStatus.READY,+ SessionStatus.INITIALIZING,+ SessionStatus.AUTHENTICATING,+ SessionStatus.ACTION_REQUIRED,+ ]);+ });++ it('a failed write on one row does not stop the rows after it', async () => {+ (repository.update as jest.Mock)+ .mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'))+ .mockResolvedValueOnce({ affected: 1 });++ const marked = await service.markLapsedDisconnected(+ [stranded({ id: 'boom' }), stranded({ id: 'fine' })],+ GONE_BEFORE,+ );++ expect(marked).toEqual(['fine']);+ });++ // This process never hosts the engine, so its de-dup map never sees the READY another node+ // announced in between, and still holds the DISCONNECTED from its own first correction.+ it('announces a second correction of the same session after another node ran it in between', async () => {+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.markLapsedDisconnected([stranded({ nodeId: 'node-c' })], GONE_BEFORE);+ // node-d claims the row, reaches READY and vanishes too; none of that happens on this process.+ await service.markLapsedDisconnected([stranded({ nodeId: 'node-d' })], GONE_BEFORE);++ const disconnected = { sessionId: 'stranded-1', status: SessionStatus.DISCONNECTED };+ expect(webhookService.dispatch).toHaveBeenCalledTimes(2);+ expect(webhookService.dispatch).toHaveBeenNthCalledWith(2, 'stranded-1', 'session.status', disconnected);+ expect(eventsGateway.emitSessionStatus).toHaveBeenCalledTimes(2);+ });++ // The mocks above show what the predicate asks for; whether it filters is SQL. A snapshot read+ // before a renewal lands is the race the predicate exists for: the write has to refuse a row whose+ // lease moved on, even though the snapshot still says that lease is long gone.+ describe('against a real database', () => {+ const TTL_MS = 60_000;+ let db: DataSource;+ let sessions: Repository<Session>;++ beforeAll(async () => {+ db = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Session], synchronize: true });+ await db.initialize();+ sessions = db.getRepository(Session);+ });++ afterAll(async () => {+ await db.destroy();+ });++ beforeEach(() => {+ (repository.update as jest.Mock).mockImplementation((...args: Parameters<Repository<Session>['update']>) =>+ sessions.update(...args),+ );+ });++ afterEach(async () => {+ await sessions.clear();+ });++ it('writes only a row whose lease is still more than two TTLs past expiry when the write lands', async () => {+ const now = Date.now();+ const seed = (name: string): Promise<Session> =>+ sessions.save(+ sessions.create({+ name,+ status: SessionStatus.READY,+ config: {},+ nodeId: 'dead-node',+ leaseExpiresAt: new Date(now - 3 * TTL_MS),+ }),+ );+ const renewed = await seed('renewed');+ const lapsedOnce = await seed('lapsed-once');+ const gone = await seed('gone');+ const snapshot = await sessions.find();++ // Between the read and the write, one holder renews and another has lapsed only once since.+ await sessions.update({ id: renewed.id }, { leaseExpiresAt: new Date(now + TTL_MS) });+ await sessions.update({ id: lapsedOnce.id }, { leaseExpiresAt: new Date(now - TTL_MS) });++ const marked = await service.markLapsedDisconnected(snapshot, new Date(now - 2 * TTL_MS));++ expect(marked).toEqual([gone.id]);+ const statusOf = async (id: string): Promise<SessionStatus> => (await sessions.findOneByOrFail({ id })).status;+ expect(await statusOf(renewed.id)).toBe(SessionStatus.READY);+ expect(await statusOf(lapsedOnce.id)).toBe(SessionStatus.READY);+ expect(await statusOf(gone.id)).toBe(SessionStatus.DISCONNECTED);+ });+ });});// An engine that retries a dropped connection ON ITS OWN never reaches the service-level reconnectdiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 3c8dd3ba1..ee3ab5774 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -81,8 +81,8 @@ export const AUTOSTART_THROTTLE_MS = 2_000;/*** Statuses that assert an engine is running somewhere. The boot reset clears them for every row this- * node may claim; markLapsedDisconnected clears them for a row whose holder never came back. FAILED- * and CREATED stay out of both: an operator has to see them.+ * node may claim; markLapsedDisconnected clears the subset below for a row whose holder never came+ * back. FAILED and CREATED stay out of both: an operator has to see them.*/const ACTIVE_STATUSES = [SessionStatus.READY,@@ -92,6 +92,16 @@ const ACTIVE_STATUSES = [SessionStatus.ACTION_REQUIRED,];+/**+ * What markLapsedDisconnected corrects: every active status the takeover sweep adopts anyway, so a+ * correction never changes what the sweep adopts. AUTHENTICATING and ACTION_REQUIRED are in: both+ * claim a running engine, and whatever a human was asked to do lived in the engine that died with its+ * node. QR_READY is left out because correcting it would change adoption: the sweep never adopts a+ * mid-pairing session, but it does adopt a DISCONNECTED one with a phone, so rewriting it would launch+ * an engine that only renders a QR nobody asked for.+ */+const LAPSED_CORRECTED_STATUSES: SessionStatus[] = ACTIVE_STATUSES.filter(status => status !== SessionStatus.QR_READY);+/*** The session-record API: CRUD over the sessions table, aggregate stats, and the thin engine query* proxies (QR/pairing/chats/groups/chat-state) behind the controller routes. Every engine LIFECYCLE@@ -874,29 +884,41 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* `goneBefore` is the caller's "really gone" cutoff, not simply now: a lease lapses while its* holder is perfectly healthy whenever a query runs long, and the next heartbeat re-extends it.* Acting on a single lapse would report a live peer's sessions as disconnected, and nothing would- * correct it, because that peer's renewal still finds its own nodeId and detects no loss.+ * correct it, because that peer's renewal still finds its own nodeId and detects no loss. The cutoff+ * narrows that case without closing it: a holder cut off from the database for longer than the+ * cutoff is marked too, and does not write its status back once it reconnects.*/async markLapsedDisconnected(sessions: Session[], goneBefore: Date): Promise<string[]> {const marked: string[] = [];for (const session of sessions) {- if (!ACTIVE_STATUSES.includes(session.status)) continue;+ if (!LAPSED_CORRECTED_STATUSES.includes(session.status)) continue;// Both are guaranteed non-null by the lapsed-claim query that produced these rows, and both are- // load-bearing in the predicate below: TypeORM drops an `undefined` value from a where clause- // rather than matching on it, so a null here would silently widen the update.+ // load-bearing in the predicate below. TypeORM throws on a null or undefined where value, so a+ // null here would fail this row's write instead of matching on it.if (session.nodeId == null) continue;if (session.leaseExpiresAt == null || session.leaseExpiresAt >= goneBefore) continue;// Written on the same predicate the read used, never by id alone: a peer, or this node's own// adopt loop, can claim and start this row at any moment, and a claim rewrites `nodeId`, so a// row that was taken matches nothing here and keeps the status its start gave it.- const { affected } = await this.sessionRepository.update(- {- id: session.id,- nodeId: session.nodeId,- leaseExpiresAt: LessThan(goneBefore),- status: session.status,- },- { status: SessionStatus.DISCONNECTED },- );+ let affected: number | undefined;+ try {+ ({ affected } = await this.sessionRepository.update(+ {+ id: session.id,+ nodeId: session.nodeId,+ leaseExpiresAt: LessThan(goneBefore),+ status: session.status,+ },+ { status: SessionStatus.DISCONNECTED },+ ));+ } catch (error) {+ // One row's failed write must not strand the rows after it. The next sweep retries this one.+ this.logger.warn(`Failed to correct the status session ${session.name} was left in`, {+ sessionId: session.id,+ error: error instanceof Error ? error.message : String(error),+ });+ continue;+ }if (!affected) continue;this.logger.warn(`Session ${session.name} was left ${session.status} by a node that never came back`, {sessionId: session.id,diff --git a/src/modules/takeover/session-takeover.service.spec.ts b/src/modules/takeover/session-takeover.service.spec.tsindex b00a99eda..14541c871 100644--- a/src/modules/takeover/session-takeover.service.spec.ts+++ b/src/modules/takeover/session-takeover.service.spec.ts@@ -182,6 +182,18 @@ describe('SessionTakeoverService', () => {expect(order).toEqual(['mark', 'start']);});+ it('a failed status correction does not cost the pass its adoptions', async () => {+ // A failed correction leaves no write behind, so nothing it guards against can land on an engine+ // this pass starts. Letting it abort the sweep would turn a database blip into a tick with no+ // failover at all.+ const { svc, start, markLapsedDisconnected } = build([lapsed({ name: 'a' })]);+ markLapsedDisconnected.mockRejectedValue(new Error('SQLITE_BUSY: database is locked'));++ await expect(svc.sweep()).resolves.toBeUndefined();++ expect(start).toHaveBeenCalledWith('id-a');+ });+it('gives the reset a cutoff of two lease TTLs, so a healthy peer that lapsed once is left alone', async () => {const { svc, markLapsedDisconnected } = build([lapsed({ name: 'a' })]);const before = Date.now();diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.tsindex cde545f69..f5090b1e7 100644--- a/src/modules/takeover/session-takeover.service.ts+++ b/src/modules/takeover/session-takeover.service.ts@@ -14,6 +14,10 @@ import { BulkMessageService } from '../message/bulk-message.service';* QR_READY is deliberately absent — an unpaired session on a dead node has nothing to resume, and* restarting it elsewhere just renders a QR nobody asked for. FAILED is deliberately absent too:* it marks a session an operator must look at, and silently relocating it would hide that.+ *+ * DISCONNECTED is present, so the status correction must never write it over a status this set+ * leaves out: markLapsedDisconnected corrects only READY, INITIALIZING, AUTHENTICATING and+ * ACTION_REQUIRED, which are adopted either way, and leaves a lapsed QR_READY row as it is.*/const TAKEOVER_STATUSES = new Set<SessionStatus>([SessionStatus.READY,@@ -27,13 +31,18 @@ const TAKEOVER_STATUSES = new Set<SessionStatus>([const TAKEOVER_START_STAGGER_MS = 2000;/**- * How many lease TTLs of silence make a holder "really gone".+ * How many lease TTLs past its expiry a lease must be before the status correction treats its holder+ * as "really gone".** Two, not one. A lease lapses while its holder is perfectly healthy whenever a query runs long, and* the next heartbeat re-extends it; correcting a status on a single lapse would report a live peer's* sessions as disconnected, and nothing would put that right, because the peer's own renewal still- * finds its nodeId and detects no loss. Adoption is unaffected and still acts on the first lapse: it- * goes through claim(), which a live holder wins back.+ * finds its nodeId and detects no loss. A lease expires one TTL after the holder's last renewal, so a+ * row is corrected more than three TTLs after that renewal, plus up to one sweep interval.+ *+ * Adoption does not wait for this and acts on the first lapse. It goes through claim(), which takes a+ * lapsed lease outright: a holder that was only slow loses the session and tears its engine down at+ * its next heartbeat.*/const STRANDED_LEASE_TTL_MULTIPLE = 2;@@ -119,8 +128,10 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD}/**- * One pass: correct every stale status a vanished node left behind, then adopt every eligible- * lapsed session. Exposed for the spec; the timer drives it.+ * One pass: correct every stale status a vanished node left behind, then, when AUTO_START_SESSIONS+ * is on, adopt every eligible lapsed session. Runs on every node whatever that flag says, and a+ * failed correction is logged without costing the pass its adoptions. Exposed for the spec; the+ * timer drives it.*/async sweep(): Promise<void> {if (this.stopping) return;@@ -128,9 +139,16 @@ export class SessionTakeoverService implements OnApplicationBootstrap, OnModuleD// Correct the stale statuses BEFORE adopting: a row this pass goes on to start gets its// INITIALIZING written by start() afterwards, so the correction can never land on a live engine.- // Idempotent, because DISCONNECTED is not one of the statuses it acts on.+ // Idempotent, because DISCONNECTED is not one of the statuses it acts on. A failure leaves no+ // write pending, so the adopt loop still runs; the next pass retries the correction.const goneBefore = new Date(Date.now() - this.ownership.leaseTtlMs * STRANDED_LEASE_TTL_MULTIPLE);- await this.sessionService.markLapsedDisconnected(lapsed, goneBefore);+ try {+ await this.sessionService.markLapsedDisconnected(lapsed, goneBefore);+ } catch (error) {+ this.logger.warn('Lapsed session status correction failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ }if (!resolveFeatureFlags(this.configService).autoStartSessions) return;const eligible = lapsed.filter(session => this.isEligible(session));