Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): fence the start-path FAILED write, and stop overclaiming the rest

Yudhi Armyndharis1b8c866ff965
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db30674f9..414127979 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +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.
+- **A node that has observed the loss of its session lease no longer writes `FAILED` for that session** — engine callbacks were fenced only by a local liveness check, so between a heartbeat detecting the loss and the teardown it schedules, a dying generation could park a row a peer already owned in `FAILED`, which is excluded from both the boot reset and the takeover sweep by design and so left the session outside every automatic recovery path on every node until an operator restarted it by hand. The fence engages from the heartbeat tick that detects the loss, not from the moment the lease lapses, so a window remains.
- **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-controls.ts b/src/modules/session/session-engine-controls.ts
index fea66c815..a5dc479fa 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -59,6 +59,8 @@ export interface SessionEngineControlsHost {
isSessionRetired(id: string): Promise<boolean>;
purgeAuthDirsIfDeleted(id: string, name: string): Promise<void>;
updateStatus(id: string, status: SessionStatus): Promise<void>;
+ /** Ownership gate, same contract as SessionEngineWiringHost.ownsSession. */
+ ownsSession(id: string): boolean;
stoppingSessions: Set<string>;
reconnectStates: Map<string, ReconnectState>;
stuckAuthRecoveryUsed: Set<string>;
@@ -218,7 +220,13 @@ export class SessionEngineControls {
this.engines.delete(id);
this.sessionErrors.set(id, err instanceof Error ? err.message : String(err));
await this.fences.teardownEngineSafely(id, orphan, e => e.forceDestroy(), 'force-destroy');
- await this.host.updateStatus(id, SessionStatus.FAILED).catch(() => undefined);
+ // Fenced on ownership like the engine callbacks: initializeEngine can await a slow
+ // Chromium launch for minutes, and this node's lease can lapse and be taken over inside
+ // that window. FAILED is excluded from the boot reset AND from the takeover sweep, so
+ // writing it onto a row a peer now owns strands the session on every node.
+ if (this.host.ownsSession(id)) {
+ await this.host.updateStatus(id, SessionStatus.FAILED).catch(() => undefined);
+ }
}
// Drop the reconnect state this start() armed up front: no engine was registered, so
// nothing will ever fire it, and leaving it behind is dead state a later liveness check
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index ab839d150..1d827ee10 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -331,6 +331,7 @@ export class SessionEngineLifecycle {
// runtime — delete()'s transaction must read the current value at call time), and the core
// call-ins are NON-async passthrough closures (the Task-1 delegate rule above).
this.controls = new SessionEngineControls({
+ ownsSession: (id: string) => this.ownsSession(id),
sessionRepository: this.sessionRepository,
engineFactory: this.engineFactory,
engines: this.engineRegistry,
@@ -501,9 +502,16 @@ export class SessionEngineLifecycle {
* 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.
+ * Defaults TRUE only when no ownership service is wired, which in practice means a
+ * direct-construction spec — the service is an unconditional SessionModule provider, so a running
+ * gateway always has one and this fence is live single-node too.
+ *
+ * SCOPE, stated plainly so the guarantee is not read wider than it is. Fenced: the three status
+ * writes in the event wiring, the exhausted-reconnect FAILED, and the start-path FAILED in
+ * controls. NOT fenced: handleEngineReady's direct row write and handleEngineDisconnected's
+ * DISCONNECTED — both statuses are in the boot reset's activeStatuses AND in TAKEOVER_STATUSES,
+ * so a wrong one self-heals, unlike FAILED. The gate is also a point-in-time read: `owned` can
+ * change while the awaited write is in flight, so this narrows the window rather than closing it.
*/
private ownsSession(id: string): boolean {
return nodeOwnsSession(this.ownership, id);
diff --git a/src/modules/session/session-ownership-status-fence.spec.ts b/src/modules/session/session-ownership-status-fence.spec.ts
index 42e820eec..62b42ed2f 100644
--- a/src/modules/session/session-ownership-status-fence.spec.ts
+++ b/src/modules/session/session-ownership-status-fence.spec.ts
@@ -76,19 +76,58 @@ describe('engine status writes are fenced by ownership', () => {
});
describe('SessionOwnershipService.owns', () => {
- const build = (): SessionOwnershipService =>
- new SessionOwnershipService({ createQueryBuilder: jest.fn() } as never, undefined);
+ /**
+ * Populated through the REAL claim()/release() path, not by poking the Set.
+ *
+ * An earlier version of this suite asserted only against a freshly built service, whose `owned`
+ * is empty — so `owns()` hardcoded to `return false` passed every assertion. That is the
+ * catastrophic direction (it silences every engine-driven status write on every node), so the
+ * test has to drive a claim before it can claim to pin anything.
+ */
+ const build = (affected: number): SessionOwnershipService => {
+ const execute = jest.fn().mockResolvedValue({ affected });
+ const qb = {
+ update: () => qb,
+ set: () => qb,
+ where: () => qb,
+ andWhere: () => qb,
+ execute,
+ };
+ return new SessionOwnershipService({ createQueryBuilder: () => qb } as never, undefined);
+ };
it('is false for a session this process never claimed', () => {
- expect(build().owns('never-claimed')).toBe(false);
+ expect(build(1).owns('never-claimed')).toBe(false);
+ });
+
+ it('is true only after a claim actually succeeds', async () => {
+ const svc = build(1);
+ expect(svc.owns('sess-1')).toBe(false);
+
+ await svc.claim('sess-1');
+
+ expect(svc.owns('sess-1')).toBe(true);
+ expect(svc.ownedIds()).toContain('sess-1');
+ // A claim is per-session, never a blanket "this node owns everything".
+ expect(svc.owns('sess-2')).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'));
+ it('stays false when the conditional claim matches no row (a peer holds it)', async () => {
+ const svc = build(0);
+
+ await svc.claim('sess-1');
+
+ expect(svc.owns('sess-1')).toBe(false);
+ });
+
+ it('goes back to false once the session is released', async () => {
+ const svc = build(1);
+ await svc.claim('sess-1');
+
+ await svc.release('sess-1');
+
+ expect(svc.owns('sess-1')).toBe(false);
+ expect(svc.ownedIds()).not.toContain('sess-1');
});
});
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index 2deb7869a..422c47336 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -379,9 +379,11 @@ export class SessionOwnershipService {
* "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
+ * carries the risk. Note what it does NOT mean: SessionOwnershipService is an unconditional provider
+ * in SessionModule, so a running gateway ALWAYS has one and this fence is live in single-node
+ * deployments too — every started session is claimed there, so `owns()` answers truthfully. The TRUE
+ * default therefore serves direct-construction specs, not production. Inverting it would silence
+ * every engine-driven status write everywhere 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 = (