Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): end a READY stretch where the engine left READY

Yudhi Armyndharisc58b95a1cf43
diff --git a/docs/31-session-lifecycle-design.md b/docs/31-session-lifecycle-design.md
index 7c7d3da1b..ee4ff8617 100644
--- a/docs/31-session-lifecycle-design.md
+++ b/docs/31-session-lifecycle-design.md
@@ -113,7 +113,9 @@ before touching anything in the logout/forceKill path.
**Defense:** `reconnect-policy.ts` — a pure decision function (attempt budget, loop alerts)
consumed by the lifecycle, which resets the budget only when the session held READY for
`STABLE_READY_MS` (5 min) before its next drop or its next READY, so a session that flaps keeps
-backing off and still alerts; the clamps exist because a naive `delay * 2^attempt` reaches values
+backing off and still alerts. The stretch ends where the engine first reports a non-READY state
+(`readyEndedAt`), so a Baileys in-engine reconnect between two READYs is not counted as READY time;
+the clamps exist because a naive `delay * 2^attempt` reaches values
`setTimeout` silently truncates, and overflows to `Infinity` on a long enough streak.
**Pinned by:** `reconnect-policy.spec.ts`, `session.service.spec.ts` (scheduleReconnect cases).
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index cad341612..acf6c994e 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -71,6 +71,8 @@ export interface SessionEngineWiringHost {
handleEngineDisconnected(id: string, engine: IWhatsAppEngine, reason: string): Promise<void>;
updateStatus(id: string, status: SessionStatus): Promise<void>;
cancelReconnect(id: string): void;
+ /** The live engine reported a non-READY state: record when its READY stretch ended. */
+ endReadyStretch(id: string): void;
/**
* Park an engine failure reported while a service-level reconnect awaits its re-init, instead of
* applying it: `run` is the failure's side effects, and `reason` is set for an onError report.
@@ -345,6 +347,7 @@ export class SessionEngineEventWiring {
},
onStateChanged: (engineState: EngineStatus): void => {
if (!host.isLiveEngine(id, engine)) return;
+ if (engineState !== EngineStatus.READY) host.endReadyStretch(id);
const statusMap: Record<EngineStatus, SessionStatus> = {
[EngineStatus.DISCONNECTED]: SessionStatus.DISCONNECTED,
[EngineStatus.INITIALIZING]: SessionStatus.INITIALIZING,
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 4481a74fe..fe35592b7 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -58,6 +58,12 @@ export interface ReconnectState extends ReconnectAttemptState {
parkedFailure?: { run: () => void; terminal: boolean };
/** When the session last reached READY; consumed by the next scheduleReconnect (see STABLE_READY_MS). */
readyAt?: number;
+ /**
+ * When that READY stretch ended inside the engine (it reported a non-READY state without a drop the
+ * gateway sees, e.g. a Baileys in-engine reconnect). The stretch is measured to here, not to the next
+ * READY or drop, so time spent reconnecting inside the engine never counts as READY time.
+ */
+ readyEndedAt?: number;
}
// Reconnect-backoff bounds. An OPERATOR-supplied session.config feeds this math, so the values
@@ -343,6 +349,7 @@ export class SessionEngineLifecycle {
handleEngineDisconnected: (id, engine, reason) => this.handleEngineDisconnected(id, engine, reason),
updateStatus: (id, status) => this.updateStatus(id, status),
cancelReconnect: id => this.cancelReconnect(id),
+ endReadyStretch: id => this.endReadyStretch(id),
parkReconnectInitFailure: (id, run, reason) => this.parkReconnectInitFailure(id, run, reason),
evictAndForceDestroy: (id, engine) => this.evictAndForceDestroy(id, engine),
trackPendingCredentialTeardown: (sessionName, raw) => this.trackPendingCredentialTeardown(sessionName, raw),
@@ -531,6 +538,21 @@ export class SessionEngineLifecycle {
);
}
+ /** Whether the last READY stretch lasted STABLE_READY_MS, measured to where it ended (or to now). */
+ private readyStretchHeld(state: ReconnectState): boolean {
+ return state.readyAt !== undefined && (state.readyEndedAt ?? Date.now()) - state.readyAt >= STABLE_READY_MS;
+ }
+
+ /**
+ * The live engine left READY without a drop the gateway handles (it reports the new state itself,
+ * e.g. a Baileys in-engine reconnect). Records when the READY stretch ended; readyAt stays set, so
+ * isEngineActive does not read the session as a pending gateway reconnect.
+ */
+ endReadyStretch(id: string): void {
+ const state = this.reconnectStates.get(id);
+ if (state?.readyAt !== undefined && state.readyEndedAt === undefined) state.readyEndedAt = Date.now();
+ }
+
// --- Leaf-event delegates (SessionEngineLeafEvents) ------------------------------------------
// Same-named, same-signature forwarders onto the extracted unit, so handleEngineReady's call
// site stays byte-identical (the wiring reaches the unit directly through host.leafEvents).
@@ -833,12 +855,13 @@ export class SessionEngineLifecycle {
// only if this READY held for STABLE_READY_MS, so a session that flaps keeps backing off.
// Baileys fires READY again on every internal socket reopen, with no drop reported in between:
// a previous READY that already held the window ends the streak here, before it is overwritten.
+ // The stretch is measured to where it ended (readyEndedAt), so an in-engine reconnect in between
+ // is not counted as READY time.
const reconnectState = this.reconnectStates.get(id);
if (reconnectState) {
- if (reconnectState.readyAt !== undefined && Date.now() - reconnectState.readyAt >= STABLE_READY_MS) {
- reconnectState.attempts = 0;
- }
+ if (this.readyStretchHeld(reconnectState)) reconnectState.attempts = 0;
reconnectState.readyAt = Date.now();
+ reconnectState.readyEndedAt = undefined;
if (reconnectState.timer) {
clearTimeout(reconnectState.timer);
reconnectState.timer = null;
@@ -1066,8 +1089,9 @@ export class SessionEngineLifecycle {
// this drop starts a fresh streak; a shorter one is the same flap and keeps the streak growing.
// Cleared either way, so a later re-init failure inside this episode never resets it.
if (state.readyAt !== undefined) {
- if (Date.now() - state.readyAt >= STABLE_READY_MS) state.attempts = 0;
+ if (this.readyStretchHeld(state)) state.attempts = 0;
state.readyAt = undefined;
+ state.readyEndedAt = undefined;
}
// All the backoff rules (budget, exponential delay, loop cadence) live in the
diff --git a/src/modules/session/session-ownership-status-fence.spec.ts b/src/modules/session/session-ownership-status-fence.spec.ts
index 8acb2813b..a8825101e 100644
--- a/src/modules/session/session-ownership-status-fence.spec.ts
+++ b/src/modules/session/session-ownership-status-fence.spec.ts
@@ -27,6 +27,7 @@ describe('engine status writes are fenced by ownership', () => {
handleEngineReady: jest.fn(),
handleEngineDisconnected: jest.fn().mockResolvedValue(undefined),
cancelReconnect: jest.fn(),
+ endReadyStretch: jest.fn(),
parkReconnectInitFailure: () => false,
evictAndForceDestroy: jest.fn(),
trackPendingCredentialTeardown: jest.fn(),
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 31a1c632a..caa4e4072 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2365,6 +2365,52 @@ describe('SessionService', () => {
}
});
+ it('measures a READY stretch to where the engine left READY, not to the next READY', async () => {
+ // Baileys handles a transient close inside the engine: it reports INITIALIZING and retries, and
+ // never reports a drop to the gateway. Those minutes spent reconnecting are not READY time.
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ let callbacks: EngineEventCallbacks = {};
+ mockEngine.initialize.mockImplementationOnce((cb: EngineEventCallbacks) => {
+ callbacks = cb;
+ return Promise.resolve();
+ });
+ await service.start('sess-uuid-1');
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ jest.spyOn(i, 'executeReconnect').mockResolvedValue(undefined);
+ const state = i.reconnectStates.get('sess-uuid-1')!;
+ state.attempts = 3;
+
+ // READY for 10s, then six minutes of in-engine reconnecting, then READY again.
+ i.handleEngineReady('sess-uuid-1', mockEngine, '628123', 'Tester');
+ jest.advanceTimersByTime(10_000);
+ callbacks.onStateChanged?.(EngineStatus.INITIALIZING);
+ jest.advanceTimersByTime(6 * 60_000);
+ i.handleEngineReady('sess-uuid-1', mockEngine, '628123', 'Tester');
+ expect(state.attempts).toBe(3);
+
+ // Same shape, but the READY held the window before the engine left it: the streak ends.
+ jest.advanceTimersByTime(STABLE_READY_MS);
+ callbacks.onStateChanged?.(EngineStatus.INITIALIZING);
+ jest.advanceTimersByTime(60_000);
+ i.handleEngineReady('sess-uuid-1', mockEngine, '628123', 'Tester');
+ expect(state.attempts).toBe(0);
+
+ // A gateway drop after an in-engine one measures the same way.
+ state.attempts = 3;
+ jest.advanceTimersByTime(10_000);
+ callbacks.onStateChanged?.(EngineStatus.INITIALIZING);
+ jest.advanceTimersByTime(6 * 60_000);
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ expect(state.attempts).toBe(4);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
it('keeps the streak when a second READY follows one that did not hold the stability window', () => {
jest.useFakeTimers();
try {