Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): preserve ownership during cleanup
Yudhi Armyndharis5c0a5cc0cce7
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 4667f1dfc..8623613ce 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -712,9 +712,9 @@ No request body.Returned via `transformSession`; status typically becomes `disconnected`.-A stopped session stays down: boot auto-start (`AUTO_START_SESSIONS`) and the multi-node takeover sweep skip it until an explicit `POST /start`. The stop is recorded before the teardown, so a `502` stop keeps it too; a `409` refusal records nothing. Ownership is checked again in the stop write: if a live peer claimed the session after the initial check, the stop answers `409` without touching its engine or record. A stop that already passed the initial check can still replace a pending delete's record; a concurrent start then yields rather than clearing it.+A stopped session stays down: boot auto-start (`AUTO_START_SESSIONS`) and the multi-node takeover sweep skip it until an explicit `POST /start`. The stop is recorded before the teardown, so a `502` stop keeps it too; a `409` refusal records nothing. Ownership is checked again in the stop write: if a live peer claimed the session after the initial check, the stop answers `409` without touching its engine or record. A stop that already passed the initial check can still record its independent intent during a pending delete; a concurrent start then yields rather than clearing it.-An accepted stop on an expired or missing foreign lease clears that claim in the same write. If the former owner still runs, its next successful heartbeat detects lease loss and retires its engine. The stop response does not wait for that remote teardown.+An accepted stop on an expired or missing foreign lease clears that claim in the same write, except while a delete holds it. Repeated stops during a delete preserve every claim field so the deleting node can renew; an independent stop remains if that delete is refused. If the former owner still runs, its next successful heartbeat detects lease loss and retires its engine. The stop response does not wait for that remote teardown.**Errors:** `401` · `403` · `404` not found · `409` another node currently holds this session's live engine (multi-node deployments) · `502` `SESSION_STOP_INCOMPLETE` — session stopped locally but the engine teardown did not complete (retryable; the graceful disconnect and the force-destroy escalation both failed, status `disconnected`, no success audit)@@ -1290,9 +1290,11 @@ Delete a session.**Response** `204` — empty body (`@HttpCode(204)`, returns void). A `findOne` lookup runs first, so a missing id yields `404`.-The delete first removes the session's messages, webhook outbox rows and webhook delivery-failure records in batches (on SQLite up to 2000 rows, each sized to about 150 ms; 500 rows on PostgreSQL) that are not atomic with the rest: a failure part-way (a database error, a timeout, a restart) leaves the session in place with fewer rows and stopped, as `POST /stop` leaves it, and repeating the delete finishes it. It then removes, in one transaction, the session's message batches, chat states, received statuses, webhooks, templates, stored Baileys messages, automation rules, integration dead-letter rows and send idempotency claims together with the session itself, then purges its on-disk auth data. It keeps the audit log, the LID mappings, and the integration conversation mappings (so a re-paired session keeps its provider conversations); ingress dedup rows age out on their own after `INGRESS_DEDUP_RETENTION_DAYS` (default 7).+The delete holds its claim while it runs. Each destructive batch and the final transaction lock the session row and check its owner in that transaction. If another node takes over an expired claim, the old delete answers `409` before its next removal; earlier committed batches remain removed. That refusal preserves the newer owner's intent and engine. Hooks run outside these transactions.-**Errors:** `401` missing/invalid key · `403` key not scoped to this session, or key role below OPERATOR · `404` session not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; on a `409` the row is **not** deleted and no hook/auth-purge runs — retry after cleanup settles), or, on a multi-node deployment, another node currently holds this session's live engine (no `code`; nothing is deleted; send the delete to the owning node) · `503` the session could not be claimed for the delete because the database did not answer (nothing is deleted; retry), or, on SQLite, another database transaction stayed open for 10 s before the final transaction (the session stays, stopped, possibly with fewer rows; retry)+The delete first removes the session's messages, webhook outbox rows and webhook delivery-failure records in batches (on SQLite up to 2000 rows, each sized to about 150 ms; 500 rows on PostgreSQL) that are not atomic with the rest: a failure part-way (a database error, a timeout, a restart), while the delete still owns its claim, leaves the session in place with fewer rows and stopped, as `POST /stop` leaves it, and repeating the delete finishes it. It then removes, in one transaction, the session's message batches, chat states, received statuses, webhooks, templates, stored Baileys messages, automation rules, integration dead-letter rows and send idempotency claims together with the session itself, then purges its on-disk auth data. It keeps the audit log, the LID mappings, and the integration conversation mappings (so a re-paired session keeps its provider conversations); ingress dedup rows age out on their own after `INGRESS_DEDUP_RETENTION_DAYS` (default 7).++**Errors:** `401` missing/invalid key · `403` key not scoped to this session, or key role below OPERATOR · `404` session not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; on a `409` the row is **not** deleted and no hook/auth-purge runs — retry after cleanup settles), or, on a multi-node deployment, another node currently holds this session's live engine (no `code`; nothing is deleted; send the delete to the owning node), or ownership changed during removal (earlier batches may already be removed) · `503` the session could not be claimed for the delete because the database did not answer (nothing is deleted; retry), or, on SQLite, another database transaction stayed open for 10 s before a delete transaction (no further rows are removed; retry)### 6.4.2 Messagesdiff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.mdindex 400d14aab..3c91b17a6 100644--- a/docs/13-horizontal-scaling.md+++ b/docs/13-horizontal-scaling.md@@ -52,7 +52,14 @@> died with its node, is never adopted, even when its claim did lapse, until an explicit `POST /start`.> While versions are mixed during an upgrade, a node still on 0.25.0 does not read a `DELETE`'s record:> it can adopt such a session, and a `POST /start` it serves leaves the record in place.-> Older nodes also lack the final ownership check on a stop write, so they can still report a stop+> A stop during a delete preserves its claim, including repeated stops after its lease expires or+> becomes NULL. If another node takes over an expired claim, each later removal transaction checks+> the new owner and refuses the old delete. No transaction remains open across a hook.+> Adoption cleanup commits with its claim or expired-claim release, so delayed cleanup cannot fail+> a later owner's new batches. Older nodes do not preserve these delete holds, fence each removal+> transaction, or serialize adoption cleanup with ownership changes. Upgrade every+> node before relying on them; older backup importers also treat the combined delete/stop record+> as unknown. Older nodes also lack the final ownership check on a stop write, so they can still report a stop> as successful while a peer starts the session. Upgrade every node before relying on that fence.>> Known limitation: a holder that is alive but cannot reach the database for more than three leasediff --git a/openapi.json b/openapi.jsonindex 904ef08de..f93441757 100644--- a/openapi.json+++ b/openapi.json@@ -889,7 +889,7 @@}},"409": {- "description": "A credential teardown for the same session name is still in flight (retryable — the body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; wait for it to settle and retry), OR another node currently holds this session's live engine and deleting it here would strip a session the owner is running. No destructive side effect runs before either refusal.",+ "description": "A credential teardown for the same session name is still in flight (retryable: the body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; wait for it to settle and retry), OR another node currently holds this session's live engine and deleting it here would strip a session the owner is running, OR ownership changes while deletion runs. The first two refusals remove nothing. Ownership loss stops later deletion units; earlier batches may already be committed.","content": {"application/json": {"schema": {diff --git a/src/modules/infra/table-importers.spec.ts b/src/modules/infra/table-importers.spec.tsindex 0e5ffa2f3..3c13a7a6d 100644--- a/src/modules/infra/table-importers.spec.ts+++ b/src/modules/infra/table-importers.spec.ts@@ -39,6 +39,7 @@ describe('sessions table importer: desiredState', () => {expect(mapped({ desiredState: 'stopped' })[12]).toBe('stopped');// No delete runs for a restored row, so the record of one that failed part-way is a stop.expect(mapped({ desiredState: 'deleting' })[12]).toBe('stopped');+ expect(mapped({ desiredState: 'deleting-stopped' })[12]).toBe('stopped');});it('restores a row without the field, or with an unknown value, as eligible (NULL)', () => {diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex b77055c0e..46cd88791 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -168,7 +168,11 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [// A failed delete's 'deleting' restores as 'stopped': no delete runs for the restored row. A// backup written before the column existed, or an unknown value, restores as NULL: eligible for// auto-start and takeover, as before.- session.desiredState === 'stopped' || session.desiredState === 'deleting' ? 'stopped' : null,+ session.desiredState === 'stopped' ||+ session.desiredState === 'deleting' ||+ session.desiredState === 'deleting-stopped'+ ? 'stopped'+ : null,],}),diff --git a/src/modules/message/batch-media.util.ts b/src/modules/message/batch-media.util.tsindex 671d72779..20d00e19a 100644--- a/src/modules/message/batch-media.util.ts+++ b/src/modules/message/batch-media.util.ts@@ -23,7 +23,10 @@ export function stripBatchMediaPayloads(messages: MessageBatch['messages']): voi* captured a scope before the close stops at its next item without recording anything, and nothing else moves* its row on while this process lives. The boot reaper gets any row this misses on the next start.*/-export async function failUnfinishedSessionBatches(dataSource: DataSource, sessionId: string): Promise<void> {+export async function failUnfinishedSessionBatches(+ dataSource: Pick<DataSource, 'getRepository'>,+ sessionId: string,+): Promise<void> {const batches = dataSource.getRepository(MessageBatch);const unfinished = await batches.find({where: { sessionId, status: In([BatchStatus.PENDING, BatchStatus.PROCESSING]) },diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 64f37d787..2cab0acb8 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -15,7 +15,7 @@ import { ShutdownService } from '../../common/services/shutdown.service';import { ConfigService } from '@nestjs/config';import { captureSessionWrites, SessionWriteScope } from '../../common/utils/session-write-scope';import { InjectRepository } from '@nestjs/typeorm';-import { In, IsNull, Not, QueryDeepPartialEntity, Repository } from 'typeorm';+import { In, IsNull, Not, QueryDeepPartialEntity, Repository, EntityManager } from 'typeorm';import { createHash, randomUUID } from 'crypto';import { setTimeout } from 'node:timers/promises';import {@@ -155,7 +155,10 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,* Registered here, before any bootstrap hook can start a session.*/onModuleInit(): void {- this.ownership?.onAdoption(sessionId => this.reapProcessingBatches(sessionId, 'session taken from a lapsed node'));+ this.ownership?.onAdoption(+ (sessionId, manager) => this.reapProcessingBatches(sessionId, 'session taken from a lapsed node', manager),+ true,+ );}/**@@ -223,6 +226,7 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,private async failOrphanedBatch(batch: Pick<MessageBatch, 'id'> & Partial<MessageBatch>,withRunState = false,+ repository = this.batchRepository,): Promise<boolean> {const set: QueryDeepPartialEntity<MessageBatch> = { status: BatchStatus.FAILED, completedAt: new Date() };if (batch.messages) {@@ -234,7 +238,7 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,if (batch.results) set.results = batch.results;if (batch.currentIndex !== undefined) set.currentIndex = batch.currentIndex;}- const failed = await this.batchRepository.update(+ const failed = await repository.update({ id: batch.id, status: In([BatchStatus.PENDING, BatchStatus.PROCESSING]) },set,);@@ -253,15 +257,16 @@ export class BulkMessageService implements OnModuleInit, OnApplicationBootstrap,* the session before or still runs a stale engine for it: createBatch registers every batch before* its row is written, so only the lapsed node's batches go.*/- async reapProcessingBatches(sessionId: string, reason: string): Promise<number> {+ async reapProcessingBatches(sessionId: string, reason: string, manager?: EntityManager): Promise<number> {+ const repository = manager?.getRepository(MessageBatch) ?? this.batchRepository;const unfinished = (- await this.batchRepository.find({+ await repository.find({where: { status: In([BatchStatus.PENDING, BatchStatus.PROCESSING]), sessionId },})).filter(batch => !this.processingBatches.has(batch.id));let failed = 0;for (const batch of unfinished) {- if (await this.failOrphanedBatch(batch)) failed++;+ if (await this.failOrphanedBatch(batch, false, repository)) failed++;}if (failed > 0) {this.logger.warn(`Marked ${failed} unfinished batch(es) FAILED for session ${sessionId} (${reason})`);diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.tsindex c970999f1..1a51d812d 100644--- a/src/modules/session/entities/session.entity.ts+++ b/src/modules/session/entities/session.entity.ts@@ -84,12 +84,13 @@ export class Session {/*** Operator intent, server-owned and not part of any session response (only the export-data* backup carries it): 'stopped' once POST /stop or POST /force-kill took the session down, and- * 'deleting' while a DELETE runs (kept if it fails part-way), both cleared again by an explicit- * POST /start. Boot auto-start and takeover skip a row holding either, so a deliberate stop+ * 'deleting' while a DELETE runs (kept if it fails part-way), or 'deleting-stopped' when an+ * independent stop also stands during that delete. All are cleared by an explicit+ * POST /start. Boot auto-start and takeover skip a row holding any of them, so a deliberate stop* survives a restart. NULL (every row that predates the column) means eligible, as before.*/@Column({ type: 'varchar', length: 20, nullable: true })- desiredState!: 'stopped' | 'deleting' | null;+ desiredState!: 'stopped' | 'deleting' | 'deleting-stopped' | null;@CreateDateColumn()createdAt!: Date;diff --git a/src/modules/session/session-content-lifetime.spec.ts b/src/modules/session/session-content-lifetime.spec.tsindex a2647b683..668a211f6 100644--- a/src/modules/session/session-content-lifetime.spec.ts+++ b/src/modules/session/session-content-lifetime.spec.ts@@ -1,7 +1,7 @@import { ConflictException, ServiceUnavailableException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { randomUUID } from 'crypto';-import { DataSource, QueryRunner } from 'typeorm';+import { DataSource, EntityManager, QueryRunner, Repository } from 'typeorm';import { Session } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { BatchStatus, MessageBatch } from '../message/entities/message-batch.entity';@@ -415,9 +415,7 @@ describe('Session content lifetime', () => {};await seed(doomed.id, count);await seed(kept.id, 3);- const deleteMessages = jest.spyOn(messages, 'delete');- const deleteOutbox = jest.spyOn(outbox, 'delete');- const deleteFailures = jest.spyOn(failures, 'delete');+ const deletes = jest.spyOn(Repository.prototype, 'delete');await controls.delete(doomed.id);@@ -431,9 +429,12 @@ describe('Session content lifetime', () => {// Three statements per table instead of one that holds the table for every row at once, each by// primary key alone: a sessionId condition beside the id list makes the database walk the session's// remaining rows on every batch.- for (const spy of [deleteMessages, deleteOutbox, deleteFailures]) {- expect(spy).toHaveBeenCalledTimes(3);- for (const [criteria] of spy.mock.calls) expect(Object.keys(criteria as object)).toEqual(['id']);+ for (const target of [Message, WebhookOutboxEvent, WebhookDeliveryFailure]) {+ const calls = deletes.mock.calls.filter(+ (_, index) => (deletes.mock.contexts[index] as Repository<Session>).target === target,+ );+ expect(calls).toHaveLength(3);+ for (const [criteria] of calls) expect(Object.keys(criteria as object)).toEqual(['id']);}}, 60000);@@ -483,7 +484,7 @@ describe('Session content lifetime', () => {await seed(kept.id, 3);const outboxReads = jest.spyOn(outbox, 'find');const failureReads = jest.spyOn(failures, 'find');- jest.spyOn(db, 'transaction').mockRejectedValue(new Error('closing transaction not under test'));+ jest.spyOn(EntityManager.prototype, 'remove').mockRejectedValue(new Error('closing transaction not under test'));await expect(controls.delete(doomed.id)).rejects.toThrow('closing transaction not under test');@@ -538,12 +539,14 @@ describe('Session content lifetime', () => {]),);const pages: string[][] = [];- jest.spyOn(messages, 'delete').mockImplementation(criteria => {+ const remove = Reflect.get(Repository.prototype, 'delete') as Repository<Message>['delete'];+ jest.spyOn(Repository.prototype, 'delete').mockImplementation(function (this: Repository<Message>, criteria) {+ if (this.target !== Message) return remove.call(this, criteria);if (pages.length >= 20) throw new Error('the pages are not advancing');pages.push((criteria as unknown as { id: { value: string[] } }).id.value.slice());return Promise.resolve({ raw: [], affected: 0 });});- jest.spyOn(db, 'transaction').mockRejectedValue(new Error('closing transaction not under test'));+ jest.spyOn(EntityManager.prototype, 'remove').mockRejectedValue(new Error('closing transaction not under test'));await expect(controls.delete(doomed.id)).rejects.toThrow('closing transaction not under test');@@ -611,16 +614,17 @@ describe('Session content lifetime', () => {})),);}- const remove = messages.delete.bind(messages);+ const remove = Reflect.get(Repository.prototype, 'delete') as Repository<Message>['delete'];let turnRan = true;const turnsBeforeStatement: boolean[] = [];- jest.spyOn(messages, 'delete').mockImplementation(criteria => {+ jest.spyOn(Repository.prototype, 'delete').mockImplementation(function (this: Repository<Message>, criteria) {+ if (this.target !== Message) return remove.call(this, criteria);turnsBeforeStatement.push(turnRan);turnRan = false;setImmediate(() => {turnRan = true;});- return remove(criteria);+ return remove.call(this, criteria);});await controls.delete(doomed.id);@@ -709,7 +713,11 @@ describe('Session content lifetime', () => {const session = await createSession();await seedBatch(session.id, BatchStatus.PROCESSING, 'b-processing');jest.spyOn(db, 'transaction').mockRejectedValueOnce(new Error('canceling statement due to statement timeout'));- jest.spyOn(db.getRepository(MessageBatch), 'find').mockRejectedValue(new Error('connection lost'));+ const find = Reflect.get(Repository.prototype, 'find') as Repository<MessageBatch>['find'];+ jest.spyOn(Repository.prototype, 'find').mockImplementation(function (this: Repository<MessageBatch>, options) {+ if (this.target === MessageBatch) return Promise.reject(new Error('connection lost'));+ return find.call(this, options);+ });await expect(controls.delete(session.id)).rejects.toThrow('statement timeout');@@ -842,8 +850,11 @@ describe('Session content lifetime', () => {expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, batches: 1 });expect(logger.warn).toHaveBeenCalledWith(- expect.stringContaining('inside another open transaction'),- expect.objectContaining({ action: 'session_delete_foreign_transaction_open' }),+ expect.stringContaining('Could not fail the unfinished batches'),+ expect.objectContaining({+ action: 'session_delete_batch_fail_failed',+ error: expect.stringContaining('another database transaction stayed open') as unknown,+ }),);},);diff --git a/src/modules/session/session-delete-claim.spec.ts b/src/modules/session/session-delete-claim.spec.tsindex a63dca889..e2bc84bbb 100644--- a/src/modules/session/session-delete-claim.spec.ts+++ b/src/modules/session/session-delete-claim.spec.ts@@ -6,7 +6,7 @@ import { randomUUID } from 'crypto';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { DataSource, DataSourceOptions } from 'typeorm';+import { DataSource, DataSourceOptions, EntityManager, Repository } from 'typeorm';import { postgresUtcExtra } from '../../database/postgres-utc';import { SessionService } from './session.service';import { SessionEngineLifecycle } from './session-engine-lifecycle.service';@@ -18,8 +18,10 @@ import { SessionLifecycleFences } from './session-lifecycle-fences';import { SessionStoppedException } from './session-engine-controls';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';-import { MessageBatch } from '../message/entities/message-batch.entity';+import { BulkMessageService } from '../message/bulk-message.service';+import { BatchStatus, MessageBatch } from '../message/entities/message-batch.entity';import { SendIdempotencyKey } from '../message/entities/send-idempotency-key.entity';+import { WebhookOutboxService } from '../webhook/webhook-outbox.service';import { Webhook } from '../webhook/entities/webhook.entity';import { WebhookOutboxEvent } from '../webhook/entities/webhook-outbox-event.entity';import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';@@ -418,7 +420,10 @@ describe('A session deleted on one node while a peer shares the database', () =>await clearing.promise;stopGo.resolve();await stopping;- expect(await sessions.findOneByOrFail({ id })).toMatchObject({ nodeId: 'node-a', desiredState: 'stopped' });+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-a',+ desiredState: 'deleting-stopped',+ });clearGo.resolve();expect(await starting).toBeInstanceOf(SessionStoppedException);@@ -1167,7 +1172,11 @@ describe('A session deleted on one node while a peer shares the database', () =>it('refuses the delete and takes nothing down when it cannot record the stop', async () => {const id = await seed({ status: SessionStatus.DISCONNECTED });await a.service.start(id, { explicit: true });- jest.spyOn(a.db.getRepository(Session), 'update').mockRejectedValueOnce(new Error('connection reset'));+ const update = Reflect.get(Repository.prototype, 'update') as Repository<Session>['update'];+ jest.spyOn(Repository.prototype, 'update').mockImplementation(function (this: Repository<Session>, where, patch) {+ if ((patch as { desiredState?: unknown }).desiredState) return Promise.reject(new Error('connection reset'));+ return update.call(this, where, patch);+ });await expect(a.service.delete(id)).rejects.toThrow('connection reset');@@ -1188,7 +1197,10 @@ describe('A session deleted on one node while a peer shares the database', () =>const sessions = a.db.getRepository(Session);const update = sessions.update.bind(sessions);// The stop is recorded; taking it back fails.- jest.spyOn(sessions, 'update').mockImplementationOnce(update).mockRejectedValueOnce(new Error('connection reset'));+ jest.spyOn(sessions, 'update').mockImplementation((where, patch) => {+ if (patch.desiredState === null) return Promise.reject(new Error('connection reset'));+ return update(where, patch);+ });await expect(a.service.delete(id)).rejects.toBeInstanceOf(ConflictException);@@ -1801,7 +1813,7 @@ describe('A session deleted on one node while a peer shares the database', () =>const starting = a.service.start(id, { explicit: true });await failed.promise;// The batches run, then the closing transaction fails: the session stays, with fewer rows.- jest.spyOn(a.db, 'transaction').mockRejectedValueOnce(new Error('transaction timed out'));+ jest.spyOn(EntityManager.prototype, 'remove').mockRejectedValueOnce(new Error('transaction timed out'));await expect(a.service.delete(id)).rejects.toThrow('transaction timed out');await expect(starting).rejects.toBeInstanceOf(SessionStoppedException);@@ -1822,7 +1834,7 @@ describe('A session deleted on one node while a peer shares the database', () =>});const starting = a.service.start(id, { explicit: true });await fenced.promise;- jest.spyOn(a.db, 'transaction').mockRejectedValueOnce(new Error('transaction timed out'));+ jest.spyOn(EntityManager.prototype, 'remove').mockRejectedValueOnce(new Error('transaction timed out'));await expect(a.service.delete(id)).rejects.toThrow('transaction timed out');go.resolve();@@ -1868,7 +1880,7 @@ describe('A session deleted on one node while a peer shares the database', () =>// and starts the session the operator was deleting.it('hands the claim back when the delete fails after claiming', async () => {const id = await seed({ status: SessionStatus.READY, phone: '628111111111' });- jest.spyOn(a.db, 'transaction').mockRejectedValueOnce(new Error('transaction timed out'));+ jest.spyOn(EntityManager.prototype, 'remove').mockRejectedValueOnce(new Error('transaction timed out'));await expect(a.service.delete(id)).rejects.toThrow('transaction timed out');@@ -1888,4 +1900,1774 @@ describe('A session deleted on one node while a peer shares the database', () =>expect(leftovers(id)).toEqual({ stopMark: false, stopCount: false });expect(a.ownership.ownedIds()).toEqual([]);});++ it.each([+ [null, false],+ ['stopped', false],+ [null, true],+ ['stopped', true],+ ] as const)(+ 'keeps a delete claim after repeated stops with a missing lease, state %s and local first stop %s',+ async (desiredState, localFirst) => {+ const id = await seed({ status: SessionStatus.DISCONNECTED, desiredState });+ await startHeldDelete(id);+ const sessions = a.db.getRepository(Session);+ await sessions.update(id, { leaseExpiresAt: null, nodeUrl: 'http://127.0.0.1:59651' });+ const before = await sessions.findOneByOrFail({ id });+ for (let i = 0; i < 2; i++) {+ await (localFirst && i === 0 ? a : b).service.stop(id);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: null,+ nodeUrl: before.nodeUrl,+ });+ }+ await a.ownership.renew();+ const renewed = await sessions.findOneByOrFail({ id });+ expect(renewed.nodeId).toBe('node-a');+ expect(renewed.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now());+ await expect(b.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ expect(b.service.getEngine(id)).toBeUndefined();+ finish!();+ await deletion;+ expect(await rowsOf(id)).toEqual(gone);+ },+ );++ it('keeps every delete claim field when a delayed peer stop resumes after expiry', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const checked = deferred();+ const go = deferred();+ const held = b.ownership.isHeldByOtherNode.bind(b.ownership);+ jest.spyOn(b.ownership, 'isHeldByOtherNode').mockImplementationOnce(async next => {+ const answer = await held(next);+ checked.resolve();+ await go.promise;+ return answer;+ });+ const stopping = b.service.stop(id);+ await checked.promise;+ await startHeldDelete(id);+ const sessions = a.db.getRepository(Session);+ await sessions.update(id, { leaseExpiresAt: lapsed(), nodeUrl: 'http://127.0.0.1:59651' });+ const before = await sessions.findOneByOrFail({ id });+ try {+ go.resolve();+ await stopping;+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ });+ await a.ownership.renew();+ await expect(b.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ expect(b.service.getEngine(id)).toBeUndefined();+ } finally {+ go.resolve();+ await stopping;+ }+ });++ it.each([+ ['hook', false],+ ['batch', false],+ ['final transaction', false],+ ['hook', true],+ ] as const)('stops deleting after ownership changes at the %s with expired peer %s', async (phase, expiredPeer) => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const messages = a.db.getRepository(Message);+ const batch = await a.db.getRepository(MessageBatch).save({+ sessionId: id,+ batchId: randomUUID(),+ status: BatchStatus.PROCESSING,+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'kept' } }],+ });+ if (phase === 'batch') {+ await messages.insert(+ Array.from({ length: 500 }, () => ({+ sessionId: id,+ chatId: '[email protected]',+ from: 'me',+ to: '[email protected]',+ body: 'kept',+ })),+ );+ }+ if (phase === 'final transaction') await messages.delete({ sessionId: id });+ const transaction = a.db.transaction.bind(a.db);+ let transactions = 0;+ let remaining = 0;+ const adopt = async (): Promise<void> => {+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ remaining = await messages.countBy({ sessionId: id });+ };+ const reached = deferred();+ const release = deferred();+ a.hooks.execute.mockImplementation(async (event: string, data: unknown) => {+ if (event === 'session:deleted') {+ reached.resolve();+ await release.promise;+ }+ return { continue: true, data };+ });+ finish = release.resolve;+ const outcome = a.service.delete(id).catch((error: unknown) => error);+ deletion = outcome.then(() => undefined);+ await reached.promise;+ if (phase !== 'hook') {+ jest.spyOn(a.db, 'transaction').mockImplementation(async (...args: Parameters<typeof transaction>) => {+ transactions++;+ if ((phase === 'batch' && transactions === 2) || (phase === 'final transaction' && transactions === 1)) {+ await adopt();+ }+ return transaction(...args);+ });+ }+ if (phase === 'hook') await adopt();+ if (expiredPeer) await sessions.update(id, { leaseExpiresAt: lapsed() });+ release.resolve();+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await messages.countBy({ sessionId: id })).toBe(remaining);+ expect(await a.db.getRepository(MessageBatch).findOneByOrFail({ id: batch.id })).toMatchObject({+ status: BatchStatus.PROCESSING,+ messages: batch.messages,+ });+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({ nodeId: 'node-b', desiredState: null });+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ expect(a.purge).not.toHaveBeenCalled();+ });++ it.each(['retirement read', 'final read'] as const)(+ 'keeps a healthy reconnect when the top-level start %s returns a stale snapshot',+ async phase => {+ const id = await seed({ status: SessionStatus.DISCONNECTED, config: { reconnectBaseDelay: 1000 } });+ const sessions = a.db.getRepository(Session);+ const findOne = sessions.findOne.bind(sessions);+ const reached = deferred();+ const go = deferred();+ let reads = 0;+ jest.spyOn(sessions, 'findOne').mockImplementation(async options => {+ reads += 1;+ if (phase === 'final read' && reads === 3) throw new Error('connection reset');+ if (reads !== (phase === 'retirement read' ? 3 : 4)) return findOne(options);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const snapshot = phase === 'retirement read' ? await findOne(options) : null;+ reached.resolve();+ await go.promise;+ return snapshot;+ });+ type Reconnector = { executeReconnect(id: string, session: Session, state: unknown): Promise<void> };+ const reconnect = (a.lifecycle as unknown as Reconnector).executeReconnect.bind(a.lifecycle);+ let reconnected: Promise<void> | undefined;+ const launched = deferred();+ jest.spyOn(a.lifecycle as unknown as Reconnector, 'executeReconnect').mockImplementation((...args) => {+ reconnected = reconnect(...args);+ launched.resolve();+ return reconnected;+ });+ const starting = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ try {+ await reached.promise;+ await a.ownership.renew();+ await a.lifecycle.handleEngineDisconnected(id, a.engines[0] as never, 'NETWORK');+ await launched.promise;+ await reconnected;+ const replacement = a.engines[1];+ expect(a.service.getEngine(id)).toBe(replacement);+ go.resolve();+ const result = await starting;+ if (phase === 'final read') expect(result).toBeInstanceOf(NotFoundException);+ else expect(result).not.toBeInstanceOf(Error);+ expect(a.service.getEngine(id)).toBe(replacement);+ expect(replacement.destroy).not.toHaveBeenCalled();+ expect(replacement.forceDestroy).not.toHaveBeenCalled();+ expect(a.engines[0].destroy).toHaveBeenCalledTimes(1);+ } finally {+ go.resolve();+ await starting;+ }+ },+ );++ it.each(+ (pg+ ? [+ ['before release', false],+ ['before release', true],+ ['owner row', false],+ ['owner row', true],+ ]+ : [+ ['before release', false],+ ['before release', true],+ ]) as Array<[string, boolean]>,+ )('keeps a later local start when delete cleanup waits at %s with pending claim %s', async (phase, pending) => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const reached = deferred();+ const go = deferred();+ const claimed = deferred();+ const answer = deferred();+ const release = a.ownership.release.bind(a.ownership);+ const transaction = a.db.transaction.bind(a.db);+ a.hooks.execute.mockRejectedValueOnce(new Error('hook unavailable'));+ jest.spyOn(a.ownership, 'release').mockImplementationOnce(async (...args) => {+ if (phase === 'before release') {+ reached.resolve();+ await go.promise;+ } else {+ jest.spyOn(a.db, 'transaction').mockImplementationOnce((async (+ run: (manager: import('typeorm').EntityManager) => Promise<void>,+ ) =>+ transaction(async manager => {+ const builder = manager.createQueryBuilder.bind(manager);+ jest.spyOn(manager, 'createQueryBuilder').mockImplementation((() => {+ const query = builder();+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation((() => {+ const updated = update(Session);+ const execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ reached.resolve();+ await go.promise;+ return execute();+ });+ return updated;+ }) as typeof query.update);+ return query;+ }) as typeof manager.createQueryBuilder);+ return run(manager);+ })) as typeof transaction);+ }+ return release(...args);+ });+ const outcome = a.service.delete(id).catch((error: unknown) => error);+ deletion = outcome.then(() => undefined);+ await reached.promise;+ const original = await sessions.findOneByOrFail({ id });+ if (pending) {+ const claim = a.ownership.claim.bind(a.ownership);+ jest.spyOn(a.ownership, 'claim').mockImplementationOnce(async next => {+ const result = await claim(next);+ claimed.resolve();+ await answer.promise;+ return result;+ });+ }+ const starting = a.service.start(id, { explicit: true });+ try {+ if (pending) await claimed.promise;+ else await starting;+ go.resolve();+ expect(await outcome).toBeInstanceOf(Error);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-a',+ claimedAt: original.claimedAt,+ });+ answer.resolve();+ await starting;+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect((await sessions.findOneByOrFail({ id })).desiredState).toBeNull();+ await a.ownership.renew();+ expect((await sessions.findOneByOrFail({ id })).nodeId).toBe('node-a');+ } finally {+ go.resolve();+ answer.resolve();+ await starting;+ }+ });++ (pg ? it : it.skip)('holds the owner row for each delete batch while other sessions can start', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const otherId = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const messages = a.db.getRepository(Message);+ await messages.insert(+ Array.from({ length: 500 }, () => ({+ sessionId: id,+ chatId: '[email protected]',+ from: 'me',+ to: '[email protected]',+ body: 'kept',+ })),+ );+ await startHeldDelete(id);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const reached = deferred();+ const go = deferred();+ const transaction = a.db.transaction.bind(a.db);+ let first = true;+ jest.spyOn(a.db, 'transaction').mockImplementation((async (+ run: (manager: import('typeorm').EntityManager) => Promise<void>,+ ) => {+ const hold = first;+ first = false;+ const result = await transaction(async manager => {+ if (hold) {+ const getRepository = manager.getRepository.bind(manager);+ jest.spyOn(manager, 'getRepository').mockImplementation(target => {+ const repository = getRepository(target);+ if (target === Message) {+ const remove = repository.delete.bind(repository);+ jest.spyOn(repository, 'delete').mockImplementationOnce(async where => {+ reached.resolve();+ await go.promise;+ return remove(where);+ });+ }+ return repository;+ });+ }+ return run(manager);+ });+ if (hold) await claiming;+ return result;+ }) as typeof transaction);+ const outcome = deletion!.catch((error: unknown) => error);+ finish!();+ await reached.promise;+ let claimed = false;+ const claiming = b.ownership.claim(id).then(result => {+ claimed = result;+ return result;+ });+ try {+ let waiting = false;+ for (let i = 0; i < 100; i++) {+ const rows = await b.db.query<Array<{ waiting: boolean }>>(+ 'SELECT true AS waiting FROM pg_stat_activity WHERE wait_event_type = $1 AND query LIKE $2',+ ['Lock', `%${(options as { schema: string }).schema}%`],+ );+ if (rows.length) {+ waiting = true;+ break;+ }+ if (claimed) break;+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ expect(waiting).toBe(true);+ expect(claimed).toBe(false);+ await b.service.start(otherId, { explicit: true });+ expect(b.service.getEngine(otherId)).toBe(b.engines[0]);+ go.resolve();+ expect(await claiming).toBe(true);+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await messages.countBy({ sessionId: id })).toBe(1);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({ nodeId: 'node-b' });+ } finally {+ go.resolve();+ await claiming;+ await outcome;+ }+ });++ it.each(['deleting', 'deleting-stopped'] as const)(+ 'does not clear an expired foreign %s claim through the stop helper',+ async desiredState => {+ const id = await seed({ status: SessionStatus.DISCONNECTED, desiredState });+ await a.ownership.claim(id);+ const sessions = a.db.getRepository(Session);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const before = await sessions.findOneByOrFail({ id });+ expect(await b.ownership.stopExpiredForeignClaim(id)).toBe(false);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ desiredState,+ });+ },+ );++ it('leaves a later owner delete hold untouched when an older delete returns', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const first = deletion!.catch((error: unknown) => error);+ const sessions = a.db.getRepository(Session);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const reached = deferred();+ const go = deferred();+ b.hooks.execute.mockImplementation(async (event: string, data: unknown) => {+ if (event === 'session:deleted') {+ reached.resolve();+ await go.promise;+ }+ return { continue: true, data };+ });+ const second = b.service.delete(id);+ try {+ await reached.promise;+ await b.service.stop(id);+ finish!();+ expect(await first).toBeInstanceOf(ConflictException);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-b',+ desiredState: 'deleting-stopped',+ });+ await b.ownership.renew();+ expect((await sessions.findOneByOrFail({ id })).leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now());+ } finally {+ go.resolve();+ await second;+ }+ });++ it.each(['retirement read', 'initialization failure'] as const)(+ 'keeps a reconnect awaiting teardown when the old start returns from its %s',+ async phase => {+ const id = await seed({ status: SessionStatus.DISCONNECTED, config: { reconnectBaseDelay: 1000 } });+ const reached = deferred();+ const go = deferred();+ let failInit!: (error: Error) => void;+ const initialization = new Promise<void>((_resolve, reject) => {+ failInit = reject;+ });+ if (phase === 'retirement read') {+ const sessions = a.db.getRepository(Session);+ const findOne = sessions.findOne.bind(sessions);+ let reads = 0;+ jest.spyOn(sessions, 'findOne').mockImplementation(async options => {+ if (++reads !== 3) return findOne(options);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const snapshot = await findOne(options);+ reached.resolve();+ await go.promise;+ return snapshot;+ });+ } else {+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const register = registry.set.bind(registry);+ jest.spyOn(registry, 'set').mockImplementationOnce((next, engine) => {+ (engine as unknown as FakeEngine).initialize.mockImplementation(() => {+ reached.resolve();+ return initialization;+ });+ return register(next, engine);+ });+ }+ type Reconnector = { executeReconnect(id: string, session: Session, state: unknown): Promise<void> };+ const reconnect = (a.lifecycle as unknown as Reconnector).executeReconnect.bind(a.lifecycle);+ let reconnected: Promise<void> | undefined;+ jest.spyOn(a.lifecycle as unknown as Reconnector, 'executeReconnect').mockImplementation((...args) => {+ reconnected = reconnect(...args);+ return reconnected;+ });+ const starting = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ await reached.promise;+ await a.ownership.renew();+ const fenced = deferred();+ const resume = deferred();+ jest.spyOn(SessionLifecycleFences.prototype, 'awaitPendingTeardown').mockImplementationOnce(async () => {+ fenced.resolve();+ await resume.promise;+ });+ await a.lifecycle.handleEngineDisconnected(id, a.engines[0] as never, 'NETWORK');+ await fenced.promise;+ try {+ go.resolve();+ if (phase === 'initialization failure') failInit(new Error('invalid auth'));+ await starting;+ expect(a.service.getEngine(id)).toBeUndefined();+ expect(a.lifecycle.isEngineActive(id)).toBe(true);+ resume.resolve();+ await reconnected;+ expect(a.service.getEngine(id)).toBe(a.engines[1]);+ expect(a.engines).toHaveLength(2);+ expect((await a.db.getRepository(Session).findOneByOrFail({ id })).nodeId).toBe('node-a');+ await expect(b.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ } finally {+ go.resolve();+ resume.resolve();+ if (phase === 'initialization failure') failInit(new Error('invalid auth'));+ await starting;+ await reconnected;+ }+ },+ );++ it.each([+ ['delete', false, false, true],+ ['delete', true, false, true],+ ['start', false, false, true],+ ['start', true, false, true],+ ['delete', false, true, true],+ ['start', false, true, true],+ ['delete', false, false, false],+ ] as const)(+ 'handles an older %s claim SQL reply with frozen clock %s, failed reply %s and ownership loss %s',+ async (operation, frozen, failedReply, loss) => {+ if (frozen) {+ jest.useFakeTimers({+ doNotFake: [+ 'nextTick',+ 'setImmediate',+ 'queueMicrotask',+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'performance',+ ],+ });+ jest.setSystemTime(new Date('2026-06-01T12:00:00Z'));+ }+ const written = deferred();+ const answer = deferred();+ try {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const builder = sessions.createQueryBuilder.bind(sessions);+ let holdClaim = true;+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementation(() => {+ const query = builder();+ if (!holdClaim) return query;+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ holdClaim = false;+ const updated = update(Session);+ const execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ const result = await execute();+ written.resolve();+ await answer.promise;+ if (failedReply) throw new Error('claim reply unavailable');+ return result;+ });+ return updated;+ });+ return query;+ });+ const outcome = (operation === 'delete' ? a.service.delete(id) : a.service.start(id, { explicit: true })).catch(+ (error: unknown) => error,+ );+ deletion = outcome.then(() => undefined);+ await written.promise;+ if (loss) {+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ }+ if (operation === 'delete') {+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(SessionStoppedException);+ } else {+ await a.service.start(id, { explicit: true });+ }+ const before = await sessions.findOneByOrFail({ id });+ const ownsNewClaim = a.ownership.captureClaim(id);+ answer.resolve();+ if (!loss) {+ expect(await outcome).toBeUndefined();+ expect(await rowsOf(id)).toEqual(gone);+ return;+ }+ expect(await outcome).toBeInstanceOf(failedReply ? Error : ConflictException);+ expect(ownsNewClaim()).toBe(true);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ desiredState: before.desiredState,+ });+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ if (operation === 'start') expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect(a.purge).not.toHaveBeenCalled();+ } finally {+ answer.resolve();+ await deletion;+ jest.useRealTimers();+ }+ },+ );++ it.each([false, true])(+ 'does not resume an older delete after this node reclaims a peer claim with frozen clock %s',+ async frozen => {+ if (frozen) {+ jest.useFakeTimers({+ doNotFake: [+ 'nextTick',+ 'setImmediate',+ 'queueMicrotask',+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'performance',+ ],+ });+ jest.setSystemTime(new Date('2026-06-01T12:00:00Z'));+ }+ try {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const outcome = deletion!.catch((error: unknown) => error);+ const sessions = a.db.getRepository(Session);+ const original = await sessions.findOneByOrFail({ id });+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(SessionStoppedException);+ const reclaimed = await sessions.findOneByOrFail({ id });+ expect(reclaimed.nodeId).toBe('node-a');+ if (frozen) expect(reclaimed.claimedAt).toEqual(original.claimedAt);+ finish!();+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-a',+ claimedAt: reclaimed.claimedAt,+ });+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ expect(a.purge).not.toHaveBeenCalled();+ } finally {+ jest.useRealTimers();+ }+ },+ );++ it.each([+ [false, false],+ [true, false],+ [false, true],+ [true, true],+ ] as const)(+ 'keeps a newer owner after a delayed delete claim with local reacquisition %s and existing claim %s',+ async (local, owned) => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ if (owned) await a.ownership.claim(id);+ const sessions = a.db.getRepository(Session);+ const reached = deferred();+ const go = deferred();+ const claim = a.ownership.claim.bind(a.ownership);+ jest.spyOn(a.ownership, 'claim').mockImplementationOnce(async (...args) => {+ const result = await claim(...args);+ reached.resolve();+ await go.promise;+ return result;+ });+ const outcome = a.service.delete(id).catch((error: unknown) => error);+ deletion = outcome.then(() => undefined);+ try {+ await reached.promise;+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ if (local) {+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(SessionStoppedException);+ }+ const before = await sessions.findOneByOrFail({ id });+ go.resolve();+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ desiredState: before.desiredState,+ });+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ expect(a.purge).not.toHaveBeenCalled();+ } finally {+ go.resolve();+ await outcome;+ }+ },+ );++ it.each([false, true])(+ 'retries a delete after its initial intent transaction fails with a local engine %s',+ async active => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ if (active) await a.service.start(id, { explicit: true });+ a.hooks.execute.mockClear();+ const sessions = a.db.getRepository(Session);+ const before = await sessions.findOneByOrFail({ id });+ jest.spyOn(a.db, 'transaction').mockRejectedValueOnce(new Error('intent transaction unavailable'));+ await expect(a.service.delete(id)).rejects.toThrow('intent transaction unavailable');+ const after = await sessions.findOneByOrFail({ id });+ expect(after.status).toBe(before.status);+ expect(after.desiredState).toBeNull();+ expect(after.nodeId).toBe(active ? 'node-a' : null);+ if (active) {+ expect(after.claimedAt).toEqual(before.claimedAt);+ expect(after.nodeUrl).toEqual(before.nodeUrl);+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ }+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ expect(a.hooks.execute).not.toHaveBeenCalled();+ expect(a.purge).not.toHaveBeenCalled();+ await a.service.delete(id);+ expect(await rowsOf(id)).toEqual(gone);+ },+ );++ it('keeps the same claim when a local start is refused during its delete', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const sessions = a.db.getRepository(Session);+ const before = await sessions.findOneByOrFail({ id });+ await new Promise(resolve => setTimeout(resolve, 5));+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(SessionStoppedException);+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ nodeUrl: before.nodeUrl,+ });+ finish!();+ await deletion;+ expect(await rowsOf(id)).toEqual(gone);+ });++ (pg ? it : it.skip)('rechecks its captured ownership after the row fence returns', async () => {+ jest.useFakeTimers({+ doNotFake: [+ 'nextTick',+ 'setImmediate',+ 'queueMicrotask',+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'performance',+ ],+ });+ jest.setSystemTime(new Date('2026-06-01T12:00:00Z'));+ const reached = deferred();+ const go = deferred();+ try {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const outcome = deletion!.catch((error: unknown) => error);+ const sessions = a.db.getRepository(Session);+ const original = await sessions.findOneByOrFail({ id });+ const transaction = a.db.transaction.bind(a.db);+ jest.spyOn(a.db, 'transaction').mockImplementationOnce((async (+ run: (manager: import('typeorm').EntityManager) => Promise<void>,+ ) =>+ transaction(async manager => {+ const builder = manager.createQueryBuilder.bind(manager);+ jest.spyOn(manager, 'createQueryBuilder').mockImplementation((() => {+ const query = builder();+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation((() => {+ const updated = update(Session);+ const execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ reached.resolve();+ await go.promise;+ return execute();+ });+ return updated;+ }) as typeof query.update);+ return query;+ }) as typeof manager.createQueryBuilder);+ return run(manager);+ })) as typeof transaction);+ finish!();+ await reached.promise;+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await a.ownership.claim(id)).toBe(true);+ expect((await sessions.findOneByOrFail({ id })).claimedAt).toEqual(original.claimedAt);+ go.resolve();+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ } finally {+ go.resolve();+ jest.useRealTimers();+ }+ });++ it('retires old deletion work before a fresh claim write returns', async () => {+ jest.useFakeTimers({+ doNotFake: [+ 'nextTick',+ 'setImmediate',+ 'queueMicrotask',+ 'setTimeout',+ 'clearTimeout',+ 'setInterval',+ 'clearInterval',+ 'performance',+ ],+ });+ jest.setSystemTime(new Date('2026-06-01T12:00:00Z'));+ const written = deferred();+ const answer = deferred();+ let claiming: Promise<boolean> | undefined;+ try {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const outcome = deletion!.catch((error: unknown) => error);+ const sessions = a.db.getRepository(Session);+ const original = await sessions.findOneByOrFail({ id });+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ const builder = sessions.createQueryBuilder.bind(sessions);+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementationOnce(() => {+ const query = builder();+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const updated = update(Session);+ const execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ const result = await execute();+ written.resolve();+ await answer.promise;+ return result;+ });+ return updated;+ });+ return query;+ });+ claiming = a.ownership.claim(id);+ await written.promise;+ expect((await sessions.findOneByOrFail({ id })).claimedAt).toEqual(original.claimedAt);+ finish!();+ expect(await outcome).toBeInstanceOf(ConflictException);+ expect(await rowsOf(id)).toEqual({ sessions: 1, messages: 1, outbox: 0, deliveryFailures: 0 });+ } finally {+ answer.resolve();+ await claiming;+ jest.useRealTimers();+ }+ });++ it('keeps an earlier take-back as the fence for a third delete after a second delete is refused', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const update = sessions.update.bind(sessions);+ const clearing = deferred();+ const clear = deferred();+ jest.spyOn(sessions, 'update').mockImplementation(async (where, patch) => {+ if (patch.desiredState === null) {+ clearing.resolve();+ await clear.promise;+ }+ return update(where, patch);+ });+ jest+ .spyOn(SessionLifecycleFences.prototype, 'awaitPendingTeardown')+ .mockRejectedValueOnce(new ConflictException('credential teardown pending'));+ const first = a.service.delete(id).catch((error: unknown) => error);+ await clearing.promise;+ jest.spyOn(a.ownership, 'claim').mockRejectedValueOnce(new Error('connection reset'));+ await expect(a.service.delete(id)).rejects.toBeInstanceOf(ServiceUnavailableException);+ const reached = deferred();+ const done = deferred();+ let removing = false;+ a.hooks.execute.mockImplementation(async (event: string, data: unknown) => {+ if (event === 'session:deleted') {+ removing = true;+ reached.resolve();+ await done.promise;+ }+ return { continue: true, data };+ });+ finish = done.resolve;+ deletion = a.service.delete(id);+ try {+ for (let waited = 0; waited < 200 && !removing; waited += 5) {+ await new Promise(resolve => setTimeout(resolve, 5));+ }+ clear.resolve();+ expect(await first).toBeInstanceOf(ConflictException);+ await reached.promise;+ expect((await sessions.findOneByOrFail({ id })).desiredState).toBe('deleting');+ } finally {+ clear.resolve();+ done.resolve();+ await deletion;+ }+ });+ (pg ? it : it.skip).each([false, true])(+ 'rechecks initial intent after the real row lock with takeover=%s',+ async takeover => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const reached = deferred(),+ go = deferred();+ const transact = a.db.transaction.bind(a.db);+ jest.spyOn(a.db, 'transaction').mockImplementationOnce((async (+ run: (manager: import('typeorm').EntityManager) => Promise<void>,+ ) => {+ reached.resolve();+ await go.promise;+ return transact(run);+ }) as typeof transact);+ const deleting = a.service.delete(id).catch((error: unknown) => error);+ await reached.promise;+ const lock = b.db.createQueryRunner();+ const peerRepo = b.db.getRepository(Session);+ const oldManager = peerRepo.manager;+ await lock.connect();+ await lock.startTransaction();+ await lock.manager.getRepository(Session).findOne({ where: { id }, lock: { mode: 'pessimistic_write' } });+ try {+ go.resolve();+ let waiting = false;+ for (let i = 0; i < 100; i++) {+ const rows = await b.db.query<Array<{ waiting: boolean }>>(+ 'SELECT true AS waiting FROM pg_stat_activity WHERE wait_event_type = $1 AND query LIKE $2',+ ['Lock', `%${(options as { schema: string }).schema}%`],+ );+ if (rows.length) {+ waiting = true;+ break;+ }+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ expect(waiting).toBe(true);+ if (takeover) {+ await lock.manager.update(Session, id, { leaseExpiresAt: lapsed() });+ Object.assign(peerRepo, { manager: lock.manager });+ await b.service.start(id, { explicit: true });+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ Object.assign(peerRepo, { manager: oldManager });+ }+ await lock.commitTransaction();+ const result = await deleting;+ if (takeover) {+ expect(result).toBeInstanceOf(ConflictException);+ expect(await rowsOf(id)).toMatchObject({ sessions: 1, messages: 1 });+ expect(await b.db.getRepository(Session).findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-b',+ desiredState: null,+ });+ expect(a.hooks.execute.mock.calls.some(([event]) => event === 'session:deleted')).toBe(false);+ } else {+ expect(result).toBeUndefined();+ expect(await rowsOf(id)).toMatchObject({ sessions: 0, messages: 0 });+ }+ } finally {+ Object.assign(peerRepo, { manager: oldManager });+ go.resolve();+ if (lock.isTransactionActive) await lock.rollbackTransaction();+ await lock.release();+ await deleting;+ }+ },+ );++ it('does not replace newer local ownership when an older failed own renewal returns', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await a.ownership.claim(id);+ const checked = deferred(),+ checkGo = deferred(),+ renewed = deferred(),+ renewGo = deferred();+ const held = a.ownership.isHeldByOtherNode.bind(a.ownership);+ jest.spyOn(a.ownership, 'isHeldByOtherNode').mockImplementationOnce(async next => {+ const result = await held(next);+ checked.resolve();+ await checkGo.promise;+ return result;+ });+ const repo = a.db.getRepository(Session),+ update = repo.update.bind(repo);+ jest.spyOn(repo, 'update').mockImplementationOnce(async (...args) => {+ const result = await update(...args);+ renewed.resolve();+ await renewGo.promise;+ return result;+ });+ const deleting = a.service.delete(id).catch((error: unknown) => error);+ try {+ await checked.promise;+ await b.db.getRepository(Session).update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ checkGo.resolve();+ await renewed.promise;+ await b.db.getRepository(Session).update(id, { leaseExpiresAt: lapsed() });+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(SessionStoppedException);+ const valid = a.ownership.captureClaim(id);+ expect(valid()).toBe(true);+ renewGo.resolve();+ expect(await deleting).toBeInstanceOf(ConflictException);+ expect(await rowsOf(id)).toMatchObject({ sessions: 1, messages: 1 });+ expect(valid()).toBe(true);+ } finally {+ checkGo.resolve();+ renewGo.resolve();+ await deleting;+ }+ });++ it.each([false, true])('leaves a newer peer claim in delete cleanup even if expired=%s', async expired => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ await startHeldDelete(id);+ const outcome = deletion!.catch((error: unknown) => error);+ await a.db.getRepository(Session).update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ if (expired) await b.db.getRepository(Session).update(id, { leaseExpiresAt: lapsed() });+ const before = await b.db.getRepository(Session).findOneByOrFail({ id });+ finish!();+ expect(await outcome).toBeInstanceOf(ConflictException);+ const after = await b.db.getRepository(Session).findOneByOrFail({ id });+ expect(after).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ desiredState: null,+ });+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ expect(await rowsOf(id)).toMatchObject({ sessions: 1, messages: 1 });+ expect(a.purge).not.toHaveBeenCalled();+ });+ it.each([false, true])(+ 'settles abandoned batches when local starts overlap with a delayed claim reply %s',+ async overlap => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const batches = a.db.getRepository(MessageBatch);+ const batch = await batches.save({+ sessionId: id,+ batchId: randomUUID(),+ status: BatchStatus.PROCESSING,+ messages: [+ {+ chatId: '[email protected]',+ type: 'image',+ content: { image: { base64: 'PRIVATE-MEDIA', mimetype: 'image/png' } },+ },+ ],+ });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const bulk = new BulkMessageService(batches, registry, {} as never, a.hooks as never, {} as never, a.ownership);+ bulk.onModuleInit();+ const reaping: Promise<number>[] = [];+ const reap = bulk.reapProcessingBatches.bind(bulk);+ jest.spyOn(bulk, 'reapProcessingBatches').mockImplementation((...args) => {+ const promise = reap(...args);+ reaping.push(promise);+ return promise;+ });+ const reached = deferred(),+ go = deferred();+ if (overlap) {+ const claim = a.ownership.claim.bind(a.ownership);+ jest.spyOn(a.ownership, 'claim').mockImplementationOnce(async (...args) => {+ const result = await claim(...args);+ reached.resolve();+ await go.promise;+ return result;+ });+ }+ const first = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ try {+ if (overlap) {+ await reached.promise;+ await a.service.start(id, { explicit: true });+ go.resolve();+ expect(await first).toBeInstanceOf(Error);+ } else expect(await first).not.toBeInstanceOf(Error);+ await new Promise<void>(resolve => setImmediate(resolve));+ await Promise.all(reaping);+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect(await batches.findOneByOrFail({ id: batch.id })).toMatchObject({ status: BatchStatus.FAILED });+ expect(JSON.stringify((await batches.findOneByOrFail({ id: batch.id })).messages)).not.toContain(+ 'PRIVATE-MEDIA',+ );+ } finally {+ go.resolve();+ await first;+ await Promise.all(reaping);+ }+ },+ );+ it.each(['claim', 'stop', 'release'] as const)(+ 'settles abandoned work in the ownership transaction before a peer starts after %s',+ async operation => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const batches = a.db.getRepository(MessageBatch);+ const old = await batches.save({+ sessionId: id,+ batchId: randomUUID(),+ status: BatchStatus.PROCESSING,+ messages: [+ { chatId: '[email protected]', type: 'image', content: { image: { base64: 'T0xE', mimetype: 'image/png' } } },+ ],+ });+ const reached = deferred(),+ go = deferred(),+ sending = deferred(),+ sendGo = deferred();+ const processing: Promise<void>[] = [];+ const bulkFor = (node: Node): BulkMessageService => {+ const registry = (node.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const bulk = new BulkMessageService(+ node.db.getRepository(MessageBatch),+ registry,+ {} as never,+ node.hooks as never,+ {+ assertSendAllowed: async () => {+ sending.resolve();+ await sendGo.promise;+ throw new Error('fixture finished');+ },+ } as never,+ node.ownership,+ );+ bulk.onModuleInit();+ type Runner = { processBatch(id: string, reserved: boolean, lifetime: unknown): Promise<void> };+ const runner = bulk as unknown as Runner,+ process = runner.processBatch.bind(bulk);+ jest.spyOn(runner, 'processBatch').mockImplementation((...args) => {+ const work = process(...args);+ processing.push(work);+ return work;+ });+ return bulk;+ };+ const bulkA = bulkFor(a),+ bulkB = bulkFor(b);+ const reap = bulkA.reapProcessingBatches.bind(bulkA);+ jest.spyOn(bulkA, 'reapProcessingBatches').mockImplementationOnce(async (...args) => {+ reached.resolve();+ await go.promise;+ return reap(...args);+ });+ const pending = (+ operation === 'claim'+ ? a.service.start(id, { explicit: true })+ : operation === 'stop'+ ? a.service.stop(id)+ : a.ownership.release(id)+ ).catch((error: unknown) => error);+ let peerClaim: Promise<boolean> | undefined;+ try {+ await reached.promise;+ if (pg) {+ peerClaim = b.ownership.claim(id);+ let waiting = false;+ for (let i = 0; i < 100; i++) {+ const rows = await b.db.query<Array<{ waiting: boolean }>>(+ 'SELECT true AS waiting FROM pg_stat_activity WHERE wait_event_type = $1 AND query LIKE $2',+ ['Lock', `%${(options as { schema: string }).schema}%`],+ );+ if (rows.length) {+ waiting = true;+ break;+ }+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ expect(waiting).toBe(true);+ } else {+ expect(+ (a.db.driver as unknown as { databaseConnection: { inTransaction: boolean } }).databaseConnection+ .inTransaction,+ ).toBe(true);+ }+ go.resolve();+ expect(await pending).not.toBeInstanceOf(Error);+ if (peerClaim) expect(await peerClaim).toBe(operation !== 'claim');+ const retired = await batches.findOneByOrFail({ id: old.id });+ expect(retired.status).toBe(BatchStatus.FAILED);+ expect(JSON.stringify(retired.messages)).not.toContain('T0xE');+ if (operation === 'claim') await b.db.getRepository(Session).update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ const callbacks = (+ b.engines[0].initialize.mock.calls as Array<[{ onReady?: (phone: string, name: string) => void }]>+ )[0][0];+ callbacks.onReady?.('628111111111', 'Fixture');+ for (let i = 0; i < 100; i++) {+ if ((await b.db.getRepository(Session).findOneByOrFail({ id })).status === SessionStatus.READY) break;+ await new Promise(resolve => setTimeout(resolve, 5));+ }+ expect((await b.db.getRepository(Session).findOneByOrFail({ id })).status).toBe(SessionStatus.READY);+ const fresh = await bulkB.createBatch(id, {+ batchId: randomUUID(),+ messages: [+ {+ chatId: '[email protected]',+ type: 'image',+ content: { image: { base64: 'TkVX', mimetype: 'image/png' } },+ },+ ],+ options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },+ });+ await sending.promise;+ const active = await batches.findOneByOrFail({ id: fresh.id });+ expect(active.status).toBe(BatchStatus.PROCESSING);+ expect(JSON.stringify(active.messages)).toContain('TkVX');+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ } finally {+ go.resolve();+ sendGo.resolve();+ await pending;+ await peerClaim;+ await Promise.all(processing);+ }+ },+ );+ it.each(['claim', 'stop', 'release'] as const)(+ 'keeps the ownership transition when SQL adoption cleanup fails during %s',+ async operation => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const batches = a.db.getRepository(MessageBatch);+ const old = await batches.save({+ sessionId: id,+ batchId: randomUUID(),+ status: BatchStatus.PROCESSING,+ messages: [+ { chatId: '[email protected]', type: 'image', content: { image: { base64: 'T0xE', mimetype: 'image/png' } } },+ ],+ });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const bulk = new BulkMessageService(batches, registry, {} as never, a.hooks as never, {} as never, a.ownership);+ bulk.onModuleInit();+ const reap = bulk.reapProcessingBatches.bind(bulk);+ jest.spyOn(bulk, 'reapProcessingBatches').mockImplementationOnce(async (...args) => {+ await reap(...args);+ await args[2]!.query('SELECT * FROM adoption_cleanup_missing_table');+ return 0;+ });+ if (operation === 'claim') await a.service.start(id, { explicit: true });+ else if (operation === 'stop') await a.service.stop(id);+ else await a.ownership.release(id);+ expect(await a.db.getRepository(Session).findOneByOrFail({ id })).toMatchObject({+ nodeId: operation === 'claim' ? 'node-a' : null,+ desiredState: operation === 'stop' ? 'stopped' : null,+ });+ const retained = await batches.findOneByOrFail({ id: old.id });+ expect(retained.status).toBe(pg ? BatchStatus.PROCESSING : BatchStatus.FAILED);+ if (pg) expect(JSON.stringify(retained.messages)).toContain('T0xE');+ else expect(JSON.stringify(retained.messages)).not.toContain('T0xE');+ },+ );+ (pg ? it.skip : it).each(['start', 'prepare', 'claim'] as const)(+ 'keeps acknowledged local %s writes when adoption SQL cleanup fails',+ async admission => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ desiredState: 'stopped',+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const bulk = new BulkMessageService(+ a.db.getRepository(MessageBatch),+ registry,+ {} as never,+ a.hooks as never,+ {} as never,+ a.ownership,+ );+ bulk.onModuleInit();+ const reached = deferred(),+ go = deferred();+ jest.spyOn(bulk, 'reapProcessingBatches').mockImplementationOnce(async (_id, _reason, manager) => {+ reached.resolve();+ await go.promise;+ await manager!.query('SELECT adoption_admission_missing_column');+ return 0;+ });+ const first = a.ownership.claim(id);+ let second: Promise<unknown> | undefined;+ try {+ await reached.promise;+ second =+ admission === 'start'+ ? a.service.start(id, { explicit: true })+ : admission === 'prepare'+ ? a.ownership.prepareStart(id, 'stopped')+ : a.ownership.claim(id);+ expect(await second).not.toBeInstanceOf(Error);+ if (admission === 'start') {+ const callbacks = (+ a.engines[0].initialize.mock.calls as Array<[{ onReady?: (phone: string, name: string) => void }]>+ )[0][0];+ callbacks.onReady?.('628111111111', 'Fixture');+ for (let i = 0; i < 100; i++) {+ if ((await a.db.getRepository(Session).findOneByOrFail({ id })).status === SessionStatus.READY) break;+ await new Promise(resolve => setTimeout(resolve, 5));+ }+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect((await a.db.getRepository(Session).findOneByOrFail({ id })).status).toBe(SessionStatus.READY);+ }+ go.resolve();+ expect(await first).toBe(true);+ expect(await a.db.getRepository(Session).findOneByOrFail({ id })).toMatchObject({+ nodeId: 'node-a',+ desiredState: admission === 'claim' ? 'stopped' : null,+ });+ } finally {+ go.resolve();+ await first;+ await second;+ }+ },+ );+ (pg ? it : it.skip)('locks the session before reading its previous owner for SQL adoption', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const otherId = await seed({ status: SessionStatus.DISCONNECTED });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ new BulkMessageService(+ a.db.getRepository(MessageBatch),+ registry,+ {} as never,+ a.hooks as never,+ {} as never,+ a.ownership,+ ).onModuleInit();+ const reached = deferred(),+ go = deferred();+ const transaction = a.db.transaction.bind(a.db);+ jest.spyOn(a.db, 'transaction').mockImplementationOnce((async (run: (manager: EntityManager) => Promise<boolean>) =>+ transaction(async manager => {+ const sessions = manager.getRepository(Session),+ find = sessions.findOne.bind(sessions);+ jest.spyOn(sessions, 'findOne').mockImplementationOnce(async options => {+ const row = await find(options);+ reached.resolve();+ await go.promise;+ return row;+ });+ return run(manager);+ })) as typeof transaction);+ const first = a.ownership.claim(id);+ await reached.promise;+ const peer = b.ownership.claim(id);+ try {+ let waiting = false;+ for (let i = 0; i < 100; i++) {+ const rows = await b.db.query<Array<{ waiting: boolean }>>(+ 'SELECT true AS waiting FROM pg_stat_activity WHERE wait_event_type = $1 AND query LIKE $2',+ ['Lock', `%${(options as { schema: string }).schema}%`],+ );+ if (rows.length) {+ waiting = true;+ break;+ }+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ expect(waiting).toBe(true);+ await b.service.start(otherId, { explicit: true });+ expect(b.service.getEngine(otherId)).toBe(b.engines[0]);+ go.resolve();+ expect(await first).toBe(true);+ expect(await peer).toBe(false);+ expect((await a.db.getRepository(Session).findOneByOrFail({ id })).nodeId).toBe('node-a');+ } finally {+ go.resolve();+ await first;+ await peer;+ }+ });+ (pg ? it.skip : it).each([+ ['stop', false],+ ['logout', false],+ ['kill', false],+ ['release', false],+ ['stop', true],+ ['release', true],+ ] as const)(+ 'keeps an independent %s durable when adoption SQL cleanup fails on same row %s',+ async (operation, same) => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const other = same ? id : await seed({ status: SessionStatus.DISCONNECTED });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const bulk = new BulkMessageService(+ a.db.getRepository(MessageBatch),+ registry,+ {} as never,+ a.hooks as never,+ {} as never,+ a.ownership,+ );+ bulk.onModuleInit();+ if (!same) {+ if (operation === 'release') await a.ownership.claim(other);+ else await a.service.start(other, { explicit: true });+ }+ const reached = deferred(),+ go = deferred();+ jest.spyOn(bulk, 'reapProcessingBatches').mockImplementationOnce(async (_id, _reason, manager) => {+ reached.resolve();+ await go.promise;+ await (manager ?? a.db.manager).query('SELECT definitely_missing_local_fixture_column');+ return 0;+ });+ const first = a.ownership.claim(id).catch((error: unknown) => error);+ let second: Promise<unknown> | undefined;+ try {+ await reached.promise;+ second = (+ operation === 'stop'+ ? a.service.stop(other)+ : operation === 'logout'+ ? a.service.logout(other)+ : operation === 'kill'+ ? a.service.forceKill(other)+ : a.ownership.release(other)+ ).catch((error: unknown) => error);+ expect(await second).not.toBeInstanceOf(Error);+ go.resolve();+ expect(await first).toBe(!same);+ expect(a.service.getEngine(other)).toBeUndefined();+ expect(a.ownership.owns(other)).toBe(false);+ expect(await a.db.getRepository(Session).findOneByOrFail({ id: other })).toMatchObject({+ nodeId: null,+ claimedAt: null,+ leaseExpiresAt: null,+ nodeUrl: null,+ desiredState: operation === 'release' || operation === 'logout' ? null : 'stopped',+ });+ } finally {+ go.resolve();+ await first;+ await second;+ }+ },+ );++ (pg ? it.skip : it).each(['batch', 'outbox'] as const)(+ 'keeps another session acknowledged %s row when adoption SQL cleanup fails',+ async kind => {+ const id = await seed({+ status: SessionStatus.DISCONNECTED,+ nodeId: 'departed',+ claimedAt: lapsed(),+ leaseExpiresAt: lapsed(),+ });+ const other = await seed({ status: SessionStatus.DISCONNECTED });+ const registry = (a.lifecycle as unknown as { engines: EngineRegistry }).engines;+ const reached = deferred(),+ go = deferred(),+ sending = deferred(),+ sendGo = deferred();+ const bulk = new BulkMessageService(+ a.db.getRepository(MessageBatch),+ registry,+ {} as never,+ a.hooks as never,+ {+ assertSendAllowed: async () => {+ sending.resolve();+ await sendGo.promise;+ throw new Error('end local fixture hold');+ },+ } as never,+ a.ownership,+ );+ bulk.onModuleInit();+ await a.service.start(other, { explicit: true });+ type Runner = { processBatch(id: string, reserved: boolean, lifetime: unknown): Promise<void> };+ const runner = bulk as unknown as Runner,+ process = runner.processBatch.bind(bulk),+ processing: Promise<void>[] = [];+ jest.spyOn(runner, 'processBatch').mockImplementation((...args) => {+ const work = process(...args);+ processing.push(work);+ return work;+ });+ jest.spyOn(bulk, 'reapProcessingBatches').mockImplementationOnce(async (_id, _reason, manager) => {+ reached.resolve();+ await go.promise;+ await (manager ?? a.db.manager).query('SELECT definitely_missing_local_fixture_column');+ return 0;+ });+ const first = a.ownership.claim(id).catch((error: unknown) => error);+ try {+ await reached.promise;+ if (kind === 'batch') {+ const fresh = await bulk.createBatch(other, {+ batchId: randomUUID(),+ messages: [+ {+ chatId: '[email protected]',+ type: 'image',+ content: { image: { base64: 'TkVX', mimetype: 'image/png' } },+ },+ ],+ options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },+ });+ await sending.promise;+ expect((await a.db.getRepository(MessageBatch).findOneByOrFail({ id: fresh.id })).status).toBe(+ BatchStatus.PROCESSING,+ );+ go.resolve();+ await first;+ expect(await a.db.getRepository(MessageBatch).findOneBy({ id: fresh.id })).toMatchObject({+ status: BatchStatus.PROCESSING,+ });+ } else {+ const key = randomUUID();+ const outbox = new WebhookOutboxService(a.db.getRepository(WebhookOutboxEvent));+ await outbox.open({+ webhookId: randomUUID(),+ sessionId: other,+ event: 'message',+ idempotencyKey: key,+ deliveryId: randomUUID(),+ payload: { dummy: 'ordinary local write' },+ });+ expect(await a.db.getRepository(WebhookOutboxEvent).countBy({ idempotencyKey: key })).toBe(1);+ go.resolve();+ await first;+ expect(await a.db.getRepository(WebhookOutboxEvent).countBy({ idempotencyKey: key })).toBe(1);+ }+ } finally {+ go.resolve();+ sendGo.resolve();+ await first;+ await Promise.all(processing);+ }+ },+ );++ it.each([false, true])(+ 'retires an old local engine after a peer takes over and a fresh claim fails with SQL error %s',+ async sqlError => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ await a.service.start(id, { explicit: true });+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ const before = await sessions.findOneByOrFail({ id });+ const failFresh = jest.fn().mockRejectedValue(new Error('fresh claim SQL unavailable'));+ if (sqlError) {+ const builder = sessions.createQueryBuilder.bind(sessions);+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementationOnce(() => {+ const query = builder();+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const updated = update(Session);+ jest.spyOn(updated, 'execute').mockImplementationOnce(failFresh);+ return updated;+ });+ return query;+ });+ }+ if (sqlError) {+ await expect(a.service.start(id, { explicit: true })).rejects.toThrow('fresh claim SQL unavailable');+ expect(failFresh).toHaveBeenCalledTimes(1);+ } else {+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ }+ await a.ownership.renew();+ expect(a.service.getEngine(id)).toBeUndefined();+ expect(a.engines[0].destroy).toHaveBeenCalled();+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ expect(b.engines[0].destroy).not.toHaveBeenCalled();+ expect(await sessions.findOneByOrFail({ id })).toMatchObject({+ nodeId: before.nodeId,+ claimedAt: before.claimedAt,+ leaseExpiresAt: before.leaseExpiresAt,+ nodeUrl: before.nodeUrl,+ desiredState: before.desiredState,+ status: before.status,+ });+ },+ );++ it('keeps an acknowledged local renewal when an older fresh SQL reply fails', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const written = deferred(),+ answer = deferred();+ const builder = sessions.createQueryBuilder.bind(sessions);+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementationOnce(() => {+ const query = builder(),+ update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const updated = update(Session),+ execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ await execute();+ written.resolve();+ await answer.promise;+ throw new Error('old claim reply unavailable');+ });+ return updated;+ });+ return query;+ });+ const first = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ try {+ await written.promise;+ await a.service.start(id, { explicit: true });+ const current = a.ownership.captureClaim(id);+ expect(current()).toBe(true);+ answer.resolve();+ expect(await first).toBeInstanceOf(Error);+ expect(a.ownership.owns(id)).toBe(true);+ expect(current()).toBe(true);+ await a.ownership.renew();+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect(current()).toBe(true);+ expect((await sessions.findOneByOrFail({ id })).nodeId).toBe('node-a');+ await a.service.stop(id);+ expect(current()).toBe(false);+ expect((await sessions.findOneByOrFail({ id })).nodeId).toBeNull();+ } finally {+ answer.resolve();+ await first;+ }+ });++ it('keeps a pending newer claim when an older fresh SQL reply throws', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const written = [deferred(), deferred()],+ answer = [deferred(), deferred()];+ const builder = sessions.createQueryBuilder.bind(sessions);+ let attempt = 0;+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementation(() => {+ const query = builder();+ if (attempt >= 2) return query;+ const update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const index = attempt++;+ const updated = update(Session),+ execute = updated.execute.bind(updated);+ jest.spyOn(updated, 'execute').mockImplementationOnce(async () => {+ const result = await execute();+ written[index].resolve();+ await answer[index].promise;+ if (index === 0) throw new Error('old claim reply unavailable');+ return result;+ });+ return updated;+ });+ return query;+ });+ const first = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ let second: Promise<unknown> | undefined;+ try {+ await written[0].promise;+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ expect(await b.ownership.claim(id)).toBe(true);+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ second = a.service.start(id, { explicit: true }).catch((error: unknown) => error);+ await written[1].promise;+ answer[0].resolve();+ expect(await first).toBeInstanceOf(Error);+ answer[1].resolve();+ expect(await second).not.toBeInstanceOf(Error);+ expect(a.ownership.captureClaim(id)()).toBe(true);+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect((await sessions.findOneByOrFail({ id })).nodeId).toBe('node-a');+ } finally {+ answer.forEach(hold => hold.resolve());+ await Promise.all([first, second]);+ }+ });++ it.each([false, true])(+ 'clears tracking after a completed delete overlaps a missing-row start with SQL error %s',+ async sqlError => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ await a.service.start(id, { explicit: true });+ const reached = deferred(),+ go = deferred();+ const release = a.ownership.release.bind(a.ownership);+ jest.spyOn(a.ownership, 'release').mockImplementationOnce(async (...args) => {+ reached.resolve();+ await go.promise;+ return release(...args);+ });+ const deleting = a.service.delete(id);+ try {+ await reached.promise;+ expect((await rowsOf(id)).sessions).toBe(0);+ if (sqlError) {+ const builder = sessions.createQueryBuilder.bind(sessions);+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementationOnce(() => {+ const query = builder(),+ update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const updated = update(Session);+ jest.spyOn(updated, 'execute').mockRejectedValueOnce(new Error('missing row claim SQL unavailable'));+ return updated;+ });+ return query;+ });+ await expect(a.service.start(id, { explicit: true })).rejects.toThrow('missing row claim SQL unavailable');+ } else {+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(NotFoundException);+ }+ expect(a.ownership.owns(id)).toBe(false);+ go.resolve();+ await deleting;+ expect(a.ownership.owns(id)).toBe(false);+ expect(a.service.getEngine(id)).toBeUndefined();+ expect(a.lifecycle.isEngineActive(id)).toBe(false);+ } finally {+ go.resolve();+ await deleting;+ }+ },+ );++ it.each([false, true])(+ 'preserves suspended loss detection while reconciling a failed claim with SQL error %s',+ async sqlError => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ await a.service.start(id, { explicit: true });+ await sessions.update(id, { leaseExpiresAt: lapsed() });+ await b.service.start(id, { explicit: true });+ const resume = a.ownership.suspendLossDetection();+ try {+ if (sqlError) {+ const builder = sessions.createQueryBuilder.bind(sessions);+ jest.spyOn(sessions, 'createQueryBuilder').mockImplementationOnce(() => {+ const query = builder(),+ update = query.update.bind(query);+ jest.spyOn(query, 'update').mockImplementation(() => {+ const updated = update(Session);+ jest.spyOn(updated, 'execute').mockRejectedValueOnce(new Error('suspended claim SQL unavailable'));+ return updated;+ });+ return query;+ });+ await expect(a.service.start(id, { explicit: true })).rejects.toThrow('suspended claim SQL unavailable');+ } else {+ await expect(a.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ }+ expect(a.ownership.owns(id)).toBe(true);+ expect(a.service.getEngine(id)).toBe(a.engines[0]);+ expect(a.engines[0].destroy).not.toHaveBeenCalled();+ } finally {+ resume();+ }+ await a.ownership.renew();+ expect(a.ownership.owns(id)).toBe(false);+ expect(a.service.getEngine(id)).toBeUndefined();+ expect(b.service.getEngine(id)).toBe(b.engines[0]);+ expect(b.engines[0].destroy).not.toHaveBeenCalled();+ expect((await sessions.findOneByOrFail({ id })).nodeId).toBe('node-b');+ },+ );});diff --git a/src/modules/session/session-delete-race.spec.ts b/src/modules/session/session-delete-race.spec.tsindex 180125b73..09de9f9f1 100644--- a/src/modules/session/session-delete-race.spec.ts+++ b/src/modules/session/session-delete-race.spec.ts@@ -147,13 +147,16 @@ describe('A session being deleted', () => {// One stored message is enough: the delete removes it in a batch, and that batch is the one held.const messages = db.getRepository(Message);await messages.insert({ sessionId, chatId: '[email protected]', from: 'me', to: '[email protected]', body: 'm' });- const removeBatch = messages.delete.bind(messages);+ const transaction = db.transaction.bind(db);reachedBatch = deferred();finishBatch = deferred();- jest.spyOn(messages, 'delete').mockImplementation(async criteria => {- reachedBatch.resolve();- await finishBatch.promise;- return removeBatch(criteria);+ let transactions = 0;+ jest.spyOn(db, 'transaction').mockImplementation(async (...args: Parameters<typeof transaction>) => {+ if (++transactions === 2) {+ reachedBatch.resolve();+ await finishBatch.promise;+ }+ return transaction(...args);});deletion = service.delete(sessionId);diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex 309daccbd..c96e88916 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -8,7 +8,7 @@ import {} from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { isUUID } from 'class-validator';-import { EntityTarget, In, Repository, DataSource } from 'typeorm';+import { EntityTarget, EntityManager, In, IsNull, Repository, DataSource } from 'typeorm';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { MessageBatch } from '../message/entities/message-batch.entity';@@ -140,6 +140,8 @@ export class StopMarks extends Set<string> {/** Caller callbacks for stop()/delete(), run around the session read that opens each verb. */export interface StopHooks {+ /** delete() only: the ownership captured by its caller still covers this operation. */+ ownsClaim?: () => boolean;/** stop() only: runs once the session read succeeds and before any teardown; records the stop. */afterRead?: () => Promise<void>;/**@@ -178,6 +180,7 @@ export interface SessionEngineControlsHost {presence: PresenceStore;hookManager: HookManager;configService?: ConfigService;+ nodeId?: string;logger: ReturnType<typeof createLogger>;/** LIVE closure — read at call time, never captured (specs replace lifecycle.dataSource at runtime). */dataSource(): DataSource;@@ -452,7 +455,8 @@ export class SessionEngineControls {// Initialize reconnect state from the (untrusted) opaque session.config — coerced + clamped// so a poisoned value can't drive a NaN/immediate-relaunch storm or an unbounded loop.const { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);- this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });+ const reconnectState: ReconnectState = { attempts: 0, timer: null, maxAttempts, baseDelay };+ this.reconnectStates.set(id, reconnectState);// An accepted top-level start() re-arms the stuck-auth recovery budget: every fence above// (duplicate-start, cap, credential-teardown) passed, so this is a deliberate, operator-initiated@@ -502,7 +506,7 @@ export class SessionEngineControls {// will ever fire it, and leaving it behind is dead state a later liveness check would have to// reason about. A retry builds its own. A reconnect that already registered a replacement// keeps its state.- if (!this.engines.has(id)) {+ if (!this.engines.has(id) && this.reconnectStates.get(id) === reconnectState && !reconnectState.started) {this.host.cancelReconnect(id);}// Shutdown's destroy is the usual cause of an init rejecting now; the adapter's error would@@ -529,7 +533,7 @@ export class SessionEngineControls {retired = false;}if (retired) {- await this.reapRetiredEngine(id);+ await this.reapRetiredEngine(id, mine, reconnectState);} else if (this.host.isClosed()) {// Shutdown destroys every engine it finds, this one included, and skips initialize() for an// engine it caught mid-start. Either way the session is not kept, so this is no success. A@@ -544,7 +548,7 @@ export class SessionEngineControls {// "already started". The row read on entry stands in for the one that failed.// A row found gone only now is the retirement the failed read above could not report: the engine// goes with it.- if (!retired && error instanceof NotFoundException) await this.reapRetiredEngine(id);+ if (!retired && error instanceof NotFoundException) await this.reapRetiredEngine(id, mine, reconnectState);if (retired || error instanceof NotFoundException) throw error;return session;}@@ -557,16 +561,19 @@ export class SessionEngineControls {* Tears down the engine a start registered for a session that was stopped or deleted meanwhile, and drops* the reconnect state it armed for it.*/- private async reapRetiredEngine(id: string): Promise<void> {- const resurrected = this.engines.get(id);- if (resurrected) {+ private async reapRetiredEngine(+ id: string,+ resurrected: IWhatsAppEngine | undefined,+ reconnectState?: ReconnectState,+ ): Promise<void> {+ if (resurrected && this.engines.isLive(id, resurrected)) {await this.fences.destroyWithEscalation(id, resurrected);this.engines.deleteIfLive(id, resurrected);}// The reconnect state this start armed up front serves no engine now, and the stop or delete that retired it// may have run before the state was armed, so nothing else would drop it. A replacement engine that// registered meanwhile keeps its own.- if (!this.engines.has(id)) {+ if (!this.engines.has(id) && this.reconnectStates.get(id) === reconnectState && !reconnectState?.started) {this.host.cancelReconnect(id);}// A delete() that raced this start purged the on-disk auth dirs BEFORE this init re-created them, so@@ -918,16 +925,9 @@ export class SessionEngineControls {// conversations, see ConversationMappingService.rebindSession), ingress_events (the// instance-keyed inbound dedup record, payload already dropped after dispatch, always pruned// after INGRESS_DEDUP_RETENTION_DAYS), lid_mappings (a global cache by design) and audit_logs (the audit trail).- await this.deleteTrafficRowsInBatches(id);- // On SQLite every caller shares one connection: opened inside another caller's transaction, this one- // would only be a savepoint in it, undone if that one rolls back after this delete has answered.+ await this.deleteTrafficRowsInBatches(session, hooks.ownsClaim);const dataSource = this.host.dataSource();- if (!(await awaitNoOpenTransaction(dataSource))) {- throw new ServiceUnavailableException(- `Session ${id} was not deleted: another database transaction stayed open. Retry the delete.`,- );- }- await dataSource.transaction(async manager => {+ await this.withDeleteClaim(session, hooks.ownsClaim, async manager => {await manager.delete(Message, { sessionId: id });await manager.delete(MessageBatch, { sessionId: id });await manager.delete(ChatState, { sessionId: id });@@ -970,7 +970,7 @@ export class SessionEngineControls {// The session survives, but the write scopes closed above stay retired for good: a bulk batch// running for it stops at its next item without recording anything, and one not yet picked up// never starts. Nothing else moves a PENDING or PROCESSING row on while this process lives.- if (!parentDeleted) await this.failUnfinishedBatches(id);+ if (!parentDeleted) await this.failUnfinishedBatches(session, hooks.ownsClaim);throw error;} finally {writes.release();@@ -1009,17 +1009,10 @@ export class SessionEngineControls {* reach without a cycle. Best effort: the database that just failed the delete may fail this too, and the* boot reaper still gets the row on the next start.*/- private async failUnfinishedBatches(sessionId: string): Promise<void> {+ private async failUnfinishedBatches(session: Session, ownsClaim?: () => boolean): Promise<void> {+ const sessionId = session.id;try {- const dataSource = this.host.dataSource();- // Not inside another caller's transaction on the shared connection, where the fail would roll back with it.- if (!(await awaitNoOpenTransaction(dataSource))) {- this.logger.warn(`Failing the unfinished batches of session ${sessionId} inside another open transaction`, {- sessionId,- action: 'session_delete_foreign_transaction_open',- });- }- await failUnfinishedSessionBatches(dataSource, sessionId);+ await this.withDeleteClaim(session, ownsClaim, manager => failUnfinishedSessionBatches(manager, sessionId));} catch (error) {this.logger.warn(`Could not fail the unfinished batches of session ${sessionId} after a failed delete`, {sessionId,@@ -1046,7 +1039,8 @@ export class SessionEngineControls {* over the session's remaining rows that filters on the list, once per batch (PostgreSQL does too while its* statistics are missing or stale), which made a long history take longer than linear.*/- private async deleteTrafficRowsInBatches(sessionId: string): Promise<void> {+ private async deleteTrafficRowsInBatches(session: Session, ownsClaim?: () => boolean): Promise<void> {+ const sessionId = session.id;const dataSource = this.host.dataSource();const postgres = dataSource.options.type === 'postgres';let size = postgres ? SESSION_DELETE_BATCH_SIZE_POSTGRES : SESSION_DELETE_BATCH_MIN_SQLITE;@@ -1082,7 +1076,9 @@ export class SessionEngineControls {const started = performance.now();const ids = await next(size);if (ids.length === 0) break;- await rows.delete({ id: In(ids) });+ await this.withDeleteClaim(session, ownsClaim, async manager => {+ await manager.getRepository(rows.target).delete({ id: In(ids) });+ });if (ids.length < size) break;if (!postgres) size = nextSqliteDeleteBatchSize(ids.length, performance.now() - started);await new Promise<void>(resolve =>@@ -1092,6 +1088,35 @@ export class SessionEngineControls {}}+ /** Lock the owner row with each destructive unit, never across a hook or between batches. */+ private async withDeleteClaim(+ session: Session,+ ownsClaim: (() => boolean) | undefined,+ remove: (manager: EntityManager) => Promise<void>,+ ): Promise<void> {+ const dataSource = this.host.dataSource();+ // A savepoint on SQLite's shared connection could be rolled back by an unrelated caller.+ if (!(await awaitNoOpenTransaction(dataSource))) {+ throw new ServiceUnavailableException(+ `Session ${session.id} was not deleted: another database transaction stayed open. Retry the delete.`,+ );+ }+ await dataSource.transaction(async manager => {+ if (this.host.nodeId !== undefined) {+ const { affected } = await manager+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: this.host.nodeId, updatedAt: () => '"updatedAt"' })+ .where({ id: session.id, nodeId: this.host.nodeId, claimedAt: session.claimedAt ?? IsNull() })+ .execute();+ if (affected !== 1) throw new ConflictException(`Session ${session.id} is no longer owned by this node`);+ }+ if (ownsClaim?.() === false)+ throw new ConflictException(`Session ${session.id} is no longer owned by this delete`);+ await remove(manager);+ });+ }+/*** The messages that carry a timestamp, a page at a time in the order of IDX_messages_session_timestamp_id,* each page starting after the last row of the one before. A select that restarted from the head of thediff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.tsindex 6261d6ddc..f51964a82 100644--- a/src/modules/session/session-engine-lifecycle-races.spec.ts+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts@@ -76,7 +76,7 @@ const flush = async (): Promise<void> => {interface Internals {engines: EngineRegistry;- controls: { reapRetiredEngine(id: string): Promise<void> };+ controls: { reapRetiredEngine(id: string, engine: IWhatsAppEngine): Promise<void> };stoppingSessions: Set<string>;reconnectStates: Map<string, ReconnectState>;logger: { warn: (...args: unknown[]) => void };@@ -433,7 +433,7 @@ describe('SessionEngineLifecycle races', () => {const state: ReconnectState = { attempts: 0, timer: null, maxAttempts: 5, baseDelay: 5000 };internals.engines.set(ID, retired as never);- const reaping = internals.controls.reapRetiredEngine(ID);+ const reaping = internals.controls.reapRetiredEngine(ID, retired as never);await flush();internals.engines.set(ID, replacement as never);internals.reconnectStates.set(ID, state);diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 6a8afe54c..8099251d9 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -438,6 +438,7 @@ export class SessionEngineLifecycle {cancelReconnect: id => this.cancelReconnect(id),initializeEngine: (id, session) => this.initializeEngine(id, session),isSessionRetired: id => this.isSessionRetired(id),+ nodeId: this.ownership?.nodeId,prepareStart: (id, desiredState) => this.prepareStart(id, desiredState),purgeAuthDirsIfDeleted: id => this.purgeAuthDirsIfDeleted(id),updateStatus: (id, status) => this.updateStatus(id, status),diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.tsindex bbf6d369b..125c82523 100644--- a/src/modules/session/session-ownership.service.spec.ts+++ b/src/modules/session/session-ownership.service.spec.ts@@ -184,6 +184,19 @@ describe('SessionOwnershipService', () => {await settle();expect((await sessions.findOneByOrFail({ id: session.id })).nodeId).toBe('node-b');});++ it('makes ownership visible before invoking a detached adoption handler', async () => {+ const node = service('node-b');+ const observed: boolean[] = [];+ node.onAdoption(id => {+ observed.push(node.owns(id));+ return Promise.resolve();+ });+ const session = await seed(lapsedBy('node-a'));+ expect(await node.claim(session.id)).toBe(true);+ await settle();+ expect(observed).toEqual([true]);+ });});describe('releasing', () => {diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.tsindex ebbb1b026..64fc8822f 100644--- a/src/modules/session/session-ownership.service.ts+++ b/src/modules/session/session-ownership.service.ts@@ -2,10 +2,11 @@ import { Injectable, Optional } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { ConfigService } from '@nestjs/config';import { hostname } from 'node:os';-import { In, IsNull, LessThan, LessThanOrEqual, MoreThan, Not, Repository } from 'typeorm';+import { In, IsNull, LessThan, LessThanOrEqual, MoreThan, Not, Or, Repository, EntityManager } from 'typeorm';import { Session } from './entities/session.entity';import { createLogger } from '../../common/services/logger.service';import { DateTransformer } from '../../common/transformers/date.transformer';+import { awaitNoOpenTransaction, SHARED_CONNECTION_DIALECTS } from '../../common/utils/shared-connection';/*** Bind a lease timestamp the way the column stores it.@@ -42,7 +43,7 @@ export class SessionOwnershipService {/** Sessions this process believes it owns, so the heartbeat knows what to renew. */private readonly owned = new Set<string>();/**- * A fresh value from claimSeq on every claim, dropped when the claim ends, so renew() can tell a+ * A fresh value from claimSeq on every new ownership, dropped when the claim ends, so renew() can tell a* claim it read from one replaced since. One sequence for all sessions: a per-session counter* restarting after a release could repeat the value a tick had read.*/@@ -51,7 +52,7 @@ export class SessionOwnershipService {/** Notified when a renewal proves this process no longer holds sessions it thought it did. */private onLeaseLost?: (sessionIds: string[]) => Promise<void> | void;/** Notified when this process takes a session over from a node whose lease lapsed. See onAdoption. */- private onAdopted?: (sessionId: string) => Promise<unknown>;+ private onAdopted?: { run: (sessionId: string, manager?: EntityManager) => Promise<unknown>; transactional: boolean };/*** How many callers are currently telling renew() that an empty/blank result is NOT evidence of@@ -124,56 +125,89 @@ export class SessionOwnershipService {}/**- * Take ownership, returning false when another live process holds it.+ * Take ownership, returning false when a live peer holds it or a newer local claim supersedes it.** The update is conditional on the same predicate the read used, so two processes racing on the* same free session cannot both succeed: the second one's UPDATE matches no row, because the* first has already written its own `nodeId` and a future expiry. Deciding on the read alone* would let both pass.*/- async claim(sessionId: string): Promise<boolean> {+ async claim(sessionId: string, onClaimed?: (ownsClaim: () => boolean) => void): Promise<boolean> {const now = new Date();const leaseExpiresAt = new Date(now.getTime() + this.leaseTtlMs);- // Who held it, read only when an adoption handler is registered. The UPDATE below still decides- // the claim; this read only tells whether it took a lapsed lease over from another node.- const previous = this.onAdopted- ? await this.sessions.findOne({- where: { id: sessionId },- select: { id: true, nodeId: true, leaseExpiresAt: true },+ // A successful SQL write may still await its reply; a local overlap shares that ownership too.+ if (this.owned.has(sessionId) || this.claimGen.has(sessionId)) {+ const generation = this.claimGen.get(sessionId);+ const renewed = await this.sessions.update({ id: sessionId, nodeId: this.nodeId }, { leaseExpiresAt });+ if (this.claimGen.get(sessionId) !== generation) return false;+ if (renewed.affected === 1) {+ this.owned.add(sessionId);+ if (!this.claimGen.has(sessionId)) this.claimGen.set(sessionId, ++this.claimSeq);+ this.lastSeenLease.set(sessionId, leaseExpiresAt.getTime());+ onClaimed?.(this.captureClaim(sessionId));+ return true;+ }+ }+ // Allocate before the awaited write: an older SQL reply cannot replace a newer local ownership.+ const generation = ++this.claimSeq;+ this.claimGen.set(sessionId, generation);+ let followUp = false;+ const claimed = await this.withAdoption(async (sessions, manager) => {+ // Keep the previous owner, transition and SQL cleanup in one row-locked transaction.+ if (manager) {+ await sessions+ .createQueryBuilder()+ .update(Session)+ .set({ updatedAt: () => '"updatedAt"' })+ .where({ id: sessionId })+ .execute();+ }+ const previous = this.onAdopted+ ? await sessions.findOne({ where: { id: sessionId }, select: { id: true, nodeId: true, leaseExpiresAt: true } })+ : null;+ if (this.claimGen.get(sessionId) !== generation) return false;+ const result = await sessions+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: this.nodeId, claimedAt: now, leaseExpiresAt, nodeUrl: this.nodeUrl || null })+ .where('id = :id', { id: sessionId })+ .andWhere('("nodeId" IS NULL OR "nodeId" = :me OR "leaseExpiresAt" < :now)', {+ me: this.nodeId,+ now: leaseParam(now),})- : null;- const result = await this.sessions- .createQueryBuilder()- .update(Session)- .set({- nodeId: this.nodeId,- claimedAt: now,- leaseExpiresAt,- nodeUrl: this.nodeUrl || null,- })- .where('id = :id', { id: sessionId })- // Without leaseParam this clause would silently never match, so an expired claim would never- // be taken over — stranding every session a crashed process was holding.- .andWhere('("nodeId" IS NULL OR "nodeId" = :me OR "leaseExpiresAt" < :now)', {- me: this.nodeId,- now: leaseParam(now),- })- .execute();-- const claimed = (result.affected ?? 0) > 0;- if (claimed) {- this.owned.add(sessionId);- this.claimGen.set(sessionId, ++this.claimSeq);- this.lastSeenLease.set(sessionId, leaseExpiresAt.getTime());- // A released row (nodeId NULL) is not an adoption: its holder may still be finishing its own- // batches, and failing them under it would leave two writers on one batch row.+ .execute();+ if (this.claimGen.get(sessionId) !== generation) return false;+ const claimed = (result.affected ?? 0) > 0;const adopted =+ claimed &&previous?.nodeId != null &&previous.nodeId !== this.nodeId &&previous.leaseExpiresAt != null &&previous.leaseExpiresAt < now;- if (adopted) this.followAdoption(sessionId);- } else this.logger.warn('Session is held by another node', { sessionId, nodeId: this.nodeId });+ if (adopted) {+ if (manager) await this.followAdoption(sessionId, manager);+ else followUp = true;+ }+ return claimed;+ }).catch(async (error: unknown) => {+ if (this.claimGen.get(sessionId) === generation) {+ if (this.owned.has(sessionId)) await this.renew();+ else this.claimGen.delete(sessionId);+ }+ throw error;+ });+ if (this.claimGen.get(sessionId) !== generation) return false;+ if (claimed) {+ this.owned.add(sessionId);+ this.lastSeenLease.set(sessionId, leaseExpiresAt.getTime());+ onClaimed?.(this.captureClaim(sessionId));+ if (followUp) void this.followAdoption(sessionId);+ } else {+ // Reconcile an existing claim through the heartbeat's loss checks, preserving a successful overlap.+ if (this.owned.has(sessionId)) await this.renew();+ else this.claimGen.delete(sessionId);+ this.logger.warn('Session is held by another node', { sessionId, nodeId: this.nodeId });+ }return claimed;}@@ -198,17 +232,23 @@ export class SessionOwnershipService {/** Record a stop and release an abandoned foreign claim without letting its heartbeat revive it. */async stopExpiredForeignClaim(sessionId: string): Promise<boolean> {- const foreign = { id: sessionId, nodeId: Not(this.nodeId) };- const { affected } = await this.sessions.update(- [- { ...foreign, leaseExpiresAt: IsNull() },- { ...foreign, leaseExpiresAt: LessThanOrEqual(new Date()) },- ],- { desiredState: 'stopped', nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null },- );- if (affected !== 1) return false;- this.followAdoption(sessionId);- return true;+ const foreign = {+ id: sessionId,+ nodeId: Not(this.nodeId),+ desiredState: Or(IsNull(), Not(In(['deleting', 'deleting-stopped']))),+ };+ return this.withAdoption(async (sessions, manager) => {+ const { affected } = await sessions.update(+ [+ { ...foreign, leaseExpiresAt: IsNull() },+ { ...foreign, leaseExpiresAt: LessThanOrEqual(new Date()) },+ ],+ { desiredState: 'stopped', nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null },+ );+ if (affected !== 1) return false;+ await this.followAdoption(sessionId, manager);+ return true;+ });}/**@@ -220,7 +260,34 @@ export class SessionOwnershipService {* which would adopt and restart the session the operator just stopped. A LIVE foreign claim is* left alone — releasing that would strand a peer's running engine.*/- async release(sessionId: string): Promise<void> {+ async release(sessionId: string, ownsClaim?: () => boolean): Promise<void> {+ if (ownsClaim) {+ const dataSource = this.sessions.manager.connection;+ if (!(await awaitNoOpenTransaction(dataSource))) throw new Error('Another database transaction stayed open');+ await dataSource.transaction(async manager => {+ // A delete releases only its captured ownership, even when a peer's newer lease has expired.+ const { affected } = await manager+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: this.nodeId, updatedAt: () => '"updatedAt"' })+ .where({ id: sessionId, nodeId: this.nodeId })+ .execute();+ // Check after the lock: a same-node start may have completed while this statement waited.+ if (!ownsClaim()) return;+ if (affected === 1) {+ await manager.update(+ Session,+ { id: sessionId, nodeId: this.nodeId },+ { nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null },+ );+ }+ if (ownsClaim()) {+ this.owned.delete(sessionId);+ this.claimGen.delete(sessionId);+ }+ });+ return;+ }const now = new Date();this.owned.delete(sessionId);this.claimGen.delete(sessionId);@@ -231,22 +298,30 @@ export class SessionOwnershipService {const own = await this.sessions.createQueryBuilder().update(Session)- .set(cleared)+ .set({+ ...cleared,+ desiredState: () => `CASE WHEN "desiredState" = 'deleting-stopped' THEN 'stopped' ELSE "desiredState" END`,+ }).where('id = :id', { id: sessionId }).andWhere('"nodeId" = :me', { me: this.nodeId }).execute();if ((own.affected ?? 0) > 0) return;- const lapsed = await this.sessions- .createQueryBuilder()- .update(Session)- .set(cleared)- .where('id = :id', { id: sessionId })- .andWhere('"nodeId" IS NOT NULL AND "nodeId" <> :me AND "leaseExpiresAt" < :now', {- me: this.nodeId,- now: leaseParam(now),- })- .execute();- if ((lapsed.affected ?? 0) > 0) this.followAdoption(sessionId);+ await this.withAdoption(async (sessions, manager) => {+ const lapsed = await sessions+ .createQueryBuilder()+ .update(Session)+ .set(cleared)+ .where('id = :id', { id: sessionId })+ .andWhere('"nodeId" IS NOT NULL AND "nodeId" <> :me AND "leaseExpiresAt" < :now', {+ me: this.nodeId,+ now: leaseParam(now),+ })+ .andWhere('("desiredState" IS NULL OR "desiredState" NOT IN (:...deleting))', {+ deleting: ['deleting', 'deleting-stopped'],+ })+ .execute();+ if ((lapsed.affected ?? 0) > 0) await this.followAdoption(sessionId, manager);+ });}/**@@ -304,27 +379,47 @@ export class SessionOwnershipService {* session can no longer finish there. A session its holder released is not taken over: that holder* may still be finishing its own work.*/- onAdoption(handler: (sessionId: string) => Promise<unknown>): void {- this.onAdopted = handler;+ onAdoption(handler: (sessionId: string, manager?: EntityManager) => Promise<unknown>, transactional = false): void {+ this.onAdopted = { run: handler, transactional };}- /**- * Run the adoption handler off the caller's path. Awaiting it inside claim() would hold the start- * between its claim and the moment it counts as starting, and a stop landing in that window would- * release the claim and let the engine launch on a row nobody holds. A failure is logged; the claim- * or release stands either way.- */- private followAdoption(sessionId: string): void {+ /** SQL adoption cleanup shares the ownership transition; arbitrary follow-ups remain detached. */+ private async withAdoption<T>(+ work: (sessions: Repository<Session>, manager?: EntityManager) => Promise<T>,+ ): Promise<T> {+ if (!this.onAdopted?.transactional) return work(this.sessions);+ const dataSource = this.sessions.manager.connection;+ if (!(await awaitNoOpenTransaction(dataSource))) throw new Error('Another database transaction stayed open');+ return dataSource.transaction(manager => work(manager.getRepository(Session), manager));+ }++ /** Isolate SQL errors where they abort the transaction, while keeping successful ownership changes. */+ private async followAdoption(sessionId: string, manager?: EntityManager): Promise<void> {const handler = this.onAdopted;if (!handler) return;- void Promise.resolve()- .then(() => handler(sessionId))- .catch((error: unknown) =>- this.logger.warn('Session adoption follow-up failed', {- sessionId,- error: error instanceof Error ? error.message : String(error),- }),- );+ const failed = (error: unknown): void => {+ this.logger.warn('Session adoption follow-up failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ };+ if (manager && handler.transactional) {+ if (SHARED_CONNECTION_DIALECTS.has(manager.connection.options.type)) {+ // SQLite statement errors keep the transaction usable. Rolling back a savepoint would also+ // undo unrelated writes that used this shared connection while cleanup awaited its queries.+ try {+ await handler.run(sessionId, manager);+ } catch (error) {+ failed(error);+ }+ } else {+ await manager.transaction(nested => handler.run(sessionId, nested)).catch(failed);+ }+ } else {+ void Promise.resolve()+ .then(() => handler.run(sessionId))+ .catch(failed);+ }}/**@@ -548,6 +643,12 @@ export class SessionOwnershipService {return [...this.owned];}+ /** Capture this ownership, including a loss and reacquisition under the same node id. */+ captureClaim(sessionId: string): () => boolean {+ const generation = this.claimGen.get(sessionId);+ return () => generation !== undefined && this.owned.has(sessionId) && this.claimGen.get(sessionId) === generation;+ }+/*** Does THIS process still hold `sessionId`? Synchronous and in-memory on purpose.*diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 0f086d67d..562ea6617 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -281,10 +281,11 @@ export class SessionController {@ApiResponse({status: 409,description:- 'A credential teardown for the same session name is still in flight (retryable — the body ' ++ 'A credential teardown for the same session name is still in flight (retryable: the body ' +"carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; wait for it to settle and retry), OR " +"another node currently holds this session's live engine and deleting it here would strip a " +- 'session the owner is running. No destructive side effect runs before either refusal.',+ 'session the owner is running, OR ownership changes while deletion runs. The first two refusals ' ++ 'remove nothing. Ownership loss stops later deletion units; earlier batches may already be committed.',})async delete(@Param('sessionId', ParseUUIDPipe) id: string): Promise<void> {const session = await this.sessionService.findOne(id);diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex fa7345432..b3e04ee98 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -121,8 +121,11 @@ function createMockSession(overrides: Partial<Session> = {}): Session {/** A query builder whose chain methods return itself and whose raw read finds nothing unless told otherwise. */function chainableQuery(): Record<string, jest.Mock> {- const query: Record<string, jest.Mock> = { getRawMany: jest.fn().mockResolvedValue([]) };- for (const name of ['select', 'addSelect', 'where', 'andWhere', 'orderBy', 'addOrderBy', 'limit']) {+ const query: Record<string, jest.Mock> = {+ getRawMany: jest.fn().mockResolvedValue([]),+ execute: jest.fn().mockResolvedValue({ affected: 1 }),+ };+ for (const name of ['select', 'addSelect', 'where', 'andWhere', 'orderBy', 'addOrderBy', 'limit', 'update', 'set']) {query[name] = jest.fn().mockReturnValue(query);}return query;@@ -138,8 +141,8 @@ describe('SessionService', () => {let shutdown: ShutdownService;let repository: jest.Mocked<Partial<Repository<Session>>>;let messageRepository: jest.Mocked<Partial<Repository<Message>>>;- let outboxRepository: { find: jest.Mock; delete: jest.Mock };- let failureRepository: { find: jest.Mock; delete: jest.Mock };+ let outboxRepository: { target: typeof WebhookOutboxEvent; find: jest.Mock; delete: jest.Mock };+ let failureRepository: { target: typeof WebhookDeliveryFailure; find: jest.Mock; delete: jest.Mock };let dataSource: jest.Mocked<Partial<DataSource>>;let engineFactory: jest.Mocked<Partial<EngineFactory>>;let eventsGateway: jest.Mocked<Partial<EventsGateway>>;@@ -165,6 +168,7 @@ describe('SessionService', () => {};messageRepository = {+ target: Message,find: jest.fn().mockResolvedValue([]),findOne: jest.fn().mockResolvedValue(null),createQueryBuilder: jest.fn().mockImplementation(chainableQuery),@@ -185,8 +189,16 @@ describe('SessionService', () => {delete: jest.fn().mockResolvedValue({ affected: 0 }),};- outboxRepository = { find: jest.fn().mockResolvedValue([]), delete: jest.fn().mockResolvedValue({ affected: 0 }) };- failureRepository = { find: jest.fn().mockResolvedValue([]), delete: jest.fn().mockResolvedValue({ affected: 0 }) };+ outboxRepository = {+ target: WebhookOutboxEvent,+ find: jest.fn().mockResolvedValue([]),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),+ };+ failureRepository = {+ target: WebhookDeliveryFailure,+ find: jest.fn().mockResolvedValue([]),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),+ };dataSource = {options: { type: 'better-sqlite3' } as DataSource['options'],@@ -195,14 +207,18 @@ describe('SessionService', () => {getRepository: jest.fn().mockImplementation((entity: unknown) =>- entity === WebhookOutboxEvent- ? outboxRepository- : entity === WebhookDeliveryFailure- ? failureRepository- : messageRepository,+ entity === Session+ ? repository+ : entity === WebhookOutboxEvent+ ? outboxRepository+ : entity === WebhookDeliveryFailure+ ? failureRepository+ : messageRepository,),transaction: jest.fn().mockImplementation(async (cb: (manager: unknown) => Promise<unknown>) => {const manager = {+ getRepository: dataSource.getRepository,+ createQueryBuilder: jest.fn().mockImplementation(chainableQuery),save: jest.fn().mockImplementation((entity: unknown) => Promise.resolve(entity)),// As TypeORM does: a removed entity comes back with its primary key cleared.remove: jest.fn().mockImplementation((entity: { id?: string }) => {@@ -1488,7 +1504,7 @@ describe('SessionService', () => {expect(del).toHaveBeenNthCalledWith(3, { id: In(ids(2 * BATCH, 20).map(row => row.id)) });// Every batch is out before the transaction that removes the rest and the session row.const transaction = dataSource.transaction as jest.Mock;- expect(del.mock.invocationCallOrder[2]).toBeLessThan(transaction.mock.invocationCallOrder[0]);+ expect(del.mock.invocationCallOrder[2]).toBeLessThan(transaction.mock.invocationCallOrder.at(-1)!);});it('without a timestamp follow the ones with, paged by id', async () => {@@ -1559,7 +1575,11 @@ describe('SessionService', () => {return Promise.resolve({ affected: id.value.length });});let leftBeforeTransaction = -1;- (dataSource.transaction as jest.Mock).mockImplementationOnce(() => {+ const transact = (dataSource.transaction as jest.Mock).getMockImplementation() as (+ cb: unknown,+ ) => Promise<unknown>;+ (dataSource.transaction as jest.Mock).mockImplementation((cb: unknown) => {+ if (left.size > 0) return transact(cb);leftBeforeTransaction = left.size;return Promise.reject(new Error('closing transaction not under test'));});@@ -1707,7 +1727,7 @@ describe('SessionService', () => {expect(outboxRepository.delete).toHaveBeenNthCalledWith(2, { id: In(ids(BATCH, 3).map(row => row.id)) });const transaction = dataSource.transaction as jest.Mock;expect(outboxRepository.delete.mock.invocationCallOrder[1]).toBeLessThan(- transaction.mock.invocationCallOrder[0],+ transaction.mock.invocationCallOrder.at(-1)!,);});@@ -1727,7 +1747,7 @@ describe('SessionService', () => {expect(failureRepository.delete).toHaveBeenNthCalledWith(2, { id: In(ids(BATCH, 3).map(row => row.id)) });const transaction = dataSource.transaction as jest.Mock;expect(failureRepository.delete.mock.invocationCallOrder[1]).toBeLessThan(- transaction.mock.invocationCallOrder[0],+ transaction.mock.invocationCallOrder.at(-1)!,);});@@ -1738,7 +1758,7 @@ describe('SessionService', () => {await expect(service.delete('sess-uuid-1')).rejects.toThrow('canceling statement');- expect(dataSource.transaction).not.toHaveBeenCalled();+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();expect(repository.remove).not.toHaveBeenCalled();});});@@ -2431,7 +2451,7 @@ describe('SessionService', () => {await expect(service.delete('sess-uuid-1')).rejects.toThrow(ConflictException);- expect(ownership.claim).toHaveBeenCalledWith('sess-uuid-1');+ expect(ownership.claim).toHaveBeenCalledWith('sess-uuid-1', expect.any(Function));expect(ownership.release).not.toHaveBeenCalled();});@@ -2974,7 +2994,10 @@ describe('SessionService', () => {],['refused when its record is written',- () => (repository.update as jest.Mock).mockResolvedValueOnce({ affected: 0 }),+ () =>+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Partial<Session>) =>+ Promise.resolve({ affected: patch.desiredState ? 0 : 1 }),+ ),ConflictException,],])(@@ -3012,7 +3035,10 @@ describe('SessionService', () => {await until(() => mockEngine.initialize.mock.calls.length === 1 && !lifecycle.isEngineActive(row.id));await service.stop(row.id);if (refusal === 'ownership read') jest.spyOn(ownership, 'isHeldByOtherNode').mockResolvedValueOnce(true);- else (repository.update as jest.Mock).mockResolvedValueOnce({ affected: 0 });+ else+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Partial<Session>) =>+ Promise.resolve({ affected: patch.desiredState ? 0 : 1 }),+ );await expect(service.stop(row.id)).rejects.toThrow(ConflictException);expect(await outcome).toBeInstanceOf(SessionStoppedException);diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 9ad8b4c61..c08018c9a 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -653,15 +653,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// before the claim is handed back.const endDelete = this.engineLifecycle.holdDelete(id);let claimed = false;+ let ownsClaim: (() => boolean) | undefined;try {try {if (this.ownership) {await this.assertNotHeldElsewhere(id, request);- await this.claimForDelete(id, this.ownership, request);+ await this.claimForDelete(id, this.ownership, request, captured => {+ claimed = true;+ ownsClaim = captured;+ });claimed = true;+ ownsClaim ??= this.ownership.captureClaim?.(id);}// A failed write took nothing down, so the mark is dropped and the request withdrawn as for a failed claim.- await this.keepDownForDelete(id, stops).catch((error: unknown) => {+ await this.keepDownForDelete(id, stops, ownsClaim).catch((error: unknown) => {this.engineLifecycle.clearStopping(id);this.withdrawStop(request);throw error;@@ -670,6 +675,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// it found it and withdraws its request, so a start it overlapped does not take it for a stop.await this.engineLifecycle.delete(id, {+ ownsClaim,onRemoving: () => {this.takeStop(request);stops.removing = true;@@ -682,33 +688,34 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat} finally {endDelete();}- await this.releaseClaimBestEffort(id);+ await this.releaseAfterTeardown(id, ownsClaim);} catch (error) {// A delete that removed nothing leaves the session as it found it. One that began to remove it leaves// it stopped, as a process that dies part-way does.- await this.leaveDelete(id, request);+ await this.leaveDelete(id, request, ownsClaim);// The row survived. A claim left on it lapses with nothing to renew it, and a peer would then// adopt and restart the session the operator was deleting.- if (claimed) await this.releaseAfterTeardown(id);+ if (claimed) await this.releaseAfterTeardown(id, ownsClaim);this.discardStopMarkForMissingSession(id, error);throw error;}- await this.leaveDelete(id, request);+ await this.leaveDelete(id, request, ownsClaim);}/*** End a delete's share of the stop record. Another delete of the session still running here relies on it, so* only the last one out takes it back, and only when they wrote it and none began removing the session. A stop- * written over it, here or on another node, is not 'deleting' and stays.+ * recorded alongside it, here or on another node, stays as a normal stop afterward.*/- private async leaveDelete(id: string, request: StopRequest): Promise<void> {+ private async leaveDelete(id: string, request: StopRequest, ownsClaim?: () => boolean): Promise<void> {const stops = this.stopRequests.get(id)!;request.ended = true;const deleting = (): boolean => [...stops.requests].some(other => other.kind === 'delete' && !other.ended);- if (!deleting() && stops.recorded && !stops.removing) {+ if (!deleting() && !stops.givingBack && (ownsClaim?.() ?? true)) {+ const clear = stops.recorded && !stops.removing;// Not theirs while it is cleared, so a delete that begins and ends meanwhile leaves it alone.stops.recorded = false;- stops.givingBack = this.clearDeleteStop(id).then(cleared => {+ stops.givingBack = this.clearDeleteStop(id, clear).then(cleared => {// Still on the row: a delete that began meanwhile shares it.if (!cleared) stops.recorded = true;stops.givingBack = undefined;@@ -730,10 +737,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* Nothing has been removed when this refuses: a peer that claimed first answers the same 409 as* assertNotHeldElsewhere, and a failed write is undone like a failed ownership read.*/- private async claimForDelete(id: string, ownership: SessionOwnershipService, request: StopRequest): Promise<void> {+ private async claimForDelete(+ id: string,+ ownership: SessionOwnershipService,+ request: StopRequest,+ onClaimed: (ownsClaim: () => boolean) => void,+ ): Promise<void> {let claimed: boolean;try {- claimed = await ownership.claim(id);+ claimed = await ownership.claim(id, onClaimed);} catch (error) {this.engineLifecycle.clearStopping(id);this.withdrawStop(request);@@ -757,22 +769,52 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* progress, which would otherwise clear it. 'deleting' rather than 'stopped', so the take-back can tell it* from a stop that replaced it, also one another node recorded.*/- private async keepDownForDelete(id: string, stops: SessionStops): Promise<void> {+ private async keepDownForDelete(id: string, stops: SessionStops, ownsClaim?: () => boolean): Promise<void> {if (stops.givingBack) await stops.givingBack;- const { affected } = await this.sessionRepository.update(- { id, desiredState: IsNull() },- { desiredState: 'deleting' },- );- if (affected === 1) stops.recorded = true;+ const record = async (sessions: Repository<Session>): Promise<void> => {+ const { affected } = await sessions.update({ id, desiredState: IsNull() }, { desiredState: 'deleting' });+ if (affected === 1) stops.recorded = true;+ await sessions.update({ id, desiredState: 'stopped' }, { desiredState: 'deleting-stopped' });+ };+ if (!this.ownership) return record(this.sessionRepository);+ if (!(await awaitNoOpenTransaction(this.dataSource))) {+ throw new ServiceUnavailableException(+ `Session ${id} could not record its delete: another transaction stayed open`,+ );+ }+ await this.dataSource.transaction(async manager => {+ const { affected } = await manager+ .createQueryBuilder()+ .update(Session)+ .set({ nodeId: this.ownership!.nodeId, updatedAt: () => '"updatedAt"' })+ .where({ id, nodeId: this.ownership!.nodeId })+ .execute();+ if (affected !== 1 || ownsClaim?.() === false) {+ throw new ConflictException(`Session ${id} is no longer owned by this delete`);+ }+ await record(manager.getRepository(Session));+ });}/*** Undo keepDownForDelete; answers whether the record is off the row. Best effort: the delete's own error is* the answer, and a stop left on is safe. A stop recorded over it since is left alone.*/- private async clearDeleteStop(id: string): Promise<boolean> {+ private async clearDeleteStop(id: string, clear: boolean): Promise<boolean> {try {- await this.sessionRepository.update({ id, desiredState: 'deleting' }, { desiredState: null });+ const owners: FindOptionsWhere<Session>[] = this.ownership+ ? [{ nodeId: this.ownership.nodeId }, { nodeId: IsNull() }]+ : [{}];+ if (clear) {+ await this.sessionRepository.update(+ owners.map(owner => ({ id, ...owner, desiredState: 'deleting' as const })),+ { desiredState: null },+ );+ }+ await this.sessionRepository.update(+ owners.map(owner => ({ id, ...owner, desiredState: 'deleting-stopped' as const })),+ { desiredState: 'stopped' },+ );return true;} catch (error) {this.logger.warn(`Could not clear the stop a failed delete recorded for session ${id}`, {@@ -1075,18 +1117,30 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat/*** Persist a stop only while no live peer owns the engine. The initial ownership read may predate a peer's* claim; deciding in this write also fences a stop delayed until after that peer's start returned. A delete's- * record still accepts a stop: replacing 'deleting' cannot be mistaken for that record by a start or take-back.+ * record still accepts a stop, while remaining distinguishable until its delete finishes.*/private async keepDown(id: string): Promise<void> {- const where: string | FindOptionsWhere<Session>[] = this.ownership+ const claims: FindOptionsWhere<Session>[] = this.ownership? [{ id, nodeId: IsNull() },{ id, nodeId: this.ownership.nodeId },- { id, desiredState: 'deleting' },]+ : [{ id }];+ const where = this.ownership+ ? claims.flatMap(claim => [+ { ...claim, desiredState: IsNull() },+ { ...claim, desiredState: 'stopped' as const },+ ]): id;const { affected } = await this.sessionRepository.update(where, { desiredState: 'stopped' });if (affected === 0) {+ const deleting = await this.sessionRepository.update(+ { id, desiredState: In(['deleting', 'deleting-stopped']) },+ { desiredState: 'deleting-stopped' },+ );+ if (deleting.affected === 1) return;+ // The delete may have finished between the two writes, leaving a normal stopped or free row.+ if ((await this.sessionRepository.update(where, { desiredState: 'stopped' })).affected === 1) return;// Clear an abandoned foreign claim with the record, before its heartbeat can revive it. A// pending delete took the branch above and keeps its claim throughout removal.if (this.ownership && (await this.ownership.stopExpiredForeignClaim(id))) return;@@ -1186,16 +1240,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* see: releasing would leave the engine it is about to launch on a row no node holds. That start* hands the claim back itself if it yields or fails.*/- private async releaseAfterTeardown(id: string): Promise<void> {+ private async releaseAfterTeardown(id: string, ownsClaim?: () => boolean): Promise<void> {if (this.startReservations.has(id)) return;- await this.releaseUnlessEngineActive(id);+ await this.releaseUnlessEngineActive(+ id,+ ownsClaim+ ? () => ownsClaim() && !this.startReservations.has(id) && !this.engineLifecycle.isEngineActive(id)+ : undefined,+ );}/*** Hand the claim back unless something still runs here (engine, in-flight start, pending reconnect,* delete in flight).*/- private async releaseUnlessEngineActive(id: string): Promise<void> {+ private async releaseUnlessEngineActive(id: string, ownsClaim?: () => boolean): Promise<void> {if (!this.ownership || this.engineLifecycle.isEngineActive(id)) {return;}@@ -1206,7 +1265,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn;}this.releaseOwed.delete(id);- await this.releaseClaimBestEffort(id);+ await this.releaseClaimBestEffort(id, ownsClaim);}/**@@ -1215,10 +1274,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* replace that outcome (a started session reported as failed, a stopped one as an error, a committed* delete as a 500 whose retry answers 404 and writes no audit row).*/- private async releaseClaimBestEffort(id: string): Promise<void> {+ private async releaseClaimBestEffort(id: string, ownsClaim?: () => boolean): Promise<void> {if (!this.ownership) return;try {- await this.ownership.release(id);+ if (ownsClaim) await this.ownership.release(id, ownsClaim);+ else await this.ownership.release(id);} catch (error) {this.logger.warn(`Could not hand back the claim of session ${id}; it lapses with its lease`, {sessionId: id,