Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(takeover): correct a lapsed qr_ready row that was never linked

Yudhi Armyndharisd6d7f170a495
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d93ea542c..153e1f047 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The Sessions page reports a dead live-event feed, and both it and the Chats page re-read their data once the feed recovers, including a feed that never connected.
- 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`, `initializing`, `authenticating` or `action_required` by a node that never returned disconnected, regardless of `AUTO_START_SESSIONS`; `qr_ready` sessions keep their status.
+- The takeover sweep marks as disconnected any session left `ready`, `initializing`, `authenticating` or `action_required` by a node that never returned, regardless of `AUTO_START_SESSIONS`.
+- The takeover sweep also marks a lapsed `qr_ready` session with no phone as disconnected; one with a phone keeps its status.
- Branch Docker images (`:main`, sha tags) rebuild the production stage without the build cache, so they cannot serve stale OS packages.
- 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.md
index 35327b244..25ad3a020 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -39,7 +39,8 @@
> 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.
+> `qr_ready` row is marked too while it has no phone, since the sweep never adopts a row without one;
+> a `qr_ready` row with a phone keeps its status, so the correction never makes it 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
diff --git a/docs/31-session-lifecycle-design.md b/docs/31-session-lifecycle-design.md
index 88e8b9a65..0f80c889c 100644
--- a/docs/31-session-lifecycle-design.md
+++ b/docs/31-session-lifecycle-design.md
@@ -79,7 +79,9 @@ stale 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). 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.
+`nodeId`, same status, lease expired more than two TTLs ago, and for a `qr_ready` row still no
+phone), so a row B has claimed, or a pairing that completed meanwhile, matches nothing. A `qr_ready`
+row with a phone is never marked: the adoption sweep would take the resulting disconnected row over.
**Pinned by:** `src/modules/takeover/session-takeover.service.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`.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index c835a02b4..acaa7775b 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -2528,18 +2528,22 @@ describe('SessionService', () => {
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 () => {
+ // A correction must never change what the takeover sweep adopts. It adopts every other corrected
+ // status anyway, and never adopts a row without a phone, so a QR_READY row is corrected only while
+ // it has none: the sweep does adopt a DISCONNECTED row with a phone, and rewriting one of those
+ // would launch an engine that only renders a QR nobody asked for.
+ it('corrects every running status the takeover sweep adopts, and QR_READY only without a phone', 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' }));
+ ...[
+ SessionStatus.READY,
+ SessionStatus.INITIALIZING,
+ SessionStatus.AUTHENTICATING,
+ SessionStatus.ACTION_REQUIRED,
+ ].map(status => stranded({ id: status, status, phone: '628123' })),
+ stranded({ id: 'qr-unlinked', status: SessionStatus.QR_READY, phone: null }),
+ stranded({ id: 'qr-linked', status: SessionStatus.QR_READY, phone: '628123' }),
+ ];
const marked = await service.markLapsedDisconnected(rows, GONE_BEFORE);
@@ -2548,6 +2552,7 @@ describe('SessionService', () => {
SessionStatus.INITIALIZING,
SessionStatus.AUTHENTICATING,
SessionStatus.ACTION_REQUIRED,
+ 'qr-unlinked',
]);
});
@@ -2636,6 +2641,40 @@ describe('SessionService', () => {
expect(await statusOf(lapsedOnce.id)).toBe(SessionStatus.READY);
expect(await statusOf(gone.id)).toBe(SessionStatus.DISCONNECTED);
});
+
+ // The phone is read in the same snapshot, so it can be stale by the time the write lands: a
+ // pairing that completes in between must not be rewritten into a DISCONNECTED row with a phone,
+ // which is exactly what the sweep adopts.
+ it('writes a QR_READY row only while it still has no phone when the write lands', async () => {
+ const now = Date.now();
+ const seed = (name: string, status: SessionStatus, phone: string | null): Promise<Session> =>
+ sessions.save(
+ sessions.create({
+ name,
+ status,
+ phone,
+ config: {},
+ nodeId: 'dead-node',
+ leaseExpiresAt: new Date(now - 3 * TTL_MS),
+ }),
+ );
+ const pairing = await seed('pairing', SessionStatus.QR_READY, null);
+ const pairedMeanwhile = await seed('paired-meanwhile', SessionStatus.QR_READY, null);
+ const relinking = await seed('relinking', SessionStatus.QR_READY, '628123');
+ const linked = await seed('linked', SessionStatus.READY, '628456');
+ const snapshot = await sessions.find();
+
+ await sessions.update({ id: pairedMeanwhile.id }, { phone: '628789' });
+
+ const marked = await service.markLapsedDisconnected(snapshot, new Date(now - 2 * TTL_MS));
+
+ expect([...marked].sort()).toEqual([pairing.id, linked.id].sort());
+ const statusOf = async (id: string): Promise<SessionStatus> => (await sessions.findOneByOrFail({ id })).status;
+ expect(await statusOf(pairing.id)).toBe(SessionStatus.DISCONNECTED);
+ expect(await statusOf(pairedMeanwhile.id)).toBe(SessionStatus.QR_READY);
+ expect(await statusOf(relinking.id)).toBe(SessionStatus.QR_READY);
+ expect(await statusOf(linked.id)).toBe(SessionStatus.DISCONNECTED);
+ });
});
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index ee3ab5774..e4bdb420e 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -81,8 +81,9 @@ 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 the subset below 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 them for a row whose holder never came back, a
+ * QR_READY row only while it has no phone. FAILED and CREATED stay out of both: an operator has to
+ * see them.
*/
const ACTIVE_STATUSES = [
SessionStatus.READY,
@@ -92,16 +93,6 @@ 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
@@ -891,7 +882,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async markLapsedDisconnected(sessions: Session[], goneBefore: Date): Promise<string[]> {
const marked: string[] = [];
for (const session of sessions) {
- if (!LAPSED_CORRECTED_STATUSES.includes(session.status)) continue;
+ if (!ACTIVE_STATUSES.includes(session.status)) continue;
+ // A correction must never change what the takeover sweep adopts. It adopts every other active
+ // status anyway: AUTHENTICATING and ACTION_REQUIRED claim a running engine too, and whatever a
+ // human was asked to do lived in the engine that died with its node. It never adopts a row
+ // without a phone, but it does adopt a DISCONNECTED row with one, so rewriting a QR_READY row
+ // that has a phone would launch an engine that only renders a QR nobody asked for. QR_READY is
+ // therefore corrected only without a phone, re-checked in the write below in case a pairing
+ // completes in between.
+ const unlinkedOnly = session.status === SessionStatus.QR_READY;
+ if (unlinkedOnly && session.phone != null) 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 throws on a null or undefined where value, so a
// null here would fail this row's write instead of matching on it.
@@ -908,6 +908,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
nodeId: session.nodeId,
leaseExpiresAt: LessThan(goneBefore),
status: session.status,
+ ...(unlinkedOnly && { phone: IsNull() }),
},
{ status: SessionStatus.DISCONNECTED },
));
diff --git a/src/modules/takeover/session-takeover.service.ts b/src/modules/takeover/session-takeover.service.ts
index f5090b1e7..f392adfbf 100644
--- a/src/modules/takeover/session-takeover.service.ts
+++ b/src/modules/takeover/session-takeover.service.ts
@@ -15,9 +15,10 @@ import { BulkMessageService } from '../message/bulk-message.service';
* 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.
+ * DISCONNECTED is present, so the status correction must never write it over a row this sweep would
+ * otherwise leave alone: markLapsedDisconnected corrects READY, INITIALIZING, AUTHENTICATING and
+ * ACTION_REQUIRED, which are adopted either way, and QR_READY only on a row with no phone, which
+ * isEligible refuses either way.
*/
const TAKEOVER_STATUSES = new Set<SessionStatus>([
SessionStatus.READY,