Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): fence engine status writes on ownership, not liveness alone

Yudhi Armyndharis488cec3ce469
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3c3832bcc..db30674f9 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
+- **A node that has lost its session lease can no longer park that session in `FAILED`** — engine callbacks were fenced only by a local liveness check, so during the window between a lapsed lease and the teardown the heartbeat schedules, a dying generation could persist a status onto a row a peer already owned; `FAILED` is excluded from both the boot reset and the takeover sweep by design, so a session pushed into it left every automatic recovery path on every node until an operator restarted it by hand.
- **Thirteen settings that did nothing under Docker now take effect** — Compose forwards environment explicitly and has no `env_file`, so `BAILEYS_MARK_ONLINE_ON_CONNECT`, `BAILEYS_SYNC_FULL_HISTORY`, `WEBHOOK_CONTACT_DETAILS`, `ALLOW_UNSIGNED_INGRESS`, `STORE_EPHEMERAL_MESSAGES`, `RESOLVE_LID_TO_PHONE`, `SIMULATE_TYPING`, `MCP_ENABLED`, `SEARCH_ENABLED`, `SERVE_DASHBOARD`, `CACHE_ENABLED`, `DATABASE_LOGGING` and `MAIN_DATABASE_SYNCHRONIZE` never reached the container however the operator's `.env` was written — the MCP server could not be enabled at all, `SEARCH_ENABLED=false` did not disable the search route it documents, and `BAILEYS_MARK_ONLINE_ON_CONNECT` left the paired phone's notifications suppressed for as long as the gateway stayed connected.
### Changed
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index 38cad0bc2..48ef9751f 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -34,6 +34,12 @@ import { SessionEngineLeafEvents } from './session-engine-leaf-events';
export interface SessionEngineWiringHost {
/** Liveness gate: true only while `engine` is still the live engine registered for `id`. */
isLiveEngine(id: string, engine: IWhatsAppEngine): boolean;
+ /**
+ * Ownership gate: true while this node may still speak for `id`. Orthogonal to isLiveEngine —
+ * between a lapsed lease and the teardown the heartbeat schedules, isLiveEngine is still true
+ * while this is already false. TRUE when no ownership service is wired (single process).
+ */
+ ownsSession(id: string): boolean;
handleEngineReady(id: string, engine: IWhatsAppEngine, phone: string, pushName: string): void;
handleEngineDisconnected(id: string, engine: IWhatsAppEngine, reason: string): Promise<void>;
updateStatus(id: string, status: SessionStatus): Promise<void>;
@@ -85,6 +91,27 @@ export class SessionEngineEventWiring {
sessionName: string,
host: SessionEngineWiringHost,
): EngineEventCallbacks {
+ /**
+ * Persist an engine-driven status, but only while this node still owns the session.
+ *
+ * Every caller has already passed the isLiveEngine fence; this closes the other axis. A node
+ * whose lease lapsed keeps a live engine until the heartbeat's teardown completes, and a status
+ * written in that window lands on a row a peer now owns. FAILED is the one that does not heal:
+ * the boot reset and the takeover sweep both exclude it by design, so the session leaves every
+ * automatic recovery path until an operator restarts it by hand.
+ */
+ const persistStatus = (status: SessionStatus): void => {
+ if (!host.ownsSession(id)) {
+ this.logger.warn('Skipped an engine status write for a session this node no longer owns', {
+ sessionId: id,
+ status,
+ action: 'status_write_skipped_not_owned',
+ });
+ return;
+ }
+ void host.updateStatus(id, status);
+ };
+
return {
onQRCode: (qr: string): void => {
if (!host.isLiveEngine(id, engine)) return;
@@ -109,7 +136,7 @@ export class SessionEngineEventWiring {
},
);
- void host.updateStatus(id, SessionStatus.QR_READY);
+ persistStatus(SessionStatus.QR_READY);
},
onReady: (phone, pushName): void => host.handleEngineReady(id, engine, phone, pushName),
onMessage: (message): void => host.messages.handleInboundMessage(id, engine, message),
@@ -204,7 +231,7 @@ export class SessionEngineEventWiring {
};
const newStatus = statusMap[engineState];
if (newStatus) {
- void host.updateStatus(id, newStatus);
+ persistStatus(newStatus);
}
},
onActionRequired: (reason: string): void => {
@@ -324,7 +351,7 @@ export class SessionEngineEventWiring {
},
);
- void host.updateStatus(id, SessionStatus.FAILED);
+ persistStatus(SessionStatus.FAILED);
// onError is terminal (no reconnect is scheduled — re-scan is required). Evict the dead engine
// and SIGKILL its process: leaving it in the map would hold a concurrency slot indefinitely and
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index bd99f47b3..ab839d150 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -30,6 +30,7 @@ import { SessionStatusBroadcaster } from './session-status-broadcaster';
import { SessionEngineLeafEvents } from './session-engine-leaf-events';
import { SessionEngineEventWiring, SessionEngineWiringHost } from './session-engine-event-wiring';
import { SessionEngineControls } from './session-engine-controls';
+import { SessionOwnershipService, nodeOwnsSession } from './session-ownership.service';
/**
* Eager status-history reads are opt-in. On affected freshly paired whatsapp-web.js accounts,
@@ -255,6 +256,11 @@ export class SessionEngineLifecycle {
// running gateway always has it.
@Optional()
private readonly auditService?: AuditService,
+ // @Optional for the same reason as the three above: direct-construction specs omit it, and an
+ // absent ownership service means a single-process deployment where every session is ours. The
+ // ownsSession() default below therefore has to be TRUE, not false.
+ @Optional()
+ private readonly ownership?: SessionOwnershipService,
) {
// The fence Maps are handed over BY REFERENCE: they stay lifecycle fields (specs poke them
// through the lifecycle), while the fence logic operates on the same instances.
@@ -286,6 +292,7 @@ export class SessionEngineLifecycle {
// promise and add settlement hops the retirement-race specs assert against).
this.wiringHost = {
isLiveEngine: (id, engine) => this.isLiveEngine(id, engine),
+ ownsSession: id => this.ownsSession(id),
handleEngineReady: (id, engine, phone, pushName) => this.handleEngineReady(id, engine, phone, pushName),
handleEngineDisconnected: (id, engine, reason) => this.handleEngineDisconnected(id, engine, reason),
updateStatus: (id, status) => this.updateStatus(id, status),
@@ -484,6 +491,24 @@ export class SessionEngineLifecycle {
return this.engines.isLive(id, engine);
}
+ /**
+ * May this node still write for `id`? Orthogonal to isLiveEngine, and both are required before a
+ * status is persisted from an engine callback.
+ *
+ * A lease can lapse while the process is perfectly healthy — a slow query is enough. The heartbeat
+ * notices at its next tick and tears the local engine down, but until that finishes isLiveEngine
+ * is still true, so a dying generation can persist a status onto a row a peer now owns. FAILED is
+ * the expensive one: it is excluded from the boot reset AND from the takeover sweep, so a session
+ * pushed into it is out of every automatic recovery path on every node until an operator acts.
+ *
+ * Defaults TRUE when no ownership service is wired (single-process deployments and the
+ * direct-construction specs) — there is no peer to protect the row from, and defaulting false
+ * would silence every engine-driven status write there.
+ */
+ private ownsSession(id: string): boolean {
+ return nodeOwnsSession(this.ownership, id);
+ }
+
private async initializeEngine(id: string, session: Session): Promise<void> {
this.logger.log(`Initializing engine for session: ${session.name}`, {
sessionId: id,
@@ -845,7 +870,10 @@ export class SessionEngineLifecycle {
// Don't leave the session silently stuck DISCONNECTED — mark it terminally FAILED with a reason
// so findOne/findAll surface it via `lastError` and the dashboard shows it needs a restart.
this.sessionErrors.set(id, decision.reason);
- void this.updateStatus(id, SessionStatus.FAILED);
+ // Same ownership fence as the engine callbacks: a reconnect chain that exhausts itself after
+ // this node's lease lapsed must not park a peer's session in FAILED, which nothing resets
+ // automatically. The in-memory error above is per-process and harmless either way.
+ if (this.ownsSession(id)) void this.updateStatus(id, SessionStatus.FAILED);
// Terminal path — evict the dead engine so it neither holds a concurrency slot nor makes a
// subsequent start() reject the session as "already started". This mirrors onError's terminal
// path (the same rationale: leaving the engine in the map wedges the session). The engine may
diff --git a/src/modules/session/session-ownership-status-fence.spec.ts b/src/modules/session/session-ownership-status-fence.spec.ts
new file mode 100644
index 000000000..42e820eec
--- /dev/null
+++ b/src/modules/session/session-ownership-status-fence.spec.ts
@@ -0,0 +1,110 @@
+import { SessionEngineEventWiring, SessionEngineWiringHost } from './session-engine-event-wiring';
+import { SessionOwnershipService, nodeOwnsSession } from './session-ownership.service';
+import { SessionStatus } from './entities/session.entity';
+import { EngineStatus, IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import { createLogger } from '../../common/services/logger.service';
+
+/**
+ * A lease can lapse while this process is perfectly healthy — a slow query is enough — and the
+ * heartbeat only tears the local engine down at its next tick. In that window `isLiveEngine` is
+ * still true, so an engine callback could persist a status onto a row a peer already owns.
+ *
+ * FAILED is the expensive one and the reason this fence exists: it is excluded from the boot reset
+ * (session.service's activeStatuses) AND from the takeover sweep (TAKEOVER_STATUSES), both by
+ * design, so a session pushed into it leaves every automatic recovery path on every node until an
+ * operator restarts it by hand. A node that no longer owns the session must not be able to do that.
+ */
+describe('engine status writes are fenced by ownership', () => {
+ const ENGINE = { destroy: jest.fn() } as unknown as IWhatsAppEngine;
+
+ /** A host that is live by every OTHER measure, so the ownership gate is the only variable. */
+ const buildHost = (owns: boolean): { host: SessionEngineWiringHost; updateStatus: jest.Mock } => {
+ const updateStatus = jest.fn().mockResolvedValue(undefined);
+ const host = {
+ isLiveEngine: () => true,
+ ownsSession: () => owns,
+ updateStatus,
+ handleEngineReady: jest.fn(),
+ handleEngineDisconnected: jest.fn().mockResolvedValue(undefined),
+ cancelReconnect: jest.fn(),
+ evictAndForceDestroy: jest.fn(),
+ trackPendingCredentialTeardown: jest.fn(),
+ reportRestrictionLifted: jest.fn(),
+ claimStuckAuthRecovery: () => false,
+ sessionErrors: { set: jest.fn(), clear: jest.fn(), get: jest.fn() },
+ sessionRestrictions: { set: jest.fn(), clear: jest.fn(), get: jest.fn() },
+ presence: { set: jest.fn(), clear: jest.fn() },
+ messages: { handleInboundMessage: jest.fn(), handleHistoryMessages: jest.fn() },
+ statusStore: { record: jest.fn() },
+ webhookService: { dispatch: jest.fn() },
+ eventsGateway: { emitQRCode: jest.fn(), emitSessionStatus: jest.fn() },
+ hookManager: { execute: jest.fn().mockResolvedValue(undefined) },
+ } as unknown as SessionEngineWiringHost;
+ return { host, updateStatus };
+ };
+
+ const callbacks = (owns: boolean) => {
+ const { host, updateStatus } = buildHost(owns);
+ const wiring = new SessionEngineEventWiring({ logger: createLogger('test') });
+ return { cb: wiring.buildCallbacks('sess-1', ENGINE, 'sess-1-name', host), updateStatus };
+ };
+
+ it('persists engine-driven statuses while this node owns the session', () => {
+ const { cb, updateStatus } = callbacks(true);
+
+ cb.onQRCode?.('qr-data');
+ cb.onStateChanged?.(EngineStatus.READY);
+ cb.onError?.('engine blew up');
+
+ expect(updateStatus.mock.calls.map((call: [string, SessionStatus]) => call[1])).toEqual([
+ SessionStatus.QR_READY,
+ SessionStatus.READY,
+ SessionStatus.FAILED,
+ ]);
+ });
+
+ it('writes NOTHING once the lease is gone — above all not FAILED, which nothing resets', () => {
+ const { cb, updateStatus } = callbacks(false);
+
+ cb.onQRCode?.('qr-data');
+ cb.onStateChanged?.(EngineStatus.READY);
+ cb.onStateChanged?.(EngineStatus.FAILED);
+ cb.onError?.('engine blew up');
+
+ expect(updateStatus).not.toHaveBeenCalled();
+ });
+});
+
+describe('SessionOwnershipService.owns', () => {
+ const build = (): SessionOwnershipService =>
+ new SessionOwnershipService({ createQueryBuilder: jest.fn() } as never, undefined);
+
+ it('is false for a session this process never claimed', () => {
+ expect(build().owns('never-claimed')).toBe(false);
+ });
+
+ it('tracks exactly what ownedIds reports, so the fence and the register cannot disagree', () => {
+ const svc = build();
+ // ownedIds() is the existing test seam; owns() must be its membership test, not a second source
+ // of truth that could drift from it.
+ for (const id of svc.ownedIds()) expect(svc.owns(id)).toBe(true);
+ expect(svc.owns('absent')).toBe(svc.ownedIds().includes('absent'));
+ });
+});
+
+describe('nodeOwnsSession default', () => {
+ // The single most dangerous way to get this wrong: defaulting to false. Every single-process
+ // deployment and every direct-construction spec has no ownership service, so a false default would
+ // stop persisting engine statuses entirely rather than fencing a rare cross-node write.
+ it('is TRUE when no ownership service is wired', () => {
+ expect(nodeOwnsSession(undefined, 'any-session')).toBe(true);
+ });
+
+ it('delegates to the service when one is wired', () => {
+ const owns = jest.fn().mockReturnValue(false);
+ expect(nodeOwnsSession({ owns }, 'sess-1')).toBe(false);
+ expect(owns).toHaveBeenCalledWith('sess-1');
+
+ expect(nodeOwnsSession({ owns: jest.fn().mockReturnValue(true) }, 'sess-1')).toBe(true);
+ });
+});
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index f9509804e..2deb7869a 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -356,4 +356,35 @@ export class SessionOwnershipService {
ownedIds(): string[] {
return [...this.owned];
}
+
+ /**
+ * Does THIS process still hold `sessionId`? Synchronous and in-memory on purpose.
+ *
+ * Callers are engine callbacks on the hot path that must not introduce an await: an extra
+ * suspension point there would re-open the very retirement race the surrounding `isLiveEngine`
+ * fence closes. The in-memory set is also the right authority here — it is what `renew()` clears
+ * the moment it observes the claim is gone, which is exactly the transition this answers.
+ *
+ * The two fences are orthogonal and both are needed. `isLiveEngine` asks "is this engine object
+ * still the registered one" (generation safety, local); this asks "may this node still speak for
+ * the session at all" (ownership, cluster-wide). Between losing a lease and finishing the teardown
+ * the heartbeat schedules, the first is still true while the second is already false.
+ */
+ owns(sessionId: string): boolean {
+ return this.owned.has(sessionId);
+ }
}
+
+/**
+ * "May this node write for `sessionId`?" with the no-ownership case decided in one place.
+ *
+ * Exported as a function rather than inlined at the call sites because the DEFAULT is the part that
+ * carries the risk: an absent ownership service means a single-process deployment (and every
+ * direct-construction spec), where every session is ours and the answer must be TRUE. Inverting it
+ * would silence every engine-driven status write instead of fencing a few — a far worse failure than
+ * the one the fence exists to prevent, and invisible without a test that pins the default.
+ */
+export const nodeOwnsSession = (
+ ownership: Pick<SessionOwnershipService, 'owns'> | undefined,
+ sessionId: string,
+): boolean => !ownership || ownership.owns(sessionId);