Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): remove a deleted session's delivery records

Yudhi Armyndharisaa918e772345
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index fb12e145d..5bb6ff6a2 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1237,6 +1237,8 @@ Delete a session.
**Response** `204` — empty body (`@HttpCode(204)`, returns void). A `findOne` lookup runs first, so a missing id yields `404`.
+The delete removes, in one transaction, the session's messages, message batches, chat states, received statuses, webhooks, templates, stored Baileys messages, automation rules, webhook outbox rows, webhook delivery-failure records and integration dead-letter rows, 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, or key not scoped to this session · `403` 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)
### 6.4.2 Messages
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index ab018d4d5..55979ede2 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -5,6 +5,9 @@ import { Session, SessionStatus } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { MessageBatch } from '../message/entities/message-batch.entity';
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';
+import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';
import { Template } from '../template/entities/template.entity';
import { BaileysStoredMessage } from '../../engine';
import { ChatState } from '../../engine/adapters/baileys-chat-state.entity';
@@ -580,7 +583,15 @@ export class SessionEngineControls {
// creation — so their explicit deletes are belt-and-braces rather than required; they stay
// because depending on a pragma neither this file nor a test pins is a thinner guarantee than
// an explicit delete, and the ordering mirrors the restore path's explicit-clear. chat_states and
- // status_updates are in the no-FK group too.
+ // status_updates are in the no-FK group too, and so are the session's webhook outbox rows,
+ // webhook delivery-failure records and integration dead-letter rows (which keep full payloads).
+ // Those three are point-in-time: a delivery still in flight can write one after the commit, and
+ // their retention windows cover it.
+ //
+ // Deliberately kept: conversation_mappings (a re-paired session is rebound to its provider
+ // 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.host.dataSource().transaction(async manager => {
await manager.delete(Message, { sessionId: id });
await manager.delete(MessageBatch, { sessionId: id });
@@ -589,6 +600,9 @@ export class SessionEngineControls {
await manager.delete(Webhook, { sessionId: id });
await manager.delete(Template, { sessionId: id });
await manager.delete(BaileysStoredMessage, { sessionId: id });
+ await manager.delete(WebhookOutboxEvent, { sessionId: id });
+ await manager.delete(WebhookDeliveryFailure, { sessionId: id });
+ await manager.delete(IntegrationDeliveryFailure, { sessionId: id });
await manager.remove(session);
});
parentDeleted = true;
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index caa4e4072..42b5ac8a0 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -38,6 +38,12 @@ import { Template } from '../template/entities/template.entity';
import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';
import { ChatState } from '../../engine/adapters/baileys-chat-state.entity';
import { StatusUpdate } from '../status-store/entities/status-update.entity';
+import { WebhookOutboxEvent } from '../webhook/entities/webhook-outbox-event.entity';
+import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';
+import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';
+import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';
+import { IngressEvent } from '../integration/entities/ingress-event.entity';
+import { LidMapping } from '../../engine/identity/lid-mapping.entity';
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
import type { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
@@ -1279,6 +1285,19 @@ describe('SessionService', () => {
// chat_states and status_updates carry a plain sessionId with no FK at all.
expect(managerDelete).toHaveBeenCalledWith(ChatState, { sessionId: 'sess-uuid-1' });
expect(managerDelete).toHaveBeenCalledWith(StatusUpdate, { sessionId: 'sess-uuid-1' });
+ // Delivery records keyed on the session: outbox rows, lost-delivery records, dead-letter payloads.
+ expect(managerDelete).toHaveBeenCalledWith(WebhookOutboxEvent, { sessionId: 'sess-uuid-1' });
+ expect(managerDelete).toHaveBeenCalledWith(WebhookDeliveryFailure, { sessionId: 'sess-uuid-1' });
+ expect(managerDelete).toHaveBeenCalledWith(IntegrationDeliveryFailure, { sessionId: 'sess-uuid-1' });
+ // Kept on purpose: a re-paired session is rebound to its conversations, ingress rows are the
+ // instance-keyed dedup record, and LID mappings are a global cache.
+ const deleted = managerDelete.mock.calls.map(([entity]) => entity as unknown);
+ expect(deleted).not.toContain(ConversationMapping);
+ expect(deleted).not.toContain(IngressEvent);
+ expect(deleted).not.toContain(LidMapping);
+ // Children before the parent.
+ const removeOrder = managerRemove.mock.invocationCallOrder[0];
+ for (const order of managerDelete.mock.invocationCallOrder) expect(order).toBeLessThan(removeOrder);
expect(managerRemove).toHaveBeenCalledWith(session);
});
});